var fx = Object.defineProperty;
var mx = (a, t, e) => t in a ? fx(a, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : a[t] = e;
var k = (a, t, e) => mx(a, typeof t != "symbol" ? t + "" : t, e);
/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
const Tc = "180", Ze = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }, zi = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }, w0 = 0, Yd = 1, A0 = 2, gx = 3, yx = 0, Mp = 1, E0 = 2, Sn = 3, $i = 0, He = 1, Mi = 2, Yn = 0, ws = 1, Zd = 2, jd = 3, Jd = 4, T0 = 5, vs = 100, C0 = 101, R0 = 102, P0 = 103, I0 = 104, L0 = 200, D0 = 201, F0 = 202, U0 = 203, Ih = 204, Lh = 205, B0 = 206, z0 = 207, N0 = 208, O0 = 209, k0 = 210, V0 = 211, H0 = 212, G0 = 213, W0 = 214, Dh = 0, Fh = 1, Uh = 2, pr = 3, Bh = 4, zh = 5, Nh = 6, Oh = 7, zo = 0, q0 = 1, $0 = 2, Zn = 0, X0 = 1, Y0 = 2, Z0 = 3, j0 = 4, J0 = 5, K0 = 6, Q0 = 7, Kd = "attached", ty = "detached", Cc = 300, is = 301, Ts = 302, vo = 303, bo = 304, Sa = 306, Mo = 1e3, Si = 1001, So = 1002, je = 1003, Sp = 1004, _x = 1004, sa = 1005, xx = 1005, Ce = 1006, lo = 1007, vx = 1007, En = 1008, bx = 1008, pn = 1009, wp = 1010, Ap = 1011, da = 1012, Rc = 1013, ns = 1014, wi = 1015, wa = 1016, Pc = 1017, Ic = 1018, pa = 1020, Ep = 35902, Tp = 35899, Cp = 1021, Rp = 1022, gi = 1023, fa = 1026, ma = 1027, Lc = 1028, No = 1029, Pp = 1030, Dc = 1031, Mx = 1032, Fc = 1033, ho = 33776, co = 33777, uo = 33778, po = 33779, kh = 35840, Vh = 35841, Hh = 35842, Gh = 35843, Wh = 36196, qh = 37492, $h = 37496, Xh = 37808, Yh = 37809, Zh = 37810, jh = 37811, Jh = 37812, Kh = 37813, Qh = 37814, tc = 37815, ec = 37816, ic = 37817, nc = 37818, sc = 37819, rc = 37820, ac = 37821, oc = 36492, lc = 36494, hc = 36495, cc = 36283, uc = 36284, dc = 36285, pc = 36286, ey = 2200, Ip = 2201, Lp = 2202, wo = 2300, fc = 2301, bh = 2302, sr = 2400, rr = 2401, Ao = 2402, Uc = 2500, Dp = 2501, Sx = 0, wx = 1, Ax = 2, iy = 3200, ny = 3201, Ex = 3202, Tx = 3203, Is = 0, sy = 1, $n = "", ri = "srgb", Cs = "srgb-linear", Eo = "linear", ce = "srgb", Cx = 0, er = 7680, Mh = 7681, Rx = 7682, Px = 7683, Sh = 34055, wh = 34056, Ix = 5386, Lx = 512, Dx = 513, Fx = 514, Ux = 515, Bx = 516, ry = 517, zx = 518, To = 519, ay = 512, oy = 513, ly = 514, Fp = 515, hy = 516, cy = 517, uy = 518, dy = 519, Co = 35044, Nx = 35048, Ox = 35040, kx = 35045, Vx = 35049, Hx = 35041, Gx = 35046, Wx = 35050, qx = 35042, $x = "100", Qd = "300 es", Ni = 2e3, ga = 2001, Xx = {
  COMPUTE: "compute",
  RENDER: "render"
}, Yx = {
  PERSPECTIVE: "perspective",
  LINEAR: "linear",
  FLAT: "flat"
}, Zx = {
  NORMAL: "normal",
  CENTROID: "centroid",
  SAMPLE: "sample",
  FIRST: "first",
  EITHER: "either"
};
let Ei = class {
  /**
   * Adds the given event listener to the given event type.
   *
   * @param {string} type - The type of event to listen to.
   * @param {Function} listener - The function that gets called when the event is fired.
   */
  addEventListener(t, e) {
    this._listeners === void 0 && (this._listeners = {});
    const i = this._listeners;
    i[t] === void 0 && (i[t] = []), i[t].indexOf(e) === -1 && i[t].push(e);
  }
  /**
   * Returns `true` if the given event listener has been added to the given event type.
   *
   * @param {string} type - The type of event.
   * @param {Function} listener - The listener to check.
   * @return {boolean} Whether the given event listener has been added to the given event type.
   */
  hasEventListener(t, e) {
    const i = this._listeners;
    return i === void 0 ? !1 : i[t] !== void 0 && i[t].indexOf(e) !== -1;
  }
  /**
   * Removes the given event listener from the given event type.
   *
   * @param {string} type - The type of event.
   * @param {Function} listener - The listener to remove.
   */
  removeEventListener(t, e) {
    const i = this._listeners;
    if (i === void 0) return;
    const n = i[t];
    if (n !== void 0) {
      const s = n.indexOf(e);
      s !== -1 && n.splice(s, 1);
    }
  }
  /**
   * Dispatches an event object.
   *
   * @param {Object} event - The event that gets fired.
   */
  dispatchEvent(t) {
    const e = this._listeners;
    if (e === void 0) return;
    const i = e[t.type];
    if (i !== void 0) {
      t.target = this;
      const n = i.slice(0);
      for (let s = 0, r = n.length; s < r; s++)
        n[s].call(this, t);
      t.target = null;
    }
  }
};
const Je = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"];
let Pf = 1234567;
const lr = Math.PI / 180, ya = 180 / Math.PI;
function Oi() {
  const a = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, e = Math.random() * 4294967295 | 0, i = Math.random() * 4294967295 | 0;
  return (Je[a & 255] + Je[a >> 8 & 255] + Je[a >> 16 & 255] + Je[a >> 24 & 255] + "-" + Je[t & 255] + Je[t >> 8 & 255] + "-" + Je[t >> 16 & 15 | 64] + Je[t >> 24 & 255] + "-" + Je[e & 63 | 128] + Je[e >> 8 & 255] + "-" + Je[e >> 16 & 255] + Je[e >> 24 & 255] + Je[i & 255] + Je[i >> 8 & 255] + Je[i >> 16 & 255] + Je[i >> 24 & 255]).toLowerCase();
}
function kt(a, t, e) {
  return Math.max(t, Math.min(e, a));
}
function Up(a, t) {
  return (a % t + t) % t;
}
function jx(a, t, e, i, n) {
  return i + (a - t) * (n - i) / (e - t);
}
function Jx(a, t, e) {
  return a !== t ? (e - a) / (t - a) : 0;
}
function fo(a, t, e) {
  return (1 - e) * a + e * t;
}
function Kx(a, t, e, i) {
  return fo(a, t, 1 - Math.exp(-e * i));
}
function Qx(a, t = 1) {
  return t - Math.abs(Up(a, t * 2) - t);
}
function tv(a, t, e) {
  return a <= t ? 0 : a >= e ? 1 : (a = (a - t) / (e - t), a * a * (3 - 2 * a));
}
function ev(a, t, e) {
  return a <= t ? 0 : a >= e ? 1 : (a = (a - t) / (e - t), a * a * a * (a * (a * 6 - 15) + 10));
}
function iv(a, t) {
  return a + Math.floor(Math.random() * (t - a + 1));
}
function nv(a, t) {
  return a + Math.random() * (t - a);
}
function sv(a) {
  return a * (0.5 - Math.random());
}
function rv(a) {
  a !== void 0 && (Pf = a);
  let t = Pf += 1831565813;
  return t = Math.imul(t ^ t >>> 15, t | 1), t ^= t + Math.imul(t ^ t >>> 7, t | 61), ((t ^ t >>> 14) >>> 0) / 4294967296;
}
function av(a) {
  return a * lr;
}
function ov(a) {
  return a * ya;
}
function lv(a) {
  return (a & a - 1) === 0 && a !== 0;
}
function hv(a) {
  return Math.pow(2, Math.ceil(Math.log(a) / Math.LN2));
}
function cv(a) {
  return Math.pow(2, Math.floor(Math.log(a) / Math.LN2));
}
function uv(a, t, e, i, n) {
  const s = Math.cos, r = Math.sin, o = s(e / 2), l = r(e / 2), h = s((t + i) / 2), c = r((t + i) / 2), u = s((t - i) / 2), d = r((t - i) / 2), p = s((i - t) / 2), f = r((i - t) / 2);
  switch (n) {
    case "XYX":
      a.set(o * c, l * u, l * d, o * h);
      break;
    case "YZY":
      a.set(l * d, o * c, l * u, o * h);
      break;
    case "ZXZ":
      a.set(l * u, l * d, o * c, o * h);
      break;
    case "XZX":
      a.set(o * c, l * f, l * p, o * h);
      break;
    case "YXY":
      a.set(l * p, o * c, l * f, o * h);
      break;
    case "ZYZ":
      a.set(l * f, l * p, o * c, o * h);
      break;
    default:
      console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + n);
  }
}
function mi(a, t) {
  switch (t.constructor) {
    case Float32Array:
      return a;
    case Uint32Array:
      return a / 4294967295;
    case Uint16Array:
      return a / 65535;
    case Uint8Array:
      return a / 255;
    case Int32Array:
      return Math.max(a / 2147483647, -1);
    case Int16Array:
      return Math.max(a / 32767, -1);
    case Int8Array:
      return Math.max(a / 127, -1);
    default:
      throw new Error("Invalid component type.");
  }
}
function Yt(a, t) {
  switch (t.constructor) {
    case Float32Array:
      return a;
    case Uint32Array:
      return Math.round(a * 4294967295);
    case Uint16Array:
      return Math.round(a * 65535);
    case Uint8Array:
      return Math.round(a * 255);
    case Int32Array:
      return Math.round(a * 2147483647);
    case Int16Array:
      return Math.round(a * 32767);
    case Int8Array:
      return Math.round(a * 127);
    default:
      throw new Error("Invalid component type.");
  }
}
const py = {
  DEG2RAD: lr,
  RAD2DEG: ya,
  /**
   * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
   * (universally unique identifier).
   *
   * @static
   * @method
   * @return {string} The UUID.
   */
  generateUUID: Oi,
  /**
   * Clamps the given value between min and max.
   *
   * @static
   * @method
   * @param {number} value - The value to clamp.
   * @param {number} min - The min value.
   * @param {number} max - The max value.
   * @return {number} The clamped value.
   */
  clamp: kt,
  /**
   * Computes the Euclidean modulo of the given parameters that
   * is `( ( n % m ) + m ) % m`.
   *
   * @static
   * @method
   * @param {number} n - The first parameter.
   * @param {number} m - The second parameter.
   * @return {number} The Euclidean modulo.
   */
  euclideanModulo: Up,
  /**
   * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
   * for the given value.
   *
   * @static
   * @method
   * @param {number} x - The value to be mapped.
   * @param {number} a1 - Minimum value for range A.
   * @param {number} a2 - Maximum value for range A.
   * @param {number} b1 - Minimum value for range B.
   * @param {number} b2 - Maximum value for range B.
   * @return {number} The mapped value.
   */
  mapLinear: jx,
  /**
   * Returns the percentage in the closed interval `[0, 1]` of the given value
   * between the start and end point.
   *
   * @static
   * @method
   * @param {number} x - The start point
   * @param {number} y - The end point.
   * @param {number} value - A value between start and end.
   * @return {number} The interpolation factor.
   */
  inverseLerp: Jx,
  /**
   * Returns a value linearly interpolated from two known points based on the given interval -
   * `t = 0` will return `x` and `t = 1` will return `y`.
   *
   * @static
   * @method
   * @param {number} x - The start point
   * @param {number} y - The end point.
   * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
   * @return {number} The interpolated value.
   */
  lerp: fo,
  /**
   * Smoothly interpolate a number from `x` to `y` in  a spring-like manner using a delta
   * time to maintain frame rate independent movement. For details, see
   * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
   *
   * @static
   * @method
   * @param {number} x - The current point.
   * @param {number} y - The target point.
   * @param {number} lambda - A higher lambda value will make the movement more sudden,
   * and a lower value will make the movement more gradual.
   * @param {number} dt - Delta time in seconds.
   * @return {number} The interpolated value.
   */
  damp: Kx,
  /**
   * Returns a value that alternates between `0` and the given `length` parameter.
   *
   * @static
   * @method
   * @param {number} x - The value to pingpong.
   * @param {number} [length=1] - The positive value the function will pingpong to.
   * @return {number} The alternated value.
   */
  pingpong: Qx,
  /**
   * Returns a value in the range `[0,1]` that represents the percentage that `x` has
   * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
   * the `min` and `max`.
   *
   * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
   *
   * @static
   * @method
   * @param {number} x - The value to evaluate based on its position between min and max.
   * @param {number} min - The min value. Any x value below min will be `0`.
   * @param {number} max - The max value. Any x value above max will be `1`.
   * @return {number} The alternated value.
   */
  smoothstep: tv,
  /**
   * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
   * that has zero 1st and 2nd order derivatives at x=0 and x=1.
   *
   * @static
   * @method
   * @param {number} x - The value to evaluate based on its position between min and max.
   * @param {number} min - The min value. Any x value below min will be `0`.
   * @param {number} max - The max value. Any x value above max will be `1`.
   * @return {number} The alternated value.
   */
  smootherstep: ev,
  /**
   * Returns a random integer from `<low, high>` interval.
   *
   * @static
   * @method
   * @param {number} low - The lower value boundary.
   * @param {number} high - The upper value boundary
   * @return {number} A random integer.
   */
  randInt: iv,
  /**
   * Returns a random float from `<low, high>` interval.
   *
   * @static
   * @method
   * @param {number} low - The lower value boundary.
   * @param {number} high - The upper value boundary
   * @return {number} A random float.
   */
  randFloat: nv,
  /**
   * Returns a random integer from `<-range/2, range/2>` interval.
   *
   * @static
   * @method
   * @param {number} range - Defines the value range.
   * @return {number} A random float.
   */
  randFloatSpread: sv,
  /**
   * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
   *
   * @static
   * @method
   * @param {number} [s] - The integer seed.
   * @return {number} A random float.
   */
  seededRandom: rv,
  /**
   * Converts degrees to radians.
   *
   * @static
   * @method
   * @param {number} degrees - A value in degrees.
   * @return {number} The converted value in radians.
   */
  degToRad: av,
  /**
   * Converts radians to degrees.
   *
   * @static
   * @method
   * @param {number} radians - A value in radians.
   * @return {number} The converted value in degrees.
   */
  radToDeg: ov,
  /**
   * Returns `true` if the given number is a power of two.
   *
   * @static
   * @method
   * @param {number} value - The value to check.
   * @return {boolean} Whether the given number is a power of two or not.
   */
  isPowerOfTwo: lv,
  /**
   * Returns the smallest power of two that is greater than or equal to the given number.
   *
   * @static
   * @method
   * @param {number} value - The value to find a POT for.
   * @return {number} The smallest power of two that is greater than or equal to the given number.
   */
  ceilPowerOfTwo: hv,
  /**
   * Returns the largest power of two that is less than or equal to the given number.
   *
   * @static
   * @method
   * @param {number} value - The value to find a POT for.
   * @return {number} The largest power of two that is less than or equal to the given number.
   */
  floorPowerOfTwo: cv,
  /**
   * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
   * defined by the given angles and order.
   *
   * Rotations are applied to the axes in the order specified by order:
   * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
   *
   * @static
   * @method
   * @param {Quaternion} q - The quaternion to set.
   * @param {number} a - The rotation applied to the first axis, in radians.
   * @param {number} b - The rotation applied to the second axis, in radians.
   * @param {number} c - The rotation applied to the third axis, in radians.
   * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
   */
  setQuaternionFromProperEuler: uv,
  /**
   * Normalizes the given value according to the given typed array.
   *
   * @static
   * @method
   * @param {number} value - The float value in the range `[0,1]` to normalize.
   * @param {TypedArray} array - The typed array that defines the data type of the value.
   * @return {number} The normalize value.
   */
  normalize: Yt,
  /**
   * Denormalizes the given value according to the given typed array.
   *
   * @static
   * @method
   * @param {number} value - The value to denormalize.
   * @param {TypedArray} array - The typed array that defines the data type of the value.
   * @return {number} The denormalize (float) value in the range `[0,1]`.
   */
  denormalize: mi
};
let J = class fy {
  /**
   * Constructs a new 2D vector.
   *
   * @param {number} [x=0] - The x value of this vector.
   * @param {number} [y=0] - The y value of this vector.
   */
  constructor(t = 0, e = 0) {
    fy.prototype.isVector2 = !0, this.x = t, this.y = e;
  }
  /**
   * Alias for {@link Vector2#x}.
   *
   * @type {number}
   */
  get width() {
    return this.x;
  }
  set width(t) {
    this.x = t;
  }
  /**
   * Alias for {@link Vector2#y}.
   *
   * @type {number}
   */
  get height() {
    return this.y;
  }
  set height(t) {
    this.y = t;
  }
  /**
   * Sets the vector components.
   *
   * @param {number} x - The value of the x component.
   * @param {number} y - The value of the y component.
   * @return {Vector2} A reference to this vector.
   */
  set(t, e) {
    return this.x = t, this.y = e, this;
  }
  /**
   * Sets the vector components to the same value.
   *
   * @param {number} scalar - The value to set for all vector components.
   * @return {Vector2} A reference to this vector.
   */
  setScalar(t) {
    return this.x = t, this.y = t, this;
  }
  /**
   * Sets the vector's x component to the given value
   *
   * @param {number} x - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setX(t) {
    return this.x = t, this;
  }
  /**
   * Sets the vector's y component to the given value
   *
   * @param {number} y - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setY(t) {
    return this.y = t, this;
  }
  /**
   * Allows to set a vector component with an index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y.
   * @param {number} value - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setComponent(t, e) {
    switch (t) {
      case 0:
        this.x = e;
        break;
      case 1:
        this.y = e;
        break;
      default:
        throw new Error("index is out of range: " + t);
    }
    return this;
  }
  /**
   * Returns the value of the vector component which matches the given index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y.
   * @return {number} A vector component value.
   */
  getComponent(t) {
    switch (t) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      default:
        throw new Error("index is out of range: " + t);
    }
  }
  /**
   * Returns a new vector with copied values from this instance.
   *
   * @return {Vector2} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.x, this.y);
  }
  /**
   * Copies the values of the given vector to this instance.
   *
   * @param {Vector2} v - The vector to copy.
   * @return {Vector2} A reference to this vector.
   */
  copy(t) {
    return this.x = t.x, this.y = t.y, this;
  }
  /**
   * Adds the given vector to this instance.
   *
   * @param {Vector2} v - The vector to add.
   * @return {Vector2} A reference to this vector.
   */
  add(t) {
    return this.x += t.x, this.y += t.y, this;
  }
  /**
   * Adds the given scalar value to all components of this instance.
   *
   * @param {number} s - The scalar to add.
   * @return {Vector2} A reference to this vector.
   */
  addScalar(t) {
    return this.x += t, this.y += t, this;
  }
  /**
   * Adds the given vectors and stores the result in this instance.
   *
   * @param {Vector2} a - The first vector.
   * @param {Vector2} b - The second vector.
   * @return {Vector2} A reference to this vector.
   */
  addVectors(t, e) {
    return this.x = t.x + e.x, this.y = t.y + e.y, this;
  }
  /**
   * Adds the given vector scaled by the given factor to this instance.
   *
   * @param {Vector2} v - The vector.
   * @param {number} s - The factor that scales `v`.
   * @return {Vector2} A reference to this vector.
   */
  addScaledVector(t, e) {
    return this.x += t.x * e, this.y += t.y * e, this;
  }
  /**
   * Subtracts the given vector from this instance.
   *
   * @param {Vector2} v - The vector to subtract.
   * @return {Vector2} A reference to this vector.
   */
  sub(t) {
    return this.x -= t.x, this.y -= t.y, this;
  }
  /**
   * Subtracts the given scalar value from all components of this instance.
   *
   * @param {number} s - The scalar to subtract.
   * @return {Vector2} A reference to this vector.
   */
  subScalar(t) {
    return this.x -= t, this.y -= t, this;
  }
  /**
   * Subtracts the given vectors and stores the result in this instance.
   *
   * @param {Vector2} a - The first vector.
   * @param {Vector2} b - The second vector.
   * @return {Vector2} A reference to this vector.
   */
  subVectors(t, e) {
    return this.x = t.x - e.x, this.y = t.y - e.y, this;
  }
  /**
   * Multiplies the given vector with this instance.
   *
   * @param {Vector2} v - The vector to multiply.
   * @return {Vector2} A reference to this vector.
   */
  multiply(t) {
    return this.x *= t.x, this.y *= t.y, this;
  }
  /**
   * Multiplies the given scalar value with all components of this instance.
   *
   * @param {number} scalar - The scalar to multiply.
   * @return {Vector2} A reference to this vector.
   */
  multiplyScalar(t) {
    return this.x *= t, this.y *= t, this;
  }
  /**
   * Divides this instance by the given vector.
   *
   * @param {Vector2} v - The vector to divide.
   * @return {Vector2} A reference to this vector.
   */
  divide(t) {
    return this.x /= t.x, this.y /= t.y, this;
  }
  /**
   * Divides this vector by the given scalar.
   *
   * @param {number} scalar - The scalar to divide.
   * @return {Vector2} A reference to this vector.
   */
  divideScalar(t) {
    return this.multiplyScalar(1 / t);
  }
  /**
   * Multiplies this vector (with an implicit 1 as the 3rd component) by
   * the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to apply.
   * @return {Vector2} A reference to this vector.
   */
  applyMatrix3(t) {
    const e = this.x, i = this.y, n = t.elements;
    return this.x = n[0] * e + n[3] * i + n[6], this.y = n[1] * e + n[4] * i + n[7], this;
  }
  /**
   * If this vector's x or y value is greater than the given vector's x or y
   * value, replace that value with the corresponding min value.
   *
   * @param {Vector2} v - The vector.
   * @return {Vector2} A reference to this vector.
   */
  min(t) {
    return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this;
  }
  /**
   * If this vector's x or y value is less than the given vector's x or y
   * value, replace that value with the corresponding max value.
   *
   * @param {Vector2} v - The vector.
   * @return {Vector2} A reference to this vector.
   */
  max(t) {
    return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this;
  }
  /**
   * If this vector's x or y value is greater than the max vector's x or y
   * value, it is replaced by the corresponding value.
   * If this vector's x or y value is less than the min vector's x or y value,
   * it is replaced by the corresponding value.
   *
   * @param {Vector2} min - The minimum x and y values.
   * @param {Vector2} max - The maximum x and y values in the desired range.
   * @return {Vector2} A reference to this vector.
   */
  clamp(t, e) {
    return this.x = kt(this.x, t.x, e.x), this.y = kt(this.y, t.y, e.y), this;
  }
  /**
   * If this vector's x or y values are greater than the max value, they are
   * replaced by the max value.
   * If this vector's x or y values are less than the min value, they are
   * replaced by the min value.
   *
   * @param {number} minVal - The minimum value the components will be clamped to.
   * @param {number} maxVal - The maximum value the components will be clamped to.
   * @return {Vector2} A reference to this vector.
   */
  clampScalar(t, e) {
    return this.x = kt(this.x, t, e), this.y = kt(this.y, t, e), this;
  }
  /**
   * If this vector's length is greater than the max value, it is replaced by
   * the max value.
   * If this vector's length is less than the min value, it is replaced by the
   * min value.
   *
   * @param {number} min - The minimum value the vector length will be clamped to.
   * @param {number} max - The maximum value the vector length will be clamped to.
   * @return {Vector2} A reference to this vector.
   */
  clampLength(t, e) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(kt(i, t, e));
  }
  /**
   * The components of this vector are rounded down to the nearest integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this;
  }
  /**
   * The components of this vector are rounded up to the nearest integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this;
  }
  /**
   * The components of this vector are rounded to the nearest integer value
   *
   * @return {Vector2} A reference to this vector.
   */
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this;
  }
  /**
   * The components of this vector are rounded towards zero (up if negative,
   * down if positive) to an integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this;
  }
  /**
   * Inverts this vector - i.e. sets x = -x and y = -y.
   *
   * @return {Vector2} A reference to this vector.
   */
  negate() {
    return this.x = -this.x, this.y = -this.y, this;
  }
  /**
   * Calculates the dot product of the given vector with this instance.
   *
   * @param {Vector2} v - The vector to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(t) {
    return this.x * t.x + this.y * t.y;
  }
  /**
   * Calculates the cross product of the given vector with this instance.
   *
   * @param {Vector2} v - The vector to compute the cross product with.
   * @return {number} The result of the cross product.
   */
  cross(t) {
    return this.x * t.y - this.y * t.x;
  }
  /**
   * Computes the square of the Euclidean length (straight-line length) from
   * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
   * compare the length squared instead as it is slightly more efficient to calculate.
   *
   * @return {number} The square length of this vector.
   */
  lengthSq() {
    return this.x * this.x + this.y * this.y;
  }
  /**
   * Computes the  Euclidean length (straight-line length) from (0, 0) to (x, y).
   *
   * @return {number} The length of this vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
  /**
   * Computes the Manhattan length of this vector.
   *
   * @return {number} The length of this vector.
   */
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y);
  }
  /**
   * Converts this vector to a unit vector - that is, sets it equal to a vector
   * with the same direction as this one, but with a vector length of `1`.
   *
   * @return {Vector2} A reference to this vector.
   */
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  /**
   * Computes the angle in radians of this vector with respect to the positive x-axis.
   *
   * @return {number} The angle in radians.
   */
  angle() {
    return Math.atan2(-this.y, -this.x) + Math.PI;
  }
  /**
   * Returns the angle between the given vector and this instance in radians.
   *
   * @param {Vector2} v - The vector to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(t) {
    const e = Math.sqrt(this.lengthSq() * t.lengthSq());
    if (e === 0) return Math.PI / 2;
    const i = this.dot(t) / e;
    return Math.acos(kt(i, -1, 1));
  }
  /**
   * Computes the distance from the given vector to this instance.
   *
   * @param {Vector2} v - The vector to compute the distance to.
   * @return {number} The distance.
   */
  distanceTo(t) {
    return Math.sqrt(this.distanceToSquared(t));
  }
  /**
   * Computes the squared distance from the given vector to this instance.
   * If you are just comparing the distance with another distance, you should compare
   * the distance squared instead as it is slightly more efficient to calculate.
   *
   * @param {Vector2} v - The vector to compute the squared distance to.
   * @return {number} The squared distance.
   */
  distanceToSquared(t) {
    const e = this.x - t.x, i = this.y - t.y;
    return e * e + i * i;
  }
  /**
   * Computes the Manhattan distance from the given vector to this instance.
   *
   * @param {Vector2} v - The vector to compute the Manhattan distance to.
   * @return {number} The Manhattan distance.
   */
  manhattanDistanceTo(t) {
    return Math.abs(this.x - t.x) + Math.abs(this.y - t.y);
  }
  /**
   * Sets this vector to a vector with the same direction as this one, but
   * with the specified length.
   *
   * @param {number} length - The new length of this vector.
   * @return {Vector2} A reference to this vector.
   */
  setLength(t) {
    return this.normalize().multiplyScalar(t);
  }
  /**
   * Linearly interpolates between the given vector and this instance, where
   * alpha is the percent distance along the line - alpha = 0 will be this
   * vector, and alpha = 1 will be the given one.
   *
   * @param {Vector2} v - The vector to interpolate towards.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector2} A reference to this vector.
   */
  lerp(t, e) {
    return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this;
  }
  /**
   * Linearly interpolates between the given vectors, where alpha is the percent
   * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
   * be the second one. The result is stored in this instance.
   *
   * @param {Vector2} v1 - The first vector.
   * @param {Vector2} v2 - The second vector.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector2} A reference to this vector.
   */
  lerpVectors(t, e, i) {
    return this.x = t.x + (e.x - t.x) * i, this.y = t.y + (e.y - t.y) * i, this;
  }
  /**
   * Returns `true` if this vector is equal with the given one.
   *
   * @param {Vector2} v - The vector to test for equality.
   * @return {boolean} Whether this vector is equal with the given one.
   */
  equals(t) {
    return t.x === this.x && t.y === this.y;
  }
  /**
   * Sets this vector's x value to be `array[ offset ]` and y
   * value to be `array[ offset + 1 ]`.
   *
   * @param {Array<number>} array - An array holding the vector component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Vector2} A reference to this vector.
   */
  fromArray(t, e = 0) {
    return this.x = t[e], this.y = t[e + 1], this;
  }
  /**
   * Writes the components of this vector to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the vector components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The vector components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this.x, t[e + 1] = this.y, t;
  }
  /**
   * Sets the components of this vector from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
   * @param {number} index - The index into the attribute.
   * @return {Vector2} A reference to this vector.
   */
  fromBufferAttribute(t, e) {
    return this.x = t.getX(e), this.y = t.getY(e), this;
  }
  /**
   * Rotates this vector around the given center by the given angle.
   *
   * @param {Vector2} center - The point around which to rotate.
   * @param {number} angle - The angle to rotate, in radians.
   * @return {Vector2} A reference to this vector.
   */
  rotateAround(t, e) {
    const i = Math.cos(e), n = Math.sin(e), s = this.x - t.x, r = this.y - t.y;
    return this.x = s * i - r * n + t.x, this.y = s * n + r * i + t.y, this;
  }
  /**
   * Sets each component of this vector to a pseudo-random value between `0` and
   * `1`, excluding `1`.
   *
   * @return {Vector2} A reference to this vector.
   */
  random() {
    return this.x = Math.random(), this.y = Math.random(), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y;
  }
}, ve = class {
  /**
   * Constructs a new quaternion.
   *
   * @param {number} [x=0] - The x value of this quaternion.
   * @param {number} [y=0] - The y value of this quaternion.
   * @param {number} [z=0] - The z value of this quaternion.
   * @param {number} [w=1] - The w value of this quaternion.
   */
  constructor(t = 0, e = 0, i = 0, n = 1) {
    this.isQuaternion = !0, this._x = t, this._y = e, this._z = i, this._w = n;
  }
  /**
   * Interpolates between two quaternions via SLERP. This implementation assumes the
   * quaternion data are managed  in flat arrays.
   *
   * @param {Array<number>} dst - The destination array.
   * @param {number} dstOffset - An offset into the destination array.
   * @param {Array<number>} src0 - The source array of the first quaternion.
   * @param {number} srcOffset0 - An offset into the first source array.
   * @param {Array<number>} src1 -  The source array of the second quaternion.
   * @param {number} srcOffset1 - An offset into the second source array.
   * @param {number} t - The interpolation factor in the range `[0,1]`.
   * @see {@link Quaternion#slerp}
   */
  static slerpFlat(t, e, i, n, s, r, o) {
    let l = i[n + 0], h = i[n + 1], c = i[n + 2], u = i[n + 3];
    const d = s[r + 0], p = s[r + 1], f = s[r + 2], y = s[r + 3];
    if (o === 0) {
      t[e + 0] = l, t[e + 1] = h, t[e + 2] = c, t[e + 3] = u;
      return;
    }
    if (o === 1) {
      t[e + 0] = d, t[e + 1] = p, t[e + 2] = f, t[e + 3] = y;
      return;
    }
    if (u !== y || l !== d || h !== p || c !== f) {
      let g = 1 - o;
      const m = l * d + h * p + c * f + u * y, v = m >= 0 ? 1 : -1, x = 1 - m * m;
      if (x > Number.EPSILON) {
        const S = Math.sqrt(x), w = Math.atan2(S, m * v);
        g = Math.sin(g * w) / S, o = Math.sin(o * w) / S;
      }
      const _ = o * v;
      if (l = l * g + d * _, h = h * g + p * _, c = c * g + f * _, u = u * g + y * _, g === 1 - o) {
        const S = 1 / Math.sqrt(l * l + h * h + c * c + u * u);
        l *= S, h *= S, c *= S, u *= S;
      }
    }
    t[e] = l, t[e + 1] = h, t[e + 2] = c, t[e + 3] = u;
  }
  /**
   * Multiplies two quaternions. This implementation assumes the quaternion data are managed
   * in flat arrays.
   *
   * @param {Array<number>} dst - The destination array.
   * @param {number} dstOffset - An offset into the destination array.
   * @param {Array<number>} src0 - The source array of the first quaternion.
   * @param {number} srcOffset0 - An offset into the first source array.
   * @param {Array<number>} src1 -  The source array of the second quaternion.
   * @param {number} srcOffset1 - An offset into the second source array.
   * @return {Array<number>} The destination array.
   * @see {@link Quaternion#multiplyQuaternions}.
   */
  static multiplyQuaternionsFlat(t, e, i, n, s, r) {
    const o = i[n], l = i[n + 1], h = i[n + 2], c = i[n + 3], u = s[r], d = s[r + 1], p = s[r + 2], f = s[r + 3];
    return t[e] = o * f + c * u + l * p - h * d, t[e + 1] = l * f + c * d + h * u - o * p, t[e + 2] = h * f + c * p + o * d - l * u, t[e + 3] = c * f - o * u - l * d - h * p, t;
  }
  /**
   * The x value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get x() {
    return this._x;
  }
  set x(t) {
    this._x = t, this._onChangeCallback();
  }
  /**
   * The y value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get y() {
    return this._y;
  }
  set y(t) {
    this._y = t, this._onChangeCallback();
  }
  /**
   * The z value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get z() {
    return this._z;
  }
  set z(t) {
    this._z = t, this._onChangeCallback();
  }
  /**
   * The w value of this quaternion.
   *
   * @type {number}
   * @default 1
   */
  get w() {
    return this._w;
  }
  set w(t) {
    this._w = t, this._onChangeCallback();
  }
  /**
   * Sets the quaternion components.
   *
   * @param {number} x - The x value of this quaternion.
   * @param {number} y - The y value of this quaternion.
   * @param {number} z - The z value of this quaternion.
   * @param {number} w - The w value of this quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  set(t, e, i, n) {
    return this._x = t, this._y = e, this._z = i, this._w = n, this._onChangeCallback(), this;
  }
  /**
   * Returns a new quaternion with copied values from this instance.
   *
   * @return {Quaternion} A clone of this instance.
   */
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._w);
  }
  /**
   * Copies the values of the given quaternion to this instance.
   *
   * @param {Quaternion} quaternion - The quaternion to copy.
   * @return {Quaternion} A reference to this quaternion.
   */
  copy(t) {
    return this._x = t.x, this._y = t.y, this._z = t.z, this._w = t.w, this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the rotation specified by the given
   * Euler angles.
   *
   * @param {Euler} euler - The Euler angles.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromEuler(t, e = !0) {
    const i = t._x, n = t._y, s = t._z, r = t._order, o = Math.cos, l = Math.sin, h = o(i / 2), c = o(n / 2), u = o(s / 2), d = l(i / 2), p = l(n / 2), f = l(s / 2);
    switch (r) {
      case "XYZ":
        this._x = d * c * u + h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "YXZ":
        this._x = d * c * u + h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u + d * p * f;
        break;
      case "ZXY":
        this._x = d * c * u - h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "ZYX":
        this._x = d * c * u - h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u + d * p * f;
        break;
      case "YZX":
        this._x = d * c * u + h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "XZY":
        this._x = d * c * u - h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u + d * p * f;
        break;
      default:
        console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + r);
    }
    return e === !0 && this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the given axis and angle.
   *
   * @param {Vector3} axis - The normalized axis.
   * @param {number} angle - The angle in radians.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromAxisAngle(t, e) {
    const i = e / 2, n = Math.sin(i);
    return this._x = t.x * n, this._y = t.y * n, this._z = t.z * n, this._w = Math.cos(i), this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the given rotation matrix.
   *
   * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromRotationMatrix(t) {
    const e = t.elements, i = e[0], n = e[4], s = e[8], r = e[1], o = e[5], l = e[9], h = e[2], c = e[6], u = e[10], d = i + o + u;
    if (d > 0) {
      const p = 0.5 / Math.sqrt(d + 1);
      this._w = 0.25 / p, this._x = (c - l) * p, this._y = (s - h) * p, this._z = (r - n) * p;
    } else if (i > o && i > u) {
      const p = 2 * Math.sqrt(1 + i - o - u);
      this._w = (c - l) / p, this._x = 0.25 * p, this._y = (n + r) / p, this._z = (s + h) / p;
    } else if (o > u) {
      const p = 2 * Math.sqrt(1 + o - i - u);
      this._w = (s - h) / p, this._x = (n + r) / p, this._y = 0.25 * p, this._z = (l + c) / p;
    } else {
      const p = 2 * Math.sqrt(1 + u - i - o);
      this._w = (r - n) / p, this._x = (s + h) / p, this._y = (l + c) / p, this._z = 0.25 * p;
    }
    return this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion to the rotation required to rotate the direction vector
   * `vFrom` to the direction vector `vTo`.
   *
   * @param {Vector3} vFrom - The first (normalized) direction vector.
   * @param {Vector3} vTo - The second (normalized) direction vector.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromUnitVectors(t, e) {
    let i = t.dot(e) + 1;
    return i < 1e-8 ? (i = 0, Math.abs(t.x) > Math.abs(t.z) ? (this._x = -t.y, this._y = t.x, this._z = 0, this._w = i) : (this._x = 0, this._y = -t.z, this._z = t.y, this._w = i)) : (this._x = t.y * e.z - t.z * e.y, this._y = t.z * e.x - t.x * e.z, this._z = t.x * e.y - t.y * e.x, this._w = i), this.normalize();
  }
  /**
   * Returns the angle between this quaternion and the given one in radians.
   *
   * @param {Quaternion} q - The quaternion to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(t) {
    return 2 * Math.acos(Math.abs(kt(this.dot(t), -1, 1)));
  }
  /**
   * Rotates this quaternion by a given angular step to the given quaternion.
   * The method ensures that the final quaternion will not overshoot `q`.
   *
   * @param {Quaternion} q - The target quaternion.
   * @param {number} step - The angular step in radians.
   * @return {Quaternion} A reference to this quaternion.
   */
  rotateTowards(t, e) {
    const i = this.angleTo(t);
    if (i === 0) return this;
    const n = Math.min(1, e / i);
    return this.slerp(t, n), this;
  }
  /**
   * Sets this quaternion to the identity quaternion; that is, to the
   * quaternion that represents "no rotation".
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  identity() {
    return this.set(0, 0, 0, 1);
  }
  /**
   * Inverts this quaternion via {@link Quaternion#conjugate}. The
   * quaternion is assumed to have unit length.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  invert() {
    return this.conjugate();
  }
  /**
   * Returns the rotational conjugate of this quaternion. The conjugate of a
   * quaternion represents the same rotation in the opposite direction about
   * the rotational axis.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  conjugate() {
    return this._x *= -1, this._y *= -1, this._z *= -1, this._onChangeCallback(), this;
  }
  /**
   * Calculates the dot product of this quaternion and the given one.
   *
   * @param {Quaternion} v - The quaternion to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(t) {
    return this._x * t._x + this._y * t._y + this._z * t._z + this._w * t._w;
  }
  /**
   * Computes the squared Euclidean length (straight-line length) of this quaternion,
   * considered as a 4 dimensional vector. This can be useful if you are comparing the
   * lengths of two quaternions, as this is a slightly more efficient calculation than
   * {@link Quaternion#length}.
   *
   * @return {number} The squared Euclidean length.
   */
  lengthSq() {
    return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  }
  /**
   * Computes the Euclidean length (straight-line length) of this quaternion,
   * considered as a 4 dimensional vector.
   *
   * @return {number} The Euclidean length.
   */
  length() {
    return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  }
  /**
   * Normalizes this quaternion - that is, calculated the quaternion that performs
   * the same rotation as this one, but has a length equal to `1`.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  normalize() {
    let t = this.length();
    return t === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (t = 1 / t, this._x = this._x * t, this._y = this._y * t, this._z = this._z * t, this._w = this._w * t), this._onChangeCallback(), this;
  }
  /**
   * Multiplies this quaternion by the given one.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  multiply(t) {
    return this.multiplyQuaternions(this, t);
  }
  /**
   * Pre-multiplies this quaternion by the given one.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  premultiply(t) {
    return this.multiplyQuaternions(t, this);
  }
  /**
   * Multiplies the given quaternions and stores the result in this instance.
   *
   * @param {Quaternion} a - The first quaternion.
   * @param {Quaternion} b - The second quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  multiplyQuaternions(t, e) {
    const i = t._x, n = t._y, s = t._z, r = t._w, o = e._x, l = e._y, h = e._z, c = e._w;
    return this._x = i * c + r * o + n * h - s * l, this._y = n * c + r * l + s * o - i * h, this._z = s * c + r * h + i * l - n * o, this._w = r * c - i * o - n * l - s * h, this._onChangeCallback(), this;
  }
  /**
   * Performs a spherical linear interpolation between quaternions.
   *
   * @param {Quaternion} qb - The target quaternion.
   * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
   * @return {Quaternion} A reference to this quaternion.
   */
  slerp(t, e) {
    if (e === 0) return this;
    if (e === 1) return this.copy(t);
    const i = this._x, n = this._y, s = this._z, r = this._w;
    let o = r * t._w + i * t._x + n * t._y + s * t._z;
    if (o < 0 ? (this._w = -t._w, this._x = -t._x, this._y = -t._y, this._z = -t._z, o = -o) : this.copy(t), o >= 1)
      return this._w = r, this._x = i, this._y = n, this._z = s, this;
    const l = 1 - o * o;
    if (l <= Number.EPSILON) {
      const p = 1 - e;
      return this._w = p * r + e * this._w, this._x = p * i + e * this._x, this._y = p * n + e * this._y, this._z = p * s + e * this._z, this.normalize(), this;
    }
    const h = Math.sqrt(l), c = Math.atan2(h, o), u = Math.sin((1 - e) * c) / h, d = Math.sin(e * c) / h;
    return this._w = r * u + this._w * d, this._x = i * u + this._x * d, this._y = n * u + this._y * d, this._z = s * u + this._z * d, this._onChangeCallback(), this;
  }
  /**
   * Performs a spherical linear interpolation between the given quaternions
   * and stores the result in this quaternion.
   *
   * @param {Quaternion} qa - The source quaternion.
   * @param {Quaternion} qb - The target quaternion.
   * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
   * @return {Quaternion} A reference to this quaternion.
   */
  slerpQuaternions(t, e, i) {
    return this.copy(t).slerp(e, i);
  }
  /**
   * Sets this quaternion to a uniformly random, normalized quaternion.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  random() {
    const t = 2 * Math.PI * Math.random(), e = 2 * Math.PI * Math.random(), i = Math.random(), n = Math.sqrt(1 - i), s = Math.sqrt(i);
    return this.set(
      n * Math.sin(t),
      n * Math.cos(t),
      s * Math.sin(e),
      s * Math.cos(e)
    );
  }
  /**
   * Returns `true` if this quaternion is equal with the given one.
   *
   * @param {Quaternion} quaternion - The quaternion to test for equality.
   * @return {boolean} Whether this quaternion is equal with the given one.
   */
  equals(t) {
    return t._x === this._x && t._y === this._y && t._z === this._z && t._w === this._w;
  }
  /**
   * Sets this quaternion's components from the given array.
   *
   * @param {Array<number>} array - An array holding the quaternion component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Quaternion} A reference to this quaternion.
   */
  fromArray(t, e = 0) {
    return this._x = t[e], this._y = t[e + 1], this._z = t[e + 2], this._w = t[e + 3], this._onChangeCallback(), this;
  }
  /**
   * Writes the components of this quaternion to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The quaternion components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this._x, t[e + 1] = this._y, t[e + 2] = this._z, t[e + 3] = this._w, t;
  }
  /**
   * Sets the components of this quaternion from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
   * @param {number} index - The index into the attribute.
   * @return {Quaternion} A reference to this quaternion.
   */
  fromBufferAttribute(t, e) {
    return this._x = t.getX(e), this._y = t.getY(e), this._z = t.getZ(e), this._w = t.getW(e), this._onChangeCallback(), this;
  }
  /**
   * This methods defines the serialization result of this class. Returns the
   * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
   *
   * @return {Array<number>} The serialized quaternion.
   */
  toJSON() {
    return this.toArray();
  }
  _onChange(t) {
    return this._onChangeCallback = t, this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x, yield this._y, yield this._z, yield this._w;
  }
}, E = class my {
  /**
   * Constructs a new 3D vector.
   *
   * @param {number} [x=0] - The x value of this vector.
   * @param {number} [y=0] - The y value of this vector.
   * @param {number} [z=0] - The z value of this vector.
   */
  constructor(t = 0, e = 0, i = 0) {
    my.prototype.isVector3 = !0, this.x = t, this.y = e, this.z = i;
  }
  /**
   * Sets the vector components.
   *
   * @param {number} x - The value of the x component.
   * @param {number} y - The value of the y component.
   * @param {number} z - The value of the z component.
   * @return {Vector3} A reference to this vector.
   */
  set(t, e, i) {
    return i === void 0 && (i = this.z), this.x = t, this.y = e, this.z = i, this;
  }
  /**
   * Sets the vector components to the same value.
   *
   * @param {number} scalar - The value to set for all vector components.
   * @return {Vector3} A reference to this vector.
   */
  setScalar(t) {
    return this.x = t, this.y = t, this.z = t, this;
  }
  /**
   * Sets the vector's x component to the given value
   *
   * @param {number} x - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setX(t) {
    return this.x = t, this;
  }
  /**
   * Sets the vector's y component to the given value
   *
   * @param {number} y - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setY(t) {
    return this.y = t, this;
  }
  /**
   * Sets the vector's z component to the given value
   *
   * @param {number} z - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setZ(t) {
    return this.z = t, this;
  }
  /**
   * Allows to set a vector component with an index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
   * @param {number} value - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setComponent(t, e) {
    switch (t) {
      case 0:
        this.x = e;
        break;
      case 1:
        this.y = e;
        break;
      case 2:
        this.z = e;
        break;
      default:
        throw new Error("index is out of range: " + t);
    }
    return this;
  }
  /**
   * Returns the value of the vector component which matches the given index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
   * @return {number} A vector component value.
   */
  getComponent(t) {
    switch (t) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      default:
        throw new Error("index is out of range: " + t);
    }
  }
  /**
   * Returns a new vector with copied values from this instance.
   *
   * @return {Vector3} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.x, this.y, this.z);
  }
  /**
   * Copies the values of the given vector to this instance.
   *
   * @param {Vector3} v - The vector to copy.
   * @return {Vector3} A reference to this vector.
   */
  copy(t) {
    return this.x = t.x, this.y = t.y, this.z = t.z, this;
  }
  /**
   * Adds the given vector to this instance.
   *
   * @param {Vector3} v - The vector to add.
   * @return {Vector3} A reference to this vector.
   */
  add(t) {
    return this.x += t.x, this.y += t.y, this.z += t.z, this;
  }
  /**
   * Adds the given scalar value to all components of this instance.
   *
   * @param {number} s - The scalar to add.
   * @return {Vector3} A reference to this vector.
   */
  addScalar(t) {
    return this.x += t, this.y += t, this.z += t, this;
  }
  /**
   * Adds the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  addVectors(t, e) {
    return this.x = t.x + e.x, this.y = t.y + e.y, this.z = t.z + e.z, this;
  }
  /**
   * Adds the given vector scaled by the given factor to this instance.
   *
   * @param {Vector3|Vector4} v - The vector.
   * @param {number} s - The factor that scales `v`.
   * @return {Vector3} A reference to this vector.
   */
  addScaledVector(t, e) {
    return this.x += t.x * e, this.y += t.y * e, this.z += t.z * e, this;
  }
  /**
   * Subtracts the given vector from this instance.
   *
   * @param {Vector3} v - The vector to subtract.
   * @return {Vector3} A reference to this vector.
   */
  sub(t) {
    return this.x -= t.x, this.y -= t.y, this.z -= t.z, this;
  }
  /**
   * Subtracts the given scalar value from all components of this instance.
   *
   * @param {number} s - The scalar to subtract.
   * @return {Vector3} A reference to this vector.
   */
  subScalar(t) {
    return this.x -= t, this.y -= t, this.z -= t, this;
  }
  /**
   * Subtracts the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  subVectors(t, e) {
    return this.x = t.x - e.x, this.y = t.y - e.y, this.z = t.z - e.z, this;
  }
  /**
   * Multiplies the given vector with this instance.
   *
   * @param {Vector3} v - The vector to multiply.
   * @return {Vector3} A reference to this vector.
   */
  multiply(t) {
    return this.x *= t.x, this.y *= t.y, this.z *= t.z, this;
  }
  /**
   * Multiplies the given scalar value with all components of this instance.
   *
   * @param {number} scalar - The scalar to multiply.
   * @return {Vector3} A reference to this vector.
   */
  multiplyScalar(t) {
    return this.x *= t, this.y *= t, this.z *= t, this;
  }
  /**
   * Multiplies the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  multiplyVectors(t, e) {
    return this.x = t.x * e.x, this.y = t.y * e.y, this.z = t.z * e.z, this;
  }
  /**
   * Applies the given Euler rotation to this vector.
   *
   * @param {Euler} euler - The Euler angles.
   * @return {Vector3} A reference to this vector.
   */
  applyEuler(t) {
    return this.applyQuaternion(If.setFromEuler(t));
  }
  /**
   * Applies a rotation specified by an axis and an angle to this vector.
   *
   * @param {Vector3} axis - A normalized vector representing the rotation axis.
   * @param {number} angle - The angle in radians.
   * @return {Vector3} A reference to this vector.
   */
  applyAxisAngle(t, e) {
    return this.applyQuaternion(If.setFromAxisAngle(t, e));
  }
  /**
   * Multiplies this vector with the given 3x3 matrix.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @return {Vector3} A reference to this vector.
   */
  applyMatrix3(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements;
    return this.x = s[0] * e + s[3] * i + s[6] * n, this.y = s[1] * e + s[4] * i + s[7] * n, this.z = s[2] * e + s[5] * i + s[8] * n, this;
  }
  /**
   * Multiplies this vector by the given normal matrix and normalizes
   * the result.
   *
   * @param {Matrix3} m - The normal matrix.
   * @return {Vector3} A reference to this vector.
   */
  applyNormalMatrix(t) {
    return this.applyMatrix3(t).normalize();
  }
  /**
   * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
   * divides by perspective.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {Vector3} A reference to this vector.
   */
  applyMatrix4(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements, r = 1 / (s[3] * e + s[7] * i + s[11] * n + s[15]);
    return this.x = (s[0] * e + s[4] * i + s[8] * n + s[12]) * r, this.y = (s[1] * e + s[5] * i + s[9] * n + s[13]) * r, this.z = (s[2] * e + s[6] * i + s[10] * n + s[14]) * r, this;
  }
  /**
   * Applies the given Quaternion to this vector.
   *
   * @param {Quaternion} q - The Quaternion.
   * @return {Vector3} A reference to this vector.
   */
  applyQuaternion(t) {
    const e = this.x, i = this.y, n = this.z, s = t.x, r = t.y, o = t.z, l = t.w, h = 2 * (r * n - o * i), c = 2 * (o * e - s * n), u = 2 * (s * i - r * e);
    return this.x = e + l * h + r * u - o * c, this.y = i + l * c + o * h - s * u, this.z = n + l * u + s * c - r * h, this;
  }
  /**
   * Projects this vector from world space into the camera's normalized
   * device coordinate (NDC) space.
   *
   * @param {Camera} camera - The camera.
   * @return {Vector3} A reference to this vector.
   */
  project(t) {
    return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix);
  }
  /**
   * Unprojects this vector from the camera's normalized device coordinate (NDC)
   * space into world space.
   *
   * @param {Camera} camera - The camera.
   * @return {Vector3} A reference to this vector.
   */
  unproject(t) {
    return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld);
  }
  /**
   * Transforms the direction of this vector by a matrix (the upper left 3 x 3
   * subset of the given 4x4 matrix and then normalizes the result.
   *
   * @param {Matrix4} m - The matrix.
   * @return {Vector3} A reference to this vector.
   */
  transformDirection(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements;
    return this.x = s[0] * e + s[4] * i + s[8] * n, this.y = s[1] * e + s[5] * i + s[9] * n, this.z = s[2] * e + s[6] * i + s[10] * n, this.normalize();
  }
  /**
   * Divides this instance by the given vector.
   *
   * @param {Vector3} v - The vector to divide.
   * @return {Vector3} A reference to this vector.
   */
  divide(t) {
    return this.x /= t.x, this.y /= t.y, this.z /= t.z, this;
  }
  /**
   * Divides this vector by the given scalar.
   *
   * @param {number} scalar - The scalar to divide.
   * @return {Vector3} A reference to this vector.
   */
  divideScalar(t) {
    return this.multiplyScalar(1 / t);
  }
  /**
   * If this vector's x, y or z value is greater than the given vector's x, y or z
   * value, replace that value with the corresponding min value.
   *
   * @param {Vector3} v - The vector.
   * @return {Vector3} A reference to this vector.
   */
  min(t) {
    return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this.z = Math.min(this.z, t.z), this;
  }
  /**
   * If this vector's x, y or z value is less than the given vector's x, y or z
   * value, replace that value with the corresponding max value.
   *
   * @param {Vector3} v - The vector.
   * @return {Vector3} A reference to this vector.
   */
  max(t) {
    return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this.z = Math.max(this.z, t.z), this;
  }
  /**
   * If this vector's x, y or z value is greater than the max vector's x, y or z
   * value, it is replaced by the corresponding value.
   * If this vector's x, y or z value is less than the min vector's x, y or z value,
   * it is replaced by the corresponding value.
   *
   * @param {Vector3} min - The minimum x, y and z values.
   * @param {Vector3} max - The maximum x, y and z values in the desired range.
   * @return {Vector3} A reference to this vector.
   */
  clamp(t, e) {
    return this.x = kt(this.x, t.x, e.x), this.y = kt(this.y, t.y, e.y), this.z = kt(this.z, t.z, e.z), this;
  }
  /**
   * If this vector's x, y or z values are greater than the max value, they are
   * replaced by the max value.
   * If this vector's x, y or z values are less than the min value, they are
   * replaced by the min value.
   *
   * @param {number} minVal - The minimum value the components will be clamped to.
   * @param {number} maxVal - The maximum value the components will be clamped to.
   * @return {Vector3} A reference to this vector.
   */
  clampScalar(t, e) {
    return this.x = kt(this.x, t, e), this.y = kt(this.y, t, e), this.z = kt(this.z, t, e), this;
  }
  /**
   * If this vector's length is greater than the max value, it is replaced by
   * the max value.
   * If this vector's length is less than the min value, it is replaced by the
   * min value.
   *
   * @param {number} min - The minimum value the vector length will be clamped to.
   * @param {number} max - The maximum value the vector length will be clamped to.
   * @return {Vector3} A reference to this vector.
   */
  clampLength(t, e) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(kt(i, t, e));
  }
  /**
   * The components of this vector are rounded down to the nearest integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this;
  }
  /**
   * The components of this vector are rounded up to the nearest integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this;
  }
  /**
   * The components of this vector are rounded to the nearest integer value
   *
   * @return {Vector3} A reference to this vector.
   */
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this;
  }
  /**
   * The components of this vector are rounded towards zero (up if negative,
   * down if positive) to an integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this;
  }
  /**
   * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
   *
   * @return {Vector3} A reference to this vector.
   */
  negate() {
    return this.x = -this.x, this.y = -this.y, this.z = -this.z, this;
  }
  /**
   * Calculates the dot product of the given vector with this instance.
   *
   * @param {Vector3} v - The vector to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(t) {
    return this.x * t.x + this.y * t.y + this.z * t.z;
  }
  // TODO lengthSquared?
  /**
   * Computes the square of the Euclidean length (straight-line length) from
   * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
   * compare the length squared instead as it is slightly more efficient to calculate.
   *
   * @return {number} The square length of this vector.
   */
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z;
  }
  /**
   * Computes the  Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
   *
   * @return {number} The length of this vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  }
  /**
   * Computes the Manhattan length of this vector.
   *
   * @return {number} The length of this vector.
   */
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  }
  /**
   * Converts this vector to a unit vector - that is, sets it equal to a vector
   * with the same direction as this one, but with a vector length of `1`.
   *
   * @return {Vector3} A reference to this vector.
   */
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  /**
   * Sets this vector to a vector with the same direction as this one, but
   * with the specified length.
   *
   * @param {number} length - The new length of this vector.
   * @return {Vector3} A reference to this vector.
   */
  setLength(t) {
    return this.normalize().multiplyScalar(t);
  }
  /**
   * Linearly interpolates between the given vector and this instance, where
   * alpha is the percent distance along the line - alpha = 0 will be this
   * vector, and alpha = 1 will be the given one.
   *
   * @param {Vector3} v - The vector to interpolate towards.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector3} A reference to this vector.
   */
  lerp(t, e) {
    return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this.z += (t.z - this.z) * e, this;
  }
  /**
   * Linearly interpolates between the given vectors, where alpha is the percent
   * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
   * be the second one. The result is stored in this instance.
   *
   * @param {Vector3} v1 - The first vector.
   * @param {Vector3} v2 - The second vector.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector3} A reference to this vector.
   */
  lerpVectors(t, e, i) {
    return this.x = t.x + (e.x - t.x) * i, this.y = t.y + (e.y - t.y) * i, this.z = t.z + (e.z - t.z) * i, this;
  }
  /**
   * Calculates the cross product of the given vector with this instance.
   *
   * @param {Vector3} v - The vector to compute the cross product with.
   * @return {Vector3} The result of the cross product.
   */
  cross(t) {
    return this.crossVectors(this, t);
  }
  /**
   * Calculates the cross product of the given vectors and stores the result
   * in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  crossVectors(t, e) {
    const i = t.x, n = t.y, s = t.z, r = e.x, o = e.y, l = e.z;
    return this.x = n * l - s * o, this.y = s * r - i * l, this.z = i * o - n * r, this;
  }
  /**
   * Projects this vector onto the given one.
   *
   * @param {Vector3} v - The vector to project to.
   * @return {Vector3} A reference to this vector.
   */
  projectOnVector(t) {
    const e = t.lengthSq();
    if (e === 0) return this.set(0, 0, 0);
    const i = t.dot(this) / e;
    return this.copy(t).multiplyScalar(i);
  }
  /**
   * Projects this vector onto a plane by subtracting this
   * vector projected onto the plane's normal from this vector.
   *
   * @param {Vector3} planeNormal - The plane normal.
   * @return {Vector3} A reference to this vector.
   */
  projectOnPlane(t) {
    return yu.copy(this).projectOnVector(t), this.sub(yu);
  }
  /**
   * Reflects this vector off a plane orthogonal to the given normal vector.
   *
   * @param {Vector3} normal - The (normalized) normal vector.
   * @return {Vector3} A reference to this vector.
   */
  reflect(t) {
    return this.sub(yu.copy(t).multiplyScalar(2 * this.dot(t)));
  }
  /**
   * Returns the angle between the given vector and this instance in radians.
   *
   * @param {Vector3} v - The vector to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(t) {
    const e = Math.sqrt(this.lengthSq() * t.lengthSq());
    if (e === 0) return Math.PI / 2;
    const i = this.dot(t) / e;
    return Math.acos(kt(i, -1, 1));
  }
  /**
   * Computes the distance from the given vector to this instance.
   *
   * @param {Vector3} v - The vector to compute the distance to.
   * @return {number} The distance.
   */
  distanceTo(t) {
    return Math.sqrt(this.distanceToSquared(t));
  }
  /**
   * Computes the squared distance from the given vector to this instance.
   * If you are just comparing the distance with another distance, you should compare
   * the distance squared instead as it is slightly more efficient to calculate.
   *
   * @param {Vector3} v - The vector to compute the squared distance to.
   * @return {number} The squared distance.
   */
  distanceToSquared(t) {
    const e = this.x - t.x, i = this.y - t.y, n = this.z - t.z;
    return e * e + i * i + n * n;
  }
  /**
   * Computes the Manhattan distance from the given vector to this instance.
   *
   * @param {Vector3} v - The vector to compute the Manhattan distance to.
   * @return {number} The Manhattan distance.
   */
  manhattanDistanceTo(t) {
    return Math.abs(this.x - t.x) + Math.abs(this.y - t.y) + Math.abs(this.z - t.z);
  }
  /**
   * Sets the vector components from the given spherical coordinates.
   *
   * @param {Spherical} s - The spherical coordinates.
   * @return {Vector3} A reference to this vector.
   */
  setFromSpherical(t) {
    return this.setFromSphericalCoords(t.radius, t.phi, t.theta);
  }
  /**
   * Sets the vector components from the given spherical coordinates.
   *
   * @param {number} radius - The radius.
   * @param {number} phi - The phi angle in radians.
   * @param {number} theta - The theta angle in radians.
   * @return {Vector3} A reference to this vector.
   */
  setFromSphericalCoords(t, e, i) {
    const n = Math.sin(e) * t;
    return this.x = n * Math.sin(i), this.y = Math.cos(e) * t, this.z = n * Math.cos(i), this;
  }
  /**
   * Sets the vector components from the given cylindrical coordinates.
   *
   * @param {Cylindrical} c - The cylindrical coordinates.
   * @return {Vector3} A reference to this vector.
   */
  setFromCylindrical(t) {
    return this.setFromCylindricalCoords(t.radius, t.theta, t.y);
  }
  /**
   * Sets the vector components from the given cylindrical coordinates.
   *
   * @param {number} radius - The radius.
   * @param {number} theta - The theta angle in radians.
   * @param {number} y - The y value.
   * @return {Vector3} A reference to this vector.
   */
  setFromCylindricalCoords(t, e, i) {
    return this.x = t * Math.sin(e), this.y = i, this.z = t * Math.cos(e), this;
  }
  /**
   * Sets the vector components to the position elements of the
   * given transformation matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixPosition(t) {
    const e = t.elements;
    return this.x = e[12], this.y = e[13], this.z = e[14], this;
  }
  /**
   * Sets the vector components to the scale elements of the
   * given transformation matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixScale(t) {
    const e = this.setFromMatrixColumn(t, 0).length(), i = this.setFromMatrixColumn(t, 1).length(), n = this.setFromMatrixColumn(t, 2).length();
    return this.x = e, this.y = i, this.z = n, this;
  }
  /**
   * Sets the vector components from the specified matrix column.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @param {number} index - The column index.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixColumn(t, e) {
    return this.fromArray(t.elements, e * 4);
  }
  /**
   * Sets the vector components from the specified matrix column.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @param {number} index - The column index.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrix3Column(t, e) {
    return this.fromArray(t.elements, e * 3);
  }
  /**
   * Sets the vector components from the given Euler angles.
   *
   * @param {Euler} e - The Euler angles to set.
   * @return {Vector3} A reference to this vector.
   */
  setFromEuler(t) {
    return this.x = t._x, this.y = t._y, this.z = t._z, this;
  }
  /**
   * Sets the vector components from the RGB components of the
   * given color.
   *
   * @param {Color} c - The color to set.
   * @return {Vector3} A reference to this vector.
   */
  setFromColor(t) {
    return this.x = t.r, this.y = t.g, this.z = t.b, this;
  }
  /**
   * Returns `true` if this vector is equal with the given one.
   *
   * @param {Vector3} v - The vector to test for equality.
   * @return {boolean} Whether this vector is equal with the given one.
   */
  equals(t) {
    return t.x === this.x && t.y === this.y && t.z === this.z;
  }
  /**
   * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
   * and z value to be `array[ offset + 2 ]`.
   *
   * @param {Array<number>} array - An array holding the vector component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Vector3} A reference to this vector.
   */
  fromArray(t, e = 0) {
    return this.x = t[e], this.y = t[e + 1], this.z = t[e + 2], this;
  }
  /**
   * Writes the components of this vector to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the vector components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The vector components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this.x, t[e + 1] = this.y, t[e + 2] = this.z, t;
  }
  /**
   * Sets the components of this vector from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
   * @param {number} index - The index into the attribute.
   * @return {Vector3} A reference to this vector.
   */
  fromBufferAttribute(t, e) {
    return this.x = t.getX(e), this.y = t.getY(e), this.z = t.getZ(e), this;
  }
  /**
   * Sets each component of this vector to a pseudo-random value between `0` and
   * `1`, excluding `1`.
   *
   * @return {Vector3} A reference to this vector.
   */
  random() {
    return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this;
  }
  /**
   * Sets this vector to a uniformly random point on a unit sphere.
   *
   * @return {Vector3} A reference to this vector.
   */
  randomDirection() {
    const t = Math.random() * Math.PI * 2, e = Math.random() * 2 - 1, i = Math.sqrt(1 - e * e);
    return this.x = i * Math.cos(t), this.y = e, this.z = i * Math.sin(t), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y, yield this.z;
  }
};
const yu = /* @__PURE__ */ new E(), If = /* @__PURE__ */ new ve();
let Xt = class gy {
  /**
   * Constructs a new 3x3 matrix. The arguments are supposed to be
   * in row-major order. If no arguments are provided, the constructor
   * initializes the matrix as an identity matrix.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   */
  constructor(t, e, i, n, s, r, o, l, h) {
    gy.prototype.isMatrix3 = !0, this.elements = [
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ], t !== void 0 && this.set(t, e, i, n, s, r, o, l, h);
  }
  /**
   * Sets the elements of the matrix.The arguments are supposed to be
   * in row-major order.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @return {Matrix3} A reference to this matrix.
   */
  set(t, e, i, n, s, r, o, l, h) {
    const c = this.elements;
    return c[0] = t, c[1] = n, c[2] = o, c[3] = e, c[4] = s, c[5] = l, c[6] = i, c[7] = r, c[8] = h, this;
  }
  /**
   * Sets this matrix to the 3x3 identity matrix.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  identity() {
    return this.set(
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Copies the values of the given matrix to this instance.
   *
   * @param {Matrix3} m - The matrix to copy.
   * @return {Matrix3} A reference to this matrix.
   */
  copy(t) {
    const e = this.elements, i = t.elements;
    return e[0] = i[0], e[1] = i[1], e[2] = i[2], e[3] = i[3], e[4] = i[4], e[5] = i[5], e[6] = i[6], e[7] = i[7], e[8] = i[8], this;
  }
  /**
   * Extracts the basis of this matrix into the three axis vectors provided.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix3} A reference to this matrix.
   */
  extractBasis(t, e, i) {
    return t.setFromMatrix3Column(this, 0), e.setFromMatrix3Column(this, 1), i.setFromMatrix3Column(this, 2), this;
  }
  /**
   * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  setFromMatrix4(t) {
    const e = t.elements;
    return this.set(
      e[0],
      e[4],
      e[8],
      e[1],
      e[5],
      e[9],
      e[2],
      e[6],
      e[10]
    ), this;
  }
  /**
   * Post-multiplies this matrix by the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to multiply with.
   * @return {Matrix3} A reference to this matrix.
   */
  multiply(t) {
    return this.multiplyMatrices(this, t);
  }
  /**
   * Pre-multiplies this matrix by the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to multiply with.
   * @return {Matrix3} A reference to this matrix.
   */
  premultiply(t) {
    return this.multiplyMatrices(t, this);
  }
  /**
   * Multiples the given 3x3 matrices and stores the result
   * in this matrix.
   *
   * @param {Matrix3} a - The first matrix.
   * @param {Matrix3} b - The second matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  multiplyMatrices(t, e) {
    const i = t.elements, n = e.elements, s = this.elements, r = i[0], o = i[3], l = i[6], h = i[1], c = i[4], u = i[7], d = i[2], p = i[5], f = i[8], y = n[0], g = n[3], m = n[6], v = n[1], x = n[4], _ = n[7], S = n[2], w = n[5], T = n[8];
    return s[0] = r * y + o * v + l * S, s[3] = r * g + o * x + l * w, s[6] = r * m + o * _ + l * T, s[1] = h * y + c * v + u * S, s[4] = h * g + c * x + u * w, s[7] = h * m + c * _ + u * T, s[2] = d * y + p * v + f * S, s[5] = d * g + p * x + f * w, s[8] = d * m + p * _ + f * T, this;
  }
  /**
   * Multiplies every component of the matrix by the given scalar.
   *
   * @param {number} s - The scalar.
   * @return {Matrix3} A reference to this matrix.
   */
  multiplyScalar(t) {
    const e = this.elements;
    return e[0] *= t, e[3] *= t, e[6] *= t, e[1] *= t, e[4] *= t, e[7] *= t, e[2] *= t, e[5] *= t, e[8] *= t, this;
  }
  /**
   * Computes and returns the determinant of this matrix.
   *
   * @return {number} The determinant.
   */
  determinant() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8];
    return e * r * c - e * o * h - i * s * c + i * o * l + n * s * h - n * r * l;
  }
  /**
   * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
   * You can not invert with a determinant of zero. If you attempt this, the method produces
   * a zero matrix instead.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  invert() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8], u = c * r - o * h, d = o * l - c * s, p = h * s - r * l, f = e * u + i * d + n * p;
    if (f === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
    const y = 1 / f;
    return t[0] = u * y, t[1] = (n * h - c * i) * y, t[2] = (o * i - n * r) * y, t[3] = d * y, t[4] = (c * e - n * l) * y, t[5] = (n * s - o * e) * y, t[6] = p * y, t[7] = (i * l - h * e) * y, t[8] = (r * e - i * s) * y, this;
  }
  /**
   * Transposes this matrix in place.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  transpose() {
    let t;
    const e = this.elements;
    return t = e[1], e[1] = e[3], e[3] = t, t = e[2], e[2] = e[6], e[6] = t, t = e[5], e[5] = e[7], e[7] = t, this;
  }
  /**
   * Computes the normal matrix which is the inverse transpose of the upper
   * left 3x3 portion of the given 4x4 matrix.
   *
   * @param {Matrix4} matrix4 - The 4x4 matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  getNormalMatrix(t) {
    return this.setFromMatrix4(t).invert().transpose();
  }
  /**
   * Transposes this matrix into the supplied array, and returns itself unchanged.
   *
   * @param {Array<number>} r - An array to store the transposed matrix elements.
   * @return {Matrix3} A reference to this matrix.
   */
  transposeIntoArray(t) {
    const e = this.elements;
    return t[0] = e[0], t[1] = e[3], t[2] = e[6], t[3] = e[1], t[4] = e[4], t[5] = e[7], t[6] = e[2], t[7] = e[5], t[8] = e[8], this;
  }
  /**
   * Sets the UV transform matrix from offset, repeat, rotation, and center.
   *
   * @param {number} tx - Offset x.
   * @param {number} ty - Offset y.
   * @param {number} sx - Repeat x.
   * @param {number} sy - Repeat y.
   * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
   * @param {number} cx - Center x of rotation.
   * @param {number} cy - Center y of rotation
   * @return {Matrix3} A reference to this matrix.
   */
  setUvTransform(t, e, i, n, s, r, o) {
    const l = Math.cos(s), h = Math.sin(s);
    return this.set(
      i * l,
      i * h,
      -i * (l * r + h * o) + r + t,
      -n * h,
      n * l,
      -n * (-h * r + l * o) + o + e,
      0,
      0,
      1
    ), this;
  }
  /**
   * Scales this matrix with the given scalar values.
   *
   * @param {number} sx - The amount to scale in the X axis.
   * @param {number} sy - The amount to scale in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  scale(t, e) {
    return this.premultiply(_u.makeScale(t, e)), this;
  }
  /**
   * Rotates this matrix by the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix3} A reference to this matrix.
   */
  rotate(t) {
    return this.premultiply(_u.makeRotation(-t)), this;
  }
  /**
   * Translates this matrix by the given scalar values.
   *
   * @param {number} tx - The amount to translate in the X axis.
   * @param {number} ty - The amount to translate in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  translate(t, e) {
    return this.premultiply(_u.makeTranslation(t, e)), this;
  }
  // for 2D Transforms
  /**
   * Sets this matrix as a 2D translation transform.
   *
   * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
   * @param {number} y - The amount to translate in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  makeTranslation(t, e) {
    return t.isVector2 ? this.set(
      1,
      0,
      t.x,
      0,
      1,
      t.y,
      0,
      0,
      1
    ) : this.set(
      1,
      0,
      t,
      0,
      1,
      e,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a 2D rotational transformation.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix3} A reference to this matrix.
   */
  makeRotation(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      -i,
      0,
      i,
      e,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a 2D scale transform.
   *
   * @param {number} x - The amount to scale in the X axis.
   * @param {number} y - The amount to scale in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  makeScale(t, e) {
    return this.set(
      t,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Returns `true` if this matrix is equal with the given one.
   *
   * @param {Matrix3} matrix - The matrix to test for equality.
   * @return {boolean} Whether this matrix is equal with the given one.
   */
  equals(t) {
    const e = this.elements, i = t.elements;
    for (let n = 0; n < 9; n++)
      if (e[n] !== i[n]) return !1;
    return !0;
  }
  /**
   * Sets the elements of the matrix from the given array.
   *
   * @param {Array<number>} array - The matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Matrix3} A reference to this matrix.
   */
  fromArray(t, e = 0) {
    for (let i = 0; i < 9; i++)
      this.elements[i] = t[i + e];
    return this;
  }
  /**
   * Writes the elements of this matrix to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The matrix elements in column-major order.
   */
  toArray(t = [], e = 0) {
    const i = this.elements;
    return t[e] = i[0], t[e + 1] = i[1], t[e + 2] = i[2], t[e + 3] = i[3], t[e + 4] = i[4], t[e + 5] = i[5], t[e + 6] = i[6], t[e + 7] = i[7], t[e + 8] = i[8], t;
  }
  /**
   * Returns a matrix with copied values from this instance.
   *
   * @return {Matrix3} A clone of this instance.
   */
  clone() {
    return new this.constructor().fromArray(this.elements);
  }
};
const _u = /* @__PURE__ */ new Xt();
function yy(a) {
  for (let t = a.length - 1; t >= 0; --t)
    if (a[t] >= 65535) return !0;
  return !1;
}
const dv = {
  Int8Array,
  Uint8Array,
  Uint8ClampedArray,
  Int16Array,
  Uint16Array,
  Int32Array,
  Uint32Array,
  Float32Array,
  Float64Array
};
function ra(a, t) {
  return new dv[a](t);
}
function Ro(a) {
  return document.createElementNS("http://www.w3.org/1999/xhtml", a);
}
function _y() {
  const a = Ro("canvas");
  return a.style.display = "block", a;
}
const Lf = {};
function Po(a) {
  a in Lf || (Lf[a] = !0, console.warn(a));
}
function pv(a, t, e) {
  return new Promise(function(i, n) {
    function s() {
      switch (a.clientWaitSync(t, a.SYNC_FLUSH_COMMANDS_BIT, 0)) {
        case a.WAIT_FAILED:
          n();
          break;
        case a.TIMEOUT_EXPIRED:
          setTimeout(s, e);
          break;
        default:
          i();
      }
    }
    setTimeout(s, e);
  });
}
const Df = /* @__PURE__ */ new Xt().set(
  0.4123908,
  0.3575843,
  0.1804808,
  0.212639,
  0.7151687,
  0.0721923,
  0.0193308,
  0.1191948,
  0.9505322
), Ff = /* @__PURE__ */ new Xt().set(
  3.2409699,
  -1.5373832,
  -0.4986108,
  -0.9692436,
  1.8759675,
  0.0415551,
  0.0556301,
  -0.203977,
  1.0569715
);
function fv() {
  const a = {
    enabled: !0,
    workingColorSpace: Cs,
    /**
     * Implementations of supported color spaces.
     *
     * Required:
     *	- primaries: chromaticity coordinates [ rx ry gx gy bx by ]
     *	- whitePoint: reference white [ x y ]
     *	- transfer: transfer function (pre-defined)
     *	- toXYZ: Matrix3 RGB to XYZ transform
     *	- fromXYZ: Matrix3 XYZ to RGB transform
     *	- luminanceCoefficients: RGB luminance coefficients
     *
     * Optional:
     *  - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
     *  - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
     *
     * Reference:
     * - https://www.russellcottrell.com/photo/matrixCalculator.htm
     */
    spaces: {},
    convert: function(n, s, r) {
      return this.enabled === !1 || s === r || !s || !r || (this.spaces[s].transfer === ce && (n.r = jn(n.r), n.g = jn(n.g), n.b = jn(n.b)), this.spaces[s].primaries !== this.spaces[r].primaries && (n.applyMatrix3(this.spaces[s].toXYZ), n.applyMatrix3(this.spaces[r].fromXYZ)), this.spaces[r].transfer === ce && (n.r = oa(n.r), n.g = oa(n.g), n.b = oa(n.b))), n;
    },
    workingToColorSpace: function(n, s) {
      return this.convert(n, this.workingColorSpace, s);
    },
    colorSpaceToWorking: function(n, s) {
      return this.convert(n, s, this.workingColorSpace);
    },
    getPrimaries: function(n) {
      return this.spaces[n].primaries;
    },
    getTransfer: function(n) {
      return n === $n ? Eo : this.spaces[n].transfer;
    },
    getToneMappingMode: function(n) {
      return this.spaces[n].outputColorSpaceConfig.toneMappingMode || "standard";
    },
    getLuminanceCoefficients: function(n, s = this.workingColorSpace) {
      return n.fromArray(this.spaces[s].luminanceCoefficients);
    },
    define: function(n) {
      Object.assign(this.spaces, n);
    },
    // Internal APIs
    _getMatrix: function(n, s, r) {
      return n.copy(this.spaces[s].toXYZ).multiply(this.spaces[r].fromXYZ);
    },
    _getDrawingBufferColorSpace: function(n) {
      return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace;
    },
    _getUnpackColorSpace: function(n = this.workingColorSpace) {
      return this.spaces[n].workingColorSpaceConfig.unpackColorSpace;
    },
    // Deprecated
    fromWorkingColorSpace: function(n, s) {
      return Po("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."), a.workingToColorSpace(n, s);
    },
    toWorkingColorSpace: function(n, s) {
      return Po("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."), a.colorSpaceToWorking(n, s);
    }
  }, t = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], e = [0.2126, 0.7152, 0.0722], i = [0.3127, 0.329];
  return a.define({
    [Cs]: {
      primaries: t,
      whitePoint: i,
      transfer: Eo,
      toXYZ: Df,
      fromXYZ: Ff,
      luminanceCoefficients: e,
      workingColorSpaceConfig: { unpackColorSpace: ri },
      outputColorSpaceConfig: { drawingBufferColorSpace: ri }
    },
    [ri]: {
      primaries: t,
      whitePoint: i,
      transfer: ce,
      toXYZ: Df,
      fromXYZ: Ff,
      luminanceCoefficients: e,
      outputColorSpaceConfig: { drawingBufferColorSpace: ri }
    }
  }), a;
}
const ee = /* @__PURE__ */ fv();
function jn(a) {
  return a < 0.04045 ? a * 0.0773993808 : Math.pow(a * 0.9478672986 + 0.0521327014, 2.4);
}
function oa(a) {
  return a < 31308e-7 ? a * 12.92 : 1.055 * Math.pow(a, 0.41666) - 0.055;
}
let vr, xy = class {
  /**
   * Returns a data URI containing a representation of the given image.
   *
   * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
   * @param {string} [type='image/png'] - Indicates the image format.
   * @return {string} The data URI.
   */
  static getDataURL(t, e = "image/png") {
    if (/^data:/i.test(t.src) || typeof HTMLCanvasElement > "u")
      return t.src;
    let i;
    if (t instanceof HTMLCanvasElement)
      i = t;
    else {
      vr === void 0 && (vr = Ro("canvas")), vr.width = t.width, vr.height = t.height;
      const n = vr.getContext("2d");
      t instanceof ImageData ? n.putImageData(t, 0, 0) : n.drawImage(t, 0, 0, t.width, t.height), i = vr;
    }
    return i.toDataURL(e);
  }
  /**
   * Converts the given sRGB image data to linear color space.
   *
   * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
   * @return {HTMLCanvasElement|Object} The converted image.
   */
  static sRGBToLinear(t) {
    if (typeof HTMLImageElement < "u" && t instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && t instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && t instanceof ImageBitmap) {
      const e = Ro("canvas");
      e.width = t.width, e.height = t.height;
      const i = e.getContext("2d");
      i.drawImage(t, 0, 0, t.width, t.height);
      const n = i.getImageData(0, 0, t.width, t.height), s = n.data;
      for (let r = 0; r < s.length; r++)
        s[r] = jn(s[r] / 255) * 255;
      return i.putImageData(n, 0, 0), e;
    } else if (t.data) {
      const e = t.data.slice(0);
      for (let i = 0; i < e.length; i++)
        e instanceof Uint8Array || e instanceof Uint8ClampedArray ? e[i] = Math.floor(jn(e[i] / 255) * 255) : e[i] = jn(e[i]);
      return {
        data: e,
        width: t.width,
        height: t.height
      };
    } else
      return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), t;
  }
}, mv = 0, Ms = class {
  /**
   * Constructs a new video texture.
   *
   * @param {any} [data=null] - The data definition of a texture.
   */
  constructor(t = null) {
    this.isSource = !0, Object.defineProperty(this, "id", { value: mv++ }), this.uuid = Oi(), this.data = t, this.dataReady = !0, this.version = 0;
  }
  /**
   * Returns the dimensions of the source into the given target vector.
   *
   * @param {(Vector2|Vector3)} target - The target object the result is written into.
   * @return {(Vector2|Vector3)} The dimensions of the source.
   */
  getSize(t) {
    const e = this.data;
    return typeof HTMLVideoElement < "u" && e instanceof HTMLVideoElement ? t.set(e.videoWidth, e.videoHeight, 0) : e instanceof VideoFrame ? t.set(e.displayHeight, e.displayWidth, 0) : e !== null ? t.set(e.width, e.height, e.depth || 0) : t.set(0, 0, 0), t;
  }
  /**
   * When the property is set to `true`, the engine allocates the memory
   * for the texture (if necessary) and triggers the actual texture upload
   * to the GPU next time the source is used.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  /**
   * Serializes the source into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized source.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(t) {
    const e = t === void 0 || typeof t == "string";
    if (!e && t.images[this.uuid] !== void 0)
      return t.images[this.uuid];
    const i = {
      uuid: this.uuid,
      url: ""
    }, n = this.data;
    if (n !== null) {
      let s;
      if (Array.isArray(n)) {
        s = [];
        for (let r = 0, o = n.length; r < o; r++)
          n[r].isDataTexture ? s.push(xu(n[r].image)) : s.push(xu(n[r]));
      } else
        s = xu(n);
      i.url = s;
    }
    return e || (t.images[this.uuid] = i), i;
  }
};
function xu(a) {
  return typeof HTMLImageElement < "u" && a instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && a instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && a instanceof ImageBitmap ? xy.getDataURL(a) : a.data ? {
    data: Array.from(a.data),
    width: a.width,
    height: a.height,
    type: a.data.constructor.name
  } : (console.warn("THREE.Texture: Unable to serialize Texture."), {});
}
let gv = 0;
const vu = /* @__PURE__ */ new E();
let Ne = class Ah extends Ei {
  /**
   * Constructs a new texture.
   *
   * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space.
   */
  constructor(t = Ah.DEFAULT_IMAGE, e = Ah.DEFAULT_MAPPING, i = Si, n = Si, s = Ce, r = En, o = gi, l = pn, h = Ah.DEFAULT_ANISOTROPY, c = $n) {
    super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: gv++ }), this.uuid = Oi(), this.name = "", this.source = new Ms(t), this.mipmaps = [], this.mapping = e, this.channel = 0, this.wrapS = i, this.wrapT = n, this.magFilter = s, this.minFilter = r, this.anisotropy = h, this.format = o, this.internalFormat = null, this.type = l, this.offset = new J(0, 0), this.repeat = new J(1, 1), this.center = new J(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new Xt(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = c, this.userData = {}, this.updateRanges = [], this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isArrayTexture = !!(t && t.depth && t.depth > 1), this.pmremVersion = 0;
  }
  /**
   * The width of the texture in pixels.
   */
  get width() {
    return this.source.getSize(vu).x;
  }
  /**
   * The height of the texture in pixels.
   */
  get height() {
    return this.source.getSize(vu).y;
  }
  /**
   * The depth of the texture in pixels.
   */
  get depth() {
    return this.source.getSize(vu).z;
  }
  /**
   * The image object holding the texture data.
   *
   * @type {?Object}
   */
  get image() {
    return this.source.data;
  }
  set image(t = null) {
    this.source.data = t;
  }
  /**
   * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
   * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
   */
  updateMatrix() {
    this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  }
  /**
   * Adds a range of data in the data texture to be updated on the GPU.
   *
   * @param {number} start - Position at which to start update.
   * @param {number} count - The number of components to update.
   */
  addUpdateRange(t, e) {
    this.updateRanges.push({ start: t, count: e });
  }
  /**
   * Clears the update ranges.
   */
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  /**
   * Returns a new texture with copied values from this instance.
   *
   * @return {Texture} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given texture to this instance.
   *
   * @param {Texture} source - The texture to copy.
   * @return {Texture} A reference to this instance.
   */
  copy(t) {
    return this.name = t.name, this.source = t.source, this.mipmaps = t.mipmaps.slice(0), this.mapping = t.mapping, this.channel = t.channel, this.wrapS = t.wrapS, this.wrapT = t.wrapT, this.magFilter = t.magFilter, this.minFilter = t.minFilter, this.anisotropy = t.anisotropy, this.format = t.format, this.internalFormat = t.internalFormat, this.type = t.type, this.offset.copy(t.offset), this.repeat.copy(t.repeat), this.center.copy(t.center), this.rotation = t.rotation, this.matrixAutoUpdate = t.matrixAutoUpdate, this.matrix.copy(t.matrix), this.generateMipmaps = t.generateMipmaps, this.premultiplyAlpha = t.premultiplyAlpha, this.flipY = t.flipY, this.unpackAlignment = t.unpackAlignment, this.colorSpace = t.colorSpace, this.renderTarget = t.renderTarget, this.isRenderTargetTexture = t.isRenderTargetTexture, this.isArrayTexture = t.isArrayTexture, this.userData = JSON.parse(JSON.stringify(t.userData)), this.needsUpdate = !0, this;
  }
  /**
   * Sets this texture's properties based on `values`.
   * @param {Object} values - A container with texture parameters.
   */
  setValues(t) {
    for (const e in t) {
      const i = t[e];
      if (i === void 0) {
        console.warn(`THREE.Texture.setValues(): parameter '${e}' has value of undefined.`);
        continue;
      }
      const n = this[e];
      if (n === void 0) {
        console.warn(`THREE.Texture.setValues(): property '${e}' does not exist.`);
        continue;
      }
      n && i && n.isVector2 && i.isVector2 || n && i && n.isVector3 && i.isVector3 || n && i && n.isMatrix3 && i.isMatrix3 ? n.copy(i) : this[e] = i;
    }
  }
  /**
   * Serializes the texture into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized texture.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(t) {
    const e = t === void 0 || typeof t == "string";
    if (!e && t.textures[this.uuid] !== void 0)
      return t.textures[this.uuid];
    const i = {
      metadata: {
        version: 4.7,
        type: "Texture",
        generator: "Texture.toJSON"
      },
      uuid: this.uuid,
      name: this.name,
      image: this.source.toJSON(t).uuid,
      mapping: this.mapping,
      channel: this.channel,
      repeat: [this.repeat.x, this.repeat.y],
      offset: [this.offset.x, this.offset.y],
      center: [this.center.x, this.center.y],
      rotation: this.rotation,
      wrap: [this.wrapS, this.wrapT],
      format: this.format,
      internalFormat: this.internalFormat,
      type: this.type,
      colorSpace: this.colorSpace,
      minFilter: this.minFilter,
      magFilter: this.magFilter,
      anisotropy: this.anisotropy,
      flipY: this.flipY,
      generateMipmaps: this.generateMipmaps,
      premultiplyAlpha: this.premultiplyAlpha,
      unpackAlignment: this.unpackAlignment
    };
    return Object.keys(this.userData).length > 0 && (i.userData = this.userData), e || (t.textures[this.uuid] = i), i;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires Texture#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  /**
   * Transforms the given uv vector with the textures uv transformation matrix.
   *
   * @param {Vector2} uv - The uv vector.
   * @return {Vector2} The transformed uv vector.
   */
  transformUv(t) {
    if (this.mapping !== Cc) return t;
    if (t.applyMatrix3(this.matrix), t.x < 0 || t.x > 1)
      switch (this.wrapS) {
        case Mo:
          t.x = t.x - Math.floor(t.x);
          break;
        case Si:
          t.x = t.x < 0 ? 0 : 1;
          break;
        case So:
          Math.abs(Math.floor(t.x) % 2) === 1 ? t.x = Math.ceil(t.x) - t.x : t.x = t.x - Math.floor(t.x);
          break;
      }
    if (t.y < 0 || t.y > 1)
      switch (this.wrapT) {
        case Mo:
          t.y = t.y - Math.floor(t.y);
          break;
        case Si:
          t.y = t.y < 0 ? 0 : 1;
          break;
        case So:
          Math.abs(Math.floor(t.y) % 2) === 1 ? t.y = Math.ceil(t.y) - t.y : t.y = t.y - Math.floor(t.y);
          break;
      }
    return this.flipY && (t.y = 1 - t.y), t;
  }
  /**
   * Setting this property to `true` indicates the engine the texture
   * must be updated in the next render. This triggers a texture upload
   * to the GPU and ensures correct texture parameter configuration.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    t === !0 && (this.version++, this.source.needsUpdate = !0);
  }
  /**
   * Setting this property to `true` indicates the engine the PMREM
   * must be regenerated.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsPMREMUpdate(t) {
    t === !0 && this.pmremVersion++;
  }
};
Ne.DEFAULT_IMAGE = null;
Ne.DEFAULT_MAPPING = Cc;
Ne.DEFAULT_ANISOTROPY = 1;
let Qt = class vy {
  /**
   * Constructs a new 4D vector.
   *
   * @param {number} [x=0] - The x value of this vector.
   * @param {number} [y=0] - The y value of this vector.
   * @param {number} [z=0] - The z value of this vector.
   * @param {number} [w=1] - The w value of this vector.
   */
  constructor(t = 0, e = 0, i = 0, n = 1) {
    vy.prototype.isVector4 = !0, this.x = t, this.y = e, this.z = i, this.w = n;
  }
  /**
   * Alias for {@link Vector4#z}.
   *
   * @type {number}
   */
  get width() {
    return this.z;
  }
  set width(t) {
    this.z = t;
  }
  /**
   * Alias for {@link Vector4#w}.
   *
   * @type {number}
   */
  get height() {
    return this.w;
  }
  set height(t) {
    this.w = t;
  }
  /**
   * Sets the vector components.
   *
   * @param {number} x - The value of the x component.
   * @param {number} y - The value of the y component.
   * @param {number} z - The value of the z component.
   * @param {number} w - The value of the w component.
   * @return {Vector4} A reference to this vector.
   */
  set(t, e, i, n) {
    return this.x = t, this.y = e, this.z = i, this.w = n, this;
  }
  /**
   * Sets the vector components to the same value.
   *
   * @param {number} scalar - The value to set for all vector components.
   * @return {Vector4} A reference to this vector.
   */
  setScalar(t) {
    return this.x = t, this.y = t, this.z = t, this.w = t, this;
  }
  /**
   * Sets the vector's x component to the given value
   *
   * @param {number} x - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setX(t) {
    return this.x = t, this;
  }
  /**
   * Sets the vector's y component to the given value
   *
   * @param {number} y - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setY(t) {
    return this.y = t, this;
  }
  /**
   * Sets the vector's z component to the given value
   *
   * @param {number} z - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setZ(t) {
    return this.z = t, this;
  }
  /**
   * Sets the vector's w component to the given value
   *
   * @param {number} w - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setW(t) {
    return this.w = t, this;
  }
  /**
   * Allows to set a vector component with an index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y,
   * `2` equals to z, `3` equals to w.
   * @param {number} value - The value to set.
   * @return {Vector4} A reference to this vector.
   */
  setComponent(t, e) {
    switch (t) {
      case 0:
        this.x = e;
        break;
      case 1:
        this.y = e;
        break;
      case 2:
        this.z = e;
        break;
      case 3:
        this.w = e;
        break;
      default:
        throw new Error("index is out of range: " + t);
    }
    return this;
  }
  /**
   * Returns the value of the vector component which matches the given index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y,
   * `2` equals to z, `3` equals to w.
   * @return {number} A vector component value.
   */
  getComponent(t) {
    switch (t) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      case 3:
        return this.w;
      default:
        throw new Error("index is out of range: " + t);
    }
  }
  /**
   * Returns a new vector with copied values from this instance.
   *
   * @return {Vector4} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.x, this.y, this.z, this.w);
  }
  /**
   * Copies the values of the given vector to this instance.
   *
   * @param {Vector3|Vector4} v - The vector to copy.
   * @return {Vector4} A reference to this vector.
   */
  copy(t) {
    return this.x = t.x, this.y = t.y, this.z = t.z, this.w = t.w !== void 0 ? t.w : 1, this;
  }
  /**
   * Adds the given vector to this instance.
   *
   * @param {Vector4} v - The vector to add.
   * @return {Vector4} A reference to this vector.
   */
  add(t) {
    return this.x += t.x, this.y += t.y, this.z += t.z, this.w += t.w, this;
  }
  /**
   * Adds the given scalar value to all components of this instance.
   *
   * @param {number} s - The scalar to add.
   * @return {Vector4} A reference to this vector.
   */
  addScalar(t) {
    return this.x += t, this.y += t, this.z += t, this.w += t, this;
  }
  /**
   * Adds the given vectors and stores the result in this instance.
   *
   * @param {Vector4} a - The first vector.
   * @param {Vector4} b - The second vector.
   * @return {Vector4} A reference to this vector.
   */
  addVectors(t, e) {
    return this.x = t.x + e.x, this.y = t.y + e.y, this.z = t.z + e.z, this.w = t.w + e.w, this;
  }
  /**
   * Adds the given vector scaled by the given factor to this instance.
   *
   * @param {Vector4} v - The vector.
   * @param {number} s - The factor that scales `v`.
   * @return {Vector4} A reference to this vector.
   */
  addScaledVector(t, e) {
    return this.x += t.x * e, this.y += t.y * e, this.z += t.z * e, this.w += t.w * e, this;
  }
  /**
   * Subtracts the given vector from this instance.
   *
   * @param {Vector4} v - The vector to subtract.
   * @return {Vector4} A reference to this vector.
   */
  sub(t) {
    return this.x -= t.x, this.y -= t.y, this.z -= t.z, this.w -= t.w, this;
  }
  /**
   * Subtracts the given scalar value from all components of this instance.
   *
   * @param {number} s - The scalar to subtract.
   * @return {Vector4} A reference to this vector.
   */
  subScalar(t) {
    return this.x -= t, this.y -= t, this.z -= t, this.w -= t, this;
  }
  /**
   * Subtracts the given vectors and stores the result in this instance.
   *
   * @param {Vector4} a - The first vector.
   * @param {Vector4} b - The second vector.
   * @return {Vector4} A reference to this vector.
   */
  subVectors(t, e) {
    return this.x = t.x - e.x, this.y = t.y - e.y, this.z = t.z - e.z, this.w = t.w - e.w, this;
  }
  /**
   * Multiplies the given vector with this instance.
   *
   * @param {Vector4} v - The vector to multiply.
   * @return {Vector4} A reference to this vector.
   */
  multiply(t) {
    return this.x *= t.x, this.y *= t.y, this.z *= t.z, this.w *= t.w, this;
  }
  /**
   * Multiplies the given scalar value with all components of this instance.
   *
   * @param {number} scalar - The scalar to multiply.
   * @return {Vector4} A reference to this vector.
   */
  multiplyScalar(t) {
    return this.x *= t, this.y *= t, this.z *= t, this.w *= t, this;
  }
  /**
   * Multiplies this vector with the given 4x4 matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector4} A reference to this vector.
   */
  applyMatrix4(t) {
    const e = this.x, i = this.y, n = this.z, s = this.w, r = t.elements;
    return this.x = r[0] * e + r[4] * i + r[8] * n + r[12] * s, this.y = r[1] * e + r[5] * i + r[9] * n + r[13] * s, this.z = r[2] * e + r[6] * i + r[10] * n + r[14] * s, this.w = r[3] * e + r[7] * i + r[11] * n + r[15] * s, this;
  }
  /**
   * Divides this instance by the given vector.
   *
   * @param {Vector4} v - The vector to divide.
   * @return {Vector4} A reference to this vector.
   */
  divide(t) {
    return this.x /= t.x, this.y /= t.y, this.z /= t.z, this.w /= t.w, this;
  }
  /**
   * Divides this vector by the given scalar.
   *
   * @param {number} scalar - The scalar to divide.
   * @return {Vector4} A reference to this vector.
   */
  divideScalar(t) {
    return this.multiplyScalar(1 / t);
  }
  /**
   * Sets the x, y and z components of this
   * vector to the quaternion's axis and w to the angle.
   *
   * @param {Quaternion} q - The Quaternion to set.
   * @return {Vector4} A reference to this vector.
   */
  setAxisAngleFromQuaternion(t) {
    this.w = 2 * Math.acos(t.w);
    const e = Math.sqrt(1 - t.w * t.w);
    return e < 1e-4 ? (this.x = 1, this.y = 0, this.z = 0) : (this.x = t.x / e, this.y = t.y / e, this.z = t.z / e), this;
  }
  /**
   * Sets the x, y and z components of this
   * vector to the axis of rotation and w to the angle.
   *
   * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
   * @return {Vector4} A reference to this vector.
   */
  setAxisAngleFromRotationMatrix(t) {
    let e, i, n, s;
    const l = t.elements, h = l[0], c = l[4], u = l[8], d = l[1], p = l[5], f = l[9], y = l[2], g = l[6], m = l[10];
    if (Math.abs(c - d) < 0.01 && Math.abs(u - y) < 0.01 && Math.abs(f - g) < 0.01) {
      if (Math.abs(c + d) < 0.1 && Math.abs(u + y) < 0.1 && Math.abs(f + g) < 0.1 && Math.abs(h + p + m - 3) < 0.1)
        return this.set(1, 0, 0, 0), this;
      e = Math.PI;
      const x = (h + 1) / 2, _ = (p + 1) / 2, S = (m + 1) / 2, w = (c + d) / 4, T = (u + y) / 4, R = (f + g) / 4;
      return x > _ && x > S ? x < 0.01 ? (i = 0, n = 0.707106781, s = 0.707106781) : (i = Math.sqrt(x), n = w / i, s = T / i) : _ > S ? _ < 0.01 ? (i = 0.707106781, n = 0, s = 0.707106781) : (n = Math.sqrt(_), i = w / n, s = R / n) : S < 0.01 ? (i = 0.707106781, n = 0.707106781, s = 0) : (s = Math.sqrt(S), i = T / s, n = R / s), this.set(i, n, s, e), this;
    }
    let v = Math.sqrt((g - f) * (g - f) + (u - y) * (u - y) + (d - c) * (d - c));
    return Math.abs(v) < 1e-3 && (v = 1), this.x = (g - f) / v, this.y = (u - y) / v, this.z = (d - c) / v, this.w = Math.acos((h + p + m - 1) / 2), this;
  }
  /**
   * Sets the vector components to the position elements of the
   * given transformation matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector4} A reference to this vector.
   */
  setFromMatrixPosition(t) {
    const e = t.elements;
    return this.x = e[12], this.y = e[13], this.z = e[14], this.w = e[15], this;
  }
  /**
   * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
   * value, replace that value with the corresponding min value.
   *
   * @param {Vector4} v - The vector.
   * @return {Vector4} A reference to this vector.
   */
  min(t) {
    return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this.z = Math.min(this.z, t.z), this.w = Math.min(this.w, t.w), this;
  }
  /**
   * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
   * value, replace that value with the corresponding max value.
   *
   * @param {Vector4} v - The vector.
   * @return {Vector4} A reference to this vector.
   */
  max(t) {
    return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this.z = Math.max(this.z, t.z), this.w = Math.max(this.w, t.w), this;
  }
  /**
   * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
   * value, it is replaced by the corresponding value.
   * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
   * it is replaced by the corresponding value.
   *
   * @param {Vector4} min - The minimum x, y and z values.
   * @param {Vector4} max - The maximum x, y and z values in the desired range.
   * @return {Vector4} A reference to this vector.
   */
  clamp(t, e) {
    return this.x = kt(this.x, t.x, e.x), this.y = kt(this.y, t.y, e.y), this.z = kt(this.z, t.z, e.z), this.w = kt(this.w, t.w, e.w), this;
  }
  /**
   * If this vector's x, y, z or w values are greater than the max value, they are
   * replaced by the max value.
   * If this vector's x, y, z or w values are less than the min value, they are
   * replaced by the min value.
   *
   * @param {number} minVal - The minimum value the components will be clamped to.
   * @param {number} maxVal - The maximum value the components will be clamped to.
   * @return {Vector4} A reference to this vector.
   */
  clampScalar(t, e) {
    return this.x = kt(this.x, t, e), this.y = kt(this.y, t, e), this.z = kt(this.z, t, e), this.w = kt(this.w, t, e), this;
  }
  /**
   * If this vector's length is greater than the max value, it is replaced by
   * the max value.
   * If this vector's length is less than the min value, it is replaced by the
   * min value.
   *
   * @param {number} min - The minimum value the vector length will be clamped to.
   * @param {number} max - The maximum value the vector length will be clamped to.
   * @return {Vector4} A reference to this vector.
   */
  clampLength(t, e) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(kt(i, t, e));
  }
  /**
   * The components of this vector are rounded down to the nearest integer value.
   *
   * @return {Vector4} A reference to this vector.
   */
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this.w = Math.floor(this.w), this;
  }
  /**
   * The components of this vector are rounded up to the nearest integer value.
   *
   * @return {Vector4} A reference to this vector.
   */
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this.w = Math.ceil(this.w), this;
  }
  /**
   * The components of this vector are rounded to the nearest integer value
   *
   * @return {Vector4} A reference to this vector.
   */
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this.w = Math.round(this.w), this;
  }
  /**
   * The components of this vector are rounded towards zero (up if negative,
   * down if positive) to an integer value.
   *
   * @return {Vector4} A reference to this vector.
   */
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this.w = Math.trunc(this.w), this;
  }
  /**
   * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
   *
   * @return {Vector4} A reference to this vector.
   */
  negate() {
    return this.x = -this.x, this.y = -this.y, this.z = -this.z, this.w = -this.w, this;
  }
  /**
   * Calculates the dot product of the given vector with this instance.
   *
   * @param {Vector4} v - The vector to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(t) {
    return this.x * t.x + this.y * t.y + this.z * t.z + this.w * t.w;
  }
  /**
   * Computes the square of the Euclidean length (straight-line length) from
   * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
   * compare the length squared instead as it is slightly more efficient to calculate.
   *
   * @return {number} The square length of this vector.
   */
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  }
  /**
   * Computes the  Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
   *
   * @return {number} The length of this vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  }
  /**
   * Computes the Manhattan length of this vector.
   *
   * @return {number} The length of this vector.
   */
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  }
  /**
   * Converts this vector to a unit vector - that is, sets it equal to a vector
   * with the same direction as this one, but with a vector length of `1`.
   *
   * @return {Vector4} A reference to this vector.
   */
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  /**
   * Sets this vector to a vector with the same direction as this one, but
   * with the specified length.
   *
   * @param {number} length - The new length of this vector.
   * @return {Vector4} A reference to this vector.
   */
  setLength(t) {
    return this.normalize().multiplyScalar(t);
  }
  /**
   * Linearly interpolates between the given vector and this instance, where
   * alpha is the percent distance along the line - alpha = 0 will be this
   * vector, and alpha = 1 will be the given one.
   *
   * @param {Vector4} v - The vector to interpolate towards.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector4} A reference to this vector.
   */
  lerp(t, e) {
    return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this.z += (t.z - this.z) * e, this.w += (t.w - this.w) * e, this;
  }
  /**
   * Linearly interpolates between the given vectors, where alpha is the percent
   * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
   * be the second one. The result is stored in this instance.
   *
   * @param {Vector4} v1 - The first vector.
   * @param {Vector4} v2 - The second vector.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector4} A reference to this vector.
   */
  lerpVectors(t, e, i) {
    return this.x = t.x + (e.x - t.x) * i, this.y = t.y + (e.y - t.y) * i, this.z = t.z + (e.z - t.z) * i, this.w = t.w + (e.w - t.w) * i, this;
  }
  /**
   * Returns `true` if this vector is equal with the given one.
   *
   * @param {Vector4} v - The vector to test for equality.
   * @return {boolean} Whether this vector is equal with the given one.
   */
  equals(t) {
    return t.x === this.x && t.y === this.y && t.z === this.z && t.w === this.w;
  }
  /**
   * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
   * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
   *
   * @param {Array<number>} array - An array holding the vector component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Vector4} A reference to this vector.
   */
  fromArray(t, e = 0) {
    return this.x = t[e], this.y = t[e + 1], this.z = t[e + 2], this.w = t[e + 3], this;
  }
  /**
   * Writes the components of this vector to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the vector components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The vector components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this.x, t[e + 1] = this.y, t[e + 2] = this.z, t[e + 3] = this.w, t;
  }
  /**
   * Sets the components of this vector from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
   * @param {number} index - The index into the attribute.
   * @return {Vector4} A reference to this vector.
   */
  fromBufferAttribute(t, e) {
    return this.x = t.getX(e), this.y = t.getY(e), this.z = t.getZ(e), this.w = t.getW(e), this;
  }
  /**
   * Sets each component of this vector to a pseudo-random value between `0` and
   * `1`, excluding `1`.
   *
   * @return {Vector4} A reference to this vector.
   */
  random() {
    return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this.w = Math.random(), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y, yield this.z, yield this.w;
  }
};
class Bp extends Ei {
  /**
   * Render target options.
   *
   * @typedef {Object} RenderTarget~Options
   * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
   * @property {number} [magFilter=LinearFilter] - The mag filter.
   * @property {number} [minFilter=LinearFilter] - The min filter.
   * @property {number} [format=RGBAFormat] - The texture format.
   * @property {number} [type=UnsignedByteType] - The texture type.
   * @property {?string} [internalFormat=null] - The texture's internal format.
   * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
   * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
   * @property {number} [anisotropy=1] - The texture's anisotropy value.
   * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
   * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
   * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
   * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
   * @property {boolean} [resolveStencilBuffer=true] - Whether  to resolve the stencil buffer or not.
   * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
   * @property {number} [samples=0] - The MSAA samples count.
   * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
   * @property {number} [depth=1] - The texture depth.
   * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
   */
  /**
   * Constructs a new render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(t = 1, e = 1, i = {}) {
    super(), i = Object.assign({
      generateMipmaps: !1,
      internalFormat: null,
      minFilter: Ce,
      depthBuffer: !0,
      stencilBuffer: !1,
      resolveDepthBuffer: !0,
      resolveStencilBuffer: !0,
      depthTexture: null,
      samples: 0,
      count: 1,
      depth: 1,
      multiview: !1
    }, i), this.isRenderTarget = !0, this.width = t, this.height = e, this.depth = i.depth, this.scissor = new Qt(0, 0, t, e), this.scissorTest = !1, this.viewport = new Qt(0, 0, t, e);
    const n = { width: t, height: e, depth: i.depth }, s = new Ne(n);
    this.textures = [];
    const r = i.count;
    for (let o = 0; o < r; o++)
      this.textures[o] = s.clone(), this.textures[o].isRenderTargetTexture = !0, this.textures[o].renderTarget = this;
    this._setTextureOptions(i), this.depthBuffer = i.depthBuffer, this.stencilBuffer = i.stencilBuffer, this.resolveDepthBuffer = i.resolveDepthBuffer, this.resolveStencilBuffer = i.resolveStencilBuffer, this._depthTexture = null, this.depthTexture = i.depthTexture, this.samples = i.samples, this.multiview = i.multiview;
  }
  _setTextureOptions(t = {}) {
    const e = {
      minFilter: Ce,
      generateMipmaps: !1,
      flipY: !1,
      internalFormat: null
    };
    t.mapping !== void 0 && (e.mapping = t.mapping), t.wrapS !== void 0 && (e.wrapS = t.wrapS), t.wrapT !== void 0 && (e.wrapT = t.wrapT), t.wrapR !== void 0 && (e.wrapR = t.wrapR), t.magFilter !== void 0 && (e.magFilter = t.magFilter), t.minFilter !== void 0 && (e.minFilter = t.minFilter), t.format !== void 0 && (e.format = t.format), t.type !== void 0 && (e.type = t.type), t.anisotropy !== void 0 && (e.anisotropy = t.anisotropy), t.colorSpace !== void 0 && (e.colorSpace = t.colorSpace), t.flipY !== void 0 && (e.flipY = t.flipY), t.generateMipmaps !== void 0 && (e.generateMipmaps = t.generateMipmaps), t.internalFormat !== void 0 && (e.internalFormat = t.internalFormat);
    for (let i = 0; i < this.textures.length; i++)
      this.textures[i].setValues(e);
  }
  /**
   * The texture representing the default color attachment.
   *
   * @type {Texture}
   */
  get texture() {
    return this.textures[0];
  }
  set texture(t) {
    this.textures[0] = t;
  }
  set depthTexture(t) {
    this._depthTexture !== null && (this._depthTexture.renderTarget = null), t !== null && (t.renderTarget = this), this._depthTexture = t;
  }
  /**
   * Instead of saving the depth in a renderbuffer, a texture
   * can be used instead which is useful for further processing
   * e.g. in context of post-processing.
   *
   * @type {?DepthTexture}
   * @default null
   */
  get depthTexture() {
    return this._depthTexture;
  }
  /**
   * Sets the size of this render target.
   *
   * @param {number} width - The width.
   * @param {number} height - The height.
   * @param {number} [depth=1] - The depth.
   */
  setSize(t, e, i = 1) {
    if (this.width !== t || this.height !== e || this.depth !== i) {
      this.width = t, this.height = e, this.depth = i;
      for (let n = 0, s = this.textures.length; n < s; n++)
        this.textures[n].image.width = t, this.textures[n].image.height = e, this.textures[n].image.depth = i, this.textures[n].isArrayTexture = this.textures[n].image.depth > 1;
      this.dispose();
    }
    this.viewport.set(0, 0, t, e), this.scissor.set(0, 0, t, e);
  }
  /**
   * Returns a new render target with copied values from this instance.
   *
   * @return {RenderTarget} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the settings of the given render target. This is a structural copy so
   * no resources are shared between render targets after the copy. That includes
   * all MRT textures and the depth texture.
   *
   * @param {RenderTarget} source - The render target to copy.
   * @return {RenderTarget} A reference to this instance.
   */
  copy(t) {
    this.width = t.width, this.height = t.height, this.depth = t.depth, this.scissor.copy(t.scissor), this.scissorTest = t.scissorTest, this.viewport.copy(t.viewport), this.textures.length = 0;
    for (let e = 0, i = t.textures.length; e < i; e++) {
      this.textures[e] = t.textures[e].clone(), this.textures[e].isRenderTargetTexture = !0, this.textures[e].renderTarget = this;
      const n = Object.assign({}, t.textures[e].image);
      this.textures[e].source = new Ms(n);
    }
    return this.depthBuffer = t.depthBuffer, this.stencilBuffer = t.stencilBuffer, this.resolveDepthBuffer = t.resolveDepthBuffer, this.resolveStencilBuffer = t.resolveStencilBuffer, t.depthTexture !== null && (this.depthTexture = t.depthTexture.clone()), this.samples = t.samples, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires RenderTarget#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
}
class Rn extends Bp {
  /**
   * Constructs a new 3D render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(t = 1, e = 1, i = {}) {
    super(t, e, i), this.isWebGLRenderTarget = !0;
  }
}
class Bc extends Ne {
  /**
   * Constructs a new data array texture.
   *
   * @param {?TypedArray} [data=null] - The buffer data.
   * @param {number} [width=1] - The width of the texture.
   * @param {number} [height=1] - The height of the texture.
   * @param {number} [depth=1] - The depth of the texture.
   */
  constructor(t = null, e = 1, i = 1, n = 1) {
    super(null), this.isDataArrayTexture = !0, this.image = { data: t, width: e, height: i, depth: n }, this.magFilter = je, this.minFilter = je, this.wrapR = Si, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1, this.layerUpdates = /* @__PURE__ */ new Set();
  }
  /**
   * Describes that a specific layer of the texture needs to be updated.
   * Normally when {@link Texture#needsUpdate} is set to `true`, the
   * entire data texture array is sent to the GPU. Marking specific
   * layers will only transmit subsets of all mipmaps associated with a
   * specific depth in the array which is often much more performant.
   *
   * @param {number} layerIndex - The layer index that should be updated.
   */
  addLayerUpdate(t) {
    this.layerUpdates.add(t);
  }
  /**
   * Resets the layer updates registry.
   */
  clearLayerUpdates() {
    this.layerUpdates.clear();
  }
}
class yv extends Rn {
  /**
   * Constructs a new array render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {number} [depth=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(t = 1, e = 1, i = 1, n = {}) {
    super(t, e, n), this.isWebGLArrayRenderTarget = !0, this.depth = i, this.texture = new Bc(null, t, e, i), this._setTextureOptions(n), this.texture.isRenderTargetTexture = !0;
  }
}
class zc extends Ne {
  /**
   * Constructs a new data array texture.
   *
   * @param {?TypedArray} [data=null] - The buffer data.
   * @param {number} [width=1] - The width of the texture.
   * @param {number} [height=1] - The height of the texture.
   * @param {number} [depth=1] - The depth of the texture.
   */
  constructor(t = null, e = 1, i = 1, n = 1) {
    super(null), this.isData3DTexture = !0, this.image = { data: t, width: e, height: i, depth: n }, this.magFilter = je, this.minFilter = je, this.wrapR = Si, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
  }
}
class _v extends Rn {
  /**
   * Constructs a new 3D render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {number} [depth=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(t = 1, e = 1, i = 1, n = {}) {
    super(t, e, n), this.isWebGL3DRenderTarget = !0, this.depth = i, this.texture = new zc(null, t, e, i), this._setTextureOptions(n), this.texture.isRenderTargetTexture = !0;
  }
}
let we = class {
  /**
   * Constructs a new bounding box.
   *
   * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
   * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
   */
  constructor(t = new E(1 / 0, 1 / 0, 1 / 0), e = new E(-1 / 0, -1 / 0, -1 / 0)) {
    this.isBox3 = !0, this.min = t, this.max = e;
  }
  /**
   * Sets the lower and upper boundaries of this box.
   * Please note that this method only copies the values from the given objects.
   *
   * @param {Vector3} min - The lower boundary of the box.
   * @param {Vector3} max - The upper boundary of the box.
   * @return {Box3} A reference to this bounding box.
   */
  set(t, e) {
    return this.min.copy(t), this.max.copy(e), this;
  }
  /**
   * Sets the upper and lower bounds of this box so it encloses the position data
   * in the given array.
   *
   * @param {Array<number>} array - An array holding 3D position data.
   * @return {Box3} A reference to this bounding box.
   */
  setFromArray(t) {
    this.makeEmpty();
    for (let e = 0, i = t.length; e < i; e += 3)
      this.expandByPoint(Zi.fromArray(t, e));
    return this;
  }
  /**
   * Sets the upper and lower bounds of this box so it encloses the position data
   * in the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
   * @return {Box3} A reference to this bounding box.
   */
  setFromBufferAttribute(t) {
    this.makeEmpty();
    for (let e = 0, i = t.count; e < i; e++)
      this.expandByPoint(Zi.fromBufferAttribute(t, e));
    return this;
  }
  /**
   * Sets the upper and lower bounds of this box so it encloses the position data
   * in the given array.
   *
   * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
   * @return {Box3} A reference to this bounding box.
   */
  setFromPoints(t) {
    this.makeEmpty();
    for (let e = 0, i = t.length; e < i; e++)
      this.expandByPoint(t[e]);
    return this;
  }
  /**
   * Centers this box on the given center vector and sets this box's width, height and
   * depth to the given size values.
   *
   * @param {Vector3} center - The center of the box.
   * @param {Vector3} size - The x, y and z dimensions of the box.
   * @return {Box3} A reference to this bounding box.
   */
  setFromCenterAndSize(t, e) {
    const i = Zi.copy(e).multiplyScalar(0.5);
    return this.min.copy(t).sub(i), this.max.copy(t).add(i), this;
  }
  /**
   * Computes the world-axis-aligned bounding box for the given 3D object
   * (including its children), accounting for the object's, and children's,
   * world transforms. The function may result in a larger box than strictly necessary.
   *
   * @param {Object3D} object - The 3D object to compute the bounding box for.
   * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
   * world-axis-aligned bounding box at the expense of more computation.
   * @return {Box3} A reference to this bounding box.
   */
  setFromObject(t, e = !1) {
    return this.makeEmpty(), this.expandByObject(t, e);
  }
  /**
   * Returns a new box with copied values from this instance.
   *
   * @return {Box3} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given box to this instance.
   *
   * @param {Box3} box - The box to copy.
   * @return {Box3} A reference to this bounding box.
   */
  copy(t) {
    return this.min.copy(t.min), this.max.copy(t.max), this;
  }
  /**
   * Makes this box empty which means in encloses a zero space in 3D.
   *
   * @return {Box3} A reference to this bounding box.
   */
  makeEmpty() {
    return this.min.x = this.min.y = this.min.z = 1 / 0, this.max.x = this.max.y = this.max.z = -1 / 0, this;
  }
  /**
   * Returns true if this box includes zero points within its bounds.
   * Note that a box with equal lower and upper bounds still includes one
   * point, the one both bounds share.
   *
   * @return {boolean} Whether this box is empty or not.
   */
  isEmpty() {
    return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  }
  /**
   * Returns the center point of this box.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The center point.
   */
  getCenter(t) {
    return this.isEmpty() ? t.set(0, 0, 0) : t.addVectors(this.min, this.max).multiplyScalar(0.5);
  }
  /**
   * Returns the dimensions of this box.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The size.
   */
  getSize(t) {
    return this.isEmpty() ? t.set(0, 0, 0) : t.subVectors(this.max, this.min);
  }
  /**
   * Expands the boundaries of this box to include the given point.
   *
   * @param {Vector3} point - The point that should be included by the bounding box.
   * @return {Box3} A reference to this bounding box.
   */
  expandByPoint(t) {
    return this.min.min(t), this.max.max(t), this;
  }
  /**
   * Expands this box equilaterally by the given vector. The width of this
   * box will be expanded by the x component of the vector in both
   * directions. The height of this box will be expanded by the y component of
   * the vector in both directions. The depth of this box will be
   * expanded by the z component of the vector in both directions.
   *
   * @param {Vector3} vector - The vector that should expand the bounding box.
   * @return {Box3} A reference to this bounding box.
   */
  expandByVector(t) {
    return this.min.sub(t), this.max.add(t), this;
  }
  /**
   * Expands each dimension of the box by the given scalar. If negative, the
   * dimensions of the box will be contracted.
   *
   * @param {number} scalar - The scalar value that should expand the bounding box.
   * @return {Box3} A reference to this bounding box.
   */
  expandByScalar(t) {
    return this.min.addScalar(-t), this.max.addScalar(t), this;
  }
  /**
   * Expands the boundaries of this box to include the given 3D object and
   * its children, accounting for the object's, and children's, world
   * transforms. The function may result in a larger box than strictly
   * necessary (unless the precise parameter is set to true).
   *
   * @param {Object3D} object - The 3D object that should expand the bounding box.
   * @param {boolean} precise - If set to `true`, the method expands the bounding box
   * as little as necessary at the expense of more computation.
   * @return {Box3} A reference to this bounding box.
   */
  expandByObject(t, e = !1) {
    t.updateWorldMatrix(!1, !1);
    const i = t.geometry;
    if (i !== void 0) {
      const s = i.getAttribute("position");
      if (e === !0 && s !== void 0 && t.isInstancedMesh !== !0)
        for (let r = 0, o = s.count; r < o; r++)
          t.isMesh === !0 ? t.getVertexPosition(r, Zi) : Zi.fromBufferAttribute(s, r), Zi.applyMatrix4(t.matrixWorld), this.expandByPoint(Zi);
      else
        t.boundingBox !== void 0 ? (t.boundingBox === null && t.computeBoundingBox(), Zo.copy(t.boundingBox)) : (i.boundingBox === null && i.computeBoundingBox(), Zo.copy(i.boundingBox)), Zo.applyMatrix4(t.matrixWorld), this.union(Zo);
    }
    const n = t.children;
    for (let s = 0, r = n.length; s < r; s++)
      this.expandByObject(n[s], e);
    return this;
  }
  /**
   * Returns `true` if the given point lies within or on the boundaries of this box.
   *
   * @param {Vector3} point - The point to test.
   * @return {boolean} Whether the bounding box contains the given point or not.
   */
  containsPoint(t) {
    return t.x >= this.min.x && t.x <= this.max.x && t.y >= this.min.y && t.y <= this.max.y && t.z >= this.min.z && t.z <= this.max.z;
  }
  /**
   * Returns `true` if this bounding box includes the entirety of the given bounding box.
   * If this box and the given one are identical, this function also returns `true`.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the bounding box contains the given bounding box or not.
   */
  containsBox(t) {
    return this.min.x <= t.min.x && t.max.x <= this.max.x && this.min.y <= t.min.y && t.max.y <= this.max.y && this.min.z <= t.min.z && t.max.z <= this.max.z;
  }
  /**
   * Returns a point as a proportion of this box's width, height and depth.
   *
   * @param {Vector3} point - A point in 3D space.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} A point as a proportion of this box's width, height and depth.
   */
  getParameter(t, e) {
    return e.set(
      (t.x - this.min.x) / (this.max.x - this.min.x),
      (t.y - this.min.y) / (this.max.y - this.min.y),
      (t.z - this.min.z) / (this.max.z - this.min.z)
    );
  }
  /**
   * Returns `true` if the given bounding box intersects with this bounding box.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the given bounding box intersects with this bounding box.
   */
  intersectsBox(t) {
    return t.max.x >= this.min.x && t.min.x <= this.max.x && t.max.y >= this.min.y && t.min.y <= this.max.y && t.max.z >= this.min.z && t.min.z <= this.max.z;
  }
  /**
   * Returns `true` if the given bounding sphere intersects with this bounding box.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
   */
  intersectsSphere(t) {
    return this.clampPoint(t.center, Zi), Zi.distanceToSquared(t.center) <= t.radius * t.radius;
  }
  /**
   * Returns `true` if the given plane intersects with this bounding box.
   *
   * @param {Plane} plane - The plane to test.
   * @return {boolean} Whether the given plane intersects with this bounding box.
   */
  intersectsPlane(t) {
    let e, i;
    return t.normal.x > 0 ? (e = t.normal.x * this.min.x, i = t.normal.x * this.max.x) : (e = t.normal.x * this.max.x, i = t.normal.x * this.min.x), t.normal.y > 0 ? (e += t.normal.y * this.min.y, i += t.normal.y * this.max.y) : (e += t.normal.y * this.max.y, i += t.normal.y * this.min.y), t.normal.z > 0 ? (e += t.normal.z * this.min.z, i += t.normal.z * this.max.z) : (e += t.normal.z * this.max.z, i += t.normal.z * this.min.z), e <= -t.constant && i >= -t.constant;
  }
  /**
   * Returns `true` if the given triangle intersects with this bounding box.
   *
   * @param {Triangle} triangle - The triangle to test.
   * @return {boolean} Whether the given triangle intersects with this bounding box.
   */
  intersectsTriangle(t) {
    if (this.isEmpty())
      return !1;
    this.getCenter(Ba), jo.subVectors(this.max, Ba), br.subVectors(t.a, Ba), Mr.subVectors(t.b, Ba), Sr.subVectors(t.c, Ba), rs.subVectors(Mr, br), as.subVectors(Sr, Mr), Ns.subVectors(br, Sr);
    let e = [
      0,
      -rs.z,
      rs.y,
      0,
      -as.z,
      as.y,
      0,
      -Ns.z,
      Ns.y,
      rs.z,
      0,
      -rs.x,
      as.z,
      0,
      -as.x,
      Ns.z,
      0,
      -Ns.x,
      -rs.y,
      rs.x,
      0,
      -as.y,
      as.x,
      0,
      -Ns.y,
      Ns.x,
      0
    ];
    return !bu(e, br, Mr, Sr, jo) || (e = [1, 0, 0, 0, 1, 0, 0, 0, 1], !bu(e, br, Mr, Sr, jo)) ? !1 : (Jo.crossVectors(rs, as), e = [Jo.x, Jo.y, Jo.z], bu(e, br, Mr, Sr, jo));
  }
  /**
   * Clamps the given point within the bounds of this box.
   *
   * @param {Vector3} point - The point to clamp.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The clamped point.
   */
  clampPoint(t, e) {
    return e.copy(t).clamp(this.min, this.max);
  }
  /**
   * Returns the euclidean distance from any edge of this box to the specified point. If
   * the given point lies inside of this box, the distance will be `0`.
   *
   * @param {Vector3} point - The point to compute the distance to.
   * @return {number} The euclidean distance.
   */
  distanceToPoint(t) {
    return this.clampPoint(t, Zi).distanceTo(t);
  }
  /**
   * Returns a bounding sphere that encloses this bounding box.
   *
   * @param {Sphere} target - The target sphere that is used to store the method's result.
   * @return {Sphere} The bounding sphere that encloses this bounding box.
   */
  getBoundingSphere(t) {
    return this.isEmpty() ? t.makeEmpty() : (this.getCenter(t.center), t.radius = this.getSize(Zi).length() * 0.5), t;
  }
  /**
   * Computes the intersection of this bounding box and the given one, setting the upper
   * bound of this box to the lesser of the two boxes' upper bounds and the
   * lower bound of this box to the greater of the two boxes' lower bounds. If
   * there's no overlap, makes this box empty.
   *
   * @param {Box3} box - The bounding box to intersect with.
   * @return {Box3} A reference to this bounding box.
   */
  intersect(t) {
    return this.min.max(t.min), this.max.min(t.max), this.isEmpty() && this.makeEmpty(), this;
  }
  /**
   * Computes the union of this box and another and the given one, setting the upper
   * bound of this box to the greater of the two boxes' upper bounds and the
   * lower bound of this box to the lesser of the two boxes' lower bounds.
   *
   * @param {Box3} box - The bounding box that will be unioned with this instance.
   * @return {Box3} A reference to this bounding box.
   */
  union(t) {
    return this.min.min(t.min), this.max.max(t.max), this;
  }
  /**
   * Transforms this bounding box by the given 4x4 transformation matrix.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   * @return {Box3} A reference to this bounding box.
   */
  applyMatrix4(t) {
    return this.isEmpty() ? this : (Ln[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(t), Ln[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(t), Ln[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(t), Ln[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(t), Ln[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(t), Ln[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(t), Ln[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(t), Ln[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(t), this.setFromPoints(Ln), this);
  }
  /**
   * Adds the given offset to both the upper and lower bounds of this bounding box,
   * effectively moving it in 3D space.
   *
   * @param {Vector3} offset - The offset that should be used to translate the bounding box.
   * @return {Box3} A reference to this bounding box.
   */
  translate(t) {
    return this.min.add(t), this.max.add(t), this;
  }
  /**
   * Returns `true` if this bounding box is equal with the given one.
   *
   * @param {Box3} box - The box to test for equality.
   * @return {boolean} Whether this bounding box is equal with the given one.
   */
  equals(t) {
    return t.min.equals(this.min) && t.max.equals(this.max);
  }
  /**
   * Returns a serialized structure of the bounding box.
   *
   * @return {Object} Serialized structure with fields representing the object state.
   */
  toJSON() {
    return {
      min: this.min.toArray(),
      max: this.max.toArray()
    };
  }
  /**
   * Returns a serialized structure of the bounding box.
   *
   * @param {Object} json - The serialized json to set the box from.
   * @return {Box3} A reference to this bounding box.
   */
  fromJSON(t) {
    return this.min.fromArray(t.min), this.max.fromArray(t.max), this;
  }
};
const Ln = [
  /* @__PURE__ */ new E(),
  /* @__PURE__ */ new E(),
  /* @__PURE__ */ new E(),
  /* @__PURE__ */ new E(),
  /* @__PURE__ */ new E(),
  /* @__PURE__ */ new E(),
  /* @__PURE__ */ new E(),
  /* @__PURE__ */ new E()
], Zi = /* @__PURE__ */ new E(), Zo = /* @__PURE__ */ new we(), br = /* @__PURE__ */ new E(), Mr = /* @__PURE__ */ new E(), Sr = /* @__PURE__ */ new E(), rs = /* @__PURE__ */ new E(), as = /* @__PURE__ */ new E(), Ns = /* @__PURE__ */ new E(), Ba = /* @__PURE__ */ new E(), jo = /* @__PURE__ */ new E(), Jo = /* @__PURE__ */ new E(), Os = /* @__PURE__ */ new E();
function bu(a, t, e, i, n) {
  for (let s = 0, r = a.length - 3; s <= r; s += 3) {
    Os.fromArray(a, s);
    const o = n.x * Math.abs(Os.x) + n.y * Math.abs(Os.y) + n.z * Math.abs(Os.z), l = t.dot(Os), h = e.dot(Os), c = i.dot(Os);
    if (Math.max(-Math.max(l, h, c), Math.min(l, h, c)) > o)
      return !1;
  }
  return !0;
}
const xv = /* @__PURE__ */ new we(), za = /* @__PURE__ */ new E(), Mu = /* @__PURE__ */ new E();
let Re = class {
  /**
   * Constructs a new sphere.
   *
   * @param {Vector3} [center=(0,0,0)] - The center of the sphere
   * @param {number} [radius=-1] - The radius of the sphere.
   */
  constructor(t = new E(), e = -1) {
    this.isSphere = !0, this.center = t, this.radius = e;
  }
  /**
   * Sets the sphere's components by copying the given values.
   *
   * @param {Vector3} center - The center.
   * @param {number} radius - The radius.
   * @return {Sphere} A reference to this sphere.
   */
  set(t, e) {
    return this.center.copy(t), this.radius = e, this;
  }
  /**
   * Computes the minimum bounding sphere for list of points.
   * If the optional center point is given, it is used as the sphere's
   * center. Otherwise, the center of the axis-aligned bounding box
   * encompassing the points is calculated.
   *
   * @param {Array<Vector3>} points - A list of points in 3D space.
   * @param {Vector3} [optionalCenter] - The center of the sphere.
   * @return {Sphere} A reference to this sphere.
   */
  setFromPoints(t, e) {
    const i = this.center;
    e !== void 0 ? i.copy(e) : xv.setFromPoints(t).getCenter(i);
    let n = 0;
    for (let s = 0, r = t.length; s < r; s++)
      n = Math.max(n, i.distanceToSquared(t[s]));
    return this.radius = Math.sqrt(n), this;
  }
  /**
   * Copies the values of the given sphere to this instance.
   *
   * @param {Sphere} sphere - The sphere to copy.
   * @return {Sphere} A reference to this sphere.
   */
  copy(t) {
    return this.center.copy(t.center), this.radius = t.radius, this;
  }
  /**
   * Returns `true` if the sphere is empty (the radius set to a negative number).
   *
   * Spheres with a radius of `0` contain only their center point and are not
   * considered to be empty.
   *
   * @return {boolean} Whether this sphere is empty or not.
   */
  isEmpty() {
    return this.radius < 0;
  }
  /**
   * Makes this sphere empty which means in encloses a zero space in 3D.
   *
   * @return {Sphere} A reference to this sphere.
   */
  makeEmpty() {
    return this.center.set(0, 0, 0), this.radius = -1, this;
  }
  /**
   * Returns `true` if this sphere contains the given point inclusive of
   * the surface of the sphere.
   *
   * @param {Vector3} point - The point to check.
   * @return {boolean} Whether this sphere contains the given point or not.
   */
  containsPoint(t) {
    return t.distanceToSquared(this.center) <= this.radius * this.radius;
  }
  /**
   * Returns the closest distance from the boundary of the sphere to the
   * given point. If the sphere contains the point, the distance will
   * be negative.
   *
   * @param {Vector3} point - The point to compute the distance to.
   * @return {number} The distance to the point.
   */
  distanceToPoint(t) {
    return t.distanceTo(this.center) - this.radius;
  }
  /**
   * Returns `true` if this sphere intersects with the given one.
   *
   * @param {Sphere} sphere - The sphere to test.
   * @return {boolean} Whether this sphere intersects with the given one or not.
   */
  intersectsSphere(t) {
    const e = this.radius + t.radius;
    return t.center.distanceToSquared(this.center) <= e * e;
  }
  /**
   * Returns `true` if this sphere intersects with the given box.
   *
   * @param {Box3} box - The box to test.
   * @return {boolean} Whether this sphere intersects with the given box or not.
   */
  intersectsBox(t) {
    return t.intersectsSphere(this);
  }
  /**
   * Returns `true` if this sphere intersects with the given plane.
   *
   * @param {Plane} plane - The plane to test.
   * @return {boolean} Whether this sphere intersects with the given plane or not.
   */
  intersectsPlane(t) {
    return Math.abs(t.distanceToPoint(this.center)) <= this.radius;
  }
  /**
   * Clamps a point within the sphere. If the point is outside the sphere, it
   * will clamp it to the closest point on the edge of the sphere. Points
   * already inside the sphere will not be affected.
   *
   * @param {Vector3} point - The plane to clamp.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The clamped point.
   */
  clampPoint(t, e) {
    const i = this.center.distanceToSquared(t);
    return e.copy(t), i > this.radius * this.radius && (e.sub(this.center).normalize(), e.multiplyScalar(this.radius).add(this.center)), e;
  }
  /**
   * Returns a bounding box that encloses this sphere.
   *
   * @param {Box3} target - The target box that is used to store the method's result.
   * @return {Box3} The bounding box that encloses this sphere.
   */
  getBoundingBox(t) {
    return this.isEmpty() ? (t.makeEmpty(), t) : (t.set(this.center, this.center), t.expandByScalar(this.radius), t);
  }
  /**
   * Transforms this sphere with the given 4x4 transformation matrix.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   * @return {Sphere} A reference to this sphere.
   */
  applyMatrix4(t) {
    return this.center.applyMatrix4(t), this.radius = this.radius * t.getMaxScaleOnAxis(), this;
  }
  /**
   * Translates the sphere's center by the given offset.
   *
   * @param {Vector3} offset - The offset.
   * @return {Sphere} A reference to this sphere.
   */
  translate(t) {
    return this.center.add(t), this;
  }
  /**
   * Expands the boundaries of this sphere to include the given point.
   *
   * @param {Vector3} point - The point to include.
   * @return {Sphere} A reference to this sphere.
   */
  expandByPoint(t) {
    if (this.isEmpty())
      return this.center.copy(t), this.radius = 0, this;
    za.subVectors(t, this.center);
    const e = za.lengthSq();
    if (e > this.radius * this.radius) {
      const i = Math.sqrt(e), n = (i - this.radius) * 0.5;
      this.center.addScaledVector(za, n / i), this.radius += n;
    }
    return this;
  }
  /**
   * Expands this sphere to enclose both the original sphere and the given sphere.
   *
   * @param {Sphere} sphere - The sphere to include.
   * @return {Sphere} A reference to this sphere.
   */
  union(t) {
    return t.isEmpty() ? this : this.isEmpty() ? (this.copy(t), this) : (this.center.equals(t.center) === !0 ? this.radius = Math.max(this.radius, t.radius) : (Mu.subVectors(t.center, this.center).setLength(t.radius), this.expandByPoint(za.copy(t.center).add(Mu)), this.expandByPoint(za.copy(t.center).sub(Mu))), this);
  }
  /**
   * Returns `true` if this sphere is equal with the given one.
   *
   * @param {Sphere} sphere - The sphere to test for equality.
   * @return {boolean} Whether this bounding sphere is equal with the given one.
   */
  equals(t) {
    return t.center.equals(this.center) && t.radius === this.radius;
  }
  /**
   * Returns a new sphere with copied values from this instance.
   *
   * @return {Sphere} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Returns a serialized structure of the bounding sphere.
   *
   * @return {Object} Serialized structure with fields representing the object state.
   */
  toJSON() {
    return {
      radius: this.radius,
      center: this.center.toArray()
    };
  }
  /**
   * Returns a serialized structure of the bounding sphere.
   *
   * @param {Object} json - The serialized json to set the sphere from.
   * @return {Box3} A reference to this bounding sphere.
   */
  fromJSON(t) {
    return this.radius = t.radius, this.center.fromArray(t.center), this;
  }
};
const Dn = /* @__PURE__ */ new E(), Su = /* @__PURE__ */ new E(), Ko = /* @__PURE__ */ new E(), os = /* @__PURE__ */ new E(), wu = /* @__PURE__ */ new E(), Qo = /* @__PURE__ */ new E(), Au = /* @__PURE__ */ new E();
let Aa = class {
  /**
   * Constructs a new ray.
   *
   * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
   * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
   */
  constructor(t = new E(), e = new E(0, 0, -1)) {
    this.origin = t, this.direction = e;
  }
  /**
   * Sets the ray's components by copying the given values.
   *
   * @param {Vector3} origin - The origin.
   * @param {Vector3} direction - The direction.
   * @return {Ray} A reference to this ray.
   */
  set(t, e) {
    return this.origin.copy(t), this.direction.copy(e), this;
  }
  /**
   * Copies the values of the given ray to this instance.
   *
   * @param {Ray} ray - The ray to copy.
   * @return {Ray} A reference to this ray.
   */
  copy(t) {
    return this.origin.copy(t.origin), this.direction.copy(t.direction), this;
  }
  /**
   * Returns a vector that is located at a given distance along this ray.
   *
   * @param {number} t - The distance along the ray to retrieve a position for.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} A position on the ray.
   */
  at(t, e) {
    return e.copy(this.origin).addScaledVector(this.direction, t);
  }
  /**
   * Adjusts the direction of the ray to point at the given vector in world space.
   *
   * @param {Vector3} v - The target position.
   * @return {Ray} A reference to this ray.
   */
  lookAt(t) {
    return this.direction.copy(t).sub(this.origin).normalize(), this;
  }
  /**
   * Shift the origin of this ray along its direction by the given distance.
   *
   * @param {number} t - The distance along the ray to interpolate.
   * @return {Ray} A reference to this ray.
   */
  recast(t) {
    return this.origin.copy(this.at(t, Dn)), this;
  }
  /**
   * Returns the point along this ray that is closest to the given point.
   *
   * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The closest point on this ray.
   */
  closestPointToPoint(t, e) {
    e.subVectors(t, this.origin);
    const i = e.dot(this.direction);
    return i < 0 ? e.copy(this.origin) : e.copy(this.origin).addScaledVector(this.direction, i);
  }
  /**
   * Returns the distance of the closest approach between this ray and the given point.
   *
   * @param {Vector3} point - A point in 3D space to compute the distance to.
   * @return {number} The distance.
   */
  distanceToPoint(t) {
    return Math.sqrt(this.distanceSqToPoint(t));
  }
  /**
   * Returns the squared distance of the closest approach between this ray and the given point.
   *
   * @param {Vector3} point - A point in 3D space to compute the distance to.
   * @return {number} The squared distance.
   */
  distanceSqToPoint(t) {
    const e = Dn.subVectors(t, this.origin).dot(this.direction);
    return e < 0 ? this.origin.distanceToSquared(t) : (Dn.copy(this.origin).addScaledVector(this.direction, e), Dn.distanceToSquared(t));
  }
  /**
   * Returns the squared distance between this ray and the given line segment.
   *
   * @param {Vector3} v0 - The start point of the line segment.
   * @param {Vector3} v1 - The end point of the line segment.
   * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
   * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
   * @return {number} The squared distance.
   */
  distanceSqToSegment(t, e, i, n) {
    Su.copy(t).add(e).multiplyScalar(0.5), Ko.copy(e).sub(t).normalize(), os.copy(this.origin).sub(Su);
    const s = t.distanceTo(e) * 0.5, r = -this.direction.dot(Ko), o = os.dot(this.direction), l = -os.dot(Ko), h = os.lengthSq(), c = Math.abs(1 - r * r);
    let u, d, p, f;
    if (c > 0)
      if (u = r * l - o, d = r * o - l, f = s * c, u >= 0)
        if (d >= -f)
          if (d <= f) {
            const y = 1 / c;
            u *= y, d *= y, p = u * (u + r * d + 2 * o) + d * (r * u + d + 2 * l) + h;
          } else
            d = s, u = Math.max(0, -(r * d + o)), p = -u * u + d * (d + 2 * l) + h;
        else
          d = -s, u = Math.max(0, -(r * d + o)), p = -u * u + d * (d + 2 * l) + h;
      else
        d <= -f ? (u = Math.max(0, -(-r * s + o)), d = u > 0 ? -s : Math.min(Math.max(-s, -l), s), p = -u * u + d * (d + 2 * l) + h) : d <= f ? (u = 0, d = Math.min(Math.max(-s, -l), s), p = d * (d + 2 * l) + h) : (u = Math.max(0, -(r * s + o)), d = u > 0 ? s : Math.min(Math.max(-s, -l), s), p = -u * u + d * (d + 2 * l) + h);
    else
      d = r > 0 ? -s : s, u = Math.max(0, -(r * d + o)), p = -u * u + d * (d + 2 * l) + h;
    return i && i.copy(this.origin).addScaledVector(this.direction, u), n && n.copy(Su).addScaledVector(Ko, d), p;
  }
  /**
   * Intersects this ray with the given sphere, returning the intersection
   * point or `null` if there is no intersection.
   *
   * @param {Sphere} sphere - The sphere to intersect.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectSphere(t, e) {
    Dn.subVectors(t.center, this.origin);
    const i = Dn.dot(this.direction), n = Dn.dot(Dn) - i * i, s = t.radius * t.radius;
    if (n > s) return null;
    const r = Math.sqrt(s - n), o = i - r, l = i + r;
    return l < 0 ? null : o < 0 ? this.at(l, e) : this.at(o, e);
  }
  /**
   * Returns `true` if this ray intersects with the given sphere.
   *
   * @param {Sphere} sphere - The sphere to intersect.
   * @return {boolean} Whether this ray intersects with the given sphere or not.
   */
  intersectsSphere(t) {
    return t.radius < 0 ? !1 : this.distanceSqToPoint(t.center) <= t.radius * t.radius;
  }
  /**
   * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
   * does not intersect with the plane.
   *
   * @param {Plane} plane - The plane to compute the distance to.
   * @return {?number} Whether this ray intersects with the given sphere or not.
   */
  distanceToPlane(t) {
    const e = t.normal.dot(this.direction);
    if (e === 0)
      return t.distanceToPoint(this.origin) === 0 ? 0 : null;
    const i = -(this.origin.dot(t.normal) + t.constant) / e;
    return i >= 0 ? i : null;
  }
  /**
   * Intersects this ray with the given plane, returning the intersection
   * point or `null` if there is no intersection.
   *
   * @param {Plane} plane - The plane to intersect.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectPlane(t, e) {
    const i = this.distanceToPlane(t);
    return i === null ? null : this.at(i, e);
  }
  /**
   * Returns `true` if this ray intersects with the given plane.
   *
   * @param {Plane} plane - The plane to intersect.
   * @return {boolean} Whether this ray intersects with the given plane or not.
   */
  intersectsPlane(t) {
    const e = t.distanceToPoint(this.origin);
    return e === 0 || t.normal.dot(this.direction) * e < 0;
  }
  /**
   * Intersects this ray with the given bounding box, returning the intersection
   * point or `null` if there is no intersection.
   *
   * @param {Box3} box - The box to intersect.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectBox(t, e) {
    let i, n, s, r, o, l;
    const h = 1 / this.direction.x, c = 1 / this.direction.y, u = 1 / this.direction.z, d = this.origin;
    return h >= 0 ? (i = (t.min.x - d.x) * h, n = (t.max.x - d.x) * h) : (i = (t.max.x - d.x) * h, n = (t.min.x - d.x) * h), c >= 0 ? (s = (t.min.y - d.y) * c, r = (t.max.y - d.y) * c) : (s = (t.max.y - d.y) * c, r = (t.min.y - d.y) * c), i > r || s > n || ((s > i || isNaN(i)) && (i = s), (r < n || isNaN(n)) && (n = r), u >= 0 ? (o = (t.min.z - d.z) * u, l = (t.max.z - d.z) * u) : (o = (t.max.z - d.z) * u, l = (t.min.z - d.z) * u), i > l || o > n) || ((o > i || i !== i) && (i = o), (l < n || n !== n) && (n = l), n < 0) ? null : this.at(i >= 0 ? i : n, e);
  }
  /**
   * Returns `true` if this ray intersects with the given box.
   *
   * @param {Box3} box - The box to intersect.
   * @return {boolean} Whether this ray intersects with the given box or not.
   */
  intersectsBox(t) {
    return this.intersectBox(t, Dn) !== null;
  }
  /**
   * Intersects this ray with the given triangle, returning the intersection
   * point or `null` if there is no intersection.
   *
   * @param {Vector3} a - The first vertex of the triangle.
   * @param {Vector3} b - The second vertex of the triangle.
   * @param {Vector3} c - The third vertex of the triangle.
   * @param {boolean} backfaceCulling - Whether to use backface culling or not.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectTriangle(t, e, i, n, s) {
    wu.subVectors(e, t), Qo.subVectors(i, t), Au.crossVectors(wu, Qo);
    let r = this.direction.dot(Au), o;
    if (r > 0) {
      if (n) return null;
      o = 1;
    } else if (r < 0)
      o = -1, r = -r;
    else
      return null;
    os.subVectors(this.origin, t);
    const l = o * this.direction.dot(Qo.crossVectors(os, Qo));
    if (l < 0)
      return null;
    const h = o * this.direction.dot(wu.cross(os));
    if (h < 0 || l + h > r)
      return null;
    const c = -o * os.dot(Au);
    return c < 0 ? null : this.at(c / r, s);
  }
  /**
   * Transforms this ray with the given 4x4 transformation matrix.
   *
   * @param {Matrix4} matrix4 - The transformation matrix.
   * @return {Ray} A reference to this ray.
   */
  applyMatrix4(t) {
    return this.origin.applyMatrix4(t), this.direction.transformDirection(t), this;
  }
  /**
   * Returns `true` if this ray is equal with the given one.
   *
   * @param {Ray} ray - The ray to test for equality.
   * @return {boolean} Whether this ray is equal with the given one.
   */
  equals(t) {
    return t.origin.equals(this.origin) && t.direction.equals(this.direction);
  }
  /**
   * Returns a new ray with copied values from this instance.
   *
   * @return {Ray} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}, Vt = class tp {
  /**
   * Constructs a new 4x4 matrix. The arguments are supposed to be
   * in row-major order. If no arguments are provided, the constructor
   * initializes the matrix as an identity matrix.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n14] - 1-4 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n24] - 2-4 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @param {number} [n34] - 3-4 matrix element.
   * @param {number} [n41] - 4-1 matrix element.
   * @param {number} [n42] - 4-2 matrix element.
   * @param {number} [n43] - 4-3 matrix element.
   * @param {number} [n44] - 4-4 matrix element.
   */
  constructor(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g) {
    tp.prototype.isMatrix4 = !0, this.elements = [
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ], t !== void 0 && this.set(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g);
  }
  /**
   * Sets the elements of the matrix.The arguments are supposed to be
   * in row-major order.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n14] - 1-4 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n24] - 2-4 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @param {number} [n34] - 3-4 matrix element.
   * @param {number} [n41] - 4-1 matrix element.
   * @param {number} [n42] - 4-2 matrix element.
   * @param {number} [n43] - 4-3 matrix element.
   * @param {number} [n44] - 4-4 matrix element.
   * @return {Matrix4} A reference to this matrix.
   */
  set(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g) {
    const m = this.elements;
    return m[0] = t, m[4] = e, m[8] = i, m[12] = n, m[1] = s, m[5] = r, m[9] = o, m[13] = l, m[2] = h, m[6] = c, m[10] = u, m[14] = d, m[3] = p, m[7] = f, m[11] = y, m[15] = g, this;
  }
  /**
   * Sets this matrix to the 4x4 identity matrix.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  identity() {
    return this.set(
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Returns a matrix with copied values from this instance.
   *
   * @return {Matrix4} A clone of this instance.
   */
  clone() {
    return new tp().fromArray(this.elements);
  }
  /**
   * Copies the values of the given matrix to this instance.
   *
   * @param {Matrix4} m - The matrix to copy.
   * @return {Matrix4} A reference to this matrix.
   */
  copy(t) {
    const e = this.elements, i = t.elements;
    return e[0] = i[0], e[1] = i[1], e[2] = i[2], e[3] = i[3], e[4] = i[4], e[5] = i[5], e[6] = i[6], e[7] = i[7], e[8] = i[8], e[9] = i[9], e[10] = i[10], e[11] = i[11], e[12] = i[12], e[13] = i[13], e[14] = i[14], e[15] = i[15], this;
  }
  /**
   * Copies the translation component of the given matrix
   * into this matrix's translation component.
   *
   * @param {Matrix4} m - The matrix to copy the translation component.
   * @return {Matrix4} A reference to this matrix.
   */
  copyPosition(t) {
    const e = this.elements, i = t.elements;
    return e[12] = i[12], e[13] = i[13], e[14] = i[14], this;
  }
  /**
   * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  setFromMatrix3(t) {
    const e = t.elements;
    return this.set(
      e[0],
      e[3],
      e[6],
      0,
      e[1],
      e[4],
      e[7],
      0,
      e[2],
      e[5],
      e[8],
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Extracts the basis of this matrix into the three axis vectors provided.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  extractBasis(t, e, i) {
    return t.setFromMatrixColumn(this, 0), e.setFromMatrixColumn(this, 1), i.setFromMatrixColumn(this, 2), this;
  }
  /**
   * Sets the given basis vectors to this matrix.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeBasis(t, e, i) {
    return this.set(
      t.x,
      e.x,
      i.x,
      0,
      t.y,
      e.y,
      i.y,
      0,
      t.z,
      e.z,
      i.z,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Extracts the rotation component of the given matrix
   * into this matrix's rotation component.
   *
   * Note: This method does not support reflection matrices.
   *
   * @param {Matrix4} m - The matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  extractRotation(t) {
    const e = this.elements, i = t.elements, n = 1 / wr.setFromMatrixColumn(t, 0).length(), s = 1 / wr.setFromMatrixColumn(t, 1).length(), r = 1 / wr.setFromMatrixColumn(t, 2).length();
    return e[0] = i[0] * n, e[1] = i[1] * n, e[2] = i[2] * n, e[3] = 0, e[4] = i[4] * s, e[5] = i[5] * s, e[6] = i[6] * s, e[7] = 0, e[8] = i[8] * r, e[9] = i[9] * r, e[10] = i[10] * r, e[11] = 0, e[12] = 0, e[13] = 0, e[14] = 0, e[15] = 1, this;
  }
  /**
   * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
   * the rotation specified by the given Euler angles. The rest of
   * the matrix is set to the identity. Depending on the {@link Euler#order},
   * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
   * for a complete list.
   *
   * @param {Euler} euler - The Euler angles.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationFromEuler(t) {
    const e = this.elements, i = t.x, n = t.y, s = t.z, r = Math.cos(i), o = Math.sin(i), l = Math.cos(n), h = Math.sin(n), c = Math.cos(s), u = Math.sin(s);
    if (t.order === "XYZ") {
      const d = r * c, p = r * u, f = o * c, y = o * u;
      e[0] = l * c, e[4] = -l * u, e[8] = h, e[1] = p + f * h, e[5] = d - y * h, e[9] = -o * l, e[2] = y - d * h, e[6] = f + p * h, e[10] = r * l;
    } else if (t.order === "YXZ") {
      const d = l * c, p = l * u, f = h * c, y = h * u;
      e[0] = d + y * o, e[4] = f * o - p, e[8] = r * h, e[1] = r * u, e[5] = r * c, e[9] = -o, e[2] = p * o - f, e[6] = y + d * o, e[10] = r * l;
    } else if (t.order === "ZXY") {
      const d = l * c, p = l * u, f = h * c, y = h * u;
      e[0] = d - y * o, e[4] = -r * u, e[8] = f + p * o, e[1] = p + f * o, e[5] = r * c, e[9] = y - d * o, e[2] = -r * h, e[6] = o, e[10] = r * l;
    } else if (t.order === "ZYX") {
      const d = r * c, p = r * u, f = o * c, y = o * u;
      e[0] = l * c, e[4] = f * h - p, e[8] = d * h + y, e[1] = l * u, e[5] = y * h + d, e[9] = p * h - f, e[2] = -h, e[6] = o * l, e[10] = r * l;
    } else if (t.order === "YZX") {
      const d = r * l, p = r * h, f = o * l, y = o * h;
      e[0] = l * c, e[4] = y - d * u, e[8] = f * u + p, e[1] = u, e[5] = r * c, e[9] = -o * c, e[2] = -h * c, e[6] = p * u + f, e[10] = d - y * u;
    } else if (t.order === "XZY") {
      const d = r * l, p = r * h, f = o * l, y = o * h;
      e[0] = l * c, e[4] = -u, e[8] = h * c, e[1] = d * u + y, e[5] = r * c, e[9] = p * u - f, e[2] = f * u - p, e[6] = o * c, e[10] = y * u + d;
    }
    return e[3] = 0, e[7] = 0, e[11] = 0, e[12] = 0, e[13] = 0, e[14] = 0, e[15] = 1, this;
  }
  /**
   * Sets the rotation component of this matrix to the rotation specified by
   * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
   * The rest of the matrix is set to the identity.
   *
   * @param {Quaternion} q - The Quaternion.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationFromQuaternion(t) {
    return this.compose(vv, t, bv);
  }
  /**
   * Sets the rotation component of the transformation matrix, looking from `eye` towards
   * `target`, and oriented by the up-direction.
   *
   * @param {Vector3} eye - The eye vector.
   * @param {Vector3} target - The target vector.
   * @param {Vector3} up - The up vector.
   * @return {Matrix4} A reference to this matrix.
   */
  lookAt(t, e, i) {
    const n = this.elements;
    return Pi.subVectors(t, e), Pi.lengthSq() === 0 && (Pi.z = 1), Pi.normalize(), ls.crossVectors(i, Pi), ls.lengthSq() === 0 && (Math.abs(i.z) === 1 ? Pi.x += 1e-4 : Pi.z += 1e-4, Pi.normalize(), ls.crossVectors(i, Pi)), ls.normalize(), tl.crossVectors(Pi, ls), n[0] = ls.x, n[4] = tl.x, n[8] = Pi.x, n[1] = ls.y, n[5] = tl.y, n[9] = Pi.y, n[2] = ls.z, n[6] = tl.z, n[10] = Pi.z, this;
  }
  /**
   * Post-multiplies this matrix by the given 4x4 matrix.
   *
   * @param {Matrix4} m - The matrix to multiply with.
   * @return {Matrix4} A reference to this matrix.
   */
  multiply(t) {
    return this.multiplyMatrices(this, t);
  }
  /**
   * Pre-multiplies this matrix by the given 4x4 matrix.
   *
   * @param {Matrix4} m - The matrix to multiply with.
   * @return {Matrix4} A reference to this matrix.
   */
  premultiply(t) {
    return this.multiplyMatrices(t, this);
  }
  /**
   * Multiples the given 4x4 matrices and stores the result
   * in this matrix.
   *
   * @param {Matrix4} a - The first matrix.
   * @param {Matrix4} b - The second matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  multiplyMatrices(t, e) {
    const i = t.elements, n = e.elements, s = this.elements, r = i[0], o = i[4], l = i[8], h = i[12], c = i[1], u = i[5], d = i[9], p = i[13], f = i[2], y = i[6], g = i[10], m = i[14], v = i[3], x = i[7], _ = i[11], S = i[15], w = n[0], T = n[4], R = n[8], b = n[12], M = n[1], L = n[5], U = n[9], O = n[13], V = n[2], W = n[6], G = n[10], et = n[14], H = n[3], at = n[7], pt = n[11], Mt = n[15];
    return s[0] = r * w + o * M + l * V + h * H, s[4] = r * T + o * L + l * W + h * at, s[8] = r * R + o * U + l * G + h * pt, s[12] = r * b + o * O + l * et + h * Mt, s[1] = c * w + u * M + d * V + p * H, s[5] = c * T + u * L + d * W + p * at, s[9] = c * R + u * U + d * G + p * pt, s[13] = c * b + u * O + d * et + p * Mt, s[2] = f * w + y * M + g * V + m * H, s[6] = f * T + y * L + g * W + m * at, s[10] = f * R + y * U + g * G + m * pt, s[14] = f * b + y * O + g * et + m * Mt, s[3] = v * w + x * M + _ * V + S * H, s[7] = v * T + x * L + _ * W + S * at, s[11] = v * R + x * U + _ * G + S * pt, s[15] = v * b + x * O + _ * et + S * Mt, this;
  }
  /**
   * Multiplies every component of the matrix by the given scalar.
   *
   * @param {number} s - The scalar.
   * @return {Matrix4} A reference to this matrix.
   */
  multiplyScalar(t) {
    const e = this.elements;
    return e[0] *= t, e[4] *= t, e[8] *= t, e[12] *= t, e[1] *= t, e[5] *= t, e[9] *= t, e[13] *= t, e[2] *= t, e[6] *= t, e[10] *= t, e[14] *= t, e[3] *= t, e[7] *= t, e[11] *= t, e[15] *= t, this;
  }
  /**
   * Computes and returns the determinant of this matrix.
   *
   * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
   *
   * @return {number} The determinant.
   */
  determinant() {
    const t = this.elements, e = t[0], i = t[4], n = t[8], s = t[12], r = t[1], o = t[5], l = t[9], h = t[13], c = t[2], u = t[6], d = t[10], p = t[14], f = t[3], y = t[7], g = t[11], m = t[15];
    return f * (+s * l * u - n * h * u - s * o * d + i * h * d + n * o * p - i * l * p) + y * (+e * l * p - e * h * d + s * r * d - n * r * p + n * h * c - s * l * c) + g * (+e * h * u - e * o * p - s * r * u + i * r * p + s * o * c - i * h * c) + m * (-n * o * c - e * l * u + e * o * d + n * r * u - i * r * d + i * l * c);
  }
  /**
   * Transposes this matrix in place.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  transpose() {
    const t = this.elements;
    let e;
    return e = t[1], t[1] = t[4], t[4] = e, e = t[2], t[2] = t[8], t[8] = e, e = t[6], t[6] = t[9], t[9] = e, e = t[3], t[3] = t[12], t[12] = e, e = t[7], t[7] = t[13], t[13] = e, e = t[11], t[11] = t[14], t[14] = e, this;
  }
  /**
   * Sets the position component for this matrix from the given vector,
   * without affecting the rest of the matrix.
   *
   * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
   * @param {number} y - The y component of the vector.
   * @param {number} z - The z component of the vector.
   * @return {Matrix4} A reference to this matrix.
   */
  setPosition(t, e, i) {
    const n = this.elements;
    return t.isVector3 ? (n[12] = t.x, n[13] = t.y, n[14] = t.z) : (n[12] = t, n[13] = e, n[14] = i), this;
  }
  /**
   * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
   * You can not invert with a determinant of zero. If you attempt this, the method produces
   * a zero matrix instead.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  invert() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8], u = t[9], d = t[10], p = t[11], f = t[12], y = t[13], g = t[14], m = t[15], v = u * g * h - y * d * h + y * l * p - o * g * p - u * l * m + o * d * m, x = f * d * h - c * g * h - f * l * p + r * g * p + c * l * m - r * d * m, _ = c * y * h - f * u * h + f * o * p - r * y * p - c * o * m + r * u * m, S = f * u * l - c * y * l - f * o * d + r * y * d + c * o * g - r * u * g, w = e * v + i * x + n * _ + s * S;
    if (w === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    const T = 1 / w;
    return t[0] = v * T, t[1] = (y * d * s - u * g * s - y * n * p + i * g * p + u * n * m - i * d * m) * T, t[2] = (o * g * s - y * l * s + y * n * h - i * g * h - o * n * m + i * l * m) * T, t[3] = (u * l * s - o * d * s - u * n * h + i * d * h + o * n * p - i * l * p) * T, t[4] = x * T, t[5] = (c * g * s - f * d * s + f * n * p - e * g * p - c * n * m + e * d * m) * T, t[6] = (f * l * s - r * g * s - f * n * h + e * g * h + r * n * m - e * l * m) * T, t[7] = (r * d * s - c * l * s + c * n * h - e * d * h - r * n * p + e * l * p) * T, t[8] = _ * T, t[9] = (f * u * s - c * y * s - f * i * p + e * y * p + c * i * m - e * u * m) * T, t[10] = (r * y * s - f * o * s + f * i * h - e * y * h - r * i * m + e * o * m) * T, t[11] = (c * o * s - r * u * s - c * i * h + e * u * h + r * i * p - e * o * p) * T, t[12] = S * T, t[13] = (c * y * n - f * u * n + f * i * d - e * y * d - c * i * g + e * u * g) * T, t[14] = (f * o * n - r * y * n - f * i * l + e * y * l + r * i * g - e * o * g) * T, t[15] = (r * u * n - c * o * n + c * i * l - e * u * l - r * i * d + e * o * d) * T, this;
  }
  /**
   * Multiplies the columns of this matrix by the given vector.
   *
   * @param {Vector3} v - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  scale(t) {
    const e = this.elements, i = t.x, n = t.y, s = t.z;
    return e[0] *= i, e[4] *= n, e[8] *= s, e[1] *= i, e[5] *= n, e[9] *= s, e[2] *= i, e[6] *= n, e[10] *= s, e[3] *= i, e[7] *= n, e[11] *= s, this;
  }
  /**
   * Gets the maximum scale value of the three axes.
   *
   * @return {number} The maximum scale.
   */
  getMaxScaleOnAxis() {
    const t = this.elements, e = t[0] * t[0] + t[1] * t[1] + t[2] * t[2], i = t[4] * t[4] + t[5] * t[5] + t[6] * t[6], n = t[8] * t[8] + t[9] * t[9] + t[10] * t[10];
    return Math.sqrt(Math.max(e, i, n));
  }
  /**
   * Sets this matrix as a translation transform from the given vector.
   *
   * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
   * @param {number} y - The amount to translate in the Y axis.
   * @param {number} z - The amount to translate in the z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeTranslation(t, e, i) {
    return t.isVector3 ? this.set(
      1,
      0,
      0,
      t.x,
      0,
      1,
      0,
      t.y,
      0,
      0,
      1,
      t.z,
      0,
      0,
      0,
      1
    ) : this.set(
      1,
      0,
      0,
      t,
      0,
      1,
      0,
      e,
      0,
      0,
      1,
      i,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the X axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationX(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      1,
      0,
      0,
      0,
      0,
      e,
      -i,
      0,
      0,
      i,
      e,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the Y axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationY(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      0,
      i,
      0,
      0,
      1,
      0,
      0,
      -i,
      0,
      e,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the Z axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationZ(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      -i,
      0,
      0,
      i,
      e,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the given axis by
   * the given angle.
   *
   * This is a somewhat controversial but mathematically sound alternative to
   * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
   *
   * @param {Vector3} axis - The normalized rotation axis.
   * @param {number} angle - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationAxis(t, e) {
    const i = Math.cos(e), n = Math.sin(e), s = 1 - i, r = t.x, o = t.y, l = t.z, h = s * r, c = s * o;
    return this.set(
      h * r + i,
      h * o - n * l,
      h * l + n * o,
      0,
      h * o + n * l,
      c * o + i,
      c * l - n * r,
      0,
      h * l - n * o,
      c * l + n * r,
      s * l * l + i,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a scale transformation.
   *
   * @param {number} x - The amount to scale in the X axis.
   * @param {number} y - The amount to scale in the Y axis.
   * @param {number} z - The amount to scale in the Z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeScale(t, e, i) {
    return this.set(
      t,
      0,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      0,
      i,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a shear transformation.
   *
   * @param {number} xy - The amount to shear X by Y.
   * @param {number} xz - The amount to shear X by Z.
   * @param {number} yx - The amount to shear Y by X.
   * @param {number} yz - The amount to shear Y by Z.
   * @param {number} zx - The amount to shear Z by X.
   * @param {number} zy - The amount to shear Z by Y.
   * @return {Matrix4} A reference to this matrix.
   */
  makeShear(t, e, i, n, s, r) {
    return this.set(
      1,
      i,
      s,
      0,
      t,
      1,
      r,
      0,
      e,
      n,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix to the transformation composed of the given position,
   * rotation (Quaternion) and scale.
   *
   * @param {Vector3} position - The position vector.
   * @param {Quaternion} quaternion - The rotation as a Quaternion.
   * @param {Vector3} scale - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  compose(t, e, i) {
    const n = this.elements, s = e._x, r = e._y, o = e._z, l = e._w, h = s + s, c = r + r, u = o + o, d = s * h, p = s * c, f = s * u, y = r * c, g = r * u, m = o * u, v = l * h, x = l * c, _ = l * u, S = i.x, w = i.y, T = i.z;
    return n[0] = (1 - (y + m)) * S, n[1] = (p + _) * S, n[2] = (f - x) * S, n[3] = 0, n[4] = (p - _) * w, n[5] = (1 - (d + m)) * w, n[6] = (g + v) * w, n[7] = 0, n[8] = (f + x) * T, n[9] = (g - v) * T, n[10] = (1 - (d + y)) * T, n[11] = 0, n[12] = t.x, n[13] = t.y, n[14] = t.z, n[15] = 1, this;
  }
  /**
   * Decomposes this matrix into its position, rotation and scale components
   * and provides the result in the given objects.
   *
   * Note: Not all matrices are decomposable in this way. For example, if an
   * object has a non-uniformly scaled parent, then the object's world matrix
   * may not be decomposable, and this method may not be appropriate.
   *
   * @param {Vector3} position - The position vector.
   * @param {Quaternion} quaternion - The rotation as a Quaternion.
   * @param {Vector3} scale - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  decompose(t, e, i) {
    const n = this.elements;
    let s = wr.set(n[0], n[1], n[2]).length();
    const r = wr.set(n[4], n[5], n[6]).length(), o = wr.set(n[8], n[9], n[10]).length();
    this.determinant() < 0 && (s = -s), t.x = n[12], t.y = n[13], t.z = n[14], ji.copy(this);
    const h = 1 / s, c = 1 / r, u = 1 / o;
    return ji.elements[0] *= h, ji.elements[1] *= h, ji.elements[2] *= h, ji.elements[4] *= c, ji.elements[5] *= c, ji.elements[6] *= c, ji.elements[8] *= u, ji.elements[9] *= u, ji.elements[10] *= u, e.setFromRotationMatrix(ji), i.x = s, i.y = r, i.z = o, this;
  }
  /**
  	 * Creates a perspective projection matrix. This is used internally by
  	 * {@link PerspectiveCamera#updateProjectionMatrix}.
  
  	 * @param {number} left - Left boundary of the viewing frustum at the near plane.
  	 * @param {number} right - Right boundary of the viewing frustum at the near plane.
  	 * @param {number} top - Top boundary of the viewing frustum at the near plane.
  	 * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  	 * @param {number} near - The distance from the camera to the near plane.
  	 * @param {number} far - The distance from the camera to the far plane.
  	 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  	 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  	 * @return {Matrix4} A reference to this matrix.
  	 */
  makePerspective(t, e, i, n, s, r, o = Ni, l = !1) {
    const h = this.elements, c = 2 * s / (e - t), u = 2 * s / (i - n), d = (e + t) / (e - t), p = (i + n) / (i - n);
    let f, y;
    if (l)
      f = s / (r - s), y = r * s / (r - s);
    else if (o === Ni)
      f = -(r + s) / (r - s), y = -2 * r * s / (r - s);
    else if (o === ga)
      f = -r / (r - s), y = -r * s / (r - s);
    else
      throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + o);
    return h[0] = c, h[4] = 0, h[8] = d, h[12] = 0, h[1] = 0, h[5] = u, h[9] = p, h[13] = 0, h[2] = 0, h[6] = 0, h[10] = f, h[14] = y, h[3] = 0, h[7] = 0, h[11] = -1, h[15] = 0, this;
  }
  /**
  	 * Creates a orthographic projection matrix. This is used internally by
  	 * {@link OrthographicCamera#updateProjectionMatrix}.
  
  	 * @param {number} left - Left boundary of the viewing frustum at the near plane.
  	 * @param {number} right - Right boundary of the viewing frustum at the near plane.
  	 * @param {number} top - Top boundary of the viewing frustum at the near plane.
  	 * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  	 * @param {number} near - The distance from the camera to the near plane.
  	 * @param {number} far - The distance from the camera to the far plane.
  	 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  	 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  	 * @return {Matrix4} A reference to this matrix.
  	 */
  makeOrthographic(t, e, i, n, s, r, o = Ni, l = !1) {
    const h = this.elements, c = 2 / (e - t), u = 2 / (i - n), d = -(e + t) / (e - t), p = -(i + n) / (i - n);
    let f, y;
    if (l)
      f = 1 / (r - s), y = r / (r - s);
    else if (o === Ni)
      f = -2 / (r - s), y = -(r + s) / (r - s);
    else if (o === ga)
      f = -1 / (r - s), y = -s / (r - s);
    else
      throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + o);
    return h[0] = c, h[4] = 0, h[8] = 0, h[12] = d, h[1] = 0, h[5] = u, h[9] = 0, h[13] = p, h[2] = 0, h[6] = 0, h[10] = f, h[14] = y, h[3] = 0, h[7] = 0, h[11] = 0, h[15] = 1, this;
  }
  /**
   * Returns `true` if this matrix is equal with the given one.
   *
   * @param {Matrix4} matrix - The matrix to test for equality.
   * @return {boolean} Whether this matrix is equal with the given one.
   */
  equals(t) {
    const e = this.elements, i = t.elements;
    for (let n = 0; n < 16; n++)
      if (e[n] !== i[n]) return !1;
    return !0;
  }
  /**
   * Sets the elements of the matrix from the given array.
   *
   * @param {Array<number>} array - The matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Matrix4} A reference to this matrix.
   */
  fromArray(t, e = 0) {
    for (let i = 0; i < 16; i++)
      this.elements[i] = t[i + e];
    return this;
  }
  /**
   * Writes the elements of this matrix to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The matrix elements in column-major order.
   */
  toArray(t = [], e = 0) {
    const i = this.elements;
    return t[e] = i[0], t[e + 1] = i[1], t[e + 2] = i[2], t[e + 3] = i[3], t[e + 4] = i[4], t[e + 5] = i[5], t[e + 6] = i[6], t[e + 7] = i[7], t[e + 8] = i[8], t[e + 9] = i[9], t[e + 10] = i[10], t[e + 11] = i[11], t[e + 12] = i[12], t[e + 13] = i[13], t[e + 14] = i[14], t[e + 15] = i[15], t;
  }
};
const wr = /* @__PURE__ */ new E(), ji = /* @__PURE__ */ new Vt(), vv = /* @__PURE__ */ new E(0, 0, 0), bv = /* @__PURE__ */ new E(1, 1, 1), ls = /* @__PURE__ */ new E(), tl = /* @__PURE__ */ new E(), Pi = /* @__PURE__ */ new E(), Uf = /* @__PURE__ */ new Vt(), Bf = /* @__PURE__ */ new ve();
let fn = class by {
  /**
   * Constructs a new euler instance.
   *
   * @param {number} [x=0] - The angle of the x axis in radians.
   * @param {number} [y=0] - The angle of the y axis in radians.
   * @param {number} [z=0] - The angle of the z axis in radians.
   * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
   */
  constructor(t = 0, e = 0, i = 0, n = by.DEFAULT_ORDER) {
    this.isEuler = !0, this._x = t, this._y = e, this._z = i, this._order = n;
  }
  /**
   * The angle of the x axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get x() {
    return this._x;
  }
  set x(t) {
    this._x = t, this._onChangeCallback();
  }
  /**
   * The angle of the y axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get y() {
    return this._y;
  }
  set y(t) {
    this._y = t, this._onChangeCallback();
  }
  /**
   * The angle of the z axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get z() {
    return this._z;
  }
  set z(t) {
    this._z = t, this._onChangeCallback();
  }
  /**
   * A string representing the order that the rotations are applied.
   *
   * @type {string}
   * @default 'XYZ'
   */
  get order() {
    return this._order;
  }
  set order(t) {
    this._order = t, this._onChangeCallback();
  }
  /**
   * Sets the Euler components.
   *
   * @param {number} x - The angle of the x axis in radians.
   * @param {number} y - The angle of the y axis in radians.
   * @param {number} z - The angle of the z axis in radians.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  set(t, e, i, n = this._order) {
    return this._x = t, this._y = e, this._z = i, this._order = n, this._onChangeCallback(), this;
  }
  /**
   * Returns a new Euler instance with copied values from this instance.
   *
   * @return {Euler} A clone of this instance.
   */
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._order);
  }
  /**
   * Copies the values of the given Euler instance to this instance.
   *
   * @param {Euler} euler - The Euler instance to copy.
   * @return {Euler} A reference to this Euler instance.
   */
  copy(t) {
    return this._x = t._x, this._y = t._y, this._z = t._z, this._order = t._order, this._onChangeCallback(), this;
  }
  /**
   * Sets the angles of this Euler instance from a pure rotation matrix.
   *
   * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromRotationMatrix(t, e = this._order, i = !0) {
    const n = t.elements, s = n[0], r = n[4], o = n[8], l = n[1], h = n[5], c = n[9], u = n[2], d = n[6], p = n[10];
    switch (e) {
      case "XYZ":
        this._y = Math.asin(kt(o, -1, 1)), Math.abs(o) < 0.9999999 ? (this._x = Math.atan2(-c, p), this._z = Math.atan2(-r, s)) : (this._x = Math.atan2(d, h), this._z = 0);
        break;
      case "YXZ":
        this._x = Math.asin(-kt(c, -1, 1)), Math.abs(c) < 0.9999999 ? (this._y = Math.atan2(o, p), this._z = Math.atan2(l, h)) : (this._y = Math.atan2(-u, s), this._z = 0);
        break;
      case "ZXY":
        this._x = Math.asin(kt(d, -1, 1)), Math.abs(d) < 0.9999999 ? (this._y = Math.atan2(-u, p), this._z = Math.atan2(-r, h)) : (this._y = 0, this._z = Math.atan2(l, s));
        break;
      case "ZYX":
        this._y = Math.asin(-kt(u, -1, 1)), Math.abs(u) < 0.9999999 ? (this._x = Math.atan2(d, p), this._z = Math.atan2(l, s)) : (this._x = 0, this._z = Math.atan2(-r, h));
        break;
      case "YZX":
        this._z = Math.asin(kt(l, -1, 1)), Math.abs(l) < 0.9999999 ? (this._x = Math.atan2(-c, h), this._y = Math.atan2(-u, s)) : (this._x = 0, this._y = Math.atan2(o, p));
        break;
      case "XZY":
        this._z = Math.asin(-kt(r, -1, 1)), Math.abs(r) < 0.9999999 ? (this._x = Math.atan2(d, h), this._y = Math.atan2(o, s)) : (this._x = Math.atan2(-c, p), this._y = 0);
        break;
      default:
        console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + e);
    }
    return this._order = e, i === !0 && this._onChangeCallback(), this;
  }
  /**
   * Sets the angles of this Euler instance from a normalized quaternion.
   *
   * @param {Quaternion} q - A normalized Quaternion.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromQuaternion(t, e, i) {
    return Uf.makeRotationFromQuaternion(t), this.setFromRotationMatrix(Uf, e, i);
  }
  /**
   * Sets the angles of this Euler instance from the given vector.
   *
   * @param {Vector3} v - The vector.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromVector3(t, e = this._order) {
    return this.set(t.x, t.y, t.z, e);
  }
  /**
   * Resets the euler angle with a new order by creating a quaternion from this
   * euler angle and then setting this euler angle with the quaternion and the
   * new order.
   *
   * Warning: This discards revolution information.
   *
   * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  reorder(t) {
    return Bf.setFromEuler(this), this.setFromQuaternion(Bf, t);
  }
  /**
   * Returns `true` if this Euler instance is equal with the given one.
   *
   * @param {Euler} euler - The Euler instance to test for equality.
   * @return {boolean} Whether this Euler instance is equal with the given one.
   */
  equals(t) {
    return t._x === this._x && t._y === this._y && t._z === this._z && t._order === this._order;
  }
  /**
   * Sets this Euler instance's components to values from the given array. The first three
   * entries of the array are assign to the x,y and z components. An optional fourth entry
   * defines the Euler order.
   *
   * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
   * @return {Euler} A reference to this Euler instance.
   */
  fromArray(t) {
    return this._x = t[0], this._y = t[1], this._z = t[2], t[3] !== void 0 && (this._order = t[3]), this._onChangeCallback(), this;
  }
  /**
   * Writes the components of this Euler instance to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number,number,number,string>} The Euler components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this._x, t[e + 1] = this._y, t[e + 2] = this._z, t[e + 3] = this._order, t;
  }
  _onChange(t) {
    return this._onChangeCallback = t, this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x, yield this._y, yield this._z, yield this._order;
  }
};
fn.DEFAULT_ORDER = "XYZ";
let Nc = class {
  /**
   * Constructs a new layers instance, with membership
   * initially set to layer `0`.
   */
  constructor() {
    this.mask = 1;
  }
  /**
   * Sets membership to the given layer, and remove membership all other layers.
   *
   * @param {number} layer - The layer to set.
   */
  set(t) {
    this.mask = (1 << t | 0) >>> 0;
  }
  /**
   * Adds membership of the given layer.
   *
   * @param {number} layer - The layer to enable.
   */
  enable(t) {
    this.mask |= 1 << t | 0;
  }
  /**
   * Adds membership to all layers.
   */
  enableAll() {
    this.mask = -1;
  }
  /**
   * Toggles the membership of the given layer.
   *
   * @param {number} layer - The layer to toggle.
   */
  toggle(t) {
    this.mask ^= 1 << t | 0;
  }
  /**
   * Removes membership of the given layer.
   *
   * @param {number} layer - The layer to enable.
   */
  disable(t) {
    this.mask &= ~(1 << t | 0);
  }
  /**
   * Removes the membership from all layers.
   */
  disableAll() {
    this.mask = 0;
  }
  /**
   * Returns `true` if this and the given layers object have at least one
   * layer in common.
   *
   * @param {Layers} layers - The layers to test.
   * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
   */
  test(t) {
    return (this.mask & t.mask) !== 0;
  }
  /**
   * Returns `true` if the given layer is enabled.
   *
   * @param {number} layer - The layer to test.
   * @return {boolean } Whether the given layer is enabled or not.
   */
  isEnabled(t) {
    return (this.mask & (1 << t | 0)) !== 0;
  }
}, Mv = 0;
const zf = /* @__PURE__ */ new E(), Ar = /* @__PURE__ */ new ve(), Fn = /* @__PURE__ */ new Vt(), el = /* @__PURE__ */ new E(), Na = /* @__PURE__ */ new E(), Sv = /* @__PURE__ */ new E(), wv = /* @__PURE__ */ new ve(), Nf = /* @__PURE__ */ new E(1, 0, 0), Of = /* @__PURE__ */ new E(0, 1, 0), kf = /* @__PURE__ */ new E(0, 0, 1), Vf = { type: "added" }, Av = { type: "removed" }, Er = { type: "childadded", child: null }, Eu = { type: "childremoved", child: null };
let le = class Eh extends Ei {
  /**
   * Constructs a new 3D object.
   */
  constructor() {
    super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: Mv++ }), this.uuid = Oi(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = Eh.DEFAULT_UP.clone();
    const t = new E(), e = new fn(), i = new ve(), n = new E(1, 1, 1);
    function s() {
      i.setFromEuler(e, !1);
    }
    function r() {
      e.setFromQuaternion(i, void 0, !1);
    }
    e._onChange(s), i._onChange(r), Object.defineProperties(this, {
      /**
       * Represents the object's local position.
       *
       * @name Object3D#position
       * @type {Vector3}
       * @default (0,0,0)
       */
      position: {
        configurable: !0,
        enumerable: !0,
        value: t
      },
      /**
       * Represents the object's local rotation as Euler angles, in radians.
       *
       * @name Object3D#rotation
       * @type {Euler}
       * @default (0,0,0)
       */
      rotation: {
        configurable: !0,
        enumerable: !0,
        value: e
      },
      /**
       * Represents the object's local rotation as Quaternions.
       *
       * @name Object3D#quaternion
       * @type {Quaternion}
       */
      quaternion: {
        configurable: !0,
        enumerable: !0,
        value: i
      },
      /**
       * Represents the object's local scale.
       *
       * @name Object3D#scale
       * @type {Vector3}
       * @default (1,1,1)
       */
      scale: {
        configurable: !0,
        enumerable: !0,
        value: n
      },
      /**
       * Represents the object's model-view matrix.
       *
       * @name Object3D#modelViewMatrix
       * @type {Matrix4}
       */
      modelViewMatrix: {
        value: new Vt()
      },
      /**
       * Represents the object's normal matrix.
       *
       * @name Object3D#normalMatrix
       * @type {Matrix3}
       */
      normalMatrix: {
        value: new Xt()
      }
    }), this.matrix = new Vt(), this.matrixWorld = new Vt(), this.matrixAutoUpdate = Eh.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = Eh.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new Nc(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.userData = {};
  }
  /**
   * A callback that is executed immediately before a 3D object is rendered to a shadow map.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {Camera} shadowCamera - The shadow camera.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} depthMaterial - The depth material.
   * @param {Object} group - The geometry group data.
   */
  onBeforeShadow() {
  }
  /**
   * A callback that is executed immediately after a 3D object is rendered to a shadow map.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {Camera} shadowCamera - The shadow camera.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} depthMaterial - The depth material.
   * @param {Object} group - The geometry group data.
   */
  onAfterShadow() {
  }
  /**
   * A callback that is executed immediately before a 3D object is rendered.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} material - The 3D object's material.
   * @param {Object} group - The geometry group data.
   */
  onBeforeRender() {
  }
  /**
   * A callback that is executed immediately after a 3D object is rendered.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} material - The 3D object's material.
   * @param {Object} group - The geometry group data.
   */
  onAfterRender() {
  }
  /**
   * Applies the given transformation matrix to the object and updates the object's position,
   * rotation and scale.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   */
  applyMatrix4(t) {
    this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(t), this.matrix.decompose(this.position, this.quaternion, this.scale);
  }
  /**
   * Applies a rotation represented by given the quaternion to the 3D object.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Object3D} A reference to this instance.
   */
  applyQuaternion(t) {
    return this.quaternion.premultiply(t), this;
  }
  /**
   * Sets the given rotation represented as an axis/angle couple to the 3D object.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   */
  setRotationFromAxisAngle(t, e) {
    this.quaternion.setFromAxisAngle(t, e);
  }
  /**
   * Sets the given rotation represented as Euler angles to the 3D object.
   *
   * @param {Euler} euler - The Euler angles.
   */
  setRotationFromEuler(t) {
    this.quaternion.setFromEuler(t, !0);
  }
  /**
   * Sets the given rotation represented as rotation matrix to the 3D object.
   *
   * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
   * a pure rotation matrix (i.e, unscaled).
   */
  setRotationFromMatrix(t) {
    this.quaternion.setFromRotationMatrix(t);
  }
  /**
   * Sets the given rotation represented as a Quaternion to the 3D object.
   *
   * @param {Quaternion} q - The Quaternion
   */
  setRotationFromQuaternion(t) {
    this.quaternion.copy(t);
  }
  /**
   * Rotates the 3D object along an axis in local space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateOnAxis(t, e) {
    return Ar.setFromAxisAngle(t, e), this.quaternion.multiply(Ar), this;
  }
  /**
   * Rotates the 3D object along an axis in world space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateOnWorldAxis(t, e) {
    return Ar.setFromAxisAngle(t, e), this.quaternion.premultiply(Ar), this;
  }
  /**
   * Rotates the 3D object around its X axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateX(t) {
    return this.rotateOnAxis(Nf, t);
  }
  /**
   * Rotates the 3D object around its Y axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateY(t) {
    return this.rotateOnAxis(Of, t);
  }
  /**
   * Rotates the 3D object around its Z axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateZ(t) {
    return this.rotateOnAxis(kf, t);
  }
  /**
   * Translate the 3D object by a distance along the given axis in local space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateOnAxis(t, e) {
    return zf.copy(t).applyQuaternion(this.quaternion), this.position.add(zf.multiplyScalar(e)), this;
  }
  /**
   * Translate the 3D object by a distance along its X-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateX(t) {
    return this.translateOnAxis(Nf, t);
  }
  /**
   * Translate the 3D object by a distance along its Y-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateY(t) {
    return this.translateOnAxis(Of, t);
  }
  /**
   * Translate the 3D object by a distance along its Z-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateZ(t) {
    return this.translateOnAxis(kf, t);
  }
  /**
   * Converts the given vector from this 3D object's local space to world space.
   *
   * @param {Vector3} vector - The vector to convert.
   * @return {Vector3} The converted vector.
   */
  localToWorld(t) {
    return this.updateWorldMatrix(!0, !1), t.applyMatrix4(this.matrixWorld);
  }
  /**
   * Converts the given vector from this 3D object's word space to local space.
   *
   * @param {Vector3} vector - The vector to convert.
   * @return {Vector3} The converted vector.
   */
  worldToLocal(t) {
    return this.updateWorldMatrix(!0, !1), t.applyMatrix4(Fn.copy(this.matrixWorld).invert());
  }
  /**
   * Rotates the object to face a point in world space.
   *
   * This method does not support objects having non-uniformly-scaled parent(s).
   *
   * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
   * @param {number} [y] - The y coordinate in world space.
   * @param {number} [z] - The z coordinate in world space.
   */
  lookAt(t, e, i) {
    t.isVector3 ? el.copy(t) : el.set(t, e, i);
    const n = this.parent;
    this.updateWorldMatrix(!0, !1), Na.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? Fn.lookAt(Na, el, this.up) : Fn.lookAt(el, Na, this.up), this.quaternion.setFromRotationMatrix(Fn), n && (Fn.extractRotation(n.matrixWorld), Ar.setFromRotationMatrix(Fn), this.quaternion.premultiply(Ar.invert()));
  }
  /**
   * Adds the given 3D object as a child to this 3D object. An arbitrary number of
   * objects may be added. Any current parent on an object passed in here will be
   * removed, since an object can have at most one parent.
   *
   * @fires Object3D#added
   * @fires Object3D#childadded
   * @param {Object3D} object - The 3D object to add.
   * @return {Object3D} A reference to this instance.
   */
  add(t) {
    if (arguments.length > 1) {
      for (let e = 0; e < arguments.length; e++)
        this.add(arguments[e]);
      return this;
    }
    return t === this ? (console.error("THREE.Object3D.add: object can't be added as a child of itself.", t), this) : (t && t.isObject3D ? (t.removeFromParent(), t.parent = this, this.children.push(t), t.dispatchEvent(Vf), Er.child = t, this.dispatchEvent(Er), Er.child = null) : console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", t), this);
  }
  /**
   * Removes the given 3D object as child from this 3D object.
   * An arbitrary number of objects may be removed.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @param {Object3D} object - The 3D object to remove.
   * @return {Object3D} A reference to this instance.
   */
  remove(t) {
    if (arguments.length > 1) {
      for (let i = 0; i < arguments.length; i++)
        this.remove(arguments[i]);
      return this;
    }
    const e = this.children.indexOf(t);
    return e !== -1 && (t.parent = null, this.children.splice(e, 1), t.dispatchEvent(Av), Eu.child = t, this.dispatchEvent(Eu), Eu.child = null), this;
  }
  /**
   * Removes this 3D object from its current parent.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @return {Object3D} A reference to this instance.
   */
  removeFromParent() {
    const t = this.parent;
    return t !== null && t.remove(this), this;
  }
  /**
   * Removes all child objects.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @return {Object3D} A reference to this instance.
   */
  clear() {
    return this.remove(...this.children);
  }
  /**
   * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
   * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
   *
   * @fires Object3D#added
   * @fires Object3D#childadded
   * @param {Object3D} object - The 3D object to attach.
   * @return {Object3D} A reference to this instance.
   */
  attach(t) {
    return this.updateWorldMatrix(!0, !1), Fn.copy(this.matrixWorld).invert(), t.parent !== null && (t.parent.updateWorldMatrix(!0, !1), Fn.multiply(t.parent.matrixWorld)), t.applyMatrix4(Fn), t.removeFromParent(), t.parent = this, this.children.push(t), t.updateWorldMatrix(!1, !0), t.dispatchEvent(Vf), Er.child = t, this.dispatchEvent(Er), Er.child = null, this;
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching ID.
   *
   * @param {number} id - The id.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectById(t) {
    return this.getObjectByProperty("id", t);
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching name.
   *
   * @param {string} name - The name.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectByName(t) {
    return this.getObjectByProperty("name", t);
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching property value.
   *
   * @param {string} name - The name of the property.
   * @param {any} value - The value.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectByProperty(t, e) {
    if (this[t] === e) return this;
    for (let i = 0, n = this.children.length; i < n; i++) {
      const r = this.children[i].getObjectByProperty(t, e);
      if (r !== void 0)
        return r;
    }
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns all 3D objects with a matching property value.
   *
   * @param {string} name - The name of the property.
   * @param {any} value - The value.
   * @param {Array<Object3D>} result - The method stores the result in this array.
   * @return {Array<Object3D>} The found 3D objects.
   */
  getObjectsByProperty(t, e, i = []) {
    this[t] === e && i.push(this);
    const n = this.children;
    for (let s = 0, r = n.length; s < r; s++)
      n[s].getObjectsByProperty(t, e, i);
    return i;
  }
  /**
   * Returns a vector representing the position of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's position in world space.
   */
  getWorldPosition(t) {
    return this.updateWorldMatrix(!0, !1), t.setFromMatrixPosition(this.matrixWorld);
  }
  /**
   * Returns a Quaternion representing the position of the 3D object in world space.
   *
   * @param {Quaternion} target - The target Quaternion the result is stored to.
   * @return {Quaternion} The 3D object's rotation in world space.
   */
  getWorldQuaternion(t) {
    return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(Na, t, Sv), t;
  }
  /**
   * Returns a vector representing the scale of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's scale in world space.
   */
  getWorldScale(t) {
    return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(Na, wv, t), t;
  }
  /**
   * Returns a vector representing the ("look") direction of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's direction in world space.
   */
  getWorldDirection(t) {
    this.updateWorldMatrix(!0, !1);
    const e = this.matrixWorld.elements;
    return t.set(e[8], e[9], e[10]).normalize();
  }
  /**
   * Abstract method to get intersections between a casted ray and this
   * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
   * implement this method in order to use raycasting.
   *
   * @abstract
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - An array holding the result of the method.
   */
  raycast() {
  }
  /**
   * Executes the callback on this 3D object and all descendants.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverse(t) {
    t(this);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].traverse(t);
  }
  /**
   * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
   * Descendants of invisible 3D objects are not traversed.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverseVisible(t) {
    if (this.visible === !1) return;
    t(this);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].traverseVisible(t);
  }
  /**
   * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverseAncestors(t) {
    const e = this.parent;
    e !== null && (t(e), e.traverseAncestors(t));
  }
  /**
   * Updates the transformation matrix in local space by computing it from the current
   * position, rotation and scale values.
   */
  updateMatrix() {
    this.matrix.compose(this.position, this.quaternion, this.scale), this.matrixWorldNeedsUpdate = !0;
  }
  /**
   * Updates the transformation matrix in world space of this 3D objects and its descendants.
   *
   * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
   * local space. The computation of the local and world matrix can be controlled with the
   * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
   * `true` by default.  Set these flags to `false` if you need more control over the update matrix process.
   *
   * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
   * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
   */
  updateMatrixWorld(t) {
    this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || t) && (this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = !1, t = !0);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].updateMatrixWorld(t);
  }
  /**
   * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
   * update of ancestor and descendant nodes.
   *
   * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
   * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
   */
  updateWorldMatrix(t, e) {
    const i = this.parent;
    if (t === !0 && i !== null && i.updateWorldMatrix(!0, !1), this.matrixAutoUpdate && this.updateMatrix(), this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), e === !0) {
      const n = this.children;
      for (let s = 0, r = n.length; s < r; s++)
        n[s].updateWorldMatrix(!1, !0);
    }
  }
  /**
   * Serializes the 3D object into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized 3D object.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(t) {
    const e = t === void 0 || typeof t == "string", i = {};
    e && (t = {
      geometries: {},
      materials: {},
      textures: {},
      images: {},
      shapes: {},
      skeletons: {},
      animations: {},
      nodes: {}
    }, i.metadata = {
      version: 4.7,
      type: "Object",
      generator: "Object3D.toJSON"
    });
    const n = {};
    n.uuid = this.uuid, n.type = this.type, this.name !== "" && (n.name = this.name), this.castShadow === !0 && (n.castShadow = !0), this.receiveShadow === !0 && (n.receiveShadow = !0), this.visible === !1 && (n.visible = !1), this.frustumCulled === !1 && (n.frustumCulled = !1), this.renderOrder !== 0 && (n.renderOrder = this.renderOrder), Object.keys(this.userData).length > 0 && (n.userData = this.userData), n.layers = this.layers.mask, n.matrix = this.matrix.toArray(), n.up = this.up.toArray(), this.matrixAutoUpdate === !1 && (n.matrixAutoUpdate = !1), this.isInstancedMesh && (n.type = "InstancedMesh", n.count = this.count, n.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (n.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (n.type = "BatchedMesh", n.perObjectFrustumCulled = this.perObjectFrustumCulled, n.sortObjects = this.sortObjects, n.drawRanges = this._drawRanges, n.reservedRanges = this._reservedRanges, n.geometryInfo = this._geometryInfo.map((o) => ({
      ...o,
      boundingBox: o.boundingBox ? o.boundingBox.toJSON() : void 0,
      boundingSphere: o.boundingSphere ? o.boundingSphere.toJSON() : void 0
    })), n.instanceInfo = this._instanceInfo.map((o) => ({ ...o })), n.availableInstanceIds = this._availableInstanceIds.slice(), n.availableGeometryIds = this._availableGeometryIds.slice(), n.nextIndexStart = this._nextIndexStart, n.nextVertexStart = this._nextVertexStart, n.geometryCount = this._geometryCount, n.maxInstanceCount = this._maxInstanceCount, n.maxVertexCount = this._maxVertexCount, n.maxIndexCount = this._maxIndexCount, n.geometryInitialized = this._geometryInitialized, n.matricesTexture = this._matricesTexture.toJSON(t), n.indirectTexture = this._indirectTexture.toJSON(t), this._colorsTexture !== null && (n.colorsTexture = this._colorsTexture.toJSON(t)), this.boundingSphere !== null && (n.boundingSphere = this.boundingSphere.toJSON()), this.boundingBox !== null && (n.boundingBox = this.boundingBox.toJSON()));
    function s(o, l) {
      return o[l.uuid] === void 0 && (o[l.uuid] = l.toJSON(t)), l.uuid;
    }
    if (this.isScene)
      this.background && (this.background.isColor ? n.background = this.background.toJSON() : this.background.isTexture && (n.background = this.background.toJSON(t).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (n.environment = this.environment.toJSON(t).uuid);
    else if (this.isMesh || this.isLine || this.isPoints) {
      n.geometry = s(t.geometries, this.geometry);
      const o = this.geometry.parameters;
      if (o !== void 0 && o.shapes !== void 0) {
        const l = o.shapes;
        if (Array.isArray(l))
          for (let h = 0, c = l.length; h < c; h++) {
            const u = l[h];
            s(t.shapes, u);
          }
        else
          s(t.shapes, l);
      }
    }
    if (this.isSkinnedMesh && (n.bindMode = this.bindMode, n.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (s(t.skeletons, this.skeleton), n.skeleton = this.skeleton.uuid)), this.material !== void 0)
      if (Array.isArray(this.material)) {
        const o = [];
        for (let l = 0, h = this.material.length; l < h; l++)
          o.push(s(t.materials, this.material[l]));
        n.material = o;
      } else
        n.material = s(t.materials, this.material);
    if (this.children.length > 0) {
      n.children = [];
      for (let o = 0; o < this.children.length; o++)
        n.children.push(this.children[o].toJSON(t).object);
    }
    if (this.animations.length > 0) {
      n.animations = [];
      for (let o = 0; o < this.animations.length; o++) {
        const l = this.animations[o];
        n.animations.push(s(t.animations, l));
      }
    }
    if (e) {
      const o = r(t.geometries), l = r(t.materials), h = r(t.textures), c = r(t.images), u = r(t.shapes), d = r(t.skeletons), p = r(t.animations), f = r(t.nodes);
      o.length > 0 && (i.geometries = o), l.length > 0 && (i.materials = l), h.length > 0 && (i.textures = h), c.length > 0 && (i.images = c), u.length > 0 && (i.shapes = u), d.length > 0 && (i.skeletons = d), p.length > 0 && (i.animations = p), f.length > 0 && (i.nodes = f);
    }
    return i.object = n, i;
    function r(o) {
      const l = [];
      for (const h in o) {
        const c = o[h];
        delete c.metadata, l.push(c);
      }
      return l;
    }
  }
  /**
   * Returns a new 3D object with copied values from this instance.
   *
   * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
   * @return {Object3D} A clone of this instance.
   */
  clone(t) {
    return new this.constructor().copy(this, t);
  }
  /**
   * Copies the values of the given 3D object to this instance.
   *
   * @param {Object3D} source - The 3D object to copy.
   * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
   * @return {Object3D} A reference to this instance.
   */
  copy(t, e = !0) {
    if (this.name = t.name, this.up.copy(t.up), this.position.copy(t.position), this.rotation.order = t.rotation.order, this.quaternion.copy(t.quaternion), this.scale.copy(t.scale), this.matrix.copy(t.matrix), this.matrixWorld.copy(t.matrixWorld), this.matrixAutoUpdate = t.matrixAutoUpdate, this.matrixWorldAutoUpdate = t.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = t.matrixWorldNeedsUpdate, this.layers.mask = t.layers.mask, this.visible = t.visible, this.castShadow = t.castShadow, this.receiveShadow = t.receiveShadow, this.frustumCulled = t.frustumCulled, this.renderOrder = t.renderOrder, this.animations = t.animations.slice(), this.userData = JSON.parse(JSON.stringify(t.userData)), e === !0)
      for (let i = 0; i < t.children.length; i++) {
        const n = t.children[i];
        this.add(n.clone());
      }
    return this;
  }
};
le.DEFAULT_UP = /* @__PURE__ */ new E(0, 1, 0);
le.DEFAULT_MATRIX_AUTO_UPDATE = !0;
le.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0;
const Ji = /* @__PURE__ */ new E(), Un = /* @__PURE__ */ new E(), Tu = /* @__PURE__ */ new E(), Bn = /* @__PURE__ */ new E(), Tr = /* @__PURE__ */ new E(), Cr = /* @__PURE__ */ new E(), Hf = /* @__PURE__ */ new E(), Cu = /* @__PURE__ */ new E(), Ru = /* @__PURE__ */ new E(), Pu = /* @__PURE__ */ new E(), Iu = /* @__PURE__ */ new Qt(), Lu = /* @__PURE__ */ new Qt(), Du = /* @__PURE__ */ new Qt();
let bs = class na {
  /**
   * Constructs a new triangle.
   *
   * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
   * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
   * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
   */
  constructor(t = new E(), e = new E(), i = new E()) {
    this.a = t, this.b = e, this.c = i;
  }
  /**
   * Computes the normal vector of a triangle.
   *
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The triangle's normal.
   */
  static getNormal(t, e, i, n) {
    n.subVectors(i, e), Ji.subVectors(t, e), n.cross(Ji);
    const s = n.lengthSq();
    return s > 0 ? n.multiplyScalar(1 / Math.sqrt(s)) : n.set(0, 0, 0);
  }
  /**
   * Computes a barycentric coordinates from the given vector.
   * Returns `null` if the triangle is degenerate.
   *
   * @param {Vector3} point - A point in 3D space.
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The barycentric coordinates for the given point
   */
  static getBarycoord(t, e, i, n, s) {
    Ji.subVectors(n, e), Un.subVectors(i, e), Tu.subVectors(t, e);
    const r = Ji.dot(Ji), o = Ji.dot(Un), l = Ji.dot(Tu), h = Un.dot(Un), c = Un.dot(Tu), u = r * h - o * o;
    if (u === 0)
      return s.set(0, 0, 0), null;
    const d = 1 / u, p = (h * l - o * c) * d, f = (r * c - o * l) * d;
    return s.set(1 - p - f, f, p);
  }
  /**
   * Returns `true` if the given point, when projected onto the plane of the
   * triangle, lies within the triangle.
   *
   * @param {Vector3} point - The point in 3D space to test.
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @return {boolean} Whether the given point, when projected onto the plane of the
   * triangle, lies within the triangle or not.
   */
  static containsPoint(t, e, i, n) {
    return this.getBarycoord(t, e, i, n, Bn) === null ? !1 : Bn.x >= 0 && Bn.y >= 0 && Bn.x + Bn.y <= 1;
  }
  /**
   * Computes the value barycentrically interpolated for the given point on the
   * triangle. Returns `null` if the triangle is degenerate.
   *
   * @param {Vector3} point - Position of interpolated point.
   * @param {Vector3} p1 - The first corner of the triangle.
   * @param {Vector3} p2 - The second corner of the triangle.
   * @param {Vector3} p3 - The third corner of the triangle.
   * @param {Vector3} v1 - Value to interpolate of first vertex.
   * @param {Vector3} v2 - Value to interpolate of second vertex.
   * @param {Vector3} v3 - Value to interpolate of third vertex.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The interpolated value.
   */
  static getInterpolation(t, e, i, n, s, r, o, l) {
    return this.getBarycoord(t, e, i, n, Bn) === null ? (l.x = 0, l.y = 0, "z" in l && (l.z = 0), "w" in l && (l.w = 0), null) : (l.setScalar(0), l.addScaledVector(s, Bn.x), l.addScaledVector(r, Bn.y), l.addScaledVector(o, Bn.z), l);
  }
  /**
   * Computes the value barycentrically interpolated for the given attribute and indices.
   *
   * @param {BufferAttribute} attr - The attribute to interpolate.
   * @param {number} i1 - Index of first vertex.
   * @param {number} i2 - Index of second vertex.
   * @param {number} i3 - Index of third vertex.
   * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The interpolated attribute value.
   */
  static getInterpolatedAttribute(t, e, i, n, s, r) {
    return Iu.setScalar(0), Lu.setScalar(0), Du.setScalar(0), Iu.fromBufferAttribute(t, e), Lu.fromBufferAttribute(t, i), Du.fromBufferAttribute(t, n), r.setScalar(0), r.addScaledVector(Iu, s.x), r.addScaledVector(Lu, s.y), r.addScaledVector(Du, s.z), r;
  }
  /**
   * Returns `true` if the triangle is oriented towards the given direction.
   *
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @param {Vector3} direction - The (normalized) direction vector.
   * @return {boolean} Whether the triangle is oriented towards the given direction or not.
   */
  static isFrontFacing(t, e, i, n) {
    return Ji.subVectors(i, e), Un.subVectors(t, e), Ji.cross(Un).dot(n) < 0;
  }
  /**
   * Sets the triangle's vertices by copying the given values.
   *
   * @param {Vector3} a - The first corner of the triangle.
   * @param {Vector3} b - The second corner of the triangle.
   * @param {Vector3} c - The third corner of the triangle.
   * @return {Triangle} A reference to this triangle.
   */
  set(t, e, i) {
    return this.a.copy(t), this.b.copy(e), this.c.copy(i), this;
  }
  /**
   * Sets the triangle's vertices by copying the given array values.
   *
   * @param {Array<Vector3>} points - An array with 3D points.
   * @param {number} i0 - The array index representing the first corner of the triangle.
   * @param {number} i1 - The array index representing the second corner of the triangle.
   * @param {number} i2 - The array index representing the third corner of the triangle.
   * @return {Triangle} A reference to this triangle.
   */
  setFromPointsAndIndices(t, e, i, n) {
    return this.a.copy(t[e]), this.b.copy(t[i]), this.c.copy(t[n]), this;
  }
  /**
   * Sets the triangle's vertices by copying the given attribute values.
   *
   * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
   * @param {number} i0 - The attribute index representing the first corner of the triangle.
   * @param {number} i1 - The attribute index representing the second corner of the triangle.
   * @param {number} i2 - The attribute index representing the third corner of the triangle.
   * @return {Triangle} A reference to this triangle.
   */
  setFromAttributeAndIndices(t, e, i, n) {
    return this.a.fromBufferAttribute(t, e), this.b.fromBufferAttribute(t, i), this.c.fromBufferAttribute(t, n), this;
  }
  /**
   * Returns a new triangle with copied values from this instance.
   *
   * @return {Triangle} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given triangle to this instance.
   *
   * @param {Triangle} triangle - The triangle to copy.
   * @return {Triangle} A reference to this triangle.
   */
  copy(t) {
    return this.a.copy(t.a), this.b.copy(t.b), this.c.copy(t.c), this;
  }
  /**
   * Computes the area of the triangle.
   *
   * @return {number} The triangle's area.
   */
  getArea() {
    return Ji.subVectors(this.c, this.b), Un.subVectors(this.a, this.b), Ji.cross(Un).length() * 0.5;
  }
  /**
   * Computes the midpoint of the triangle.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The triangle's midpoint.
   */
  getMidpoint(t) {
    return t.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  }
  /**
   * Computes the normal of the triangle.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The triangle's normal.
   */
  getNormal(t) {
    return na.getNormal(this.a, this.b, this.c, t);
  }
  /**
   * Computes a plane the triangle lies within.
   *
   * @param {Plane} target - The target vector that is used to store the method's result.
   * @return {Plane} The plane the triangle lies within.
   */
  getPlane(t) {
    return t.setFromCoplanarPoints(this.a, this.b, this.c);
  }
  /**
   * Computes a barycentric coordinates from the given vector.
   * Returns `null` if the triangle is degenerate.
   *
   * @param {Vector3} point - A point in 3D space.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The barycentric coordinates for the given point
   */
  getBarycoord(t, e) {
    return na.getBarycoord(t, this.a, this.b, this.c, e);
  }
  /**
   * Computes the value barycentrically interpolated for the given point on the
   * triangle. Returns `null` if the triangle is degenerate.
   *
   * @param {Vector3} point - Position of interpolated point.
   * @param {Vector3} v1 - Value to interpolate of first vertex.
   * @param {Vector3} v2 - Value to interpolate of second vertex.
   * @param {Vector3} v3 - Value to interpolate of third vertex.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The interpolated value.
   */
  getInterpolation(t, e, i, n, s) {
    return na.getInterpolation(t, this.a, this.b, this.c, e, i, n, s);
  }
  /**
   * Returns `true` if the given point, when projected onto the plane of the
   * triangle, lies within the triangle.
   *
   * @param {Vector3} point - The point in 3D space to test.
   * @return {boolean} Whether the given point, when projected onto the plane of the
   * triangle, lies within the triangle or not.
   */
  containsPoint(t) {
    return na.containsPoint(t, this.a, this.b, this.c);
  }
  /**
   * Returns `true` if the triangle is oriented towards the given direction.
   *
   * @param {Vector3} direction - The (normalized) direction vector.
   * @return {boolean} Whether the triangle is oriented towards the given direction or not.
   */
  isFrontFacing(t) {
    return na.isFrontFacing(this.a, this.b, this.c, t);
  }
  /**
   * Returns `true` if this triangle intersects with the given box.
   *
   * @param {Box3} box - The box to intersect.
   * @return {boolean} Whether this triangle intersects with the given box or not.
   */
  intersectsBox(t) {
    return t.intersectsTriangle(this);
  }
  /**
   * Returns the closest point on the triangle to the given point.
   *
   * @param {Vector3} p - The point to compute the closest point for.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The closest point on the triangle.
   */
  closestPointToPoint(t, e) {
    const i = this.a, n = this.b, s = this.c;
    let r, o;
    Tr.subVectors(n, i), Cr.subVectors(s, i), Cu.subVectors(t, i);
    const l = Tr.dot(Cu), h = Cr.dot(Cu);
    if (l <= 0 && h <= 0)
      return e.copy(i);
    Ru.subVectors(t, n);
    const c = Tr.dot(Ru), u = Cr.dot(Ru);
    if (c >= 0 && u <= c)
      return e.copy(n);
    const d = l * u - c * h;
    if (d <= 0 && l >= 0 && c <= 0)
      return r = l / (l - c), e.copy(i).addScaledVector(Tr, r);
    Pu.subVectors(t, s);
    const p = Tr.dot(Pu), f = Cr.dot(Pu);
    if (f >= 0 && p <= f)
      return e.copy(s);
    const y = p * h - l * f;
    if (y <= 0 && h >= 0 && f <= 0)
      return o = h / (h - f), e.copy(i).addScaledVector(Cr, o);
    const g = c * f - p * u;
    if (g <= 0 && u - c >= 0 && p - f >= 0)
      return Hf.subVectors(s, n), o = (u - c) / (u - c + (p - f)), e.copy(n).addScaledVector(Hf, o);
    const m = 1 / (g + y + d);
    return r = y * m, o = d * m, e.copy(i).addScaledVector(Tr, r).addScaledVector(Cr, o);
  }
  /**
   * Returns `true` if this triangle is equal with the given one.
   *
   * @param {Triangle} triangle - The triangle to test for equality.
   * @return {boolean} Whether this triangle is equal with the given one.
   */
  equals(t) {
    return t.a.equals(this.a) && t.b.equals(this.b) && t.c.equals(this.c);
  }
};
const My = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
}, hs = { h: 0, s: 0, l: 0 }, il = { h: 0, s: 0, l: 0 };
function Fu(a, t, e) {
  return e < 0 && (e += 1), e > 1 && (e -= 1), e < 1 / 6 ? a + (t - a) * 6 * e : e < 1 / 2 ? t : e < 2 / 3 ? a + (t - a) * 6 * (2 / 3 - e) : a;
}
let ct = class {
  /**
   * Constructs a new color.
   *
   * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
   * and that method is used throughout the rest of the documentation.
   *
   * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
   * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
   * @param {number} [g] - The green component.
   * @param {number} [b] - The blue component.
   */
  constructor(t, e, i) {
    return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(t, e, i);
  }
  /**
   * Sets the colors's components from the given values.
   *
   * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
   * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
   * @param {number} [g] - The green component.
   * @param {number} [b] - The blue component.
   * @return {Color} A reference to this color.
   */
  set(t, e, i) {
    if (e === void 0 && i === void 0) {
      const n = t;
      n && n.isColor ? this.copy(n) : typeof n == "number" ? this.setHex(n) : typeof n == "string" && this.setStyle(n);
    } else
      this.setRGB(t, e, i);
    return this;
  }
  /**
   * Sets the colors's components to the given scalar value.
   *
   * @param {number} scalar - The scalar value.
   * @return {Color} A reference to this color.
   */
  setScalar(t) {
    return this.r = t, this.g = t, this.b = t, this;
  }
  /**
   * Sets this color from a hexadecimal value.
   *
   * @param {number} hex - The hexadecimal value.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setHex(t, e = ri) {
    return t = Math.floor(t), this.r = (t >> 16 & 255) / 255, this.g = (t >> 8 & 255) / 255, this.b = (t & 255) / 255, ee.colorSpaceToWorking(this, e), this;
  }
  /**
   * Sets this color from RGB values.
   *
   * @param {number} r - Red channel value between `0.0` and `1.0`.
   * @param {number} g - Green channel value between `0.0` and `1.0`.
   * @param {number} b - Blue channel value between `0.0` and `1.0`.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setRGB(t, e, i, n = ee.workingColorSpace) {
    return this.r = t, this.g = e, this.b = i, ee.colorSpaceToWorking(this, n), this;
  }
  /**
   * Sets this color from RGB values.
   *
   * @param {number} h - Hue value between `0.0` and `1.0`.
   * @param {number} s - Saturation value between `0.0` and `1.0`.
   * @param {number} l - Lightness value between `0.0` and `1.0`.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setHSL(t, e, i, n = ee.workingColorSpace) {
    if (t = Up(t, 1), e = kt(e, 0, 1), i = kt(i, 0, 1), e === 0)
      this.r = this.g = this.b = i;
    else {
      const s = i <= 0.5 ? i * (1 + e) : i + e - i * e, r = 2 * i - s;
      this.r = Fu(r, s, t + 1 / 3), this.g = Fu(r, s, t), this.b = Fu(r, s, t - 1 / 3);
    }
    return ee.colorSpaceToWorking(this, n), this;
  }
  /**
   * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
   * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
   * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
   * all 140 color names are supported).
   *
   * @param {string} style - Color as a CSS-style string.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setStyle(t, e = ri) {
    function i(s) {
      s !== void 0 && parseFloat(s) < 1 && console.warn("THREE.Color: Alpha component of " + t + " will be ignored.");
    }
    let n;
    if (n = /^(\w+)\(([^\)]*)\)/.exec(t)) {
      let s;
      const r = n[1], o = n[2];
      switch (r) {
        case "rgb":
        case "rgba":
          if (s = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setRGB(
              Math.min(255, parseInt(s[1], 10)) / 255,
              Math.min(255, parseInt(s[2], 10)) / 255,
              Math.min(255, parseInt(s[3], 10)) / 255,
              e
            );
          if (s = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setRGB(
              Math.min(100, parseInt(s[1], 10)) / 100,
              Math.min(100, parseInt(s[2], 10)) / 100,
              Math.min(100, parseInt(s[3], 10)) / 100,
              e
            );
          break;
        case "hsl":
        case "hsla":
          if (s = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setHSL(
              parseFloat(s[1]) / 360,
              parseFloat(s[2]) / 100,
              parseFloat(s[3]) / 100,
              e
            );
          break;
        default:
          console.warn("THREE.Color: Unknown color model " + t);
      }
    } else if (n = /^\#([A-Fa-f\d]+)$/.exec(t)) {
      const s = n[1], r = s.length;
      if (r === 3)
        return this.setRGB(
          parseInt(s.charAt(0), 16) / 15,
          parseInt(s.charAt(1), 16) / 15,
          parseInt(s.charAt(2), 16) / 15,
          e
        );
      if (r === 6)
        return this.setHex(parseInt(s, 16), e);
      console.warn("THREE.Color: Invalid hex color " + t);
    } else if (t && t.length > 0)
      return this.setColorName(t, e);
    return this;
  }
  /**
   * Sets this color from a color name. Faster than {@link Color#setStyle} if
   * you don't need the other CSS-style formats.
   *
   * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
   * ```js
   * Color.NAMES.aliceblue // returns 0xF0F8FF
   * ```
   *
   * @param {string} style - The color name.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setColorName(t, e = ri) {
    const i = My[t.toLowerCase()];
    return i !== void 0 ? this.setHex(i, e) : console.warn("THREE.Color: Unknown color " + t), this;
  }
  /**
   * Returns a new color with copied values from this instance.
   *
   * @return {Color} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.r, this.g, this.b);
  }
  /**
   * Copies the values of the given color to this instance.
   *
   * @param {Color} color - The color to copy.
   * @return {Color} A reference to this color.
   */
  copy(t) {
    return this.r = t.r, this.g = t.g, this.b = t.b, this;
  }
  /**
   * Copies the given color into this color, and then converts this color from
   * `SRGBColorSpace` to `LinearSRGBColorSpace`.
   *
   * @param {Color} color - The color to copy/convert.
   * @return {Color} A reference to this color.
   */
  copySRGBToLinear(t) {
    return this.r = jn(t.r), this.g = jn(t.g), this.b = jn(t.b), this;
  }
  /**
   * Copies the given color into this color, and then converts this color from
   * `LinearSRGBColorSpace` to `SRGBColorSpace`.
   *
   * @param {Color} color - The color to copy/convert.
   * @return {Color} A reference to this color.
   */
  copyLinearToSRGB(t) {
    return this.r = oa(t.r), this.g = oa(t.g), this.b = oa(t.b), this;
  }
  /**
   * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
   *
   * @return {Color} A reference to this color.
   */
  convertSRGBToLinear() {
    return this.copySRGBToLinear(this), this;
  }
  /**
   * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
   *
   * @return {Color} A reference to this color.
   */
  convertLinearToSRGB() {
    return this.copyLinearToSRGB(this), this;
  }
  /**
   * Returns the hexadecimal value of this color.
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {number} The hexadecimal value.
   */
  getHex(t = ri) {
    return ee.workingToColorSpace(Ke.copy(this), t), Math.round(kt(Ke.r * 255, 0, 255)) * 65536 + Math.round(kt(Ke.g * 255, 0, 255)) * 256 + Math.round(kt(Ke.b * 255, 0, 255));
  }
  /**
   * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {string} The hexadecimal value as a string.
   */
  getHexString(t = ri) {
    return ("000000" + this.getHex(t).toString(16)).slice(-6);
  }
  /**
   * Converts the colors RGB values into the HSL format and stores them into the
   * given target object.
   *
   * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {{h:number,s:number,l:number}} The HSL representation of this color.
   */
  getHSL(t, e = ee.workingColorSpace) {
    ee.workingToColorSpace(Ke.copy(this), e);
    const i = Ke.r, n = Ke.g, s = Ke.b, r = Math.max(i, n, s), o = Math.min(i, n, s);
    let l, h;
    const c = (o + r) / 2;
    if (o === r)
      l = 0, h = 0;
    else {
      const u = r - o;
      switch (h = c <= 0.5 ? u / (r + o) : u / (2 - r - o), r) {
        case i:
          l = (n - s) / u + (n < s ? 6 : 0);
          break;
        case n:
          l = (s - i) / u + 2;
          break;
        case s:
          l = (i - n) / u + 4;
          break;
      }
      l /= 6;
    }
    return t.h = l, t.s = h, t.l = c, t;
  }
  /**
   * Returns the RGB values of this color and stores them into the given target object.
   *
   * @param {Color} target - The target color that is used to store the method's result.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} The RGB representation of this color.
   */
  getRGB(t, e = ee.workingColorSpace) {
    return ee.workingToColorSpace(Ke.copy(this), e), t.r = Ke.r, t.g = Ke.g, t.b = Ke.b, t;
  }
  /**
   * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {string} The CSS representation of this color.
   */
  getStyle(t = ri) {
    ee.workingToColorSpace(Ke.copy(this), t);
    const e = Ke.r, i = Ke.g, n = Ke.b;
    return t !== ri ? `color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})` : `rgb(${Math.round(e * 255)},${Math.round(i * 255)},${Math.round(n * 255)})`;
  }
  /**
   * Adds the given HSL values to this color's values.
   * Internally, this converts the color's RGB values to HSL, adds HSL
   * and then converts the color back to RGB.
   *
   * @param {number} h - Hue value between `0.0` and `1.0`.
   * @param {number} s - Saturation value between `0.0` and `1.0`.
   * @param {number} l - Lightness value between `0.0` and `1.0`.
   * @return {Color} A reference to this color.
   */
  offsetHSL(t, e, i) {
    return this.getHSL(hs), this.setHSL(hs.h + t, hs.s + e, hs.l + i);
  }
  /**
   * Adds the RGB values of the given color to the RGB values of this color.
   *
   * @param {Color} color - The color to add.
   * @return {Color} A reference to this color.
   */
  add(t) {
    return this.r += t.r, this.g += t.g, this.b += t.b, this;
  }
  /**
   * Adds the RGB values of the given colors and stores the result in this instance.
   *
   * @param {Color} color1 - The first color.
   * @param {Color} color2 - The second color.
   * @return {Color} A reference to this color.
   */
  addColors(t, e) {
    return this.r = t.r + e.r, this.g = t.g + e.g, this.b = t.b + e.b, this;
  }
  /**
   * Adds the given scalar value to the RGB values of this color.
   *
   * @param {number} s - The scalar to add.
   * @return {Color} A reference to this color.
   */
  addScalar(t) {
    return this.r += t, this.g += t, this.b += t, this;
  }
  /**
   * Subtracts the RGB values of the given color from the RGB values of this color.
   *
   * @param {Color} color - The color to subtract.
   * @return {Color} A reference to this color.
   */
  sub(t) {
    return this.r = Math.max(0, this.r - t.r), this.g = Math.max(0, this.g - t.g), this.b = Math.max(0, this.b - t.b), this;
  }
  /**
   * Multiplies the RGB values of the given color with the RGB values of this color.
   *
   * @param {Color} color - The color to multiply.
   * @return {Color} A reference to this color.
   */
  multiply(t) {
    return this.r *= t.r, this.g *= t.g, this.b *= t.b, this;
  }
  /**
   * Multiplies the given scalar value with the RGB values of this color.
   *
   * @param {number} s - The scalar to multiply.
   * @return {Color} A reference to this color.
   */
  multiplyScalar(t) {
    return this.r *= t, this.g *= t, this.b *= t, this;
  }
  /**
   * Linearly interpolates this color's RGB values toward the RGB values of the
   * given color. The alpha argument can be thought of as the ratio between
   * the two colors, where `0.0` is this color and `1.0` is the first argument.
   *
   * @param {Color} color - The color to converge on.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerp(t, e) {
    return this.r += (t.r - this.r) * e, this.g += (t.g - this.g) * e, this.b += (t.b - this.b) * e, this;
  }
  /**
   * Linearly interpolates between the given colors and stores the result in this instance.
   * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
   * is the first and `1.0` is the second color.
   *
   * @param {Color} color1 - The first color.
   * @param {Color} color2 - The second color.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerpColors(t, e, i) {
    return this.r = t.r + (e.r - t.r) * i, this.g = t.g + (e.g - t.g) * i, this.b = t.b + (e.b - t.b) * i, this;
  }
  /**
   * Linearly interpolates this color's HSL values toward the HSL values of the
   * given color. It differs from {@link Color#lerp} by not interpolating straight
   * from one color to the other, but instead going through all the hues in between
   * those two colors. The alpha argument can be thought of as the ratio between
   * the two colors, where 0.0 is this color and 1.0 is the first argument.
   *
   * @param {Color} color - The color to converge on.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerpHSL(t, e) {
    this.getHSL(hs), t.getHSL(il);
    const i = fo(hs.h, il.h, e), n = fo(hs.s, il.s, e), s = fo(hs.l, il.l, e);
    return this.setHSL(i, n, s), this;
  }
  /**
   * Sets the color's RGB components from the given 3D vector.
   *
   * @param {Vector3} v - The vector to set.
   * @return {Color} A reference to this color.
   */
  setFromVector3(t) {
    return this.r = t.x, this.g = t.y, this.b = t.z, this;
  }
  /**
   * Transforms this color with the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix.
   * @return {Color} A reference to this color.
   */
  applyMatrix3(t) {
    const e = this.r, i = this.g, n = this.b, s = t.elements;
    return this.r = s[0] * e + s[3] * i + s[6] * n, this.g = s[1] * e + s[4] * i + s[7] * n, this.b = s[2] * e + s[5] * i + s[8] * n, this;
  }
  /**
   * Returns `true` if this color is equal with the given one.
   *
   * @param {Color} c - The color to test for equality.
   * @return {boolean} Whether this bounding color is equal with the given one.
   */
  equals(t) {
    return t.r === this.r && t.g === this.g && t.b === this.b;
  }
  /**
   * Sets this color's RGB components from the given array.
   *
   * @param {Array<number>} array - An array holding the RGB values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Color} A reference to this color.
   */
  fromArray(t, e = 0) {
    return this.r = t[e], this.g = t[e + 1], this.b = t[e + 2], this;
  }
  /**
   * Writes the RGB components of this color to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the color components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The color components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this.r, t[e + 1] = this.g, t[e + 2] = this.b, t;
  }
  /**
   * Sets the components of this color from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding color data.
   * @param {number} index - The index into the attribute.
   * @return {Color} A reference to this color.
   */
  fromBufferAttribute(t, e) {
    return this.r = t.getX(e), this.g = t.getY(e), this.b = t.getZ(e), this;
  }
  /**
   * This methods defines the serialization result of this class. Returns the color
   * as a hexadecimal value.
   *
   * @return {number} The hexadecimal value.
   */
  toJSON() {
    return this.getHex();
  }
  *[Symbol.iterator]() {
    yield this.r, yield this.g, yield this.b;
  }
};
const Ke = /* @__PURE__ */ new ct();
ct.NAMES = My;
let Ev = 0, hi = class extends Ei {
  /**
   * Constructs a new material.
   */
  constructor() {
    super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: Ev++ }), this.uuid = Oi(), this.name = "", this.type = "Material", this.blending = ws, this.side = $i, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = Ih, this.blendDst = Lh, this.blendEquation = vs, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new ct(0, 0, 0), this.blendAlpha = 0, this.depthFunc = pr, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = To, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = er, this.stencilZFail = er, this.stencilZPass = er, this.stencilWrite = !1, this.clippingPlanes = null, this.clipIntersection = !1, this.clipShadows = !1, this.shadowSide = null, this.colorWrite = !0, this.precision = null, this.polygonOffset = !1, this.polygonOffsetFactor = 0, this.polygonOffsetUnits = 0, this.dithering = !1, this.alphaToCoverage = !1, this.premultipliedAlpha = !1, this.forceSinglePass = !1, this.allowOverride = !0, this.visible = !0, this.toneMapped = !0, this.userData = {}, this.version = 0, this._alphaTest = 0;
  }
  /**
   * Sets the alpha value to be used when running an alpha test. The material
   * will not be rendered if the opacity is lower than this value.
   *
   * @type {number}
   * @readonly
   * @default 0
   */
  get alphaTest() {
    return this._alphaTest;
  }
  set alphaTest(t) {
    this._alphaTest > 0 != t > 0 && this.version++, this._alphaTest = t;
  }
  /**
   * An optional callback that is executed immediately before the material is used to render a 3D object.
   *
   * This method can only be used when rendering with {@link WebGLRenderer}.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {Scene} scene - The scene.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Object3D} object - The 3D object.
   * @param {Object} group - The geometry group data.
   */
  onBeforeRender() {
  }
  /**
   * An optional callback that is executed immediately before the shader
   * program is compiled. This function is called with the shader source code
   * as a parameter. Useful for the modification of built-in materials.
   *
   * This method can only be used when rendering with {@link WebGLRenderer}. The
   * recommended approach when customizing materials is to use `WebGPURenderer` with the new
   * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
   *
   * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
   * @param {WebGLRenderer} renderer - A reference to the renderer.
   */
  onBeforeCompile() {
  }
  /**
   * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
   * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
   * shader or recompile the shader for this material as needed.
   *
   * This method can only be used when rendering with {@link WebGLRenderer}.
   *
   * @return {string} The custom program cache key.
   */
  customProgramCacheKey() {
    return this.onBeforeCompile.toString();
  }
  /**
   * This method can be used to set default values from parameter objects.
   * It is a generic implementation so it can be used with different types
   * of materials.
   *
   * @param {Object} [values] - The material values to set.
   */
  setValues(t) {
    if (t !== void 0)
      for (const e in t) {
        const i = t[e];
        if (i === void 0) {
          console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);
          continue;
        }
        const n = this[e];
        if (n === void 0) {
          console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`);
          continue;
        }
        n && n.isColor ? n.set(i) : n && n.isVector3 && i && i.isVector3 ? n.copy(i) : this[e] = i;
      }
  }
  /**
   * Serializes the material into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized material.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(t) {
    const e = t === void 0 || typeof t == "string";
    e && (t = {
      textures: {},
      images: {}
    });
    const i = {
      metadata: {
        version: 4.7,
        type: "Material",
        generator: "Material.toJSON"
      }
    };
    i.uuid = this.uuid, i.type = this.type, this.name !== "" && (i.name = this.name), this.color && this.color.isColor && (i.color = this.color.getHex()), this.roughness !== void 0 && (i.roughness = this.roughness), this.metalness !== void 0 && (i.metalness = this.metalness), this.sheen !== void 0 && (i.sheen = this.sheen), this.sheenColor && this.sheenColor.isColor && (i.sheenColor = this.sheenColor.getHex()), this.sheenRoughness !== void 0 && (i.sheenRoughness = this.sheenRoughness), this.emissive && this.emissive.isColor && (i.emissive = this.emissive.getHex()), this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1 && (i.emissiveIntensity = this.emissiveIntensity), this.specular && this.specular.isColor && (i.specular = this.specular.getHex()), this.specularIntensity !== void 0 && (i.specularIntensity = this.specularIntensity), this.specularColor && this.specularColor.isColor && (i.specularColor = this.specularColor.getHex()), this.shininess !== void 0 && (i.shininess = this.shininess), this.clearcoat !== void 0 && (i.clearcoat = this.clearcoat), this.clearcoatRoughness !== void 0 && (i.clearcoatRoughness = this.clearcoatRoughness), this.clearcoatMap && this.clearcoatMap.isTexture && (i.clearcoatMap = this.clearcoatMap.toJSON(t).uuid), this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture && (i.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(t).uuid), this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture && (i.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(t).uuid, i.clearcoatNormalScale = this.clearcoatNormalScale.toArray()), this.sheenColorMap && this.sheenColorMap.isTexture && (i.sheenColorMap = this.sheenColorMap.toJSON(t).uuid), this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture && (i.sheenRoughnessMap = this.sheenRoughnessMap.toJSON(t).uuid), this.dispersion !== void 0 && (i.dispersion = this.dispersion), this.iridescence !== void 0 && (i.iridescence = this.iridescence), this.iridescenceIOR !== void 0 && (i.iridescenceIOR = this.iridescenceIOR), this.iridescenceThicknessRange !== void 0 && (i.iridescenceThicknessRange = this.iridescenceThicknessRange), this.iridescenceMap && this.iridescenceMap.isTexture && (i.iridescenceMap = this.iridescenceMap.toJSON(t).uuid), this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture && (i.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(t).uuid), this.anisotropy !== void 0 && (i.anisotropy = this.anisotropy), this.anisotropyRotation !== void 0 && (i.anisotropyRotation = this.anisotropyRotation), this.anisotropyMap && this.anisotropyMap.isTexture && (i.anisotropyMap = this.anisotropyMap.toJSON(t).uuid), this.map && this.map.isTexture && (i.map = this.map.toJSON(t).uuid), this.matcap && this.matcap.isTexture && (i.matcap = this.matcap.toJSON(t).uuid), this.alphaMap && this.alphaMap.isTexture && (i.alphaMap = this.alphaMap.toJSON(t).uuid), this.lightMap && this.lightMap.isTexture && (i.lightMap = this.lightMap.toJSON(t).uuid, i.lightMapIntensity = this.lightMapIntensity), this.aoMap && this.aoMap.isTexture && (i.aoMap = this.aoMap.toJSON(t).uuid, i.aoMapIntensity = this.aoMapIntensity), this.bumpMap && this.bumpMap.isTexture && (i.bumpMap = this.bumpMap.toJSON(t).uuid, i.bumpScale = this.bumpScale), this.normalMap && this.normalMap.isTexture && (i.normalMap = this.normalMap.toJSON(t).uuid, i.normalMapType = this.normalMapType, i.normalScale = this.normalScale.toArray()), this.displacementMap && this.displacementMap.isTexture && (i.displacementMap = this.displacementMap.toJSON(t).uuid, i.displacementScale = this.displacementScale, i.displacementBias = this.displacementBias), this.roughnessMap && this.roughnessMap.isTexture && (i.roughnessMap = this.roughnessMap.toJSON(t).uuid), this.metalnessMap && this.metalnessMap.isTexture && (i.metalnessMap = this.metalnessMap.toJSON(t).uuid), this.emissiveMap && this.emissiveMap.isTexture && (i.emissiveMap = this.emissiveMap.toJSON(t).uuid), this.specularMap && this.specularMap.isTexture && (i.specularMap = this.specularMap.toJSON(t).uuid), this.specularIntensityMap && this.specularIntensityMap.isTexture && (i.specularIntensityMap = this.specularIntensityMap.toJSON(t).uuid), this.specularColorMap && this.specularColorMap.isTexture && (i.specularColorMap = this.specularColorMap.toJSON(t).uuid), this.envMap && this.envMap.isTexture && (i.envMap = this.envMap.toJSON(t).uuid, this.combine !== void 0 && (i.combine = this.combine)), this.envMapRotation !== void 0 && (i.envMapRotation = this.envMapRotation.toArray()), this.envMapIntensity !== void 0 && (i.envMapIntensity = this.envMapIntensity), this.reflectivity !== void 0 && (i.reflectivity = this.reflectivity), this.refractionRatio !== void 0 && (i.refractionRatio = this.refractionRatio), this.gradientMap && this.gradientMap.isTexture && (i.gradientMap = this.gradientMap.toJSON(t).uuid), this.transmission !== void 0 && (i.transmission = this.transmission), this.transmissionMap && this.transmissionMap.isTexture && (i.transmissionMap = this.transmissionMap.toJSON(t).uuid), this.thickness !== void 0 && (i.thickness = this.thickness), this.thicknessMap && this.thicknessMap.isTexture && (i.thicknessMap = this.thicknessMap.toJSON(t).uuid), this.attenuationDistance !== void 0 && this.attenuationDistance !== 1 / 0 && (i.attenuationDistance = this.attenuationDistance), this.attenuationColor !== void 0 && (i.attenuationColor = this.attenuationColor.getHex()), this.size !== void 0 && (i.size = this.size), this.shadowSide !== null && (i.shadowSide = this.shadowSide), this.sizeAttenuation !== void 0 && (i.sizeAttenuation = this.sizeAttenuation), this.blending !== ws && (i.blending = this.blending), this.side !== $i && (i.side = this.side), this.vertexColors === !0 && (i.vertexColors = !0), this.opacity < 1 && (i.opacity = this.opacity), this.transparent === !0 && (i.transparent = !0), this.blendSrc !== Ih && (i.blendSrc = this.blendSrc), this.blendDst !== Lh && (i.blendDst = this.blendDst), this.blendEquation !== vs && (i.blendEquation = this.blendEquation), this.blendSrcAlpha !== null && (i.blendSrcAlpha = this.blendSrcAlpha), this.blendDstAlpha !== null && (i.blendDstAlpha = this.blendDstAlpha), this.blendEquationAlpha !== null && (i.blendEquationAlpha = this.blendEquationAlpha), this.blendColor && this.blendColor.isColor && (i.blendColor = this.blendColor.getHex()), this.blendAlpha !== 0 && (i.blendAlpha = this.blendAlpha), this.depthFunc !== pr && (i.depthFunc = this.depthFunc), this.depthTest === !1 && (i.depthTest = this.depthTest), this.depthWrite === !1 && (i.depthWrite = this.depthWrite), this.colorWrite === !1 && (i.colorWrite = this.colorWrite), this.stencilWriteMask !== 255 && (i.stencilWriteMask = this.stencilWriteMask), this.stencilFunc !== To && (i.stencilFunc = this.stencilFunc), this.stencilRef !== 0 && (i.stencilRef = this.stencilRef), this.stencilFuncMask !== 255 && (i.stencilFuncMask = this.stencilFuncMask), this.stencilFail !== er && (i.stencilFail = this.stencilFail), this.stencilZFail !== er && (i.stencilZFail = this.stencilZFail), this.stencilZPass !== er && (i.stencilZPass = this.stencilZPass), this.stencilWrite === !0 && (i.stencilWrite = this.stencilWrite), this.rotation !== void 0 && this.rotation !== 0 && (i.rotation = this.rotation), this.polygonOffset === !0 && (i.polygonOffset = !0), this.polygonOffsetFactor !== 0 && (i.polygonOffsetFactor = this.polygonOffsetFactor), this.polygonOffsetUnits !== 0 && (i.polygonOffsetUnits = this.polygonOffsetUnits), this.linewidth !== void 0 && this.linewidth !== 1 && (i.linewidth = this.linewidth), this.dashSize !== void 0 && (i.dashSize = this.dashSize), this.gapSize !== void 0 && (i.gapSize = this.gapSize), this.scale !== void 0 && (i.scale = this.scale), this.dithering === !0 && (i.dithering = !0), this.alphaTest > 0 && (i.alphaTest = this.alphaTest), this.alphaHash === !0 && (i.alphaHash = !0), this.alphaToCoverage === !0 && (i.alphaToCoverage = !0), this.premultipliedAlpha === !0 && (i.premultipliedAlpha = !0), this.forceSinglePass === !0 && (i.forceSinglePass = !0), this.wireframe === !0 && (i.wireframe = !0), this.wireframeLinewidth > 1 && (i.wireframeLinewidth = this.wireframeLinewidth), this.wireframeLinecap !== "round" && (i.wireframeLinecap = this.wireframeLinecap), this.wireframeLinejoin !== "round" && (i.wireframeLinejoin = this.wireframeLinejoin), this.flatShading === !0 && (i.flatShading = !0), this.visible === !1 && (i.visible = !1), this.toneMapped === !1 && (i.toneMapped = !1), this.fog === !1 && (i.fog = !1), Object.keys(this.userData).length > 0 && (i.userData = this.userData);
    function n(s) {
      const r = [];
      for (const o in s) {
        const l = s[o];
        delete l.metadata, r.push(l);
      }
      return r;
    }
    if (e) {
      const s = n(t.textures), r = n(t.images);
      s.length > 0 && (i.textures = s), r.length > 0 && (i.images = r);
    }
    return i;
  }
  /**
   * Returns a new material with copied values from this instance.
   *
   * @return {Material} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given material to this instance.
   *
   * @param {Material} source - The material to copy.
   * @return {Material} A reference to this instance.
   */
  copy(t) {
    this.name = t.name, this.blending = t.blending, this.side = t.side, this.vertexColors = t.vertexColors, this.opacity = t.opacity, this.transparent = t.transparent, this.blendSrc = t.blendSrc, this.blendDst = t.blendDst, this.blendEquation = t.blendEquation, this.blendSrcAlpha = t.blendSrcAlpha, this.blendDstAlpha = t.blendDstAlpha, this.blendEquationAlpha = t.blendEquationAlpha, this.blendColor.copy(t.blendColor), this.blendAlpha = t.blendAlpha, this.depthFunc = t.depthFunc, this.depthTest = t.depthTest, this.depthWrite = t.depthWrite, this.stencilWriteMask = t.stencilWriteMask, this.stencilFunc = t.stencilFunc, this.stencilRef = t.stencilRef, this.stencilFuncMask = t.stencilFuncMask, this.stencilFail = t.stencilFail, this.stencilZFail = t.stencilZFail, this.stencilZPass = t.stencilZPass, this.stencilWrite = t.stencilWrite;
    const e = t.clippingPlanes;
    let i = null;
    if (e !== null) {
      const n = e.length;
      i = new Array(n);
      for (let s = 0; s !== n; ++s)
        i[s] = e[s].clone();
    }
    return this.clippingPlanes = i, this.clipIntersection = t.clipIntersection, this.clipShadows = t.clipShadows, this.shadowSide = t.shadowSide, this.colorWrite = t.colorWrite, this.precision = t.precision, this.polygonOffset = t.polygonOffset, this.polygonOffsetFactor = t.polygonOffsetFactor, this.polygonOffsetUnits = t.polygonOffsetUnits, this.dithering = t.dithering, this.alphaTest = t.alphaTest, this.alphaHash = t.alphaHash, this.alphaToCoverage = t.alphaToCoverage, this.premultipliedAlpha = t.premultipliedAlpha, this.forceSinglePass = t.forceSinglePass, this.visible = t.visible, this.toneMapped = t.toneMapped, this.userData = JSON.parse(JSON.stringify(t.userData)), this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires Material#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  /**
   * Setting this property to `true` indicates the engine the material
   * needs to be recompiled.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
}, li = class extends hi {
  /**
   * Constructs a new mesh basic material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshBasicMaterial = !0, this.type = "MeshBasicMaterial", this.color = new ct(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new fn(), this.combine = zo, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.map = t.map, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.specularMap = t.specularMap, this.alphaMap = t.alphaMap, this.envMap = t.envMap, this.envMapRotation.copy(t.envMapRotation), this.combine = t.combine, this.reflectivity = t.reflectivity, this.refractionRatio = t.refractionRatio, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.fog = t.fog, this;
  }
};
const Xn = /* @__PURE__ */ Tv();
function Tv() {
  const a = new ArrayBuffer(4), t = new Float32Array(a), e = new Uint32Array(a), i = new Uint32Array(512), n = new Uint32Array(512);
  for (let l = 0; l < 256; ++l) {
    const h = l - 127;
    h < -27 ? (i[l] = 0, i[l | 256] = 32768, n[l] = 24, n[l | 256] = 24) : h < -14 ? (i[l] = 1024 >> -h - 14, i[l | 256] = 1024 >> -h - 14 | 32768, n[l] = -h - 1, n[l | 256] = -h - 1) : h <= 15 ? (i[l] = h + 15 << 10, i[l | 256] = h + 15 << 10 | 32768, n[l] = 13, n[l | 256] = 13) : h < 128 ? (i[l] = 31744, i[l | 256] = 64512, n[l] = 24, n[l | 256] = 24) : (i[l] = 31744, i[l | 256] = 64512, n[l] = 13, n[l | 256] = 13);
  }
  const s = new Uint32Array(2048), r = new Uint32Array(64), o = new Uint32Array(64);
  for (let l = 1; l < 1024; ++l) {
    let h = l << 13, c = 0;
    for (; !(h & 8388608); )
      h <<= 1, c -= 8388608;
    h &= -8388609, c += 947912704, s[l] = h | c;
  }
  for (let l = 1024; l < 2048; ++l)
    s[l] = 939524096 + (l - 1024 << 13);
  for (let l = 1; l < 31; ++l)
    r[l] = l << 23;
  r[31] = 1199570944, r[32] = 2147483648;
  for (let l = 33; l < 63; ++l)
    r[l] = 2147483648 + (l - 32 << 23);
  r[63] = 3347054592;
  for (let l = 1; l < 64; ++l)
    l !== 32 && (o[l] = 1024);
  return {
    floatView: t,
    uint32View: e,
    baseTable: i,
    shiftTable: n,
    mantissaTable: s,
    exponentTable: r,
    offsetTable: o
  };
}
function bi(a) {
  Math.abs(a) > 65504 && console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."), a = kt(a, -65504, 65504), Xn.floatView[0] = a;
  const t = Xn.uint32View[0], e = t >> 23 & 511;
  return Xn.baseTable[e] + ((t & 8388607) >> Xn.shiftTable[e]);
}
function no(a) {
  const t = a >> 10;
  return Xn.uint32View[0] = Xn.mantissaTable[Xn.offsetTable[t] + (a & 1023)] + Xn.exponentTable[t], Xn.floatView[0];
}
class Cv {
  /**
   * Returns a half precision floating point value (FP16) from the given single
   * precision floating point value (FP32).
   *
   * @param {number} val - A single precision floating point value.
   * @return {number} The FP16 value.
   */
  static toHalfFloat(t) {
    return bi(t);
  }
  /**
   * Returns a single precision floating point value (FP32) from the given half
   * precision floating point value (FP16).
   *
   * @param {number} val - A half precision floating point value.
   * @return {number} The FP32 value.
   */
  static fromHalfFloat(t) {
    return no(t);
  }
}
const Ie = /* @__PURE__ */ new E(), nl = /* @__PURE__ */ new J();
let Rv = 0, ie = class {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {TypedArray} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i = !1) {
    if (Array.isArray(t))
      throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
    this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: Rv++ }), this.name = "", this.array = t, this.itemSize = e, this.count = t !== void 0 ? t.length / e : 0, this.normalized = i, this.usage = Co, this.updateRanges = [], this.gpuType = wi, this.version = 0;
  }
  /**
   * A callback function that is executed after the renderer has transferred the attribute
   * array data to the GPU.
   */
  onUploadCallback() {
  }
  /**
   * Flag to indicate that this attribute has changed and should be re-sent to
   * the GPU. Set this to `true` when you modify the value of the array.
   *
   * @type {number}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  /**
   * Sets the usage of this buffer attribute.
   *
   * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
   * @return {BufferAttribute} A reference to this buffer attribute.
   */
  setUsage(t) {
    return this.usage = t, this;
  }
  /**
   * Adds a range of data in the data array to be updated on the GPU.
   *
   * @param {number} start - Position at which to start update.
   * @param {number} count - The number of components to update.
   */
  addUpdateRange(t, e) {
    this.updateRanges.push({ start: t, count: e });
  }
  /**
   * Clears the update ranges.
   */
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  /**
   * Copies the values of the given buffer attribute to this instance.
   *
   * @param {BufferAttribute} source - The buffer attribute to copy.
   * @return {BufferAttribute} A reference to this instance.
   */
  copy(t) {
    return this.name = t.name, this.array = new t.array.constructor(t.array), this.itemSize = t.itemSize, this.count = t.count, this.normalized = t.normalized, this.usage = t.usage, this.gpuType = t.gpuType, this;
  }
  /**
   * Copies a vector from the given buffer attribute to this one. The start
   * and destination position in the attribute buffers are represented by the
   * given indices.
   *
   * @param {number} index1 - The destination index into this buffer attribute.
   * @param {BufferAttribute} attribute - The buffer attribute to copy from.
   * @param {number} index2 - The source index into the given buffer attribute.
   * @return {BufferAttribute} A reference to this instance.
   */
  copyAt(t, e, i) {
    t *= this.itemSize, i *= e.itemSize;
    for (let n = 0, s = this.itemSize; n < s; n++)
      this.array[t + n] = e.array[i + n];
    return this;
  }
  /**
   * Copies the given array data into this buffer attribute.
   *
   * @param {(TypedArray|Array)} array - The array to copy.
   * @return {BufferAttribute} A reference to this instance.
   */
  copyArray(t) {
    return this.array.set(t), this;
  }
  /**
   * Applies the given 3x3 matrix to the given attribute. Works with
   * item size `2` and `3`.
   *
   * @param {Matrix3} m - The matrix to apply.
   * @return {BufferAttribute} A reference to this instance.
   */
  applyMatrix3(t) {
    if (this.itemSize === 2)
      for (let e = 0, i = this.count; e < i; e++)
        nl.fromBufferAttribute(this, e), nl.applyMatrix3(t), this.setXY(e, nl.x, nl.y);
    else if (this.itemSize === 3)
      for (let e = 0, i = this.count; e < i; e++)
        Ie.fromBufferAttribute(this, e), Ie.applyMatrix3(t), this.setXYZ(e, Ie.x, Ie.y, Ie.z);
    return this;
  }
  /**
   * Applies the given 4x4 matrix to the given attribute. Only works with
   * item size `3`.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {BufferAttribute} A reference to this instance.
   */
  applyMatrix4(t) {
    for (let e = 0, i = this.count; e < i; e++)
      Ie.fromBufferAttribute(this, e), Ie.applyMatrix4(t), this.setXYZ(e, Ie.x, Ie.y, Ie.z);
    return this;
  }
  /**
   * Applies the given 3x3 normal matrix to the given attribute. Only works with
   * item size `3`.
   *
   * @param {Matrix3} m - The normal matrix to apply.
   * @return {BufferAttribute} A reference to this instance.
   */
  applyNormalMatrix(t) {
    for (let e = 0, i = this.count; e < i; e++)
      Ie.fromBufferAttribute(this, e), Ie.applyNormalMatrix(t), this.setXYZ(e, Ie.x, Ie.y, Ie.z);
    return this;
  }
  /**
   * Applies the given 4x4 matrix to the given attribute. Only works with
   * item size `3` and with direction vectors.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {BufferAttribute} A reference to this instance.
   */
  transformDirection(t) {
    for (let e = 0, i = this.count; e < i; e++)
      Ie.fromBufferAttribute(this, e), Ie.transformDirection(t), this.setXYZ(e, Ie.x, Ie.y, Ie.z);
    return this;
  }
  /**
   * Sets the given array data in the buffer attribute.
   *
   * @param {(TypedArray|Array)} value - The array data to set.
   * @param {number} [offset=0] - The offset in this buffer attribute's array.
   * @return {BufferAttribute} A reference to this instance.
   */
  set(t, e = 0) {
    return this.array.set(t, e), this;
  }
  /**
   * Returns the given component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} component - The component index.
   * @return {number} The returned value.
   */
  getComponent(t, e) {
    let i = this.array[t * this.itemSize + e];
    return this.normalized && (i = mi(i, this.array)), i;
  }
  /**
   * Sets the given value to the given component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} component - The component index.
   * @param {number} value - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setComponent(t, e, i) {
    return this.normalized && (i = Yt(i, this.array)), this.array[t * this.itemSize + e] = i, this;
  }
  /**
   * Returns the x component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The x component.
   */
  getX(t) {
    let e = this.array[t * this.itemSize];
    return this.normalized && (e = mi(e, this.array)), e;
  }
  /**
   * Sets the x component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setX(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.array[t * this.itemSize] = e, this;
  }
  /**
   * Returns the y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The y component.
   */
  getY(t) {
    let e = this.array[t * this.itemSize + 1];
    return this.normalized && (e = mi(e, this.array)), e;
  }
  /**
   * Sets the y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} y - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setY(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.array[t * this.itemSize + 1] = e, this;
  }
  /**
   * Returns the z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The z component.
   */
  getZ(t) {
    let e = this.array[t * this.itemSize + 2];
    return this.normalized && (e = mi(e, this.array)), e;
  }
  /**
   * Sets the z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} z - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setZ(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.array[t * this.itemSize + 2] = e, this;
  }
  /**
   * Returns the w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The w component.
   */
  getW(t) {
    let e = this.array[t * this.itemSize + 3];
    return this.normalized && (e = mi(e, this.array)), e;
  }
  /**
   * Sets the w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} w - The value to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setW(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.array[t * this.itemSize + 3] = e, this;
  }
  /**
   * Sets the x and y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setXY(t, e, i) {
    return t *= this.itemSize, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array)), this.array[t + 0] = e, this.array[t + 1] = i, this;
  }
  /**
   * Sets the x, y and z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @param {number} z - The value for the z component to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setXYZ(t, e, i, n) {
    return t *= this.itemSize, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array), n = Yt(n, this.array)), this.array[t + 0] = e, this.array[t + 1] = i, this.array[t + 2] = n, this;
  }
  /**
   * Sets the x, y, z and w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @param {number} z - The value for the z component to set.
   * @param {number} w - The value for the w component to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setXYZW(t, e, i, n, s) {
    return t *= this.itemSize, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array), n = Yt(n, this.array), s = Yt(s, this.array)), this.array[t + 0] = e, this.array[t + 1] = i, this.array[t + 2] = n, this.array[t + 3] = s, this;
  }
  /**
   * Sets the given callback function that is executed after the Renderer has transferred
   * the attribute array data to the GPU. Can be used to perform clean-up operations after
   * the upload when attribute data are not needed anymore on the CPU side.
   *
   * @param {Function} callback - The `onUpload()` callback.
   * @return {BufferAttribute} A reference to this instance.
   */
  onUpload(t) {
    return this.onUploadCallback = t, this;
  }
  /**
   * Returns a new buffer attribute with copied values from this instance.
   *
   * @return {BufferAttribute} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.array, this.itemSize).copy(this);
  }
  /**
   * Serializes the buffer attribute into JSON.
   *
   * @return {Object} A JSON object representing the serialized buffer attribute.
   */
  toJSON() {
    const t = {
      itemSize: this.itemSize,
      type: this.array.constructor.name,
      array: Array.from(this.array),
      normalized: this.normalized
    };
    return this.name !== "" && (t.name = this.name), this.usage !== Co && (t.usage = this.usage), t;
  }
};
class Pv extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Int8Array(t), e, i);
  }
}
class Iv extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Uint8Array(t), e, i);
  }
}
class Lv extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Uint8ClampedArray(t), e, i);
  }
}
class Dv extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Int16Array(t), e, i);
  }
}
let zp = class extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Uint16Array(t), e, i);
  }
};
class Fv extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Int32Array(t), e, i);
  }
}
let Np = class extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Uint32Array(t), e, i);
  }
};
class Uv extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Uint16Array(t), e, i), this.isFloat16BufferAttribute = !0;
  }
  getX(t) {
    let e = no(this.array[t * this.itemSize]);
    return this.normalized && (e = mi(e, this.array)), e;
  }
  setX(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.array[t * this.itemSize] = bi(e), this;
  }
  getY(t) {
    let e = no(this.array[t * this.itemSize + 1]);
    return this.normalized && (e = mi(e, this.array)), e;
  }
  setY(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.array[t * this.itemSize + 1] = bi(e), this;
  }
  getZ(t) {
    let e = no(this.array[t * this.itemSize + 2]);
    return this.normalized && (e = mi(e, this.array)), e;
  }
  setZ(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.array[t * this.itemSize + 2] = bi(e), this;
  }
  getW(t) {
    let e = no(this.array[t * this.itemSize + 3]);
    return this.normalized && (e = mi(e, this.array)), e;
  }
  setW(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.array[t * this.itemSize + 3] = bi(e), this;
  }
  setXY(t, e, i) {
    return t *= this.itemSize, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array)), this.array[t + 0] = bi(e), this.array[t + 1] = bi(i), this;
  }
  setXYZ(t, e, i, n) {
    return t *= this.itemSize, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array), n = Yt(n, this.array)), this.array[t + 0] = bi(e), this.array[t + 1] = bi(i), this.array[t + 2] = bi(n), this;
  }
  setXYZW(t, e, i, n, s) {
    return t *= this.itemSize, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array), n = Yt(n, this.array), s = Yt(s, this.array)), this.array[t + 0] = bi(e), this.array[t + 1] = bi(i), this.array[t + 2] = bi(n), this.array[t + 3] = bi(s), this;
  }
}
let wt = class extends ie {
  /**
   * Constructs a new buffer attribute.
   *
   * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i) {
    super(new Float32Array(t), e, i);
  }
}, Bv = 0;
const Hi = /* @__PURE__ */ new Vt(), Uu = /* @__PURE__ */ new le(), Rr = /* @__PURE__ */ new E(), Ii = /* @__PURE__ */ new we(), Oa = /* @__PURE__ */ new we(), Oe = /* @__PURE__ */ new E();
let Ht = class Sy extends Ei {
  /**
   * Constructs a new geometry.
   */
  constructor() {
    super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: Bv++ }), this.uuid = Oi(), this.name = "", this.type = "BufferGeometry", this.index = null, this.indirect = null, this.attributes = {}, this.morphAttributes = {}, this.morphTargetsRelative = !1, this.groups = [], this.boundingBox = null, this.boundingSphere = null, this.drawRange = { start: 0, count: 1 / 0 }, this.userData = {};
  }
  /**
   * Returns the index of this geometry.
   *
   * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
   */
  getIndex() {
    return this.index;
  }
  /**
   * Sets the given index to this geometry.
   *
   * @param {Array<number>|BufferAttribute} index - The index to set.
   * @return {BufferGeometry} A reference to this instance.
   */
  setIndex(t) {
    return Array.isArray(t) ? this.index = new (yy(t) ? Np : zp)(t, 1) : this.index = t, this;
  }
  /**
   * Sets the given indirect attribute to this geometry.
   *
   * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
   * @return {BufferGeometry} A reference to this instance.
   */
  setIndirect(t) {
    return this.indirect = t, this;
  }
  /**
   * Returns the indirect attribute of this geometry.
   *
   * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
   */
  getIndirect() {
    return this.indirect;
  }
  /**
   * Returns the buffer attribute for the given name.
   *
   * @param {string} name - The attribute name.
   * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
   * Returns `undefined` if not attribute has been found.
   */
  getAttribute(t) {
    return this.attributes[t];
  }
  /**
   * Sets the given attribute for the given name.
   *
   * @param {string} name - The attribute name.
   * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
   * @return {BufferGeometry} A reference to this instance.
   */
  setAttribute(t, e) {
    return this.attributes[t] = e, this;
  }
  /**
   * Deletes the attribute for the given name.
   *
   * @param {string} name - The attribute name to delete.
   * @return {BufferGeometry} A reference to this instance.
   */
  deleteAttribute(t) {
    return delete this.attributes[t], this;
  }
  /**
   * Returns `true` if this geometry has an attribute for the given name.
   *
   * @param {string} name - The attribute name.
   * @return {boolean} Whether this geometry has an attribute for the given name or not.
   */
  hasAttribute(t) {
    return this.attributes[t] !== void 0;
  }
  /**
   * Adds a group to this geometry.
   *
   * @param {number} start - The first element in this draw call. That is the first
   * vertex for non-indexed geometry, otherwise the first triangle index.
   * @param {number} count - Specifies how many vertices (or indices) are part of this group.
   * @param {number} [materialIndex=0] - The material array index to use.
   */
  addGroup(t, e, i = 0) {
    this.groups.push({
      start: t,
      count: e,
      materialIndex: i
    });
  }
  /**
   * Clears all groups.
   */
  clearGroups() {
    this.groups = [];
  }
  /**
   * Sets the draw range for this geometry.
   *
   * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
   * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
   * For indexed BufferGeometry, `count` is the number of indices to render.
   */
  setDrawRange(t, e) {
    this.drawRange.start = t, this.drawRange.count = e;
  }
  /**
   * Applies the given 4x4 transformation matrix to the geometry.
   *
   * @param {Matrix4} matrix - The matrix to apply.
   * @return {BufferGeometry} A reference to this instance.
   */
  applyMatrix4(t) {
    const e = this.attributes.position;
    e !== void 0 && (e.applyMatrix4(t), e.needsUpdate = !0);
    const i = this.attributes.normal;
    if (i !== void 0) {
      const s = new Xt().getNormalMatrix(t);
      i.applyNormalMatrix(s), i.needsUpdate = !0;
    }
    const n = this.attributes.tangent;
    return n !== void 0 && (n.transformDirection(t), n.needsUpdate = !0), this.boundingBox !== null && this.computeBoundingBox(), this.boundingSphere !== null && this.computeBoundingSphere(), this;
  }
  /**
   * Applies the rotation represented by the Quaternion to the geometry.
   *
   * @param {Quaternion} q - The Quaternion to apply.
   * @return {BufferGeometry} A reference to this instance.
   */
  applyQuaternion(t) {
    return Hi.makeRotationFromQuaternion(t), this.applyMatrix4(Hi), this;
  }
  /**
   * Rotates the geometry about the X axis. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#rotation} for typical
   * real-time mesh rotation.
   *
   * @param {number} angle - The angle in radians.
   * @return {BufferGeometry} A reference to this instance.
   */
  rotateX(t) {
    return Hi.makeRotationX(t), this.applyMatrix4(Hi), this;
  }
  /**
   * Rotates the geometry about the Y axis. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#rotation} for typical
   * real-time mesh rotation.
   *
   * @param {number} angle - The angle in radians.
   * @return {BufferGeometry} A reference to this instance.
   */
  rotateY(t) {
    return Hi.makeRotationY(t), this.applyMatrix4(Hi), this;
  }
  /**
   * Rotates the geometry about the Z axis. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#rotation} for typical
   * real-time mesh rotation.
   *
   * @param {number} angle - The angle in radians.
   * @return {BufferGeometry} A reference to this instance.
   */
  rotateZ(t) {
    return Hi.makeRotationZ(t), this.applyMatrix4(Hi), this;
  }
  /**
   * Translates the geometry. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#position} for typical
   * real-time mesh rotation.
   *
   * @param {number} x - The x offset.
   * @param {number} y - The y offset.
   * @param {number} z - The z offset.
   * @return {BufferGeometry} A reference to this instance.
   */
  translate(t, e, i) {
    return Hi.makeTranslation(t, e, i), this.applyMatrix4(Hi), this;
  }
  /**
   * Scales the geometry. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#scale} for typical
   * real-time mesh rotation.
   *
   * @param {number} x - The x scale.
   * @param {number} y - The y scale.
   * @param {number} z - The z scale.
   * @return {BufferGeometry} A reference to this instance.
   */
  scale(t, e, i) {
    return Hi.makeScale(t, e, i), this.applyMatrix4(Hi), this;
  }
  /**
   * Rotates the geometry to face a point in 3D space. This is typically done as a one time
   * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
   * real-time mesh rotation.
   *
   * @param {Vector3} vector - The target point.
   * @return {BufferGeometry} A reference to this instance.
   */
  lookAt(t) {
    return Uu.lookAt(t), Uu.updateMatrix(), this.applyMatrix4(Uu.matrix), this;
  }
  /**
   * Center the geometry based on its bounding box.
   *
   * @return {BufferGeometry} A reference to this instance.
   */
  center() {
    return this.computeBoundingBox(), this.boundingBox.getCenter(Rr).negate(), this.translate(Rr.x, Rr.y, Rr.z), this;
  }
  /**
   * Defines a geometry by creating a `position` attribute based on the given array of points. The array
   * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
   * set to `0`.
   *
   * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
   * data from the array. The length of the array must match the vertex count.
   *
   * @param {Array<Vector2>|Array<Vector3>} points - The points.
   * @return {BufferGeometry} A reference to this instance.
   */
  setFromPoints(t) {
    const e = this.getAttribute("position");
    if (e === void 0) {
      const i = [];
      for (let n = 0, s = t.length; n < s; n++) {
        const r = t[n];
        i.push(r.x, r.y, r.z || 0);
      }
      this.setAttribute("position", new wt(i, 3));
    } else {
      const i = Math.min(t.length, e.count);
      for (let n = 0; n < i; n++) {
        const s = t[n];
        e.setXYZ(n, s.x, s.y, s.z || 0);
      }
      t.length > e.count && console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."), e.needsUpdate = !0;
    }
    return this;
  }
  /**
   * Computes the bounding box of the geometry, and updates the `boundingBox` member.
   * The bounding box is not computed by the engine; it must be computed by your app.
   * You may need to recompute the bounding box if the geometry vertices are modified.
   */
  computeBoundingBox() {
    this.boundingBox === null && (this.boundingBox = new we());
    const t = this.attributes.position, e = this.morphAttributes.position;
    if (t && t.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this), this.boundingBox.set(
        new E(-1 / 0, -1 / 0, -1 / 0),
        new E(1 / 0, 1 / 0, 1 / 0)
      );
      return;
    }
    if (t !== void 0) {
      if (this.boundingBox.setFromBufferAttribute(t), e)
        for (let i = 0, n = e.length; i < n; i++) {
          const s = e[i];
          Ii.setFromBufferAttribute(s), this.morphTargetsRelative ? (Oe.addVectors(this.boundingBox.min, Ii.min), this.boundingBox.expandByPoint(Oe), Oe.addVectors(this.boundingBox.max, Ii.max), this.boundingBox.expandByPoint(Oe)) : (this.boundingBox.expandByPoint(Ii.min), this.boundingBox.expandByPoint(Ii.max));
        }
    } else
      this.boundingBox.makeEmpty();
    (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) && console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  }
  /**
   * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
   * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
   * You may need to recompute the bounding sphere if the geometry vertices are modified.
   */
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new Re());
    const t = this.attributes.position, e = this.morphAttributes.position;
    if (t && t.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this), this.boundingSphere.set(new E(), 1 / 0);
      return;
    }
    if (t) {
      const i = this.boundingSphere.center;
      if (Ii.setFromBufferAttribute(t), e)
        for (let s = 0, r = e.length; s < r; s++) {
          const o = e[s];
          Oa.setFromBufferAttribute(o), this.morphTargetsRelative ? (Oe.addVectors(Ii.min, Oa.min), Ii.expandByPoint(Oe), Oe.addVectors(Ii.max, Oa.max), Ii.expandByPoint(Oe)) : (Ii.expandByPoint(Oa.min), Ii.expandByPoint(Oa.max));
        }
      Ii.getCenter(i);
      let n = 0;
      for (let s = 0, r = t.count; s < r; s++)
        Oe.fromBufferAttribute(t, s), n = Math.max(n, i.distanceToSquared(Oe));
      if (e)
        for (let s = 0, r = e.length; s < r; s++) {
          const o = e[s], l = this.morphTargetsRelative;
          for (let h = 0, c = o.count; h < c; h++)
            Oe.fromBufferAttribute(o, h), l && (Rr.fromBufferAttribute(t, h), Oe.add(Rr)), n = Math.max(n, i.distanceToSquared(Oe));
        }
      this.boundingSphere.radius = Math.sqrt(n), isNaN(this.boundingSphere.radius) && console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
    }
  }
  /**
   * Calculates and adds a tangent attribute to this geometry.
   *
   * The computation is only supported for indexed geometries and if position, normal, and uv attributes
   * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
   * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
   */
  computeTangents() {
    const t = this.index, e = this.attributes;
    if (t === null || e.position === void 0 || e.normal === void 0 || e.uv === void 0) {
      console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");
      return;
    }
    const i = e.position, n = e.normal, s = e.uv;
    this.hasAttribute("tangent") === !1 && this.setAttribute("tangent", new ie(new Float32Array(4 * i.count), 4));
    const r = this.getAttribute("tangent"), o = [], l = [];
    for (let R = 0; R < i.count; R++)
      o[R] = new E(), l[R] = new E();
    const h = new E(), c = new E(), u = new E(), d = new J(), p = new J(), f = new J(), y = new E(), g = new E();
    function m(R, b, M) {
      h.fromBufferAttribute(i, R), c.fromBufferAttribute(i, b), u.fromBufferAttribute(i, M), d.fromBufferAttribute(s, R), p.fromBufferAttribute(s, b), f.fromBufferAttribute(s, M), c.sub(h), u.sub(h), p.sub(d), f.sub(d);
      const L = 1 / (p.x * f.y - f.x * p.y);
      isFinite(L) && (y.copy(c).multiplyScalar(f.y).addScaledVector(u, -p.y).multiplyScalar(L), g.copy(u).multiplyScalar(p.x).addScaledVector(c, -f.x).multiplyScalar(L), o[R].add(y), o[b].add(y), o[M].add(y), l[R].add(g), l[b].add(g), l[M].add(g));
    }
    let v = this.groups;
    v.length === 0 && (v = [{
      start: 0,
      count: t.count
    }]);
    for (let R = 0, b = v.length; R < b; ++R) {
      const M = v[R], L = M.start, U = M.count;
      for (let O = L, V = L + U; O < V; O += 3)
        m(
          t.getX(O + 0),
          t.getX(O + 1),
          t.getX(O + 2)
        );
    }
    const x = new E(), _ = new E(), S = new E(), w = new E();
    function T(R) {
      S.fromBufferAttribute(n, R), w.copy(S);
      const b = o[R];
      x.copy(b), x.sub(S.multiplyScalar(S.dot(b))).normalize(), _.crossVectors(w, b);
      const L = _.dot(l[R]) < 0 ? -1 : 1;
      r.setXYZW(R, x.x, x.y, x.z, L);
    }
    for (let R = 0, b = v.length; R < b; ++R) {
      const M = v[R], L = M.start, U = M.count;
      for (let O = L, V = L + U; O < V; O += 3)
        T(t.getX(O + 0)), T(t.getX(O + 1)), T(t.getX(O + 2));
    }
  }
  /**
   * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
   * each vertex normal to be the average of the face normals of the faces that share that vertex.
   * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
   * to be the same as the face normal.
   */
  computeVertexNormals() {
    const t = this.index, e = this.getAttribute("position");
    if (e !== void 0) {
      let i = this.getAttribute("normal");
      if (i === void 0)
        i = new ie(new Float32Array(e.count * 3), 3), this.setAttribute("normal", i);
      else
        for (let d = 0, p = i.count; d < p; d++)
          i.setXYZ(d, 0, 0, 0);
      const n = new E(), s = new E(), r = new E(), o = new E(), l = new E(), h = new E(), c = new E(), u = new E();
      if (t)
        for (let d = 0, p = t.count; d < p; d += 3) {
          const f = t.getX(d + 0), y = t.getX(d + 1), g = t.getX(d + 2);
          n.fromBufferAttribute(e, f), s.fromBufferAttribute(e, y), r.fromBufferAttribute(e, g), c.subVectors(r, s), u.subVectors(n, s), c.cross(u), o.fromBufferAttribute(i, f), l.fromBufferAttribute(i, y), h.fromBufferAttribute(i, g), o.add(c), l.add(c), h.add(c), i.setXYZ(f, o.x, o.y, o.z), i.setXYZ(y, l.x, l.y, l.z), i.setXYZ(g, h.x, h.y, h.z);
        }
      else
        for (let d = 0, p = e.count; d < p; d += 3)
          n.fromBufferAttribute(e, d + 0), s.fromBufferAttribute(e, d + 1), r.fromBufferAttribute(e, d + 2), c.subVectors(r, s), u.subVectors(n, s), c.cross(u), i.setXYZ(d + 0, c.x, c.y, c.z), i.setXYZ(d + 1, c.x, c.y, c.z), i.setXYZ(d + 2, c.x, c.y, c.z);
      this.normalizeNormals(), i.needsUpdate = !0;
    }
  }
  /**
   * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
   * correct lighting on the geometry surfaces.
   */
  normalizeNormals() {
    const t = this.attributes.normal;
    for (let e = 0, i = t.count; e < i; e++)
      Oe.fromBufferAttribute(t, e), Oe.normalize(), t.setXYZ(e, Oe.x, Oe.y, Oe.z);
  }
  /**
   * Return a new non-index version of this indexed geometry. If the geometry
   * is already non-indexed, the method is a NOOP.
   *
   * @return {BufferGeometry} The non-indexed version of this indexed geometry.
   */
  toNonIndexed() {
    function t(o, l) {
      const h = o.array, c = o.itemSize, u = o.normalized, d = new h.constructor(l.length * c);
      let p = 0, f = 0;
      for (let y = 0, g = l.length; y < g; y++) {
        o.isInterleavedBufferAttribute ? p = l[y] * o.data.stride + o.offset : p = l[y] * c;
        for (let m = 0; m < c; m++)
          d[f++] = h[p++];
      }
      return new ie(d, c, u);
    }
    if (this.index === null)
      return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."), this;
    const e = new Sy(), i = this.index.array, n = this.attributes;
    for (const o in n) {
      const l = n[o], h = t(l, i);
      e.setAttribute(o, h);
    }
    const s = this.morphAttributes;
    for (const o in s) {
      const l = [], h = s[o];
      for (let c = 0, u = h.length; c < u; c++) {
        const d = h[c], p = t(d, i);
        l.push(p);
      }
      e.morphAttributes[o] = l;
    }
    e.morphTargetsRelative = this.morphTargetsRelative;
    const r = this.groups;
    for (let o = 0, l = r.length; o < l; o++) {
      const h = r[o];
      e.addGroup(h.start, h.count, h.materialIndex);
    }
    return e;
  }
  /**
   * Serializes the geometry into JSON.
   *
   * @return {Object} A JSON object representing the serialized geometry.
   */
  toJSON() {
    const t = {
      metadata: {
        version: 4.7,
        type: "BufferGeometry",
        generator: "BufferGeometry.toJSON"
      }
    };
    if (t.uuid = this.uuid, t.type = this.type, this.name !== "" && (t.name = this.name), Object.keys(this.userData).length > 0 && (t.userData = this.userData), this.parameters !== void 0) {
      const l = this.parameters;
      for (const h in l)
        l[h] !== void 0 && (t[h] = l[h]);
      return t;
    }
    t.data = { attributes: {} };
    const e = this.index;
    e !== null && (t.data.index = {
      type: e.array.constructor.name,
      array: Array.prototype.slice.call(e.array)
    });
    const i = this.attributes;
    for (const l in i) {
      const h = i[l];
      t.data.attributes[l] = h.toJSON(t.data);
    }
    const n = {};
    let s = !1;
    for (const l in this.morphAttributes) {
      const h = this.morphAttributes[l], c = [];
      for (let u = 0, d = h.length; u < d; u++) {
        const p = h[u];
        c.push(p.toJSON(t.data));
      }
      c.length > 0 && (n[l] = c, s = !0);
    }
    s && (t.data.morphAttributes = n, t.data.morphTargetsRelative = this.morphTargetsRelative);
    const r = this.groups;
    r.length > 0 && (t.data.groups = JSON.parse(JSON.stringify(r)));
    const o = this.boundingSphere;
    return o !== null && (t.data.boundingSphere = o.toJSON()), t;
  }
  /**
   * Returns a new geometry with copied values from this instance.
   *
   * @return {BufferGeometry} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given geometry to this instance.
   *
   * @param {BufferGeometry} source - The geometry to copy.
   * @return {BufferGeometry} A reference to this instance.
   */
  copy(t) {
    this.index = null, this.attributes = {}, this.morphAttributes = {}, this.groups = [], this.boundingBox = null, this.boundingSphere = null;
    const e = {};
    this.name = t.name;
    const i = t.index;
    i !== null && this.setIndex(i.clone());
    const n = t.attributes;
    for (const h in n) {
      const c = n[h];
      this.setAttribute(h, c.clone(e));
    }
    const s = t.morphAttributes;
    for (const h in s) {
      const c = [], u = s[h];
      for (let d = 0, p = u.length; d < p; d++)
        c.push(u[d].clone(e));
      this.morphAttributes[h] = c;
    }
    this.morphTargetsRelative = t.morphTargetsRelative;
    const r = t.groups;
    for (let h = 0, c = r.length; h < c; h++) {
      const u = r[h];
      this.addGroup(u.start, u.count, u.materialIndex);
    }
    const o = t.boundingBox;
    o !== null && (this.boundingBox = o.clone());
    const l = t.boundingSphere;
    return l !== null && (this.boundingSphere = l.clone()), this.drawRange.start = t.drawRange.start, this.drawRange.count = t.drawRange.count, this.userData = t.userData, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires BufferGeometry#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
};
const Gf = /* @__PURE__ */ new Vt(), ks = /* @__PURE__ */ new Aa(), sl = /* @__PURE__ */ new Re(), Wf = /* @__PURE__ */ new E(), rl = /* @__PURE__ */ new E(), al = /* @__PURE__ */ new E(), ol = /* @__PURE__ */ new E(), Bu = /* @__PURE__ */ new E(), ll = /* @__PURE__ */ new E(), qf = /* @__PURE__ */ new E(), hl = /* @__PURE__ */ new E();
let re = class extends le {
  /**
   * Constructs a new mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(t = new Ht(), e = new li()) {
    super(), this.isMesh = !0, this.type = "Mesh", this.geometry = t, this.material = e, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.count = 1, this.updateMorphTargets();
  }
  copy(t, e) {
    return super.copy(t, e), t.morphTargetInfluences !== void 0 && (this.morphTargetInfluences = t.morphTargetInfluences.slice()), t.morphTargetDictionary !== void 0 && (this.morphTargetDictionary = Object.assign({}, t.morphTargetDictionary)), this.material = Array.isArray(t.material) ? t.material.slice() : t.material, this.geometry = t.geometry, this;
  }
  /**
   * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
   * to make sure existing morph targets can influence this 3D object.
   */
  updateMorphTargets() {
    const e = this.geometry.morphAttributes, i = Object.keys(e);
    if (i.length > 0) {
      const n = e[i[0]];
      if (n !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let s = 0, r = n.length; s < r; s++) {
          const o = n[s].name || String(s);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[o] = s;
        }
      }
    }
  }
  /**
   * Returns the local-space position of the vertex at the given index, taking into
   * account the current animation state of both morph targets and skinning.
   *
   * @param {number} index - The vertex index.
   * @param {Vector3} target - The target object that is used to store the method's result.
   * @return {Vector3} The vertex position in local space.
   */
  getVertexPosition(t, e) {
    const i = this.geometry, n = i.attributes.position, s = i.morphAttributes.position, r = i.morphTargetsRelative;
    e.fromBufferAttribute(n, t);
    const o = this.morphTargetInfluences;
    if (s && o) {
      ll.set(0, 0, 0);
      for (let l = 0, h = s.length; l < h; l++) {
        const c = o[l], u = s[l];
        c !== 0 && (Bu.fromBufferAttribute(u, t), r ? ll.addScaledVector(Bu, c) : ll.addScaledVector(Bu.sub(e), c));
      }
      e.add(ll);
    }
    return e;
  }
  /**
   * Computes intersection points between a casted ray and this line.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(t, e) {
    const i = this.geometry, n = this.material, s = this.matrixWorld;
    n !== void 0 && (i.boundingSphere === null && i.computeBoundingSphere(), sl.copy(i.boundingSphere), sl.applyMatrix4(s), ks.copy(t.ray).recast(t.near), !(sl.containsPoint(ks.origin) === !1 && (ks.intersectSphere(sl, Wf) === null || ks.origin.distanceToSquared(Wf) > (t.far - t.near) ** 2)) && (Gf.copy(s).invert(), ks.copy(t.ray).applyMatrix4(Gf), !(i.boundingBox !== null && ks.intersectsBox(i.boundingBox) === !1) && this._computeIntersections(t, e, ks)));
  }
  _computeIntersections(t, e, i) {
    let n;
    const s = this.geometry, r = this.material, o = s.index, l = s.attributes.position, h = s.attributes.uv, c = s.attributes.uv1, u = s.attributes.normal, d = s.groups, p = s.drawRange;
    if (o !== null)
      if (Array.isArray(r))
        for (let f = 0, y = d.length; f < y; f++) {
          const g = d[f], m = r[g.materialIndex], v = Math.max(g.start, p.start), x = Math.min(o.count, Math.min(g.start + g.count, p.start + p.count));
          for (let _ = v, S = x; _ < S; _ += 3) {
            const w = o.getX(_), T = o.getX(_ + 1), R = o.getX(_ + 2);
            n = cl(this, m, t, i, h, c, u, w, T, R), n && (n.faceIndex = Math.floor(_ / 3), n.face.materialIndex = g.materialIndex, e.push(n));
          }
        }
      else {
        const f = Math.max(0, p.start), y = Math.min(o.count, p.start + p.count);
        for (let g = f, m = y; g < m; g += 3) {
          const v = o.getX(g), x = o.getX(g + 1), _ = o.getX(g + 2);
          n = cl(this, r, t, i, h, c, u, v, x, _), n && (n.faceIndex = Math.floor(g / 3), e.push(n));
        }
      }
    else if (l !== void 0)
      if (Array.isArray(r))
        for (let f = 0, y = d.length; f < y; f++) {
          const g = d[f], m = r[g.materialIndex], v = Math.max(g.start, p.start), x = Math.min(l.count, Math.min(g.start + g.count, p.start + p.count));
          for (let _ = v, S = x; _ < S; _ += 3) {
            const w = _, T = _ + 1, R = _ + 2;
            n = cl(this, m, t, i, h, c, u, w, T, R), n && (n.faceIndex = Math.floor(_ / 3), n.face.materialIndex = g.materialIndex, e.push(n));
          }
        }
      else {
        const f = Math.max(0, p.start), y = Math.min(l.count, p.start + p.count);
        for (let g = f, m = y; g < m; g += 3) {
          const v = g, x = g + 1, _ = g + 2;
          n = cl(this, r, t, i, h, c, u, v, x, _), n && (n.faceIndex = Math.floor(g / 3), e.push(n));
        }
      }
  }
};
function zv(a, t, e, i, n, s, r, o) {
  let l;
  if (t.side === He ? l = i.intersectTriangle(r, s, n, !0, o) : l = i.intersectTriangle(n, s, r, t.side === $i, o), l === null) return null;
  hl.copy(o), hl.applyMatrix4(a.matrixWorld);
  const h = e.ray.origin.distanceTo(hl);
  return h < e.near || h > e.far ? null : {
    distance: h,
    point: hl.clone(),
    object: a
  };
}
function cl(a, t, e, i, n, s, r, o, l, h) {
  a.getVertexPosition(o, rl), a.getVertexPosition(l, al), a.getVertexPosition(h, ol);
  const c = zv(a, t, e, i, rl, al, ol, qf);
  if (c) {
    const u = new E();
    bs.getBarycoord(qf, rl, al, ol, u), n && (c.uv = bs.getInterpolatedAttribute(n, o, l, h, u, new J())), s && (c.uv1 = bs.getInterpolatedAttribute(s, o, l, h, u, new J())), r && (c.normal = bs.getInterpolatedAttribute(r, o, l, h, u, new E()), c.normal.dot(i.direction) > 0 && c.normal.multiplyScalar(-1));
    const d = {
      a: o,
      b: l,
      c: h,
      normal: new E(),
      materialIndex: 0
    };
    bs.getNormal(rl, al, ol, d.normal), c.face = d, c.barycoord = u;
  }
  return c;
}
class mr extends Ht {
  /**
   * Constructs a new box geometry.
   *
   * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
   * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
   * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
   * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
   * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
   * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
   */
  constructor(t = 1, e = 1, i = 1, n = 1, s = 1, r = 1) {
    super(), this.type = "BoxGeometry", this.parameters = {
      width: t,
      height: e,
      depth: i,
      widthSegments: n,
      heightSegments: s,
      depthSegments: r
    };
    const o = this;
    n = Math.floor(n), s = Math.floor(s), r = Math.floor(r);
    const l = [], h = [], c = [], u = [];
    let d = 0, p = 0;
    f("z", "y", "x", -1, -1, i, e, t, r, s, 0), f("z", "y", "x", 1, -1, i, e, -t, r, s, 1), f("x", "z", "y", 1, 1, t, i, e, n, r, 2), f("x", "z", "y", 1, -1, t, i, -e, n, r, 3), f("x", "y", "z", 1, -1, t, e, i, n, s, 4), f("x", "y", "z", -1, -1, t, e, -i, n, s, 5), this.setIndex(l), this.setAttribute("position", new wt(h, 3)), this.setAttribute("normal", new wt(c, 3)), this.setAttribute("uv", new wt(u, 2));
    function f(y, g, m, v, x, _, S, w, T, R, b) {
      const M = _ / T, L = S / R, U = _ / 2, O = S / 2, V = w / 2, W = T + 1, G = R + 1;
      let et = 0, H = 0;
      const at = new E();
      for (let pt = 0; pt < G; pt++) {
        const Mt = pt * L - O;
        for (let Lt = 0; Lt < W; Lt++) {
          const jt = Lt * M - U;
          at[y] = jt * v, at[g] = Mt * x, at[m] = V, h.push(at.x, at.y, at.z), at[y] = 0, at[g] = 0, at[m] = w > 0 ? 1 : -1, c.push(at.x, at.y, at.z), u.push(Lt / T), u.push(1 - pt / R), et += 1;
        }
      }
      for (let pt = 0; pt < R; pt++)
        for (let Mt = 0; Mt < T; Mt++) {
          const Lt = d + Mt + W * pt, jt = d + Mt + W * (pt + 1), ne = d + (Mt + 1) + W * (pt + 1), Jt = d + (Mt + 1) + W * pt;
          l.push(Lt, jt, Jt), l.push(jt, ne, Jt), H += 6;
        }
      o.addGroup(p, H, b), p += H, d += et;
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {BoxGeometry} A new instance.
   */
  static fromJSON(t) {
    return new mr(t.width, t.height, t.depth, t.widthSegments, t.heightSegments, t.depthSegments);
  }
}
function _a(a) {
  const t = {};
  for (const e in a) {
    t[e] = {};
    for (const i in a[e]) {
      const n = a[e][i];
      n && (n.isColor || n.isMatrix3 || n.isMatrix4 || n.isVector2 || n.isVector3 || n.isVector4 || n.isTexture || n.isQuaternion) ? n.isRenderTargetTexture ? (console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), t[e][i] = null) : t[e][i] = n.clone() : Array.isArray(n) ? t[e][i] = n.slice() : t[e][i] = n;
    }
  }
  return t;
}
function pi(a) {
  const t = {};
  for (let e = 0; e < a.length; e++) {
    const i = _a(a[e]);
    for (const n in i)
      t[n] = i[n];
  }
  return t;
}
function Nv(a) {
  const t = [];
  for (let e = 0; e < a.length; e++)
    t.push(a[e].clone());
  return t;
}
function wy(a) {
  const t = a.getRenderTarget();
  return t === null ? a.outputColorSpace : t.isXRRenderTarget === !0 ? t.texture.colorSpace : ee.workingColorSpace;
}
const Oc = { clone: _a, merge: pi };
var Ov = `void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`, kv = `void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;
let Xi = class extends hi {
  /**
   * Constructs a new shader material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isShaderMaterial = !0, this.type = "ShaderMaterial", this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = Ov, this.fragmentShader = kv, this.linewidth = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.fog = !1, this.lights = !1, this.clipping = !1, this.forceSinglePass = !0, this.extensions = {
      clipCullDistance: !1,
      // set to use vertex shader clipping
      multiDraw: !1
      // set to use vertex shader multi_draw / enable gl_DrawID
    }, this.defaultAttributeValues = {
      color: [1, 1, 1],
      uv: [0, 0],
      uv1: [0, 0]
    }, this.index0AttributeName = void 0, this.uniformsNeedUpdate = !1, this.glslVersion = null, t !== void 0 && this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.fragmentShader = t.fragmentShader, this.vertexShader = t.vertexShader, this.uniforms = _a(t.uniforms), this.uniformsGroups = Nv(t.uniformsGroups), this.defines = Object.assign({}, t.defines), this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.fog = t.fog, this.lights = t.lights, this.clipping = t.clipping, this.extensions = Object.assign({}, t.extensions), this.glslVersion = t.glslVersion, this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    e.glslVersion = this.glslVersion, e.uniforms = {};
    for (const n in this.uniforms) {
      const r = this.uniforms[n].value;
      r && r.isTexture ? e.uniforms[n] = {
        type: "t",
        value: r.toJSON(t).uuid
      } : r && r.isColor ? e.uniforms[n] = {
        type: "c",
        value: r.getHex()
      } : r && r.isVector2 ? e.uniforms[n] = {
        type: "v2",
        value: r.toArray()
      } : r && r.isVector3 ? e.uniforms[n] = {
        type: "v3",
        value: r.toArray()
      } : r && r.isVector4 ? e.uniforms[n] = {
        type: "v4",
        value: r.toArray()
      } : r && r.isMatrix3 ? e.uniforms[n] = {
        type: "m3",
        value: r.toArray()
      } : r && r.isMatrix4 ? e.uniforms[n] = {
        type: "m4",
        value: r.toArray()
      } : e.uniforms[n] = {
        value: r
      };
    }
    Object.keys(this.defines).length > 0 && (e.defines = this.defines), e.vertexShader = this.vertexShader, e.fragmentShader = this.fragmentShader, e.lights = this.lights, e.clipping = this.clipping;
    const i = {};
    for (const n in this.extensions)
      this.extensions[n] === !0 && (i[n] = !0);
    return Object.keys(i).length > 0 && (e.extensions = i), e;
  }
}, kc = class extends le {
  /**
   * Constructs a new camera.
   */
  constructor() {
    super(), this.isCamera = !0, this.type = "Camera", this.matrixWorldInverse = new Vt(), this.projectionMatrix = new Vt(), this.projectionMatrixInverse = new Vt(), this.coordinateSystem = Ni, this._reversedDepth = !1;
  }
  /**
   * The flag that indicates whether the camera uses a reversed depth buffer.
   *
   * @type {boolean}
   * @default false
   */
  get reversedDepth() {
    return this._reversedDepth;
  }
  copy(t, e) {
    return super.copy(t, e), this.matrixWorldInverse.copy(t.matrixWorldInverse), this.projectionMatrix.copy(t.projectionMatrix), this.projectionMatrixInverse.copy(t.projectionMatrixInverse), this.coordinateSystem = t.coordinateSystem, this;
  }
  /**
   * Returns a vector representing the ("look") direction of the 3D object in world space.
   *
   * This method is overwritten since cameras have a different forward vector compared to other
   * 3D objects. A camera looks down its local, negative z-axis by default.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's direction in world space.
   */
  getWorldDirection(t) {
    return super.getWorldDirection(t).negate();
  }
  updateMatrixWorld(t) {
    super.updateMatrixWorld(t), this.matrixWorldInverse.copy(this.matrixWorld).invert();
  }
  updateWorldMatrix(t, e) {
    super.updateWorldMatrix(t, e), this.matrixWorldInverse.copy(this.matrixWorld).invert();
  }
  clone() {
    return new this.constructor().copy(this);
  }
};
const cs = /* @__PURE__ */ new E(), $f = /* @__PURE__ */ new J(), Xf = /* @__PURE__ */ new J();
class Ve extends kc {
  /**
   * Constructs a new perspective camera.
   *
   * @param {number} [fov=50] - The vertical field of view.
   * @param {number} [aspect=1] - The aspect ratio.
   * @param {number} [near=0.1] - The camera's near plane.
   * @param {number} [far=2000] - The camera's far plane.
   */
  constructor(t = 50, e = 1, i = 0.1, n = 2e3) {
    super(), this.isPerspectiveCamera = !0, this.type = "PerspectiveCamera", this.fov = t, this.zoom = 1, this.near = i, this.far = n, this.focus = 10, this.aspect = e, this.view = null, this.filmGauge = 35, this.filmOffset = 0, this.updateProjectionMatrix();
  }
  copy(t, e) {
    return super.copy(t, e), this.fov = t.fov, this.zoom = t.zoom, this.near = t.near, this.far = t.far, this.focus = t.focus, this.aspect = t.aspect, this.view = t.view === null ? null : Object.assign({}, t.view), this.filmGauge = t.filmGauge, this.filmOffset = t.filmOffset, this;
  }
  /**
   * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
   *
   * The default film gauge is 35, so that the focal length can be specified for
   * a 35mm (full frame) camera.
   *
   * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
   */
  setFocalLength(t) {
    const e = 0.5 * this.getFilmHeight() / t;
    this.fov = ya * 2 * Math.atan(e), this.updateProjectionMatrix();
  }
  /**
   * Returns the focal length from the current {@link PerspectiveCamera#fov} and
   * {@link PerspectiveCamera#filmGauge}.
   *
   * @return {number} The computed focal length.
   */
  getFocalLength() {
    const t = Math.tan(lr * 0.5 * this.fov);
    return 0.5 * this.getFilmHeight() / t;
  }
  /**
   * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
   *
   * @return {number} The effective FOV.
   */
  getEffectiveFOV() {
    return ya * 2 * Math.atan(
      Math.tan(lr * 0.5 * this.fov) / this.zoom
    );
  }
  /**
   * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
   * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
   *
   * @return {number} The film width.
   */
  getFilmWidth() {
    return this.filmGauge * Math.min(this.aspect, 1);
  }
  /**
   * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
   * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
   *
   * @return {number} The film width.
   */
  getFilmHeight() {
    return this.filmGauge / Math.max(this.aspect, 1);
  }
  /**
   * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
   * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
   *
   * @param {number} distance - The viewing distance.
   * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
   * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
   */
  getViewBounds(t, e, i) {
    cs.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse), e.set(cs.x, cs.y).multiplyScalar(-t / cs.z), cs.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse), i.set(cs.x, cs.y).multiplyScalar(-t / cs.z);
  }
  /**
   * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
   *
   * @param {number} distance - The viewing distance.
   * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
   * @returns {Vector2} The view size.
   */
  getViewSize(t, e) {
    return this.getViewBounds(t, $f, Xf), e.subVectors(Xf, $f);
  }
  /**
   * Sets an offset in a larger frustum. This is useful for multi-window or
   * multi-monitor/multi-machine setups.
   *
   * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
   * the monitors are in grid like this
   *```
   *   +---+---+---+
   *   | A | B | C |
   *   +---+---+---+
   *   | D | E | F |
   *   +---+---+---+
   *```
   * then for each monitor you would call it like this:
   *```js
   * const w = 1920;
   * const h = 1080;
   * const fullWidth = w * 3;
   * const fullHeight = h * 2;
   *
   * // --A--
   * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
   * // --B--
   * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
   * // --C--
   * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
   * // --D--
   * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
   * // --E--
   * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
   * // --F--
   * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
   * ```
   *
   * Note there is no reason monitors have to be the same size or in a grid.
   *
   * @param {number} fullWidth - The full width of multiview setup.
   * @param {number} fullHeight - The full height of multiview setup.
   * @param {number} x - The horizontal offset of the subcamera.
   * @param {number} y - The vertical offset of the subcamera.
   * @param {number} width - The width of subcamera.
   * @param {number} height - The height of subcamera.
   */
  setViewOffset(t, e, i, n, s, r) {
    this.aspect = t / e, this.view === null && (this.view = {
      enabled: !0,
      fullWidth: 1,
      fullHeight: 1,
      offsetX: 0,
      offsetY: 0,
      width: 1,
      height: 1
    }), this.view.enabled = !0, this.view.fullWidth = t, this.view.fullHeight = e, this.view.offsetX = i, this.view.offsetY = n, this.view.width = s, this.view.height = r, this.updateProjectionMatrix();
  }
  /**
   * Removes the view offset from the projection matrix.
   */
  clearViewOffset() {
    this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix();
  }
  /**
   * Updates the camera's projection matrix. Must be called after any change of
   * camera properties.
   */
  updateProjectionMatrix() {
    const t = this.near;
    let e = t * Math.tan(lr * 0.5 * this.fov) / this.zoom, i = 2 * e, n = this.aspect * i, s = -0.5 * n;
    const r = this.view;
    if (this.view !== null && this.view.enabled) {
      const l = r.fullWidth, h = r.fullHeight;
      s += r.offsetX * n / l, e -= r.offsetY * i / h, n *= r.width / l, i *= r.height / h;
    }
    const o = this.filmOffset;
    o !== 0 && (s += t * o / this.getFilmWidth()), this.projectionMatrix.makePerspective(s, s + n, e, e - i, t, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.object.fov = this.fov, e.object.zoom = this.zoom, e.object.near = this.near, e.object.far = this.far, e.object.focus = this.focus, e.object.aspect = this.aspect, this.view !== null && (e.object.view = Object.assign({}, this.view)), e.object.filmGauge = this.filmGauge, e.object.filmOffset = this.filmOffset, e;
  }
}
const Pr = -90, Ir = 1;
class Ay extends le {
  /**
   * Constructs a new cube camera.
   *
   * @param {number} near - The camera's near plane.
   * @param {number} far - The camera's far plane.
   * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
   */
  constructor(t, e, i) {
    super(), this.type = "CubeCamera", this.renderTarget = i, this.coordinateSystem = null, this.activeMipmapLevel = 0;
    const n = new Ve(Pr, Ir, t, e);
    n.layers = this.layers, this.add(n);
    const s = new Ve(Pr, Ir, t, e);
    s.layers = this.layers, this.add(s);
    const r = new Ve(Pr, Ir, t, e);
    r.layers = this.layers, this.add(r);
    const o = new Ve(Pr, Ir, t, e);
    o.layers = this.layers, this.add(o);
    const l = new Ve(Pr, Ir, t, e);
    l.layers = this.layers, this.add(l);
    const h = new Ve(Pr, Ir, t, e);
    h.layers = this.layers, this.add(h);
  }
  /**
   * Must be called when the coordinate system of the cube camera is changed.
   */
  updateCoordinateSystem() {
    const t = this.coordinateSystem, e = this.children.concat(), [i, n, s, r, o, l] = e;
    for (const h of e) this.remove(h);
    if (t === Ni)
      i.up.set(0, 1, 0), i.lookAt(1, 0, 0), n.up.set(0, 1, 0), n.lookAt(-1, 0, 0), s.up.set(0, 0, -1), s.lookAt(0, 1, 0), r.up.set(0, 0, 1), r.lookAt(0, -1, 0), o.up.set(0, 1, 0), o.lookAt(0, 0, 1), l.up.set(0, 1, 0), l.lookAt(0, 0, -1);
    else if (t === ga)
      i.up.set(0, -1, 0), i.lookAt(-1, 0, 0), n.up.set(0, -1, 0), n.lookAt(1, 0, 0), s.up.set(0, 0, 1), s.lookAt(0, 1, 0), r.up.set(0, 0, -1), r.lookAt(0, -1, 0), o.up.set(0, -1, 0), o.lookAt(0, 0, 1), l.up.set(0, -1, 0), l.lookAt(0, 0, -1);
    else
      throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + t);
    for (const h of e)
      this.add(h), h.updateMatrixWorld();
  }
  /**
   * Calling this method will render the given scene with the given renderer
   * into the cube render target of the camera.
   *
   * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
   * @param {Scene} scene - The scene to render.
   */
  update(t, e) {
    this.parent === null && this.updateMatrixWorld();
    const { renderTarget: i, activeMipmapLevel: n } = this;
    this.coordinateSystem !== t.coordinateSystem && (this.coordinateSystem = t.coordinateSystem, this.updateCoordinateSystem());
    const [s, r, o, l, h, c] = this.children, u = t.getRenderTarget(), d = t.getActiveCubeFace(), p = t.getActiveMipmapLevel(), f = t.xr.enabled;
    t.xr.enabled = !1;
    const y = i.texture.generateMipmaps;
    i.texture.generateMipmaps = !1, t.setRenderTarget(i, 0, n), t.render(e, s), t.setRenderTarget(i, 1, n), t.render(e, r), t.setRenderTarget(i, 2, n), t.render(e, o), t.setRenderTarget(i, 3, n), t.render(e, l), t.setRenderTarget(i, 4, n), t.render(e, h), i.texture.generateMipmaps = y, t.setRenderTarget(i, 5, n), t.render(e, c), t.setRenderTarget(u, d, p), t.xr.enabled = f, i.texture.needsPMREMUpdate = !0;
  }
}
class Oo extends Ne {
  /**
   * Constructs a new cube texture.
   *
   * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
   * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space value.
   */
  constructor(t = [], e = is, i, n, s, r, o, l, h, c) {
    super(t, e, i, n, s, r, o, l, h, c), this.isCubeTexture = !0, this.flipY = !1;
  }
  /**
   * Alias for {@link CubeTexture#image}.
   *
   * @type {Array<Image>}
   */
  get images() {
    return this.image;
  }
  set images(t) {
    this.image = t;
  }
}
class Ey extends Rn {
  /**
   * Constructs a new cube render target.
   *
   * @param {number} [size=1] - The size of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(t = 1, e = {}) {
    super(t, t, e), this.isWebGLCubeRenderTarget = !0;
    const i = { width: t, height: t, depth: 1 }, n = [i, i, i, i, i, i];
    this.texture = new Oo(n), this._setTextureOptions(e), this.texture.isRenderTargetTexture = !0;
  }
  /**
   * Converts the given equirectangular texture to a cube map.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {Texture} texture - The equirectangular texture.
   * @return {WebGLCubeRenderTarget} A reference to this cube render target.
   */
  fromEquirectangularTexture(t, e) {
    this.texture.type = e.type, this.texture.colorSpace = e.colorSpace, this.texture.generateMipmaps = e.generateMipmaps, this.texture.minFilter = e.minFilter, this.texture.magFilter = e.magFilter;
    const i = {
      uniforms: {
        tEquirect: { value: null }
      },
      vertexShader: (
        /* glsl */
        `

				varying vec3 vWorldDirection;

				vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

					return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

				}

				void main() {

					vWorldDirection = transformDirection( position, modelMatrix );

					#include <begin_vertex>
					#include <project_vertex>

				}
			`
      ),
      fragmentShader: (
        /* glsl */
        `

				uniform sampler2D tEquirect;

				varying vec3 vWorldDirection;

				#include <common>

				void main() {

					vec3 direction = normalize( vWorldDirection );

					vec2 sampleUV = equirectUv( direction );

					gl_FragColor = texture2D( tEquirect, sampleUV );

				}
			`
      )
    }, n = new mr(5, 5, 5), s = new Xi({
      name: "CubemapFromEquirect",
      uniforms: _a(i.uniforms),
      vertexShader: i.vertexShader,
      fragmentShader: i.fragmentShader,
      side: He,
      blending: Yn
    });
    s.uniforms.tEquirect.value = e;
    const r = new re(n, s), o = e.minFilter;
    return e.minFilter === En && (e.minFilter = Ce), new Ay(1, 10, this).update(t, r), e.minFilter = o, r.geometry.dispose(), r.material.dispose(), this;
  }
  /**
   * Clears this cube render target.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
   * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
   * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
   */
  clear(t, e = !0, i = !0, n = !0) {
    const s = t.getRenderTarget();
    for (let r = 0; r < 6; r++)
      t.setRenderTarget(this, r), t.clear(e, i, n);
    t.setRenderTarget(s);
  }
}
let yi = class extends le {
  constructor() {
    super(), this.isGroup = !0, this.type = "Group";
  }
};
const Vv = { type: "move" };
class Th {
  /**
   * Constructs a new XR controller.
   */
  constructor() {
    this._targetRay = null, this._grip = null, this._hand = null;
  }
  /**
   * Returns a group representing the hand space of the XR controller.
   *
   * @return {Group} A group representing the hand space of the XR controller.
   */
  getHandSpace() {
    return this._hand === null && (this._hand = new yi(), this._hand.matrixAutoUpdate = !1, this._hand.visible = !1, this._hand.joints = {}, this._hand.inputState = { pinching: !1 }), this._hand;
  }
  /**
   * Returns a group representing the target ray space of the XR controller.
   *
   * @return {Group} A group representing the target ray space of the XR controller.
   */
  getTargetRaySpace() {
    return this._targetRay === null && (this._targetRay = new yi(), this._targetRay.matrixAutoUpdate = !1, this._targetRay.visible = !1, this._targetRay.hasLinearVelocity = !1, this._targetRay.linearVelocity = new E(), this._targetRay.hasAngularVelocity = !1, this._targetRay.angularVelocity = new E()), this._targetRay;
  }
  /**
   * Returns a group representing the grip space of the XR controller.
   *
   * @return {Group} A group representing the grip space of the XR controller.
   */
  getGripSpace() {
    return this._grip === null && (this._grip = new yi(), this._grip.matrixAutoUpdate = !1, this._grip.visible = !1, this._grip.hasLinearVelocity = !1, this._grip.linearVelocity = new E(), this._grip.hasAngularVelocity = !1, this._grip.angularVelocity = new E()), this._grip;
  }
  /**
   * Dispatches the given event to the groups representing
   * the different coordinate spaces of the XR controller.
   *
   * @param {Object} event - The event to dispatch.
   * @return {WebXRController} A reference to this instance.
   */
  dispatchEvent(t) {
    return this._targetRay !== null && this._targetRay.dispatchEvent(t), this._grip !== null && this._grip.dispatchEvent(t), this._hand !== null && this._hand.dispatchEvent(t), this;
  }
  /**
   * Connects the controller with the given XR input source.
   *
   * @param {XRInputSource} inputSource - The input source.
   * @return {WebXRController} A reference to this instance.
   */
  connect(t) {
    if (t && t.hand) {
      const e = this._hand;
      if (e)
        for (const i of t.hand.values())
          this._getHandJoint(e, i);
    }
    return this.dispatchEvent({ type: "connected", data: t }), this;
  }
  /**
   * Disconnects the controller from the given XR input source.
   *
   * @param {XRInputSource} inputSource - The input source.
   * @return {WebXRController} A reference to this instance.
   */
  disconnect(t) {
    return this.dispatchEvent({ type: "disconnected", data: t }), this._targetRay !== null && (this._targetRay.visible = !1), this._grip !== null && (this._grip.visible = !1), this._hand !== null && (this._hand.visible = !1), this;
  }
  /**
   * Updates the controller with the given input source, XR frame and reference space.
   * This updates the transformations of the groups that represent the different
   * coordinate systems of the controller.
   *
   * @param {XRInputSource} inputSource - The input source.
   * @param {XRFrame} frame - The XR frame.
   * @param {XRReferenceSpace} referenceSpace - The reference space.
   * @return {WebXRController} A reference to this instance.
   */
  update(t, e, i) {
    let n = null, s = null, r = null;
    const o = this._targetRay, l = this._grip, h = this._hand;
    if (t && e.session.visibilityState !== "visible-blurred") {
      if (h && t.hand) {
        r = !0;
        for (const y of t.hand.values()) {
          const g = e.getJointPose(y, i), m = this._getHandJoint(h, y);
          g !== null && (m.matrix.fromArray(g.transform.matrix), m.matrix.decompose(m.position, m.rotation, m.scale), m.matrixWorldNeedsUpdate = !0, m.jointRadius = g.radius), m.visible = g !== null;
        }
        const c = h.joints["index-finger-tip"], u = h.joints["thumb-tip"], d = c.position.distanceTo(u.position), p = 0.02, f = 5e-3;
        h.inputState.pinching && d > p + f ? (h.inputState.pinching = !1, this.dispatchEvent({
          type: "pinchend",
          handedness: t.handedness,
          target: this
        })) : !h.inputState.pinching && d <= p - f && (h.inputState.pinching = !0, this.dispatchEvent({
          type: "pinchstart",
          handedness: t.handedness,
          target: this
        }));
      } else
        l !== null && t.gripSpace && (s = e.getPose(t.gripSpace, i), s !== null && (l.matrix.fromArray(s.transform.matrix), l.matrix.decompose(l.position, l.rotation, l.scale), l.matrixWorldNeedsUpdate = !0, s.linearVelocity ? (l.hasLinearVelocity = !0, l.linearVelocity.copy(s.linearVelocity)) : l.hasLinearVelocity = !1, s.angularVelocity ? (l.hasAngularVelocity = !0, l.angularVelocity.copy(s.angularVelocity)) : l.hasAngularVelocity = !1));
      o !== null && (n = e.getPose(t.targetRaySpace, i), n === null && s !== null && (n = s), n !== null && (o.matrix.fromArray(n.transform.matrix), o.matrix.decompose(o.position, o.rotation, o.scale), o.matrixWorldNeedsUpdate = !0, n.linearVelocity ? (o.hasLinearVelocity = !0, o.linearVelocity.copy(n.linearVelocity)) : o.hasLinearVelocity = !1, n.angularVelocity ? (o.hasAngularVelocity = !0, o.angularVelocity.copy(n.angularVelocity)) : o.hasAngularVelocity = !1, this.dispatchEvent(Vv)));
    }
    return o !== null && (o.visible = n !== null), l !== null && (l.visible = s !== null), h !== null && (h.visible = r !== null), this;
  }
  /**
   * Returns a group representing the hand joint for the given input joint.
   *
   * @private
   * @param {Group} hand - The group representing the hand space.
   * @param {XRJointSpace} inputjoint - The hand joint data.
   * @return {Group} A group representing the hand joint for the given input joint.
   */
  _getHandJoint(t, e) {
    if (t.joints[e.jointName] === void 0) {
      const i = new yi();
      i.matrixAutoUpdate = !1, i.visible = !1, t.joints[e.jointName] = i, t.add(i);
    }
    return t.joints[e.jointName];
  }
}
class Vc {
  /**
   * Constructs a new fog.
   *
   * @param {number|Color} color - The fog's color.
   * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
   */
  constructor(t, e = 25e-5) {
    this.isFogExp2 = !0, this.name = "", this.color = new ct(t), this.density = e;
  }
  /**
   * Returns a new fog with copied values from this instance.
   *
   * @return {FogExp2} A clone of this instance.
   */
  clone() {
    return new Vc(this.color, this.density);
  }
  /**
   * Serializes the fog into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized fog
   */
  toJSON() {
    return {
      type: "FogExp2",
      name: this.name,
      color: this.color.getHex(),
      density: this.density
    };
  }
}
class Hc {
  /**
   * Constructs a new fog.
   *
   * @param {number|Color} color - The fog's color.
   * @param {number} [near=1] - The minimum distance to start applying fog.
   * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
   */
  constructor(t, e = 1, i = 1e3) {
    this.isFog = !0, this.name = "", this.color = new ct(t), this.near = e, this.far = i;
  }
  /**
   * Returns a new fog with copied values from this instance.
   *
   * @return {Fog} A clone of this instance.
   */
  clone() {
    return new Hc(this.color, this.near, this.far);
  }
  /**
   * Serializes the fog into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized fog
   */
  toJSON() {
    return {
      type: "Fog",
      name: this.name,
      color: this.color.getHex(),
      near: this.near,
      far: this.far
    };
  }
}
class ko extends le {
  /**
   * Constructs a new scene.
   */
  constructor() {
    super(), this.isScene = !0, this.type = "Scene", this.background = null, this.environment = null, this.fog = null, this.backgroundBlurriness = 0, this.backgroundIntensity = 1, this.backgroundRotation = new fn(), this.environmentIntensity = 1, this.environmentRotation = new fn(), this.overrideMaterial = null, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this }));
  }
  copy(t, e) {
    return super.copy(t, e), t.background !== null && (this.background = t.background.clone()), t.environment !== null && (this.environment = t.environment.clone()), t.fog !== null && (this.fog = t.fog.clone()), this.backgroundBlurriness = t.backgroundBlurriness, this.backgroundIntensity = t.backgroundIntensity, this.backgroundRotation.copy(t.backgroundRotation), this.environmentIntensity = t.environmentIntensity, this.environmentRotation.copy(t.environmentRotation), t.overrideMaterial !== null && (this.overrideMaterial = t.overrideMaterial.clone()), this.matrixAutoUpdate = t.matrixAutoUpdate, this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return this.fog !== null && (e.object.fog = this.fog.toJSON()), this.backgroundBlurriness > 0 && (e.object.backgroundBlurriness = this.backgroundBlurriness), this.backgroundIntensity !== 1 && (e.object.backgroundIntensity = this.backgroundIntensity), e.object.backgroundRotation = this.backgroundRotation.toArray(), this.environmentIntensity !== 1 && (e.object.environmentIntensity = this.environmentIntensity), e.object.environmentRotation = this.environmentRotation.toArray(), e;
  }
}
let Gc = class {
  /**
   * Constructs a new interleaved buffer.
   *
   * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
   * @param {number} stride - The number of typed-array elements per vertex.
   */
  constructor(t, e) {
    this.isInterleavedBuffer = !0, this.array = t, this.stride = e, this.count = t !== void 0 ? t.length / e : 0, this.usage = Co, this.updateRanges = [], this.version = 0, this.uuid = Oi();
  }
  /**
   * A callback function that is executed after the renderer has transferred the attribute array
   * data to the GPU.
   */
  onUploadCallback() {
  }
  /**
   * Flag to indicate that this attribute has changed and should be re-sent to
   * the GPU. Set this to `true` when you modify the value of the array.
   *
   * @type {number}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  /**
   * Sets the usage of this interleaved buffer.
   *
   * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
   * @return {InterleavedBuffer} A reference to this interleaved buffer.
   */
  setUsage(t) {
    return this.usage = t, this;
  }
  /**
   * Adds a range of data in the data array to be updated on the GPU.
   *
   * @param {number} start - Position at which to start update.
   * @param {number} count - The number of components to update.
   */
  addUpdateRange(t, e) {
    this.updateRanges.push({ start: t, count: e });
  }
  /**
   * Clears the update ranges.
   */
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  /**
   * Copies the values of the given interleaved buffer to this instance.
   *
   * @param {InterleavedBuffer} source - The interleaved buffer to copy.
   * @return {InterleavedBuffer} A reference to this instance.
   */
  copy(t) {
    return this.array = new t.array.constructor(t.array), this.count = t.count, this.stride = t.stride, this.usage = t.usage, this;
  }
  /**
   * Copies a vector from the given interleaved buffer to this one. The start
   * and destination position in the attribute buffers are represented by the
   * given indices.
   *
   * @param {number} index1 - The destination index into this interleaved buffer.
   * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
   * @param {number} index2 - The source index into the given interleaved buffer.
   * @return {InterleavedBuffer} A reference to this instance.
   */
  copyAt(t, e, i) {
    t *= this.stride, i *= e.stride;
    for (let n = 0, s = this.stride; n < s; n++)
      this.array[t + n] = e.array[i + n];
    return this;
  }
  /**
   * Sets the given array data in the interleaved buffer.
   *
   * @param {(TypedArray|Array)} value - The array data to set.
   * @param {number} [offset=0] - The offset in this interleaved buffer's array.
   * @return {InterleavedBuffer} A reference to this instance.
   */
  set(t, e = 0) {
    return this.array.set(t, e), this;
  }
  /**
   * Returns a new interleaved buffer with copied values from this instance.
   *
   * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
   * @return {InterleavedBuffer} A clone of this instance.
   */
  clone(t) {
    t.arrayBuffers === void 0 && (t.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = Oi()), t.arrayBuffers[this.array.buffer._uuid] === void 0 && (t.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer);
    const e = new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]), i = new this.constructor(e, this.stride);
    return i.setUsage(this.usage), i;
  }
  /**
   * Sets the given callback function that is executed after the Renderer has transferred
   * the array data to the GPU. Can be used to perform clean-up operations after
   * the upload when data are not needed anymore on the CPU side.
   *
   * @param {Function} callback - The `onUpload()` callback.
   * @return {InterleavedBuffer} A reference to this instance.
   */
  onUpload(t) {
    return this.onUploadCallback = t, this;
  }
  /**
   * Serializes the interleaved buffer into JSON.
   *
   * @param {Object} [data] - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized interleaved buffer.
   */
  toJSON(t) {
    return t.arrayBuffers === void 0 && (t.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = Oi()), t.arrayBuffers[this.array.buffer._uuid] === void 0 && (t.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer))), {
      uuid: this.uuid,
      buffer: this.array.buffer._uuid,
      type: this.array.constructor.name,
      stride: this.stride
    };
  }
};
const ui = /* @__PURE__ */ new E();
let un = class Ty {
  /**
   * Constructs a new interleaved buffer attribute.
   *
   * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
   * @param {number} itemSize - The item size.
   * @param {number} offset - The attribute offset into the buffer.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i, n = !1) {
    this.isInterleavedBufferAttribute = !0, this.name = "", this.data = t, this.itemSize = e, this.offset = i, this.normalized = n;
  }
  /**
   * The item count of this buffer attribute.
   *
   * @type {number}
   * @readonly
   */
  get count() {
    return this.data.count;
  }
  /**
   * The array holding the interleaved buffer attribute data.
   *
   * @type {TypedArray}
   */
  get array() {
    return this.data.array;
  }
  /**
   * Flag to indicate that this attribute has changed and should be re-sent to
   * the GPU. Set this to `true` when you modify the value of the array.
   *
   * @type {number}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    this.data.needsUpdate = t;
  }
  /**
   * Applies the given 4x4 matrix to the given attribute. Only works with
   * item size `3`.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  applyMatrix4(t) {
    for (let e = 0, i = this.data.count; e < i; e++)
      ui.fromBufferAttribute(this, e), ui.applyMatrix4(t), this.setXYZ(e, ui.x, ui.y, ui.z);
    return this;
  }
  /**
   * Applies the given 3x3 normal matrix to the given attribute. Only works with
   * item size `3`.
   *
   * @param {Matrix3} m - The normal matrix to apply.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  applyNormalMatrix(t) {
    for (let e = 0, i = this.count; e < i; e++)
      ui.fromBufferAttribute(this, e), ui.applyNormalMatrix(t), this.setXYZ(e, ui.x, ui.y, ui.z);
    return this;
  }
  /**
   * Applies the given 4x4 matrix to the given attribute. Only works with
   * item size `3` and with direction vectors.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  transformDirection(t) {
    for (let e = 0, i = this.count; e < i; e++)
      ui.fromBufferAttribute(this, e), ui.transformDirection(t), this.setXYZ(e, ui.x, ui.y, ui.z);
    return this;
  }
  /**
   * Returns the given component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} component - The component index.
   * @return {number} The returned value.
   */
  getComponent(t, e) {
    let i = this.array[t * this.data.stride + this.offset + e];
    return this.normalized && (i = mi(i, this.array)), i;
  }
  /**
   * Sets the given value to the given component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} component - The component index.
   * @param {number} value - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setComponent(t, e, i) {
    return this.normalized && (i = Yt(i, this.array)), this.data.array[t * this.data.stride + this.offset + e] = i, this;
  }
  /**
   * Sets the x component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setX(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.data.array[t * this.data.stride + this.offset] = e, this;
  }
  /**
   * Sets the y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} y - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setY(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.data.array[t * this.data.stride + this.offset + 1] = e, this;
  }
  /**
   * Sets the z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} z - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setZ(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.data.array[t * this.data.stride + this.offset + 2] = e, this;
  }
  /**
   * Sets the w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} w - The value to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setW(t, e) {
    return this.normalized && (e = Yt(e, this.array)), this.data.array[t * this.data.stride + this.offset + 3] = e, this;
  }
  /**
   * Returns the x component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The x component.
   */
  getX(t) {
    let e = this.data.array[t * this.data.stride + this.offset];
    return this.normalized && (e = mi(e, this.array)), e;
  }
  /**
   * Returns the y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The y component.
   */
  getY(t) {
    let e = this.data.array[t * this.data.stride + this.offset + 1];
    return this.normalized && (e = mi(e, this.array)), e;
  }
  /**
   * Returns the z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The z component.
   */
  getZ(t) {
    let e = this.data.array[t * this.data.stride + this.offset + 2];
    return this.normalized && (e = mi(e, this.array)), e;
  }
  /**
   * Returns the w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @return {number} The w component.
   */
  getW(t) {
    let e = this.data.array[t * this.data.stride + this.offset + 3];
    return this.normalized && (e = mi(e, this.array)), e;
  }
  /**
   * Sets the x and y component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setXY(t, e, i) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = i, this;
  }
  /**
   * Sets the x, y and z component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @param {number} z - The value for the z component to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setXYZ(t, e, i, n) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array), n = Yt(n, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = i, this.data.array[t + 2] = n, this;
  }
  /**
   * Sets the x, y, z and w component of the vector at the given index.
   *
   * @param {number} index - The index into the buffer attribute.
   * @param {number} x - The value for the x component to set.
   * @param {number} y - The value for the y component to set.
   * @param {number} z - The value for the z component to set.
   * @param {number} w - The value for the w component to set.
   * @return {InterleavedBufferAttribute} A reference to this instance.
   */
  setXYZW(t, e, i, n, s) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = Yt(e, this.array), i = Yt(i, this.array), n = Yt(n, this.array), s = Yt(s, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = i, this.data.array[t + 2] = n, this.data.array[t + 3] = s, this;
  }
  /**
   * Returns a new buffer attribute with copied values from this instance.
   *
   * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
   *
   * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
   * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
   */
  clone(t) {
    if (t === void 0) {
      console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");
      const e = [];
      for (let i = 0; i < this.count; i++) {
        const n = i * this.data.stride + this.offset;
        for (let s = 0; s < this.itemSize; s++)
          e.push(this.data.array[n + s]);
      }
      return new ie(new this.array.constructor(e), this.itemSize, this.normalized);
    } else
      return t.interleavedBuffers === void 0 && (t.interleavedBuffers = {}), t.interleavedBuffers[this.data.uuid] === void 0 && (t.interleavedBuffers[this.data.uuid] = this.data.clone(t)), new Ty(t.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  }
  /**
   * Serializes the buffer attribute into JSON.
   *
   * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
   *
   * @param {Object} [data] - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized buffer attribute.
   */
  toJSON(t) {
    if (t === void 0) {
      console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");
      const e = [];
      for (let i = 0; i < this.count; i++) {
        const n = i * this.data.stride + this.offset;
        for (let s = 0; s < this.itemSize; s++)
          e.push(this.data.array[n + s]);
      }
      return {
        itemSize: this.itemSize,
        type: this.array.constructor.name,
        array: e,
        normalized: this.normalized
      };
    } else
      return t.interleavedBuffers === void 0 && (t.interleavedBuffers = {}), t.interleavedBuffers[this.data.uuid] === void 0 && (t.interleavedBuffers[this.data.uuid] = this.data.toJSON(t)), {
        isInterleavedBufferAttribute: !0,
        itemSize: this.itemSize,
        data: this.data.uuid,
        offset: this.offset,
        normalized: this.normalized
      };
  }
};
class Wc extends hi {
  /**
   * Constructs a new sprite material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isSpriteMaterial = !0, this.type = "SpriteMaterial", this.color = new ct(16777215), this.map = null, this.alphaMap = null, this.rotation = 0, this.sizeAttenuation = !0, this.transparent = !0, this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.map = t.map, this.alphaMap = t.alphaMap, this.rotation = t.rotation, this.sizeAttenuation = t.sizeAttenuation, this.fog = t.fog, this;
  }
}
let Lr;
const ka = /* @__PURE__ */ new E(), Dr = /* @__PURE__ */ new E(), Fr = /* @__PURE__ */ new E(), Ur = /* @__PURE__ */ new J(), Va = /* @__PURE__ */ new J(), Cy = /* @__PURE__ */ new Vt(), ul = /* @__PURE__ */ new E(), Ha = /* @__PURE__ */ new E(), dl = /* @__PURE__ */ new E(), Yf = /* @__PURE__ */ new J(), zu = /* @__PURE__ */ new J(), Zf = /* @__PURE__ */ new J();
class mc extends le {
  /**
   * Constructs a new sprite.
   *
   * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
   */
  constructor(t = new Wc()) {
    if (super(), this.isSprite = !0, this.type = "Sprite", Lr === void 0) {
      Lr = new Ht();
      const e = new Float32Array([
        -0.5,
        -0.5,
        0,
        0,
        0,
        0.5,
        -0.5,
        0,
        1,
        0,
        0.5,
        0.5,
        0,
        1,
        1,
        -0.5,
        0.5,
        0,
        0,
        1
      ]), i = new Gc(e, 5);
      Lr.setIndex([0, 1, 2, 0, 2, 3]), Lr.setAttribute("position", new un(i, 3, 0, !1)), Lr.setAttribute("uv", new un(i, 2, 3, !1));
    }
    this.geometry = Lr, this.material = t, this.center = new J(0.5, 0.5), this.count = 1;
  }
  /**
   * Computes intersection points between a casted ray and this sprite.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(t, e) {
    t.camera === null && console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'), Dr.setFromMatrixScale(this.matrixWorld), Cy.copy(t.camera.matrixWorld), this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse, this.matrixWorld), Fr.setFromMatrixPosition(this.modelViewMatrix), t.camera.isPerspectiveCamera && this.material.sizeAttenuation === !1 && Dr.multiplyScalar(-Fr.z);
    const i = this.material.rotation;
    let n, s;
    i !== 0 && (s = Math.cos(i), n = Math.sin(i));
    const r = this.center;
    pl(ul.set(-0.5, -0.5, 0), Fr, r, Dr, n, s), pl(Ha.set(0.5, -0.5, 0), Fr, r, Dr, n, s), pl(dl.set(0.5, 0.5, 0), Fr, r, Dr, n, s), Yf.set(0, 0), zu.set(1, 0), Zf.set(1, 1);
    let o = t.ray.intersectTriangle(ul, Ha, dl, !1, ka);
    if (o === null && (pl(Ha.set(-0.5, 0.5, 0), Fr, r, Dr, n, s), zu.set(0, 1), o = t.ray.intersectTriangle(ul, dl, Ha, !1, ka), o === null))
      return;
    const l = t.ray.origin.distanceTo(ka);
    l < t.near || l > t.far || e.push({
      distance: l,
      point: ka.clone(),
      uv: bs.getInterpolation(ka, ul, Ha, dl, Yf, zu, Zf, new J()),
      face: null,
      object: this
    });
  }
  copy(t, e) {
    return super.copy(t, e), t.center !== void 0 && this.center.copy(t.center), this.material = t.material, this;
  }
}
function pl(a, t, e, i, n, s) {
  Ur.subVectors(a, e).addScalar(0.5).multiply(i), n !== void 0 ? (Va.x = s * Ur.x - n * Ur.y, Va.y = n * Ur.x + s * Ur.y) : Va.copy(Ur), a.copy(t), a.x += Va.x, a.y += Va.y, a.applyMatrix4(Cy);
}
const fl = /* @__PURE__ */ new E(), jf = /* @__PURE__ */ new E();
class Ry extends le {
  /**
   * Constructs a new LOD.
   */
  constructor() {
    super(), this.isLOD = !0, this._currentLevel = 0, this.type = "LOD", Object.defineProperties(this, {
      /**
       * This array holds the LOD levels.
       *
       * @name LOD#levels
       * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
       */
      levels: {
        enumerable: !0,
        value: []
      }
    }), this.autoUpdate = !0;
  }
  copy(t) {
    super.copy(t, !1);
    const e = t.levels;
    for (let i = 0, n = e.length; i < n; i++) {
      const s = e[i];
      this.addLevel(s.object.clone(), s.distance, s.hysteresis);
    }
    return this.autoUpdate = t.autoUpdate, this;
  }
  /**
   * Adds a mesh that will display at a certain distance and greater. Typically
   * the further away the distance, the lower the detail on the mesh.
   *
   * @param {Object3D} object - The 3D object to display at this level.
   * @param {number} [distance=0] - The distance at which to display this level of detail.
   * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
   * @return {LOD} A reference to this instance.
   */
  addLevel(t, e = 0, i = 0) {
    e = Math.abs(e);
    const n = this.levels;
    let s;
    for (s = 0; s < n.length && !(e < n[s].distance); s++)
      ;
    return n.splice(s, 0, { distance: e, hysteresis: i, object: t }), this.add(t), this;
  }
  /**
   * Removes an existing level, based on the distance from the camera.
   * Returns `true` when the level has been removed. Otherwise `false`.
   *
   * @param {number} distance - Distance of the level to remove.
   * @return {boolean} Whether the level has been removed or not.
   */
  removeLevel(t) {
    const e = this.levels;
    for (let i = 0; i < e.length; i++)
      if (e[i].distance === t) {
        const n = e.splice(i, 1);
        return this.remove(n[0].object), !0;
      }
    return !1;
  }
  /**
   * Returns the currently active LOD level index.
   *
   * @return {number} The current active LOD level index.
   */
  getCurrentLevel() {
    return this._currentLevel;
  }
  /**
   * Returns a reference to the first 3D object that is greater than
   * the given distance.
   *
   * @param {number} distance - The LOD distance.
   * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
   */
  getObjectForDistance(t) {
    const e = this.levels;
    if (e.length > 0) {
      let i, n;
      for (i = 1, n = e.length; i < n; i++) {
        let s = e[i].distance;
        if (e[i].object.visible && (s -= s * e[i].hysteresis), t < s)
          break;
      }
      return e[i - 1].object;
    }
    return null;
  }
  /**
   * Computes intersection points between a casted ray and this LOD.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(t, e) {
    if (this.levels.length > 0) {
      fl.setFromMatrixPosition(this.matrixWorld);
      const n = t.ray.origin.distanceTo(fl);
      this.getObjectForDistance(n).raycast(t, e);
    }
  }
  /**
   * Updates the LOD by computing which LOD level should be visible according
   * to the current distance of the given camera.
   *
   * @param {Camera} camera - The camera the scene is rendered with.
   */
  update(t) {
    const e = this.levels;
    if (e.length > 1) {
      fl.setFromMatrixPosition(t.matrixWorld), jf.setFromMatrixPosition(this.matrixWorld);
      const i = fl.distanceTo(jf) / t.zoom;
      e[0].object.visible = !0;
      let n, s;
      for (n = 1, s = e.length; n < s; n++) {
        let r = e[n].distance;
        if (e[n].object.visible && (r -= r * e[n].hysteresis), i >= r)
          e[n - 1].object.visible = !1, e[n].object.visible = !0;
        else
          break;
      }
      for (this._currentLevel = n - 1; n < s; n++)
        e[n].object.visible = !1;
    }
  }
  toJSON(t) {
    const e = super.toJSON(t);
    this.autoUpdate === !1 && (e.object.autoUpdate = !1), e.object.levels = [];
    const i = this.levels;
    for (let n = 0, s = i.length; n < s; n++) {
      const r = i[n];
      e.object.levels.push({
        object: r.object.uuid,
        distance: r.distance,
        hysteresis: r.hysteresis
      });
    }
    return e;
  }
}
const Jf = /* @__PURE__ */ new E(), Kf = /* @__PURE__ */ new Qt(), Qf = /* @__PURE__ */ new Qt(), Hv = /* @__PURE__ */ new E(), tm = /* @__PURE__ */ new Vt(), ml = /* @__PURE__ */ new E(), Nu = /* @__PURE__ */ new Re(), em = /* @__PURE__ */ new Vt(), Ou = /* @__PURE__ */ new Aa();
class Py extends re {
  /**
   * Constructs a new skinned mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(t, e) {
    super(t, e), this.isSkinnedMesh = !0, this.type = "SkinnedMesh", this.bindMode = Kd, this.bindMatrix = new Vt(), this.bindMatrixInverse = new Vt(), this.boundingBox = null, this.boundingSphere = null;
  }
  /**
   * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
   * The bounding box is not automatically computed by the engine; this method must be called by your app.
   * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
   * the current animation state.
   */
  computeBoundingBox() {
    const t = this.geometry;
    this.boundingBox === null && (this.boundingBox = new we()), this.boundingBox.makeEmpty();
    const e = t.getAttribute("position");
    for (let i = 0; i < e.count; i++)
      this.getVertexPosition(i, ml), this.boundingBox.expandByPoint(ml);
  }
  /**
   * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
   * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
   * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
   * per frame in order to reflect the current animation state.
   */
  computeBoundingSphere() {
    const t = this.geometry;
    this.boundingSphere === null && (this.boundingSphere = new Re()), this.boundingSphere.makeEmpty();
    const e = t.getAttribute("position");
    for (let i = 0; i < e.count; i++)
      this.getVertexPosition(i, ml), this.boundingSphere.expandByPoint(ml);
  }
  copy(t, e) {
    return super.copy(t, e), this.bindMode = t.bindMode, this.bindMatrix.copy(t.bindMatrix), this.bindMatrixInverse.copy(t.bindMatrixInverse), this.skeleton = t.skeleton, t.boundingBox !== null && (this.boundingBox = t.boundingBox.clone()), t.boundingSphere !== null && (this.boundingSphere = t.boundingSphere.clone()), this;
  }
  raycast(t, e) {
    const i = this.material, n = this.matrixWorld;
    i !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), Nu.copy(this.boundingSphere), Nu.applyMatrix4(n), t.ray.intersectsSphere(Nu) !== !1 && (em.copy(n).invert(), Ou.copy(t.ray).applyMatrix4(em), !(this.boundingBox !== null && Ou.intersectsBox(this.boundingBox) === !1) && this._computeIntersections(t, e, Ou)));
  }
  getVertexPosition(t, e) {
    return super.getVertexPosition(t, e), this.applyBoneTransform(t, e), e;
  }
  /**
   * Binds the given skeleton to the skinned mesh.
   *
   * @param {Skeleton} skeleton - The skeleton to bind.
   * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
   * the skinned mesh's world matrix will be used instead.
   */
  bind(t, e) {
    this.skeleton = t, e === void 0 && (this.updateMatrixWorld(!0), this.skeleton.calculateInverses(), e = this.matrixWorld), this.bindMatrix.copy(e), this.bindMatrixInverse.copy(e).invert();
  }
  /**
   * This method sets the skinned mesh in the rest pose).
   */
  pose() {
    this.skeleton.pose();
  }
  /**
   * Normalizes the skin weights which are defined as a buffer attribute
   * in the skinned mesh's geometry.
   */
  normalizeSkinWeights() {
    const t = new Qt(), e = this.geometry.attributes.skinWeight;
    for (let i = 0, n = e.count; i < n; i++) {
      t.fromBufferAttribute(e, i);
      const s = 1 / t.manhattanLength();
      s !== 1 / 0 ? t.multiplyScalar(s) : t.set(1, 0, 0, 0), e.setXYZW(i, t.x, t.y, t.z, t.w);
    }
  }
  updateMatrixWorld(t) {
    super.updateMatrixWorld(t), this.bindMode === Kd ? this.bindMatrixInverse.copy(this.matrixWorld).invert() : this.bindMode === ty ? this.bindMatrixInverse.copy(this.bindMatrix).invert() : console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode);
  }
  /**
   * Applies the bone transform associated with the given index to the given
   * vertex position. Returns the updated vector.
   *
   * @param {number} index - The vertex index.
   * @param {Vector3} target - The target object that is used to store the method's result.
   * the skinned mesh's world matrix will be used instead.
   * @return {Vector3} The updated vertex position.
   */
  applyBoneTransform(t, e) {
    const i = this.skeleton, n = this.geometry;
    Kf.fromBufferAttribute(n.attributes.skinIndex, t), Qf.fromBufferAttribute(n.attributes.skinWeight, t), Jf.copy(e).applyMatrix4(this.bindMatrix), e.set(0, 0, 0);
    for (let s = 0; s < 4; s++) {
      const r = Qf.getComponent(s);
      if (r !== 0) {
        const o = Kf.getComponent(s);
        tm.multiplyMatrices(i.bones[o].matrixWorld, i.boneInverses[o]), e.addScaledVector(Hv.copy(Jf).applyMatrix4(tm), r);
      }
    }
    return e.applyMatrix4(this.bindMatrixInverse);
  }
}
class Op extends le {
  /**
   * Constructs a new bone.
   */
  constructor() {
    super(), this.isBone = !0, this.type = "Bone";
  }
}
class Cn extends Ne {
  /**
   * Constructs a new data texture.
   *
   * @param {?TypedArray} [data=null] - The buffer data.
   * @param {number} [width=1] - The width of the texture.
   * @param {number} [height=1] - The height of the texture.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=NearestFilter] - The mag filter value.
   * @param {number} [minFilter=NearestFilter] - The min filter value.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space.
   */
  constructor(t = null, e = 1, i = 1, n, s, r, o, l, h = je, c = je, u, d) {
    super(null, r, o, l, h, c, n, s, u, d), this.isDataTexture = !0, this.image = { data: t, width: e, height: i }, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
  }
}
const im = /* @__PURE__ */ new Vt(), Gv = /* @__PURE__ */ new Vt();
class qc {
  /**
   * Constructs a new skeleton.
   *
   * @param {Array<Bone>} [bones] - An array of bones.
   * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
   * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
   */
  constructor(t = [], e = []) {
    this.uuid = Oi(), this.bones = t.slice(0), this.boneInverses = e, this.boneMatrices = null, this.boneTexture = null, this.init();
  }
  /**
   * Initializes the skeleton. This method gets automatically called by the constructor
   * but depending on how the skeleton is created it might be necessary to call this method
   * manually.
   */
  init() {
    const t = this.bones, e = this.boneInverses;
    if (this.boneMatrices = new Float32Array(t.length * 16), e.length === 0)
      this.calculateInverses();
    else if (t.length !== e.length) {
      console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."), this.boneInverses = [];
      for (let i = 0, n = this.bones.length; i < n; i++)
        this.boneInverses.push(new Vt());
    }
  }
  /**
   * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
   * and fills it with new matrices.
   */
  calculateInverses() {
    this.boneInverses.length = 0;
    for (let t = 0, e = this.bones.length; t < e; t++) {
      const i = new Vt();
      this.bones[t] && i.copy(this.bones[t].matrixWorld).invert(), this.boneInverses.push(i);
    }
  }
  /**
   * Resets the skeleton to the base pose.
   */
  pose() {
    for (let t = 0, e = this.bones.length; t < e; t++) {
      const i = this.bones[t];
      i && i.matrixWorld.copy(this.boneInverses[t]).invert();
    }
    for (let t = 0, e = this.bones.length; t < e; t++) {
      const i = this.bones[t];
      i && (i.parent && i.parent.isBone ? (i.matrix.copy(i.parent.matrixWorld).invert(), i.matrix.multiply(i.matrixWorld)) : i.matrix.copy(i.matrixWorld), i.matrix.decompose(i.position, i.quaternion, i.scale));
    }
  }
  /**
   * Resets the skeleton to the base pose.
   */
  update() {
    const t = this.bones, e = this.boneInverses, i = this.boneMatrices, n = this.boneTexture;
    for (let s = 0, r = t.length; s < r; s++) {
      const o = t[s] ? t[s].matrixWorld : Gv;
      im.multiplyMatrices(o, e[s]), im.toArray(i, s * 16);
    }
    n !== null && (n.needsUpdate = !0);
  }
  /**
   * Returns a new skeleton with copied values from this instance.
   *
   * @return {Skeleton} A clone of this instance.
   */
  clone() {
    return new qc(this.bones, this.boneInverses);
  }
  /**
   * Computes a data texture for passing bone data to the vertex shader.
   *
   * @return {Skeleton} A reference of this instance.
   */
  computeBoneTexture() {
    let t = Math.sqrt(this.bones.length * 4);
    t = Math.ceil(t / 4) * 4, t = Math.max(t, 4);
    const e = new Float32Array(t * t * 4);
    e.set(this.boneMatrices);
    const i = new Cn(e, t, t, gi, wi);
    return i.needsUpdate = !0, this.boneMatrices = e, this.boneTexture = i, this;
  }
  /**
   * Searches through the skeleton's bone array and returns the first with a
   * matching name.
   *
   * @param {string} name - The name of the bone.
   * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
   */
  getBoneByName(t) {
    for (let e = 0, i = this.bones.length; e < i; e++) {
      const n = this.bones[e];
      if (n.name === t)
        return n;
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.boneTexture !== null && (this.boneTexture.dispose(), this.boneTexture = null);
  }
  /**
   * Setups the skeleton by the given JSON and bones.
   *
   * @param {Object} json - The skeleton as serialized JSON.
   * @param {Object<string, Bone>} bones - An array of bones.
   * @return {Skeleton} A reference of this instance.
   */
  fromJSON(t, e) {
    this.uuid = t.uuid;
    for (let i = 0, n = t.bones.length; i < n; i++) {
      const s = t.bones[i];
      let r = e[s];
      r === void 0 && (console.warn("THREE.Skeleton: No bone found with UUID:", s), r = new Op()), this.bones.push(r), this.boneInverses.push(new Vt().fromArray(t.boneInverses[i]));
    }
    return this.init(), this;
  }
  /**
   * Serializes the skeleton into JSON.
   *
   * @return {Object} A JSON object representing the serialized skeleton.
   * @see {@link ObjectLoader#parse}
   */
  toJSON() {
    const t = {
      metadata: {
        version: 4.7,
        type: "Skeleton",
        generator: "Skeleton.toJSON"
      },
      bones: [],
      boneInverses: []
    };
    t.uuid = this.uuid;
    const e = this.bones, i = this.boneInverses;
    for (let n = 0, s = e.length; n < s; n++) {
      const r = e[n];
      t.bones.push(r.uuid);
      const o = i[n];
      t.boneInverses.push(o.toArray());
    }
    return t;
  }
}
class xa extends ie {
  /**
   * Constructs a new instanced buffer attribute.
   *
   * @param {TypedArray} array - The array holding the attribute data.
   * @param {number} itemSize - The item size.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
   */
  constructor(t, e, i, n = 1) {
    super(t, e, i), this.isInstancedBufferAttribute = !0, this.meshPerAttribute = n;
  }
  copy(t) {
    return super.copy(t), this.meshPerAttribute = t.meshPerAttribute, this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.meshPerAttribute = this.meshPerAttribute, t.isInstancedBufferAttribute = !0, t;
  }
}
const Br = /* @__PURE__ */ new Vt(), nm = /* @__PURE__ */ new Vt(), gl = [], sm = /* @__PURE__ */ new we(), Wv = /* @__PURE__ */ new Vt(), Ga = /* @__PURE__ */ new re(), Wa = /* @__PURE__ */ new Re();
class Iy extends re {
  /**
   * Constructs a new instanced mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   * @param {number} count - The number of instances.
   */
  constructor(t, e, i) {
    super(t, e), this.isInstancedMesh = !0, this.instanceMatrix = new xa(new Float32Array(i * 16), 16), this.instanceColor = null, this.morphTexture = null, this.count = i, this.boundingBox = null, this.boundingSphere = null;
    for (let n = 0; n < i; n++)
      this.setMatrixAt(n, Wv);
  }
  /**
   * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
   * The bounding box is not automatically computed by the engine; this method must be called by your app.
   * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
   */
  computeBoundingBox() {
    const t = this.geometry, e = this.count;
    this.boundingBox === null && (this.boundingBox = new we()), t.boundingBox === null && t.computeBoundingBox(), this.boundingBox.makeEmpty();
    for (let i = 0; i < e; i++)
      this.getMatrixAt(i, Br), sm.copy(t.boundingBox).applyMatrix4(Br), this.boundingBox.union(sm);
  }
  /**
   * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
   * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
   * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
   */
  computeBoundingSphere() {
    const t = this.geometry, e = this.count;
    this.boundingSphere === null && (this.boundingSphere = new Re()), t.boundingSphere === null && t.computeBoundingSphere(), this.boundingSphere.makeEmpty();
    for (let i = 0; i < e; i++)
      this.getMatrixAt(i, Br), Wa.copy(t.boundingSphere).applyMatrix4(Br), this.boundingSphere.union(Wa);
  }
  copy(t, e) {
    return super.copy(t, e), this.instanceMatrix.copy(t.instanceMatrix), t.morphTexture !== null && (this.morphTexture = t.morphTexture.clone()), t.instanceColor !== null && (this.instanceColor = t.instanceColor.clone()), this.count = t.count, t.boundingBox !== null && (this.boundingBox = t.boundingBox.clone()), t.boundingSphere !== null && (this.boundingSphere = t.boundingSphere.clone()), this;
  }
  /**
   * Gets the color of the defined instance.
   *
   * @param {number} index - The instance index.
   * @param {Color} color - The target object that is used to store the method's result.
   */
  getColorAt(t, e) {
    e.fromArray(this.instanceColor.array, t * 3);
  }
  /**
   * Gets the local transformation matrix of the defined instance.
   *
   * @param {number} index - The instance index.
   * @param {Matrix4} matrix - The target object that is used to store the method's result.
   */
  getMatrixAt(t, e) {
    e.fromArray(this.instanceMatrix.array, t * 16);
  }
  /**
   * Gets the morph target weights of the defined instance.
   *
   * @param {number} index - The instance index.
   * @param {Mesh} object - The target object that is used to store the method's result.
   */
  getMorphAt(t, e) {
    const i = e.morphTargetInfluences, n = this.morphTexture.source.data.data, s = i.length + 1, r = t * s + 1;
    for (let o = 0; o < i.length; o++)
      i[o] = n[r + o];
  }
  raycast(t, e) {
    const i = this.matrixWorld, n = this.count;
    if (Ga.geometry = this.geometry, Ga.material = this.material, Ga.material !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), Wa.copy(this.boundingSphere), Wa.applyMatrix4(i), t.ray.intersectsSphere(Wa) !== !1))
      for (let s = 0; s < n; s++) {
        this.getMatrixAt(s, Br), nm.multiplyMatrices(i, Br), Ga.matrixWorld = nm, Ga.raycast(t, gl);
        for (let r = 0, o = gl.length; r < o; r++) {
          const l = gl[r];
          l.instanceId = s, l.object = this, e.push(l);
        }
        gl.length = 0;
      }
  }
  /**
   * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
   * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
   *
   * @param {number} index - The instance index.
   * @param {Color} color - The instance color.
   */
  setColorAt(t, e) {
    this.instanceColor === null && (this.instanceColor = new xa(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3)), e.toArray(this.instanceColor.array, t * 3);
  }
  /**
   * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
   * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
   *
   * @param {number} index - The instance index.
   * @param {Matrix4} matrix - The local transformation.
   */
  setMatrixAt(t, e) {
    e.toArray(this.instanceMatrix.array, t * 16);
  }
  /**
   * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
   * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
   *
   * @param {number} index - The instance index.
   * @param {Mesh} object -  A mesh which `morphTargetInfluences` property containing the morph target weights
   * of a single instance.
   */
  setMorphAt(t, e) {
    const i = e.morphTargetInfluences, n = i.length + 1;
    this.morphTexture === null && (this.morphTexture = new Cn(new Float32Array(n * this.count), n, this.count, Lc, wi));
    const s = this.morphTexture.source.data.data;
    let r = 0;
    for (let h = 0; h < i.length; h++)
      r += i[h];
    const o = this.geometry.morphTargetsRelative ? 1 : 1 - r, l = n * t;
    s[l] = o, s.set(i, l + 1);
  }
  updateMorphTargets() {
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" }), this.morphTexture !== null && (this.morphTexture.dispose(), this.morphTexture = null);
  }
}
const ku = /* @__PURE__ */ new E(), qv = /* @__PURE__ */ new E(), $v = /* @__PURE__ */ new Xt();
class qn {
  /**
   * Constructs a new plane.
   *
   * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
   * @param {number} [constant=0] - The signed distance from the origin to the plane.
   */
  constructor(t = new E(1, 0, 0), e = 0) {
    this.isPlane = !0, this.normal = t, this.constant = e;
  }
  /**
   * Sets the plane components by copying the given values.
   *
   * @param {Vector3} normal - The normal.
   * @param {number} constant - The constant.
   * @return {Plane} A reference to this plane.
   */
  set(t, e) {
    return this.normal.copy(t), this.constant = e, this;
  }
  /**
   * Sets the plane components by defining `x`, `y`, `z` as the
   * plane normal and `w` as the constant.
   *
   * @param {number} x - The value for the normal's x component.
   * @param {number} y - The value for the normal's y component.
   * @param {number} z - The value for the normal's z component.
   * @param {number} w - The constant value.
   * @return {Plane} A reference to this plane.
   */
  setComponents(t, e, i, n) {
    return this.normal.set(t, e, i), this.constant = n, this;
  }
  /**
   * Sets the plane from the given normal and coplanar point (that is a point
   * that lies onto the plane).
   *
   * @param {Vector3} normal - The normal.
   * @param {Vector3} point - A coplanar point.
   * @return {Plane} A reference to this plane.
   */
  setFromNormalAndCoplanarPoint(t, e) {
    return this.normal.copy(t), this.constant = -e.dot(this.normal), this;
  }
  /**
   * Sets the plane from three coplanar points. The winding order is
   * assumed to be counter-clockwise, and determines the direction of
   * the plane normal.
   *
   * @param {Vector3} a - The first coplanar point.
   * @param {Vector3} b - The second coplanar point.
   * @param {Vector3} c - The third coplanar point.
   * @return {Plane} A reference to this plane.
   */
  setFromCoplanarPoints(t, e, i) {
    const n = ku.subVectors(i, e).cross(qv.subVectors(t, e)).normalize();
    return this.setFromNormalAndCoplanarPoint(n, t), this;
  }
  /**
   * Copies the values of the given plane to this instance.
   *
   * @param {Plane} plane - The plane to copy.
   * @return {Plane} A reference to this plane.
   */
  copy(t) {
    return this.normal.copy(t.normal), this.constant = t.constant, this;
  }
  /**
   * Normalizes the plane normal and adjusts the constant accordingly.
   *
   * @return {Plane} A reference to this plane.
   */
  normalize() {
    const t = 1 / this.normal.length();
    return this.normal.multiplyScalar(t), this.constant *= t, this;
  }
  /**
   * Negates both the plane normal and the constant.
   *
   * @return {Plane} A reference to this plane.
   */
  negate() {
    return this.constant *= -1, this.normal.negate(), this;
  }
  /**
   * Returns the signed distance from the given point to this plane.
   *
   * @param {Vector3} point - The point to compute the distance for.
   * @return {number} The signed distance.
   */
  distanceToPoint(t) {
    return this.normal.dot(t) + this.constant;
  }
  /**
   * Returns the signed distance from the given sphere to this plane.
   *
   * @param {Sphere} sphere - The sphere to compute the distance for.
   * @return {number} The signed distance.
   */
  distanceToSphere(t) {
    return this.distanceToPoint(t.center) - t.radius;
  }
  /**
   * Projects a the given point onto the plane.
   *
   * @param {Vector3} point - The point to project.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The projected point on the plane.
   */
  projectPoint(t, e) {
    return e.copy(t).addScaledVector(this.normal, -this.distanceToPoint(t));
  }
  /**
   * Returns the intersection point of the passed line and the plane. Returns
   * `null` if the line does not intersect. Returns the line's starting point if
   * the line is coplanar with the plane.
   *
   * @param {Line3} line - The line to compute the intersection for.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point.
   */
  intersectLine(t, e) {
    const i = t.delta(ku), n = this.normal.dot(i);
    if (n === 0)
      return this.distanceToPoint(t.start) === 0 ? e.copy(t.start) : null;
    const s = -(t.start.dot(this.normal) + this.constant) / n;
    return s < 0 || s > 1 ? null : e.copy(t.start).addScaledVector(i, s);
  }
  /**
   * Returns `true` if the given line segment intersects with (passes through) the plane.
   *
   * @param {Line3} line - The line to test.
   * @return {boolean} Whether the given line segment intersects with the plane or not.
   */
  intersectsLine(t) {
    const e = this.distanceToPoint(t.start), i = this.distanceToPoint(t.end);
    return e < 0 && i > 0 || i < 0 && e > 0;
  }
  /**
   * Returns `true` if the given bounding box intersects with the plane.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the given bounding box intersects with the plane or not.
   */
  intersectsBox(t) {
    return t.intersectsPlane(this);
  }
  /**
   * Returns `true` if the given bounding sphere intersects with the plane.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
   */
  intersectsSphere(t) {
    return t.intersectsPlane(this);
  }
  /**
   * Returns a coplanar vector to the plane, by calculating the
   * projection of the normal at the origin onto the plane.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The coplanar point.
   */
  coplanarPoint(t) {
    return t.copy(this.normal).multiplyScalar(-this.constant);
  }
  /**
   * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
   *
   * The optional normal matrix can be pre-computed like so:
   * ```js
   * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
   * ```
   *
   * @param {Matrix4} matrix - The transformation matrix.
   * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
   * @return {Plane} A reference to this plane.
   */
  applyMatrix4(t, e) {
    const i = e || $v.getNormalMatrix(t), n = this.coplanarPoint(ku).applyMatrix4(t), s = this.normal.applyMatrix3(i).normalize();
    return this.constant = -n.dot(s), this;
  }
  /**
   * Translates the plane by the distance defined by the given offset vector.
   * Note that this only affects the plane constant and will not affect the normal vector.
   *
   * @param {Vector3} offset - The offset vector.
   * @return {Plane} A reference to this plane.
   */
  translate(t) {
    return this.constant -= t.dot(this.normal), this;
  }
  /**
   * Returns `true` if this plane is equal with the given one.
   *
   * @param {Plane} plane - The plane to test for equality.
   * @return {boolean} Whether this plane is equal with the given one.
   */
  equals(t) {
    return t.normal.equals(this.normal) && t.constant === this.constant;
  }
  /**
   * Returns a new plane with copied values from this instance.
   *
   * @return {Plane} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
const Vs = /* @__PURE__ */ new Re(), Xv = /* @__PURE__ */ new J(0.5, 0.5), yl = /* @__PURE__ */ new E();
class Ea {
  /**
   * Constructs a new frustum.
   *
   * @param {Plane} [p0] - The first plane that encloses the frustum.
   * @param {Plane} [p1] - The second plane that encloses the frustum.
   * @param {Plane} [p2] - The third plane that encloses the frustum.
   * @param {Plane} [p3] - The fourth plane that encloses the frustum.
   * @param {Plane} [p4] - The fifth plane that encloses the frustum.
   * @param {Plane} [p5] - The sixth plane that encloses the frustum.
   */
  constructor(t = new qn(), e = new qn(), i = new qn(), n = new qn(), s = new qn(), r = new qn()) {
    this.planes = [t, e, i, n, s, r];
  }
  /**
   * Sets the frustum planes by copying the given planes.
   *
   * @param {Plane} [p0] - The first plane that encloses the frustum.
   * @param {Plane} [p1] - The second plane that encloses the frustum.
   * @param {Plane} [p2] - The third plane that encloses the frustum.
   * @param {Plane} [p3] - The fourth plane that encloses the frustum.
   * @param {Plane} [p4] - The fifth plane that encloses the frustum.
   * @param {Plane} [p5] - The sixth plane that encloses the frustum.
   * @return {Frustum} A reference to this frustum.
   */
  set(t, e, i, n, s, r) {
    const o = this.planes;
    return o[0].copy(t), o[1].copy(e), o[2].copy(i), o[3].copy(n), o[4].copy(s), o[5].copy(r), this;
  }
  /**
   * Copies the values of the given frustum to this instance.
   *
   * @param {Frustum} frustum - The frustum to copy.
   * @return {Frustum} A reference to this frustum.
   */
  copy(t) {
    const e = this.planes;
    for (let i = 0; i < 6; i++)
      e[i].copy(t.planes[i]);
    return this;
  }
  /**
   * Sets the frustum planes from the given projection matrix.
   *
   * @param {Matrix4} m - The projection matrix.
   * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
   * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
   * @return {Frustum} A reference to this frustum.
   */
  setFromProjectionMatrix(t, e = Ni, i = !1) {
    const n = this.planes, s = t.elements, r = s[0], o = s[1], l = s[2], h = s[3], c = s[4], u = s[5], d = s[6], p = s[7], f = s[8], y = s[9], g = s[10], m = s[11], v = s[12], x = s[13], _ = s[14], S = s[15];
    if (n[0].setComponents(h - r, p - c, m - f, S - v).normalize(), n[1].setComponents(h + r, p + c, m + f, S + v).normalize(), n[2].setComponents(h + o, p + u, m + y, S + x).normalize(), n[3].setComponents(h - o, p - u, m - y, S - x).normalize(), i)
      n[4].setComponents(l, d, g, _).normalize(), n[5].setComponents(h - l, p - d, m - g, S - _).normalize();
    else if (n[4].setComponents(h - l, p - d, m - g, S - _).normalize(), e === Ni)
      n[5].setComponents(h + l, p + d, m + g, S + _).normalize();
    else if (e === ga)
      n[5].setComponents(l, d, g, _).normalize();
    else
      throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + e);
    return this;
  }
  /**
   * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
   *
   * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
   *
   * @param {Object3D} object - The 3D object to test.
   * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
   */
  intersectsObject(t) {
    if (t.boundingSphere !== void 0)
      t.boundingSphere === null && t.computeBoundingSphere(), Vs.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);
    else {
      const e = t.geometry;
      e.boundingSphere === null && e.computeBoundingSphere(), Vs.copy(e.boundingSphere).applyMatrix4(t.matrixWorld);
    }
    return this.intersectsSphere(Vs);
  }
  /**
   * Returns `true` if the given sprite is intersecting this frustum.
   *
   * @param {Sprite} sprite - The sprite to test.
   * @return {boolean} Whether the sprite is intersecting this frustum or not.
   */
  intersectsSprite(t) {
    Vs.center.set(0, 0, 0);
    const e = Xv.distanceTo(t.center);
    return Vs.radius = 0.7071067811865476 + e, Vs.applyMatrix4(t.matrixWorld), this.intersectsSphere(Vs);
  }
  /**
   * Returns `true` if the given bounding sphere is intersecting this frustum.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
   */
  intersectsSphere(t) {
    const e = this.planes, i = t.center, n = -t.radius;
    for (let s = 0; s < 6; s++)
      if (e[s].distanceToPoint(i) < n)
        return !1;
    return !0;
  }
  /**
   * Returns `true` if the given bounding box is intersecting this frustum.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the bounding box is intersecting this frustum or not.
   */
  intersectsBox(t) {
    const e = this.planes;
    for (let i = 0; i < 6; i++) {
      const n = e[i];
      if (yl.x = n.normal.x > 0 ? t.max.x : t.min.x, yl.y = n.normal.y > 0 ? t.max.y : t.min.y, yl.z = n.normal.z > 0 ? t.max.z : t.min.z, n.distanceToPoint(yl) < 0)
        return !1;
    }
    return !0;
  }
  /**
   * Returns `true` if the given point lies within the frustum.
   *
   * @param {Vector3} point - The point to test.
   * @return {boolean} Whether the point lies within this frustum or not.
   */
  containsPoint(t) {
    const e = this.planes;
    for (let i = 0; i < 6; i++)
      if (e[i].distanceToPoint(t) < 0)
        return !1;
    return !0;
  }
  /**
   * Returns a new frustum with copied values from this instance.
   *
   * @return {Frustum} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
const yn = /* @__PURE__ */ new Vt(), _n = /* @__PURE__ */ new Ea();
class $c {
  /**
   * Constructs a new frustum array.
   *
   */
  constructor() {
    this.coordinateSystem = Ni;
  }
  /**
   * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
   * from the camera array.
   *
   * @param {Object3D} object - The 3D object to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the 3D object is visible in any camera.
   */
  intersectsObject(t, e) {
    if (!e.isArrayCamera || e.cameras.length === 0)
      return !1;
    for (let i = 0; i < e.cameras.length; i++) {
      const n = e.cameras[i];
      if (yn.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), _n.setFromProjectionMatrix(
        yn,
        n.coordinateSystem,
        n.reversedDepth
      ), _n.intersectsObject(t))
        return !0;
    }
    return !1;
  }
  /**
   * Returns `true` if the given sprite is intersecting any frustum
   * from the camera array.
   *
   * @param {Sprite} sprite - The sprite to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the sprite is visible in any camera.
   */
  intersectsSprite(t, e) {
    if (!e || !e.cameras || e.cameras.length === 0)
      return !1;
    for (let i = 0; i < e.cameras.length; i++) {
      const n = e.cameras[i];
      if (yn.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), _n.setFromProjectionMatrix(
        yn,
        n.coordinateSystem,
        n.reversedDepth
      ), _n.intersectsSprite(t))
        return !0;
    }
    return !1;
  }
  /**
   * Returns `true` if the given bounding sphere is intersecting any frustum
   * from the camera array.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the sphere is visible in any camera.
   */
  intersectsSphere(t, e) {
    if (!e || !e.cameras || e.cameras.length === 0)
      return !1;
    for (let i = 0; i < e.cameras.length; i++) {
      const n = e.cameras[i];
      if (yn.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), _n.setFromProjectionMatrix(
        yn,
        n.coordinateSystem,
        n.reversedDepth
      ), _n.intersectsSphere(t))
        return !0;
    }
    return !1;
  }
  /**
   * Returns `true` if the given bounding box is intersecting any frustum
   * from the camera array.
   *
   * @param {Box3} box - The bounding box to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the box is visible in any camera.
   */
  intersectsBox(t, e) {
    if (!e || !e.cameras || e.cameras.length === 0)
      return !1;
    for (let i = 0; i < e.cameras.length; i++) {
      const n = e.cameras[i];
      if (yn.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), _n.setFromProjectionMatrix(
        yn,
        n.coordinateSystem,
        n.reversedDepth
      ), _n.intersectsBox(t))
        return !0;
    }
    return !1;
  }
  /**
   * Returns `true` if the given point lies within any frustum
   * from the camera array.
   *
   * @param {Vector3} point - The point to test.
   * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
   * @return {boolean} Whether the point is visible in any camera.
   */
  containsPoint(t, e) {
    if (!e || !e.cameras || e.cameras.length === 0)
      return !1;
    for (let i = 0; i < e.cameras.length; i++) {
      const n = e.cameras[i];
      if (yn.multiplyMatrices(
        n.projectionMatrix,
        n.matrixWorldInverse
      ), _n.setFromProjectionMatrix(
        yn,
        n.coordinateSystem,
        n.reversedDepth
      ), _n.containsPoint(t))
        return !0;
    }
    return !1;
  }
  /**
   * Returns a new frustum array with copied values from this instance.
   *
   * @return {FrustumArray} A clone of this instance.
   */
  clone() {
    return new $c();
  }
}
function Vu(a, t) {
  return a - t;
}
function Yv(a, t) {
  return a.z - t.z;
}
function Zv(a, t) {
  return t.z - a.z;
}
class jv {
  constructor() {
    this.index = 0, this.pool = [], this.list = [];
  }
  push(t, e, i, n) {
    const s = this.pool, r = this.list;
    this.index >= s.length && s.push({
      start: -1,
      count: -1,
      z: -1,
      index: -1
    });
    const o = s[this.index];
    r.push(o), this.index++, o.start = t, o.count = e, o.z = i, o.index = n;
  }
  reset() {
    this.list.length = 0, this.index = 0;
  }
}
const vi = /* @__PURE__ */ new Vt(), Jv = /* @__PURE__ */ new ct(1, 1, 1), rm = /* @__PURE__ */ new Ea(), Kv = /* @__PURE__ */ new $c(), _l = /* @__PURE__ */ new we(), Hs = /* @__PURE__ */ new Re(), qa = /* @__PURE__ */ new E(), am = /* @__PURE__ */ new E(), Qv = /* @__PURE__ */ new E(), Hu = /* @__PURE__ */ new jv(), Qe = /* @__PURE__ */ new re(), xl = [];
function tb(a, t, e = 0) {
  const i = t.itemSize;
  if (a.isInterleavedBufferAttribute || a.array.constructor !== t.array.constructor) {
    const n = a.count;
    for (let s = 0; s < n; s++)
      for (let r = 0; r < i; r++)
        t.setComponent(s + e, r, a.getComponent(s, r));
  } else
    t.array.set(a.array, e * i);
  t.needsUpdate = !0;
}
function Gs(a, t) {
  if (a.constructor !== t.constructor) {
    const e = Math.min(a.length, t.length);
    for (let i = 0; i < e; i++)
      t[i] = a[i];
  } else {
    const e = Math.min(a.length, t.length);
    t.set(new a.constructor(a.buffer, 0, e));
  }
}
class Ly extends re {
  /**
   * Constructs a new batched mesh.
   *
   * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
   * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
   * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(t, e, i = e * 2, n) {
    super(new Ht(), n), this.isBatchedMesh = !0, this.perObjectFrustumCulled = !0, this.sortObjects = !0, this.boundingBox = null, this.boundingSphere = null, this.customSort = null, this._instanceInfo = [], this._geometryInfo = [], this._availableInstanceIds = [], this._availableGeometryIds = [], this._nextIndexStart = 0, this._nextVertexStart = 0, this._geometryCount = 0, this._visibilityChanged = !0, this._geometryInitialized = !1, this._maxInstanceCount = t, this._maxVertexCount = e, this._maxIndexCount = i, this._multiDrawCounts = new Int32Array(t), this._multiDrawStarts = new Int32Array(t), this._multiDrawCount = 0, this._multiDrawInstances = null, this._matricesTexture = null, this._indirectTexture = null, this._colorsTexture = null, this._initMatricesTexture(), this._initIndirectTexture();
  }
  /**
   * The maximum number of individual instances that can be stored in the batch.
   *
   * @type {number}
   * @readonly
   */
  get maxInstanceCount() {
    return this._maxInstanceCount;
  }
  /**
   * The instance count.
   *
   * @type {number}
   * @readonly
   */
  get instanceCount() {
    return this._instanceInfo.length - this._availableInstanceIds.length;
  }
  /**
   * The number of unused vertices.
   *
   * @type {number}
   * @readonly
   */
  get unusedVertexCount() {
    return this._maxVertexCount - this._nextVertexStart;
  }
  /**
   * The number of unused indices.
   *
   * @type {number}
   * @readonly
   */
  get unusedIndexCount() {
    return this._maxIndexCount - this._nextIndexStart;
  }
  _initMatricesTexture() {
    let t = Math.sqrt(this._maxInstanceCount * 4);
    t = Math.ceil(t / 4) * 4, t = Math.max(t, 4);
    const e = new Float32Array(t * t * 4), i = new Cn(e, t, t, gi, wi);
    this._matricesTexture = i;
  }
  _initIndirectTexture() {
    let t = Math.sqrt(this._maxInstanceCount);
    t = Math.ceil(t);
    const e = new Uint32Array(t * t), i = new Cn(e, t, t, No, ns);
    this._indirectTexture = i;
  }
  _initColorsTexture() {
    let t = Math.sqrt(this._maxInstanceCount);
    t = Math.ceil(t);
    const e = new Float32Array(t * t * 4).fill(1), i = new Cn(e, t, t, gi, wi);
    i.colorSpace = ee.workingColorSpace, this._colorsTexture = i;
  }
  _initializeGeometry(t) {
    const e = this.geometry, i = this._maxVertexCount, n = this._maxIndexCount;
    if (this._geometryInitialized === !1) {
      for (const s in t.attributes) {
        const r = t.getAttribute(s), { array: o, itemSize: l, normalized: h } = r, c = new o.constructor(i * l), u = new ie(c, l, h);
        e.setAttribute(s, u);
      }
      if (t.getIndex() !== null) {
        const s = i > 65535 ? new Uint32Array(n) : new Uint16Array(n);
        e.setIndex(new ie(s, 1));
      }
      this._geometryInitialized = !0;
    }
  }
  // Make sure the geometry is compatible with the existing combined geometry attributes
  _validateGeometry(t) {
    const e = this.geometry;
    if (!!t.getIndex() != !!e.getIndex())
      throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');
    for (const i in e.attributes) {
      if (!t.hasAttribute(i))
        throw new Error(`THREE.BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`);
      const n = t.getAttribute(i), s = e.getAttribute(i);
      if (n.itemSize !== s.itemSize || n.normalized !== s.normalized)
        throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.");
    }
  }
  /**
   * Validates the instance defined by the given ID.
   *
   * @param {number} instanceId - The instance to validate.
   */
  validateInstanceId(t) {
    const e = this._instanceInfo;
    if (t < 0 || t >= e.length || e[t].active === !1)
      throw new Error(`THREE.BatchedMesh: Invalid instanceId ${t}. Instance is either out of range or has been deleted.`);
  }
  /**
   * Validates the geometry defined by the given ID.
   *
   * @param {number} geometryId - The geometry to validate.
   */
  validateGeometryId(t) {
    const e = this._geometryInfo;
    if (t < 0 || t >= e.length || e[t].active === !1)
      throw new Error(`THREE.BatchedMesh: Invalid geometryId ${t}. Geometry is either out of range or has been deleted.`);
  }
  /**
   * Takes a sort a function that is run before render. The function takes a list of instances to
   * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
   *
   * @param {Function} func - The custom sort function.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setCustomSort(t) {
    return this.customSort = t, this;
  }
  /**
   * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
   * Bounding boxes aren't computed by default. They need to be explicitly computed,
   * otherwise they are `null`.
   */
  computeBoundingBox() {
    this.boundingBox === null && (this.boundingBox = new we());
    const t = this.boundingBox, e = this._instanceInfo;
    t.makeEmpty();
    for (let i = 0, n = e.length; i < n; i++) {
      if (e[i].active === !1) continue;
      const s = e[i].geometryIndex;
      this.getMatrixAt(i, vi), this.getBoundingBoxAt(s, _l).applyMatrix4(vi), t.union(_l);
    }
  }
  /**
   * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
   * Bounding spheres aren't computed by default. They need to be explicitly computed,
   * otherwise they are `null`.
   */
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new Re());
    const t = this.boundingSphere, e = this._instanceInfo;
    t.makeEmpty();
    for (let i = 0, n = e.length; i < n; i++) {
      if (e[i].active === !1) continue;
      const s = e[i].geometryIndex;
      this.getMatrixAt(i, vi), this.getBoundingSphereAt(s, Hs).applyMatrix4(vi), t.union(Hs);
    }
  }
  /**
   * Adds a new instance to the batch using the geometry of the given ID and returns
   * a new id referring to the new instance to be used by other functions.
   *
   * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
   * @return {number} The instance ID.
   */
  addInstance(t) {
    if (this._instanceInfo.length >= this.maxInstanceCount && this._availableInstanceIds.length === 0)
      throw new Error("THREE.BatchedMesh: Maximum item count reached.");
    const i = {
      visible: !0,
      active: !0,
      geometryIndex: t
    };
    let n = null;
    this._availableInstanceIds.length > 0 ? (this._availableInstanceIds.sort(Vu), n = this._availableInstanceIds.shift(), this._instanceInfo[n] = i) : (n = this._instanceInfo.length, this._instanceInfo.push(i));
    const s = this._matricesTexture;
    vi.identity().toArray(s.image.data, n * 16), s.needsUpdate = !0;
    const r = this._colorsTexture;
    return r && (Jv.toArray(r.image.data, n * 4), r.needsUpdate = !0), this._visibilityChanged = !0, n;
  }
  /**
   * Adds the given geometry to the batch and returns the associated
   * geometry id referring to it to be used in other functions.
   *
   * @param {BufferGeometry} geometry - The geometry to add.
   * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
   * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
   * to set a new geometry at this index at a later time that is larger than the original geometry.
   * Defaults to the length of the given geometry vertex buffer.
   * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
   * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
   * new geometry at this index at a later time that is larger than the original geometry. Defaults to
   * the length of the given geometry index buffer.
   * @return {number} The geometry ID.
   */
  addGeometry(t, e = -1, i = -1) {
    this._initializeGeometry(t), this._validateGeometry(t);
    const n = {
      // geometry information
      vertexStart: -1,
      vertexCount: -1,
      reservedVertexCount: -1,
      indexStart: -1,
      indexCount: -1,
      reservedIndexCount: -1,
      // draw range information
      start: -1,
      count: -1,
      // state
      boundingBox: null,
      boundingSphere: null,
      active: !0
    }, s = this._geometryInfo;
    n.vertexStart = this._nextVertexStart, n.reservedVertexCount = e === -1 ? t.getAttribute("position").count : e;
    const r = t.getIndex();
    if (r !== null && (n.indexStart = this._nextIndexStart, n.reservedIndexCount = i === -1 ? r.count : i), n.indexStart !== -1 && n.indexStart + n.reservedIndexCount > this._maxIndexCount || n.vertexStart + n.reservedVertexCount > this._maxVertexCount)
      throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");
    let l;
    return this._availableGeometryIds.length > 0 ? (this._availableGeometryIds.sort(Vu), l = this._availableGeometryIds.shift(), s[l] = n) : (l = this._geometryCount, this._geometryCount++, s.push(n)), this.setGeometryAt(l, t), this._nextIndexStart = n.indexStart + n.reservedIndexCount, this._nextVertexStart = n.vertexStart + n.reservedVertexCount, l;
  }
  /**
   * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
   * is not enough space reserved for geometry. Calling this will change all instances that are
   * rendering that geometry.
   *
   * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
   * @param {BufferGeometry} geometry - The new geometry.
   * @return {number} The geometry ID.
   */
  setGeometryAt(t, e) {
    if (t >= this._geometryCount)
      throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");
    this._validateGeometry(e);
    const i = this.geometry, n = i.getIndex() !== null, s = i.getIndex(), r = e.getIndex(), o = this._geometryInfo[t];
    if (n && r.count > o.reservedIndexCount || e.attributes.position.count > o.reservedVertexCount)
      throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");
    const l = o.vertexStart, h = o.reservedVertexCount;
    o.vertexCount = e.getAttribute("position").count;
    for (const c in i.attributes) {
      const u = e.getAttribute(c), d = i.getAttribute(c);
      tb(u, d, l);
      const p = u.itemSize;
      for (let f = u.count, y = h; f < y; f++) {
        const g = l + f;
        for (let m = 0; m < p; m++)
          d.setComponent(g, m, 0);
      }
      d.needsUpdate = !0, d.addUpdateRange(l * p, h * p);
    }
    if (n) {
      const c = o.indexStart, u = o.reservedIndexCount;
      o.indexCount = e.getIndex().count;
      for (let d = 0; d < r.count; d++)
        s.setX(c + d, l + r.getX(d));
      for (let d = r.count, p = u; d < p; d++)
        s.setX(c + d, l);
      s.needsUpdate = !0, s.addUpdateRange(c, o.reservedIndexCount);
    }
    return o.start = n ? o.indexStart : o.vertexStart, o.count = n ? o.indexCount : o.vertexCount, o.boundingBox = null, e.boundingBox !== null && (o.boundingBox = e.boundingBox.clone()), o.boundingSphere = null, e.boundingSphere !== null && (o.boundingSphere = e.boundingSphere.clone()), this._visibilityChanged = !0, t;
  }
  /**
   * Deletes the geometry defined by the given ID from this batch. Any instances referencing
   * this geometry will also be removed as a side effect.
   *
   * @param {number} geometryId - The ID of the geometry to remove from the batch.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  deleteGeometry(t) {
    const e = this._geometryInfo;
    if (t >= e.length || e[t].active === !1)
      return this;
    const i = this._instanceInfo;
    for (let n = 0, s = i.length; n < s; n++)
      i[n].active && i[n].geometryIndex === t && this.deleteInstance(n);
    return e[t].active = !1, this._availableGeometryIds.push(t), this._visibilityChanged = !0, this;
  }
  /**
   * Deletes an existing instance from the batch using the given ID.
   *
   * @param {number} instanceId - The ID of the instance to remove from the batch.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  deleteInstance(t) {
    return this.validateInstanceId(t), this._instanceInfo[t].active = !1, this._availableInstanceIds.push(t), this._visibilityChanged = !0, this;
  }
  /**
   * Repacks the sub geometries in [name] to remove any unused space remaining from
   * previously deleted geometry, freeing up space to add new geometry.
   *
   * @param {number} instanceId - The ID of the instance to remove from the batch.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  optimize() {
    let t = 0, e = 0;
    const i = this._geometryInfo, n = i.map((r, o) => o).sort((r, o) => i[r].vertexStart - i[o].vertexStart), s = this.geometry;
    for (let r = 0, o = i.length; r < o; r++) {
      const l = n[r], h = i[l];
      if (h.active !== !1) {
        if (s.index !== null) {
          if (h.indexStart !== e) {
            const { indexStart: c, vertexStart: u, reservedIndexCount: d } = h, p = s.index, f = p.array, y = t - u;
            for (let g = c; g < c + d; g++)
              f[g] = f[g] + y;
            p.array.copyWithin(e, c, c + d), p.addUpdateRange(e, d), h.indexStart = e;
          }
          e += h.reservedIndexCount;
        }
        if (h.vertexStart !== t) {
          const { vertexStart: c, reservedVertexCount: u } = h, d = s.attributes;
          for (const p in d) {
            const f = d[p], { array: y, itemSize: g } = f;
            y.copyWithin(t * g, c * g, (c + u) * g), f.addUpdateRange(t * g, u * g);
          }
          h.vertexStart = t;
        }
        t += h.reservedVertexCount, h.start = s.index ? h.indexStart : h.vertexStart, this._nextIndexStart = s.index ? h.indexStart + h.reservedIndexCount : 0, this._nextVertexStart = h.vertexStart + h.reservedVertexCount;
      }
    }
    return this;
  }
  /**
   * Returns the bounding box for the given geometry.
   *
   * @param {number} geometryId - The ID of the geometry to return the bounding box for.
   * @param {Box3} target - The target object that is used to store the method's result.
   * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
   */
  getBoundingBoxAt(t, e) {
    if (t >= this._geometryCount)
      return null;
    const i = this.geometry, n = this._geometryInfo[t];
    if (n.boundingBox === null) {
      const s = new we(), r = i.index, o = i.attributes.position;
      for (let l = n.start, h = n.start + n.count; l < h; l++) {
        let c = l;
        r && (c = r.getX(c)), s.expandByPoint(qa.fromBufferAttribute(o, c));
      }
      n.boundingBox = s;
    }
    return e.copy(n.boundingBox), e;
  }
  /**
   * Returns the bounding sphere for the given geometry.
   *
   * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
   * @param {Sphere} target - The target object that is used to store the method's result.
   * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
   */
  getBoundingSphereAt(t, e) {
    if (t >= this._geometryCount)
      return null;
    const i = this.geometry, n = this._geometryInfo[t];
    if (n.boundingSphere === null) {
      const s = new Re();
      this.getBoundingBoxAt(t, _l), _l.getCenter(s.center);
      const r = i.index, o = i.attributes.position;
      let l = 0;
      for (let h = n.start, c = n.start + n.count; h < c; h++) {
        let u = h;
        r && (u = r.getX(u)), qa.fromBufferAttribute(o, u), l = Math.max(l, s.center.distanceToSquared(qa));
      }
      s.radius = Math.sqrt(l), n.boundingSphere = s;
    }
    return e.copy(n.boundingSphere), e;
  }
  /**
   * Sets the given local transformation matrix to the defined instance.
   * Negatively scaled matrices are not supported.
   *
   * @param {number} instanceId - The ID of an instance to set the matrix of.
   * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setMatrixAt(t, e) {
    this.validateInstanceId(t);
    const i = this._matricesTexture, n = this._matricesTexture.image.data;
    return e.toArray(n, t * 16), i.needsUpdate = !0, this;
  }
  /**
   * Returns the local transformation matrix of the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to get the matrix of.
   * @param {Matrix4} matrix - The target object that is used to store the method's result.
   * @return {Matrix4} The instance's local transformation matrix.
   */
  getMatrixAt(t, e) {
    return this.validateInstanceId(t), e.fromArray(this._matricesTexture.image.data, t * 16);
  }
  /**
   * Sets the given color to the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to set the color of.
   * @param {Color} color - The color to set the instance to.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setColorAt(t, e) {
    return this.validateInstanceId(t), this._colorsTexture === null && this._initColorsTexture(), e.toArray(this._colorsTexture.image.data, t * 4), this._colorsTexture.needsUpdate = !0, this;
  }
  /**
   * Returns the color of the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to get the color of.
   * @param {Color} color - The target object that is used to store the method's result.
   * @return {Color} The instance's color.
   */
  getColorAt(t, e) {
    return this.validateInstanceId(t), e.fromArray(this._colorsTexture.image.data, t * 4);
  }
  /**
   * Sets the visibility of the instance.
   *
   * @param {number} instanceId - The id of the instance to set the visibility of.
   * @param {boolean} visible - Whether the instance is visible or not.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setVisibleAt(t, e) {
    return this.validateInstanceId(t), this._instanceInfo[t].visible === e ? this : (this._instanceInfo[t].visible = e, this._visibilityChanged = !0, this);
  }
  /**
   * Returns the visibility state of the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to get the visibility state of.
   * @return {boolean} Whether the instance is visible or not.
   */
  getVisibleAt(t) {
    return this.validateInstanceId(t), this._instanceInfo[t].visible;
  }
  /**
   * Sets the geometry ID of the instance at the given index.
   *
   * @param {number} instanceId - The ID of the instance to set the geometry ID of.
   * @param {number} geometryId - The geometry ID to be use by the instance.
   * @return {BatchedMesh} A reference to this batched mesh.
   */
  setGeometryIdAt(t, e) {
    return this.validateInstanceId(t), this.validateGeometryId(e), this._instanceInfo[t].geometryIndex = e, this;
  }
  /**
   * Returns the geometry ID of the defined instance.
   *
   * @param {number} instanceId - The ID of an instance to get the geometry ID of.
   * @return {number} The instance's geometry ID.
   */
  getGeometryIdAt(t) {
    return this.validateInstanceId(t), this._instanceInfo[t].geometryIndex;
  }
  /**
   * Get the range representing the subset of triangles related to the attached geometry,
   * indicating the starting offset and count, or `null` if invalid.
   *
   * @param {number} geometryId - The id of the geometry to get the range of.
   * @param {Object} [target] - The target object that is used to store the method's result.
   * @return {{
   * 	vertexStart:number,vertexCount:number,reservedVertexCount:number,
   * 	indexStart:number,indexCount:number,reservedIndexCount:number,
   * 	start:number,count:number
   * }} The result object with range data.
   */
  getGeometryRangeAt(t, e = {}) {
    this.validateGeometryId(t);
    const i = this._geometryInfo[t];
    return e.vertexStart = i.vertexStart, e.vertexCount = i.vertexCount, e.reservedVertexCount = i.reservedVertexCount, e.indexStart = i.indexStart, e.indexCount = i.indexCount, e.reservedIndexCount = i.reservedIndexCount, e.start = i.start, e.count = i.count, e;
  }
  /**
   * Resizes the necessary buffers to support the provided number of instances.
   * If the provided arguments shrink the number of instances but there are not enough
   * unused Ids at the end of the list then an error is thrown.
   *
   * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  */
  setInstanceCount(t) {
    const e = this._availableInstanceIds, i = this._instanceInfo;
    for (e.sort(Vu); e[e.length - 1] === i.length - 1; )
      i.pop(), e.pop();
    if (t < i.length)
      throw new Error(`BatchedMesh: Instance ids outside the range ${t} are being used. Cannot shrink instance count.`);
    const n = new Int32Array(t), s = new Int32Array(t);
    Gs(this._multiDrawCounts, n), Gs(this._multiDrawStarts, s), this._multiDrawCounts = n, this._multiDrawStarts = s, this._maxInstanceCount = t;
    const r = this._indirectTexture, o = this._matricesTexture, l = this._colorsTexture;
    r.dispose(), this._initIndirectTexture(), Gs(r.image.data, this._indirectTexture.image.data), o.dispose(), this._initMatricesTexture(), Gs(o.image.data, this._matricesTexture.image.data), l && (l.dispose(), this._initColorsTexture(), Gs(l.image.data, this._colorsTexture.image.data));
  }
  /**
   * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
   * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
   * end of the geometry attributes then an error is thrown.
   *
   * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
   * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  */
  setGeometrySize(t, e) {
    const i = [...this._geometryInfo].filter((o) => o.active);
    if (Math.max(...i.map((o) => o.vertexStart + o.reservedVertexCount)) > t)
      throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${e}. Cannot shrink further.`);
    if (this.geometry.index && Math.max(...i.map((l) => l.indexStart + l.reservedIndexCount)) > e)
      throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${e}. Cannot shrink further.`);
    const s = this.geometry;
    s.dispose(), this._maxVertexCount = t, this._maxIndexCount = e, this._geometryInitialized && (this._geometryInitialized = !1, this.geometry = new Ht(), this._initializeGeometry(s));
    const r = this.geometry;
    s.index && Gs(s.index.array, r.index.array);
    for (const o in s.attributes)
      Gs(s.attributes[o].array, r.attributes[o].array);
  }
  raycast(t, e) {
    const i = this._instanceInfo, n = this._geometryInfo, s = this.matrixWorld, r = this.geometry;
    Qe.material = this.material, Qe.geometry.index = r.index, Qe.geometry.attributes = r.attributes, Qe.geometry.boundingBox === null && (Qe.geometry.boundingBox = new we()), Qe.geometry.boundingSphere === null && (Qe.geometry.boundingSphere = new Re());
    for (let o = 0, l = i.length; o < l; o++) {
      if (!i[o].visible || !i[o].active)
        continue;
      const h = i[o].geometryIndex, c = n[h];
      Qe.geometry.setDrawRange(c.start, c.count), this.getMatrixAt(o, Qe.matrixWorld).premultiply(s), this.getBoundingBoxAt(h, Qe.geometry.boundingBox), this.getBoundingSphereAt(h, Qe.geometry.boundingSphere), Qe.raycast(t, xl);
      for (let u = 0, d = xl.length; u < d; u++) {
        const p = xl[u];
        p.object = this, p.batchId = o, e.push(p);
      }
      xl.length = 0;
    }
    Qe.material = null, Qe.geometry.index = null, Qe.geometry.attributes = {}, Qe.geometry.setDrawRange(0, 1 / 0);
  }
  copy(t) {
    return super.copy(t), this.geometry = t.geometry.clone(), this.perObjectFrustumCulled = t.perObjectFrustumCulled, this.sortObjects = t.sortObjects, this.boundingBox = t.boundingBox !== null ? t.boundingBox.clone() : null, this.boundingSphere = t.boundingSphere !== null ? t.boundingSphere.clone() : null, this._geometryInfo = t._geometryInfo.map((e) => ({
      ...e,
      boundingBox: e.boundingBox !== null ? e.boundingBox.clone() : null,
      boundingSphere: e.boundingSphere !== null ? e.boundingSphere.clone() : null
    })), this._instanceInfo = t._instanceInfo.map((e) => ({ ...e })), this._availableInstanceIds = t._availableInstanceIds.slice(), this._availableGeometryIds = t._availableGeometryIds.slice(), this._nextIndexStart = t._nextIndexStart, this._nextVertexStart = t._nextVertexStart, this._geometryCount = t._geometryCount, this._maxInstanceCount = t._maxInstanceCount, this._maxVertexCount = t._maxVertexCount, this._maxIndexCount = t._maxIndexCount, this._geometryInitialized = t._geometryInitialized, this._multiDrawCounts = t._multiDrawCounts.slice(), this._multiDrawStarts = t._multiDrawStarts.slice(), this._indirectTexture = t._indirectTexture.clone(), this._indirectTexture.image.data = this._indirectTexture.image.data.slice(), this._matricesTexture = t._matricesTexture.clone(), this._matricesTexture.image.data = this._matricesTexture.image.data.slice(), this._colorsTexture !== null && (this._colorsTexture = t._colorsTexture.clone(), this._colorsTexture.image.data = this._colorsTexture.image.data.slice()), this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this._matricesTexture.dispose(), this._matricesTexture = null, this._indirectTexture.dispose(), this._indirectTexture = null, this._colorsTexture !== null && (this._colorsTexture.dispose(), this._colorsTexture = null);
  }
  onBeforeRender(t, e, i, n, s) {
    if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects)
      return;
    const r = n.getIndex(), o = r === null ? 1 : r.array.BYTES_PER_ELEMENT, l = this._instanceInfo, h = this._multiDrawStarts, c = this._multiDrawCounts, u = this._geometryInfo, d = this.perObjectFrustumCulled, p = this._indirectTexture, f = p.image.data, y = i.isArrayCamera ? Kv : rm;
    d && !i.isArrayCamera && (vi.multiplyMatrices(i.projectionMatrix, i.matrixWorldInverse).multiply(this.matrixWorld), rm.setFromProjectionMatrix(
      vi,
      i.coordinateSystem,
      i.reversedDepth
    ));
    let g = 0;
    if (this.sortObjects) {
      vi.copy(this.matrixWorld).invert(), qa.setFromMatrixPosition(i.matrixWorld).applyMatrix4(vi), am.set(0, 0, -1).transformDirection(i.matrixWorld).transformDirection(vi);
      for (let x = 0, _ = l.length; x < _; x++)
        if (l[x].visible && l[x].active) {
          const S = l[x].geometryIndex;
          this.getMatrixAt(x, vi), this.getBoundingSphereAt(S, Hs).applyMatrix4(vi);
          let w = !1;
          if (d && (w = !y.intersectsSphere(Hs, i)), !w) {
            const T = u[S], R = Qv.subVectors(Hs.center, qa).dot(am);
            Hu.push(T.start, T.count, R, x);
          }
        }
      const m = Hu.list, v = this.customSort;
      v === null ? m.sort(s.transparent ? Zv : Yv) : v.call(this, m, i);
      for (let x = 0, _ = m.length; x < _; x++) {
        const S = m[x];
        h[g] = S.start * o, c[g] = S.count, f[g] = S.index, g++;
      }
      Hu.reset();
    } else
      for (let m = 0, v = l.length; m < v; m++)
        if (l[m].visible && l[m].active) {
          const x = l[m].geometryIndex;
          let _ = !1;
          if (d && (this.getMatrixAt(m, vi), this.getBoundingSphereAt(x, Hs).applyMatrix4(vi), _ = !y.intersectsSphere(Hs, i)), !_) {
            const S = u[x];
            h[g] = S.start * o, c[g] = S.count, f[g] = m, g++;
          }
        }
    p.needsUpdate = !0, this._multiDrawCount = g, this._visibilityChanged = !1;
  }
  onBeforeShadow(t, e, i, n, s, r) {
    this.onBeforeRender(t, null, n, s, r);
  }
}
class Pe extends hi {
  /**
   * Constructs a new line basic material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isLineBasicMaterial = !0, this.type = "LineBasicMaterial", this.color = new ct(16777215), this.map = null, this.linewidth = 1, this.linecap = "round", this.linejoin = "round", this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.map = t.map, this.linewidth = t.linewidth, this.linecap = t.linecap, this.linejoin = t.linejoin, this.fog = t.fog, this;
  }
}
const gc = /* @__PURE__ */ new E(), yc = /* @__PURE__ */ new E(), om = /* @__PURE__ */ new Vt(), $a = /* @__PURE__ */ new Aa(), vl = /* @__PURE__ */ new Re(), Gu = /* @__PURE__ */ new E(), lm = /* @__PURE__ */ new E();
class Rs extends le {
  /**
   * Constructs a new line.
   *
   * @param {BufferGeometry} [geometry] - The line geometry.
   * @param {Material|Array<Material>} [material] - The line material.
   */
  constructor(t = new Ht(), e = new Pe()) {
    super(), this.isLine = !0, this.type = "Line", this.geometry = t, this.material = e, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets();
  }
  copy(t, e) {
    return super.copy(t, e), this.material = Array.isArray(t.material) ? t.material.slice() : t.material, this.geometry = t.geometry, this;
  }
  /**
   * Computes an array of distance values which are necessary for rendering dashed lines.
   * For each vertex in the geometry, the method calculates the cumulative length from the
   * current point to the very beginning of the line.
   *
   * @return {Line} A reference to this line.
   */
  computeLineDistances() {
    const t = this.geometry;
    if (t.index === null) {
      const e = t.attributes.position, i = [0];
      for (let n = 1, s = e.count; n < s; n++)
        gc.fromBufferAttribute(e, n - 1), yc.fromBufferAttribute(e, n), i[n] = i[n - 1], i[n] += gc.distanceTo(yc);
      t.setAttribute("lineDistance", new wt(i, 1));
    } else
      console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
    return this;
  }
  /**
   * Computes intersection points between a casted ray and this line.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(t, e) {
    const i = this.geometry, n = this.matrixWorld, s = t.params.Line.threshold, r = i.drawRange;
    if (i.boundingSphere === null && i.computeBoundingSphere(), vl.copy(i.boundingSphere), vl.applyMatrix4(n), vl.radius += s, t.ray.intersectsSphere(vl) === !1) return;
    om.copy(n).invert(), $a.copy(t.ray).applyMatrix4(om);
    const o = s / ((this.scale.x + this.scale.y + this.scale.z) / 3), l = o * o, h = this.isLineSegments ? 2 : 1, c = i.index, d = i.attributes.position;
    if (c !== null) {
      const p = Math.max(0, r.start), f = Math.min(c.count, r.start + r.count);
      for (let y = p, g = f - 1; y < g; y += h) {
        const m = c.getX(y), v = c.getX(y + 1), x = bl(this, t, $a, l, m, v, y);
        x && e.push(x);
      }
      if (this.isLineLoop) {
        const y = c.getX(f - 1), g = c.getX(p), m = bl(this, t, $a, l, y, g, f - 1);
        m && e.push(m);
      }
    } else {
      const p = Math.max(0, r.start), f = Math.min(d.count, r.start + r.count);
      for (let y = p, g = f - 1; y < g; y += h) {
        const m = bl(this, t, $a, l, y, y + 1, y);
        m && e.push(m);
      }
      if (this.isLineLoop) {
        const y = bl(this, t, $a, l, f - 1, p, f - 1);
        y && e.push(y);
      }
    }
  }
  /**
   * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
   * to make sure existing morph targets can influence this 3D object.
   */
  updateMorphTargets() {
    const e = this.geometry.morphAttributes, i = Object.keys(e);
    if (i.length > 0) {
      const n = e[i[0]];
      if (n !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let s = 0, r = n.length; s < r; s++) {
          const o = n[s].name || String(s);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[o] = s;
        }
      }
    }
  }
}
function bl(a, t, e, i, n, s, r) {
  const o = a.geometry.attributes.position;
  if (gc.fromBufferAttribute(o, n), yc.fromBufferAttribute(o, s), e.distanceSqToSegment(gc, yc, Gu, lm) > i) return;
  Gu.applyMatrix4(a.matrixWorld);
  const h = t.ray.origin.distanceTo(Gu);
  if (!(h < t.near || h > t.far))
    return {
      distance: h,
      // What do we want? intersection point on the ray or on the segment??
      // point: raycaster.ray.at( distance ),
      point: lm.clone().applyMatrix4(a.matrixWorld),
      index: r,
      face: null,
      faceIndex: null,
      barycoord: null,
      object: a
    };
}
const hm = /* @__PURE__ */ new E(), cm = /* @__PURE__ */ new E();
class oi extends Rs {
  /**
   * Constructs a new line segments.
   *
   * @param {BufferGeometry} [geometry] - The line geometry.
   * @param {Material|Array<Material>} [material] - The line material.
   */
  constructor(t, e) {
    super(t, e), this.isLineSegments = !0, this.type = "LineSegments";
  }
  computeLineDistances() {
    const t = this.geometry;
    if (t.index === null) {
      const e = t.attributes.position, i = [];
      for (let n = 0, s = e.count; n < s; n += 2)
        hm.fromBufferAttribute(e, n), cm.fromBufferAttribute(e, n + 1), i[n] = n === 0 ? 0 : i[n - 1], i[n + 1] = i[n] + hm.distanceTo(cm);
      t.setAttribute("lineDistance", new wt(i, 1));
    } else
      console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
    return this;
  }
}
class Dy extends Rs {
  /**
   * Constructs a new line loop.
   *
   * @param {BufferGeometry} [geometry] - The line geometry.
   * @param {Material|Array<Material>} [material] - The line material.
   */
  constructor(t, e) {
    super(t, e), this.isLineLoop = !0, this.type = "LineLoop";
  }
}
class Xc extends hi {
  /**
   * Constructs a new points material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isPointsMaterial = !0, this.type = "PointsMaterial", this.color = new ct(16777215), this.map = null, this.alphaMap = null, this.size = 1, this.sizeAttenuation = !0, this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.map = t.map, this.alphaMap = t.alphaMap, this.size = t.size, this.sizeAttenuation = t.sizeAttenuation, this.fog = t.fog, this;
  }
}
const um = /* @__PURE__ */ new Vt(), ep = /* @__PURE__ */ new Aa(), Ml = /* @__PURE__ */ new Re(), Sl = /* @__PURE__ */ new E();
class kp extends le {
  /**
   * Constructs a new point cloud.
   *
   * @param {BufferGeometry} [geometry] - The points geometry.
   * @param {Material|Array<Material>} [material] - The points material.
   */
  constructor(t = new Ht(), e = new Xc()) {
    super(), this.isPoints = !0, this.type = "Points", this.geometry = t, this.material = e, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets();
  }
  copy(t, e) {
    return super.copy(t, e), this.material = Array.isArray(t.material) ? t.material.slice() : t.material, this.geometry = t.geometry, this;
  }
  /**
   * Computes intersection points between a casted ray and this point cloud.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(t, e) {
    const i = this.geometry, n = this.matrixWorld, s = t.params.Points.threshold, r = i.drawRange;
    if (i.boundingSphere === null && i.computeBoundingSphere(), Ml.copy(i.boundingSphere), Ml.applyMatrix4(n), Ml.radius += s, t.ray.intersectsSphere(Ml) === !1) return;
    um.copy(n).invert(), ep.copy(t.ray).applyMatrix4(um);
    const o = s / ((this.scale.x + this.scale.y + this.scale.z) / 3), l = o * o, h = i.index, u = i.attributes.position;
    if (h !== null) {
      const d = Math.max(0, r.start), p = Math.min(h.count, r.start + r.count);
      for (let f = d, y = p; f < y; f++) {
        const g = h.getX(f);
        Sl.fromBufferAttribute(u, g), dm(Sl, g, l, n, t, e, this);
      }
    } else {
      const d = Math.max(0, r.start), p = Math.min(u.count, r.start + r.count);
      for (let f = d, y = p; f < y; f++)
        Sl.fromBufferAttribute(u, f), dm(Sl, f, l, n, t, e, this);
    }
  }
  /**
   * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
   * to make sure existing morph targets can influence this 3D object.
   */
  updateMorphTargets() {
    const e = this.geometry.morphAttributes, i = Object.keys(e);
    if (i.length > 0) {
      const n = e[i[0]];
      if (n !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let s = 0, r = n.length; s < r; s++) {
          const o = n[s].name || String(s);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[o] = s;
        }
      }
    }
  }
}
function dm(a, t, e, i, n, s, r) {
  const o = ep.distanceSqToPoint(a);
  if (o < e) {
    const l = new E();
    ep.closestPointToPoint(a, l), l.applyMatrix4(i);
    const h = n.ray.origin.distanceTo(l);
    if (h < n.near || h > n.far) return;
    s.push({
      distance: h,
      distanceToRay: Math.sqrt(o),
      point: l,
      index: t,
      face: null,
      faceIndex: null,
      barycoord: null,
      object: r
    });
  }
}
class Fy extends Ne {
  /**
   * Constructs a new video texture.
   *
   * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   */
  constructor(t, e, i, n, s = Ce, r = Ce, o, l, h) {
    super(t, e, i, n, s, r, o, l, h), this.isVideoTexture = !0, this.generateMipmaps = !1, this._requestVideoFrameCallbackId = 0;
    const c = this;
    function u() {
      c.needsUpdate = !0, c._requestVideoFrameCallbackId = t.requestVideoFrameCallback(u);
    }
    "requestVideoFrameCallback" in t && (this._requestVideoFrameCallbackId = t.requestVideoFrameCallback(u));
  }
  clone() {
    return new this.constructor(this.image).copy(this);
  }
  /**
   * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
   * to `true` every time a new frame is available.
   *
   * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
   */
  update() {
    const t = this.image;
    "requestVideoFrameCallback" in t === !1 && t.readyState >= t.HAVE_CURRENT_DATA && (this.needsUpdate = !0);
  }
  dispose() {
    this._requestVideoFrameCallbackId !== 0 && this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId), super.dispose();
  }
}
class eb extends Fy {
  /**
   * Constructs a new video frame texture.
   *
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   */
  constructor(t, e, i, n, s, r, o, l) {
    super({}, t, e, i, n, s, r, o, l), this.isVideoFrameTexture = !0;
  }
  /**
   * This method overwritten with an empty implementation since
   * this type of texture is updated via `setFrame()`.
   */
  update() {
  }
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Sets the current frame of the video. This will automatically update the texture
   * so the data can be used for rendering.
   *
   * @param {VideoFrame} frame - The video frame.
   */
  setFrame(t) {
    this.image = t, this.needsUpdate = !0;
  }
}
class ib extends Ne {
  /**
   * Constructs a new framebuffer texture.
   *
   * @param {number} [width] - The width of the texture.
   * @param {number} [height] - The height of the texture.
   */
  constructor(t, e) {
    super({ width: t, height: e }), this.isFramebufferTexture = !0, this.magFilter = je, this.minFilter = je, this.generateMipmaps = !1, this.needsUpdate = !0;
  }
}
class Yc extends Ne {
  /**
   * Constructs a new compressed texture.
   *
   * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
   * the data and dimensions.
   * @param {number} width - The width of the texture.
   * @param {number} height - The height of the texture.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space.
   */
  constructor(t, e, i, n, s, r, o, l, h, c, u, d) {
    super(null, r, o, l, h, c, n, s, u, d), this.isCompressedTexture = !0, this.image = { width: e, height: i }, this.mipmaps = t, this.flipY = !1, this.generateMipmaps = !1;
  }
}
class nb extends Yc {
  /**
   * Constructs a new compressed array texture.
   *
   * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
   * the data and dimensions.
   * @param {number} width - The width of the texture.
   * @param {number} height - The height of the texture.
   * @param {number} depth - The depth of the texture.
   * @param {number} [format=RGBAFormat] - The min filter value.
   * @param {number} [type=UnsignedByteType] - The min filter value.
   */
  constructor(t, e, i, n, s, r) {
    super(t, e, i, s, r), this.isCompressedArrayTexture = !0, this.image.depth = n, this.wrapR = Si, this.layerUpdates = /* @__PURE__ */ new Set();
  }
  /**
   * Describes that a specific layer of the texture needs to be updated.
   * Normally when {@link Texture#needsUpdate} is set to `true`, the
   * entire compressed texture array is sent to the GPU. Marking specific
   * layers will only transmit subsets of all mipmaps associated with a
   * specific depth in the array which is often much more performant.
   *
   * @param {number} layerIndex - The layer index that should be updated.
   */
  addLayerUpdate(t) {
    this.layerUpdates.add(t);
  }
  /**
   * Resets the layer updates registry.
   */
  clearLayerUpdates() {
    this.layerUpdates.clear();
  }
}
class sb extends Yc {
  /**
   * Constructs a new compressed texture.
   *
   * @param {Array<CompressedTexture>} images - An array of compressed textures.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   */
  constructor(t, e, i) {
    super(void 0, t[0].width, t[0].height, e, i, is), this.isCompressedCubeTexture = !0, this.isCubeTexture = !0, this.image = t;
  }
}
class Uy extends Ne {
  /**
   * Constructs a new texture.
   *
   * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   */
  constructor(t, e, i, n, s, r, o, l, h) {
    super(t, e, i, n, s, r, o, l, h), this.isCanvasTexture = !0, this.needsUpdate = !0;
  }
}
class Vp extends Ne {
  /**
   * Constructs a new depth texture.
   *
   * @param {number} width - The width of the texture.
   * @param {number} height - The height of the texture.
   * @param {number} [type=UnsignedIntType] - The texture type.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearFilter] - The min filter value.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {number} [format=DepthFormat] - The texture format.
   * @param {number} [depth=1] - The depth of the texture.
   */
  constructor(t, e, i = ns, n, s, r, o = je, l = je, h, c = fa, u = 1) {
    if (c !== fa && c !== ma)
      throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");
    const d = { width: t, height: e, depth: u };
    super(d, n, s, r, o, l, c, i, h), this.isDepthTexture = !0, this.flipY = !1, this.generateMipmaps = !1, this.compareFunction = null;
  }
  copy(t) {
    return super.copy(t), this.source = new Ms(Object.assign({}, t.image)), this.compareFunction = t.compareFunction, this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return this.compareFunction !== null && (e.compareFunction = this.compareFunction), e;
  }
}
class Hp extends Ne {
  /**
   * Creates a new raw texture.
   *
   * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
   */
  constructor(t = null) {
    super(), this.sourceTexture = t, this.isExternalTexture = !0;
  }
  copy(t) {
    return super.copy(t), this.sourceTexture = t.sourceTexture, this;
  }
}
class Zc extends Ht {
  /**
   * Constructs a new capsule geometry.
   *
   * @param {number} [radius=1] - Radius of the capsule.
   * @param {number} [height=1] - Height of the middle section.
   * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
   * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
   * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
   */
  constructor(t = 1, e = 1, i = 4, n = 8, s = 1) {
    super(), this.type = "CapsuleGeometry", this.parameters = {
      radius: t,
      height: e,
      capSegments: i,
      radialSegments: n,
      heightSegments: s
    }, e = Math.max(0, e), i = Math.max(1, Math.floor(i)), n = Math.max(3, Math.floor(n)), s = Math.max(1, Math.floor(s));
    const r = [], o = [], l = [], h = [], c = e / 2, u = Math.PI / 2 * t, d = e, p = 2 * u + d, f = i * 2 + s, y = n + 1, g = new E(), m = new E();
    for (let v = 0; v <= f; v++) {
      let x = 0, _ = 0, S = 0, w = 0;
      if (v <= i) {
        const b = v / i, M = b * Math.PI / 2;
        _ = -c - t * Math.cos(M), S = t * Math.sin(M), w = -t * Math.cos(M), x = b * u;
      } else if (v <= i + s) {
        const b = (v - i) / s;
        _ = -c + b * e, S = t, w = 0, x = u + b * d;
      } else {
        const b = (v - i - s) / i, M = b * Math.PI / 2;
        _ = c + t * Math.sin(M), S = t * Math.cos(M), w = t * Math.sin(M), x = u + d + b * u;
      }
      const T = Math.max(0, Math.min(1, x / p));
      let R = 0;
      v === 0 ? R = 0.5 / n : v === f && (R = -0.5 / n);
      for (let b = 0; b <= n; b++) {
        const M = b / n, L = M * Math.PI * 2, U = Math.sin(L), O = Math.cos(L);
        m.x = -S * O, m.y = _, m.z = S * U, o.push(m.x, m.y, m.z), g.set(
          -S * O,
          w,
          S * U
        ), g.normalize(), l.push(g.x, g.y, g.z), h.push(M + R, T);
      }
      if (v > 0) {
        const b = (v - 1) * y;
        for (let M = 0; M < n; M++) {
          const L = b + M, U = b + M + 1, O = v * y + M, V = v * y + M + 1;
          r.push(L, U, O), r.push(U, V, O);
        }
      }
    }
    this.setIndex(r), this.setAttribute("position", new wt(o, 3)), this.setAttribute("normal", new wt(l, 3)), this.setAttribute("uv", new wt(h, 2));
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {CapsuleGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Zc(t.radius, t.height, t.capSegments, t.radialSegments, t.heightSegments);
  }
}
class jc extends Ht {
  /**
   * Constructs a new circle geometry.
   *
   * @param {number} [radius=1] - Radius of the circle.
   * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
   * @param {number} [thetaStart=0] - Start angle for first segment in radians.
   * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
   * of the circular sector in radians. The default value results in a complete circle.
   */
  constructor(t = 1, e = 32, i = 0, n = Math.PI * 2) {
    super(), this.type = "CircleGeometry", this.parameters = {
      radius: t,
      segments: e,
      thetaStart: i,
      thetaLength: n
    }, e = Math.max(3, e);
    const s = [], r = [], o = [], l = [], h = new E(), c = new J();
    r.push(0, 0, 0), o.push(0, 0, 1), l.push(0.5, 0.5);
    for (let u = 0, d = 3; u <= e; u++, d += 3) {
      const p = i + u / e * n;
      h.x = t * Math.cos(p), h.y = t * Math.sin(p), r.push(h.x, h.y, h.z), o.push(0, 0, 1), c.x = (r[d] / t + 1) / 2, c.y = (r[d + 1] / t + 1) / 2, l.push(c.x, c.y);
    }
    for (let u = 1; u <= e; u++)
      s.push(u, u + 1, 0);
    this.setIndex(s), this.setAttribute("position", new wt(r, 3)), this.setAttribute("normal", new wt(o, 3)), this.setAttribute("uv", new wt(l, 2));
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {CircleGeometry} A new instance.
   */
  static fromJSON(t) {
    return new jc(t.radius, t.segments, t.thetaStart, t.thetaLength);
  }
}
class Ta extends Ht {
  /**
   * Constructs a new cylinder geometry.
   *
   * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
   * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
   * @param {number} [height=1] - Height of the cylinder.
   * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
   * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
   * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
   * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
   * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
   * The default value results in a complete cylinder.
   */
  constructor(t = 1, e = 1, i = 1, n = 32, s = 1, r = !1, o = 0, l = Math.PI * 2) {
    super(), this.type = "CylinderGeometry", this.parameters = {
      radiusTop: t,
      radiusBottom: e,
      height: i,
      radialSegments: n,
      heightSegments: s,
      openEnded: r,
      thetaStart: o,
      thetaLength: l
    };
    const h = this;
    n = Math.floor(n), s = Math.floor(s);
    const c = [], u = [], d = [], p = [];
    let f = 0;
    const y = [], g = i / 2;
    let m = 0;
    v(), r === !1 && (t > 0 && x(!0), e > 0 && x(!1)), this.setIndex(c), this.setAttribute("position", new wt(u, 3)), this.setAttribute("normal", new wt(d, 3)), this.setAttribute("uv", new wt(p, 2));
    function v() {
      const _ = new E(), S = new E();
      let w = 0;
      const T = (e - t) / i;
      for (let R = 0; R <= s; R++) {
        const b = [], M = R / s, L = M * (e - t) + t;
        for (let U = 0; U <= n; U++) {
          const O = U / n, V = O * l + o, W = Math.sin(V), G = Math.cos(V);
          S.x = L * W, S.y = -M * i + g, S.z = L * G, u.push(S.x, S.y, S.z), _.set(W, T, G).normalize(), d.push(_.x, _.y, _.z), p.push(O, 1 - M), b.push(f++);
        }
        y.push(b);
      }
      for (let R = 0; R < n; R++)
        for (let b = 0; b < s; b++) {
          const M = y[b][R], L = y[b + 1][R], U = y[b + 1][R + 1], O = y[b][R + 1];
          (t > 0 || b !== 0) && (c.push(M, L, O), w += 3), (e > 0 || b !== s - 1) && (c.push(L, U, O), w += 3);
        }
      h.addGroup(m, w, 0), m += w;
    }
    function x(_) {
      const S = f, w = new J(), T = new E();
      let R = 0;
      const b = _ === !0 ? t : e, M = _ === !0 ? 1 : -1;
      for (let U = 1; U <= n; U++)
        u.push(0, g * M, 0), d.push(0, M, 0), p.push(0.5, 0.5), f++;
      const L = f;
      for (let U = 0; U <= n; U++) {
        const V = U / n * l + o, W = Math.cos(V), G = Math.sin(V);
        T.x = b * G, T.y = g * M, T.z = b * W, u.push(T.x, T.y, T.z), d.push(0, M, 0), w.x = W * 0.5 + 0.5, w.y = G * 0.5 * M + 0.5, p.push(w.x, w.y), f++;
      }
      for (let U = 0; U < n; U++) {
        const O = S + U, V = L + U;
        _ === !0 ? c.push(V, V + 1, O) : c.push(V + 1, V, O), R += 3;
      }
      h.addGroup(m, R, _ === !0 ? 1 : 2), m += R;
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {CylinderGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Ta(t.radiusTop, t.radiusBottom, t.height, t.radialSegments, t.heightSegments, t.openEnded, t.thetaStart, t.thetaLength);
  }
}
class Ca extends Ta {
  /**
   * Constructs a new cone geometry.
   *
   * @param {number} [radius=1] - Radius of the cone base.
   * @param {number} [height=1] - Height of the cone.
   * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
   * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
   * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
   * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
   * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
   * The default value results in a complete cone.
   */
  constructor(t = 1, e = 1, i = 32, n = 1, s = !1, r = 0, o = Math.PI * 2) {
    super(0, t, e, i, n, s, r, o), this.type = "ConeGeometry", this.parameters = {
      radius: t,
      height: e,
      radialSegments: i,
      heightSegments: n,
      openEnded: s,
      thetaStart: r,
      thetaLength: o
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {ConeGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Ca(t.radius, t.height, t.radialSegments, t.heightSegments, t.openEnded, t.thetaStart, t.thetaLength);
  }
}
class Ls extends Ht {
  /**
   * Constructs a new polyhedron geometry.
   *
   * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
   * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
   * @param {number} [radius=1] - The radius of the shape.
   * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
   */
  constructor(t = [], e = [], i = 1, n = 0) {
    super(), this.type = "PolyhedronGeometry", this.parameters = {
      vertices: t,
      indices: e,
      radius: i,
      detail: n
    };
    const s = [], r = [];
    o(n), h(i), c(), this.setAttribute("position", new wt(s, 3)), this.setAttribute("normal", new wt(s.slice(), 3)), this.setAttribute("uv", new wt(r, 2)), n === 0 ? this.computeVertexNormals() : this.normalizeNormals();
    function o(v) {
      const x = new E(), _ = new E(), S = new E();
      for (let w = 0; w < e.length; w += 3)
        p(e[w + 0], x), p(e[w + 1], _), p(e[w + 2], S), l(x, _, S, v);
    }
    function l(v, x, _, S) {
      const w = S + 1, T = [];
      for (let R = 0; R <= w; R++) {
        T[R] = [];
        const b = v.clone().lerp(_, R / w), M = x.clone().lerp(_, R / w), L = w - R;
        for (let U = 0; U <= L; U++)
          U === 0 && R === w ? T[R][U] = b : T[R][U] = b.clone().lerp(M, U / L);
      }
      for (let R = 0; R < w; R++)
        for (let b = 0; b < 2 * (w - R) - 1; b++) {
          const M = Math.floor(b / 2);
          b % 2 === 0 ? (d(T[R][M + 1]), d(T[R + 1][M]), d(T[R][M])) : (d(T[R][M + 1]), d(T[R + 1][M + 1]), d(T[R + 1][M]));
        }
    }
    function h(v) {
      const x = new E();
      for (let _ = 0; _ < s.length; _ += 3)
        x.x = s[_ + 0], x.y = s[_ + 1], x.z = s[_ + 2], x.normalize().multiplyScalar(v), s[_ + 0] = x.x, s[_ + 1] = x.y, s[_ + 2] = x.z;
    }
    function c() {
      const v = new E();
      for (let x = 0; x < s.length; x += 3) {
        v.x = s[x + 0], v.y = s[x + 1], v.z = s[x + 2];
        const _ = g(v) / 2 / Math.PI + 0.5, S = m(v) / Math.PI + 0.5;
        r.push(_, 1 - S);
      }
      f(), u();
    }
    function u() {
      for (let v = 0; v < r.length; v += 6) {
        const x = r[v + 0], _ = r[v + 2], S = r[v + 4], w = Math.max(x, _, S), T = Math.min(x, _, S);
        w > 0.9 && T < 0.1 && (x < 0.2 && (r[v + 0] += 1), _ < 0.2 && (r[v + 2] += 1), S < 0.2 && (r[v + 4] += 1));
      }
    }
    function d(v) {
      s.push(v.x, v.y, v.z);
    }
    function p(v, x) {
      const _ = v * 3;
      x.x = t[_ + 0], x.y = t[_ + 1], x.z = t[_ + 2];
    }
    function f() {
      const v = new E(), x = new E(), _ = new E(), S = new E(), w = new J(), T = new J(), R = new J();
      for (let b = 0, M = 0; b < s.length; b += 9, M += 6) {
        v.set(s[b + 0], s[b + 1], s[b + 2]), x.set(s[b + 3], s[b + 4], s[b + 5]), _.set(s[b + 6], s[b + 7], s[b + 8]), w.set(r[M + 0], r[M + 1]), T.set(r[M + 2], r[M + 3]), R.set(r[M + 4], r[M + 5]), S.copy(v).add(x).add(_).divideScalar(3);
        const L = g(S);
        y(w, M + 0, v, L), y(T, M + 2, x, L), y(R, M + 4, _, L);
      }
    }
    function y(v, x, _, S) {
      S < 0 && v.x === 1 && (r[x] = v.x - 1), _.x === 0 && _.z === 0 && (r[x] = S / 2 / Math.PI + 0.5);
    }
    function g(v) {
      return Math.atan2(v.z, -v.x);
    }
    function m(v) {
      return Math.atan2(-v.y, Math.sqrt(v.x * v.x + v.z * v.z));
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {PolyhedronGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Ls(t.vertices, t.indices, t.radius, t.details);
  }
}
class Jc extends Ls {
  /**
   * Constructs a new dodecahedron geometry.
   *
   * @param {number} [radius=1] - Radius of the dodecahedron.
   * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
   */
  constructor(t = 1, e = 0) {
    const i = (1 + Math.sqrt(5)) / 2, n = 1 / i, s = [
      // (±1, ±1, ±1)
      -1,
      -1,
      -1,
      -1,
      -1,
      1,
      -1,
      1,
      -1,
      -1,
      1,
      1,
      1,
      -1,
      -1,
      1,
      -1,
      1,
      1,
      1,
      -1,
      1,
      1,
      1,
      // (0, ±1/φ, ±φ)
      0,
      -n,
      -i,
      0,
      -n,
      i,
      0,
      n,
      -i,
      0,
      n,
      i,
      // (±1/φ, ±φ, 0)
      -n,
      -i,
      0,
      -n,
      i,
      0,
      n,
      -i,
      0,
      n,
      i,
      0,
      // (±φ, 0, ±1/φ)
      -i,
      0,
      -n,
      i,
      0,
      -n,
      -i,
      0,
      n,
      i,
      0,
      n
    ], r = [
      3,
      11,
      7,
      3,
      7,
      15,
      3,
      15,
      13,
      7,
      19,
      17,
      7,
      17,
      6,
      7,
      6,
      15,
      17,
      4,
      8,
      17,
      8,
      10,
      17,
      10,
      6,
      8,
      0,
      16,
      8,
      16,
      2,
      8,
      2,
      10,
      0,
      12,
      1,
      0,
      1,
      18,
      0,
      18,
      16,
      6,
      10,
      2,
      6,
      2,
      13,
      6,
      13,
      15,
      2,
      16,
      18,
      2,
      18,
      3,
      2,
      3,
      13,
      18,
      1,
      9,
      18,
      9,
      11,
      18,
      11,
      3,
      4,
      14,
      12,
      4,
      12,
      0,
      4,
      0,
      8,
      11,
      9,
      5,
      11,
      5,
      19,
      11,
      19,
      7,
      19,
      5,
      14,
      19,
      14,
      4,
      19,
      4,
      17,
      1,
      12,
      14,
      1,
      14,
      5,
      1,
      5,
      9
    ];
    super(s, r, t, e), this.type = "DodecahedronGeometry", this.parameters = {
      radius: t,
      detail: e
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {DodecahedronGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Jc(t.radius, t.detail);
  }
}
const wl = /* @__PURE__ */ new E(), Al = /* @__PURE__ */ new E(), Wu = /* @__PURE__ */ new E(), El = /* @__PURE__ */ new bs();
class By extends Ht {
  /**
   * Constructs a new edges geometry.
   *
   * @param {?BufferGeometry} [geometry=null] - The geometry.
   * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
   * between the face normals of the adjoining faces exceeds this value.
   */
  constructor(t = null, e = 1) {
    if (super(), this.type = "EdgesGeometry", this.parameters = {
      geometry: t,
      thresholdAngle: e
    }, t !== null) {
      const n = Math.pow(10, 4), s = Math.cos(lr * e), r = t.getIndex(), o = t.getAttribute("position"), l = r ? r.count : o.count, h = [0, 0, 0], c = ["a", "b", "c"], u = new Array(3), d = {}, p = [];
      for (let f = 0; f < l; f += 3) {
        r ? (h[0] = r.getX(f), h[1] = r.getX(f + 1), h[2] = r.getX(f + 2)) : (h[0] = f, h[1] = f + 1, h[2] = f + 2);
        const { a: y, b: g, c: m } = El;
        if (y.fromBufferAttribute(o, h[0]), g.fromBufferAttribute(o, h[1]), m.fromBufferAttribute(o, h[2]), El.getNormal(Wu), u[0] = `${Math.round(y.x * n)},${Math.round(y.y * n)},${Math.round(y.z * n)}`, u[1] = `${Math.round(g.x * n)},${Math.round(g.y * n)},${Math.round(g.z * n)}`, u[2] = `${Math.round(m.x * n)},${Math.round(m.y * n)},${Math.round(m.z * n)}`, !(u[0] === u[1] || u[1] === u[2] || u[2] === u[0]))
          for (let v = 0; v < 3; v++) {
            const x = (v + 1) % 3, _ = u[v], S = u[x], w = El[c[v]], T = El[c[x]], R = `${_}_${S}`, b = `${S}_${_}`;
            b in d && d[b] ? (Wu.dot(d[b].normal) <= s && (p.push(w.x, w.y, w.z), p.push(T.x, T.y, T.z)), d[b] = null) : R in d || (d[R] = {
              index0: h[v],
              index1: h[x],
              normal: Wu.clone()
            });
          }
      }
      for (const f in d)
        if (d[f]) {
          const { index0: y, index1: g } = d[f];
          wl.fromBufferAttribute(o, y), Al.fromBufferAttribute(o, g), p.push(wl.x, wl.y, wl.z), p.push(Al.x, Al.y, Al.z);
        }
      this.setAttribute("position", new wt(p, 3));
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
}
class mn {
  /**
   * Constructs a new curve.
   */
  constructor() {
    this.type = "Curve", this.arcLengthDivisions = 200, this.needsUpdate = !1, this.cacheArcLengths = null;
  }
  /**
   * This method returns a vector in 2D or 3D space (depending on the curve definition)
   * for the given interpolation factor.
   *
   * @abstract
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
   */
  getPoint() {
    console.warn("THREE.Curve: .getPoint() not implemented.");
  }
  /**
   * This method returns a vector in 2D or 3D space (depending on the curve definition)
   * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
   * of the curve which equidistant samples.
   *
   * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
   */
  getPointAt(t, e) {
    const i = this.getUtoTmapping(t);
    return this.getPoint(i, e);
  }
  /**
   * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
   * the curve shape.
   *
   * @param {number} [divisions=5] - The number of divisions.
   * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
   */
  getPoints(t = 5) {
    const e = [];
    for (let i = 0; i <= t; i++)
      e.push(this.getPoint(i / t));
    return e;
  }
  // Get sequence of points using getPointAt( u )
  /**
   * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
   * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
   * curve.
   *
   * @param {number} [divisions=5] - The number of divisions.
   * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
   */
  getSpacedPoints(t = 5) {
    const e = [];
    for (let i = 0; i <= t; i++)
      e.push(this.getPointAt(i / t));
    return e;
  }
  /**
   * Returns the total arc length of the curve.
   *
   * @return {number} The length of the curve.
   */
  getLength() {
    const t = this.getLengths();
    return t[t.length - 1];
  }
  /**
   * Returns an array of cumulative segment lengths of the curve.
   *
   * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
   * @return {Array<number>} An array holding the cumulative segment lengths.
   */
  getLengths(t = this.arcLengthDivisions) {
    if (this.cacheArcLengths && this.cacheArcLengths.length === t + 1 && !this.needsUpdate)
      return this.cacheArcLengths;
    this.needsUpdate = !1;
    const e = [];
    let i, n = this.getPoint(0), s = 0;
    e.push(0);
    for (let r = 1; r <= t; r++)
      i = this.getPoint(r / t), s += i.distanceTo(n), e.push(s), n = i;
    return this.cacheArcLengths = e, e;
  }
  /**
   * Update the cumulative segment distance cache. The method must be called
   * every time curve parameters are changed. If an updated curve is part of a
   * composed curve like {@link CurvePath}, this method must be called on the
   * composed curve, too.
   */
  updateArcLengths() {
    this.needsUpdate = !0, this.getLengths();
  }
  /**
   * Given an interpolation factor in the range `[0,1]`, this method returns an updated
   * interpolation factor in the same range that can be ued to sample equidistant points
   * from a curve.
   *
   * @param {number} u - The interpolation factor.
   * @param {?number} distance - An optional distance on the curve.
   * @return {number} The updated interpolation factor.
   */
  getUtoTmapping(t, e = null) {
    const i = this.getLengths();
    let n = 0;
    const s = i.length;
    let r;
    e ? r = e : r = t * i[s - 1];
    let o = 0, l = s - 1, h;
    for (; o <= l; )
      if (n = Math.floor(o + (l - o) / 2), h = i[n] - r, h < 0)
        o = n + 1;
      else if (h > 0)
        l = n - 1;
      else {
        l = n;
        break;
      }
    if (n = l, i[n] === r)
      return n / (s - 1);
    const c = i[n], d = i[n + 1] - c, p = (r - c) / d;
    return (n + p) / (s - 1);
  }
  /**
   * Returns a unit vector tangent for the given interpolation factor.
   * If the derived curve does not implement its tangent derivation,
   * two points a small delta apart will be used to find its gradient
   * which seems to give a reasonable approximation.
   *
   * @param {number} t - The interpolation factor.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {(Vector2|Vector3)} The tangent vector.
   */
  getTangent(t, e) {
    let n = t - 1e-4, s = t + 1e-4;
    n < 0 && (n = 0), s > 1 && (s = 1);
    const r = this.getPoint(n), o = this.getPoint(s), l = e || (r.isVector2 ? new J() : new E());
    return l.copy(o).sub(r).normalize(), l;
  }
  /**
   * Same as {@link Curve#getTangent} but with equidistant samples.
   *
   * @param {number} u - The interpolation factor.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {(Vector2|Vector3)} The tangent vector.
   * @see {@link Curve#getPointAt}
   */
  getTangentAt(t, e) {
    const i = this.getUtoTmapping(t);
    return this.getTangent(i, e);
  }
  /**
   * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
   * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
   *
   * @param {number} segments - The number of segments.
   * @param {boolean} [closed=false] - Whether the curve is closed or not.
   * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
   */
  computeFrenetFrames(t, e = !1) {
    const i = new E(), n = [], s = [], r = [], o = new E(), l = new Vt();
    for (let p = 0; p <= t; p++) {
      const f = p / t;
      n[p] = this.getTangentAt(f, new E());
    }
    s[0] = new E(), r[0] = new E();
    let h = Number.MAX_VALUE;
    const c = Math.abs(n[0].x), u = Math.abs(n[0].y), d = Math.abs(n[0].z);
    c <= h && (h = c, i.set(1, 0, 0)), u <= h && (h = u, i.set(0, 1, 0)), d <= h && i.set(0, 0, 1), o.crossVectors(n[0], i).normalize(), s[0].crossVectors(n[0], o), r[0].crossVectors(n[0], s[0]);
    for (let p = 1; p <= t; p++) {
      if (s[p] = s[p - 1].clone(), r[p] = r[p - 1].clone(), o.crossVectors(n[p - 1], n[p]), o.length() > Number.EPSILON) {
        o.normalize();
        const f = Math.acos(kt(n[p - 1].dot(n[p]), -1, 1));
        s[p].applyMatrix4(l.makeRotationAxis(o, f));
      }
      r[p].crossVectors(n[p], s[p]);
    }
    if (e === !0) {
      let p = Math.acos(kt(s[0].dot(s[t]), -1, 1));
      p /= t, n[0].dot(o.crossVectors(s[0], s[t])) > 0 && (p = -p);
      for (let f = 1; f <= t; f++)
        s[f].applyMatrix4(l.makeRotationAxis(n[f], p * f)), r[f].crossVectors(n[f], s[f]);
    }
    return {
      tangents: n,
      normals: s,
      binormals: r
    };
  }
  /**
   * Returns a new curve with copied values from this instance.
   *
   * @return {Curve} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given curve to this instance.
   *
   * @param {Curve} source - The curve to copy.
   * @return {Curve} A reference to this curve.
   */
  copy(t) {
    return this.arcLengthDivisions = t.arcLengthDivisions, this;
  }
  /**
   * Serializes the curve into JSON.
   *
   * @return {Object} A JSON object representing the serialized curve.
   * @see {@link ObjectLoader#parse}
   */
  toJSON() {
    const t = {
      metadata: {
        version: 4.7,
        type: "Curve",
        generator: "Curve.toJSON"
      }
    };
    return t.arcLengthDivisions = this.arcLengthDivisions, t.type = this.type, t;
  }
  /**
   * Deserializes the curve from the given JSON.
   *
   * @param {Object} json - The JSON holding the serialized curve.
   * @return {Curve} A reference to this curve.
   */
  fromJSON(t) {
    return this.arcLengthDivisions = t.arcLengthDivisions, this;
  }
}
class Kc extends mn {
  /**
   * Constructs a new ellipse curve.
   *
   * @param {number} [aX=0] - The X center of the ellipse.
   * @param {number} [aY=0] - The Y center of the ellipse.
   * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
   * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
   * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
   * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
   * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
   */
  constructor(t = 0, e = 0, i = 1, n = 1, s = 0, r = Math.PI * 2, o = !1, l = 0) {
    super(), this.isEllipseCurve = !0, this.type = "EllipseCurve", this.aX = t, this.aY = e, this.xRadius = i, this.yRadius = n, this.aStartAngle = s, this.aEndAngle = r, this.aClockwise = o, this.aRotation = l;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the curve.
   */
  getPoint(t, e = new J()) {
    const i = e, n = Math.PI * 2;
    let s = this.aEndAngle - this.aStartAngle;
    const r = Math.abs(s) < Number.EPSILON;
    for (; s < 0; ) s += n;
    for (; s > n; ) s -= n;
    s < Number.EPSILON && (r ? s = 0 : s = n), this.aClockwise === !0 && !r && (s === n ? s = -n : s = s - n);
    const o = this.aStartAngle + t * s;
    let l = this.aX + this.xRadius * Math.cos(o), h = this.aY + this.yRadius * Math.sin(o);
    if (this.aRotation !== 0) {
      const c = Math.cos(this.aRotation), u = Math.sin(this.aRotation), d = l - this.aX, p = h - this.aY;
      l = d * c - p * u + this.aX, h = d * u + p * c + this.aY;
    }
    return i.set(l, h);
  }
  copy(t) {
    return super.copy(t), this.aX = t.aX, this.aY = t.aY, this.xRadius = t.xRadius, this.yRadius = t.yRadius, this.aStartAngle = t.aStartAngle, this.aEndAngle = t.aEndAngle, this.aClockwise = t.aClockwise, this.aRotation = t.aRotation, this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.aX = this.aX, t.aY = this.aY, t.xRadius = this.xRadius, t.yRadius = this.yRadius, t.aStartAngle = this.aStartAngle, t.aEndAngle = this.aEndAngle, t.aClockwise = this.aClockwise, t.aRotation = this.aRotation, t;
  }
  fromJSON(t) {
    return super.fromJSON(t), this.aX = t.aX, this.aY = t.aY, this.xRadius = t.xRadius, this.yRadius = t.yRadius, this.aStartAngle = t.aStartAngle, this.aEndAngle = t.aEndAngle, this.aClockwise = t.aClockwise, this.aRotation = t.aRotation, this;
  }
}
class zy extends Kc {
  /**
   * Constructs a new arc curve.
   *
   * @param {number} [aX=0] - The X center of the ellipse.
   * @param {number} [aY=0] - The Y center of the ellipse.
   * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
   * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
   * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
   */
  constructor(t, e, i, n, s, r) {
    super(t, e, i, i, n, s, r), this.isArcCurve = !0, this.type = "ArcCurve";
  }
}
function Gp() {
  let a = 0, t = 0, e = 0, i = 0;
  function n(s, r, o, l) {
    a = s, t = o, e = -3 * s + 3 * r - 2 * o - l, i = 2 * s - 2 * r + o + l;
  }
  return {
    initCatmullRom: function(s, r, o, l, h) {
      n(r, o, h * (o - s), h * (l - r));
    },
    initNonuniformCatmullRom: function(s, r, o, l, h, c, u) {
      let d = (r - s) / h - (o - s) / (h + c) + (o - r) / c, p = (o - r) / c - (l - r) / (c + u) + (l - o) / u;
      d *= c, p *= c, n(r, o, d, p);
    },
    calc: function(s) {
      const r = s * s, o = r * s;
      return a + t * s + e * r + i * o;
    }
  };
}
const Tl = /* @__PURE__ */ new E(), qu = /* @__PURE__ */ new Gp(), $u = /* @__PURE__ */ new Gp(), Xu = /* @__PURE__ */ new Gp();
class Ny extends mn {
  /**
   * Constructs a new Catmull-Rom curve.
   *
   * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
   * @param {boolean} [closed=false] - Whether the curve is closed or not.
   * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
   * @param {number} [tension=0.5] - Tension of the curve.
   */
  constructor(t = [], e = !1, i = "centripetal", n = 0.5) {
    super(), this.isCatmullRomCurve3 = !0, this.type = "CatmullRomCurve3", this.points = t, this.closed = e, this.curveType = i, this.tension = n;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t, e = new E()) {
    const i = e, n = this.points, s = n.length, r = (s - (this.closed ? 0 : 1)) * t;
    let o = Math.floor(r), l = r - o;
    this.closed ? o += o > 0 ? 0 : (Math.floor(Math.abs(o) / s) + 1) * s : l === 0 && o === s - 1 && (o = s - 2, l = 1);
    let h, c;
    this.closed || o > 0 ? h = n[(o - 1) % s] : (Tl.subVectors(n[0], n[1]).add(n[0]), h = Tl);
    const u = n[o % s], d = n[(o + 1) % s];
    if (this.closed || o + 2 < s ? c = n[(o + 2) % s] : (Tl.subVectors(n[s - 1], n[s - 2]).add(n[s - 1]), c = Tl), this.curveType === "centripetal" || this.curveType === "chordal") {
      const p = this.curveType === "chordal" ? 0.5 : 0.25;
      let f = Math.pow(h.distanceToSquared(u), p), y = Math.pow(u.distanceToSquared(d), p), g = Math.pow(d.distanceToSquared(c), p);
      y < 1e-4 && (y = 1), f < 1e-4 && (f = y), g < 1e-4 && (g = y), qu.initNonuniformCatmullRom(h.x, u.x, d.x, c.x, f, y, g), $u.initNonuniformCatmullRom(h.y, u.y, d.y, c.y, f, y, g), Xu.initNonuniformCatmullRom(h.z, u.z, d.z, c.z, f, y, g);
    } else this.curveType === "catmullrom" && (qu.initCatmullRom(h.x, u.x, d.x, c.x, this.tension), $u.initCatmullRom(h.y, u.y, d.y, c.y, this.tension), Xu.initCatmullRom(h.z, u.z, d.z, c.z, this.tension));
    return i.set(
      qu.calc(l),
      $u.calc(l),
      Xu.calc(l)
    ), i;
  }
  copy(t) {
    super.copy(t), this.points = [];
    for (let e = 0, i = t.points.length; e < i; e++) {
      const n = t.points[e];
      this.points.push(n.clone());
    }
    return this.closed = t.closed, this.curveType = t.curveType, this.tension = t.tension, this;
  }
  toJSON() {
    const t = super.toJSON();
    t.points = [];
    for (let e = 0, i = this.points.length; e < i; e++) {
      const n = this.points[e];
      t.points.push(n.toArray());
    }
    return t.closed = this.closed, t.curveType = this.curveType, t.tension = this.tension, t;
  }
  fromJSON(t) {
    super.fromJSON(t), this.points = [];
    for (let e = 0, i = t.points.length; e < i; e++) {
      const n = t.points[e];
      this.points.push(new E().fromArray(n));
    }
    return this.closed = t.closed, this.curveType = t.curveType, this.tension = t.tension, this;
  }
}
function pm(a, t, e, i, n) {
  const s = (i - t) * 0.5, r = (n - e) * 0.5, o = a * a, l = a * o;
  return (2 * e - 2 * i + s + r) * l + (-3 * e + 3 * i - 2 * s - r) * o + s * a + e;
}
function rb(a, t) {
  const e = 1 - a;
  return e * e * t;
}
function ab(a, t) {
  return 2 * (1 - a) * a * t;
}
function ob(a, t) {
  return a * a * t;
}
function mo(a, t, e, i) {
  return rb(a, t) + ab(a, e) + ob(a, i);
}
function lb(a, t) {
  const e = 1 - a;
  return e * e * e * t;
}
function hb(a, t) {
  const e = 1 - a;
  return 3 * e * e * a * t;
}
function cb(a, t) {
  return 3 * (1 - a) * a * a * t;
}
function ub(a, t) {
  return a * a * a * t;
}
function go(a, t, e, i, n) {
  return lb(a, t) + hb(a, e) + cb(a, i) + ub(a, n);
}
class Wp extends mn {
  /**
   * Constructs a new Cubic Bezier curve.
   *
   * @param {Vector2} [v0] - The start point.
   * @param {Vector2} [v1] - The first control point.
   * @param {Vector2} [v2] - The second control point.
   * @param {Vector2} [v3] - The end point.
   */
  constructor(t = new J(), e = new J(), i = new J(), n = new J()) {
    super(), this.isCubicBezierCurve = !0, this.type = "CubicBezierCurve", this.v0 = t, this.v1 = e, this.v2 = i, this.v3 = n;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the curve.
   */
  getPoint(t, e = new J()) {
    const i = e, n = this.v0, s = this.v1, r = this.v2, o = this.v3;
    return i.set(
      go(t, n.x, s.x, r.x, o.x),
      go(t, n.y, s.y, r.y, o.y)
    ), i;
  }
  copy(t) {
    return super.copy(t), this.v0.copy(t.v0), this.v1.copy(t.v1), this.v2.copy(t.v2), this.v3.copy(t.v3), this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.v0 = this.v0.toArray(), t.v1 = this.v1.toArray(), t.v2 = this.v2.toArray(), t.v3 = this.v3.toArray(), t;
  }
  fromJSON(t) {
    return super.fromJSON(t), this.v0.fromArray(t.v0), this.v1.fromArray(t.v1), this.v2.fromArray(t.v2), this.v3.fromArray(t.v3), this;
  }
}
class Oy extends mn {
  /**
   * Constructs a new Cubic Bezier curve.
   *
   * @param {Vector3} [v0] - The start point.
   * @param {Vector3} [v1] - The first control point.
   * @param {Vector3} [v2] - The second control point.
   * @param {Vector3} [v3] - The end point.
   */
  constructor(t = new E(), e = new E(), i = new E(), n = new E()) {
    super(), this.isCubicBezierCurve3 = !0, this.type = "CubicBezierCurve3", this.v0 = t, this.v1 = e, this.v2 = i, this.v3 = n;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t, e = new E()) {
    const i = e, n = this.v0, s = this.v1, r = this.v2, o = this.v3;
    return i.set(
      go(t, n.x, s.x, r.x, o.x),
      go(t, n.y, s.y, r.y, o.y),
      go(t, n.z, s.z, r.z, o.z)
    ), i;
  }
  copy(t) {
    return super.copy(t), this.v0.copy(t.v0), this.v1.copy(t.v1), this.v2.copy(t.v2), this.v3.copy(t.v3), this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.v0 = this.v0.toArray(), t.v1 = this.v1.toArray(), t.v2 = this.v2.toArray(), t.v3 = this.v3.toArray(), t;
  }
  fromJSON(t) {
    return super.fromJSON(t), this.v0.fromArray(t.v0), this.v1.fromArray(t.v1), this.v2.fromArray(t.v2), this.v3.fromArray(t.v3), this;
  }
}
class qp extends mn {
  /**
   * Constructs a new line curve.
   *
   * @param {Vector2} [v1] - The start point.
   * @param {Vector2} [v2] - The end point.
   */
  constructor(t = new J(), e = new J()) {
    super(), this.isLineCurve = !0, this.type = "LineCurve", this.v1 = t, this.v2 = e;
  }
  /**
   * Returns a point on the line.
   *
   * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the line.
   */
  getPoint(t, e = new J()) {
    const i = e;
    return t === 1 ? i.copy(this.v2) : (i.copy(this.v2).sub(this.v1), i.multiplyScalar(t).add(this.v1)), i;
  }
  // Line curve is linear, so we can overwrite default getPointAt
  getPointAt(t, e) {
    return this.getPoint(t, e);
  }
  getTangent(t, e = new J()) {
    return e.subVectors(this.v2, this.v1).normalize();
  }
  getTangentAt(t, e) {
    return this.getTangent(t, e);
  }
  copy(t) {
    return super.copy(t), this.v1.copy(t.v1), this.v2.copy(t.v2), this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.v1 = this.v1.toArray(), t.v2 = this.v2.toArray(), t;
  }
  fromJSON(t) {
    return super.fromJSON(t), this.v1.fromArray(t.v1), this.v2.fromArray(t.v2), this;
  }
}
class ky extends mn {
  /**
   * Constructs a new line curve.
   *
   * @param {Vector3} [v1] - The start point.
   * @param {Vector3} [v2] - The end point.
   */
  constructor(t = new E(), e = new E()) {
    super(), this.isLineCurve3 = !0, this.type = "LineCurve3", this.v1 = t, this.v2 = e;
  }
  /**
   * Returns a point on the line.
   *
   * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the line.
   */
  getPoint(t, e = new E()) {
    const i = e;
    return t === 1 ? i.copy(this.v2) : (i.copy(this.v2).sub(this.v1), i.multiplyScalar(t).add(this.v1)), i;
  }
  // Line curve is linear, so we can overwrite default getPointAt
  getPointAt(t, e) {
    return this.getPoint(t, e);
  }
  getTangent(t, e = new E()) {
    return e.subVectors(this.v2, this.v1).normalize();
  }
  getTangentAt(t, e) {
    return this.getTangent(t, e);
  }
  copy(t) {
    return super.copy(t), this.v1.copy(t.v1), this.v2.copy(t.v2), this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.v1 = this.v1.toArray(), t.v2 = this.v2.toArray(), t;
  }
  fromJSON(t) {
    return super.fromJSON(t), this.v1.fromArray(t.v1), this.v2.fromArray(t.v2), this;
  }
}
class $p extends mn {
  /**
   * Constructs a new Quadratic Bezier curve.
   *
   * @param {Vector2} [v0] - The start point.
   * @param {Vector2} [v1] - The control point.
   * @param {Vector2} [v2] - The end point.
   */
  constructor(t = new J(), e = new J(), i = new J()) {
    super(), this.isQuadraticBezierCurve = !0, this.type = "QuadraticBezierCurve", this.v0 = t, this.v1 = e, this.v2 = i;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the curve.
   */
  getPoint(t, e = new J()) {
    const i = e, n = this.v0, s = this.v1, r = this.v2;
    return i.set(
      mo(t, n.x, s.x, r.x),
      mo(t, n.y, s.y, r.y)
    ), i;
  }
  copy(t) {
    return super.copy(t), this.v0.copy(t.v0), this.v1.copy(t.v1), this.v2.copy(t.v2), this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.v0 = this.v0.toArray(), t.v1 = this.v1.toArray(), t.v2 = this.v2.toArray(), t;
  }
  fromJSON(t) {
    return super.fromJSON(t), this.v0.fromArray(t.v0), this.v1.fromArray(t.v1), this.v2.fromArray(t.v2), this;
  }
}
class Xp extends mn {
  /**
   * Constructs a new Quadratic Bezier curve.
   *
   * @param {Vector3} [v0] - The start point.
   * @param {Vector3} [v1] - The control point.
   * @param {Vector3} [v2] - The end point.
   */
  constructor(t = new E(), e = new E(), i = new E()) {
    super(), this.isQuadraticBezierCurve3 = !0, this.type = "QuadraticBezierCurve3", this.v0 = t, this.v1 = e, this.v2 = i;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t, e = new E()) {
    const i = e, n = this.v0, s = this.v1, r = this.v2;
    return i.set(
      mo(t, n.x, s.x, r.x),
      mo(t, n.y, s.y, r.y),
      mo(t, n.z, s.z, r.z)
    ), i;
  }
  copy(t) {
    return super.copy(t), this.v0.copy(t.v0), this.v1.copy(t.v1), this.v2.copy(t.v2), this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.v0 = this.v0.toArray(), t.v1 = this.v1.toArray(), t.v2 = this.v2.toArray(), t;
  }
  fromJSON(t) {
    return super.fromJSON(t), this.v0.fromArray(t.v0), this.v1.fromArray(t.v1), this.v2.fromArray(t.v2), this;
  }
}
class Yp extends mn {
  /**
   * Constructs a new 2D spline curve.
   *
   * @param {Array<Vector2>} [points] -  An array of 2D points defining the curve.
   */
  constructor(t = []) {
    super(), this.isSplineCurve = !0, this.type = "SplineCurve", this.points = t;
  }
  /**
   * Returns a point on the curve.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector2} The position on the curve.
   */
  getPoint(t, e = new J()) {
    const i = e, n = this.points, s = (n.length - 1) * t, r = Math.floor(s), o = s - r, l = n[r === 0 ? r : r - 1], h = n[r], c = n[r > n.length - 2 ? n.length - 1 : r + 1], u = n[r > n.length - 3 ? n.length - 1 : r + 2];
    return i.set(
      pm(o, l.x, h.x, c.x, u.x),
      pm(o, l.y, h.y, c.y, u.y)
    ), i;
  }
  copy(t) {
    super.copy(t), this.points = [];
    for (let e = 0, i = t.points.length; e < i; e++) {
      const n = t.points[e];
      this.points.push(n.clone());
    }
    return this;
  }
  toJSON() {
    const t = super.toJSON();
    t.points = [];
    for (let e = 0, i = this.points.length; e < i; e++) {
      const n = this.points[e];
      t.points.push(n.toArray());
    }
    return t;
  }
  fromJSON(t) {
    super.fromJSON(t), this.points = [];
    for (let e = 0, i = t.points.length; e < i; e++) {
      const n = t.points[e];
      this.points.push(new J().fromArray(n));
    }
    return this;
  }
}
var _c = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ArcCurve: zy,
  CatmullRomCurve3: Ny,
  CubicBezierCurve: Wp,
  CubicBezierCurve3: Oy,
  EllipseCurve: Kc,
  LineCurve: qp,
  LineCurve3: ky,
  QuadraticBezierCurve: $p,
  QuadraticBezierCurve3: Xp,
  SplineCurve: Yp
});
class Vy extends mn {
  /**
   * Constructs a new curve path.
   */
  constructor() {
    super(), this.type = "CurvePath", this.curves = [], this.autoClose = !1;
  }
  /**
   * Adds a curve to this curve path.
   *
   * @param {Curve} curve - The curve to add.
   */
  add(t) {
    this.curves.push(t);
  }
  /**
   * Adds a line curve to close the path.
   *
   * @return {CurvePath} A reference to this curve path.
   */
  closePath() {
    const t = this.curves[0].getPoint(0), e = this.curves[this.curves.length - 1].getPoint(1);
    if (!t.equals(e)) {
      const i = t.isVector2 === !0 ? "LineCurve" : "LineCurve3";
      this.curves.push(new _c[i](e, t));
    }
    return this;
  }
  /**
   * This method returns a vector in 2D or 3D space (depending on the curve definitions)
   * for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
   * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
   */
  getPoint(t, e) {
    const i = t * this.getLength(), n = this.getCurveLengths();
    let s = 0;
    for (; s < n.length; ) {
      if (n[s] >= i) {
        const r = n[s] - i, o = this.curves[s], l = o.getLength(), h = l === 0 ? 0 : 1 - r / l;
        return o.getPointAt(h, e);
      }
      s++;
    }
    return null;
  }
  getLength() {
    const t = this.getCurveLengths();
    return t[t.length - 1];
  }
  updateArcLengths() {
    this.needsUpdate = !0, this.cacheLengths = null, this.getCurveLengths();
  }
  /**
   * Returns list of cumulative curve lengths of the defined curves.
   *
   * @return {Array<number>} The curve lengths.
   */
  getCurveLengths() {
    if (this.cacheLengths && this.cacheLengths.length === this.curves.length)
      return this.cacheLengths;
    const t = [];
    let e = 0;
    for (let i = 0, n = this.curves.length; i < n; i++)
      e += this.curves[i].getLength(), t.push(e);
    return this.cacheLengths = t, t;
  }
  getSpacedPoints(t = 40) {
    const e = [];
    for (let i = 0; i <= t; i++)
      e.push(this.getPoint(i / t));
    return this.autoClose && e.push(e[0]), e;
  }
  getPoints(t = 12) {
    const e = [];
    let i;
    for (let n = 0, s = this.curves; n < s.length; n++) {
      const r = s[n], o = r.isEllipseCurve ? t * 2 : r.isLineCurve || r.isLineCurve3 ? 1 : r.isSplineCurve ? t * r.points.length : t, l = r.getPoints(o);
      for (let h = 0; h < l.length; h++) {
        const c = l[h];
        i && i.equals(c) || (e.push(c), i = c);
      }
    }
    return this.autoClose && e.length > 1 && !e[e.length - 1].equals(e[0]) && e.push(e[0]), e;
  }
  copy(t) {
    super.copy(t), this.curves = [];
    for (let e = 0, i = t.curves.length; e < i; e++) {
      const n = t.curves[e];
      this.curves.push(n.clone());
    }
    return this.autoClose = t.autoClose, this;
  }
  toJSON() {
    const t = super.toJSON();
    t.autoClose = this.autoClose, t.curves = [];
    for (let e = 0, i = this.curves.length; e < i; e++) {
      const n = this.curves[e];
      t.curves.push(n.toJSON());
    }
    return t;
  }
  fromJSON(t) {
    super.fromJSON(t), this.autoClose = t.autoClose, this.curves = [];
    for (let e = 0, i = t.curves.length; e < i; e++) {
      const n = t.curves[e];
      this.curves.push(new _c[n.type]().fromJSON(n));
    }
    return this;
  }
}
class xc extends Vy {
  /**
   * Constructs a new path.
   *
   * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
   */
  constructor(t) {
    super(), this.type = "Path", this.currentPoint = new J(), t && this.setFromPoints(t);
  }
  /**
   * Creates a path from the given list of points. The points are added
   * to the path as instances of {@link LineCurve}.
   *
   * @param {Array<Vector2>} points - An array of 2D points.
   * @return {Path} A reference to this path.
   */
  setFromPoints(t) {
    this.moveTo(t[0].x, t[0].y);
    for (let e = 1, i = t.length; e < i; e++)
      this.lineTo(t[e].x, t[e].y);
    return this;
  }
  /**
   * Moves {@link Path#currentPoint} to the given point.
   *
   * @param {number} x - The x coordinate.
   * @param {number} y - The y coordinate.
   * @return {Path} A reference to this path.
   */
  moveTo(t, e) {
    return this.currentPoint.set(t, e), this;
  }
  /**
   * Adds an instance of {@link LineCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} x - The x coordinate of the end point.
   * @param {number} y - The y coordinate of the end point.
   * @return {Path} A reference to this path.
   */
  lineTo(t, e) {
    const i = new qp(this.currentPoint.clone(), new J(t, e));
    return this.curves.push(i), this.currentPoint.set(t, e), this;
  }
  /**
   * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} aCPx - The x coordinate of the control point.
   * @param {number} aCPy - The y coordinate of the control point.
   * @param {number} aX - The x coordinate of the end point.
   * @param {number} aY - The y coordinate of the end point.
   * @return {Path} A reference to this path.
   */
  quadraticCurveTo(t, e, i, n) {
    const s = new $p(
      this.currentPoint.clone(),
      new J(t, e),
      new J(i, n)
    );
    return this.curves.push(s), this.currentPoint.set(i, n), this;
  }
  /**
   * Adds an instance of {@link CubicBezierCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} aCP1x - The x coordinate of the first control point.
   * @param {number} aCP1y - The y coordinate of the first control point.
   * @param {number} aCP2x - The x coordinate of the second control point.
   * @param {number} aCP2y - The y coordinate of the second control point.
   * @param {number} aX - The x coordinate of the end point.
   * @param {number} aY - The y coordinate of the end point.
   * @return {Path} A reference to this path.
   */
  bezierCurveTo(t, e, i, n, s, r) {
    const o = new Wp(
      this.currentPoint.clone(),
      new J(t, e),
      new J(i, n),
      new J(s, r)
    );
    return this.curves.push(o), this.currentPoint.set(s, r), this;
  }
  /**
   * Adds an instance of {@link SplineCurve} to the path by connecting
   * the current point with the given list of points.
   *
   * @param {Array<Vector2>} pts - An array of points in 2D space.
   * @return {Path} A reference to this path.
   */
  splineThru(t) {
    const e = [this.currentPoint.clone()].concat(t), i = new Yp(e);
    return this.curves.push(i), this.currentPoint.copy(t[t.length - 1]), this;
  }
  /**
   * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
   * to the current point.
   *
   * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
   * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
   * @param {number} [aRadius=1] - The radius of the arc.
   * @param {number} [aStartAngle=0] - The start angle in radians.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
   * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
   * @return {Path} A reference to this path.
   */
  arc(t, e, i, n, s, r) {
    const o = this.currentPoint.x, l = this.currentPoint.y;
    return this.absarc(
      t + o,
      e + l,
      i,
      n,
      s,
      r
    ), this;
  }
  /**
   * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
   *
   * @param {number} [aX=0] - The x coordinate of the center of the arc.
   * @param {number} [aY=0] - The y coordinate of the center of the arc.
   * @param {number} [aRadius=1] - The radius of the arc.
   * @param {number} [aStartAngle=0] - The start angle in radians.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
   * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
   * @return {Path} A reference to this path.
   */
  absarc(t, e, i, n, s, r) {
    return this.absellipse(t, e, i, i, n, s, r), this;
  }
  /**
   * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
   * to the current point
   *
   * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
   * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
   * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
   * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
   * @param {number} [aStartAngle=0] - The start angle in radians.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
   * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
   * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
   * @return {Path} A reference to this path.
   */
  ellipse(t, e, i, n, s, r, o, l) {
    const h = this.currentPoint.x, c = this.currentPoint.y;
    return this.absellipse(t + h, e + c, i, n, s, r, o, l), this;
  }
  /**
   * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
   *
   * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
   * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
   * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
   * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
   * @param {number} [aStartAngle=0] - The start angle in radians.
   * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
   * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
   * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
   * @return {Path} A reference to this path.
   */
  absellipse(t, e, i, n, s, r, o, l) {
    const h = new Kc(t, e, i, n, s, r, o, l);
    if (this.curves.length > 0) {
      const u = h.getPoint(0);
      u.equals(this.currentPoint) || this.lineTo(u.x, u.y);
    }
    this.curves.push(h);
    const c = h.getPoint(1);
    return this.currentPoint.copy(c), this;
  }
  copy(t) {
    return super.copy(t), this.currentPoint.copy(t.currentPoint), this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.currentPoint = this.currentPoint.toArray(), t;
  }
  fromJSON(t) {
    return super.fromJSON(t), this.currentPoint.fromArray(t.currentPoint), this;
  }
}
class As extends xc {
  /**
   * Constructs a new shape.
   *
   * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
   */
  constructor(t) {
    super(t), this.uuid = Oi(), this.type = "Shape", this.holes = [];
  }
  /**
   * Returns an array representing each contour of the holes
   * as a list of 2D points.
   *
   * @param {number} divisions - The fineness of the result.
   * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
   */
  getPointsHoles(t) {
    const e = [];
    for (let i = 0, n = this.holes.length; i < n; i++)
      e[i] = this.holes[i].getPoints(t);
    return e;
  }
  // get points of shape and holes (keypoints based on segments parameter)
  /**
   * Returns an object that holds contour data for the shape and its holes as
   * arrays of 2D points.
   *
   * @param {number} divisions - The fineness of the result.
   * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
   */
  extractPoints(t) {
    return {
      shape: this.getPoints(t),
      holes: this.getPointsHoles(t)
    };
  }
  copy(t) {
    super.copy(t), this.holes = [];
    for (let e = 0, i = t.holes.length; e < i; e++) {
      const n = t.holes[e];
      this.holes.push(n.clone());
    }
    return this;
  }
  toJSON() {
    const t = super.toJSON();
    t.uuid = this.uuid, t.holes = [];
    for (let e = 0, i = this.holes.length; e < i; e++) {
      const n = this.holes[e];
      t.holes.push(n.toJSON());
    }
    return t;
  }
  fromJSON(t) {
    super.fromJSON(t), this.uuid = t.uuid, this.holes = [];
    for (let e = 0, i = t.holes.length; e < i; e++) {
      const n = t.holes[e];
      this.holes.push(new xc().fromJSON(n));
    }
    return this;
  }
}
function db(a, t, e = 2) {
  const i = t && t.length, n = i ? t[0] * e : a.length;
  let s = Hy(a, 0, n, e, !0);
  const r = [];
  if (!s || s.next === s.prev) return r;
  let o, l, h;
  if (i && (s = yb(a, t, s, e)), a.length > 80 * e) {
    o = 1 / 0, l = 1 / 0;
    let c = -1 / 0, u = -1 / 0;
    for (let d = e; d < n; d += e) {
      const p = a[d], f = a[d + 1];
      p < o && (o = p), f < l && (l = f), p > c && (c = p), f > u && (u = f);
    }
    h = Math.max(c - o, u - l), h = h !== 0 ? 32767 / h : 0;
  }
  return Io(s, r, e, o, l, h, 0), r;
}
function Hy(a, t, e, i, n) {
  let s;
  if (n === Cb(a, t, e, i) > 0)
    for (let r = t; r < e; r += i) s = fm(r / i | 0, a[r], a[r + 1], s);
  else
    for (let r = e - i; r >= t; r -= i) s = fm(r / i | 0, a[r], a[r + 1], s);
  return s && va(s, s.next) && (Do(s), s = s.next), s;
}
function fr(a, t) {
  if (!a) return a;
  t || (t = a);
  let e = a, i;
  do
    if (i = !1, !e.steiner && (va(e, e.next) || Se(e.prev, e, e.next) === 0)) {
      if (Do(e), e = t = e.prev, e === e.next) break;
      i = !0;
    } else
      e = e.next;
  while (i || e !== t);
  return t;
}
function Io(a, t, e, i, n, s, r) {
  if (!a) return;
  !r && s && Mb(a, i, n, s);
  let o = a;
  for (; a.prev !== a.next; ) {
    const l = a.prev, h = a.next;
    if (s ? fb(a, i, n, s) : pb(a)) {
      t.push(l.i, a.i, h.i), Do(a), a = h.next, o = h.next;
      continue;
    }
    if (a = h, a === o) {
      r ? r === 1 ? (a = mb(fr(a), t), Io(a, t, e, i, n, s, 2)) : r === 2 && gb(a, t, e, i, n, s) : Io(fr(a), t, e, i, n, s, 1);
      break;
    }
  }
}
function pb(a) {
  const t = a.prev, e = a, i = a.next;
  if (Se(t, e, i) >= 0) return !1;
  const n = t.x, s = e.x, r = i.x, o = t.y, l = e.y, h = i.y, c = Math.min(n, s, r), u = Math.min(o, l, h), d = Math.max(n, s, r), p = Math.max(o, l, h);
  let f = i.next;
  for (; f !== t; ) {
    if (f.x >= c && f.x <= d && f.y >= u && f.y <= p && so(n, o, s, l, r, h, f.x, f.y) && Se(f.prev, f, f.next) >= 0) return !1;
    f = f.next;
  }
  return !0;
}
function fb(a, t, e, i) {
  const n = a.prev, s = a, r = a.next;
  if (Se(n, s, r) >= 0) return !1;
  const o = n.x, l = s.x, h = r.x, c = n.y, u = s.y, d = r.y, p = Math.min(o, l, h), f = Math.min(c, u, d), y = Math.max(o, l, h), g = Math.max(c, u, d), m = ip(p, f, t, e, i), v = ip(y, g, t, e, i);
  let x = a.prevZ, _ = a.nextZ;
  for (; x && x.z >= m && _ && _.z <= v; ) {
    if (x.x >= p && x.x <= y && x.y >= f && x.y <= g && x !== n && x !== r && so(o, c, l, u, h, d, x.x, x.y) && Se(x.prev, x, x.next) >= 0 || (x = x.prevZ, _.x >= p && _.x <= y && _.y >= f && _.y <= g && _ !== n && _ !== r && so(o, c, l, u, h, d, _.x, _.y) && Se(_.prev, _, _.next) >= 0)) return !1;
    _ = _.nextZ;
  }
  for (; x && x.z >= m; ) {
    if (x.x >= p && x.x <= y && x.y >= f && x.y <= g && x !== n && x !== r && so(o, c, l, u, h, d, x.x, x.y) && Se(x.prev, x, x.next) >= 0) return !1;
    x = x.prevZ;
  }
  for (; _ && _.z <= v; ) {
    if (_.x >= p && _.x <= y && _.y >= f && _.y <= g && _ !== n && _ !== r && so(o, c, l, u, h, d, _.x, _.y) && Se(_.prev, _, _.next) >= 0) return !1;
    _ = _.nextZ;
  }
  return !0;
}
function mb(a, t) {
  let e = a;
  do {
    const i = e.prev, n = e.next.next;
    !va(i, n) && Wy(i, e, e.next, n) && Lo(i, n) && Lo(n, i) && (t.push(i.i, e.i, n.i), Do(e), Do(e.next), e = a = n), e = e.next;
  } while (e !== a);
  return fr(e);
}
function gb(a, t, e, i, n, s) {
  let r = a;
  do {
    let o = r.next.next;
    for (; o !== r.prev; ) {
      if (r.i !== o.i && Ab(r, o)) {
        let l = qy(r, o);
        r = fr(r, r.next), l = fr(l, l.next), Io(r, t, e, i, n, s, 0), Io(l, t, e, i, n, s, 0);
        return;
      }
      o = o.next;
    }
    r = r.next;
  } while (r !== a);
}
function yb(a, t, e, i) {
  const n = [];
  for (let s = 0, r = t.length; s < r; s++) {
    const o = t[s] * i, l = s < r - 1 ? t[s + 1] * i : a.length, h = Hy(a, o, l, i, !1);
    h === h.next && (h.steiner = !0), n.push(wb(h));
  }
  n.sort(_b);
  for (let s = 0; s < n.length; s++)
    e = xb(n[s], e);
  return e;
}
function _b(a, t) {
  let e = a.x - t.x;
  if (e === 0 && (e = a.y - t.y, e === 0)) {
    const i = (a.next.y - a.y) / (a.next.x - a.x), n = (t.next.y - t.y) / (t.next.x - t.x);
    e = i - n;
  }
  return e;
}
function xb(a, t) {
  const e = vb(a, t);
  if (!e)
    return t;
  const i = qy(e, a);
  return fr(i, i.next), fr(e, e.next);
}
function vb(a, t) {
  let e = t;
  const i = a.x, n = a.y;
  let s = -1 / 0, r;
  if (va(a, e)) return e;
  do {
    if (va(a, e.next)) return e.next;
    if (n <= e.y && n >= e.next.y && e.next.y !== e.y) {
      const u = e.x + (n - e.y) * (e.next.x - e.x) / (e.next.y - e.y);
      if (u <= i && u > s && (s = u, r = e.x < e.next.x ? e : e.next, u === i))
        return r;
    }
    e = e.next;
  } while (e !== t);
  if (!r) return null;
  const o = r, l = r.x, h = r.y;
  let c = 1 / 0;
  e = r;
  do {
    if (i >= e.x && e.x >= l && i !== e.x && Gy(n < h ? i : s, n, l, h, n < h ? s : i, n, e.x, e.y)) {
      const u = Math.abs(n - e.y) / (i - e.x);
      Lo(e, a) && (u < c || u === c && (e.x > r.x || e.x === r.x && bb(r, e))) && (r = e, c = u);
    }
    e = e.next;
  } while (e !== o);
  return r;
}
function bb(a, t) {
  return Se(a.prev, a, t.prev) < 0 && Se(t.next, a, a.next) < 0;
}
function Mb(a, t, e, i) {
  let n = a;
  do
    n.z === 0 && (n.z = ip(n.x, n.y, t, e, i)), n.prevZ = n.prev, n.nextZ = n.next, n = n.next;
  while (n !== a);
  n.prevZ.nextZ = null, n.prevZ = null, Sb(n);
}
function Sb(a) {
  let t, e = 1;
  do {
    let i = a, n;
    a = null;
    let s = null;
    for (t = 0; i; ) {
      t++;
      let r = i, o = 0;
      for (let h = 0; h < e && (o++, r = r.nextZ, !!r); h++)
        ;
      let l = e;
      for (; o > 0 || l > 0 && r; )
        o !== 0 && (l === 0 || !r || i.z <= r.z) ? (n = i, i = i.nextZ, o--) : (n = r, r = r.nextZ, l--), s ? s.nextZ = n : a = n, n.prevZ = s, s = n;
      i = r;
    }
    s.nextZ = null, e *= 2;
  } while (t > 1);
  return a;
}
function ip(a, t, e, i, n) {
  return a = (a - e) * n | 0, t = (t - i) * n | 0, a = (a | a << 8) & 16711935, a = (a | a << 4) & 252645135, a = (a | a << 2) & 858993459, a = (a | a << 1) & 1431655765, t = (t | t << 8) & 16711935, t = (t | t << 4) & 252645135, t = (t | t << 2) & 858993459, t = (t | t << 1) & 1431655765, a | t << 1;
}
function wb(a) {
  let t = a, e = a;
  do
    (t.x < e.x || t.x === e.x && t.y < e.y) && (e = t), t = t.next;
  while (t !== a);
  return e;
}
function Gy(a, t, e, i, n, s, r, o) {
  return (n - r) * (t - o) >= (a - r) * (s - o) && (a - r) * (i - o) >= (e - r) * (t - o) && (e - r) * (s - o) >= (n - r) * (i - o);
}
function so(a, t, e, i, n, s, r, o) {
  return !(a === r && t === o) && Gy(a, t, e, i, n, s, r, o);
}
function Ab(a, t) {
  return a.next.i !== t.i && a.prev.i !== t.i && !Eb(a, t) && // doesn't intersect other edges
  (Lo(a, t) && Lo(t, a) && Tb(a, t) && // locally visible
  (Se(a.prev, a, t.prev) || Se(a, t.prev, t)) || // does not create opposite-facing sectors
  va(a, t) && Se(a.prev, a, a.next) > 0 && Se(t.prev, t, t.next) > 0);
}
function Se(a, t, e) {
  return (t.y - a.y) * (e.x - t.x) - (t.x - a.x) * (e.y - t.y);
}
function va(a, t) {
  return a.x === t.x && a.y === t.y;
}
function Wy(a, t, e, i) {
  const n = Rl(Se(a, t, e)), s = Rl(Se(a, t, i)), r = Rl(Se(e, i, a)), o = Rl(Se(e, i, t));
  return !!(n !== s && r !== o || n === 0 && Cl(a, e, t) || s === 0 && Cl(a, i, t) || r === 0 && Cl(e, a, i) || o === 0 && Cl(e, t, i));
}
function Cl(a, t, e) {
  return t.x <= Math.max(a.x, e.x) && t.x >= Math.min(a.x, e.x) && t.y <= Math.max(a.y, e.y) && t.y >= Math.min(a.y, e.y);
}
function Rl(a) {
  return a > 0 ? 1 : a < 0 ? -1 : 0;
}
function Eb(a, t) {
  let e = a;
  do {
    if (e.i !== a.i && e.next.i !== a.i && e.i !== t.i && e.next.i !== t.i && Wy(e, e.next, a, t)) return !0;
    e = e.next;
  } while (e !== a);
  return !1;
}
function Lo(a, t) {
  return Se(a.prev, a, a.next) < 0 ? Se(a, t, a.next) >= 0 && Se(a, a.prev, t) >= 0 : Se(a, t, a.prev) < 0 || Se(a, a.next, t) < 0;
}
function Tb(a, t) {
  let e = a, i = !1;
  const n = (a.x + t.x) / 2, s = (a.y + t.y) / 2;
  do
    e.y > s != e.next.y > s && e.next.y !== e.y && n < (e.next.x - e.x) * (s - e.y) / (e.next.y - e.y) + e.x && (i = !i), e = e.next;
  while (e !== a);
  return i;
}
function qy(a, t) {
  const e = np(a.i, a.x, a.y), i = np(t.i, t.x, t.y), n = a.next, s = t.prev;
  return a.next = t, t.prev = a, e.next = n, n.prev = e, i.next = e, e.prev = i, s.next = i, i.prev = s, i;
}
function fm(a, t, e, i) {
  const n = np(a, t, e);
  return i ? (n.next = i.next, n.prev = i, i.next.prev = n, i.next = n) : (n.prev = n, n.next = n), n;
}
function Do(a) {
  a.next.prev = a.prev, a.prev.next = a.next, a.prevZ && (a.prevZ.nextZ = a.nextZ), a.nextZ && (a.nextZ.prevZ = a.prevZ);
}
function np(a, t, e) {
  return {
    i: a,
    // vertex index in coordinates array
    x: t,
    y: e,
    // vertex coordinates
    prev: null,
    // previous and next vertex nodes in a polygon ring
    next: null,
    z: 0,
    // z-order curve value
    prevZ: null,
    // previous and next nodes in z-order
    nextZ: null,
    steiner: !1
    // indicates whether this is a steiner point
  };
}
function Cb(a, t, e, i) {
  let n = 0;
  for (let s = t, r = e - i; s < e; s += i)
    n += (a[r] - a[s]) * (a[s + 1] + a[r + 1]), r = s;
  return n;
}
class Rb {
  /**
   * Triangulates the given shape definition by returning an array of triangles.
   *
   * @param {Array<number>} data - An array with 2D points.
   * @param {Array<number>} holeIndices - An array with indices defining holes.
   * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
   * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
   * representing vertex indices.
   */
  static triangulate(t, e, i = 2) {
    return db(t, e, i);
  }
}
class dn {
  /**
   * Calculate area of a ( 2D ) contour polygon.
   *
   * @param {Array<Vector2>} contour - An array of 2D points.
   * @return {number} The area.
   */
  static area(t) {
    const e = t.length;
    let i = 0;
    for (let n = e - 1, s = 0; s < e; n = s++)
      i += t[n].x * t[s].y - t[s].x * t[n].y;
    return i * 0.5;
  }
  /**
   * Returns `true` if the given contour uses a clockwise winding order.
   *
   * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
   * @return {boolean} Whether the given contour uses a clockwise winding order or not.
   */
  static isClockWise(t) {
    return dn.area(t) < 0;
  }
  /**
   * Triangulates the given shape definition.
   *
   * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
   * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
   * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
   */
  static triangulateShape(t, e) {
    const i = [], n = [], s = [];
    mm(t), gm(i, t);
    let r = t.length;
    e.forEach(mm);
    for (let l = 0; l < e.length; l++)
      n.push(r), r += e[l].length, gm(i, e[l]);
    const o = Rb.triangulate(i, n);
    for (let l = 0; l < o.length; l += 3)
      s.push(o.slice(l, l + 3));
    return s;
  }
}
function mm(a) {
  const t = a.length;
  t > 2 && a[t - 1].equals(a[0]) && a.pop();
}
function gm(a, t) {
  for (let e = 0; e < t.length; e++)
    a.push(t[e].x), a.push(t[e].y);
}
class Vo extends Ht {
  /**
   * Constructs a new extrude geometry.
   *
   * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
   * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
   */
  constructor(t = new As([new J(0.5, 0.5), new J(-0.5, 0.5), new J(-0.5, -0.5), new J(0.5, -0.5)]), e = {}) {
    super(), this.type = "ExtrudeGeometry", this.parameters = {
      shapes: t,
      options: e
    }, t = Array.isArray(t) ? t : [t];
    const i = this, n = [], s = [];
    for (let o = 0, l = t.length; o < l; o++) {
      const h = t[o];
      r(h);
    }
    this.setAttribute("position", new wt(n, 3)), this.setAttribute("uv", new wt(s, 2)), this.computeVertexNormals();
    function r(o) {
      const l = [], h = e.curveSegments !== void 0 ? e.curveSegments : 12, c = e.steps !== void 0 ? e.steps : 1, u = e.depth !== void 0 ? e.depth : 1;
      let d = e.bevelEnabled !== void 0 ? e.bevelEnabled : !0, p = e.bevelThickness !== void 0 ? e.bevelThickness : 0.2, f = e.bevelSize !== void 0 ? e.bevelSize : p - 0.1, y = e.bevelOffset !== void 0 ? e.bevelOffset : 0, g = e.bevelSegments !== void 0 ? e.bevelSegments : 3;
      const m = e.extrudePath, v = e.UVGenerator !== void 0 ? e.UVGenerator : Pb;
      let x, _ = !1, S, w, T, R;
      m && (x = m.getSpacedPoints(c), _ = !0, d = !1, S = m.computeFrenetFrames(c, !1), w = new E(), T = new E(), R = new E()), d || (g = 0, p = 0, f = 0, y = 0);
      const b = o.extractPoints(h);
      let M = b.shape;
      const L = b.holes;
      if (!dn.isClockWise(M)) {
        M = M.reverse();
        for (let ot = 0, it = L.length; ot < it; ot++) {
          const Q = L[ot];
          dn.isClockWise(Q) && (L[ot] = Q.reverse());
        }
      }
      function O(ot) {
        const Q = 10000000000000001e-36;
        let K = ot[0];
        for (let yt = 1; yt <= ot.length; yt++) {
          const ut = yt % ot.length, xt = ot[ut], Wt = xt.x - K.x, Nt = xt.y - K.y, P = Wt * Wt + Nt * Nt, A = Math.max(
            Math.abs(xt.x),
            Math.abs(xt.y),
            Math.abs(K.x),
            Math.abs(K.y)
          ), N = Q * A * A;
          if (P <= N) {
            ot.splice(ut, 1), yt--;
            continue;
          }
          K = xt;
        }
      }
      O(M), L.forEach(O);
      const V = L.length, W = M;
      for (let ot = 0; ot < V; ot++) {
        const it = L[ot];
        M = M.concat(it);
      }
      function G(ot, it, Q) {
        return it || console.error("THREE.ExtrudeGeometry: vec does not exist"), ot.clone().addScaledVector(it, Q);
      }
      const et = M.length;
      function H(ot, it, Q) {
        let K, yt, ut;
        const xt = ot.x - it.x, Wt = ot.y - it.y, Nt = Q.x - ot.x, P = Q.y - ot.y, A = xt * xt + Wt * Wt, N = xt * P - Wt * Nt;
        if (Math.abs(N) > Number.EPSILON) {
          const X = Math.sqrt(A), rt = Math.sqrt(Nt * Nt + P * P), Z = it.x - Wt / X, It = it.y + xt / X, I = Q.x - P / rt, lt = Q.y + Nt / rt, gt = ((I - Z) * P - (lt - It) * Nt) / (xt * P - Wt * Nt);
          K = Z + xt * gt - ot.x, yt = It + Wt * gt - ot.y;
          const j = K * K + yt * yt;
          if (j <= 2)
            return new J(K, yt);
          ut = Math.sqrt(j / 2);
        } else {
          let X = !1;
          xt > Number.EPSILON ? Nt > Number.EPSILON && (X = !0) : xt < -Number.EPSILON ? Nt < -Number.EPSILON && (X = !0) : Math.sign(Wt) === Math.sign(P) && (X = !0), X ? (K = -Wt, yt = xt, ut = Math.sqrt(A)) : (K = xt, yt = Wt, ut = Math.sqrt(A / 2));
        }
        return new J(K / ut, yt / ut);
      }
      const at = [];
      for (let ot = 0, it = W.length, Q = it - 1, K = ot + 1; ot < it; ot++, Q++, K++)
        Q === it && (Q = 0), K === it && (K = 0), at[ot] = H(W[ot], W[Q], W[K]);
      const pt = [];
      let Mt, Lt = at.concat();
      for (let ot = 0, it = V; ot < it; ot++) {
        const Q = L[ot];
        Mt = [];
        for (let K = 0, yt = Q.length, ut = yt - 1, xt = K + 1; K < yt; K++, ut++, xt++)
          ut === yt && (ut = 0), xt === yt && (xt = 0), Mt[K] = H(Q[K], Q[ut], Q[xt]);
        pt.push(Mt), Lt = Lt.concat(Mt);
      }
      let jt;
      if (g === 0)
        jt = dn.triangulateShape(W, L);
      else {
        const ot = [], it = [];
        for (let Q = 0; Q < g; Q++) {
          const K = Q / g, yt = p * Math.cos(K * Math.PI / 2), ut = f * Math.sin(K * Math.PI / 2) + y;
          for (let xt = 0, Wt = W.length; xt < Wt; xt++) {
            const Nt = G(W[xt], at[xt], ut);
            Ut(Nt.x, Nt.y, -yt), K === 0 && ot.push(Nt);
          }
          for (let xt = 0, Wt = V; xt < Wt; xt++) {
            const Nt = L[xt];
            Mt = pt[xt];
            const P = [];
            for (let A = 0, N = Nt.length; A < N; A++) {
              const X = G(Nt[A], Mt[A], ut);
              Ut(X.x, X.y, -yt), K === 0 && P.push(X);
            }
            K === 0 && it.push(P);
          }
        }
        jt = dn.triangulateShape(ot, it);
      }
      const ne = jt.length, Jt = f + y;
      for (let ot = 0; ot < et; ot++) {
        const it = d ? G(M[ot], Lt[ot], Jt) : M[ot];
        _ ? (T.copy(S.normals[0]).multiplyScalar(it.x), w.copy(S.binormals[0]).multiplyScalar(it.y), R.copy(x[0]).add(T).add(w), Ut(R.x, R.y, R.z)) : Ut(it.x, it.y, 0);
      }
      for (let ot = 1; ot <= c; ot++)
        for (let it = 0; it < et; it++) {
          const Q = d ? G(M[it], Lt[it], Jt) : M[it];
          _ ? (T.copy(S.normals[ot]).multiplyScalar(Q.x), w.copy(S.binormals[ot]).multiplyScalar(Q.y), R.copy(x[ot]).add(T).add(w), Ut(R.x, R.y, R.z)) : Ut(Q.x, Q.y, u / c * ot);
        }
      for (let ot = g - 1; ot >= 0; ot--) {
        const it = ot / g, Q = p * Math.cos(it * Math.PI / 2), K = f * Math.sin(it * Math.PI / 2) + y;
        for (let yt = 0, ut = W.length; yt < ut; yt++) {
          const xt = G(W[yt], at[yt], K);
          Ut(xt.x, xt.y, u + Q);
        }
        for (let yt = 0, ut = L.length; yt < ut; yt++) {
          const xt = L[yt];
          Mt = pt[yt];
          for (let Wt = 0, Nt = xt.length; Wt < Nt; Wt++) {
            const P = G(xt[Wt], Mt[Wt], K);
            _ ? Ut(P.x, P.y + x[c - 1].y, x[c - 1].x + Q) : Ut(P.x, P.y, u + Q);
          }
        }
      }
      Y(), st();
      function Y() {
        const ot = n.length / 3;
        if (d) {
          let it = 0, Q = et * it;
          for (let K = 0; K < ne; K++) {
            const yt = jt[K];
            Pt(yt[2] + Q, yt[1] + Q, yt[0] + Q);
          }
          it = c + g * 2, Q = et * it;
          for (let K = 0; K < ne; K++) {
            const yt = jt[K];
            Pt(yt[0] + Q, yt[1] + Q, yt[2] + Q);
          }
        } else {
          for (let it = 0; it < ne; it++) {
            const Q = jt[it];
            Pt(Q[2], Q[1], Q[0]);
          }
          for (let it = 0; it < ne; it++) {
            const Q = jt[it];
            Pt(Q[0] + et * c, Q[1] + et * c, Q[2] + et * c);
          }
        }
        i.addGroup(ot, n.length / 3 - ot, 0);
      }
      function st() {
        const ot = n.length / 3;
        let it = 0;
        Et(W, it), it += W.length;
        for (let Q = 0, K = L.length; Q < K; Q++) {
          const yt = L[Q];
          Et(yt, it), it += yt.length;
        }
        i.addGroup(ot, n.length / 3 - ot, 1);
      }
      function Et(ot, it) {
        let Q = ot.length;
        for (; --Q >= 0; ) {
          const K = Q;
          let yt = Q - 1;
          yt < 0 && (yt = ot.length - 1);
          for (let ut = 0, xt = c + g * 2; ut < xt; ut++) {
            const Wt = et * ut, Nt = et * (ut + 1), P = it + K + Wt, A = it + yt + Wt, N = it + yt + Nt, X = it + K + Nt;
            Kt(P, A, N, X);
          }
        }
      }
      function Ut(ot, it, Q) {
        l.push(ot), l.push(it), l.push(Q);
      }
      function Pt(ot, it, Q) {
        he(ot), he(it), he(Q);
        const K = n.length / 3, yt = v.generateTopUV(i, n, K - 3, K - 2, K - 1);
        D(yt[0]), D(yt[1]), D(yt[2]);
      }
      function Kt(ot, it, Q, K) {
        he(ot), he(it), he(K), he(it), he(Q), he(K);
        const yt = n.length / 3, ut = v.generateSideWallUV(i, n, yt - 6, yt - 3, yt - 2, yt - 1);
        D(ut[0]), D(ut[1]), D(ut[3]), D(ut[1]), D(ut[2]), D(ut[3]);
      }
      function he(ot) {
        n.push(l[ot * 3 + 0]), n.push(l[ot * 3 + 1]), n.push(l[ot * 3 + 2]);
      }
      function D(ot) {
        s.push(ot.x), s.push(ot.y);
      }
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  toJSON() {
    const t = super.toJSON(), e = this.parameters.shapes, i = this.parameters.options;
    return Ib(e, i, t);
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @param {Array<Shape>} shapes - An array of shapes.
   * @return {ExtrudeGeometry} A new instance.
   */
  static fromJSON(t, e) {
    const i = [];
    for (let s = 0, r = t.shapes.length; s < r; s++) {
      const o = e[t.shapes[s]];
      i.push(o);
    }
    const n = t.options.extrudePath;
    return n !== void 0 && (t.options.extrudePath = new _c[n.type]().fromJSON(n)), new Vo(i, t.options);
  }
}
const Pb = {
  generateTopUV: function(a, t, e, i, n) {
    const s = t[e * 3], r = t[e * 3 + 1], o = t[i * 3], l = t[i * 3 + 1], h = t[n * 3], c = t[n * 3 + 1];
    return [
      new J(s, r),
      new J(o, l),
      new J(h, c)
    ];
  },
  generateSideWallUV: function(a, t, e, i, n, s) {
    const r = t[e * 3], o = t[e * 3 + 1], l = t[e * 3 + 2], h = t[i * 3], c = t[i * 3 + 1], u = t[i * 3 + 2], d = t[n * 3], p = t[n * 3 + 1], f = t[n * 3 + 2], y = t[s * 3], g = t[s * 3 + 1], m = t[s * 3 + 2];
    return Math.abs(o - c) < Math.abs(r - h) ? [
      new J(r, 1 - l),
      new J(h, 1 - u),
      new J(d, 1 - f),
      new J(y, 1 - m)
    ] : [
      new J(o, 1 - l),
      new J(c, 1 - u),
      new J(p, 1 - f),
      new J(g, 1 - m)
    ];
  }
};
function Ib(a, t, e) {
  if (e.shapes = [], Array.isArray(a))
    for (let i = 0, n = a.length; i < n; i++) {
      const s = a[i];
      e.shapes.push(s.uuid);
    }
  else
    e.shapes.push(a.uuid);
  return e.options = Object.assign({}, t), t.extrudePath !== void 0 && (e.options.extrudePath = t.extrudePath.toJSON()), e;
}
class Qc extends Ls {
  /**
   * Constructs a new icosahedron geometry.
   *
   * @param {number} [radius=1] - Radius of the icosahedron.
   * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
   */
  constructor(t = 1, e = 0) {
    const i = (1 + Math.sqrt(5)) / 2, n = [
      -1,
      i,
      0,
      1,
      i,
      0,
      -1,
      -i,
      0,
      1,
      -i,
      0,
      0,
      -1,
      i,
      0,
      1,
      i,
      0,
      -1,
      -i,
      0,
      1,
      -i,
      i,
      0,
      -1,
      i,
      0,
      1,
      -i,
      0,
      -1,
      -i,
      0,
      1
    ], s = [
      0,
      11,
      5,
      0,
      5,
      1,
      0,
      1,
      7,
      0,
      7,
      10,
      0,
      10,
      11,
      1,
      5,
      9,
      5,
      11,
      4,
      11,
      10,
      2,
      10,
      7,
      6,
      7,
      1,
      8,
      3,
      9,
      4,
      3,
      4,
      2,
      3,
      2,
      6,
      3,
      6,
      8,
      3,
      8,
      9,
      4,
      9,
      5,
      2,
      4,
      11,
      6,
      2,
      10,
      8,
      6,
      7,
      9,
      8,
      1
    ];
    super(n, s, t, e), this.type = "IcosahedronGeometry", this.parameters = {
      radius: t,
      detail: e
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {IcosahedronGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Qc(t.radius, t.detail);
  }
}
class tu extends Ht {
  /**
   * Constructs a new lathe geometry.
   *
   * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
   * must be greater than zero.
   * @param {number} [segments=12] - The number of circumference segments to generate.
   * @param {number} [phiStart=0] - The starting angle in radians.
   * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
   * closed lathe, less than 2PI is a portion.
   */
  constructor(t = [new J(0, -0.5), new J(0.5, 0), new J(0, 0.5)], e = 12, i = 0, n = Math.PI * 2) {
    super(), this.type = "LatheGeometry", this.parameters = {
      points: t,
      segments: e,
      phiStart: i,
      phiLength: n
    }, e = Math.floor(e), n = kt(n, 0, Math.PI * 2);
    const s = [], r = [], o = [], l = [], h = [], c = 1 / e, u = new E(), d = new J(), p = new E(), f = new E(), y = new E();
    let g = 0, m = 0;
    for (let v = 0; v <= t.length - 1; v++)
      switch (v) {
        case 0:
          g = t[v + 1].x - t[v].x, m = t[v + 1].y - t[v].y, p.x = m * 1, p.y = -g, p.z = m * 0, y.copy(p), p.normalize(), l.push(p.x, p.y, p.z);
          break;
        case t.length - 1:
          l.push(y.x, y.y, y.z);
          break;
        default:
          g = t[v + 1].x - t[v].x, m = t[v + 1].y - t[v].y, p.x = m * 1, p.y = -g, p.z = m * 0, f.copy(p), p.x += y.x, p.y += y.y, p.z += y.z, p.normalize(), l.push(p.x, p.y, p.z), y.copy(f);
      }
    for (let v = 0; v <= e; v++) {
      const x = i + v * c * n, _ = Math.sin(x), S = Math.cos(x);
      for (let w = 0; w <= t.length - 1; w++) {
        u.x = t[w].x * _, u.y = t[w].y, u.z = t[w].x * S, r.push(u.x, u.y, u.z), d.x = v / e, d.y = w / (t.length - 1), o.push(d.x, d.y);
        const T = l[3 * w + 0] * _, R = l[3 * w + 1], b = l[3 * w + 0] * S;
        h.push(T, R, b);
      }
    }
    for (let v = 0; v < e; v++)
      for (let x = 0; x < t.length - 1; x++) {
        const _ = x + v * t.length, S = _, w = _ + t.length, T = _ + t.length + 1, R = _ + 1;
        s.push(S, w, R), s.push(T, R, w);
      }
    this.setIndex(s), this.setAttribute("position", new wt(r, 3)), this.setAttribute("uv", new wt(o, 2)), this.setAttribute("normal", new wt(h, 3));
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {LatheGeometry} A new instance.
   */
  static fromJSON(t) {
    return new tu(t.points, t.segments, t.phiStart, t.phiLength);
  }
}
class Ho extends Ls {
  /**
   * Constructs a new octahedron geometry.
   *
   * @param {number} [radius=1] - Radius of the octahedron.
   * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
   */
  constructor(t = 1, e = 0) {
    const i = [
      1,
      0,
      0,
      -1,
      0,
      0,
      0,
      1,
      0,
      0,
      -1,
      0,
      0,
      0,
      1,
      0,
      0,
      -1
    ], n = [
      0,
      2,
      4,
      0,
      4,
      3,
      0,
      3,
      5,
      0,
      5,
      2,
      1,
      2,
      5,
      1,
      5,
      3,
      1,
      3,
      4,
      1,
      4,
      2
    ];
    super(i, n, t, e), this.type = "OctahedronGeometry", this.parameters = {
      radius: t,
      detail: e
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {OctahedronGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Ho(t.radius, t.detail);
  }
}
class Ds extends Ht {
  /**
   * Constructs a new plane geometry.
   *
   * @param {number} [width=1] - The width along the X axis.
   * @param {number} [height=1] - The height along the Y axis
   * @param {number} [widthSegments=1] - The number of segments along the X axis.
   * @param {number} [heightSegments=1] - The number of segments along the Y axis.
   */
  constructor(t = 1, e = 1, i = 1, n = 1) {
    super(), this.type = "PlaneGeometry", this.parameters = {
      width: t,
      height: e,
      widthSegments: i,
      heightSegments: n
    };
    const s = t / 2, r = e / 2, o = Math.floor(i), l = Math.floor(n), h = o + 1, c = l + 1, u = t / o, d = e / l, p = [], f = [], y = [], g = [];
    for (let m = 0; m < c; m++) {
      const v = m * d - r;
      for (let x = 0; x < h; x++) {
        const _ = x * u - s;
        f.push(_, -v, 0), y.push(0, 0, 1), g.push(x / o), g.push(1 - m / l);
      }
    }
    for (let m = 0; m < l; m++)
      for (let v = 0; v < o; v++) {
        const x = v + h * m, _ = v + h * (m + 1), S = v + 1 + h * (m + 1), w = v + 1 + h * m;
        p.push(x, _, w), p.push(_, S, w);
      }
    this.setIndex(p), this.setAttribute("position", new wt(f, 3)), this.setAttribute("normal", new wt(y, 3)), this.setAttribute("uv", new wt(g, 2));
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {PlaneGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Ds(t.width, t.height, t.widthSegments, t.heightSegments);
  }
}
class eu extends Ht {
  /**
   * Constructs a new ring geometry.
   *
   * @param {number} [innerRadius=0.5] - The inner radius of the ring.
   * @param {number} [outerRadius=1] - The outer radius of the ring.
   * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
   * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
   * @param {number} [thetaStart=0] - Starting angle in radians.
   * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
   */
  constructor(t = 0.5, e = 1, i = 32, n = 1, s = 0, r = Math.PI * 2) {
    super(), this.type = "RingGeometry", this.parameters = {
      innerRadius: t,
      outerRadius: e,
      thetaSegments: i,
      phiSegments: n,
      thetaStart: s,
      thetaLength: r
    }, i = Math.max(3, i), n = Math.max(1, n);
    const o = [], l = [], h = [], c = [];
    let u = t;
    const d = (e - t) / n, p = new E(), f = new J();
    for (let y = 0; y <= n; y++) {
      for (let g = 0; g <= i; g++) {
        const m = s + g / i * r;
        p.x = u * Math.cos(m), p.y = u * Math.sin(m), l.push(p.x, p.y, p.z), h.push(0, 0, 1), f.x = (p.x / e + 1) / 2, f.y = (p.y / e + 1) / 2, c.push(f.x, f.y);
      }
      u += d;
    }
    for (let y = 0; y < n; y++) {
      const g = y * (i + 1);
      for (let m = 0; m < i; m++) {
        const v = m + g, x = v, _ = v + i + 1, S = v + i + 2, w = v + 1;
        o.push(x, _, w), o.push(_, S, w);
      }
    }
    this.setIndex(o), this.setAttribute("position", new wt(l, 3)), this.setAttribute("normal", new wt(h, 3)), this.setAttribute("uv", new wt(c, 2));
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {RingGeometry} A new instance.
   */
  static fromJSON(t) {
    return new eu(t.innerRadius, t.outerRadius, t.thetaSegments, t.phiSegments, t.thetaStart, t.thetaLength);
  }
}
class Go extends Ht {
  /**
   * Constructs a new shape geometry.
   *
   * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
   * @param {number} [curveSegments=12] - Number of segments per shape.
   */
  constructor(t = new As([new J(0, 0.5), new J(-0.5, -0.5), new J(0.5, -0.5)]), e = 12) {
    super(), this.type = "ShapeGeometry", this.parameters = {
      shapes: t,
      curveSegments: e
    };
    const i = [], n = [], s = [], r = [];
    let o = 0, l = 0;
    if (Array.isArray(t) === !1)
      h(t);
    else
      for (let c = 0; c < t.length; c++)
        h(t[c]), this.addGroup(o, l, c), o += l, l = 0;
    this.setIndex(i), this.setAttribute("position", new wt(n, 3)), this.setAttribute("normal", new wt(s, 3)), this.setAttribute("uv", new wt(r, 2));
    function h(c) {
      const u = n.length / 3, d = c.extractPoints(e);
      let p = d.shape;
      const f = d.holes;
      dn.isClockWise(p) === !1 && (p = p.reverse());
      for (let g = 0, m = f.length; g < m; g++) {
        const v = f[g];
        dn.isClockWise(v) === !0 && (f[g] = v.reverse());
      }
      const y = dn.triangulateShape(p, f);
      for (let g = 0, m = f.length; g < m; g++) {
        const v = f[g];
        p = p.concat(v);
      }
      for (let g = 0, m = p.length; g < m; g++) {
        const v = p[g];
        n.push(v.x, v.y, 0), s.push(0, 0, 1), r.push(v.x, v.y);
      }
      for (let g = 0, m = y.length; g < m; g++) {
        const v = y[g], x = v[0] + u, _ = v[1] + u, S = v[2] + u;
        i.push(x, _, S), l += 3;
      }
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  toJSON() {
    const t = super.toJSON(), e = this.parameters.shapes;
    return Lb(e, t);
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @param {Array<Shape>} shapes - An array of shapes.
   * @return {ShapeGeometry} A new instance.
   */
  static fromJSON(t, e) {
    const i = [];
    for (let n = 0, s = t.shapes.length; n < s; n++) {
      const r = e[t.shapes[n]];
      i.push(r);
    }
    return new Go(i, t.curveSegments);
  }
}
function Lb(a, t) {
  if (t.shapes = [], Array.isArray(a))
    for (let e = 0, i = a.length; e < i; e++) {
      const n = a[e];
      t.shapes.push(n.uuid);
    }
  else
    t.shapes.push(a.uuid);
  return t;
}
class Ra extends Ht {
  /**
   * Constructs a new sphere geometry.
   *
   * @param {number} [radius=1] - The sphere radius.
   * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
   * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
   * @param {number} [phiStart=0] - The horizontal starting angle in radians.
   * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
   * @param {number} [thetaStart=0] - The vertical starting angle in radians.
   * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
   */
  constructor(t = 1, e = 32, i = 16, n = 0, s = Math.PI * 2, r = 0, o = Math.PI) {
    super(), this.type = "SphereGeometry", this.parameters = {
      radius: t,
      widthSegments: e,
      heightSegments: i,
      phiStart: n,
      phiLength: s,
      thetaStart: r,
      thetaLength: o
    }, e = Math.max(3, Math.floor(e)), i = Math.max(2, Math.floor(i));
    const l = Math.min(r + o, Math.PI);
    let h = 0;
    const c = [], u = new E(), d = new E(), p = [], f = [], y = [], g = [];
    for (let m = 0; m <= i; m++) {
      const v = [], x = m / i;
      let _ = 0;
      m === 0 && r === 0 ? _ = 0.5 / e : m === i && l === Math.PI && (_ = -0.5 / e);
      for (let S = 0; S <= e; S++) {
        const w = S / e;
        u.x = -t * Math.cos(n + w * s) * Math.sin(r + x * o), u.y = t * Math.cos(r + x * o), u.z = t * Math.sin(n + w * s) * Math.sin(r + x * o), f.push(u.x, u.y, u.z), d.copy(u).normalize(), y.push(d.x, d.y, d.z), g.push(w + _, 1 - x), v.push(h++);
      }
      c.push(v);
    }
    for (let m = 0; m < i; m++)
      for (let v = 0; v < e; v++) {
        const x = c[m][v + 1], _ = c[m][v], S = c[m + 1][v], w = c[m + 1][v + 1];
        (m !== 0 || r > 0) && p.push(x, _, w), (m !== i - 1 || l < Math.PI) && p.push(_, S, w);
      }
    this.setIndex(p), this.setAttribute("position", new wt(f, 3)), this.setAttribute("normal", new wt(y, 3)), this.setAttribute("uv", new wt(g, 2));
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {SphereGeometry} A new instance.
   */
  static fromJSON(t) {
    return new Ra(t.radius, t.widthSegments, t.heightSegments, t.phiStart, t.phiLength, t.thetaStart, t.thetaLength);
  }
}
class iu extends Ls {
  /**
   * Constructs a new tetrahedron geometry.
   *
   * @param {number} [radius=1] - Radius of the tetrahedron.
   * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
   */
  constructor(t = 1, e = 0) {
    const i = [
      1,
      1,
      1,
      -1,
      -1,
      1,
      -1,
      1,
      -1,
      1,
      -1,
      -1
    ], n = [
      2,
      1,
      0,
      0,
      3,
      2,
      1,
      3,
      0,
      2,
      3,
      1
    ];
    super(i, n, t, e), this.type = "TetrahedronGeometry", this.parameters = {
      radius: t,
      detail: e
    };
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {TetrahedronGeometry} A new instance.
   */
  static fromJSON(t) {
    return new iu(t.radius, t.detail);
  }
}
class nu extends Ht {
  /**
   * Constructs a new torus geometry.
   *
   * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
   * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
   * @param {number} [radialSegments=12] - The number of radial segments.
   * @param {number} [tubularSegments=48] - The number of tubular segments.
   * @param {number} [arc=Math.PI*2] - Central angle in radians.
   */
  constructor(t = 1, e = 0.4, i = 12, n = 48, s = Math.PI * 2) {
    super(), this.type = "TorusGeometry", this.parameters = {
      radius: t,
      tube: e,
      radialSegments: i,
      tubularSegments: n,
      arc: s
    }, i = Math.floor(i), n = Math.floor(n);
    const r = [], o = [], l = [], h = [], c = new E(), u = new E(), d = new E();
    for (let p = 0; p <= i; p++)
      for (let f = 0; f <= n; f++) {
        const y = f / n * s, g = p / i * Math.PI * 2;
        u.x = (t + e * Math.cos(g)) * Math.cos(y), u.y = (t + e * Math.cos(g)) * Math.sin(y), u.z = e * Math.sin(g), o.push(u.x, u.y, u.z), c.x = t * Math.cos(y), c.y = t * Math.sin(y), d.subVectors(u, c).normalize(), l.push(d.x, d.y, d.z), h.push(f / n), h.push(p / i);
      }
    for (let p = 1; p <= i; p++)
      for (let f = 1; f <= n; f++) {
        const y = (n + 1) * p + f - 1, g = (n + 1) * (p - 1) + f - 1, m = (n + 1) * (p - 1) + f, v = (n + 1) * p + f;
        r.push(y, g, v), r.push(g, m, v);
      }
    this.setIndex(r), this.setAttribute("position", new wt(o, 3)), this.setAttribute("normal", new wt(l, 3)), this.setAttribute("uv", new wt(h, 2));
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {TorusGeometry} A new instance.
   */
  static fromJSON(t) {
    return new nu(t.radius, t.tube, t.radialSegments, t.tubularSegments, t.arc);
  }
}
class su extends Ht {
  /**
   * Constructs a new torus knot geometry.
   *
   * @param {number} [radius=1] - Radius of the torus knot.
   * @param {number} [tube=0.4] - Radius of the tube.
   * @param {number} [tubularSegments=64] - The number of tubular segments.
   * @param {number} [radialSegments=8] - The number of radial segments.
   * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
   * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
   */
  constructor(t = 1, e = 0.4, i = 64, n = 8, s = 2, r = 3) {
    super(), this.type = "TorusKnotGeometry", this.parameters = {
      radius: t,
      tube: e,
      tubularSegments: i,
      radialSegments: n,
      p: s,
      q: r
    }, i = Math.floor(i), n = Math.floor(n);
    const o = [], l = [], h = [], c = [], u = new E(), d = new E(), p = new E(), f = new E(), y = new E(), g = new E(), m = new E();
    for (let x = 0; x <= i; ++x) {
      const _ = x / i * s * Math.PI * 2;
      v(_, s, r, t, p), v(_ + 0.01, s, r, t, f), g.subVectors(f, p), m.addVectors(f, p), y.crossVectors(g, m), m.crossVectors(y, g), y.normalize(), m.normalize();
      for (let S = 0; S <= n; ++S) {
        const w = S / n * Math.PI * 2, T = -e * Math.cos(w), R = e * Math.sin(w);
        u.x = p.x + (T * m.x + R * y.x), u.y = p.y + (T * m.y + R * y.y), u.z = p.z + (T * m.z + R * y.z), l.push(u.x, u.y, u.z), d.subVectors(u, p).normalize(), h.push(d.x, d.y, d.z), c.push(x / i), c.push(S / n);
      }
    }
    for (let x = 1; x <= i; x++)
      for (let _ = 1; _ <= n; _++) {
        const S = (n + 1) * (x - 1) + (_ - 1), w = (n + 1) * x + (_ - 1), T = (n + 1) * x + _, R = (n + 1) * (x - 1) + _;
        o.push(S, w, R), o.push(w, T, R);
      }
    this.setIndex(o), this.setAttribute("position", new wt(l, 3)), this.setAttribute("normal", new wt(h, 3)), this.setAttribute("uv", new wt(c, 2));
    function v(x, _, S, w, T) {
      const R = Math.cos(x), b = Math.sin(x), M = S / _ * x, L = Math.cos(M);
      T.x = w * (2 + L) * 0.5 * R, T.y = w * (2 + L) * b * 0.5, T.z = w * Math.sin(M) * 0.5;
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {TorusKnotGeometry} A new instance.
   */
  static fromJSON(t) {
    return new su(t.radius, t.tube, t.tubularSegments, t.radialSegments, t.p, t.q);
  }
}
class ru extends Ht {
  /**
   * Constructs a new tube geometry.
   *
   * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
   * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
   * @param {number} [radius=1] -The radius of the tube.
   * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
   * @param {boolean} [closed=false] - Whether the tube is closed or not.
   */
  constructor(t = new Xp(new E(-1, -1, 0), new E(-1, 1, 0), new E(1, 1, 0)), e = 64, i = 1, n = 8, s = !1) {
    super(), this.type = "TubeGeometry", this.parameters = {
      path: t,
      tubularSegments: e,
      radius: i,
      radialSegments: n,
      closed: s
    };
    const r = t.computeFrenetFrames(e, s);
    this.tangents = r.tangents, this.normals = r.normals, this.binormals = r.binormals;
    const o = new E(), l = new E(), h = new J();
    let c = new E();
    const u = [], d = [], p = [], f = [];
    y(), this.setIndex(f), this.setAttribute("position", new wt(u, 3)), this.setAttribute("normal", new wt(d, 3)), this.setAttribute("uv", new wt(p, 2));
    function y() {
      for (let x = 0; x < e; x++)
        g(x);
      g(s === !1 ? e : 0), v(), m();
    }
    function g(x) {
      c = t.getPointAt(x / e, c);
      const _ = r.normals[x], S = r.binormals[x];
      for (let w = 0; w <= n; w++) {
        const T = w / n * Math.PI * 2, R = Math.sin(T), b = -Math.cos(T);
        l.x = b * _.x + R * S.x, l.y = b * _.y + R * S.y, l.z = b * _.z + R * S.z, l.normalize(), d.push(l.x, l.y, l.z), o.x = c.x + i * l.x, o.y = c.y + i * l.y, o.z = c.z + i * l.z, u.push(o.x, o.y, o.z);
      }
    }
    function m() {
      for (let x = 1; x <= e; x++)
        for (let _ = 1; _ <= n; _++) {
          const S = (n + 1) * (x - 1) + (_ - 1), w = (n + 1) * x + (_ - 1), T = (n + 1) * x + _, R = (n + 1) * (x - 1) + _;
          f.push(S, w, R), f.push(w, T, R);
        }
    }
    function v() {
      for (let x = 0; x <= e; x++)
        for (let _ = 0; _ <= n; _++)
          h.x = x / e, h.y = _ / n, p.push(h.x, h.y);
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.path = this.parameters.path.toJSON(), t;
  }
  /**
   * Factory method for creating an instance of this class from the given
   * JSON object.
   *
   * @param {Object} data - A JSON object representing the serialized geometry.
   * @return {TubeGeometry} A new instance.
   */
  static fromJSON(t) {
    return new ru(
      new _c[t.path.type]().fromJSON(t.path),
      t.tubularSegments,
      t.radius,
      t.radialSegments,
      t.closed
    );
  }
}
let Zp = class extends Ht {
  /**
   * Constructs a new wireframe geometry.
   *
   * @param {?BufferGeometry} [geometry=null] - The geometry.
   */
  constructor(t = null) {
    if (super(), this.type = "WireframeGeometry", this.parameters = {
      geometry: t
    }, t !== null) {
      const e = [], i = /* @__PURE__ */ new Set(), n = new E(), s = new E();
      if (t.index !== null) {
        const r = t.attributes.position, o = t.index;
        let l = t.groups;
        l.length === 0 && (l = [{ start: 0, count: o.count, materialIndex: 0 }]);
        for (let h = 0, c = l.length; h < c; ++h) {
          const u = l[h], d = u.start, p = u.count;
          for (let f = d, y = d + p; f < y; f += 3)
            for (let g = 0; g < 3; g++) {
              const m = o.getX(f + g), v = o.getX(f + (g + 1) % 3);
              n.fromBufferAttribute(r, m), s.fromBufferAttribute(r, v), ym(n, s, i) === !0 && (e.push(n.x, n.y, n.z), e.push(s.x, s.y, s.z));
            }
        }
      } else {
        const r = t.attributes.position;
        for (let o = 0, l = r.count / 3; o < l; o++)
          for (let h = 0; h < 3; h++) {
            const c = 3 * o + h, u = 3 * o + (h + 1) % 3;
            n.fromBufferAttribute(r, c), s.fromBufferAttribute(r, u), ym(n, s, i) === !0 && (e.push(n.x, n.y, n.z), e.push(s.x, s.y, s.z));
          }
      }
      this.setAttribute("position", new wt(e, 3));
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
};
function ym(a, t, e) {
  const i = `${a.x},${a.y},${a.z}-${t.x},${t.y},${t.z}`, n = `${t.x},${t.y},${t.z}-${a.x},${a.y},${a.z}`;
  return e.has(i) === !0 || e.has(n) === !0 ? !1 : (e.add(i), e.add(n), !0);
}
var _m = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  BoxGeometry: mr,
  CapsuleGeometry: Zc,
  CircleGeometry: jc,
  ConeGeometry: Ca,
  CylinderGeometry: Ta,
  DodecahedronGeometry: Jc,
  EdgesGeometry: By,
  ExtrudeGeometry: Vo,
  IcosahedronGeometry: Qc,
  LatheGeometry: tu,
  OctahedronGeometry: Ho,
  PlaneGeometry: Ds,
  PolyhedronGeometry: Ls,
  RingGeometry: eu,
  ShapeGeometry: Go,
  SphereGeometry: Ra,
  TetrahedronGeometry: iu,
  TorusGeometry: nu,
  TorusKnotGeometry: su,
  TubeGeometry: ru,
  WireframeGeometry: Zp
});
class $y extends hi {
  /**
   * Constructs a new shadow material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isShadowMaterial = !0, this.type = "ShadowMaterial", this.color = new ct(0), this.transparent = !0, this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.fog = t.fog, this;
  }
}
class Xy extends Xi {
  /**
   * Constructs a new raw shader material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(t), this.isRawShaderMaterial = !0, this.type = "RawShaderMaterial";
  }
}
let hr = class extends hi {
  /**
   * Constructs a new mesh standard material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshStandardMaterial = !0, this.type = "MeshStandardMaterial", this.defines = { STANDARD: "" }, this.color = new ct(16777215), this.roughness = 1, this.metalness = 0, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new ct(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Is, this.normalScale = new J(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.roughnessMap = null, this.metalnessMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new fn(), this.envMapIntensity = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.defines = { STANDARD: "" }, this.color.copy(t.color), this.roughness = t.roughness, this.metalness = t.metalness, this.map = t.map, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.emissive.copy(t.emissive), this.emissiveMap = t.emissiveMap, this.emissiveIntensity = t.emissiveIntensity, this.bumpMap = t.bumpMap, this.bumpScale = t.bumpScale, this.normalMap = t.normalMap, this.normalMapType = t.normalMapType, this.normalScale.copy(t.normalScale), this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.roughnessMap = t.roughnessMap, this.metalnessMap = t.metalnessMap, this.alphaMap = t.alphaMap, this.envMap = t.envMap, this.envMapRotation.copy(t.envMapRotation), this.envMapIntensity = t.envMapIntensity, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.flatShading = t.flatShading, this.fog = t.fog, this;
  }
};
class Yy extends hr {
  /**
   * Constructs a new mesh physical material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshPhysicalMaterial = !0, this.defines = {
      STANDARD: "",
      PHYSICAL: ""
    }, this.type = "MeshPhysicalMaterial", this.anisotropyRotation = 0, this.anisotropyMap = null, this.clearcoatMap = null, this.clearcoatRoughness = 0, this.clearcoatRoughnessMap = null, this.clearcoatNormalScale = new J(1, 1), this.clearcoatNormalMap = null, this.ior = 1.5, Object.defineProperty(this, "reflectivity", {
      get: function() {
        return kt(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
      },
      set: function(e) {
        this.ior = (1 + 0.4 * e) / (1 - 0.4 * e);
      }
    }), this.iridescenceMap = null, this.iridescenceIOR = 1.3, this.iridescenceThicknessRange = [100, 400], this.iridescenceThicknessMap = null, this.sheenColor = new ct(0), this.sheenColorMap = null, this.sheenRoughness = 1, this.sheenRoughnessMap = null, this.transmissionMap = null, this.thickness = 0, this.thicknessMap = null, this.attenuationDistance = 1 / 0, this.attenuationColor = new ct(1, 1, 1), this.specularIntensity = 1, this.specularIntensityMap = null, this.specularColor = new ct(1, 1, 1), this.specularColorMap = null, this._anisotropy = 0, this._clearcoat = 0, this._dispersion = 0, this._iridescence = 0, this._sheen = 0, this._transmission = 0, this.setValues(t);
  }
  /**
   * The anisotropy strength.
   *
   * @type {number}
   * @default 0
   */
  get anisotropy() {
    return this._anisotropy;
  }
  set anisotropy(t) {
    this._anisotropy > 0 != t > 0 && this.version++, this._anisotropy = t;
  }
  /**
   * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
   * clear coat related properties to enable multilayer materials that have a
   * thin translucent layer over the base layer.
   *
   * @type {number}
   * @default 0
   */
  get clearcoat() {
    return this._clearcoat;
  }
  set clearcoat(t) {
    this._clearcoat > 0 != t > 0 && this.version++, this._clearcoat = t;
  }
  /**
   * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
   * the surface and the viewer, from `0.0` to `1.0`.
   *
   * @type {number}
   * @default 0
   */
  get iridescence() {
    return this._iridescence;
  }
  set iridescence(t) {
    this._iridescence > 0 != t > 0 && this.version++, this._iridescence = t;
  }
  /**
   * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
   * through a relatively clear volume. Any value zero or larger is valid, the typical range of
   * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
   *
   * @type {number}
   * @default 0
   */
  get dispersion() {
    return this._dispersion;
  }
  set dispersion(t) {
    this._dispersion > 0 != t > 0 && this.version++, this._dispersion = t;
  }
  /**
   * The intensity of the sheen layer, from `0.0` to `1.0`.
   *
   * @type {number}
   * @default 0
   */
  get sheen() {
    return this._sheen;
  }
  set sheen(t) {
    this._sheen > 0 != t > 0 && this.version++, this._sheen = t;
  }
  /**
   * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
   *
   * Thin, transparent or semitransparent, plastic or glass materials remain
   * largely reflective even if they are fully transmissive. The transmission
   * property can be used to model these materials.
   *
   * When transmission is non-zero, `opacity` should be  set to `1`.
   *
   * @type {number}
   * @default 0
   */
  get transmission() {
    return this._transmission;
  }
  set transmission(t) {
    this._transmission > 0 != t > 0 && this.version++, this._transmission = t;
  }
  copy(t) {
    return super.copy(t), this.defines = {
      STANDARD: "",
      PHYSICAL: ""
    }, this.anisotropy = t.anisotropy, this.anisotropyRotation = t.anisotropyRotation, this.anisotropyMap = t.anisotropyMap, this.clearcoat = t.clearcoat, this.clearcoatMap = t.clearcoatMap, this.clearcoatRoughness = t.clearcoatRoughness, this.clearcoatRoughnessMap = t.clearcoatRoughnessMap, this.clearcoatNormalMap = t.clearcoatNormalMap, this.clearcoatNormalScale.copy(t.clearcoatNormalScale), this.dispersion = t.dispersion, this.ior = t.ior, this.iridescence = t.iridescence, this.iridescenceMap = t.iridescenceMap, this.iridescenceIOR = t.iridescenceIOR, this.iridescenceThicknessRange = [...t.iridescenceThicknessRange], this.iridescenceThicknessMap = t.iridescenceThicknessMap, this.sheen = t.sheen, this.sheenColor.copy(t.sheenColor), this.sheenColorMap = t.sheenColorMap, this.sheenRoughness = t.sheenRoughness, this.sheenRoughnessMap = t.sheenRoughnessMap, this.transmission = t.transmission, this.transmissionMap = t.transmissionMap, this.thickness = t.thickness, this.thicknessMap = t.thicknessMap, this.attenuationDistance = t.attenuationDistance, this.attenuationColor.copy(t.attenuationColor), this.specularIntensity = t.specularIntensity, this.specularIntensityMap = t.specularIntensityMap, this.specularColor.copy(t.specularColor), this.specularColorMap = t.specularColorMap, this;
  }
}
class Zy extends hi {
  /**
   * Constructs a new mesh phong material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshPhongMaterial = !0, this.type = "MeshPhongMaterial", this.color = new ct(16777215), this.specular = new ct(1118481), this.shininess = 30, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new ct(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Is, this.normalScale = new J(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new fn(), this.combine = zo, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.specular.copy(t.specular), this.shininess = t.shininess, this.map = t.map, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.emissive.copy(t.emissive), this.emissiveMap = t.emissiveMap, this.emissiveIntensity = t.emissiveIntensity, this.bumpMap = t.bumpMap, this.bumpScale = t.bumpScale, this.normalMap = t.normalMap, this.normalMapType = t.normalMapType, this.normalScale.copy(t.normalScale), this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.specularMap = t.specularMap, this.alphaMap = t.alphaMap, this.envMap = t.envMap, this.envMapRotation.copy(t.envMapRotation), this.combine = t.combine, this.reflectivity = t.reflectivity, this.refractionRatio = t.refractionRatio, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.flatShading = t.flatShading, this.fog = t.fog, this;
  }
}
class jy extends hi {
  /**
   * Constructs a new mesh toon material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshToonMaterial = !0, this.defines = { TOON: "" }, this.type = "MeshToonMaterial", this.color = new ct(16777215), this.map = null, this.gradientMap = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new ct(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Is, this.normalScale = new J(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.alphaMap = null, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.map = t.map, this.gradientMap = t.gradientMap, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.emissive.copy(t.emissive), this.emissiveMap = t.emissiveMap, this.emissiveIntensity = t.emissiveIntensity, this.bumpMap = t.bumpMap, this.bumpScale = t.bumpScale, this.normalMap = t.normalMap, this.normalMapType = t.normalMapType, this.normalScale.copy(t.normalScale), this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.alphaMap = t.alphaMap, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.fog = t.fog, this;
  }
}
class Jy extends hi {
  /**
   * Constructs a new mesh normal material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshNormalMaterial = !0, this.type = "MeshNormalMaterial", this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Is, this.normalScale = new J(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.flatShading = !1, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.bumpMap = t.bumpMap, this.bumpScale = t.bumpScale, this.normalMap = t.normalMap, this.normalMapType = t.normalMapType, this.normalScale.copy(t.normalScale), this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.flatShading = t.flatShading, this;
  }
}
class Ky extends hi {
  /**
   * Constructs a new mesh lambert material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshLambertMaterial = !0, this.type = "MeshLambertMaterial", this.color = new ct(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new ct(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Is, this.normalScale = new J(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new fn(), this.combine = zo, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.map = t.map, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.emissive.copy(t.emissive), this.emissiveMap = t.emissiveMap, this.emissiveIntensity = t.emissiveIntensity, this.bumpMap = t.bumpMap, this.bumpScale = t.bumpScale, this.normalMap = t.normalMap, this.normalMapType = t.normalMapType, this.normalScale.copy(t.normalScale), this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.specularMap = t.specularMap, this.alphaMap = t.alphaMap, this.envMap = t.envMap, this.envMapRotation.copy(t.envMapRotation), this.combine = t.combine, this.reflectivity = t.reflectivity, this.refractionRatio = t.refractionRatio, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.flatShading = t.flatShading, this.fog = t.fog, this;
  }
}
class jp extends hi {
  /**
   * Constructs a new mesh depth material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshDepthMaterial = !0, this.type = "MeshDepthMaterial", this.depthPacking = iy, this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.depthPacking = t.depthPacking, this.map = t.map, this.alphaMap = t.alphaMap, this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this;
  }
}
class Jp extends hi {
  /**
   * Constructs a new mesh distance material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshDistanceMaterial = !0, this.type = "MeshDistanceMaterial", this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.map = t.map, this.alphaMap = t.alphaMap, this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this;
  }
}
class Qy extends hi {
  /**
   * Constructs a new mesh matcap material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isMeshMatcapMaterial = !0, this.defines = { MATCAP: "" }, this.type = "MeshMatcapMaterial", this.color = new ct(16777215), this.matcap = null, this.map = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Is, this.normalScale = new J(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.alphaMap = null, this.flatShading = !1, this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.defines = { MATCAP: "" }, this.color.copy(t.color), this.matcap = t.matcap, this.map = t.map, this.bumpMap = t.bumpMap, this.bumpScale = t.bumpScale, this.normalMap = t.normalMap, this.normalMapType = t.normalMapType, this.normalScale.copy(t.normalScale), this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.alphaMap = t.alphaMap, this.flatShading = t.flatShading, this.fog = t.fog, this;
  }
}
class Kp extends Pe {
  /**
   * Constructs a new line dashed material.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super(), this.isLineDashedMaterial = !0, this.type = "LineDashedMaterial", this.scale = 1, this.dashSize = 3, this.gapSize = 1, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.scale = t.scale, this.dashSize = t.dashSize, this.gapSize = t.gapSize, this;
  }
}
function ar(a, t) {
  return !a || a.constructor === t ? a : typeof t.BYTES_PER_ELEMENT == "number" ? new t(a) : Array.prototype.slice.call(a);
}
function t_(a) {
  return ArrayBuffer.isView(a) && !(a instanceof DataView);
}
function e_(a) {
  function t(n, s) {
    return a[n] - a[s];
  }
  const e = a.length, i = new Array(e);
  for (let n = 0; n !== e; ++n) i[n] = n;
  return i.sort(t), i;
}
function sp(a, t, e) {
  const i = a.length, n = new a.constructor(i);
  for (let s = 0, r = 0; r !== i; ++s) {
    const o = e[s] * t;
    for (let l = 0; l !== t; ++l)
      n[r++] = a[o + l];
  }
  return n;
}
function Qp(a, t, e, i) {
  let n = 1, s = a[0];
  for (; s !== void 0 && s[i] === void 0; )
    s = a[n++];
  if (s === void 0) return;
  let r = s[i];
  if (r !== void 0)
    if (Array.isArray(r))
      do
        r = s[i], r !== void 0 && (t.push(s.time), e.push(...r)), s = a[n++];
      while (s !== void 0);
    else if (r.toArray !== void 0)
      do
        r = s[i], r !== void 0 && (t.push(s.time), r.toArray(e, e.length)), s = a[n++];
      while (s !== void 0);
    else
      do
        r = s[i], r !== void 0 && (t.push(s.time), e.push(r)), s = a[n++];
      while (s !== void 0);
}
function Db(a, t, e, i, n = 30) {
  const s = a.clone();
  s.name = t;
  const r = [];
  for (let l = 0; l < s.tracks.length; ++l) {
    const h = s.tracks[l], c = h.getValueSize(), u = [], d = [];
    for (let p = 0; p < h.times.length; ++p) {
      const f = h.times[p] * n;
      if (!(f < e || f >= i)) {
        u.push(h.times[p]);
        for (let y = 0; y < c; ++y)
          d.push(h.values[p * c + y]);
      }
    }
    u.length !== 0 && (h.times = ar(u, h.times.constructor), h.values = ar(d, h.values.constructor), r.push(h));
  }
  s.tracks = r;
  let o = 1 / 0;
  for (let l = 0; l < s.tracks.length; ++l)
    o > s.tracks[l].times[0] && (o = s.tracks[l].times[0]);
  for (let l = 0; l < s.tracks.length; ++l)
    s.tracks[l].shift(-1 * o);
  return s.resetDuration(), s;
}
function Fb(a, t = 0, e = a, i = 30) {
  i <= 0 && (i = 30);
  const n = e.tracks.length, s = t / i;
  for (let r = 0; r < n; ++r) {
    const o = e.tracks[r], l = o.ValueTypeName;
    if (l === "bool" || l === "string") continue;
    const h = a.tracks.find(function(m) {
      return m.name === o.name && m.ValueTypeName === l;
    });
    if (h === void 0) continue;
    let c = 0;
    const u = o.getValueSize();
    o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline && (c = u / 3);
    let d = 0;
    const p = h.getValueSize();
    h.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline && (d = p / 3);
    const f = o.times.length - 1;
    let y;
    if (s <= o.times[0]) {
      const m = c, v = u - c;
      y = o.values.slice(m, v);
    } else if (s >= o.times[f]) {
      const m = f * u + c, v = m + u - c;
      y = o.values.slice(m, v);
    } else {
      const m = o.createInterpolant(), v = c, x = u - c;
      m.evaluate(s), y = m.resultBuffer.slice(v, x);
    }
    l === "quaternion" && new ve().fromArray(y).normalize().conjugate().toArray(y);
    const g = h.times.length;
    for (let m = 0; m < g; ++m) {
      const v = m * p + d;
      if (l === "quaternion")
        ve.multiplyQuaternionsFlat(
          h.values,
          v,
          y,
          0,
          h.values,
          v
        );
      else {
        const x = p - d * 2;
        for (let _ = 0; _ < x; ++_)
          h.values[v + _] -= y[_];
      }
    }
  }
  return a.blendMode = Dp, a;
}
class Ub {
  /**
   * Converts an array to a specific type
   *
   * @static
   * @param {TypedArray|Array} array - The array to convert.
   * @param {TypedArray.constructor} type - The constructor of a type array.
   * @return {TypedArray} The converted array
   */
  static convertArray(t, e) {
    return ar(t, e);
  }
  /**
   * Returns `true` if the given object is a typed array.
   *
   * @static
   * @param {any} object - The object to check.
   * @return {boolean} Whether the given object is a typed array.
   */
  static isTypedArray(t) {
    return t_(t);
  }
  /**
   * Returns an array by which times and values can be sorted.
   *
   * @static
   * @param {Array<number>} times - The keyframe time values.
   * @return {Array<number>} The array.
   */
  static getKeyframeOrder(t) {
    return e_(t);
  }
  /**
   * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
   *
   * @static
   * @param {Array<number>} values - The values to sort.
   * @param {number} stride - The stride.
   * @param {Array<number>} order - The sort order.
   * @return {Array<number>} The sorted values.
   */
  static sortedArray(t, e, i) {
    return sp(t, e, i);
  }
  /**
   * Used for parsing AOS keyframe formats.
   *
   * @static
   * @param {Array<number>} jsonKeys - A list of JSON keyframes.
   * @param {Array<number>} times - This array will be filled with keyframe times by this method.
   * @param {Array<number>} values - This array will be filled with keyframe values by this method.
   * @param {string} valuePropertyName - The name of the property to use.
   */
  static flattenJSON(t, e, i, n) {
    Qp(t, e, i, n);
  }
  /**
   * Creates a new clip, containing only the segment of the original clip between the given frames.
   *
   * @static
   * @param {AnimationClip} sourceClip - The values to sort.
   * @param {string} name - The name of the clip.
   * @param {number} startFrame - The start frame.
   * @param {number} endFrame - The end frame.
   * @param {number} [fps=30] - The FPS.
   * @return {AnimationClip} The new sub clip.
   */
  static subclip(t, e, i, n, s = 30) {
    return Db(t, e, i, n, s);
  }
  /**
   * Converts the keyframes of the given animation clip to an additive format.
   *
   * @static
   * @param {AnimationClip} targetClip - The clip to make additive.
   * @param {number} [referenceFrame=0] - The reference frame.
   * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
   * @param {number} [fps=30] - The FPS.
   * @return {AnimationClip} The updated clip which is now additive.
   */
  static makeClipAdditive(t, e = 0, i = t, n = 30) {
    return Fb(t, e, i, n);
  }
}
class Wo {
  /**
   * Constructs a new interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(t, e, i, n) {
    this.parameterPositions = t, this._cachedIndex = 0, this.resultBuffer = n !== void 0 ? n : new e.constructor(i), this.sampleValues = e, this.valueSize = i, this.settings = null, this.DefaultSettings_ = {};
  }
  /**
   * Evaluate the interpolant at position `t`.
   *
   * @param {number} t - The interpolation factor.
   * @return {TypedArray} The result buffer.
   */
  evaluate(t) {
    const e = this.parameterPositions;
    let i = this._cachedIndex, n = e[i], s = e[i - 1];
    t: {
      e: {
        let r;
        i: {
          n: if (!(t < n)) {
            for (let o = i + 2; ; ) {
              if (n === void 0) {
                if (t < s) break n;
                return i = e.length, this._cachedIndex = i, this.copySampleValue_(i - 1);
              }
              if (i === o) break;
              if (s = n, n = e[++i], t < n)
                break e;
            }
            r = e.length;
            break i;
          }
          if (!(t >= s)) {
            const o = e[1];
            t < o && (i = 2, s = o);
            for (let l = i - 2; ; ) {
              if (s === void 0)
                return this._cachedIndex = 0, this.copySampleValue_(0);
              if (i === l) break;
              if (n = s, s = e[--i - 1], t >= s)
                break e;
            }
            r = i, i = 0;
            break i;
          }
          break t;
        }
        for (; i < r; ) {
          const o = i + r >>> 1;
          t < e[o] ? r = o : i = o + 1;
        }
        if (n = e[i], s = e[i - 1], s === void 0)
          return this._cachedIndex = 0, this.copySampleValue_(0);
        if (n === void 0)
          return i = e.length, this._cachedIndex = i, this.copySampleValue_(i - 1);
      }
      this._cachedIndex = i, this.intervalChanged_(i, s, n);
    }
    return this.interpolate_(i, s, t, n);
  }
  /**
   * Returns the interpolation settings.
   *
   * @return {Object} The interpolation settings.
   */
  getSettings_() {
    return this.settings || this.DefaultSettings_;
  }
  /**
   * Copies a sample value to the result buffer.
   *
   * @param {number} index - An index into the sample value buffer.
   * @return {TypedArray} The result buffer.
   */
  copySampleValue_(t) {
    const e = this.resultBuffer, i = this.sampleValues, n = this.valueSize, s = t * n;
    for (let r = 0; r !== n; ++r)
      e[r] = i[s + r];
    return e;
  }
  /**
   * Copies a sample value to the result buffer.
   *
   * @abstract
   * @param {number} i1 - An index into the sample value buffer.
   * @param {number} t0 - The previous interpolation factor.
   * @param {number} t - The current interpolation factor.
   * @param {number} t1 - The next interpolation factor.
   * @return {TypedArray} The result buffer.
   */
  interpolate_() {
    throw new Error("call to abstract method");
  }
  /**
   * Optional method that is executed when the interval has changed.
   *
   * @param {number} i1 - An index into the sample value buffer.
   * @param {number} t0 - The previous interpolation factor.
   * @param {number} t - The current interpolation factor.
   */
  intervalChanged_() {
  }
}
class i_ extends Wo {
  /**
   * Constructs a new cubic interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(t, e, i, n) {
    super(t, e, i, n), this._weightPrev = -0, this._offsetPrev = -0, this._weightNext = -0, this._offsetNext = -0, this.DefaultSettings_ = {
      endingStart: sr,
      endingEnd: sr
    };
  }
  intervalChanged_(t, e, i) {
    const n = this.parameterPositions;
    let s = t - 2, r = t + 1, o = n[s], l = n[r];
    if (o === void 0)
      switch (this.getSettings_().endingStart) {
        case rr:
          s = t, o = 2 * e - i;
          break;
        case Ao:
          s = n.length - 2, o = e + n[s] - n[s + 1];
          break;
        default:
          s = t, o = i;
      }
    if (l === void 0)
      switch (this.getSettings_().endingEnd) {
        case rr:
          r = t, l = 2 * i - e;
          break;
        case Ao:
          r = 1, l = i + n[1] - n[0];
          break;
        default:
          r = t - 1, l = e;
      }
    const h = (i - e) * 0.5, c = this.valueSize;
    this._weightPrev = h / (e - o), this._weightNext = h / (l - i), this._offsetPrev = s * c, this._offsetNext = r * c;
  }
  interpolate_(t, e, i, n) {
    const s = this.resultBuffer, r = this.sampleValues, o = this.valueSize, l = t * o, h = l - o, c = this._offsetPrev, u = this._offsetNext, d = this._weightPrev, p = this._weightNext, f = (i - e) / (n - e), y = f * f, g = y * f, m = -d * g + 2 * d * y - d * f, v = (1 + d) * g + (-1.5 - 2 * d) * y + (-0.5 + d) * f + 1, x = (-1 - p) * g + (1.5 + p) * y + 0.5 * f, _ = p * g - p * y;
    for (let S = 0; S !== o; ++S)
      s[S] = m * r[c + S] + v * r[h + S] + x * r[l + S] + _ * r[u + S];
    return s;
  }
}
class tf extends Wo {
  /**
   * Constructs a new linear interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(t, e, i, n) {
    super(t, e, i, n);
  }
  interpolate_(t, e, i, n) {
    const s = this.resultBuffer, r = this.sampleValues, o = this.valueSize, l = t * o, h = l - o, c = (i - e) / (n - e), u = 1 - c;
    for (let d = 0; d !== o; ++d)
      s[d] = r[h + d] * u + r[l + d] * c;
    return s;
  }
}
class n_ extends Wo {
  /**
   * Constructs a new discrete interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(t, e, i, n) {
    super(t, e, i, n);
  }
  interpolate_(t) {
    return this.copySampleValue_(t - 1);
  }
}
class Yi {
  /**
   * Constructs a new keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number|string|boolean>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(t, e, i, n) {
    if (t === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined");
    if (e === void 0 || e.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + t);
    this.name = t, this.times = ar(e, this.TimeBufferType), this.values = ar(i, this.ValueBufferType), this.setInterpolation(n || this.DefaultInterpolation);
  }
  /**
   * Converts the keyframe track to JSON.
   *
   * @static
   * @param {KeyframeTrack} track - The keyframe track to serialize.
   * @return {Object} The serialized keyframe track as JSON.
   */
  static toJSON(t) {
    const e = t.constructor;
    let i;
    if (e.toJSON !== this.toJSON)
      i = e.toJSON(t);
    else {
      i = {
        name: t.name,
        times: ar(t.times, Array),
        values: ar(t.values, Array)
      };
      const n = t.getInterpolation();
      n !== t.DefaultInterpolation && (i.interpolation = n);
    }
    return i.type = t.ValueTypeName, i;
  }
  /**
   * Factory method for creating a new discrete interpolant.
   *
   * @static
   * @param {TypedArray} [result] - The result buffer.
   * @return {DiscreteInterpolant} The new interpolant.
   */
  InterpolantFactoryMethodDiscrete(t) {
    return new n_(this.times, this.values, this.getValueSize(), t);
  }
  /**
   * Factory method for creating a new linear interpolant.
   *
   * @static
   * @param {TypedArray} [result] - The result buffer.
   * @return {LinearInterpolant} The new interpolant.
   */
  InterpolantFactoryMethodLinear(t) {
    return new tf(this.times, this.values, this.getValueSize(), t);
  }
  /**
   * Factory method for creating a new smooth interpolant.
   *
   * @static
   * @param {TypedArray} [result] - The result buffer.
   * @return {CubicInterpolant} The new interpolant.
   */
  InterpolantFactoryMethodSmooth(t) {
    return new i_(this.times, this.values, this.getValueSize(), t);
  }
  /**
   * Defines the interpolation factor method for this keyframe track.
   *
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
   * @return {KeyframeTrack} A reference to this keyframe track.
   */
  setInterpolation(t) {
    let e;
    switch (t) {
      case wo:
        e = this.InterpolantFactoryMethodDiscrete;
        break;
      case fc:
        e = this.InterpolantFactoryMethodLinear;
        break;
      case bh:
        e = this.InterpolantFactoryMethodSmooth;
        break;
    }
    if (e === void 0) {
      const i = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
      if (this.createInterpolant === void 0)
        if (t !== this.DefaultInterpolation)
          this.setInterpolation(this.DefaultInterpolation);
        else
          throw new Error(i);
      return console.warn("THREE.KeyframeTrack:", i), this;
    }
    return this.createInterpolant = e, this;
  }
  /**
   * Returns the current interpolation type.
   *
   * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
   */
  getInterpolation() {
    switch (this.createInterpolant) {
      case this.InterpolantFactoryMethodDiscrete:
        return wo;
      case this.InterpolantFactoryMethodLinear:
        return fc;
      case this.InterpolantFactoryMethodSmooth:
        return bh;
    }
  }
  /**
   * Returns the value size.
   *
   * @return {number} The value size.
   */
  getValueSize() {
    return this.values.length / this.times.length;
  }
  /**
   * Moves all keyframes either forward or backward in time.
   *
   * @param {number} timeOffset - The offset to move the time values.
   * @return {KeyframeTrack} A reference to this keyframe track.
   */
  shift(t) {
    if (t !== 0) {
      const e = this.times;
      for (let i = 0, n = e.length; i !== n; ++i)
        e[i] += t;
    }
    return this;
  }
  /**
   * Scale all keyframe times by a factor (useful for frame - seconds conversions).
   *
   * @param {number} timeScale - The time scale.
   * @return {KeyframeTrack} A reference to this keyframe track.
   */
  scale(t) {
    if (t !== 1) {
      const e = this.times;
      for (let i = 0, n = e.length; i !== n; ++i)
        e[i] *= t;
    }
    return this;
  }
  /**
   * Removes keyframes before and after animation without changing any values within the defined time range.
   *
   * Note: The method does not shift around keys to the start of the track time, because for interpolated
   * keys this will change their values
   *
   * @param {number} startTime - The start time.
   * @param {number} endTime - The end time.
   * @return {KeyframeTrack} A reference to this keyframe track.
   */
  trim(t, e) {
    const i = this.times, n = i.length;
    let s = 0, r = n - 1;
    for (; s !== n && i[s] < t; )
      ++s;
    for (; r !== -1 && i[r] > e; )
      --r;
    if (++r, s !== 0 || r !== n) {
      s >= r && (r = Math.max(r, 1), s = r - 1);
      const o = this.getValueSize();
      this.times = i.slice(s, r), this.values = this.values.slice(s * o, r * o);
    }
    return this;
  }
  /**
   * Performs minimal validation on the keyframe track. Returns `true` if the values
   * are valid.
   *
   * @return {boolean} Whether the keyframes are valid or not.
   */
  validate() {
    let t = !0;
    const e = this.getValueSize();
    e - Math.floor(e) !== 0 && (console.error("THREE.KeyframeTrack: Invalid value size in track.", this), t = !1);
    const i = this.times, n = this.values, s = i.length;
    s === 0 && (console.error("THREE.KeyframeTrack: Track is empty.", this), t = !1);
    let r = null;
    for (let o = 0; o !== s; o++) {
      const l = i[o];
      if (typeof l == "number" && isNaN(l)) {
        console.error("THREE.KeyframeTrack: Time is not a valid number.", this, o, l), t = !1;
        break;
      }
      if (r !== null && r > l) {
        console.error("THREE.KeyframeTrack: Out of order keys.", this, o, l, r), t = !1;
        break;
      }
      r = l;
    }
    if (n !== void 0 && t_(n))
      for (let o = 0, l = n.length; o !== l; ++o) {
        const h = n[o];
        if (isNaN(h)) {
          console.error("THREE.KeyframeTrack: Value is not a valid number.", this, o, h), t = !1;
          break;
        }
      }
    return t;
  }
  /**
   * Optimizes this keyframe track by removing equivalent sequential keys (which are
   * common in morph target sequences).
   *
   * @return {AnimationClip} A reference to this animation clip.
   */
  optimize() {
    const t = this.times.slice(), e = this.values.slice(), i = this.getValueSize(), n = this.getInterpolation() === bh, s = t.length - 1;
    let r = 1;
    for (let o = 1; o < s; ++o) {
      let l = !1;
      const h = t[o], c = t[o + 1];
      if (h !== c && (o !== 1 || h !== t[0]))
        if (n)
          l = !0;
        else {
          const u = o * i, d = u - i, p = u + i;
          for (let f = 0; f !== i; ++f) {
            const y = e[u + f];
            if (y !== e[d + f] || y !== e[p + f]) {
              l = !0;
              break;
            }
          }
        }
      if (l) {
        if (o !== r) {
          t[r] = t[o];
          const u = o * i, d = r * i;
          for (let p = 0; p !== i; ++p)
            e[d + p] = e[u + p];
        }
        ++r;
      }
    }
    if (s > 0) {
      t[r] = t[s];
      for (let o = s * i, l = r * i, h = 0; h !== i; ++h)
        e[l + h] = e[o + h];
      ++r;
    }
    return r !== t.length ? (this.times = t.slice(0, r), this.values = e.slice(0, r * i)) : (this.times = t, this.values = e), this;
  }
  /**
   * Returns a new keyframe track with copied values from this instance.
   *
   * @return {KeyframeTrack} A clone of this instance.
   */
  clone() {
    const t = this.times.slice(), e = this.values.slice(), i = this.constructor, n = new i(this.name, t, e);
    return n.createInterpolant = this.createInterpolant, n;
  }
}
Yi.prototype.ValueTypeName = "";
Yi.prototype.TimeBufferType = Float32Array;
Yi.prototype.ValueBufferType = Float32Array;
Yi.prototype.DefaultInterpolation = fc;
class gr extends Yi {
  /**
   * Constructs a new boolean keyframe track.
   *
   * This keyframe track type has no `interpolation` parameter because the
   * interpolation is always discrete.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<boolean>} values - A list of keyframe values.
   */
  constructor(t, e, i) {
    super(t, e, i);
  }
}
gr.prototype.ValueTypeName = "bool";
gr.prototype.ValueBufferType = Array;
gr.prototype.DefaultInterpolation = wo;
gr.prototype.InterpolantFactoryMethodLinear = void 0;
gr.prototype.InterpolantFactoryMethodSmooth = void 0;
class ef extends Yi {
  /**
   * Constructs a new color keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(t, e, i, n) {
    super(t, e, i, n);
  }
}
ef.prototype.ValueTypeName = "color";
class Fo extends Yi {
  /**
   * Constructs a new number keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(t, e, i, n) {
    super(t, e, i, n);
  }
}
Fo.prototype.ValueTypeName = "number";
class s_ extends Wo {
  /**
   * Constructs a new SLERP interpolant.
   *
   * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
   * @param {TypedArray} sampleValues - The sample values.
   * @param {number} sampleSize - The sample size
   * @param {TypedArray} [resultBuffer] - The result buffer.
   */
  constructor(t, e, i, n) {
    super(t, e, i, n);
  }
  interpolate_(t, e, i, n) {
    const s = this.resultBuffer, r = this.sampleValues, o = this.valueSize, l = (i - e) / (n - e);
    let h = t * o;
    for (let c = h + o; h !== c; h += 4)
      ve.slerpFlat(s, 0, r, h - o, r, h, l);
    return s;
  }
}
class Pa extends Yi {
  /**
   * Constructs a new Quaternion keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(t, e, i, n) {
    super(t, e, i, n);
  }
  /**
   * Overwritten so the method returns Quaternion based interpolant.
   *
   * @static
   * @param {TypedArray} [result] - The result buffer.
   * @return {QuaternionLinearInterpolant} The new interpolant.
   */
  InterpolantFactoryMethodLinear(t) {
    return new s_(this.times, this.values, this.getValueSize(), t);
  }
}
Pa.prototype.ValueTypeName = "quaternion";
Pa.prototype.InterpolantFactoryMethodSmooth = void 0;
class yr extends Yi {
  /**
   * Constructs a new string keyframe track.
   *
   * This keyframe track type has no `interpolation` parameter because the
   * interpolation is always discrete.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<string>} values - A list of keyframe values.
   */
  constructor(t, e, i) {
    super(t, e, i);
  }
}
yr.prototype.ValueTypeName = "string";
yr.prototype.ValueBufferType = Array;
yr.prototype.DefaultInterpolation = wo;
yr.prototype.InterpolantFactoryMethodLinear = void 0;
yr.prototype.InterpolantFactoryMethodSmooth = void 0;
class ba extends Yi {
  /**
   * Constructs a new vector keyframe track.
   *
   * @param {string} name - The keyframe track's name.
   * @param {Array<number>} times - A list of keyframe times.
   * @param {Array<number>} values - A list of keyframe values.
   * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
   */
  constructor(t, e, i, n) {
    super(t, e, i, n);
  }
}
ba.prototype.ValueTypeName = "vector";
class Ma {
  /**
   * Constructs a new animation clip.
   *
   * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
   * use the static interface of this class for creating clips. In most cases though, animation clips
   * will automatically be created by loaders when importing animated 3D assets.
   *
   * @param {string} [name=''] - The clip's name.
   * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
   * the duration will be calculated from the passed keyframes.
   * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
   * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
   * is blended/combined when two or more animations are simultaneously played.
   */
  constructor(t = "", e = -1, i = [], n = Uc) {
    this.name = t, this.tracks = i, this.duration = e, this.blendMode = n, this.uuid = Oi(), this.userData = {}, this.duration < 0 && this.resetDuration();
  }
  /**
   * Factory method for creating an animation clip from the given JSON.
   *
   * @static
   * @param {Object} json - The serialized animation clip.
   * @return {AnimationClip} The new animation clip.
   */
  static parse(t) {
    const e = [], i = t.tracks, n = 1 / (t.fps || 1);
    for (let r = 0, o = i.length; r !== o; ++r)
      e.push(zb(i[r]).scale(n));
    const s = new this(t.name, t.duration, e, t.blendMode);
    return s.uuid = t.uuid, s.userData = JSON.parse(t.userData || "{}"), s;
  }
  /**
   * Serializes the given animation clip into JSON.
   *
   * @static
   * @param {AnimationClip} clip - The animation clip to serialize.
   * @return {Object} The JSON object.
   */
  static toJSON(t) {
    const e = [], i = t.tracks, n = {
      name: t.name,
      duration: t.duration,
      tracks: e,
      uuid: t.uuid,
      blendMode: t.blendMode,
      userData: JSON.stringify(t.userData)
    };
    for (let s = 0, r = i.length; s !== r; ++s)
      e.push(Yi.toJSON(i[s]));
    return n;
  }
  /**
   * Returns a new animation clip from the passed morph targets array of a
   * geometry, taking a name and the number of frames per second.
   *
   * Note: The fps parameter is required, but the animation speed can be
   * overridden via {@link AnimationAction#setDuration}.
   *
   * @static
   * @param {string} name - The name of the animation clip.
   * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
   * @param {number} fps - The Frames-Per-Second value.
   * @param {boolean} noLoop - Whether the clip should be no loop or not.
   * @return {AnimationClip} The new animation clip.
   */
  static CreateFromMorphTargetSequence(t, e, i, n) {
    const s = e.length, r = [];
    for (let o = 0; o < s; o++) {
      let l = [], h = [];
      l.push(
        (o + s - 1) % s,
        o,
        (o + 1) % s
      ), h.push(0, 1, 0);
      const c = e_(l);
      l = sp(l, 1, c), h = sp(h, 1, c), !n && l[0] === 0 && (l.push(s), h.push(h[0])), r.push(
        new Fo(
          ".morphTargetInfluences[" + e[o].name + "]",
          l,
          h
        ).scale(1 / i)
      );
    }
    return new this(t, -1, r);
  }
  /**
   * Searches for an animation clip by name, taking as its first parameter
   * either an array of clips, or a mesh or geometry that contains an
   * array named "animations" property.
   *
   * @static
   * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
   * @param {string} name - The name to search for.
   * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
   */
  static findByName(t, e) {
    let i = t;
    if (!Array.isArray(t)) {
      const n = t;
      i = n.geometry && n.geometry.animations || n.animations;
    }
    for (let n = 0; n < i.length; n++)
      if (i[n].name === e)
        return i[n];
    return null;
  }
  /**
   * Returns an array of new AnimationClips created from the morph target
   * sequences of a geometry, trying to sort morph target names into
   * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
   *
   * See {@link MD2Loader#parse} as an example for how the method should be used.
   *
   * @static
   * @param {Array<Object>} morphTargets - A sequence of morph targets.
   * @param {number} fps - The Frames-Per-Second value.
   * @param {boolean} noLoop - Whether the clip should be no loop or not.
   * @return {Array<AnimationClip>} An array of new animation clips.
   */
  static CreateClipsFromMorphTargetSequences(t, e, i) {
    const n = {}, s = /^([\w-]*?)([\d]+)$/;
    for (let o = 0, l = t.length; o < l; o++) {
      const h = t[o], c = h.name.match(s);
      if (c && c.length > 1) {
        const u = c[1];
        let d = n[u];
        d || (n[u] = d = []), d.push(h);
      }
    }
    const r = [];
    for (const o in n)
      r.push(this.CreateFromMorphTargetSequence(o, n[o], e, i));
    return r;
  }
  /**
   * Parses the `animation.hierarchy` format and returns a new animation clip.
   *
   * @static
   * @deprecated since r175.
   * @param {Object} animation - A serialized animation clip as JSON.
   * @param {Array<Bones>} bones - An array of bones.
   * @return {?AnimationClip} The new animation clip.
   */
  static parseAnimation(t, e) {
    if (console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"), !t)
      return console.error("THREE.AnimationClip: No animation in JSONLoader data."), null;
    const i = function(u, d, p, f, y) {
      if (p.length !== 0) {
        const g = [], m = [];
        Qp(p, g, m, f), g.length !== 0 && y.push(new u(d, g, m));
      }
    }, n = [], s = t.name || "default", r = t.fps || 30, o = t.blendMode;
    let l = t.length || -1;
    const h = t.hierarchy || [];
    for (let u = 0; u < h.length; u++) {
      const d = h[u].keys;
      if (!(!d || d.length === 0))
        if (d[0].morphTargets) {
          const p = {};
          let f;
          for (f = 0; f < d.length; f++)
            if (d[f].morphTargets)
              for (let y = 0; y < d[f].morphTargets.length; y++)
                p[d[f].morphTargets[y]] = -1;
          for (const y in p) {
            const g = [], m = [];
            for (let v = 0; v !== d[f].morphTargets.length; ++v) {
              const x = d[f];
              g.push(x.time), m.push(x.morphTarget === y ? 1 : 0);
            }
            n.push(new Fo(".morphTargetInfluence[" + y + "]", g, m));
          }
          l = p.length * r;
        } else {
          const p = ".bones[" + e[u].name + "]";
          i(
            ba,
            p + ".position",
            d,
            "pos",
            n
          ), i(
            Pa,
            p + ".quaternion",
            d,
            "rot",
            n
          ), i(
            ba,
            p + ".scale",
            d,
            "scl",
            n
          );
        }
    }
    return n.length === 0 ? null : new this(s, l, n, o);
  }
  /**
   * Sets the duration of this clip to the duration of its longest keyframe track.
   *
   * @return {AnimationClip} A reference to this animation clip.
   */
  resetDuration() {
    const t = this.tracks;
    let e = 0;
    for (let i = 0, n = t.length; i !== n; ++i) {
      const s = this.tracks[i];
      e = Math.max(e, s.times[s.times.length - 1]);
    }
    return this.duration = e, this;
  }
  /**
   * Trims all tracks to the clip's duration.
   *
   * @return {AnimationClip} A reference to this animation clip.
   */
  trim() {
    for (let t = 0; t < this.tracks.length; t++)
      this.tracks[t].trim(0, this.duration);
    return this;
  }
  /**
   * Performs minimal validation on each track in the clip. Returns `true` if all
   * tracks are valid.
   *
   * @return {boolean} Whether the clip's keyframes are valid or not.
   */
  validate() {
    let t = !0;
    for (let e = 0; e < this.tracks.length; e++)
      t = t && this.tracks[e].validate();
    return t;
  }
  /**
   * Optimizes each track by removing equivalent sequential keys (which are
   * common in morph target sequences).
   *
   * @return {AnimationClip} A reference to this animation clip.
   */
  optimize() {
    for (let t = 0; t < this.tracks.length; t++)
      this.tracks[t].optimize();
    return this;
  }
  /**
   * Returns a new animation clip with copied values from this instance.
   *
   * @return {AnimationClip} A clone of this instance.
   */
  clone() {
    const t = [];
    for (let i = 0; i < this.tracks.length; i++)
      t.push(this.tracks[i].clone());
    const e = new this.constructor(this.name, this.duration, t, this.blendMode);
    return e.userData = JSON.parse(JSON.stringify(this.userData)), e;
  }
  /**
   * Serializes this animation clip into JSON.
   *
   * @return {Object} The JSON object.
   */
  toJSON() {
    return this.constructor.toJSON(this);
  }
}
function Bb(a) {
  switch (a.toLowerCase()) {
    case "scalar":
    case "double":
    case "float":
    case "number":
    case "integer":
      return Fo;
    case "vector":
    case "vector2":
    case "vector3":
    case "vector4":
      return ba;
    case "color":
      return ef;
    case "quaternion":
      return Pa;
    case "bool":
    case "boolean":
      return gr;
    case "string":
      return yr;
  }
  throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + a);
}
function zb(a) {
  if (a.type === void 0)
    throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");
  const t = Bb(a.type);
  if (a.times === void 0) {
    const e = [], i = [];
    Qp(a.keys, e, i, "value"), a.times = e, a.values = i;
  }
  return t.parse !== void 0 ? t.parse(a) : new t(a.name, a.times, a.values, a.interpolation);
}
const Tn = {
  /**
   * Whether caching is enabled or not.
   *
   * @static
   * @type {boolean}
   * @default false
   */
  enabled: !1,
  /**
   * A dictionary that holds cached files.
   *
   * @static
   * @type {Object<string,Object>}
   */
  files: {},
  /**
   * Adds a cache entry with a key to reference the file. If this key already
   * holds a file, it is overwritten.
   *
   * @static
   * @param {string} key - The key to reference the cached file.
   * @param {Object} file -  The file to be cached.
   */
  add: function(a, t) {
    this.enabled !== !1 && (this.files[a] = t);
  },
  /**
   * Gets the cached value for the given key.
   *
   * @static
   * @param {string} key - The key to reference the cached file.
   * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
   */
  get: function(a) {
    if (this.enabled !== !1)
      return this.files[a];
  },
  /**
   * Removes the cached file associated with the given key.
   *
   * @static
   * @param {string} key - The key to reference the cached file.
   */
  remove: function(a) {
    delete this.files[a];
  },
  /**
   * Remove all values from the cache.
   *
   * @static
   */
  clear: function() {
    this.files = {};
  }
};
class nf {
  /**
   * Constructs a new loading manager.
   *
   * @param {Function} [onLoad] - Executes when all items have been loaded.
   * @param {Function} [onProgress] - Executes when single items have been loaded.
   * @param {Function} [onError] - Executes when an error occurs.
   */
  constructor(t, e, i) {
    const n = this;
    let s = !1, r = 0, o = 0, l;
    const h = [];
    this.onStart = void 0, this.onLoad = t, this.onProgress = e, this.onError = i, this.abortController = new AbortController(), this.itemStart = function(c) {
      o++, s === !1 && n.onStart !== void 0 && n.onStart(c, r, o), s = !0;
    }, this.itemEnd = function(c) {
      r++, n.onProgress !== void 0 && n.onProgress(c, r, o), r === o && (s = !1, n.onLoad !== void 0 && n.onLoad());
    }, this.itemError = function(c) {
      n.onError !== void 0 && n.onError(c);
    }, this.resolveURL = function(c) {
      return l ? l(c) : c;
    }, this.setURLModifier = function(c) {
      return l = c, this;
    }, this.addHandler = function(c, u) {
      return h.push(c, u), this;
    }, this.removeHandler = function(c) {
      const u = h.indexOf(c);
      return u !== -1 && h.splice(u, 2), this;
    }, this.getHandler = function(c) {
      for (let u = 0, d = h.length; u < d; u += 2) {
        const p = h[u], f = h[u + 1];
        if (p.global && (p.lastIndex = 0), p.test(c))
          return f;
      }
      return null;
    }, this.abort = function() {
      return this.abortController.abort(), this.abortController = new AbortController(), this;
    };
  }
}
const r_ = /* @__PURE__ */ new nf();
class Ti {
  /**
   * Constructs a new loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    this.manager = t !== void 0 ? t : r_, this.crossOrigin = "anonymous", this.withCredentials = !1, this.path = "", this.resourcePath = "", this.requestHeader = {};
  }
  /**
   * This method needs to be implemented by all concrete loaders. It holds the
   * logic for loading assets from the backend.
   *
   * @abstract
   * @param {string} url - The path/URL of the file to be loaded.
   * @param {Function} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
   * @param {onErrorCallback} [onError] - Executed when errors occur.
   */
  load() {
  }
  /**
   * A async version of {@link Loader#load}.
   *
   * @param {string} url - The path/URL of the file to be loaded.
   * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
   * @return {Promise} A Promise that resolves when the asset has been loaded.
   */
  loadAsync(t, e) {
    const i = this;
    return new Promise(function(n, s) {
      i.load(t, n, e, s);
    });
  }
  /**
   * This method needs to be implemented by all concrete loaders. It holds the
   * logic for parsing the asset into three.js entities.
   *
   * @abstract
   * @param {any} data - The data to parse.
   */
  parse() {
  }
  /**
   * Sets the `crossOrigin` String to implement CORS for loading the URL
   * from a different domain that allows CORS.
   *
   * @param {string} crossOrigin - The `crossOrigin` value.
   * @return {Loader} A reference to this instance.
   */
  setCrossOrigin(t) {
    return this.crossOrigin = t, this;
  }
  /**
   * Whether the XMLHttpRequest uses credentials such as cookies, authorization
   * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
   *
   * Note: This setting has no effect if you are loading files locally or from the same domain.
   *
   * @param {boolean} value - The `withCredentials` value.
   * @return {Loader} A reference to this instance.
   */
  setWithCredentials(t) {
    return this.withCredentials = t, this;
  }
  /**
   * Sets the base path for the asset.
   *
   * @param {string} path - The base path.
   * @return {Loader} A reference to this instance.
   */
  setPath(t) {
    return this.path = t, this;
  }
  /**
   * Sets the base path for dependent resources like textures.
   *
   * @param {string} resourcePath - The resource path.
   * @return {Loader} A reference to this instance.
   */
  setResourcePath(t) {
    return this.resourcePath = t, this;
  }
  /**
   * Sets the given request header.
   *
   * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
   * for configuring the HTTP request.
   * @return {Loader} A reference to this instance.
   */
  setRequestHeader(t) {
    return this.requestHeader = t, this;
  }
  /**
   * This method can be implemented in loaders for aborting ongoing requests.
   *
   * @abstract
   * @return {Loader} A reference to this instance.
   */
  abort() {
    return this;
  }
}
Ti.DEFAULT_MATERIAL_NAME = "__DEFAULT";
const zn = {};
class Nb extends Error {
  constructor(t, e) {
    super(t), this.response = e;
  }
}
class ss extends Ti {
  /**
   * Constructs a new file loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t), this.mimeType = "", this.responseType = "", this._abortController = new AbortController();
  }
  /**
   * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(any)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
   * @param {onErrorCallback} [onError] - Executed when errors occur.
   * @return {any|undefined} The cached resource if available.
   */
  load(t, e, i, n) {
    t === void 0 && (t = ""), this.path !== void 0 && (t = this.path + t), t = this.manager.resolveURL(t);
    const s = Tn.get(`file:${t}`);
    if (s !== void 0)
      return this.manager.itemStart(t), setTimeout(() => {
        e && e(s), this.manager.itemEnd(t);
      }, 0), s;
    if (zn[t] !== void 0) {
      zn[t].push({
        onLoad: e,
        onProgress: i,
        onError: n
      });
      return;
    }
    zn[t] = [], zn[t].push({
      onLoad: e,
      onProgress: i,
      onError: n
    });
    const r = new Request(t, {
      headers: new Headers(this.requestHeader),
      credentials: this.withCredentials ? "include" : "same-origin",
      signal: typeof AbortSignal.any == "function" ? AbortSignal.any([this._abortController.signal, this.manager.abortController.signal]) : this._abortController.signal
    }), o = this.mimeType, l = this.responseType;
    fetch(r).then((h) => {
      if (h.status === 200 || h.status === 0) {
        if (h.status === 0 && console.warn("THREE.FileLoader: HTTP Status 0 received."), typeof ReadableStream > "u" || h.body === void 0 || h.body.getReader === void 0)
          return h;
        const c = zn[t], u = h.body.getReader(), d = h.headers.get("X-File-Size") || h.headers.get("Content-Length"), p = d ? parseInt(d) : 0, f = p !== 0;
        let y = 0;
        const g = new ReadableStream({
          start(m) {
            v();
            function v() {
              u.read().then(({ done: x, value: _ }) => {
                if (x)
                  m.close();
                else {
                  y += _.byteLength;
                  const S = new ProgressEvent("progress", { lengthComputable: f, loaded: y, total: p });
                  for (let w = 0, T = c.length; w < T; w++) {
                    const R = c[w];
                    R.onProgress && R.onProgress(S);
                  }
                  m.enqueue(_), v();
                }
              }, (x) => {
                m.error(x);
              });
            }
          }
        });
        return new Response(g);
      } else
        throw new Nb(`fetch for "${h.url}" responded with ${h.status}: ${h.statusText}`, h);
    }).then((h) => {
      switch (l) {
        case "arraybuffer":
          return h.arrayBuffer();
        case "blob":
          return h.blob();
        case "document":
          return h.text().then((c) => new DOMParser().parseFromString(c, o));
        case "json":
          return h.json();
        default:
          if (o === "")
            return h.text();
          {
            const u = /charset="?([^;"\s]*)"?/i.exec(o), d = u && u[1] ? u[1].toLowerCase() : void 0, p = new TextDecoder(d);
            return h.arrayBuffer().then((f) => p.decode(f));
          }
      }
    }).then((h) => {
      Tn.add(`file:${t}`, h);
      const c = zn[t];
      delete zn[t];
      for (let u = 0, d = c.length; u < d; u++) {
        const p = c[u];
        p.onLoad && p.onLoad(h);
      }
    }).catch((h) => {
      const c = zn[t];
      if (c === void 0)
        throw this.manager.itemError(t), h;
      delete zn[t];
      for (let u = 0, d = c.length; u < d; u++) {
        const p = c[u];
        p.onError && p.onError(h);
      }
      this.manager.itemError(t);
    }).finally(() => {
      this.manager.itemEnd(t);
    }), this.manager.itemStart(t);
  }
  /**
   * Sets the expected response type.
   *
   * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
   * @return {FileLoader} A reference to this file loader.
   */
  setResponseType(t) {
    return this.responseType = t, this;
  }
  /**
   * Sets the expected mime type of the loaded file.
   *
   * @param {string} value - The mime type.
   * @return {FileLoader} A reference to this file loader.
   */
  setMimeType(t) {
    return this.mimeType = t, this;
  }
  /**
   * Aborts ongoing fetch requests.
   *
   * @return {FileLoader} A reference to this instance.
   */
  abort() {
    return this._abortController.abort(), this._abortController = new AbortController(), this;
  }
}
class Ob extends Ti {
  /**
   * Constructs a new animation loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and pass the loaded animations as an array
   * holding instances of {@link AnimationClip} to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(t, e, i, n) {
    const s = this, r = new ss(this.manager);
    r.setPath(this.path), r.setRequestHeader(this.requestHeader), r.setWithCredentials(this.withCredentials), r.load(t, function(o) {
      try {
        e(s.parse(JSON.parse(o)));
      } catch (l) {
        n ? n(l) : console.error(l), s.manager.itemError(t);
      }
    }, i, n);
  }
  /**
   * Parses the given JSON object and returns an array of animation clips.
   *
   * @param {Object} json - The serialized animation clips.
   * @return {Array<AnimationClip>} The parsed animation clips.
   */
  parse(t) {
    const e = [];
    for (let i = 0; i < t.length; i++) {
      const n = Ma.parse(t[i]);
      e.push(n);
    }
    return e;
  }
}
class kb extends Ti {
  /**
   * Constructs a new compressed texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and passes the loaded compressed texture
   * to the `onLoad()` callback. The method also returns a new texture object which can
   * directly be used for material creation. If you do it this way, the texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {CompressedTexture} The compressed texture.
   */
  load(t, e, i, n) {
    const s = this, r = [], o = new Yc(), l = new ss(this.manager);
    l.setPath(this.path), l.setResponseType("arraybuffer"), l.setRequestHeader(this.requestHeader), l.setWithCredentials(s.withCredentials);
    let h = 0;
    function c(u) {
      l.load(t[u], function(d) {
        const p = s.parse(d, !0);
        r[u] = {
          width: p.width,
          height: p.height,
          format: p.format,
          mipmaps: p.mipmaps
        }, h += 1, h === 6 && (p.mipmapCount === 1 && (o.minFilter = Ce), o.image = r, o.format = p.format, o.needsUpdate = !0, e && e(o));
      }, i, n);
    }
    if (Array.isArray(t))
      for (let u = 0, d = t.length; u < d; ++u)
        c(u);
    else
      l.load(t, function(u) {
        const d = s.parse(u, !0);
        if (d.isCubemap) {
          const p = d.mipmaps.length / d.mipmapCount;
          for (let f = 0; f < p; f++) {
            r[f] = { mipmaps: [] };
            for (let y = 0; y < d.mipmapCount; y++)
              r[f].mipmaps.push(d.mipmaps[f * d.mipmapCount + y]), r[f].format = d.format, r[f].width = d.width, r[f].height = d.height;
          }
          o.image = r;
        } else
          o.image.width = d.width, o.image.height = d.height, o.mipmaps = d.mipmaps;
        d.mipmapCount === 1 && (o.minFilter = Ce), o.format = d.format, o.needsUpdate = !0, e && e(o);
      }, i, n);
    return o;
  }
}
const zr = /* @__PURE__ */ new WeakMap();
class Uo extends Ti {
  /**
   * Constructs a new image loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and passes the loaded image
   * to the `onLoad()` callback. The method also returns a new `Image` object which can
   * directly be used for texture creation. If you do it this way, the texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Image)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Unsupported in this loader.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {Image} The image.
   */
  load(t, e, i, n) {
    this.path !== void 0 && (t = this.path + t), t = this.manager.resolveURL(t);
    const s = this, r = Tn.get(`image:${t}`);
    if (r !== void 0) {
      if (r.complete === !0)
        s.manager.itemStart(t), setTimeout(function() {
          e && e(r), s.manager.itemEnd(t);
        }, 0);
      else {
        let u = zr.get(r);
        u === void 0 && (u = [], zr.set(r, u)), u.push({ onLoad: e, onError: n });
      }
      return r;
    }
    const o = Ro("img");
    function l() {
      c(), e && e(this);
      const u = zr.get(this) || [];
      for (let d = 0; d < u.length; d++) {
        const p = u[d];
        p.onLoad && p.onLoad(this);
      }
      zr.delete(this), s.manager.itemEnd(t);
    }
    function h(u) {
      c(), n && n(u), Tn.remove(`image:${t}`);
      const d = zr.get(this) || [];
      for (let p = 0; p < d.length; p++) {
        const f = d[p];
        f.onError && f.onError(u);
      }
      zr.delete(this), s.manager.itemError(t), s.manager.itemEnd(t);
    }
    function c() {
      o.removeEventListener("load", l, !1), o.removeEventListener("error", h, !1);
    }
    return o.addEventListener("load", l, !1), o.addEventListener("error", h, !1), t.slice(0, 5) !== "data:" && this.crossOrigin !== void 0 && (o.crossOrigin = this.crossOrigin), Tn.add(`image:${t}`, o), s.manager.itemStart(t), o.src = t, o;
  }
}
class Vb extends Ti {
  /**
   * Constructs a new cube texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and pass the fully loaded cube texture
   * to the `onLoad()` callback. The method also returns a new cube texture object which can
   * directly be used for material creation. If you do it this way, the cube texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
   * cube texture. The urls should be specified in the following order: pos-x,
   * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
   * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Unsupported in this loader.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {CubeTexture} The cube texture.
   */
  load(t, e, i, n) {
    const s = new Oo();
    s.colorSpace = ri;
    const r = new Uo(this.manager);
    r.setCrossOrigin(this.crossOrigin), r.setPath(this.path);
    let o = 0;
    function l(h) {
      r.load(t[h], function(c) {
        s.images[h] = c, o++, o === 6 && (s.needsUpdate = !0, e && e(s));
      }, void 0, n);
    }
    for (let h = 0; h < t.length; ++h)
      l(h);
    return s;
  }
}
class Hb extends Ti {
  /**
   * Constructs a new data texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and passes the loaded data texture
   * to the `onLoad()` callback. The method also returns a new texture object which can
   * directly be used for material creation. If you do it this way, the texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {DataTexture} The data texture.
   */
  load(t, e, i, n) {
    const s = this, r = new Cn(), o = new ss(this.manager);
    return o.setResponseType("arraybuffer"), o.setRequestHeader(this.requestHeader), o.setPath(this.path), o.setWithCredentials(s.withCredentials), o.load(t, function(l) {
      let h;
      try {
        h = s.parse(l);
      } catch (c) {
        if (n !== void 0)
          n(c);
        else {
          console.error(c);
          return;
        }
      }
      h.image !== void 0 ? r.image = h.image : h.data !== void 0 && (r.image.width = h.width, r.image.height = h.height, r.image.data = h.data), r.wrapS = h.wrapS !== void 0 ? h.wrapS : Si, r.wrapT = h.wrapT !== void 0 ? h.wrapT : Si, r.magFilter = h.magFilter !== void 0 ? h.magFilter : Ce, r.minFilter = h.minFilter !== void 0 ? h.minFilter : Ce, r.anisotropy = h.anisotropy !== void 0 ? h.anisotropy : 1, h.colorSpace !== void 0 && (r.colorSpace = h.colorSpace), h.flipY !== void 0 && (r.flipY = h.flipY), h.format !== void 0 && (r.format = h.format), h.type !== void 0 && (r.type = h.type), h.mipmaps !== void 0 && (r.mipmaps = h.mipmaps, r.minFilter = En), h.mipmapCount === 1 && (r.minFilter = Ce), h.generateMipmaps !== void 0 && (r.generateMipmaps = h.generateMipmaps), r.needsUpdate = !0, e && e(r, h);
    }, i, n), r;
  }
}
class Gb extends Ti {
  /**
   * Constructs a new texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and pass the fully loaded texture
   * to the `onLoad()` callback. The method also returns a new texture object which can
   * directly be used for material creation. If you do it this way, the texture
   * may pop up in your scene once the respective loading process is finished.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Unsupported in this loader.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {Texture} The texture.
   */
  load(t, e, i, n) {
    const s = new Ne(), r = new Uo(this.manager);
    return r.setCrossOrigin(this.crossOrigin), r.setPath(this.path), r.load(t, function(o) {
      s.image = o, s.needsUpdate = !0, e !== void 0 && e(s);
    }, i, n), s;
  }
}
class Fs extends le {
  /**
   * Constructs a new light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(t, e = 1) {
    super(), this.isLight = !0, this.type = "Light", this.color = new ct(t), this.intensity = e;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
  }
  copy(t, e) {
    return super.copy(t, e), this.color.copy(t.color), this.intensity = t.intensity, this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.object.color = this.color.getHex(), e.object.intensity = this.intensity, this.groundColor !== void 0 && (e.object.groundColor = this.groundColor.getHex()), this.distance !== void 0 && (e.object.distance = this.distance), this.angle !== void 0 && (e.object.angle = this.angle), this.decay !== void 0 && (e.object.decay = this.decay), this.penumbra !== void 0 && (e.object.penumbra = this.penumbra), this.shadow !== void 0 && (e.object.shadow = this.shadow.toJSON()), this.target !== void 0 && (e.object.target = this.target.uuid), e;
  }
}
class a_ extends Fs {
  /**
   * Constructs a new hemisphere light.
   *
   * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
   * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(t, e, i) {
    super(t, i), this.isHemisphereLight = !0, this.type = "HemisphereLight", this.position.copy(le.DEFAULT_UP), this.updateMatrix(), this.groundColor = new ct(e);
  }
  copy(t, e) {
    return super.copy(t, e), this.groundColor.copy(t.groundColor), this;
  }
}
const Yu = /* @__PURE__ */ new Vt(), xm = /* @__PURE__ */ new E(), vm = /* @__PURE__ */ new E();
class sf {
  /**
   * Constructs a new light shadow.
   *
   * @param {Camera} camera - The light's view of the world.
   */
  constructor(t) {
    this.camera = t, this.intensity = 1, this.bias = 0, this.normalBias = 0, this.radius = 1, this.blurSamples = 8, this.mapSize = new J(512, 512), this.mapType = pn, this.map = null, this.mapPass = null, this.matrix = new Vt(), this.autoUpdate = !0, this.needsUpdate = !1, this._frustum = new Ea(), this._frameExtents = new J(1, 1), this._viewportCount = 1, this._viewports = [
      new Qt(0, 0, 1, 1)
    ];
  }
  /**
   * Used internally by the renderer to get the number of viewports that need
   * to be rendered for this shadow.
   *
   * @return {number} The viewport count.
   */
  getViewportCount() {
    return this._viewportCount;
  }
  /**
   * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
   *
   * @return {Frustum} The shadow camera frustum.
   */
  getFrustum() {
    return this._frustum;
  }
  /**
   * Update the matrices for the camera and shadow, used internally by the renderer.
   *
   * @param {Light} light - The light for which the shadow is being rendered.
   */
  updateMatrices(t) {
    const e = this.camera, i = this.matrix;
    xm.setFromMatrixPosition(t.matrixWorld), e.position.copy(xm), vm.setFromMatrixPosition(t.target.matrixWorld), e.lookAt(vm), e.updateMatrixWorld(), Yu.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse), this._frustum.setFromProjectionMatrix(Yu, e.coordinateSystem, e.reversedDepth), e.reversedDepth ? i.set(
      0.5,
      0,
      0,
      0.5,
      0,
      0.5,
      0,
      0.5,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ) : i.set(
      0.5,
      0,
      0,
      0.5,
      0,
      0.5,
      0,
      0.5,
      0,
      0,
      0.5,
      0.5,
      0,
      0,
      0,
      1
    ), i.multiply(Yu);
  }
  /**
   * Returns a viewport definition for the given viewport index.
   *
   * @param {number} viewportIndex - The viewport index.
   * @return {Vector4} The viewport.
   */
  getViewport(t) {
    return this._viewports[t];
  }
  /**
   * Returns the frame extends.
   *
   * @return {Vector2} The frame extends.
   */
  getFrameExtents() {
    return this._frameExtents;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.map && this.map.dispose(), this.mapPass && this.mapPass.dispose();
  }
  /**
   * Copies the values of the given light shadow instance to this instance.
   *
   * @param {LightShadow} source - The light shadow to copy.
   * @return {LightShadow} A reference to this light shadow instance.
   */
  copy(t) {
    return this.camera = t.camera.clone(), this.intensity = t.intensity, this.bias = t.bias, this.radius = t.radius, this.autoUpdate = t.autoUpdate, this.needsUpdate = t.needsUpdate, this.normalBias = t.normalBias, this.blurSamples = t.blurSamples, this.mapSize.copy(t.mapSize), this;
  }
  /**
   * Returns a new light shadow instance with copied values from this instance.
   *
   * @return {LightShadow} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Serializes the light shadow into JSON.
   *
   * @return {Object} A JSON object representing the serialized light shadow.
   * @see {@link ObjectLoader#parse}
   */
  toJSON() {
    const t = {};
    return this.intensity !== 1 && (t.intensity = this.intensity), this.bias !== 0 && (t.bias = this.bias), this.normalBias !== 0 && (t.normalBias = this.normalBias), this.radius !== 1 && (t.radius = this.radius), (this.mapSize.x !== 512 || this.mapSize.y !== 512) && (t.mapSize = this.mapSize.toArray()), t.camera = this.camera.toJSON(!1).object, delete t.camera.matrix, t;
  }
}
class Wb extends sf {
  /**
   * Constructs a new spot light shadow.
   */
  constructor() {
    super(new Ve(50, 1, 0.5, 500)), this.isSpotLightShadow = !0, this.focus = 1, this.aspect = 1;
  }
  updateMatrices(t) {
    const e = this.camera, i = ya * 2 * t.angle * this.focus, n = this.mapSize.width / this.mapSize.height * this.aspect, s = t.distance || e.far;
    (i !== e.fov || n !== e.aspect || s !== e.far) && (e.fov = i, e.aspect = n, e.far = s, e.updateProjectionMatrix()), super.updateMatrices(t);
  }
  copy(t) {
    return super.copy(t), this.focus = t.focus, this;
  }
}
class o_ extends Fs {
  /**
   * Constructs a new spot light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
   * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
   * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
   * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
   * @param {number} [decay=2] - The amount the light dims along the distance of the light.
   */
  constructor(t, e, i = 0, n = Math.PI / 3, s = 0, r = 2) {
    super(t, e), this.isSpotLight = !0, this.type = "SpotLight", this.position.copy(le.DEFAULT_UP), this.updateMatrix(), this.target = new le(), this.distance = i, this.angle = n, this.penumbra = s, this.decay = r, this.map = null, this.shadow = new Wb();
  }
  /**
   * The light's power. Power is the luminous power of the light measured in lumens (lm).
   *  Changing the power will also change the light's intensity.
   *
   * @type {number}
   */
  get power() {
    return this.intensity * Math.PI;
  }
  set power(t) {
    this.intensity = t / Math.PI;
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(t, e) {
    return super.copy(t, e), this.distance = t.distance, this.angle = t.angle, this.penumbra = t.penumbra, this.decay = t.decay, this.target = t.target.clone(), this.shadow = t.shadow.clone(), this;
  }
}
const bm = /* @__PURE__ */ new Vt(), Xa = /* @__PURE__ */ new E(), Zu = /* @__PURE__ */ new E();
class qb extends sf {
  /**
   * Constructs a new point light shadow.
   */
  constructor() {
    super(new Ve(90, 1, 0.5, 500)), this.isPointLightShadow = !0, this._frameExtents = new J(4, 2), this._viewportCount = 6, this._viewports = [
      // These viewports map a cube-map onto a 2D texture with the
      // following orientation:
      //
      //  xzXZ
      //   y Y
      //
      // X - Positive x direction
      // x - Negative x direction
      // Y - Positive y direction
      // y - Negative y direction
      // Z - Positive z direction
      // z - Negative z direction
      // positive X
      new Qt(2, 1, 1, 1),
      // negative X
      new Qt(0, 1, 1, 1),
      // positive Z
      new Qt(3, 1, 1, 1),
      // negative Z
      new Qt(1, 1, 1, 1),
      // positive Y
      new Qt(3, 0, 1, 1),
      // negative Y
      new Qt(1, 0, 1, 1)
    ], this._cubeDirections = [
      new E(1, 0, 0),
      new E(-1, 0, 0),
      new E(0, 0, 1),
      new E(0, 0, -1),
      new E(0, 1, 0),
      new E(0, -1, 0)
    ], this._cubeUps = [
      new E(0, 1, 0),
      new E(0, 1, 0),
      new E(0, 1, 0),
      new E(0, 1, 0),
      new E(0, 0, 1),
      new E(0, 0, -1)
    ];
  }
  /**
   * Update the matrices for the camera and shadow, used internally by the renderer.
   *
   * @param {Light} light - The light for which the shadow is being rendered.
   * @param {number} [viewportIndex=0] - The viewport index.
   */
  updateMatrices(t, e = 0) {
    const i = this.camera, n = this.matrix, s = t.distance || i.far;
    s !== i.far && (i.far = s, i.updateProjectionMatrix()), Xa.setFromMatrixPosition(t.matrixWorld), i.position.copy(Xa), Zu.copy(i.position), Zu.add(this._cubeDirections[e]), i.up.copy(this._cubeUps[e]), i.lookAt(Zu), i.updateMatrixWorld(), n.makeTranslation(-Xa.x, -Xa.y, -Xa.z), bm.multiplyMatrices(i.projectionMatrix, i.matrixWorldInverse), this._frustum.setFromProjectionMatrix(bm, i.coordinateSystem, i.reversedDepth);
  }
}
class l_ extends Fs {
  /**
   * Constructs a new point light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
   * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
   * @param {number} [decay=2] - The amount the light dims along the distance of the light.
   */
  constructor(t, e, i = 0, n = 2) {
    super(t, e), this.isPointLight = !0, this.type = "PointLight", this.distance = i, this.decay = n, this.shadow = new qb();
  }
  /**
   * The light's power. Power is the luminous power of the light measured in lumens (lm).
   * Changing the power will also change the light's intensity.
   *
   * @type {number}
   */
  get power() {
    return this.intensity * 4 * Math.PI;
  }
  set power(t) {
    this.intensity = t / (4 * Math.PI);
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(t, e) {
    return super.copy(t, e), this.distance = t.distance, this.decay = t.decay, this.shadow = t.shadow.clone(), this;
  }
}
class Ia extends kc {
  /**
   * Constructs a new orthographic camera.
   *
   * @param {number} [left=-1] - The left plane of the camera's frustum.
   * @param {number} [right=1] - The right plane of the camera's frustum.
   * @param {number} [top=1] - The top plane of the camera's frustum.
   * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
   * @param {number} [near=0.1] - The camera's near plane.
   * @param {number} [far=2000] - The camera's far plane.
   */
  constructor(t = -1, e = 1, i = 1, n = -1, s = 0.1, r = 2e3) {
    super(), this.isOrthographicCamera = !0, this.type = "OrthographicCamera", this.zoom = 1, this.view = null, this.left = t, this.right = e, this.top = i, this.bottom = n, this.near = s, this.far = r, this.updateProjectionMatrix();
  }
  copy(t, e) {
    return super.copy(t, e), this.left = t.left, this.right = t.right, this.top = t.top, this.bottom = t.bottom, this.near = t.near, this.far = t.far, this.zoom = t.zoom, this.view = t.view === null ? null : Object.assign({}, t.view), this;
  }
  /**
   * Sets an offset in a larger frustum. This is useful for multi-window or
   * multi-monitor/multi-machine setups.
   *
   * @param {number} fullWidth - The full width of multiview setup.
   * @param {number} fullHeight - The full height of multiview setup.
   * @param {number} x - The horizontal offset of the subcamera.
   * @param {number} y - The vertical offset of the subcamera.
   * @param {number} width - The width of subcamera.
   * @param {number} height - The height of subcamera.
   * @see {@link PerspectiveCamera#setViewOffset}
   */
  setViewOffset(t, e, i, n, s, r) {
    this.view === null && (this.view = {
      enabled: !0,
      fullWidth: 1,
      fullHeight: 1,
      offsetX: 0,
      offsetY: 0,
      width: 1,
      height: 1
    }), this.view.enabled = !0, this.view.fullWidth = t, this.view.fullHeight = e, this.view.offsetX = i, this.view.offsetY = n, this.view.width = s, this.view.height = r, this.updateProjectionMatrix();
  }
  /**
   * Removes the view offset from the projection matrix.
   */
  clearViewOffset() {
    this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix();
  }
  /**
   * Updates the camera's projection matrix. Must be called after any change of
   * camera properties.
   */
  updateProjectionMatrix() {
    const t = (this.right - this.left) / (2 * this.zoom), e = (this.top - this.bottom) / (2 * this.zoom), i = (this.right + this.left) / 2, n = (this.top + this.bottom) / 2;
    let s = i - t, r = i + t, o = n + e, l = n - e;
    if (this.view !== null && this.view.enabled) {
      const h = (this.right - this.left) / this.view.fullWidth / this.zoom, c = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
      s += h * this.view.offsetX, r = s + h * this.view.width, o -= c * this.view.offsetY, l = o - c * this.view.height;
    }
    this.projectionMatrix.makeOrthographic(s, r, o, l, this.near, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.object.zoom = this.zoom, e.object.left = this.left, e.object.right = this.right, e.object.top = this.top, e.object.bottom = this.bottom, e.object.near = this.near, e.object.far = this.far, this.view !== null && (e.object.view = Object.assign({}, this.view)), e;
  }
}
class $b extends sf {
  /**
   * Constructs a new directional light shadow.
   */
  constructor() {
    super(new Ia(-5, 5, 5, -5, 0.5, 500)), this.isDirectionalLightShadow = !0;
  }
}
class rf extends Fs {
  /**
   * Constructs a new directional light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(t, e) {
    super(t, e), this.isDirectionalLight = !0, this.type = "DirectionalLight", this.position.copy(le.DEFAULT_UP), this.updateMatrix(), this.target = new le(), this.shadow = new $b();
  }
  dispose() {
    this.shadow.dispose();
  }
  copy(t) {
    return super.copy(t), this.target = t.target.clone(), this.shadow = t.shadow.clone(), this;
  }
}
class af extends Fs {
  /**
   * Constructs a new ambient light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(t, e) {
    super(t, e), this.isAmbientLight = !0, this.type = "AmbientLight";
  }
}
class h_ extends Fs {
  /**
   * Constructs a new area light.
   *
   * @param {(number|Color|string)} [color=0xffffff] - The light's color.
   * @param {number} [intensity=1] - The light's strength/intensity.
   * @param {number} [width=10] - The width of the light.
   * @param {number} [height=10] - The height of the light.
   */
  constructor(t, e, i = 10, n = 10) {
    super(t, e), this.isRectAreaLight = !0, this.type = "RectAreaLight", this.width = i, this.height = n;
  }
  /**
   * The light's power. Power is the luminous power of the light measured in lumens (lm).
   * Changing the power will also change the light's intensity.
   *
   * @type {number}
   */
  get power() {
    return this.intensity * this.width * this.height * Math.PI;
  }
  set power(t) {
    this.intensity = t / (this.width * this.height * Math.PI);
  }
  copy(t) {
    return super.copy(t), this.width = t.width, this.height = t.height, this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.object.width = this.width, e.object.height = this.height, e;
  }
}
class c_ {
  /**
   * Constructs a new spherical harmonics.
   */
  constructor() {
    this.isSphericalHarmonics3 = !0, this.coefficients = [];
    for (let t = 0; t < 9; t++)
      this.coefficients.push(new E());
  }
  /**
   * Sets the given SH coefficients to this instance by copying
   * the values.
   *
   * @param {Array<Vector3>} coefficients - The SH coefficients.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  set(t) {
    for (let e = 0; e < 9; e++)
      this.coefficients[e].copy(t[e]);
    return this;
  }
  /**
   * Sets all SH coefficients to `0`.
   *
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  zero() {
    for (let t = 0; t < 9; t++)
      this.coefficients[t].set(0, 0, 0);
    return this;
  }
  /**
   * Returns the radiance in the direction of the given normal.
   *
   * @param {Vector3} normal - The normal vector (assumed to be unit length)
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The radiance.
   */
  getAt(t, e) {
    const i = t.x, n = t.y, s = t.z, r = this.coefficients;
    return e.copy(r[0]).multiplyScalar(0.282095), e.addScaledVector(r[1], 0.488603 * n), e.addScaledVector(r[2], 0.488603 * s), e.addScaledVector(r[3], 0.488603 * i), e.addScaledVector(r[4], 1.092548 * (i * n)), e.addScaledVector(r[5], 1.092548 * (n * s)), e.addScaledVector(r[6], 0.315392 * (3 * s * s - 1)), e.addScaledVector(r[7], 1.092548 * (i * s)), e.addScaledVector(r[8], 0.546274 * (i * i - n * n)), e;
  }
  /**
   * Returns the irradiance (radiance convolved with cosine lobe) in the
   * direction of the given normal.
   *
   * @param {Vector3} normal - The normal vector (assumed to be unit length)
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The irradiance.
   */
  getIrradianceAt(t, e) {
    const i = t.x, n = t.y, s = t.z, r = this.coefficients;
    return e.copy(r[0]).multiplyScalar(0.886227), e.addScaledVector(r[1], 2 * 0.511664 * n), e.addScaledVector(r[2], 2 * 0.511664 * s), e.addScaledVector(r[3], 2 * 0.511664 * i), e.addScaledVector(r[4], 2 * 0.429043 * i * n), e.addScaledVector(r[5], 2 * 0.429043 * n * s), e.addScaledVector(r[6], 0.743125 * s * s - 0.247708), e.addScaledVector(r[7], 2 * 0.429043 * i * s), e.addScaledVector(r[8], 0.429043 * (i * i - n * n)), e;
  }
  /**
   * Adds the given SH to this instance.
   *
   * @param {SphericalHarmonics3} sh - The SH to add.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  add(t) {
    for (let e = 0; e < 9; e++)
      this.coefficients[e].add(t.coefficients[e]);
    return this;
  }
  /**
   * A convenience method for performing {@link SphericalHarmonics3#add} and
   * {@link SphericalHarmonics3#scale} at once.
   *
   * @param {SphericalHarmonics3} sh - The SH to add.
   * @param {number} s - The scale factor.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  addScaledSH(t, e) {
    for (let i = 0; i < 9; i++)
      this.coefficients[i].addScaledVector(t.coefficients[i], e);
    return this;
  }
  /**
   * Scales this SH by the given scale factor.
   *
   * @param {number} s - The scale factor.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  scale(t) {
    for (let e = 0; e < 9; e++)
      this.coefficients[e].multiplyScalar(t);
    return this;
  }
  /**
   * Linear interpolates between the given SH and this instance by the given
   * alpha factor.
   *
   * @param {SphericalHarmonics3} sh - The SH to interpolate with.
   * @param {number} alpha - The alpha factor.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  lerp(t, e) {
    for (let i = 0; i < 9; i++)
      this.coefficients[i].lerp(t.coefficients[i], e);
    return this;
  }
  /**
   * Returns `true` if this spherical harmonics is equal with the given one.
   *
   * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
   * @return {boolean} Whether this spherical harmonics is equal with the given one.
   */
  equals(t) {
    for (let e = 0; e < 9; e++)
      if (!this.coefficients[e].equals(t.coefficients[e]))
        return !1;
    return !0;
  }
  /**
   * Copies the values of the given spherical harmonics to this instance.
   *
   * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
   * @return {SphericalHarmonics3} A reference to this spherical harmonics.
   */
  copy(t) {
    return this.set(t.coefficients);
  }
  /**
   * Returns a new spherical harmonics with copied values from this instance.
   *
   * @return {SphericalHarmonics3} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Sets the SH coefficients of this instance from the given array.
   *
   * @param {Array<number>} array - An array holding the SH coefficients.
   * @param {number} [offset=0] - The array offset where to start copying.
   * @return {SphericalHarmonics3} A clone of this instance.
   */
  fromArray(t, e = 0) {
    const i = this.coefficients;
    for (let n = 0; n < 9; n++)
      i[n].fromArray(t, e + n * 3);
    return this;
  }
  /**
   * Returns an array with the SH coefficients, or copies them into the provided
   * array. The coefficients are represented as numbers.
   *
   * @param {Array<number>} [array=[]] - The target array.
   * @param {number} [offset=0] - The array offset where to start copying.
   * @return {Array<number>} An array with flat SH coefficients.
   */
  toArray(t = [], e = 0) {
    const i = this.coefficients;
    for (let n = 0; n < 9; n++)
      i[n].toArray(t, e + n * 3);
    return t;
  }
  /**
   * Computes the SH basis for the given normal vector.
   *
   * @param {Vector3} normal - The normal.
   * @param {Array<number>} shBasis - The target array holding the SH basis.
   */
  static getBasisAt(t, e) {
    const i = t.x, n = t.y, s = t.z;
    e[0] = 0.282095, e[1] = 0.488603 * n, e[2] = 0.488603 * s, e[3] = 0.488603 * i, e[4] = 1.092548 * i * n, e[5] = 1.092548 * n * s, e[6] = 0.315392 * (3 * s * s - 1), e[7] = 1.092548 * i * s, e[8] = 0.546274 * (i * i - n * n);
  }
}
class u_ extends Fs {
  /**
   * Constructs a new light probe.
   *
   * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
   * @param {number} [intensity=1] - The light's strength/intensity.
   */
  constructor(t = new c_(), e = 1) {
    super(void 0, e), this.isLightProbe = !0, this.sh = t;
  }
  copy(t) {
    return super.copy(t), this.sh.copy(t.sh), this;
  }
  /**
   * Deserializes the light prove from the given JSON.
   *
   * @param {Object} json - The JSON holding the serialized light probe.
   * @return {LightProbe} A reference to this light probe.
   */
  fromJSON(t) {
    return this.intensity = t.intensity, this.sh.fromArray(t.sh), this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.object.sh = this.sh.toArray(), e;
  }
}
class au extends Ti {
  /**
   * Constructs a new material loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t), this.textures = {};
  }
  /**
   * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Material)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(t, e, i, n) {
    const s = this, r = new ss(s.manager);
    r.setPath(s.path), r.setRequestHeader(s.requestHeader), r.setWithCredentials(s.withCredentials), r.load(t, function(o) {
      try {
        e(s.parse(JSON.parse(o)));
      } catch (l) {
        n ? n(l) : console.error(l), s.manager.itemError(t);
      }
    }, i, n);
  }
  /**
   * Parses the given JSON object and returns a material.
   *
   * @param {Object} json - The serialized material.
   * @return {Material} The parsed material.
   */
  parse(t) {
    const e = this.textures;
    function i(s) {
      return e[s] === void 0 && console.warn("THREE.MaterialLoader: Undefined texture", s), e[s];
    }
    const n = this.createMaterialFromType(t.type);
    if (t.uuid !== void 0 && (n.uuid = t.uuid), t.name !== void 0 && (n.name = t.name), t.color !== void 0 && n.color !== void 0 && n.color.setHex(t.color), t.roughness !== void 0 && (n.roughness = t.roughness), t.metalness !== void 0 && (n.metalness = t.metalness), t.sheen !== void 0 && (n.sheen = t.sheen), t.sheenColor !== void 0 && (n.sheenColor = new ct().setHex(t.sheenColor)), t.sheenRoughness !== void 0 && (n.sheenRoughness = t.sheenRoughness), t.emissive !== void 0 && n.emissive !== void 0 && n.emissive.setHex(t.emissive), t.specular !== void 0 && n.specular !== void 0 && n.specular.setHex(t.specular), t.specularIntensity !== void 0 && (n.specularIntensity = t.specularIntensity), t.specularColor !== void 0 && n.specularColor !== void 0 && n.specularColor.setHex(t.specularColor), t.shininess !== void 0 && (n.shininess = t.shininess), t.clearcoat !== void 0 && (n.clearcoat = t.clearcoat), t.clearcoatRoughness !== void 0 && (n.clearcoatRoughness = t.clearcoatRoughness), t.dispersion !== void 0 && (n.dispersion = t.dispersion), t.iridescence !== void 0 && (n.iridescence = t.iridescence), t.iridescenceIOR !== void 0 && (n.iridescenceIOR = t.iridescenceIOR), t.iridescenceThicknessRange !== void 0 && (n.iridescenceThicknessRange = t.iridescenceThicknessRange), t.transmission !== void 0 && (n.transmission = t.transmission), t.thickness !== void 0 && (n.thickness = t.thickness), t.attenuationDistance !== void 0 && (n.attenuationDistance = t.attenuationDistance), t.attenuationColor !== void 0 && n.attenuationColor !== void 0 && n.attenuationColor.setHex(t.attenuationColor), t.anisotropy !== void 0 && (n.anisotropy = t.anisotropy), t.anisotropyRotation !== void 0 && (n.anisotropyRotation = t.anisotropyRotation), t.fog !== void 0 && (n.fog = t.fog), t.flatShading !== void 0 && (n.flatShading = t.flatShading), t.blending !== void 0 && (n.blending = t.blending), t.combine !== void 0 && (n.combine = t.combine), t.side !== void 0 && (n.side = t.side), t.shadowSide !== void 0 && (n.shadowSide = t.shadowSide), t.opacity !== void 0 && (n.opacity = t.opacity), t.transparent !== void 0 && (n.transparent = t.transparent), t.alphaTest !== void 0 && (n.alphaTest = t.alphaTest), t.alphaHash !== void 0 && (n.alphaHash = t.alphaHash), t.depthFunc !== void 0 && (n.depthFunc = t.depthFunc), t.depthTest !== void 0 && (n.depthTest = t.depthTest), t.depthWrite !== void 0 && (n.depthWrite = t.depthWrite), t.colorWrite !== void 0 && (n.colorWrite = t.colorWrite), t.blendSrc !== void 0 && (n.blendSrc = t.blendSrc), t.blendDst !== void 0 && (n.blendDst = t.blendDst), t.blendEquation !== void 0 && (n.blendEquation = t.blendEquation), t.blendSrcAlpha !== void 0 && (n.blendSrcAlpha = t.blendSrcAlpha), t.blendDstAlpha !== void 0 && (n.blendDstAlpha = t.blendDstAlpha), t.blendEquationAlpha !== void 0 && (n.blendEquationAlpha = t.blendEquationAlpha), t.blendColor !== void 0 && n.blendColor !== void 0 && n.blendColor.setHex(t.blendColor), t.blendAlpha !== void 0 && (n.blendAlpha = t.blendAlpha), t.stencilWriteMask !== void 0 && (n.stencilWriteMask = t.stencilWriteMask), t.stencilFunc !== void 0 && (n.stencilFunc = t.stencilFunc), t.stencilRef !== void 0 && (n.stencilRef = t.stencilRef), t.stencilFuncMask !== void 0 && (n.stencilFuncMask = t.stencilFuncMask), t.stencilFail !== void 0 && (n.stencilFail = t.stencilFail), t.stencilZFail !== void 0 && (n.stencilZFail = t.stencilZFail), t.stencilZPass !== void 0 && (n.stencilZPass = t.stencilZPass), t.stencilWrite !== void 0 && (n.stencilWrite = t.stencilWrite), t.wireframe !== void 0 && (n.wireframe = t.wireframe), t.wireframeLinewidth !== void 0 && (n.wireframeLinewidth = t.wireframeLinewidth), t.wireframeLinecap !== void 0 && (n.wireframeLinecap = t.wireframeLinecap), t.wireframeLinejoin !== void 0 && (n.wireframeLinejoin = t.wireframeLinejoin), t.rotation !== void 0 && (n.rotation = t.rotation), t.linewidth !== void 0 && (n.linewidth = t.linewidth), t.dashSize !== void 0 && (n.dashSize = t.dashSize), t.gapSize !== void 0 && (n.gapSize = t.gapSize), t.scale !== void 0 && (n.scale = t.scale), t.polygonOffset !== void 0 && (n.polygonOffset = t.polygonOffset), t.polygonOffsetFactor !== void 0 && (n.polygonOffsetFactor = t.polygonOffsetFactor), t.polygonOffsetUnits !== void 0 && (n.polygonOffsetUnits = t.polygonOffsetUnits), t.dithering !== void 0 && (n.dithering = t.dithering), t.alphaToCoverage !== void 0 && (n.alphaToCoverage = t.alphaToCoverage), t.premultipliedAlpha !== void 0 && (n.premultipliedAlpha = t.premultipliedAlpha), t.forceSinglePass !== void 0 && (n.forceSinglePass = t.forceSinglePass), t.visible !== void 0 && (n.visible = t.visible), t.toneMapped !== void 0 && (n.toneMapped = t.toneMapped), t.userData !== void 0 && (n.userData = t.userData), t.vertexColors !== void 0 && (typeof t.vertexColors == "number" ? n.vertexColors = t.vertexColors > 0 : n.vertexColors = t.vertexColors), t.uniforms !== void 0)
      for (const s in t.uniforms) {
        const r = t.uniforms[s];
        switch (n.uniforms[s] = {}, r.type) {
          case "t":
            n.uniforms[s].value = i(r.value);
            break;
          case "c":
            n.uniforms[s].value = new ct().setHex(r.value);
            break;
          case "v2":
            n.uniforms[s].value = new J().fromArray(r.value);
            break;
          case "v3":
            n.uniforms[s].value = new E().fromArray(r.value);
            break;
          case "v4":
            n.uniforms[s].value = new Qt().fromArray(r.value);
            break;
          case "m3":
            n.uniforms[s].value = new Xt().fromArray(r.value);
            break;
          case "m4":
            n.uniforms[s].value = new Vt().fromArray(r.value);
            break;
          default:
            n.uniforms[s].value = r.value;
        }
      }
    if (t.defines !== void 0 && (n.defines = t.defines), t.vertexShader !== void 0 && (n.vertexShader = t.vertexShader), t.fragmentShader !== void 0 && (n.fragmentShader = t.fragmentShader), t.glslVersion !== void 0 && (n.glslVersion = t.glslVersion), t.extensions !== void 0)
      for (const s in t.extensions)
        n.extensions[s] = t.extensions[s];
    if (t.lights !== void 0 && (n.lights = t.lights), t.clipping !== void 0 && (n.clipping = t.clipping), t.size !== void 0 && (n.size = t.size), t.sizeAttenuation !== void 0 && (n.sizeAttenuation = t.sizeAttenuation), t.map !== void 0 && (n.map = i(t.map)), t.matcap !== void 0 && (n.matcap = i(t.matcap)), t.alphaMap !== void 0 && (n.alphaMap = i(t.alphaMap)), t.bumpMap !== void 0 && (n.bumpMap = i(t.bumpMap)), t.bumpScale !== void 0 && (n.bumpScale = t.bumpScale), t.normalMap !== void 0 && (n.normalMap = i(t.normalMap)), t.normalMapType !== void 0 && (n.normalMapType = t.normalMapType), t.normalScale !== void 0) {
      let s = t.normalScale;
      Array.isArray(s) === !1 && (s = [s, s]), n.normalScale = new J().fromArray(s);
    }
    return t.displacementMap !== void 0 && (n.displacementMap = i(t.displacementMap)), t.displacementScale !== void 0 && (n.displacementScale = t.displacementScale), t.displacementBias !== void 0 && (n.displacementBias = t.displacementBias), t.roughnessMap !== void 0 && (n.roughnessMap = i(t.roughnessMap)), t.metalnessMap !== void 0 && (n.metalnessMap = i(t.metalnessMap)), t.emissiveMap !== void 0 && (n.emissiveMap = i(t.emissiveMap)), t.emissiveIntensity !== void 0 && (n.emissiveIntensity = t.emissiveIntensity), t.specularMap !== void 0 && (n.specularMap = i(t.specularMap)), t.specularIntensityMap !== void 0 && (n.specularIntensityMap = i(t.specularIntensityMap)), t.specularColorMap !== void 0 && (n.specularColorMap = i(t.specularColorMap)), t.envMap !== void 0 && (n.envMap = i(t.envMap)), t.envMapRotation !== void 0 && n.envMapRotation.fromArray(t.envMapRotation), t.envMapIntensity !== void 0 && (n.envMapIntensity = t.envMapIntensity), t.reflectivity !== void 0 && (n.reflectivity = t.reflectivity), t.refractionRatio !== void 0 && (n.refractionRatio = t.refractionRatio), t.lightMap !== void 0 && (n.lightMap = i(t.lightMap)), t.lightMapIntensity !== void 0 && (n.lightMapIntensity = t.lightMapIntensity), t.aoMap !== void 0 && (n.aoMap = i(t.aoMap)), t.aoMapIntensity !== void 0 && (n.aoMapIntensity = t.aoMapIntensity), t.gradientMap !== void 0 && (n.gradientMap = i(t.gradientMap)), t.clearcoatMap !== void 0 && (n.clearcoatMap = i(t.clearcoatMap)), t.clearcoatRoughnessMap !== void 0 && (n.clearcoatRoughnessMap = i(t.clearcoatRoughnessMap)), t.clearcoatNormalMap !== void 0 && (n.clearcoatNormalMap = i(t.clearcoatNormalMap)), t.clearcoatNormalScale !== void 0 && (n.clearcoatNormalScale = new J().fromArray(t.clearcoatNormalScale)), t.iridescenceMap !== void 0 && (n.iridescenceMap = i(t.iridescenceMap)), t.iridescenceThicknessMap !== void 0 && (n.iridescenceThicknessMap = i(t.iridescenceThicknessMap)), t.transmissionMap !== void 0 && (n.transmissionMap = i(t.transmissionMap)), t.thicknessMap !== void 0 && (n.thicknessMap = i(t.thicknessMap)), t.anisotropyMap !== void 0 && (n.anisotropyMap = i(t.anisotropyMap)), t.sheenColorMap !== void 0 && (n.sheenColorMap = i(t.sheenColorMap)), t.sheenRoughnessMap !== void 0 && (n.sheenRoughnessMap = i(t.sheenRoughnessMap)), n;
  }
  /**
   * Textures are not embedded in the material JSON so they have
   * to be injected before the loading process starts.
   *
   * @param {Object} value - A dictionary holding textures for material properties.
   * @return {MaterialLoader} A reference to this material loader.
   */
  setTextures(t) {
    return this.textures = t, this;
  }
  /**
   * Creates a material for the given type.
   *
   * @param {string} type - The material type.
   * @return {Material} The new material.
   */
  createMaterialFromType(t) {
    return au.createMaterialFromType(t);
  }
  /**
   * Creates a material for the given type.
   *
   * @static
   * @param {string} type - The material type.
   * @return {Material} The new material.
   */
  static createMaterialFromType(t) {
    const e = {
      ShadowMaterial: $y,
      SpriteMaterial: Wc,
      RawShaderMaterial: Xy,
      ShaderMaterial: Xi,
      PointsMaterial: Xc,
      MeshPhysicalMaterial: Yy,
      MeshStandardMaterial: hr,
      MeshPhongMaterial: Zy,
      MeshToonMaterial: jy,
      MeshNormalMaterial: Jy,
      MeshLambertMaterial: Ky,
      MeshDepthMaterial: jp,
      MeshDistanceMaterial: Jp,
      MeshBasicMaterial: li,
      MeshMatcapMaterial: Qy,
      LineDashedMaterial: Kp,
      LineBasicMaterial: Pe,
      Material: hi
    };
    return new e[t]();
  }
}
class rp {
  /**
   * Extracts the base URL from the given URL.
   *
   * @param {string} url -The URL to extract the base URL from.
   * @return {string} The extracted base URL.
   */
  static extractUrlBase(t) {
    const e = t.lastIndexOf("/");
    return e === -1 ? "./" : t.slice(0, e + 1);
  }
  /**
   * Resolves relative URLs against the given path. Absolute paths, data urls,
   * and blob URLs will be returned as is. Invalid URLs will return an empty
   * string.
   *
   * @param {string} url -The URL to resolve.
   * @param {string} path - The base path for relative URLs to be resolved against.
   * @return {string} The resolved URL.
   */
  static resolveURL(t, e) {
    return typeof t != "string" || t === "" ? "" : (/^https?:\/\//i.test(e) && /^\//.test(t) && (e = e.replace(/(^https?:\/\/[^\/]+).*/i, "$1")), /^(https?:)?\/\//i.test(t) || /^data:.*,.*$/i.test(t) || /^blob:.*$/i.test(t) ? t : e + t);
  }
}
let ou = class extends Ht {
  /**
   * Constructs a new instanced buffer geometry.
   */
  constructor() {
    super(), this.isInstancedBufferGeometry = !0, this.type = "InstancedBufferGeometry", this.instanceCount = 1 / 0;
  }
  copy(t) {
    return super.copy(t), this.instanceCount = t.instanceCount, this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.instanceCount = this.instanceCount, t.isInstancedBufferGeometry = !0, t;
  }
};
class d_ extends Ti {
  /**
   * Constructs a new geometry loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(t, e, i, n) {
    const s = this, r = new ss(s.manager);
    r.setPath(s.path), r.setRequestHeader(s.requestHeader), r.setWithCredentials(s.withCredentials), r.load(t, function(o) {
      try {
        e(s.parse(JSON.parse(o)));
      } catch (l) {
        n ? n(l) : console.error(l), s.manager.itemError(t);
      }
    }, i, n);
  }
  /**
   * Parses the given JSON object and returns a geometry.
   *
   * @param {Object} json - The serialized geometry.
   * @return {BufferGeometry} The parsed geometry.
   */
  parse(t) {
    const e = {}, i = {};
    function n(p, f) {
      if (e[f] !== void 0) return e[f];
      const g = p.interleavedBuffers[f], m = s(p, g.buffer), v = ra(g.type, m), x = new Gc(v, g.stride);
      return x.uuid = g.uuid, e[f] = x, x;
    }
    function s(p, f) {
      if (i[f] !== void 0) return i[f];
      const g = p.arrayBuffers[f], m = new Uint32Array(g).buffer;
      return i[f] = m, m;
    }
    const r = t.isInstancedBufferGeometry ? new ou() : new Ht(), o = t.data.index;
    if (o !== void 0) {
      const p = ra(o.type, o.array);
      r.setIndex(new ie(p, 1));
    }
    const l = t.data.attributes;
    for (const p in l) {
      const f = l[p];
      let y;
      if (f.isInterleavedBufferAttribute) {
        const g = n(t.data, f.data);
        y = new un(g, f.itemSize, f.offset, f.normalized);
      } else {
        const g = ra(f.type, f.array), m = f.isInstancedBufferAttribute ? xa : ie;
        y = new m(g, f.itemSize, f.normalized);
      }
      f.name !== void 0 && (y.name = f.name), f.usage !== void 0 && y.setUsage(f.usage), r.setAttribute(p, y);
    }
    const h = t.data.morphAttributes;
    if (h)
      for (const p in h) {
        const f = h[p], y = [];
        for (let g = 0, m = f.length; g < m; g++) {
          const v = f[g];
          let x;
          if (v.isInterleavedBufferAttribute) {
            const _ = n(t.data, v.data);
            x = new un(_, v.itemSize, v.offset, v.normalized);
          } else {
            const _ = ra(v.type, v.array);
            x = new ie(_, v.itemSize, v.normalized);
          }
          v.name !== void 0 && (x.name = v.name), y.push(x);
        }
        r.morphAttributes[p] = y;
      }
    t.data.morphTargetsRelative && (r.morphTargetsRelative = !0);
    const u = t.data.groups || t.data.drawcalls || t.data.offsets;
    if (u !== void 0)
      for (let p = 0, f = u.length; p !== f; ++p) {
        const y = u[p];
        r.addGroup(y.start, y.count, y.materialIndex);
      }
    const d = t.data.boundingSphere;
    return d !== void 0 && (r.boundingSphere = new Re().fromJSON(d)), t.name && (r.name = t.name), t.userData && (r.userData = t.userData), r;
  }
}
class Xb extends Ti {
  /**
   * Constructs a new object loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(t, e, i, n) {
    const s = this, r = this.path === "" ? rp.extractUrlBase(t) : this.path;
    this.resourcePath = this.resourcePath || r;
    const o = new ss(this.manager);
    o.setPath(this.path), o.setRequestHeader(this.requestHeader), o.setWithCredentials(this.withCredentials), o.load(t, function(l) {
      let h = null;
      try {
        h = JSON.parse(l);
      } catch (u) {
        n !== void 0 && n(u), console.error("THREE:ObjectLoader: Can't parse " + t + ".", u.message);
        return;
      }
      const c = h.metadata;
      if (c === void 0 || c.type === void 0 || c.type.toLowerCase() === "geometry") {
        n !== void 0 && n(new Error("THREE.ObjectLoader: Can't load " + t)), console.error("THREE.ObjectLoader: Can't load " + t);
        return;
      }
      s.parse(h, e);
    }, i, n);
  }
  /**
   * Async version of {@link ObjectLoader#load}.
   *
   * @async
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
   */
  async loadAsync(t, e) {
    const i = this, n = this.path === "" ? rp.extractUrlBase(t) : this.path;
    this.resourcePath = this.resourcePath || n;
    const s = new ss(this.manager);
    s.setPath(this.path), s.setRequestHeader(this.requestHeader), s.setWithCredentials(this.withCredentials);
    const r = await s.loadAsync(t, e), o = JSON.parse(r), l = o.metadata;
    if (l === void 0 || l.type === void 0 || l.type.toLowerCase() === "geometry")
      throw new Error("THREE.ObjectLoader: Can't load " + t);
    return await i.parseAsync(o);
  }
  /**
   * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
   * but can also be used directly to parse a previously loaded JSON structure.
   *
   * @param {Object} json - The serialized 3D object.
   * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
   * @return {Object3D} The parsed 3D object.
   */
  parse(t, e) {
    const i = this.parseAnimations(t.animations), n = this.parseShapes(t.shapes), s = this.parseGeometries(t.geometries, n), r = this.parseImages(t.images, function() {
      e !== void 0 && e(h);
    }), o = this.parseTextures(t.textures, r), l = this.parseMaterials(t.materials, o), h = this.parseObject(t.object, s, l, o, i), c = this.parseSkeletons(t.skeletons, h);
    if (this.bindSkeletons(h, c), this.bindLightTargets(h), e !== void 0) {
      let u = !1;
      for (const d in r)
        if (r[d].data instanceof HTMLImageElement) {
          u = !0;
          break;
        }
      u === !1 && e(h);
    }
    return h;
  }
  /**
   * Async version of {@link ObjectLoader#parse}.
   *
   * @param {Object} json - The serialized 3D object.
   * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
   */
  async parseAsync(t) {
    const e = this.parseAnimations(t.animations), i = this.parseShapes(t.shapes), n = this.parseGeometries(t.geometries, i), s = await this.parseImagesAsync(t.images), r = this.parseTextures(t.textures, s), o = this.parseMaterials(t.materials, r), l = this.parseObject(t.object, n, o, r, e), h = this.parseSkeletons(t.skeletons, l);
    return this.bindSkeletons(l, h), this.bindLightTargets(l), l;
  }
  // internals
  parseShapes(t) {
    const e = {};
    if (t !== void 0)
      for (let i = 0, n = t.length; i < n; i++) {
        const s = new As().fromJSON(t[i]);
        e[s.uuid] = s;
      }
    return e;
  }
  parseSkeletons(t, e) {
    const i = {}, n = {};
    if (e.traverse(function(s) {
      s.isBone && (n[s.uuid] = s);
    }), t !== void 0)
      for (let s = 0, r = t.length; s < r; s++) {
        const o = new qc().fromJSON(t[s], n);
        i[o.uuid] = o;
      }
    return i;
  }
  parseGeometries(t, e) {
    const i = {};
    if (t !== void 0) {
      const n = new d_();
      for (let s = 0, r = t.length; s < r; s++) {
        let o;
        const l = t[s];
        switch (l.type) {
          case "BufferGeometry":
          case "InstancedBufferGeometry":
            o = n.parse(l);
            break;
          default:
            l.type in _m ? o = _m[l.type].fromJSON(l, e) : console.warn(`THREE.ObjectLoader: Unsupported geometry type "${l.type}"`);
        }
        o.uuid = l.uuid, l.name !== void 0 && (o.name = l.name), l.userData !== void 0 && (o.userData = l.userData), i[l.uuid] = o;
      }
    }
    return i;
  }
  parseMaterials(t, e) {
    const i = {}, n = {};
    if (t !== void 0) {
      const s = new au();
      s.setTextures(e);
      for (let r = 0, o = t.length; r < o; r++) {
        const l = t[r];
        i[l.uuid] === void 0 && (i[l.uuid] = s.parse(l)), n[l.uuid] = i[l.uuid];
      }
    }
    return n;
  }
  parseAnimations(t) {
    const e = {};
    if (t !== void 0)
      for (let i = 0; i < t.length; i++) {
        const n = t[i], s = Ma.parse(n);
        e[s.uuid] = s;
      }
    return e;
  }
  parseImages(t, e) {
    const i = this, n = {};
    let s;
    function r(l) {
      return i.manager.itemStart(l), s.load(l, function() {
        i.manager.itemEnd(l);
      }, void 0, function() {
        i.manager.itemError(l), i.manager.itemEnd(l);
      });
    }
    function o(l) {
      if (typeof l == "string") {
        const h = l, c = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(h) ? h : i.resourcePath + h;
        return r(c);
      } else
        return l.data ? {
          data: ra(l.type, l.data),
          width: l.width,
          height: l.height
        } : null;
    }
    if (t !== void 0 && t.length > 0) {
      const l = new nf(e);
      s = new Uo(l), s.setCrossOrigin(this.crossOrigin);
      for (let h = 0, c = t.length; h < c; h++) {
        const u = t[h], d = u.url;
        if (Array.isArray(d)) {
          const p = [];
          for (let f = 0, y = d.length; f < y; f++) {
            const g = d[f], m = o(g);
            m !== null && (m instanceof HTMLImageElement ? p.push(m) : p.push(new Cn(m.data, m.width, m.height)));
          }
          n[u.uuid] = new Ms(p);
        } else {
          const p = o(u.url);
          n[u.uuid] = new Ms(p);
        }
      }
    }
    return n;
  }
  async parseImagesAsync(t) {
    const e = this, i = {};
    let n;
    async function s(r) {
      if (typeof r == "string") {
        const o = r, l = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(o) ? o : e.resourcePath + o;
        return await n.loadAsync(l);
      } else
        return r.data ? {
          data: ra(r.type, r.data),
          width: r.width,
          height: r.height
        } : null;
    }
    if (t !== void 0 && t.length > 0) {
      n = new Uo(this.manager), n.setCrossOrigin(this.crossOrigin);
      for (let r = 0, o = t.length; r < o; r++) {
        const l = t[r], h = l.url;
        if (Array.isArray(h)) {
          const c = [];
          for (let u = 0, d = h.length; u < d; u++) {
            const p = h[u], f = await s(p);
            f !== null && (f instanceof HTMLImageElement ? c.push(f) : c.push(new Cn(f.data, f.width, f.height)));
          }
          i[l.uuid] = new Ms(c);
        } else {
          const c = await s(l.url);
          i[l.uuid] = new Ms(c);
        }
      }
    }
    return i;
  }
  parseTextures(t, e) {
    function i(s, r) {
      return typeof s == "number" ? s : (console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", s), r[s]);
    }
    const n = {};
    if (t !== void 0)
      for (let s = 0, r = t.length; s < r; s++) {
        const o = t[s];
        o.image === void 0 && console.warn('THREE.ObjectLoader: No "image" specified for', o.uuid), e[o.image] === void 0 && console.warn("THREE.ObjectLoader: Undefined image", o.image);
        const l = e[o.image], h = l.data;
        let c;
        Array.isArray(h) ? (c = new Oo(), h.length === 6 && (c.needsUpdate = !0)) : (h && h.data ? c = new Cn() : c = new Ne(), h && (c.needsUpdate = !0)), c.source = l, c.uuid = o.uuid, o.name !== void 0 && (c.name = o.name), o.mapping !== void 0 && (c.mapping = i(o.mapping, Yb)), o.channel !== void 0 && (c.channel = o.channel), o.offset !== void 0 && c.offset.fromArray(o.offset), o.repeat !== void 0 && c.repeat.fromArray(o.repeat), o.center !== void 0 && c.center.fromArray(o.center), o.rotation !== void 0 && (c.rotation = o.rotation), o.wrap !== void 0 && (c.wrapS = i(o.wrap[0], Mm), c.wrapT = i(o.wrap[1], Mm)), o.format !== void 0 && (c.format = o.format), o.internalFormat !== void 0 && (c.internalFormat = o.internalFormat), o.type !== void 0 && (c.type = o.type), o.colorSpace !== void 0 && (c.colorSpace = o.colorSpace), o.minFilter !== void 0 && (c.minFilter = i(o.minFilter, Sm)), o.magFilter !== void 0 && (c.magFilter = i(o.magFilter, Sm)), o.anisotropy !== void 0 && (c.anisotropy = o.anisotropy), o.flipY !== void 0 && (c.flipY = o.flipY), o.generateMipmaps !== void 0 && (c.generateMipmaps = o.generateMipmaps), o.premultiplyAlpha !== void 0 && (c.premultiplyAlpha = o.premultiplyAlpha), o.unpackAlignment !== void 0 && (c.unpackAlignment = o.unpackAlignment), o.compareFunction !== void 0 && (c.compareFunction = o.compareFunction), o.userData !== void 0 && (c.userData = o.userData), n[o.uuid] = c;
      }
    return n;
  }
  parseObject(t, e, i, n, s) {
    let r;
    function o(d) {
      return e[d] === void 0 && console.warn("THREE.ObjectLoader: Undefined geometry", d), e[d];
    }
    function l(d) {
      if (d !== void 0) {
        if (Array.isArray(d)) {
          const p = [];
          for (let f = 0, y = d.length; f < y; f++) {
            const g = d[f];
            i[g] === void 0 && console.warn("THREE.ObjectLoader: Undefined material", g), p.push(i[g]);
          }
          return p;
        }
        return i[d] === void 0 && console.warn("THREE.ObjectLoader: Undefined material", d), i[d];
      }
    }
    function h(d) {
      return n[d] === void 0 && console.warn("THREE.ObjectLoader: Undefined texture", d), n[d];
    }
    let c, u;
    switch (t.type) {
      case "Scene":
        r = new ko(), t.background !== void 0 && (Number.isInteger(t.background) ? r.background = new ct(t.background) : r.background = h(t.background)), t.environment !== void 0 && (r.environment = h(t.environment)), t.fog !== void 0 && (t.fog.type === "Fog" ? r.fog = new Hc(t.fog.color, t.fog.near, t.fog.far) : t.fog.type === "FogExp2" && (r.fog = new Vc(t.fog.color, t.fog.density)), t.fog.name !== "" && (r.fog.name = t.fog.name)), t.backgroundBlurriness !== void 0 && (r.backgroundBlurriness = t.backgroundBlurriness), t.backgroundIntensity !== void 0 && (r.backgroundIntensity = t.backgroundIntensity), t.backgroundRotation !== void 0 && r.backgroundRotation.fromArray(t.backgroundRotation), t.environmentIntensity !== void 0 && (r.environmentIntensity = t.environmentIntensity), t.environmentRotation !== void 0 && r.environmentRotation.fromArray(t.environmentRotation);
        break;
      case "PerspectiveCamera":
        r = new Ve(t.fov, t.aspect, t.near, t.far), t.focus !== void 0 && (r.focus = t.focus), t.zoom !== void 0 && (r.zoom = t.zoom), t.filmGauge !== void 0 && (r.filmGauge = t.filmGauge), t.filmOffset !== void 0 && (r.filmOffset = t.filmOffset), t.view !== void 0 && (r.view = Object.assign({}, t.view));
        break;
      case "OrthographicCamera":
        r = new Ia(t.left, t.right, t.top, t.bottom, t.near, t.far), t.zoom !== void 0 && (r.zoom = t.zoom), t.view !== void 0 && (r.view = Object.assign({}, t.view));
        break;
      case "AmbientLight":
        r = new af(t.color, t.intensity);
        break;
      case "DirectionalLight":
        r = new rf(t.color, t.intensity), r.target = t.target || "";
        break;
      case "PointLight":
        r = new l_(t.color, t.intensity, t.distance, t.decay);
        break;
      case "RectAreaLight":
        r = new h_(t.color, t.intensity, t.width, t.height);
        break;
      case "SpotLight":
        r = new o_(t.color, t.intensity, t.distance, t.angle, t.penumbra, t.decay), r.target = t.target || "";
        break;
      case "HemisphereLight":
        r = new a_(t.color, t.groundColor, t.intensity);
        break;
      case "LightProbe":
        r = new u_().fromJSON(t);
        break;
      case "SkinnedMesh":
        c = o(t.geometry), u = l(t.material), r = new Py(c, u), t.bindMode !== void 0 && (r.bindMode = t.bindMode), t.bindMatrix !== void 0 && r.bindMatrix.fromArray(t.bindMatrix), t.skeleton !== void 0 && (r.skeleton = t.skeleton);
        break;
      case "Mesh":
        c = o(t.geometry), u = l(t.material), r = new re(c, u);
        break;
      case "InstancedMesh":
        c = o(t.geometry), u = l(t.material);
        const d = t.count, p = t.instanceMatrix, f = t.instanceColor;
        r = new Iy(c, u, d), r.instanceMatrix = new xa(new Float32Array(p.array), 16), f !== void 0 && (r.instanceColor = new xa(new Float32Array(f.array), f.itemSize));
        break;
      case "BatchedMesh":
        c = o(t.geometry), u = l(t.material), r = new Ly(t.maxInstanceCount, t.maxVertexCount, t.maxIndexCount, u), r.geometry = c, r.perObjectFrustumCulled = t.perObjectFrustumCulled, r.sortObjects = t.sortObjects, r._drawRanges = t.drawRanges, r._reservedRanges = t.reservedRanges, r._geometryInfo = t.geometryInfo.map((y) => {
          let g = null, m = null;
          return y.boundingBox !== void 0 && (g = new we().fromJSON(y.boundingBox)), y.boundingSphere !== void 0 && (m = new Re().fromJSON(y.boundingSphere)), {
            ...y,
            boundingBox: g,
            boundingSphere: m
          };
        }), r._instanceInfo = t.instanceInfo, r._availableInstanceIds = t._availableInstanceIds, r._availableGeometryIds = t._availableGeometryIds, r._nextIndexStart = t.nextIndexStart, r._nextVertexStart = t.nextVertexStart, r._geometryCount = t.geometryCount, r._maxInstanceCount = t.maxInstanceCount, r._maxVertexCount = t.maxVertexCount, r._maxIndexCount = t.maxIndexCount, r._geometryInitialized = t.geometryInitialized, r._matricesTexture = h(t.matricesTexture.uuid), r._indirectTexture = h(t.indirectTexture.uuid), t.colorsTexture !== void 0 && (r._colorsTexture = h(t.colorsTexture.uuid)), t.boundingSphere !== void 0 && (r.boundingSphere = new Re().fromJSON(t.boundingSphere)), t.boundingBox !== void 0 && (r.boundingBox = new we().fromJSON(t.boundingBox));
        break;
      case "LOD":
        r = new Ry();
        break;
      case "Line":
        r = new Rs(o(t.geometry), l(t.material));
        break;
      case "LineLoop":
        r = new Dy(o(t.geometry), l(t.material));
        break;
      case "LineSegments":
        r = new oi(o(t.geometry), l(t.material));
        break;
      case "PointCloud":
      case "Points":
        r = new kp(o(t.geometry), l(t.material));
        break;
      case "Sprite":
        r = new mc(l(t.material));
        break;
      case "Group":
        r = new yi();
        break;
      case "Bone":
        r = new Op();
        break;
      default:
        r = new le();
    }
    if (r.uuid = t.uuid, t.name !== void 0 && (r.name = t.name), t.matrix !== void 0 ? (r.matrix.fromArray(t.matrix), t.matrixAutoUpdate !== void 0 && (r.matrixAutoUpdate = t.matrixAutoUpdate), r.matrixAutoUpdate && r.matrix.decompose(r.position, r.quaternion, r.scale)) : (t.position !== void 0 && r.position.fromArray(t.position), t.rotation !== void 0 && r.rotation.fromArray(t.rotation), t.quaternion !== void 0 && r.quaternion.fromArray(t.quaternion), t.scale !== void 0 && r.scale.fromArray(t.scale)), t.up !== void 0 && r.up.fromArray(t.up), t.castShadow !== void 0 && (r.castShadow = t.castShadow), t.receiveShadow !== void 0 && (r.receiveShadow = t.receiveShadow), t.shadow && (t.shadow.intensity !== void 0 && (r.shadow.intensity = t.shadow.intensity), t.shadow.bias !== void 0 && (r.shadow.bias = t.shadow.bias), t.shadow.normalBias !== void 0 && (r.shadow.normalBias = t.shadow.normalBias), t.shadow.radius !== void 0 && (r.shadow.radius = t.shadow.radius), t.shadow.mapSize !== void 0 && r.shadow.mapSize.fromArray(t.shadow.mapSize), t.shadow.camera !== void 0 && (r.shadow.camera = this.parseObject(t.shadow.camera))), t.visible !== void 0 && (r.visible = t.visible), t.frustumCulled !== void 0 && (r.frustumCulled = t.frustumCulled), t.renderOrder !== void 0 && (r.renderOrder = t.renderOrder), t.userData !== void 0 && (r.userData = t.userData), t.layers !== void 0 && (r.layers.mask = t.layers), t.children !== void 0) {
      const d = t.children;
      for (let p = 0; p < d.length; p++)
        r.add(this.parseObject(d[p], e, i, n, s));
    }
    if (t.animations !== void 0) {
      const d = t.animations;
      for (let p = 0; p < d.length; p++) {
        const f = d[p];
        r.animations.push(s[f]);
      }
    }
    if (t.type === "LOD") {
      t.autoUpdate !== void 0 && (r.autoUpdate = t.autoUpdate);
      const d = t.levels;
      for (let p = 0; p < d.length; p++) {
        const f = d[p], y = r.getObjectByProperty("uuid", f.object);
        y !== void 0 && r.addLevel(y, f.distance, f.hysteresis);
      }
    }
    return r;
  }
  bindSkeletons(t, e) {
    Object.keys(e).length !== 0 && t.traverse(function(i) {
      if (i.isSkinnedMesh === !0 && i.skeleton !== void 0) {
        const n = e[i.skeleton];
        n === void 0 ? console.warn("THREE.ObjectLoader: No skeleton found with UUID:", i.skeleton) : i.bind(n, i.bindMatrix);
      }
    });
  }
  bindLightTargets(t) {
    t.traverse(function(e) {
      if (e.isDirectionalLight || e.isSpotLight) {
        const i = e.target, n = t.getObjectByProperty("uuid", i);
        n !== void 0 ? e.target = n : e.target = new le();
      }
    });
  }
}
const Yb = {
  UVMapping: Cc,
  CubeReflectionMapping: is,
  CubeRefractionMapping: Ts,
  EquirectangularReflectionMapping: vo,
  EquirectangularRefractionMapping: bo,
  CubeUVReflectionMapping: Sa
}, Mm = {
  RepeatWrapping: Mo,
  ClampToEdgeWrapping: Si,
  MirroredRepeatWrapping: So
}, Sm = {
  NearestFilter: je,
  NearestMipmapNearestFilter: Sp,
  NearestMipmapLinearFilter: sa,
  LinearFilter: Ce,
  LinearMipmapNearestFilter: lo,
  LinearMipmapLinearFilter: En
}, ju = /* @__PURE__ */ new WeakMap();
class Zb extends Ti {
  /**
   * Constructs a new image bitmap loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t), this.isImageBitmapLoader = !0, typeof createImageBitmap > "u" && console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."), typeof fetch > "u" && console.warn("THREE.ImageBitmapLoader: fetch() not supported."), this.options = { premultiplyAlpha: "none" }, this._abortController = new AbortController();
  }
  /**
   * Sets the given loader options. The structure of the object must match the `options` parameter of
   * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
   *
   * @param {Object} options - The loader options to set.
   * @return {ImageBitmapLoader} A reference to this image bitmap loader.
   */
  setOptions(t) {
    return this.options = t, this;
  }
  /**
   * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Unsupported in this loader.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {ImageBitmap|undefined} The image bitmap.
   */
  load(t, e, i, n) {
    t === void 0 && (t = ""), this.path !== void 0 && (t = this.path + t), t = this.manager.resolveURL(t);
    const s = this, r = Tn.get(`image-bitmap:${t}`);
    if (r !== void 0) {
      if (s.manager.itemStart(t), r.then) {
        r.then((h) => {
          if (ju.has(r) === !0)
            n && n(ju.get(r)), s.manager.itemError(t), s.manager.itemEnd(t);
          else
            return e && e(h), s.manager.itemEnd(t), h;
        });
        return;
      }
      return setTimeout(function() {
        e && e(r), s.manager.itemEnd(t);
      }, 0), r;
    }
    const o = {};
    o.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include", o.headers = this.requestHeader, o.signal = typeof AbortSignal.any == "function" ? AbortSignal.any([this._abortController.signal, this.manager.abortController.signal]) : this._abortController.signal;
    const l = fetch(t, o).then(function(h) {
      return h.blob();
    }).then(function(h) {
      return createImageBitmap(h, Object.assign(s.options, { colorSpaceConversion: "none" }));
    }).then(function(h) {
      return Tn.add(`image-bitmap:${t}`, h), e && e(h), s.manager.itemEnd(t), h;
    }).catch(function(h) {
      n && n(h), ju.set(l, h), Tn.remove(`image-bitmap:${t}`), s.manager.itemError(t), s.manager.itemEnd(t);
    });
    Tn.add(`image-bitmap:${t}`, l), s.manager.itemStart(t);
  }
  /**
   * Aborts ongoing fetch requests.
   *
   * @return {ImageBitmapLoader} A reference to this instance.
   */
  abort() {
    return this._abortController.abort(), this._abortController = new AbortController(), this;
  }
}
let Pl;
class of {
  /**
   * Returns the global native audio context.
   *
   * @return {AudioContext} The native audio context.
   */
  static getContext() {
    return Pl === void 0 && (Pl = new (window.AudioContext || window.webkitAudioContext)()), Pl;
  }
  /**
   * Allows to set the global native audio context from outside.
   *
   * @param {AudioContext} value - The native context to set.
   */
  static setContext(t) {
    Pl = t;
  }
}
class jb extends Ti {
  /**
   * Constructs a new audio loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(t) {
    super(t);
  }
  /**
   * Starts loading from the given URL and passes the loaded audio buffer
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(t, e, i, n) {
    const s = this, r = new ss(this.manager);
    r.setResponseType("arraybuffer"), r.setPath(this.path), r.setRequestHeader(this.requestHeader), r.setWithCredentials(this.withCredentials), r.load(t, function(l) {
      try {
        const h = l.slice(0);
        of.getContext().decodeAudioData(h, function(u) {
          e(u);
        }).catch(o);
      } catch (h) {
        o(h);
      }
    }, i, n);
    function o(l) {
      n ? n(l) : console.error(l), s.manager.itemError(t);
    }
  }
}
const wm = /* @__PURE__ */ new Vt(), Am = /* @__PURE__ */ new Vt(), Ws = /* @__PURE__ */ new Vt();
class Jb {
  /**
   * Constructs a new stereo camera.
   */
  constructor() {
    this.type = "StereoCamera", this.aspect = 1, this.eyeSep = 0.064, this.cameraL = new Ve(), this.cameraL.layers.enable(1), this.cameraL.matrixAutoUpdate = !1, this.cameraR = new Ve(), this.cameraR.layers.enable(2), this.cameraR.matrixAutoUpdate = !1, this._cache = {
      focus: null,
      fov: null,
      aspect: null,
      near: null,
      far: null,
      zoom: null,
      eyeSep: null
    };
  }
  /**
   * Updates the stereo camera based on the given perspective camera.
   *
   * @param {PerspectiveCamera} camera - The perspective camera.
   */
  update(t) {
    const e = this._cache;
    if (e.focus !== t.focus || e.fov !== t.fov || e.aspect !== t.aspect * this.aspect || e.near !== t.near || e.far !== t.far || e.zoom !== t.zoom || e.eyeSep !== this.eyeSep) {
      e.focus = t.focus, e.fov = t.fov, e.aspect = t.aspect * this.aspect, e.near = t.near, e.far = t.far, e.zoom = t.zoom, e.eyeSep = this.eyeSep, Ws.copy(t.projectionMatrix);
      const n = e.eyeSep / 2, s = n * e.near / e.focus, r = e.near * Math.tan(lr * e.fov * 0.5) / e.zoom;
      let o, l;
      Am.elements[12] = -n, wm.elements[12] = n, o = -r * e.aspect + s, l = r * e.aspect + s, Ws.elements[0] = 2 * e.near / (l - o), Ws.elements[8] = (l + o) / (l - o), this.cameraL.projectionMatrix.copy(Ws), o = -r * e.aspect - s, l = r * e.aspect - s, Ws.elements[0] = 2 * e.near / (l - o), Ws.elements[8] = (l + o) / (l - o), this.cameraR.projectionMatrix.copy(Ws);
    }
    this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(Am), this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(wm);
  }
}
class p_ extends Ve {
  /**
   * Constructs a new array camera.
   *
   * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
   */
  constructor(t = []) {
    super(), this.isArrayCamera = !0, this.isMultiViewCamera = !1, this.cameras = t;
  }
}
class lf {
  /**
   * Constructs a new clock.
   *
   * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
   * `getDelta()` is called for the first time.
   */
  constructor(t = !0) {
    this.autoStart = t, this.startTime = 0, this.oldTime = 0, this.elapsedTime = 0, this.running = !1;
  }
  /**
   * Starts the clock. When `autoStart` is set to `true`, the method is automatically
   * called by the class.
   */
  start() {
    this.startTime = performance.now(), this.oldTime = this.startTime, this.elapsedTime = 0, this.running = !0;
  }
  /**
   * Stops the clock.
   */
  stop() {
    this.getElapsedTime(), this.running = !1, this.autoStart = !1;
  }
  /**
   * Returns the elapsed time in seconds.
   *
   * @return {number} The elapsed time.
   */
  getElapsedTime() {
    return this.getDelta(), this.elapsedTime;
  }
  /**
   * Returns the delta time in seconds.
   *
   * @return {number} The delta time.
   */
  getDelta() {
    let t = 0;
    if (this.autoStart && !this.running)
      return this.start(), 0;
    if (this.running) {
      const e = performance.now();
      t = (e - this.oldTime) / 1e3, this.oldTime = e, this.elapsedTime += t;
    }
    return t;
  }
}
const qs = /* @__PURE__ */ new E(), Ju = /* @__PURE__ */ new ve(), Kb = /* @__PURE__ */ new E(), $s = /* @__PURE__ */ new E(), Xs = /* @__PURE__ */ new E();
class Qb extends le {
  /**
   * Constructs a new audio listener.
   */
  constructor() {
    super(), this.type = "AudioListener", this.context = of.getContext(), this.gain = this.context.createGain(), this.gain.connect(this.context.destination), this.filter = null, this.timeDelta = 0, this._clock = new lf();
  }
  /**
   * Returns the listener's input node.
   *
   * This method is used by other audio nodes to connect to this listener.
   *
   * @return {GainNode} The input node.
   */
  getInput() {
    return this.gain;
  }
  /**
   * Removes the current filter from this listener.
   *
   * @return {AudioListener} A reference to this listener.
   */
  removeFilter() {
    return this.filter !== null && (this.gain.disconnect(this.filter), this.filter.disconnect(this.context.destination), this.gain.connect(this.context.destination), this.filter = null), this;
  }
  /**
   * Returns the current set filter.
   *
   * @return {?AudioNode} The filter.
   */
  getFilter() {
    return this.filter;
  }
  /**
   * Sets the given filter to this listener.
   *
   * @param {AudioNode} value - The filter to set.
   * @return {AudioListener} A reference to this listener.
   */
  setFilter(t) {
    return this.filter !== null ? (this.gain.disconnect(this.filter), this.filter.disconnect(this.context.destination)) : this.gain.disconnect(this.context.destination), this.filter = t, this.gain.connect(this.filter), this.filter.connect(this.context.destination), this;
  }
  /**
   * Returns the applications master volume.
   *
   * @return {number} The master volume.
   */
  getMasterVolume() {
    return this.gain.gain.value;
  }
  /**
   * Sets the applications master volume. This volume setting affects
   * all audio nodes in the scene.
   *
   * @param {number} value - The master volume to set.
   * @return {AudioListener} A reference to this listener.
   */
  setMasterVolume(t) {
    return this.gain.gain.setTargetAtTime(t, this.context.currentTime, 0.01), this;
  }
  updateMatrixWorld(t) {
    super.updateMatrixWorld(t);
    const e = this.context.listener;
    if (this.timeDelta = this._clock.getDelta(), this.matrixWorld.decompose(qs, Ju, Kb), $s.set(0, 0, -1).applyQuaternion(Ju), Xs.set(0, 1, 0).applyQuaternion(Ju), e.positionX) {
      const i = this.context.currentTime + this.timeDelta;
      e.positionX.linearRampToValueAtTime(qs.x, i), e.positionY.linearRampToValueAtTime(qs.y, i), e.positionZ.linearRampToValueAtTime(qs.z, i), e.forwardX.linearRampToValueAtTime($s.x, i), e.forwardY.linearRampToValueAtTime($s.y, i), e.forwardZ.linearRampToValueAtTime($s.z, i), e.upX.linearRampToValueAtTime(Xs.x, i), e.upY.linearRampToValueAtTime(Xs.y, i), e.upZ.linearRampToValueAtTime(Xs.z, i);
    } else
      e.setPosition(qs.x, qs.y, qs.z), e.setOrientation($s.x, $s.y, $s.z, Xs.x, Xs.y, Xs.z);
  }
}
class f_ extends le {
  /**
   * Constructs a new audio.
   *
   * @param {AudioListener} listener - The global audio listener.
   */
  constructor(t) {
    super(), this.type = "Audio", this.listener = t, this.context = t.context, this.gain = this.context.createGain(), this.gain.connect(t.getInput()), this.autoplay = !1, this.buffer = null, this.detune = 0, this.loop = !1, this.loopStart = 0, this.loopEnd = 0, this.offset = 0, this.duration = void 0, this.playbackRate = 1, this.isPlaying = !1, this.hasPlaybackControl = !0, this.source = null, this.sourceType = "empty", this._startedAt = 0, this._progress = 0, this._connected = !1, this.filters = [];
  }
  /**
   * Returns the output audio node.
   *
   * @return {GainNode} The output node.
   */
  getOutput() {
    return this.gain;
  }
  /**
   * Sets the given audio node as the source of this instance.
   *
   * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
   *
   * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
   * @return {Audio} A reference to this instance.
   */
  setNodeSource(t) {
    return this.hasPlaybackControl = !1, this.sourceType = "audioNode", this.source = t, this.connect(), this;
  }
  /**
   * Sets the given media element as the source of this instance.
   *
   * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
   *
   * @param {HTMLMediaElement} mediaElement - The media element.
   * @return {Audio} A reference to this instance.
   */
  setMediaElementSource(t) {
    return this.hasPlaybackControl = !1, this.sourceType = "mediaNode", this.source = this.context.createMediaElementSource(t), this.connect(), this;
  }
  /**
   * Sets the given media stream as the source of this instance.
   *
   * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
   *
   * @param {MediaStream} mediaStream - The media stream.
   * @return {Audio} A reference to this instance.
   */
  setMediaStreamSource(t) {
    return this.hasPlaybackControl = !1, this.sourceType = "mediaStreamNode", this.source = this.context.createMediaStreamSource(t), this.connect(), this;
  }
  /**
   * Sets the given audio buffer as the source of this instance.
   *
   * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
   *
   * @param {AudioBuffer} audioBuffer - The audio buffer.
   * @return {Audio} A reference to this instance.
   */
  setBuffer(t) {
    return this.buffer = t, this.sourceType = "buffer", this.autoplay && this.play(), this;
  }
  /**
   * Starts the playback of the audio.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
   * @return {Audio|undefined} A reference to this instance.
   */
  play(t = 0) {
    if (this.isPlaying === !0) {
      console.warn("THREE.Audio: Audio is already playing.");
      return;
    }
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    this._startedAt = this.context.currentTime + t;
    const e = this.context.createBufferSource();
    return e.buffer = this.buffer, e.loop = this.loop, e.loopStart = this.loopStart, e.loopEnd = this.loopEnd, e.onended = this.onEnded.bind(this), e.start(this._startedAt, this._progress + this.offset, this.duration), this.isPlaying = !0, this.source = e, this.setDetune(this.detune), this.setPlaybackRate(this.playbackRate), this.connect();
  }
  /**
   * Pauses the playback of the audio.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @return {Audio|undefined} A reference to this instance.
   */
  pause() {
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    return this.isPlaying === !0 && (this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate, this.loop === !0 && (this._progress = this._progress % (this.duration || this.buffer.duration)), this.source.stop(), this.source.onended = null, this.isPlaying = !1), this;
  }
  /**
   * Stops the playback of the audio.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
   * @return {Audio|undefined} A reference to this instance.
   */
  stop(t = 0) {
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    return this._progress = 0, this.source !== null && (this.source.stop(this.context.currentTime + t), this.source.onended = null), this.isPlaying = !1, this;
  }
  /**
   * Connects to the audio source. This is used internally on
   * initialisation and when setting / removing filters.
   *
   * @return {Audio} A reference to this instance.
   */
  connect() {
    if (this.filters.length > 0) {
      this.source.connect(this.filters[0]);
      for (let t = 1, e = this.filters.length; t < e; t++)
        this.filters[t - 1].connect(this.filters[t]);
      this.filters[this.filters.length - 1].connect(this.getOutput());
    } else
      this.source.connect(this.getOutput());
    return this._connected = !0, this;
  }
  /**
   * Disconnects to the audio source. This is used internally on
   * initialisation and when setting / removing filters.
   *
   * @return {Audio|undefined} A reference to this instance.
   */
  disconnect() {
    if (this._connected !== !1) {
      if (this.filters.length > 0) {
        this.source.disconnect(this.filters[0]);
        for (let t = 1, e = this.filters.length; t < e; t++)
          this.filters[t - 1].disconnect(this.filters[t]);
        this.filters[this.filters.length - 1].disconnect(this.getOutput());
      } else
        this.source.disconnect(this.getOutput());
      return this._connected = !1, this;
    }
  }
  /**
   * Returns the current set filters.
   *
   * @return {Array<AudioNode>} The list of filters.
   */
  getFilters() {
    return this.filters;
  }
  /**
   * Sets an array of filters and connects them with the audio source.
   *
   * @param {Array<AudioNode>} [value] - A list of filters.
   * @return {Audio} A reference to this instance.
   */
  setFilters(t) {
    return t || (t = []), this._connected === !0 ? (this.disconnect(), this.filters = t.slice(), this.connect()) : this.filters = t.slice(), this;
  }
  /**
   * Defines the detuning of oscillation in cents.
   *
   * @param {number} value - The detuning of oscillation in cents.
   * @return {Audio} A reference to this instance.
   */
  setDetune(t) {
    return this.detune = t, this.isPlaying === !0 && this.source.detune !== void 0 && this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01), this;
  }
  /**
   * Returns the detuning of oscillation in cents.
   *
   * @return {number} The detuning of oscillation in cents.
   */
  getDetune() {
    return this.detune;
  }
  /**
   * Returns the first filter in the list of filters.
   *
   * @return {AudioNode|undefined} The first filter in the list of filters.
   */
  getFilter() {
    return this.getFilters()[0];
  }
  /**
   * Applies a single filter node to the audio.
   *
   * @param {AudioNode} [filter] - The filter to set.
   * @return {Audio} A reference to this instance.
   */
  setFilter(t) {
    return this.setFilters(t ? [t] : []);
  }
  /**
   * Sets the playback rate.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @param {number} [value] - The playback rate to set.
   * @return {Audio|undefined} A reference to this instance.
   */
  setPlaybackRate(t) {
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    return this.playbackRate = t, this.isPlaying === !0 && this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01), this;
  }
  /**
  	 * Returns the current playback rate.
  
  	 * @return {number} The playback rate.
  	 */
  getPlaybackRate() {
    return this.playbackRate;
  }
  /**
   * Automatically called when playback finished.
   */
  onEnded() {
    this.isPlaying = !1, this._progress = 0;
  }
  /**
   * Returns the loop flag.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @return {boolean} Whether the audio should loop or not.
   */
  getLoop() {
    return this.hasPlaybackControl === !1 ? (console.warn("THREE.Audio: this Audio has no playback control."), !1) : this.loop;
  }
  /**
   * Sets the loop flag.
   *
   * Can only be used with compatible audio sources that allow playback control.
   *
   * @param {boolean} value - Whether the audio should loop or not.
   * @return {Audio|undefined} A reference to this instance.
   */
  setLoop(t) {
    if (this.hasPlaybackControl === !1) {
      console.warn("THREE.Audio: this Audio has no playback control.");
      return;
    }
    return this.loop = t, this.isPlaying === !0 && (this.source.loop = this.loop), this;
  }
  /**
   * Sets the loop start value which defines where in the audio buffer the replay should
   * start, in seconds.
   *
   * @param {number} value - The loop start value.
   * @return {Audio} A reference to this instance.
   */
  setLoopStart(t) {
    return this.loopStart = t, this;
  }
  /**
   * Sets the loop end value which defines where in the audio buffer the replay should
   * stop, in seconds.
   *
   * @param {number} value - The loop end value.
   * @return {Audio} A reference to this instance.
   */
  setLoopEnd(t) {
    return this.loopEnd = t, this;
  }
  /**
   * Returns the volume.
   *
   * @return {number} The volume.
   */
  getVolume() {
    return this.gain.gain.value;
  }
  /**
   * Sets the volume.
   *
   * @param {number} value - The volume to set.
   * @return {Audio} A reference to this instance.
   */
  setVolume(t) {
    return this.gain.gain.setTargetAtTime(t, this.context.currentTime, 0.01), this;
  }
  copy(t, e) {
    return super.copy(t, e), t.sourceType !== "buffer" ? (console.warn("THREE.Audio: Audio source type cannot be copied."), this) : (this.autoplay = t.autoplay, this.buffer = t.buffer, this.detune = t.detune, this.loop = t.loop, this.loopStart = t.loopStart, this.loopEnd = t.loopEnd, this.offset = t.offset, this.duration = t.duration, this.playbackRate = t.playbackRate, this.hasPlaybackControl = t.hasPlaybackControl, this.sourceType = t.sourceType, this.filters = t.filters.slice(), this);
  }
  clone(t) {
    return new this.constructor(this.listener).copy(this, t);
  }
}
const Ys = /* @__PURE__ */ new E(), Em = /* @__PURE__ */ new ve(), tM = /* @__PURE__ */ new E(), Zs = /* @__PURE__ */ new E();
class eM extends f_ {
  /**
   * Constructs a positional audio.
   *
   * @param {AudioListener} listener - The global audio listener.
   */
  constructor(t) {
    super(t), this.panner = this.context.createPanner(), this.panner.panningModel = "HRTF", this.panner.connect(this.gain);
  }
  connect() {
    return super.connect(), this.panner.connect(this.gain), this;
  }
  disconnect() {
    return super.disconnect(), this.panner.disconnect(this.gain), this;
  }
  getOutput() {
    return this.panner;
  }
  /**
   * Returns the current reference distance.
   *
   * @return {number} The reference distance.
   */
  getRefDistance() {
    return this.panner.refDistance;
  }
  /**
   * Defines the reference distance for reducing volume as the audio source moves
   * further from the listener – i.e. the distance at which the volume reduction
   * starts taking effect.
   *
   * @param {number} value - The reference distance to set.
   * @return {PositionalAudio} A reference to this instance.
   */
  setRefDistance(t) {
    return this.panner.refDistance = t, this;
  }
  /**
   * Returns the current rolloff factor.
   *
   * @return {number} The rolloff factor.
   */
  getRolloffFactor() {
    return this.panner.rolloffFactor;
  }
  /**
   * Defines how quickly the volume is reduced as the source moves away from the listener.
   *
   * @param {number} value - The rolloff factor.
   * @return {PositionalAudio} A reference to this instance.
   */
  setRolloffFactor(t) {
    return this.panner.rolloffFactor = t, this;
  }
  /**
   * Returns the current distance model.
   *
   * @return {('linear'|'inverse'|'exponential')} The distance model.
   */
  getDistanceModel() {
    return this.panner.distanceModel;
  }
  /**
   * Defines which algorithm to use to reduce the volume of the audio source
   * as it moves away from the listener.
   *
   * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
   * for more details.
   *
   * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
   * @return {PositionalAudio} A reference to this instance.
   */
  setDistanceModel(t) {
    return this.panner.distanceModel = t, this;
  }
  /**
   * Returns the current max distance.
   *
   * @return {number} The max distance.
   */
  getMaxDistance() {
    return this.panner.maxDistance;
  }
  /**
   * Defines the maximum distance between the audio source and the listener,
   * after which the volume is not reduced any further.
   *
   * This value is used only by the `linear` distance model.
   *
   * @param {number} value - The max distance.
   * @return {PositionalAudio} A reference to this instance.
   */
  setMaxDistance(t) {
    return this.panner.maxDistance = t, this;
  }
  /**
   * Sets the directional cone in which the audio can be listened.
   *
   * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
   * @param {number} coneOuterAngle - An angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` parameter.
   * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
   * @return {PositionalAudio} A reference to this instance.
   */
  setDirectionalCone(t, e, i) {
    return this.panner.coneInnerAngle = t, this.panner.coneOuterAngle = e, this.panner.coneOuterGain = i, this;
  }
  updateMatrixWorld(t) {
    if (super.updateMatrixWorld(t), this.hasPlaybackControl === !0 && this.isPlaying === !1) return;
    this.matrixWorld.decompose(Ys, Em, tM), Zs.set(0, 0, 1).applyQuaternion(Em);
    const e = this.panner;
    if (e.positionX) {
      const i = this.context.currentTime + this.listener.timeDelta;
      e.positionX.linearRampToValueAtTime(Ys.x, i), e.positionY.linearRampToValueAtTime(Ys.y, i), e.positionZ.linearRampToValueAtTime(Ys.z, i), e.orientationX.linearRampToValueAtTime(Zs.x, i), e.orientationY.linearRampToValueAtTime(Zs.y, i), e.orientationZ.linearRampToValueAtTime(Zs.z, i);
    } else
      e.setPosition(Ys.x, Ys.y, Ys.z), e.setOrientation(Zs.x, Zs.y, Zs.z);
  }
}
class iM {
  /**
   * Constructs a new audio analyzer.
   *
   * @param {Audio} audio - The audio to analyze.
   * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
   */
  constructor(t, e = 2048) {
    this.analyser = t.context.createAnalyser(), this.analyser.fftSize = e, this.data = new Uint8Array(this.analyser.frequencyBinCount), t.getOutput().connect(this.analyser);
  }
  /**
   * Returns an array with frequency data of the audio.
   *
   * Each item in the array represents the decibel value for a specific frequency.
   * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
   * For example, for 48000 sample rate, the last item of the array will represent
   * the decibel value for 24000 Hz.
   *
   * @return {Uint8Array} The frequency data.
   */
  getFrequencyData() {
    return this.analyser.getByteFrequencyData(this.data), this.data;
  }
  /**
   * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
   *
   * @return {number} The average frequency.
   */
  getAverageFrequency() {
    let t = 0;
    const e = this.getFrequencyData();
    for (let i = 0; i < e.length; i++)
      t += e[i];
    return t / e.length;
  }
}
class m_ {
  /**
   * Constructs a new property mixer.
   *
   * @param {PropertyBinding} binding - The property binding.
   * @param {string} typeName - The keyframe track type name.
   * @param {number} valueSize - The keyframe track value size.
   */
  constructor(t, e, i) {
    this.binding = t, this.valueSize = i;
    let n, s, r;
    switch (e) {
      case "quaternion":
        n = this._slerp, s = this._slerpAdditive, r = this._setAdditiveIdentityQuaternion, this.buffer = new Float64Array(i * 6), this._workIndex = 5;
        break;
      case "string":
      case "bool":
        n = this._select, s = this._select, r = this._setAdditiveIdentityOther, this.buffer = new Array(i * 5);
        break;
      default:
        n = this._lerp, s = this._lerpAdditive, r = this._setAdditiveIdentityNumeric, this.buffer = new Float64Array(i * 5);
    }
    this._mixBufferRegion = n, this._mixBufferRegionAdditive = s, this._setIdentity = r, this._origIndex = 3, this._addIndex = 4, this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0, this.useCount = 0, this.referenceCount = 0;
  }
  /**
   * Accumulates data in the `incoming` region into `accu<i>`.
   *
   * @param {number} accuIndex - The accumulation index.
   * @param {number} weight - The weight.
   */
  accumulate(t, e) {
    const i = this.buffer, n = this.valueSize, s = t * n + n;
    let r = this.cumulativeWeight;
    if (r === 0) {
      for (let o = 0; o !== n; ++o)
        i[s + o] = i[o];
      r = e;
    } else {
      r += e;
      const o = e / r;
      this._mixBufferRegion(i, s, 0, o, n);
    }
    this.cumulativeWeight = r;
  }
  /**
   * Accumulates data in the `incoming` region into `add`.
   *
   * @param {number} weight - The weight.
   */
  accumulateAdditive(t) {
    const e = this.buffer, i = this.valueSize, n = i * this._addIndex;
    this.cumulativeWeightAdditive === 0 && this._setIdentity(), this._mixBufferRegionAdditive(e, n, 0, t, i), this.cumulativeWeightAdditive += t;
  }
  /**
   * Applies the state of `accu<i>` to the binding when accus differ.
   *
   * @param {number} accuIndex - The accumulation index.
   */
  apply(t) {
    const e = this.valueSize, i = this.buffer, n = t * e + e, s = this.cumulativeWeight, r = this.cumulativeWeightAdditive, o = this.binding;
    if (this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0, s < 1) {
      const l = e * this._origIndex;
      this._mixBufferRegion(
        i,
        n,
        l,
        1 - s,
        e
      );
    }
    r > 0 && this._mixBufferRegionAdditive(i, n, this._addIndex * e, 1, e);
    for (let l = e, h = e + e; l !== h; ++l)
      if (i[l] !== i[l + e]) {
        o.setValue(i, n);
        break;
      }
  }
  /**
   * Remembers the state of the bound property and copy it to both accus.
   */
  saveOriginalState() {
    const t = this.binding, e = this.buffer, i = this.valueSize, n = i * this._origIndex;
    t.getValue(e, n);
    for (let s = i, r = n; s !== r; ++s)
      e[s] = e[n + s % i];
    this._setIdentity(), this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0;
  }
  /**
   * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
   */
  restoreOriginalState() {
    const t = this.valueSize * 3;
    this.binding.setValue(this.buffer, t);
  }
  // internals
  _setAdditiveIdentityNumeric() {
    const t = this._addIndex * this.valueSize, e = t + this.valueSize;
    for (let i = t; i < e; i++)
      this.buffer[i] = 0;
  }
  _setAdditiveIdentityQuaternion() {
    this._setAdditiveIdentityNumeric(), this.buffer[this._addIndex * this.valueSize + 3] = 1;
  }
  _setAdditiveIdentityOther() {
    const t = this._origIndex * this.valueSize, e = this._addIndex * this.valueSize;
    for (let i = 0; i < this.valueSize; i++)
      this.buffer[e + i] = this.buffer[t + i];
  }
  // mix functions
  _select(t, e, i, n, s) {
    if (n >= 0.5)
      for (let r = 0; r !== s; ++r)
        t[e + r] = t[i + r];
  }
  _slerp(t, e, i, n) {
    ve.slerpFlat(t, e, t, e, t, i, n);
  }
  _slerpAdditive(t, e, i, n, s) {
    const r = this._workIndex * s;
    ve.multiplyQuaternionsFlat(t, r, t, e, t, i), ve.slerpFlat(t, e, t, e, t, r, n);
  }
  _lerp(t, e, i, n, s) {
    const r = 1 - n;
    for (let o = 0; o !== s; ++o) {
      const l = e + o;
      t[l] = t[l] * r + t[i + o] * n;
    }
  }
  _lerpAdditive(t, e, i, n, s) {
    for (let r = 0; r !== s; ++r) {
      const o = e + r;
      t[o] = t[o] + t[i + r] * n;
    }
  }
}
const hf = "\\[\\]\\.:\\/", nM = new RegExp("[" + hf + "]", "g"), cf = "[^" + hf + "]", sM = "[^" + hf.replace("\\.", "") + "]", rM = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", cf), aM = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", sM), oM = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", cf), lM = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", cf), hM = new RegExp(
  "^" + rM + aM + oM + lM + "$"
), cM = ["material", "materials", "bones", "map"];
class uM {
  constructor(t, e, i) {
    const n = i || se.parseTrackName(e);
    this._targetGroup = t, this._bindings = t.subscribe_(e, n);
  }
  getValue(t, e) {
    this.bind();
    const i = this._targetGroup.nCachedObjects_, n = this._bindings[i];
    n !== void 0 && n.getValue(t, e);
  }
  setValue(t, e) {
    const i = this._bindings;
    for (let n = this._targetGroup.nCachedObjects_, s = i.length; n !== s; ++n)
      i[n].setValue(t, e);
  }
  bind() {
    const t = this._bindings;
    for (let e = this._targetGroup.nCachedObjects_, i = t.length; e !== i; ++e)
      t[e].bind();
  }
  unbind() {
    const t = this._bindings;
    for (let e = this._targetGroup.nCachedObjects_, i = t.length; e !== i; ++e)
      t[e].unbind();
  }
}
class se {
  /**
   * Constructs a new property binding.
   *
   * @param {Object} rootNode - The root node.
   * @param {string} path - The path.
   * @param {?Object} [parsedPath] - The parsed path.
   */
  constructor(t, e, i) {
    this.path = e, this.parsedPath = i || se.parseTrackName(e), this.node = se.findNode(t, this.parsedPath.nodeName), this.rootNode = t, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound;
  }
  /**
   * Factory method for creating a property binding from the given parameters.
   *
   * @static
   * @param {Object} root - The root node.
   * @param {string} path - The path.
   * @param {?Object} [parsedPath] - The parsed path.
   * @return {PropertyBinding|Composite} The created property binding or composite.
   */
  static create(t, e, i) {
    return t && t.isAnimationObjectGroup ? new se.Composite(t, e, i) : new se(t, e, i);
  }
  /**
   * Replaces spaces with underscores and removes unsupported characters from
   * node names, to ensure compatibility with parseTrackName().
   *
   * @param {string} name - Node name to be sanitized.
   * @return {string} The sanitized node name.
   */
  static sanitizeNodeName(t) {
    return t.replace(/\s/g, "_").replace(nM, "");
  }
  /**
   * Parses the given track name (an object path to an animated property) and
   * returns an object with information about the path. Matches strings in the following forms:
   *
   * - nodeName.property
   * - nodeName.property[accessor]
   * - nodeName.material.property[accessor]
   * - uuid.property[accessor]
   * - uuid.objectName[objectIndex].propertyName[propertyIndex]
   * - parentName/nodeName.property
   * - parentName/parentName/nodeName.property[index]
   * - .bone[Armature.DEF_cog].position
   * - scene:helium_balloon_model:helium_balloon_model.position
   *
   * @static
   * @param {string} trackName - The track name to parse.
   * @return {Object} The parsed track name as an object.
   */
  static parseTrackName(t) {
    const e = hM.exec(t);
    if (e === null)
      throw new Error("PropertyBinding: Cannot parse trackName: " + t);
    const i = {
      // directoryName: matches[ 1 ], // (tschw) currently unused
      nodeName: e[2],
      objectName: e[3],
      objectIndex: e[4],
      propertyName: e[5],
      // required
      propertyIndex: e[6]
    }, n = i.nodeName && i.nodeName.lastIndexOf(".");
    if (n !== void 0 && n !== -1) {
      const s = i.nodeName.substring(n + 1);
      cM.indexOf(s) !== -1 && (i.nodeName = i.nodeName.substring(0, n), i.objectName = s);
    }
    if (i.propertyName === null || i.propertyName.length === 0)
      throw new Error("PropertyBinding: can not parse propertyName from trackName: " + t);
    return i;
  }
  /**
   * Searches for a node in the hierarchy of the given root object by the given
   * node name.
   *
   * @static
   * @param {Object} root - The root object.
   * @param {string|number} nodeName - The name of the node.
   * @return {?Object} The found node. Returns `null` if no object was found.
   */
  static findNode(t, e) {
    if (e === void 0 || e === "" || e === "." || e === -1 || e === t.name || e === t.uuid)
      return t;
    if (t.skeleton) {
      const i = t.skeleton.getBoneByName(e);
      if (i !== void 0)
        return i;
    }
    if (t.children) {
      const i = function(s) {
        for (let r = 0; r < s.length; r++) {
          const o = s[r];
          if (o.name === e || o.uuid === e)
            return o;
          const l = i(o.children);
          if (l) return l;
        }
        return null;
      }, n = i(t.children);
      if (n)
        return n;
    }
    return null;
  }
  // these are used to "bind" a nonexistent property
  _getValue_unavailable() {
  }
  _setValue_unavailable() {
  }
  // Getters
  _getValue_direct(t, e) {
    t[e] = this.targetObject[this.propertyName];
  }
  _getValue_array(t, e) {
    const i = this.resolvedProperty;
    for (let n = 0, s = i.length; n !== s; ++n)
      t[e++] = i[n];
  }
  _getValue_arrayElement(t, e) {
    t[e] = this.resolvedProperty[this.propertyIndex];
  }
  _getValue_toArray(t, e) {
    this.resolvedProperty.toArray(t, e);
  }
  // Direct
  _setValue_direct(t, e) {
    this.targetObject[this.propertyName] = t[e];
  }
  _setValue_direct_setNeedsUpdate(t, e) {
    this.targetObject[this.propertyName] = t[e], this.targetObject.needsUpdate = !0;
  }
  _setValue_direct_setMatrixWorldNeedsUpdate(t, e) {
    this.targetObject[this.propertyName] = t[e], this.targetObject.matrixWorldNeedsUpdate = !0;
  }
  // EntireArray
  _setValue_array(t, e) {
    const i = this.resolvedProperty;
    for (let n = 0, s = i.length; n !== s; ++n)
      i[n] = t[e++];
  }
  _setValue_array_setNeedsUpdate(t, e) {
    const i = this.resolvedProperty;
    for (let n = 0, s = i.length; n !== s; ++n)
      i[n] = t[e++];
    this.targetObject.needsUpdate = !0;
  }
  _setValue_array_setMatrixWorldNeedsUpdate(t, e) {
    const i = this.resolvedProperty;
    for (let n = 0, s = i.length; n !== s; ++n)
      i[n] = t[e++];
    this.targetObject.matrixWorldNeedsUpdate = !0;
  }
  // ArrayElement
  _setValue_arrayElement(t, e) {
    this.resolvedProperty[this.propertyIndex] = t[e];
  }
  _setValue_arrayElement_setNeedsUpdate(t, e) {
    this.resolvedProperty[this.propertyIndex] = t[e], this.targetObject.needsUpdate = !0;
  }
  _setValue_arrayElement_setMatrixWorldNeedsUpdate(t, e) {
    this.resolvedProperty[this.propertyIndex] = t[e], this.targetObject.matrixWorldNeedsUpdate = !0;
  }
  // HasToFromArray
  _setValue_fromArray(t, e) {
    this.resolvedProperty.fromArray(t, e);
  }
  _setValue_fromArray_setNeedsUpdate(t, e) {
    this.resolvedProperty.fromArray(t, e), this.targetObject.needsUpdate = !0;
  }
  _setValue_fromArray_setMatrixWorldNeedsUpdate(t, e) {
    this.resolvedProperty.fromArray(t, e), this.targetObject.matrixWorldNeedsUpdate = !0;
  }
  _getValue_unbound(t, e) {
    this.bind(), this.getValue(t, e);
  }
  _setValue_unbound(t, e) {
    this.bind(), this.setValue(t, e);
  }
  /**
   * Creates a getter / setter pair for the property tracked by this binding.
   */
  bind() {
    let t = this.node;
    const e = this.parsedPath, i = e.objectName, n = e.propertyName;
    let s = e.propertyIndex;
    if (t || (t = se.findNode(this.rootNode, e.nodeName), this.node = t), this.getValue = this._getValue_unavailable, this.setValue = this._setValue_unavailable, !t) {
      console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + ".");
      return;
    }
    if (i) {
      let h = e.objectIndex;
      switch (i) {
        case "materials":
          if (!t.material) {
            console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
            return;
          }
          if (!t.material.materials) {
            console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this);
            return;
          }
          t = t.material.materials;
          break;
        case "bones":
          if (!t.skeleton) {
            console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this);
            return;
          }
          t = t.skeleton.bones;
          for (let c = 0; c < t.length; c++)
            if (t[c].name === h) {
              h = c;
              break;
            }
          break;
        case "map":
          if ("map" in t) {
            t = t.map;
            break;
          }
          if (!t.material) {
            console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
            return;
          }
          if (!t.material.map) {
            console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this);
            return;
          }
          t = t.material.map;
          break;
        default:
          if (t[i] === void 0) {
            console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this);
            return;
          }
          t = t[i];
      }
      if (h !== void 0) {
        if (t[h] === void 0) {
          console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, t);
          return;
        }
        t = t[h];
      }
    }
    const r = t[n];
    if (r === void 0) {
      const h = e.nodeName;
      console.error("THREE.PropertyBinding: Trying to update property for track: " + h + "." + n + " but it wasn't found.", t);
      return;
    }
    let o = this.Versioning.None;
    this.targetObject = t, t.isMaterial === !0 ? o = this.Versioning.NeedsUpdate : t.isObject3D === !0 && (o = this.Versioning.MatrixWorldNeedsUpdate);
    let l = this.BindingType.Direct;
    if (s !== void 0) {
      if (n === "morphTargetInfluences") {
        if (!t.geometry) {
          console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this);
          return;
        }
        if (!t.geometry.morphAttributes) {
          console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this);
          return;
        }
        t.morphTargetDictionary[s] !== void 0 && (s = t.morphTargetDictionary[s]);
      }
      l = this.BindingType.ArrayElement, this.resolvedProperty = r, this.propertyIndex = s;
    } else r.fromArray !== void 0 && r.toArray !== void 0 ? (l = this.BindingType.HasFromToArray, this.resolvedProperty = r) : Array.isArray(r) ? (l = this.BindingType.EntireArray, this.resolvedProperty = r) : this.propertyName = n;
    this.getValue = this.GetterByBindingType[l], this.setValue = this.SetterByBindingTypeAndVersioning[l][o];
  }
  /**
   * Unbinds the property.
   */
  unbind() {
    this.node = null, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound;
  }
}
se.Composite = uM;
se.prototype.BindingType = {
  Direct: 0,
  EntireArray: 1,
  ArrayElement: 2,
  HasFromToArray: 3
};
se.prototype.Versioning = {
  None: 0,
  NeedsUpdate: 1,
  MatrixWorldNeedsUpdate: 2
};
se.prototype.GetterByBindingType = [
  se.prototype._getValue_direct,
  se.prototype._getValue_array,
  se.prototype._getValue_arrayElement,
  se.prototype._getValue_toArray
];
se.prototype.SetterByBindingTypeAndVersioning = [
  [
    // Direct
    se.prototype._setValue_direct,
    se.prototype._setValue_direct_setNeedsUpdate,
    se.prototype._setValue_direct_setMatrixWorldNeedsUpdate
  ],
  [
    // EntireArray
    se.prototype._setValue_array,
    se.prototype._setValue_array_setNeedsUpdate,
    se.prototype._setValue_array_setMatrixWorldNeedsUpdate
  ],
  [
    // ArrayElement
    se.prototype._setValue_arrayElement,
    se.prototype._setValue_arrayElement_setNeedsUpdate,
    se.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate
  ],
  [
    // HasToFromArray
    se.prototype._setValue_fromArray,
    se.prototype._setValue_fromArray_setNeedsUpdate,
    se.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate
  ]
];
class dM {
  /**
   * Constructs a new animation group.
   *
   * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
   */
  constructor() {
    this.isAnimationObjectGroup = !0, this.uuid = Oi(), this._objects = Array.prototype.slice.call(arguments), this.nCachedObjects_ = 0;
    const t = {};
    this._indicesByUUID = t;
    for (let i = 0, n = arguments.length; i !== n; ++i)
      t[arguments[i].uuid] = i;
    this._paths = [], this._parsedPaths = [], this._bindings = [], this._bindingsIndicesByPath = {};
    const e = this;
    this.stats = {
      objects: {
        get total() {
          return e._objects.length;
        },
        get inUse() {
          return this.total - e.nCachedObjects_;
        }
      },
      get bindingsPerObject() {
        return e._bindings.length;
      }
    };
  }
  /**
   * Adds an arbitrary number of objects to this animation group.
   *
   * @param {...Object3D} arguments - The 3D objects to add.
   */
  add() {
    const t = this._objects, e = this._indicesByUUID, i = this._paths, n = this._parsedPaths, s = this._bindings, r = s.length;
    let o, l = t.length, h = this.nCachedObjects_;
    for (let c = 0, u = arguments.length; c !== u; ++c) {
      const d = arguments[c], p = d.uuid;
      let f = e[p];
      if (f === void 0) {
        f = l++, e[p] = f, t.push(d);
        for (let y = 0, g = r; y !== g; ++y)
          s[y].push(new se(d, i[y], n[y]));
      } else if (f < h) {
        o = t[f];
        const y = --h, g = t[y];
        e[g.uuid] = f, t[f] = g, e[p] = y, t[y] = d;
        for (let m = 0, v = r; m !== v; ++m) {
          const x = s[m], _ = x[y];
          let S = x[f];
          x[f] = _, S === void 0 && (S = new se(d, i[m], n[m])), x[y] = S;
        }
      } else t[f] !== o && console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.");
    }
    this.nCachedObjects_ = h;
  }
  /**
   * Removes an arbitrary number of objects to this animation group
   *
   * @param {...Object3D} arguments - The 3D objects to remove.
   */
  remove() {
    const t = this._objects, e = this._indicesByUUID, i = this._bindings, n = i.length;
    let s = this.nCachedObjects_;
    for (let r = 0, o = arguments.length; r !== o; ++r) {
      const l = arguments[r], h = l.uuid, c = e[h];
      if (c !== void 0 && c >= s) {
        const u = s++, d = t[u];
        e[d.uuid] = c, t[c] = d, e[h] = u, t[u] = l;
        for (let p = 0, f = n; p !== f; ++p) {
          const y = i[p], g = y[u], m = y[c];
          y[c] = g, y[u] = m;
        }
      }
    }
    this.nCachedObjects_ = s;
  }
  /**
   * Deallocates all memory resources for the passed 3D objects of this animation group.
   *
   * @param {...Object3D} arguments - The 3D objects to uncache.
   */
  uncache() {
    const t = this._objects, e = this._indicesByUUID, i = this._bindings, n = i.length;
    let s = this.nCachedObjects_, r = t.length;
    for (let o = 0, l = arguments.length; o !== l; ++o) {
      const h = arguments[o], c = h.uuid, u = e[c];
      if (u !== void 0)
        if (delete e[c], u < s) {
          const d = --s, p = t[d], f = --r, y = t[f];
          e[p.uuid] = u, t[u] = p, e[y.uuid] = d, t[d] = y, t.pop();
          for (let g = 0, m = n; g !== m; ++g) {
            const v = i[g], x = v[d], _ = v[f];
            v[u] = x, v[d] = _, v.pop();
          }
        } else {
          const d = --r, p = t[d];
          d > 0 && (e[p.uuid] = u), t[u] = p, t.pop();
          for (let f = 0, y = n; f !== y; ++f) {
            const g = i[f];
            g[u] = g[d], g.pop();
          }
        }
    }
    this.nCachedObjects_ = s;
  }
  // Internal interface used by befriended PropertyBinding.Composite:
  subscribe_(t, e) {
    const i = this._bindingsIndicesByPath;
    let n = i[t];
    const s = this._bindings;
    if (n !== void 0) return s[n];
    const r = this._paths, o = this._parsedPaths, l = this._objects, h = l.length, c = this.nCachedObjects_, u = new Array(h);
    n = s.length, i[t] = n, r.push(t), o.push(e), s.push(u);
    for (let d = c, p = l.length; d !== p; ++d) {
      const f = l[d];
      u[d] = new se(f, t, e);
    }
    return u;
  }
  unsubscribe_(t) {
    const e = this._bindingsIndicesByPath, i = e[t];
    if (i !== void 0) {
      const n = this._paths, s = this._parsedPaths, r = this._bindings, o = r.length - 1, l = r[o], h = t[o];
      e[h] = i, r[i] = l, r.pop(), s[i] = s[o], s.pop(), n[i] = n[o], n.pop();
    }
  }
}
class g_ {
  /**
   * Constructs a new animation action.
   *
   * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
   * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
   * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
   * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
   */
  constructor(t, e, i = null, n = e.blendMode) {
    this._mixer = t, this._clip = e, this._localRoot = i, this.blendMode = n;
    const s = e.tracks, r = s.length, o = new Array(r), l = {
      endingStart: sr,
      endingEnd: sr
    };
    for (let h = 0; h !== r; ++h) {
      const c = s[h].createInterpolant(null);
      o[h] = c, c.settings = l;
    }
    this._interpolantSettings = l, this._interpolants = o, this._propertyBindings = new Array(r), this._cacheIndex = null, this._byClipCacheIndex = null, this._timeScaleInterpolant = null, this._weightInterpolant = null, this.loop = Ip, this._loopCount = -1, this._startTime = null, this.time = 0, this.timeScale = 1, this._effectiveTimeScale = 1, this.weight = 1, this._effectiveWeight = 1, this.repetitions = 1 / 0, this.paused = !1, this.enabled = !0, this.clampWhenFinished = !1, this.zeroSlopeAtStart = !0, this.zeroSlopeAtEnd = !0;
  }
  /**
   * Starts the playback of the animation.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  play() {
    return this._mixer._activateAction(this), this;
  }
  /**
   * Stops the playback of the animation.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  stop() {
    return this._mixer._deactivateAction(this), this.reset();
  }
  /**
   * Resets the playback of the animation.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  reset() {
    return this.paused = !1, this.enabled = !0, this.time = 0, this._loopCount = -1, this._startTime = null, this.stopFading().stopWarping();
  }
  /**
   * Returns `true` if the animation is running.
   *
   * @return {boolean} Whether the animation is running or not.
   */
  isRunning() {
    return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  }
  /**
   * Returns `true` when {@link AnimationAction#play} has been called.
   *
   * @return {boolean} Whether the animation is scheduled or not.
   */
  isScheduled() {
    return this._mixer._isActiveAction(this);
  }
  /**
   * Defines the time when the animation should start.
   *
   * @param {number} time - The start time in seconds.
   * @return {AnimationAction} A reference to this animation action.
   */
  startAt(t) {
    return this._startTime = t, this;
  }
  /**
   * Configures the loop settings for this action.
   *
   * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
   * @param {number} repetitions - The number of repetitions.
   * @return {AnimationAction} A reference to this animation action.
   */
  setLoop(t, e) {
    return this.loop = t, this.repetitions = e, this;
  }
  /**
   * Sets the effective weight of this action.
   *
   * An action has no effect and thus an effective weight of zero when the
   * action is disabled.
   *
   * @param {number} weight - The weight to set.
   * @return {AnimationAction} A reference to this animation action.
   */
  setEffectiveWeight(t) {
    return this.weight = t, this._effectiveWeight = this.enabled ? t : 0, this.stopFading();
  }
  /**
   * Returns the effective weight of this action.
   *
   * @return {number} The effective weight.
   */
  getEffectiveWeight() {
    return this._effectiveWeight;
  }
  /**
   * Fades the animation in by increasing its weight gradually from `0` to `1`,
   * within the passed time interval.
   *
   * @param {number} duration - The duration of the fade.
   * @return {AnimationAction} A reference to this animation action.
   */
  fadeIn(t) {
    return this._scheduleFading(t, 0, 1);
  }
  /**
   * Fades the animation out by decreasing its weight gradually from `1` to `0`,
   * within the passed time interval.
   *
   * @param {number} duration - The duration of the fade.
   * @return {AnimationAction} A reference to this animation action.
   */
  fadeOut(t) {
    return this._scheduleFading(t, 1, 0);
  }
  /**
   * Causes this action to fade in and the given action to fade out,
   * within the passed time interval.
   *
   * @param {AnimationAction} fadeOutAction - The animation action to fade out.
   * @param {number} duration - The duration of the fade.
   * @param {boolean} [warp=false] - Whether warping should be used or not.
   * @return {AnimationAction} A reference to this animation action.
   */
  crossFadeFrom(t, e, i = !1) {
    if (t.fadeOut(e), this.fadeIn(e), i === !0) {
      const n = this._clip.duration, s = t._clip.duration, r = s / n, o = n / s;
      t.warp(1, r, e), this.warp(o, 1, e);
    }
    return this;
  }
  /**
   * Causes this action to fade out and the given action to fade in,
   * within the passed time interval.
   *
   * @param {AnimationAction} fadeInAction - The animation action to fade in.
   * @param {number} duration - The duration of the fade.
   * @param {boolean} [warp=false] - Whether warping should be used or not.
   * @return {AnimationAction} A reference to this animation action.
   */
  crossFadeTo(t, e, i = !1) {
    return t.crossFadeFrom(this, e, i);
  }
  /**
   * Stops any fading which is applied to this action.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  stopFading() {
    const t = this._weightInterpolant;
    return t !== null && (this._weightInterpolant = null, this._mixer._takeBackControlInterpolant(t)), this;
  }
  /**
   * Sets the effective time scale of this action.
   *
   * An action has no effect and thus an effective time scale of zero when the
   * action is paused.
   *
   * @param {number} timeScale - The time scale to set.
   * @return {AnimationAction} A reference to this animation action.
   */
  setEffectiveTimeScale(t) {
    return this.timeScale = t, this._effectiveTimeScale = this.paused ? 0 : t, this.stopWarping();
  }
  /**
   * Returns the effective time scale of this action.
   *
   * @return {number} The effective time scale.
   */
  getEffectiveTimeScale() {
    return this._effectiveTimeScale;
  }
  /**
   * Sets the duration for a single loop of this action.
   *
   * @param {number} duration - The duration to set.
   * @return {AnimationAction} A reference to this animation action.
   */
  setDuration(t) {
    return this.timeScale = this._clip.duration / t, this.stopWarping();
  }
  /**
   * Synchronizes this action with the passed other action.
   *
   * @param {AnimationAction} action - The action to sync with.
   * @return {AnimationAction} A reference to this animation action.
   */
  syncWith(t) {
    return this.time = t.time, this.timeScale = t.timeScale, this.stopWarping();
  }
  /**
   * Decelerates this animation's speed to `0` within the passed time interval.
   *
   * @param {number} duration - The duration.
   * @return {AnimationAction} A reference to this animation action.
   */
  halt(t) {
    return this.warp(this._effectiveTimeScale, 0, t);
  }
  /**
   * Changes the playback speed, within the passed time interval, by modifying
   * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
   * `endTimeScale`.
   *
   * @param {number} startTimeScale - The start time scale.
   * @param {number} endTimeScale - The end time scale.
   * @param {number} duration - The duration.
   * @return {AnimationAction} A reference to this animation action.
   */
  warp(t, e, i) {
    const n = this._mixer, s = n.time, r = this.timeScale;
    let o = this._timeScaleInterpolant;
    o === null && (o = n._lendControlInterpolant(), this._timeScaleInterpolant = o);
    const l = o.parameterPositions, h = o.sampleValues;
    return l[0] = s, l[1] = s + i, h[0] = t / r, h[1] = e / r, this;
  }
  /**
   * Stops any scheduled warping which is applied to this action.
   *
   * @return {AnimationAction} A reference to this animation action.
   */
  stopWarping() {
    const t = this._timeScaleInterpolant;
    return t !== null && (this._timeScaleInterpolant = null, this._mixer._takeBackControlInterpolant(t)), this;
  }
  /**
   * Returns the animation mixer of this animation action.
   *
   * @return {AnimationMixer} The animation mixer.
   */
  getMixer() {
    return this._mixer;
  }
  /**
   * Returns the animation clip of this animation action.
   *
   * @return {AnimationClip} The animation clip.
   */
  getClip() {
    return this._clip;
  }
  /**
   * Returns the root object of this animation action.
   *
   * @return {Object3D} The root object.
   */
  getRoot() {
    return this._localRoot || this._mixer._root;
  }
  // Interna
  _update(t, e, i, n) {
    if (!this.enabled) {
      this._updateWeight(t);
      return;
    }
    const s = this._startTime;
    if (s !== null) {
      const l = (t - s) * i;
      l < 0 || i === 0 ? e = 0 : (this._startTime = null, e = i * l);
    }
    e *= this._updateTimeScale(t);
    const r = this._updateTime(e), o = this._updateWeight(t);
    if (o > 0) {
      const l = this._interpolants, h = this._propertyBindings;
      switch (this.blendMode) {
        case Dp:
          for (let c = 0, u = l.length; c !== u; ++c)
            l[c].evaluate(r), h[c].accumulateAdditive(o);
          break;
        case Uc:
        default:
          for (let c = 0, u = l.length; c !== u; ++c)
            l[c].evaluate(r), h[c].accumulate(n, o);
      }
    }
  }
  _updateWeight(t) {
    let e = 0;
    if (this.enabled) {
      e = this.weight;
      const i = this._weightInterpolant;
      if (i !== null) {
        const n = i.evaluate(t)[0];
        e *= n, t > i.parameterPositions[1] && (this.stopFading(), n === 0 && (this.enabled = !1));
      }
    }
    return this._effectiveWeight = e, e;
  }
  _updateTimeScale(t) {
    let e = 0;
    if (!this.paused) {
      e = this.timeScale;
      const i = this._timeScaleInterpolant;
      if (i !== null) {
        const n = i.evaluate(t)[0];
        e *= n, t > i.parameterPositions[1] && (this.stopWarping(), e === 0 ? this.paused = !0 : this.timeScale = e);
      }
    }
    return this._effectiveTimeScale = e, e;
  }
  _updateTime(t) {
    const e = this._clip.duration, i = this.loop;
    let n = this.time + t, s = this._loopCount;
    const r = i === Lp;
    if (t === 0)
      return s === -1 ? n : r && (s & 1) === 1 ? e - n : n;
    if (i === ey) {
      s === -1 && (this._loopCount = 0, this._setEndings(!0, !0, !1));
      t: {
        if (n >= e)
          n = e;
        else if (n < 0)
          n = 0;
        else {
          this.time = n;
          break t;
        }
        this.clampWhenFinished ? this.paused = !0 : this.enabled = !1, this.time = n, this._mixer.dispatchEvent({
          type: "finished",
          action: this,
          direction: t < 0 ? -1 : 1
        });
      }
    } else {
      if (s === -1 && (t >= 0 ? (s = 0, this._setEndings(!0, this.repetitions === 0, r)) : this._setEndings(this.repetitions === 0, !0, r)), n >= e || n < 0) {
        const o = Math.floor(n / e);
        n -= e * o, s += Math.abs(o);
        const l = this.repetitions - s;
        if (l <= 0)
          this.clampWhenFinished ? this.paused = !0 : this.enabled = !1, n = t > 0 ? e : 0, this.time = n, this._mixer.dispatchEvent({
            type: "finished",
            action: this,
            direction: t > 0 ? 1 : -1
          });
        else {
          if (l === 1) {
            const h = t < 0;
            this._setEndings(h, !h, r);
          } else
            this._setEndings(!1, !1, r);
          this._loopCount = s, this.time = n, this._mixer.dispatchEvent({
            type: "loop",
            action: this,
            loopDelta: o
          });
        }
      } else
        this.time = n;
      if (r && (s & 1) === 1)
        return e - n;
    }
    return n;
  }
  _setEndings(t, e, i) {
    const n = this._interpolantSettings;
    i ? (n.endingStart = rr, n.endingEnd = rr) : (t ? n.endingStart = this.zeroSlopeAtStart ? rr : sr : n.endingStart = Ao, e ? n.endingEnd = this.zeroSlopeAtEnd ? rr : sr : n.endingEnd = Ao);
  }
  _scheduleFading(t, e, i) {
    const n = this._mixer, s = n.time;
    let r = this._weightInterpolant;
    r === null && (r = n._lendControlInterpolant(), this._weightInterpolant = r);
    const o = r.parameterPositions, l = r.sampleValues;
    return o[0] = s, l[0] = e, o[1] = s + t, l[1] = i, this;
  }
}
const pM = new Float32Array(1);
class y_ extends Ei {
  /**
   * Constructs a new animation mixer.
   *
   * @param {Object3D} root - The object whose animations shall be played by this mixer.
   */
  constructor(t) {
    super(), this._root = t, this._initMemoryManager(), this._accuIndex = 0, this.time = 0, this.timeScale = 1;
  }
  _bindAction(t, e) {
    const i = t._localRoot || this._root, n = t._clip.tracks, s = n.length, r = t._propertyBindings, o = t._interpolants, l = i.uuid, h = this._bindingsByRootAndName;
    let c = h[l];
    c === void 0 && (c = {}, h[l] = c);
    for (let u = 0; u !== s; ++u) {
      const d = n[u], p = d.name;
      let f = c[p];
      if (f !== void 0)
        ++f.referenceCount, r[u] = f;
      else {
        if (f = r[u], f !== void 0) {
          f._cacheIndex === null && (++f.referenceCount, this._addInactiveBinding(f, l, p));
          continue;
        }
        const y = e && e._propertyBindings[u].binding.parsedPath;
        f = new m_(
          se.create(i, p, y),
          d.ValueTypeName,
          d.getValueSize()
        ), ++f.referenceCount, this._addInactiveBinding(f, l, p), r[u] = f;
      }
      o[u].resultBuffer = f.buffer;
    }
  }
  _activateAction(t) {
    if (!this._isActiveAction(t)) {
      if (t._cacheIndex === null) {
        const i = (t._localRoot || this._root).uuid, n = t._clip.uuid, s = this._actionsByClip[n];
        this._bindAction(
          t,
          s && s.knownActions[0]
        ), this._addInactiveAction(t, n, i);
      }
      const e = t._propertyBindings;
      for (let i = 0, n = e.length; i !== n; ++i) {
        const s = e[i];
        s.useCount++ === 0 && (this._lendBinding(s), s.saveOriginalState());
      }
      this._lendAction(t);
    }
  }
  _deactivateAction(t) {
    if (this._isActiveAction(t)) {
      const e = t._propertyBindings;
      for (let i = 0, n = e.length; i !== n; ++i) {
        const s = e[i];
        --s.useCount === 0 && (s.restoreOriginalState(), this._takeBackBinding(s));
      }
      this._takeBackAction(t);
    }
  }
  // Memory manager
  _initMemoryManager() {
    this._actions = [], this._nActiveActions = 0, this._actionsByClip = {}, this._bindings = [], this._nActiveBindings = 0, this._bindingsByRootAndName = {}, this._controlInterpolants = [], this._nActiveControlInterpolants = 0;
    const t = this;
    this.stats = {
      actions: {
        get total() {
          return t._actions.length;
        },
        get inUse() {
          return t._nActiveActions;
        }
      },
      bindings: {
        get total() {
          return t._bindings.length;
        },
        get inUse() {
          return t._nActiveBindings;
        }
      },
      controlInterpolants: {
        get total() {
          return t._controlInterpolants.length;
        },
        get inUse() {
          return t._nActiveControlInterpolants;
        }
      }
    };
  }
  // Memory management for AnimationAction objects
  _isActiveAction(t) {
    const e = t._cacheIndex;
    return e !== null && e < this._nActiveActions;
  }
  _addInactiveAction(t, e, i) {
    const n = this._actions, s = this._actionsByClip;
    let r = s[e];
    if (r === void 0)
      r = {
        knownActions: [t],
        actionByRoot: {}
      }, t._byClipCacheIndex = 0, s[e] = r;
    else {
      const o = r.knownActions;
      t._byClipCacheIndex = o.length, o.push(t);
    }
    t._cacheIndex = n.length, n.push(t), r.actionByRoot[i] = t;
  }
  _removeInactiveAction(t) {
    const e = this._actions, i = e[e.length - 1], n = t._cacheIndex;
    i._cacheIndex = n, e[n] = i, e.pop(), t._cacheIndex = null;
    const s = t._clip.uuid, r = this._actionsByClip, o = r[s], l = o.knownActions, h = l[l.length - 1], c = t._byClipCacheIndex;
    h._byClipCacheIndex = c, l[c] = h, l.pop(), t._byClipCacheIndex = null;
    const u = o.actionByRoot, d = (t._localRoot || this._root).uuid;
    delete u[d], l.length === 0 && delete r[s], this._removeInactiveBindingsForAction(t);
  }
  _removeInactiveBindingsForAction(t) {
    const e = t._propertyBindings;
    for (let i = 0, n = e.length; i !== n; ++i) {
      const s = e[i];
      --s.referenceCount === 0 && this._removeInactiveBinding(s);
    }
  }
  _lendAction(t) {
    const e = this._actions, i = t._cacheIndex, n = this._nActiveActions++, s = e[n];
    t._cacheIndex = n, e[n] = t, s._cacheIndex = i, e[i] = s;
  }
  _takeBackAction(t) {
    const e = this._actions, i = t._cacheIndex, n = --this._nActiveActions, s = e[n];
    t._cacheIndex = n, e[n] = t, s._cacheIndex = i, e[i] = s;
  }
  // Memory management for PropertyMixer objects
  _addInactiveBinding(t, e, i) {
    const n = this._bindingsByRootAndName, s = this._bindings;
    let r = n[e];
    r === void 0 && (r = {}, n[e] = r), r[i] = t, t._cacheIndex = s.length, s.push(t);
  }
  _removeInactiveBinding(t) {
    const e = this._bindings, i = t.binding, n = i.rootNode.uuid, s = i.path, r = this._bindingsByRootAndName, o = r[n], l = e[e.length - 1], h = t._cacheIndex;
    l._cacheIndex = h, e[h] = l, e.pop(), delete o[s], Object.keys(o).length === 0 && delete r[n];
  }
  _lendBinding(t) {
    const e = this._bindings, i = t._cacheIndex, n = this._nActiveBindings++, s = e[n];
    t._cacheIndex = n, e[n] = t, s._cacheIndex = i, e[i] = s;
  }
  _takeBackBinding(t) {
    const e = this._bindings, i = t._cacheIndex, n = --this._nActiveBindings, s = e[n];
    t._cacheIndex = n, e[n] = t, s._cacheIndex = i, e[i] = s;
  }
  // Memory management of Interpolants for weight and time scale
  _lendControlInterpolant() {
    const t = this._controlInterpolants, e = this._nActiveControlInterpolants++;
    let i = t[e];
    return i === void 0 && (i = new tf(
      new Float32Array(2),
      new Float32Array(2),
      1,
      pM
    ), i.__cacheIndex = e, t[e] = i), i;
  }
  _takeBackControlInterpolant(t) {
    const e = this._controlInterpolants, i = t.__cacheIndex, n = --this._nActiveControlInterpolants, s = e[n];
    t.__cacheIndex = n, e[n] = t, s.__cacheIndex = i, e[i] = s;
  }
  /**
   * Returns an instance of {@link AnimationAction} for the passed clip.
   *
   * If an action fitting the clip and root parameters doesn't yet exist, it
   * will be created by this method. Calling this method several times with the
   * same clip and root parameters always returns the same action.
   *
   * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
   * @param {Object3D} [optionalRoot] - An alternative root object.
   * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
   * @return {?AnimationAction} The animation action.
   */
  clipAction(t, e, i) {
    const n = e || this._root, s = n.uuid;
    let r = typeof t == "string" ? Ma.findByName(n, t) : t;
    const o = r !== null ? r.uuid : t, l = this._actionsByClip[o];
    let h = null;
    if (i === void 0 && (r !== null ? i = r.blendMode : i = Uc), l !== void 0) {
      const u = l.actionByRoot[s];
      if (u !== void 0 && u.blendMode === i)
        return u;
      h = l.knownActions[0], r === null && (r = h._clip);
    }
    if (r === null) return null;
    const c = new g_(this, r, e, i);
    return this._bindAction(c, h), this._addInactiveAction(c, o, s), c;
  }
  /**
   * Returns an existing animation action for the passed clip.
   *
   * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
   * @param {Object3D} [optionalRoot] - An alternative root object.
   * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
   */
  existingAction(t, e) {
    const i = e || this._root, n = i.uuid, s = typeof t == "string" ? Ma.findByName(i, t) : t, r = s ? s.uuid : t, o = this._actionsByClip[r];
    return o !== void 0 && o.actionByRoot[n] || null;
  }
  /**
   * Deactivates all previously scheduled actions on this mixer.
   *
   * @return {AnimationMixer} A reference to thi animation mixer.
   */
  stopAllAction() {
    const t = this._actions, e = this._nActiveActions;
    for (let i = e - 1; i >= 0; --i)
      t[i].stop();
    return this;
  }
  /**
   * Advances the global mixer time and updates the animation.
   *
   * This is usually done in the render loop by passing the delta
   * time from {@link Clock} or {@link Timer}.
   *
   * @param {number} deltaTime - The delta time in seconds.
   * @return {AnimationMixer} A reference to thi animation mixer.
   */
  update(t) {
    t *= this.timeScale;
    const e = this._actions, i = this._nActiveActions, n = this.time += t, s = Math.sign(t), r = this._accuIndex ^= 1;
    for (let h = 0; h !== i; ++h)
      e[h]._update(n, t, s, r);
    const o = this._bindings, l = this._nActiveBindings;
    for (let h = 0; h !== l; ++h)
      o[h].apply(r);
    return this;
  }
  /**
   * Sets the global mixer to a specific time and updates the animation accordingly.
   *
   * This is useful when you need to jump to an exact time in an animation. The
   * input parameter will be scaled by {@link AnimationMixer#timeScale}
   *
   * @param {number} time - The time to set in seconds.
   * @return {AnimationMixer} A reference to thi animation mixer.
   */
  setTime(t) {
    this.time = 0;
    for (let e = 0; e < this._actions.length; e++)
      this._actions[e].time = 0;
    return this.update(t);
  }
  /**
   * Returns this mixer's root object.
   *
   * @return {Object3D} The mixer's root object.
   */
  getRoot() {
    return this._root;
  }
  /**
   * Deallocates all memory resources for a clip. Before using this method make
   * sure to call {@link AnimationAction#stop} for all related actions.
   *
   * @param {AnimationClip} clip - The clip to uncache.
   */
  uncacheClip(t) {
    const e = this._actions, i = t.uuid, n = this._actionsByClip, s = n[i];
    if (s !== void 0) {
      const r = s.knownActions;
      for (let o = 0, l = r.length; o !== l; ++o) {
        const h = r[o];
        this._deactivateAction(h);
        const c = h._cacheIndex, u = e[e.length - 1];
        h._cacheIndex = null, h._byClipCacheIndex = null, u._cacheIndex = c, e[c] = u, e.pop(), this._removeInactiveBindingsForAction(h);
      }
      delete n[i];
    }
  }
  /**
   * Deallocates all memory resources for a root object. Before using this
   * method make sure to call {@link AnimationAction#stop} for all related
   * actions or alternatively {@link AnimationMixer#stopAllAction} when the
   * mixer operates on a single root.
   *
   * @param {Object3D} root - The root object to uncache.
   */
  uncacheRoot(t) {
    const e = t.uuid, i = this._actionsByClip;
    for (const r in i) {
      const o = i[r].actionByRoot, l = o[e];
      l !== void 0 && (this._deactivateAction(l), this._removeInactiveAction(l));
    }
    const n = this._bindingsByRootAndName, s = n[e];
    if (s !== void 0)
      for (const r in s) {
        const o = s[r];
        o.restoreOriginalState(), this._removeInactiveBinding(o);
      }
  }
  /**
   * Deallocates all memory resources for an action. The action is identified by the
   * given clip and an optional root object. Before using this method make
   * sure to call {@link AnimationAction#stop} to deactivate the action.
   *
   * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
   * @param {Object3D} [optionalRoot] - An alternative root object.
   */
  uncacheAction(t, e) {
    const i = this.existingAction(t, e);
    i !== null && (this._deactivateAction(i), this._removeInactiveAction(i));
  }
}
class fM extends Bp {
  /**
   * Constructs a new 3D render target.
   *
   * @param {number} [width=1] - The width of the render target.
   * @param {number} [height=1] - The height of the render target.
   * @param {number} [depth=1] - The height of the render target.
   * @param {RenderTarget~Options} [options] - The configuration object.
   */
  constructor(t = 1, e = 1, i = 1, n = {}) {
    super(t, e, n), this.isRenderTarget3D = !0, this.depth = i, this.texture = new zc(null, t, e, i), this._setTextureOptions(n), this.texture.isRenderTargetTexture = !0;
  }
}
class uf {
  /**
   * Constructs a new uniform.
   *
   * @param {any} value - The uniform value.
   */
  constructor(t) {
    this.value = t;
  }
  /**
   * Returns a new uniform with copied values from this instance.
   * If the value has a `clone()` method, the value is cloned as well.
   *
   * @return {Uniform} A clone of this instance.
   */
  clone() {
    return new uf(this.value.clone === void 0 ? this.value : this.value.clone());
  }
}
let mM = 0;
class gM extends Ei {
  /**
   * Constructs a new uniforms group.
   */
  constructor() {
    super(), this.isUniformsGroup = !0, Object.defineProperty(this, "id", { value: mM++ }), this.name = "", this.usage = Co, this.uniforms = [];
  }
  /**
   * Adds the given uniform to this uniforms group.
   *
   * @param {Uniform} uniform - The uniform to add.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  add(t) {
    return this.uniforms.push(t), this;
  }
  /**
   * Removes the given uniform from this uniforms group.
   *
   * @param {Uniform} uniform - The uniform to remove.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  remove(t) {
    const e = this.uniforms.indexOf(t);
    return e !== -1 && this.uniforms.splice(e, 1), this;
  }
  /**
   * Sets the name of this uniforms group.
   *
   * @param {string} name - The name to set.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  setName(t) {
    return this.name = t, this;
  }
  /**
   * Sets the usage of this uniforms group.
   *
   * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  setUsage(t) {
    return this.usage = t, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires Texture#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  /**
   * Copies the values of the given uniforms group to this instance.
   *
   * @param {UniformsGroup} source - The uniforms group to copy.
   * @return {UniformsGroup} A reference to this uniforms group.
   */
  copy(t) {
    this.name = t.name, this.usage = t.usage;
    const e = t.uniforms;
    this.uniforms.length = 0;
    for (let i = 0, n = e.length; i < n; i++) {
      const s = Array.isArray(e[i]) ? e[i] : [e[i]];
      for (let r = 0; r < s.length; r++)
        this.uniforms.push(s[r].clone());
    }
    return this;
  }
  /**
   * Returns a new uniforms group with copied values from this instance.
   *
   * @return {UniformsGroup} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
let vc = class extends Gc {
  /**
   * Constructs a new instanced interleaved buffer.
   *
   * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
   * @param {number} stride - The number of typed-array elements per vertex.
   * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
   */
  constructor(t, e, i = 1) {
    super(t, e), this.isInstancedInterleavedBuffer = !0, this.meshPerAttribute = i;
  }
  copy(t) {
    return super.copy(t), this.meshPerAttribute = t.meshPerAttribute, this;
  }
  clone(t) {
    const e = super.clone(t);
    return e.meshPerAttribute = this.meshPerAttribute, e;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.isInstancedInterleavedBuffer = !0, e.meshPerAttribute = this.meshPerAttribute, e;
  }
};
class yM {
  /**
   * Constructs a new GL buffer attribute.
   *
   * @param {WebGLBuffer} buffer - The native WebGL buffer.
   * @param {number} type - The native data type (e.g. `gl.FLOAT`).
   * @param {number} itemSize - The item size.
   * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
   * @param {number} count - The expected number of vertices in VBO.
   * @param {boolean} [normalized=false] - Whether the data are normalized or not.
   */
  constructor(t, e, i, n, s, r = !1) {
    this.isGLBufferAttribute = !0, this.name = "", this.buffer = t, this.type = e, this.itemSize = i, this.elementSize = n, this.count = s, this.normalized = r, this.version = 0;
  }
  /**
   * Flag to indicate that this attribute has changed and should be re-sent to
   * the GPU. Set this to `true` when you modify the value of the array.
   *
   * @type {number}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  /**
   * Sets the given native WebGL buffer.
   *
   * @param {WebGLBuffer} buffer - The buffer to set.
   * @return {BufferAttribute} A reference to this instance.
   */
  setBuffer(t) {
    return this.buffer = t, this;
  }
  /**
   * Sets the given native data type and element size.
   *
   * @param {number} type - The native data type (e.g. `gl.FLOAT`).
   * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
   * @return {BufferAttribute} A reference to this instance.
   */
  setType(t, e) {
    return this.type = t, this.elementSize = e, this;
  }
  /**
   * Sets the item size.
   *
   * @param {number} itemSize - The item size.
   * @return {BufferAttribute} A reference to this instance.
   */
  setItemSize(t) {
    return this.itemSize = t, this;
  }
  /**
   * Sets the count (the expected number of vertices in VBO).
   *
   * @param {number} count - The count.
   * @return {BufferAttribute} A reference to this instance.
   */
  setCount(t) {
    return this.count = t, this;
  }
}
const Tm = /* @__PURE__ */ new Vt();
let __ = class {
  /**
   * Constructs a new raycaster.
   *
   * @param {Vector3} origin - The origin vector where the ray casts from.
   * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
   * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
   * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
   */
  constructor(t, e, i = 0, n = 1 / 0) {
    this.ray = new Aa(t, e), this.near = i, this.far = n, this.camera = null, this.layers = new Nc(), this.params = {
      Mesh: {},
      Line: { threshold: 1 },
      LOD: {},
      Points: { threshold: 1 },
      Sprite: {}
    };
  }
  /**
   * Updates the ray with a new origin and direction by copying the values from the arguments.
   *
   * @param {Vector3} origin - The origin vector where the ray casts from.
   * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
   */
  set(t, e) {
    this.ray.set(t, e);
  }
  /**
   * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
   *
   * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
   * X and Y components should be between `-1` and `1`.
   * @param {Camera} camera - The camera from which the ray should originate.
   */
  setFromCamera(t, e) {
    e.isPerspectiveCamera ? (this.ray.origin.setFromMatrixPosition(e.matrixWorld), this.ray.direction.set(t.x, t.y, 0.5).unproject(e).sub(this.ray.origin).normalize(), this.camera = e) : e.isOrthographicCamera ? (this.ray.origin.set(t.x, t.y, (e.near + e.far) / (e.near - e.far)).unproject(e), this.ray.direction.set(0, 0, -1).transformDirection(e.matrixWorld), this.camera = e) : console.error("THREE.Raycaster: Unsupported camera type: " + e.type);
  }
  /**
   * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
   *
   * @param {WebXRController} controller - The controller to copy the position and direction from.
   * @return {Raycaster} A reference to this raycaster.
   */
  setFromXRController(t) {
    return Tm.identity().extractRotation(t.matrixWorld), this.ray.origin.setFromMatrixPosition(t.matrixWorld), this.ray.direction.set(0, 0, -1).applyMatrix4(Tm), this;
  }
  /**
   * The intersection point of a raycaster intersection test.
   * @typedef {Object} Raycaster~Intersection
   * @property {number} distance - The distance from the ray's origin to the intersection point.
   * @property {number} distanceToRay -  Some 3D objects e.g. {@link Points} provide the distance of the
   * intersection to the nearest point on the ray. For other objects it will be `undefined`.
   * @property {Vector3} point - The intersection point, in world coordinates.
   * @property {Object} face - The face that has been intersected.
   * @property {number} faceIndex - The face index.
   * @property {Object3D} object - The 3D object that has been intersected.
   * @property {Vector2} uv - U,V coordinates at point of intersection.
   * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
   * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
   * @property {number} instanceId - The index number of the instance where the ray
   * intersects the {@link InstancedMesh}.
   */
  /**
   * Checks all intersection between the ray and the object with or without the
   * descendants. Intersections are returned sorted by distance, closest first.
   *
   * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
   * evaluating whether the ray intersects the object or not. This allows meshes to respond
   * differently to ray casting than lines or points.
   *
   * Note that for meshes, faces must be pointed towards the origin of the ray in order
   * to be detected; intersections of the ray passing through the back of a face will not
   * be detected. To raycast against both faces of an object, you'll want to set  {@link Material#side}
   * to `THREE.DoubleSide`.
   *
   * @param {Object3D} object - The 3D object to check for intersection with the ray.
   * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
   * Otherwise it only checks intersection with the object.
   * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
   * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
   */
  intersectObject(t, e = !0, i = []) {
    return ap(t, this, i, e), i.sort(Cm), i;
  }
  /**
   * Checks all intersection between the ray and the objects with or without
   * the descendants. Intersections are returned sorted by distance, closest first.
   *
   * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
   * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
   * Otherwise it only checks intersection with the object.
   * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
   * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
   */
  intersectObjects(t, e = !0, i = []) {
    for (let n = 0, s = t.length; n < s; n++)
      ap(t[n], this, i, e);
    return i.sort(Cm), i;
  }
};
function Cm(a, t) {
  return a.distance - t.distance;
}
function ap(a, t, e, i) {
  let n = !0;
  if (a.layers.test(t.layers) && a.raycast(t, e) === !1 && (n = !1), n === !0 && i === !0) {
    const s = a.children;
    for (let r = 0, o = s.length; r < o; r++)
      ap(s[r], t, e, !0);
  }
}
let _M = class {
  /**
   * Constructs a new timer.
   */
  constructor() {
    this._previousTime = 0, this._currentTime = 0, this._startTime = performance.now(), this._delta = 0, this._elapsed = 0, this._timescale = 1, this._document = null, this._pageVisibilityHandler = null;
  }
  /**
   * Connect the timer to the given document.Calling this method is not mandatory to
   * use the timer but enables the usage of the Page Visibility API to avoid large time
   * delta values.
   *
   * @param {Document} document - The document.
   */
  connect(t) {
    this._document = t, t.hidden !== void 0 && (this._pageVisibilityHandler = xM.bind(this), t.addEventListener("visibilitychange", this._pageVisibilityHandler, !1));
  }
  /**
   * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
   */
  disconnect() {
    this._pageVisibilityHandler !== null && (this._document.removeEventListener("visibilitychange", this._pageVisibilityHandler), this._pageVisibilityHandler = null), this._document = null;
  }
  /**
   * Returns the time delta in seconds.
   *
   * @return {number} The time delta in second.
   */
  getDelta() {
    return this._delta / 1e3;
  }
  /**
   * Returns the elapsed time in seconds.
   *
   * @return {number} The elapsed time in second.
   */
  getElapsed() {
    return this._elapsed / 1e3;
  }
  /**
   * Returns the timescale.
   *
   * @return {number} The timescale.
   */
  getTimescale() {
    return this._timescale;
  }
  /**
   * Sets the given timescale which scale the time delta computation
   * in `update()`.
   *
   * @param {number} timescale - The timescale to set.
   * @return {Timer} A reference to this timer.
   */
  setTimescale(t) {
    return this._timescale = t, this;
  }
  /**
   * Resets the time computation for the current simulation step.
   *
   * @return {Timer} A reference to this timer.
   */
  reset() {
    return this._currentTime = performance.now() - this._startTime, this;
  }
  /**
   * Can be used to free all internal resources. Usually called when
   * the timer instance isn't required anymore.
   */
  dispose() {
    this.disconnect();
  }
  /**
   * Updates the internal state of the timer. This method should be called
   * once per simulation step and before you perform queries against the timer
   * (e.g. via `getDelta()`).
   *
   * @param {number} timestamp - The current time in milliseconds. Can be obtained
   * from the `requestAnimationFrame` callback argument. If not provided, the current
   * time will be determined with `performance.now`.
   * @return {Timer} A reference to this timer.
   */
  update(t) {
    return this._pageVisibilityHandler !== null && this._document.hidden === !0 ? this._delta = 0 : (this._previousTime = this._currentTime, this._currentTime = (t !== void 0 ? t : performance.now()) - this._startTime, this._delta = (this._currentTime - this._previousTime) * this._timescale, this._elapsed += this._delta), this;
  }
};
function xM() {
  this._document.hidden === !1 && this.reset();
}
class op {
  /**
   * Constructs a new spherical.
   *
   * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
   * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
   * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
   */
  constructor(t = 1, e = 0, i = 0) {
    this.radius = t, this.phi = e, this.theta = i;
  }
  /**
   * Sets the spherical components by copying the given values.
   *
   * @param {number} radius - The radius.
   * @param {number} phi - The polar angle.
   * @param {number} theta - The azimuthal angle.
   * @return {Spherical} A reference to this spherical.
   */
  set(t, e, i) {
    return this.radius = t, this.phi = e, this.theta = i, this;
  }
  /**
   * Copies the values of the given spherical to this instance.
   *
   * @param {Spherical} other - The spherical to copy.
   * @return {Spherical} A reference to this spherical.
   */
  copy(t) {
    return this.radius = t.radius, this.phi = t.phi, this.theta = t.theta, this;
  }
  /**
   * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
   * `0.000001`.
   *
   * @return {Spherical} A reference to this spherical.
   */
  makeSafe() {
    return this.phi = kt(this.phi, 1e-6, Math.PI - 1e-6), this;
  }
  /**
   * Sets the spherical components from the given vector which is assumed to hold
   * Cartesian coordinates.
   *
   * @param {Vector3} v - The vector to set.
   * @return {Spherical} A reference to this spherical.
   */
  setFromVector3(t) {
    return this.setFromCartesianCoords(t.x, t.y, t.z);
  }
  /**
   * Sets the spherical components from the given Cartesian coordinates.
   *
   * @param {number} x - The x value.
   * @param {number} y - The y value.
   * @param {number} z - The z value.
   * @return {Spherical} A reference to this spherical.
   */
  setFromCartesianCoords(t, e, i) {
    return this.radius = Math.sqrt(t * t + e * e + i * i), this.radius === 0 ? (this.theta = 0, this.phi = 0) : (this.theta = Math.atan2(t, i), this.phi = Math.acos(kt(e / this.radius, -1, 1))), this;
  }
  /**
   * Returns a new spherical with copied values from this instance.
   *
   * @return {Spherical} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
class vM {
  /**
   * Constructs a new cylindrical.
   *
   * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
   * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
   * @param {number} [y=0] - The height above the x-z plane.
   */
  constructor(t = 1, e = 0, i = 0) {
    this.radius = t, this.theta = e, this.y = i;
  }
  /**
   * Sets the cylindrical components by copying the given values.
   *
   * @param {number} radius - The radius.
   * @param {number} theta - The theta angle.
   * @param {number} y - The height value.
   * @return {Cylindrical} A reference to this cylindrical.
   */
  set(t, e, i) {
    return this.radius = t, this.theta = e, this.y = i, this;
  }
  /**
   * Copies the values of the given cylindrical to this instance.
   *
   * @param {Cylindrical} other - The cylindrical to copy.
   * @return {Cylindrical} A reference to this cylindrical.
   */
  copy(t) {
    return this.radius = t.radius, this.theta = t.theta, this.y = t.y, this;
  }
  /**
   * Sets the cylindrical components from the given vector which is assumed to hold
   * Cartesian coordinates.
   *
   * @param {Vector3} v - The vector to set.
   * @return {Cylindrical} A reference to this cylindrical.
   */
  setFromVector3(t) {
    return this.setFromCartesianCoords(t.x, t.y, t.z);
  }
  /**
   * Sets the cylindrical components from the given Cartesian coordinates.
   *
   * @param {number} x - The x value.
   * @param {number} y - The x value.
   * @param {number} z - The x value.
   * @return {Cylindrical} A reference to this cylindrical.
   */
  setFromCartesianCoords(t, e, i) {
    return this.radius = Math.sqrt(t * t + i * i), this.theta = Math.atan2(t, i), this.y = e, this;
  }
  /**
   * Returns a new cylindrical with copied values from this instance.
   *
   * @return {Cylindrical} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
}
class df {
  /**
   * Constructs a new 2x2 matrix. The arguments are supposed to be
   * in row-major order. If no arguments are provided, the constructor
   * initializes the matrix as an identity matrix.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   */
  constructor(t, e, i, n) {
    df.prototype.isMatrix2 = !0, this.elements = [
      1,
      0,
      0,
      1
    ], t !== void 0 && this.set(t, e, i, n);
  }
  /**
   * Sets this matrix to the 2x2 identity matrix.
   *
   * @return {Matrix2} A reference to this matrix.
   */
  identity() {
    return this.set(
      1,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets the elements of the matrix from the given array.
   *
   * @param {Array<number>} array - The matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Matrix2} A reference to this matrix.
   */
  fromArray(t, e = 0) {
    for (let i = 0; i < 4; i++)
      this.elements[i] = t[i + e];
    return this;
  }
  /**
   * Sets the elements of the matrix.The arguments are supposed to be
   * in row-major order.
   *
   * @param {number} n11 - 1-1 matrix element.
   * @param {number} n12 - 1-2 matrix element.
   * @param {number} n21 - 2-1 matrix element.
   * @param {number} n22 - 2-2 matrix element.
   * @return {Matrix2} A reference to this matrix.
   */
  set(t, e, i, n) {
    const s = this.elements;
    return s[0] = t, s[2] = e, s[1] = i, s[3] = n, this;
  }
}
const Rm = /* @__PURE__ */ new J();
class bM {
  /**
   * Constructs a new bounding box.
   *
   * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
   * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
   */
  constructor(t = new J(1 / 0, 1 / 0), e = new J(-1 / 0, -1 / 0)) {
    this.isBox2 = !0, this.min = t, this.max = e;
  }
  /**
   * Sets the lower and upper boundaries of this box.
   * Please note that this method only copies the values from the given objects.
   *
   * @param {Vector2} min - The lower boundary of the box.
   * @param {Vector2} max - The upper boundary of the box.
   * @return {Box2} A reference to this bounding box.
   */
  set(t, e) {
    return this.min.copy(t), this.max.copy(e), this;
  }
  /**
   * Sets the upper and lower bounds of this box so it encloses the position data
   * in the given array.
   *
   * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
   * @return {Box2} A reference to this bounding box.
   */
  setFromPoints(t) {
    this.makeEmpty();
    for (let e = 0, i = t.length; e < i; e++)
      this.expandByPoint(t[e]);
    return this;
  }
  /**
   * Centers this box on the given center vector and sets this box's width, height and
   * depth to the given size values.
   *
   * @param {Vector2} center - The center of the box.
   * @param {Vector2} size - The x and y dimensions of the box.
   * @return {Box2} A reference to this bounding box.
   */
  setFromCenterAndSize(t, e) {
    const i = Rm.copy(e).multiplyScalar(0.5);
    return this.min.copy(t).sub(i), this.max.copy(t).add(i), this;
  }
  /**
   * Returns a new box with copied values from this instance.
   *
   * @return {Box2} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given box to this instance.
   *
   * @param {Box2} box - The box to copy.
   * @return {Box2} A reference to this bounding box.
   */
  copy(t) {
    return this.min.copy(t.min), this.max.copy(t.max), this;
  }
  /**
   * Makes this box empty which means in encloses a zero space in 2D.
   *
   * @return {Box2} A reference to this bounding box.
   */
  makeEmpty() {
    return this.min.x = this.min.y = 1 / 0, this.max.x = this.max.y = -1 / 0, this;
  }
  /**
   * Returns true if this box includes zero points within its bounds.
   * Note that a box with equal lower and upper bounds still includes one
   * point, the one both bounds share.
   *
   * @return {boolean} Whether this box is empty or not.
   */
  isEmpty() {
    return this.max.x < this.min.x || this.max.y < this.min.y;
  }
  /**
   * Returns the center point of this box.
   *
   * @param {Vector2} target - The target vector that is used to store the method's result.
   * @return {Vector2} The center point.
   */
  getCenter(t) {
    return this.isEmpty() ? t.set(0, 0) : t.addVectors(this.min, this.max).multiplyScalar(0.5);
  }
  /**
   * Returns the dimensions of this box.
   *
   * @param {Vector2} target - The target vector that is used to store the method's result.
   * @return {Vector2} The size.
   */
  getSize(t) {
    return this.isEmpty() ? t.set(0, 0) : t.subVectors(this.max, this.min);
  }
  /**
   * Expands the boundaries of this box to include the given point.
   *
   * @param {Vector2} point - The point that should be included by the bounding box.
   * @return {Box2} A reference to this bounding box.
   */
  expandByPoint(t) {
    return this.min.min(t), this.max.max(t), this;
  }
  /**
   * Expands this box equilaterally by the given vector. The width of this
   * box will be expanded by the x component of the vector in both
   * directions. The height of this box will be expanded by the y component of
   * the vector in both directions.
   *
   * @param {Vector2} vector - The vector that should expand the bounding box.
   * @return {Box2} A reference to this bounding box.
   */
  expandByVector(t) {
    return this.min.sub(t), this.max.add(t), this;
  }
  /**
   * Expands each dimension of the box by the given scalar. If negative, the
   * dimensions of the box will be contracted.
   *
   * @param {number} scalar - The scalar value that should expand the bounding box.
   * @return {Box2} A reference to this bounding box.
   */
  expandByScalar(t) {
    return this.min.addScalar(-t), this.max.addScalar(t), this;
  }
  /**
   * Returns `true` if the given point lies within or on the boundaries of this box.
   *
   * @param {Vector2} point - The point to test.
   * @return {boolean} Whether the bounding box contains the given point or not.
   */
  containsPoint(t) {
    return t.x >= this.min.x && t.x <= this.max.x && t.y >= this.min.y && t.y <= this.max.y;
  }
  /**
   * Returns `true` if this bounding box includes the entirety of the given bounding box.
   * If this box and the given one are identical, this function also returns `true`.
   *
   * @param {Box2} box - The bounding box to test.
   * @return {boolean} Whether the bounding box contains the given bounding box or not.
   */
  containsBox(t) {
    return this.min.x <= t.min.x && t.max.x <= this.max.x && this.min.y <= t.min.y && t.max.y <= this.max.y;
  }
  /**
   * Returns a point as a proportion of this box's width and height.
   *
   * @param {Vector2} point - A point in 2D space.
   * @param {Vector2} target - The target vector that is used to store the method's result.
   * @return {Vector2} A point as a proportion of this box's width and height.
   */
  getParameter(t, e) {
    return e.set(
      (t.x - this.min.x) / (this.max.x - this.min.x),
      (t.y - this.min.y) / (this.max.y - this.min.y)
    );
  }
  /**
   * Returns `true` if the given bounding box intersects with this bounding box.
   *
   * @param {Box2} box - The bounding box to test.
   * @return {boolean} Whether the given bounding box intersects with this bounding box.
   */
  intersectsBox(t) {
    return t.max.x >= this.min.x && t.min.x <= this.max.x && t.max.y >= this.min.y && t.min.y <= this.max.y;
  }
  /**
   * Clamps the given point within the bounds of this box.
   *
   * @param {Vector2} point - The point to clamp.
   * @param {Vector2} target - The target vector that is used to store the method's result.
   * @return {Vector2} The clamped point.
   */
  clampPoint(t, e) {
    return e.copy(t).clamp(this.min, this.max);
  }
  /**
   * Returns the euclidean distance from any edge of this box to the specified point. If
   * the given point lies inside of this box, the distance will be `0`.
   *
   * @param {Vector2} point - The point to compute the distance to.
   * @return {number} The euclidean distance.
   */
  distanceToPoint(t) {
    return this.clampPoint(t, Rm).distanceTo(t);
  }
  /**
   * Computes the intersection of this bounding box and the given one, setting the upper
   * bound of this box to the lesser of the two boxes' upper bounds and the
   * lower bound of this box to the greater of the two boxes' lower bounds. If
   * there's no overlap, makes this box empty.
   *
   * @param {Box2} box - The bounding box to intersect with.
   * @return {Box2} A reference to this bounding box.
   */
  intersect(t) {
    return this.min.max(t.min), this.max.min(t.max), this.isEmpty() && this.makeEmpty(), this;
  }
  /**
   * Computes the union of this box and another and the given one, setting the upper
   * bound of this box to the greater of the two boxes' upper bounds and the
   * lower bound of this box to the lesser of the two boxes' lower bounds.
   *
   * @param {Box2} box - The bounding box that will be unioned with this instance.
   * @return {Box2} A reference to this bounding box.
   */
  union(t) {
    return this.min.min(t.min), this.max.max(t.max), this;
  }
  /**
   * Adds the given offset to both the upper and lower bounds of this bounding box,
   * effectively moving it in 2D space.
   *
   * @param {Vector2} offset - The offset that should be used to translate the bounding box.
   * @return {Box2} A reference to this bounding box.
   */
  translate(t) {
    return this.min.add(t), this.max.add(t), this;
  }
  /**
   * Returns `true` if this bounding box is equal with the given one.
   *
   * @param {Box2} box - The box to test for equality.
   * @return {boolean} Whether this bounding box is equal with the given one.
   */
  equals(t) {
    return t.min.equals(this.min) && t.max.equals(this.max);
  }
}
const Pm = /* @__PURE__ */ new E(), Il = /* @__PURE__ */ new E(), Nr = /* @__PURE__ */ new E(), Or = /* @__PURE__ */ new E(), Ku = /* @__PURE__ */ new E(), MM = /* @__PURE__ */ new E(), SM = /* @__PURE__ */ new E();
let x_ = class {
  /**
   * Constructs a new line segment.
   *
   * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
   * @param {Vector3} [end=(0,0,0)] - End of the line segment.
   */
  constructor(t = new E(), e = new E()) {
    this.start = t, this.end = e;
  }
  /**
   * Sets the start and end values by copying the given vectors.
   *
   * @param {Vector3} start - The start point.
   * @param {Vector3} end - The end point.
   * @return {Line3} A reference to this line segment.
   */
  set(t, e) {
    return this.start.copy(t), this.end.copy(e), this;
  }
  /**
   * Copies the values of the given line segment to this instance.
   *
   * @param {Line3} line - The line segment to copy.
   * @return {Line3} A reference to this line segment.
   */
  copy(t) {
    return this.start.copy(t.start), this.end.copy(t.end), this;
  }
  /**
   * Returns the center of the line segment.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The center point.
   */
  getCenter(t) {
    return t.addVectors(this.start, this.end).multiplyScalar(0.5);
  }
  /**
   * Returns the delta vector of the line segment's start and end point.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The delta vector.
   */
  delta(t) {
    return t.subVectors(this.end, this.start);
  }
  /**
   * Returns the squared Euclidean distance between the line' start and end point.
   *
   * @return {number} The squared Euclidean distance.
   */
  distanceSq() {
    return this.start.distanceToSquared(this.end);
  }
  /**
   * Returns the Euclidean distance between the line' start and end point.
   *
   * @return {number} The Euclidean distance.
   */
  distance() {
    return this.start.distanceTo(this.end);
  }
  /**
   * Returns a vector at a certain position along the line segment.
   *
   * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The delta vector.
   */
  at(t, e) {
    return this.delta(e).multiplyScalar(t).add(this.start);
  }
  /**
   * Returns a point parameter based on the closest point as projected on the line segment.
   *
   * @param {Vector3} point - The point for which to return a point parameter.
   * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
   * @return {number} The point parameter.
   */
  closestPointToPointParameter(t, e) {
    Pm.subVectors(t, this.start), Il.subVectors(this.end, this.start);
    const i = Il.dot(Il);
    let s = Il.dot(Pm) / i;
    return e && (s = kt(s, 0, 1)), s;
  }
  /**
   * Returns the closest point on the line for a given point.
   *
   * @param {Vector3} point - The point to compute the closest point on the line for.
   * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The closest point on the line.
   */
  closestPointToPoint(t, e, i) {
    const n = this.closestPointToPointParameter(t, e);
    return this.delta(i).multiplyScalar(n).add(this.start);
  }
  /**
   * Returns the closest squared distance between this line segment and the given one.
   *
   * @param {Line3} line - The line segment to compute the closest squared distance to.
   * @param {Vector3} [c1] - The closest point on this line segment.
   * @param {Vector3} [c2] - The closest point on the given line segment.
   * @return {number} The squared distance between this line segment and the given one.
   */
  distanceSqToLine3(t, e = MM, i = SM) {
    const n = 10000000000000001e-32;
    let s, r;
    const o = this.start, l = t.start, h = this.end, c = t.end;
    Nr.subVectors(h, o), Or.subVectors(c, l), Ku.subVectors(o, l);
    const u = Nr.dot(Nr), d = Or.dot(Or), p = Or.dot(Ku);
    if (u <= n && d <= n)
      return e.copy(o), i.copy(l), e.sub(i), e.dot(e);
    if (u <= n)
      s = 0, r = p / d, r = kt(r, 0, 1);
    else {
      const f = Nr.dot(Ku);
      if (d <= n)
        r = 0, s = kt(-f / u, 0, 1);
      else {
        const y = Nr.dot(Or), g = u * d - y * y;
        g !== 0 ? s = kt((y * p - f * d) / g, 0, 1) : s = 0, r = (y * s + p) / d, r < 0 ? (r = 0, s = kt(-f / u, 0, 1)) : r > 1 && (r = 1, s = kt((y - f) / u, 0, 1));
      }
    }
    return e.copy(o).add(Nr.multiplyScalar(s)), i.copy(l).add(Or.multiplyScalar(r)), e.sub(i), e.dot(e);
  }
  /**
   * Applies a 4x4 transformation matrix to this line segment.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   * @return {Line3} A reference to this line segment.
   */
  applyMatrix4(t) {
    return this.start.applyMatrix4(t), this.end.applyMatrix4(t), this;
  }
  /**
   * Returns `true` if this line segment is equal with the given one.
   *
   * @param {Line3} line - The line segment to test for equality.
   * @return {boolean} Whether this line segment is equal with the given one.
   */
  equals(t) {
    return t.start.equals(this.start) && t.end.equals(this.end);
  }
  /**
   * Returns a new line segment with copied values from this instance.
   *
   * @return {Line3} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
};
const Im = /* @__PURE__ */ new E();
class wM extends le {
  /**
   * Constructs a new spot light helper.
   *
   * @param {HemisphereLight} light - The light to be visualized.
   * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
   * the color of the light.
   */
  constructor(t, e) {
    super(), this.light = t, this.matrixAutoUpdate = !1, this.color = e, this.type = "SpotLightHelper";
    const i = new Ht(), n = [
      0,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1,
      0,
      1,
      0,
      0,
      0,
      -1,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      1,
      0,
      0,
      0,
      0,
      -1,
      1
    ];
    for (let r = 0, o = 1, l = 32; r < l; r++, o++) {
      const h = r / l * Math.PI * 2, c = o / l * Math.PI * 2;
      n.push(
        Math.cos(h),
        Math.sin(h),
        1,
        Math.cos(c),
        Math.sin(c),
        1
      );
    }
    i.setAttribute("position", new wt(n, 3));
    const s = new Pe({ fog: !1, toneMapped: !1 });
    this.cone = new oi(i, s), this.add(this.cone), this.update();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.cone.geometry.dispose(), this.cone.material.dispose();
  }
  /**
   * Updates the helper to match the position and direction of the
   * light being visualized.
   */
  update() {
    this.light.updateWorldMatrix(!0, !1), this.light.target.updateWorldMatrix(!0, !1), this.parent ? (this.parent.updateWorldMatrix(!0), this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)) : this.matrix.copy(this.light.matrixWorld), this.matrixWorld.copy(this.light.matrixWorld);
    const t = this.light.distance ? this.light.distance : 1e3, e = t * Math.tan(this.light.angle);
    this.cone.scale.set(e, e, t), Im.setFromMatrixPosition(this.light.target.matrixWorld), this.cone.lookAt(Im), this.color !== void 0 ? this.cone.material.color.set(this.color) : this.cone.material.color.copy(this.light.color);
  }
}
const us = /* @__PURE__ */ new E(), Ll = /* @__PURE__ */ new Vt(), Qu = /* @__PURE__ */ new Vt();
class AM extends oi {
  /**
   * Constructs a new skeleton helper.
   *
   * @param {Object3D} object -  Usually an instance of {@link SkinnedMesh}. However, any 3D object
   * can be used if it represents a hierarchy of bones (see {@link Bone}).
   */
  constructor(t) {
    const e = v_(t), i = new Ht(), n = [], s = [];
    for (let h = 0; h < e.length; h++) {
      const c = e[h];
      c.parent && c.parent.isBone && (n.push(0, 0, 0), n.push(0, 0, 0), s.push(0, 0, 0), s.push(0, 0, 0));
    }
    i.setAttribute("position", new wt(n, 3)), i.setAttribute("color", new wt(s, 3));
    const r = new Pe({ vertexColors: !0, depthTest: !1, depthWrite: !1, toneMapped: !1, transparent: !0 });
    super(i, r), this.isSkeletonHelper = !0, this.type = "SkeletonHelper", this.root = t, this.bones = e, this.matrix = t.matrixWorld, this.matrixAutoUpdate = !1;
    const o = new ct(255), l = new ct(65280);
    this.setColors(o, l);
  }
  updateMatrixWorld(t) {
    const e = this.bones, i = this.geometry, n = i.getAttribute("position");
    Qu.copy(this.root.matrixWorld).invert();
    for (let s = 0, r = 0; s < e.length; s++) {
      const o = e[s];
      o.parent && o.parent.isBone && (Ll.multiplyMatrices(Qu, o.matrixWorld), us.setFromMatrixPosition(Ll), n.setXYZ(r, us.x, us.y, us.z), Ll.multiplyMatrices(Qu, o.parent.matrixWorld), us.setFromMatrixPosition(Ll), n.setXYZ(r + 1, us.x, us.y, us.z), r += 2);
    }
    i.getAttribute("position").needsUpdate = !0, super.updateMatrixWorld(t);
  }
  /**
   * Defines the colors of the helper.
   *
   * @param {Color} color1 - The first line color for each bone.
   * @param {Color} color2 - The second line color for each bone.
   * @return {SkeletonHelper} A reference to this helper.
   */
  setColors(t, e) {
    const n = this.geometry.getAttribute("color");
    for (let s = 0; s < n.count; s += 2)
      n.setXYZ(s, t.r, t.g, t.b), n.setXYZ(s + 1, e.r, e.g, e.b);
    return n.needsUpdate = !0, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
function v_(a) {
  const t = [];
  a.isBone === !0 && t.push(a);
  for (let e = 0; e < a.children.length; e++)
    t.push(...v_(a.children[e]));
  return t;
}
class EM extends re {
  /**
   * Constructs a new point light helper.
   *
   * @param {PointLight} light - The light to be visualized.
   * @param {number} [sphereSize=1] - The size of the sphere helper.
   * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
   * the color of the light.
   */
  constructor(t, e, i) {
    const n = new Ra(e, 4, 2), s = new li({ wireframe: !0, fog: !1, toneMapped: !1 });
    super(n, s), this.light = t, this.color = i, this.type = "PointLightHelper", this.matrix = this.light.matrixWorld, this.matrixAutoUpdate = !1, this.update();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
  /**
   * Updates the helper to match the position of the
   * light being visualized.
   */
  update() {
    this.light.updateWorldMatrix(!0, !1), this.color !== void 0 ? this.material.color.set(this.color) : this.material.color.copy(this.light.color);
  }
}
const TM = /* @__PURE__ */ new E(), Lm = /* @__PURE__ */ new ct(), Dm = /* @__PURE__ */ new ct();
class CM extends le {
  /**
   * Constructs a new hemisphere light helper.
   *
   * @param {HemisphereLight} light - The light to be visualized.
   * @param {number} [size=1] - The size of the mesh used to visualize the light.
   * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
   * the color of the light.
   */
  constructor(t, e, i) {
    super(), this.light = t, this.matrix = t.matrixWorld, this.matrixAutoUpdate = !1, this.color = i, this.type = "HemisphereLightHelper";
    const n = new Ho(e);
    n.rotateY(Math.PI * 0.5), this.material = new li({ wireframe: !0, fog: !1, toneMapped: !1 }), this.color === void 0 && (this.material.vertexColors = !0);
    const s = n.getAttribute("position"), r = new Float32Array(s.count * 3);
    n.setAttribute("color", new ie(r, 3)), this.add(new re(n, this.material)), this.update();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.children[0].geometry.dispose(), this.children[0].material.dispose();
  }
  /**
   * Updates the helper to match the position and direction of the
   * light being visualized.
   */
  update() {
    const t = this.children[0];
    if (this.color !== void 0)
      this.material.color.set(this.color);
    else {
      const e = t.geometry.getAttribute("color");
      Lm.copy(this.light.color), Dm.copy(this.light.groundColor);
      for (let i = 0, n = e.count; i < n; i++) {
        const s = i < n / 2 ? Lm : Dm;
        e.setXYZ(i, s.r, s.g, s.b);
      }
      e.needsUpdate = !0;
    }
    this.light.updateWorldMatrix(!0, !1), t.lookAt(TM.setFromMatrixPosition(this.light.matrixWorld).negate());
  }
}
let RM = class extends oi {
  /**
   * Constructs a new grid helper.
   *
   * @param {number} [size=10] - The size of the grid.
   * @param {number} [divisions=10] - The number of divisions across the grid.
   * @param {number|Color|string} [color1=0x444444] - The color of the center line.
   * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
   */
  constructor(t = 10, e = 10, i = 4473924, n = 8947848) {
    i = new ct(i), n = new ct(n);
    const s = e / 2, r = t / e, o = t / 2, l = [], h = [];
    for (let d = 0, p = 0, f = -o; d <= e; d++, f += r) {
      l.push(-o, 0, f, o, 0, f), l.push(f, 0, -o, f, 0, o);
      const y = d === s ? i : n;
      y.toArray(h, p), p += 3, y.toArray(h, p), p += 3, y.toArray(h, p), p += 3, y.toArray(h, p), p += 3;
    }
    const c = new Ht();
    c.setAttribute("position", new wt(l, 3)), c.setAttribute("color", new wt(h, 3));
    const u = new Pe({ vertexColors: !0, toneMapped: !1 });
    super(c, u), this.type = "GridHelper";
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
};
class PM extends oi {
  /**
   * Constructs a new polar grid helper.
   *
   * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
   * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
   * @param {number} [rings=16] - The number of rings. This can be any positive integer.
   * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
   * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
   * @param {number|Color|string} [color2=0x888888] -  The second color used for grid elements.
   */
  constructor(t = 10, e = 16, i = 8, n = 64, s = 4473924, r = 8947848) {
    s = new ct(s), r = new ct(r);
    const o = [], l = [];
    if (e > 1)
      for (let u = 0; u < e; u++) {
        const d = u / e * (Math.PI * 2), p = Math.sin(d) * t, f = Math.cos(d) * t;
        o.push(0, 0, 0), o.push(p, 0, f);
        const y = u & 1 ? s : r;
        l.push(y.r, y.g, y.b), l.push(y.r, y.g, y.b);
      }
    for (let u = 0; u < i; u++) {
      const d = u & 1 ? s : r, p = t - t / i * u;
      for (let f = 0; f < n; f++) {
        let y = f / n * (Math.PI * 2), g = Math.sin(y) * p, m = Math.cos(y) * p;
        o.push(g, 0, m), l.push(d.r, d.g, d.b), y = (f + 1) / n * (Math.PI * 2), g = Math.sin(y) * p, m = Math.cos(y) * p, o.push(g, 0, m), l.push(d.r, d.g, d.b);
      }
    }
    const h = new Ht();
    h.setAttribute("position", new wt(o, 3)), h.setAttribute("color", new wt(l, 3));
    const c = new Pe({ vertexColors: !0, toneMapped: !1 });
    super(h, c), this.type = "PolarGridHelper";
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
const Fm = /* @__PURE__ */ new E(), Dl = /* @__PURE__ */ new E(), Um = /* @__PURE__ */ new E();
class IM extends le {
  /**
   * Constructs a new directional light helper.
   *
   * @param {DirectionalLight} light - The light to be visualized.
   * @param {number} [size=1] - The dimensions of the plane.
   * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
   * the color of the light.
   */
  constructor(t, e, i) {
    super(), this.light = t, this.matrix = t.matrixWorld, this.matrixAutoUpdate = !1, this.color = i, this.type = "DirectionalLightHelper", e === void 0 && (e = 1);
    let n = new Ht();
    n.setAttribute("position", new wt([
      -e,
      e,
      0,
      e,
      e,
      0,
      e,
      -e,
      0,
      -e,
      -e,
      0,
      -e,
      e,
      0
    ], 3));
    const s = new Pe({ fog: !1, toneMapped: !1 });
    this.lightPlane = new Rs(n, s), this.add(this.lightPlane), n = new Ht(), n.setAttribute("position", new wt([0, 0, 0, 0, 0, 1], 3)), this.targetLine = new Rs(n, s), this.add(this.targetLine), this.update();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.lightPlane.geometry.dispose(), this.lightPlane.material.dispose(), this.targetLine.geometry.dispose(), this.targetLine.material.dispose();
  }
  /**
   * Updates the helper to match the position and direction of the
   * light being visualized.
   */
  update() {
    this.light.updateWorldMatrix(!0, !1), this.light.target.updateWorldMatrix(!0, !1), Fm.setFromMatrixPosition(this.light.matrixWorld), Dl.setFromMatrixPosition(this.light.target.matrixWorld), Um.subVectors(Dl, Fm), this.lightPlane.lookAt(Dl), this.color !== void 0 ? (this.lightPlane.material.color.set(this.color), this.targetLine.material.color.set(this.color)) : (this.lightPlane.material.color.copy(this.light.color), this.targetLine.material.color.copy(this.light.color)), this.targetLine.lookAt(Dl), this.targetLine.scale.z = Um.length();
  }
}
const Fl = /* @__PURE__ */ new E(), Ee = /* @__PURE__ */ new kc();
class LM extends oi {
  /**
   * Constructs a new arrow helper.
   *
   * @param {Camera} camera - The camera to visualize.
   */
  constructor(t) {
    const e = new Ht(), i = new Pe({ color: 16777215, vertexColors: !0, toneMapped: !1 }), n = [], s = [], r = {};
    o("n1", "n2"), o("n2", "n4"), o("n4", "n3"), o("n3", "n1"), o("f1", "f2"), o("f2", "f4"), o("f4", "f3"), o("f3", "f1"), o("n1", "f1"), o("n2", "f2"), o("n3", "f3"), o("n4", "f4"), o("p", "n1"), o("p", "n2"), o("p", "n3"), o("p", "n4"), o("u1", "u2"), o("u2", "u3"), o("u3", "u1"), o("c", "t"), o("p", "c"), o("cn1", "cn2"), o("cn3", "cn4"), o("cf1", "cf2"), o("cf3", "cf4");
    function o(f, y) {
      l(f), l(y);
    }
    function l(f) {
      n.push(0, 0, 0), s.push(0, 0, 0), r[f] === void 0 && (r[f] = []), r[f].push(n.length / 3 - 1);
    }
    e.setAttribute("position", new wt(n, 3)), e.setAttribute("color", new wt(s, 3)), super(e, i), this.type = "CameraHelper", this.camera = t, this.camera.updateProjectionMatrix && this.camera.updateProjectionMatrix(), this.matrix = t.matrixWorld, this.matrixAutoUpdate = !1, this.pointMap = r, this.update();
    const h = new ct(16755200), c = new ct(16711680), u = new ct(43775), d = new ct(16777215), p = new ct(3355443);
    this.setColors(h, c, u, d, p);
  }
  /**
   * Defines the colors of the helper.
   *
   * @param {Color} frustum - The frustum line color.
   * @param {Color} cone - The cone line color.
   * @param {Color} up - The up line color.
   * @param {Color} target - The target line color.
   * @param {Color} cross - The cross line color.
   * @return {CameraHelper} A reference to this helper.
   */
  setColors(t, e, i, n, s) {
    const o = this.geometry.getAttribute("color");
    return o.setXYZ(0, t.r, t.g, t.b), o.setXYZ(1, t.r, t.g, t.b), o.setXYZ(2, t.r, t.g, t.b), o.setXYZ(3, t.r, t.g, t.b), o.setXYZ(4, t.r, t.g, t.b), o.setXYZ(5, t.r, t.g, t.b), o.setXYZ(6, t.r, t.g, t.b), o.setXYZ(7, t.r, t.g, t.b), o.setXYZ(8, t.r, t.g, t.b), o.setXYZ(9, t.r, t.g, t.b), o.setXYZ(10, t.r, t.g, t.b), o.setXYZ(11, t.r, t.g, t.b), o.setXYZ(12, t.r, t.g, t.b), o.setXYZ(13, t.r, t.g, t.b), o.setXYZ(14, t.r, t.g, t.b), o.setXYZ(15, t.r, t.g, t.b), o.setXYZ(16, t.r, t.g, t.b), o.setXYZ(17, t.r, t.g, t.b), o.setXYZ(18, t.r, t.g, t.b), o.setXYZ(19, t.r, t.g, t.b), o.setXYZ(20, t.r, t.g, t.b), o.setXYZ(21, t.r, t.g, t.b), o.setXYZ(22, t.r, t.g, t.b), o.setXYZ(23, t.r, t.g, t.b), o.setXYZ(24, e.r, e.g, e.b), o.setXYZ(25, e.r, e.g, e.b), o.setXYZ(26, e.r, e.g, e.b), o.setXYZ(27, e.r, e.g, e.b), o.setXYZ(28, e.r, e.g, e.b), o.setXYZ(29, e.r, e.g, e.b), o.setXYZ(30, e.r, e.g, e.b), o.setXYZ(31, e.r, e.g, e.b), o.setXYZ(32, i.r, i.g, i.b), o.setXYZ(33, i.r, i.g, i.b), o.setXYZ(34, i.r, i.g, i.b), o.setXYZ(35, i.r, i.g, i.b), o.setXYZ(36, i.r, i.g, i.b), o.setXYZ(37, i.r, i.g, i.b), o.setXYZ(38, n.r, n.g, n.b), o.setXYZ(39, n.r, n.g, n.b), o.setXYZ(40, s.r, s.g, s.b), o.setXYZ(41, s.r, s.g, s.b), o.setXYZ(42, s.r, s.g, s.b), o.setXYZ(43, s.r, s.g, s.b), o.setXYZ(44, s.r, s.g, s.b), o.setXYZ(45, s.r, s.g, s.b), o.setXYZ(46, s.r, s.g, s.b), o.setXYZ(47, s.r, s.g, s.b), o.setXYZ(48, s.r, s.g, s.b), o.setXYZ(49, s.r, s.g, s.b), o.needsUpdate = !0, this;
  }
  /**
   * Updates the helper based on the projection matrix of the camera.
   */
  update() {
    const t = this.geometry, e = this.pointMap, i = 1, n = 1;
    let s, r;
    if (Ee.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse), this.camera.reversedDepth === !0)
      s = 1, r = 0;
    else if (this.camera.coordinateSystem === Ni)
      s = -1, r = 1;
    else if (this.camera.coordinateSystem === ga)
      s = 0, r = 1;
    else
      throw new Error("THREE.CameraHelper.update(): Invalid coordinate system: " + this.camera.coordinateSystem);
    Te("c", e, t, Ee, 0, 0, s), Te("t", e, t, Ee, 0, 0, r), Te("n1", e, t, Ee, -i, -n, s), Te("n2", e, t, Ee, i, -n, s), Te("n3", e, t, Ee, -i, n, s), Te("n4", e, t, Ee, i, n, s), Te("f1", e, t, Ee, -i, -n, r), Te("f2", e, t, Ee, i, -n, r), Te("f3", e, t, Ee, -i, n, r), Te("f4", e, t, Ee, i, n, r), Te("u1", e, t, Ee, i * 0.7, n * 1.1, s), Te("u2", e, t, Ee, -i * 0.7, n * 1.1, s), Te("u3", e, t, Ee, 0, n * 2, s), Te("cf1", e, t, Ee, -i, 0, r), Te("cf2", e, t, Ee, i, 0, r), Te("cf3", e, t, Ee, 0, -n, r), Te("cf4", e, t, Ee, 0, n, r), Te("cn1", e, t, Ee, -i, 0, s), Te("cn2", e, t, Ee, i, 0, s), Te("cn3", e, t, Ee, 0, -n, s), Te("cn4", e, t, Ee, 0, n, s), t.getAttribute("position").needsUpdate = !0;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
function Te(a, t, e, i, n, s, r) {
  Fl.set(n, s, r).unproject(i);
  const o = t[a];
  if (o !== void 0) {
    const l = e.getAttribute("position");
    for (let h = 0, c = o.length; h < c; h++)
      l.setXYZ(o[h], Fl.x, Fl.y, Fl.z);
  }
}
const Ul = /* @__PURE__ */ new we();
let DM = class extends oi {
  /**
   * Constructs a new box helper.
   *
   * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
   * @param {number|Color|string} [color=0xffff00] - The box's color.
   */
  constructor(t, e = 16776960) {
    const i = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]), n = new Float32Array(8 * 3), s = new Ht();
    s.setIndex(new ie(i, 1)), s.setAttribute("position", new ie(n, 3)), super(s, new Pe({ color: e, toneMapped: !1 })), this.object = t, this.type = "BoxHelper", this.matrixAutoUpdate = !1, this.update();
  }
  /**
   * Updates the helper's geometry to match the dimensions of the object,
   * including any children.
   */
  update() {
    if (this.object !== void 0 && Ul.setFromObject(this.object), Ul.isEmpty()) return;
    const t = Ul.min, e = Ul.max, i = this.geometry.attributes.position, n = i.array;
    n[0] = e.x, n[1] = e.y, n[2] = e.z, n[3] = t.x, n[4] = e.y, n[5] = e.z, n[6] = t.x, n[7] = t.y, n[8] = e.z, n[9] = e.x, n[10] = t.y, n[11] = e.z, n[12] = e.x, n[13] = e.y, n[14] = t.z, n[15] = t.x, n[16] = e.y, n[17] = t.z, n[18] = t.x, n[19] = t.y, n[20] = t.z, n[21] = e.x, n[22] = t.y, n[23] = t.z, i.needsUpdate = !0, this.geometry.computeBoundingSphere();
  }
  /**
   * Updates the wireframe box for the passed object.
   *
   * @param {Object3D} object - The 3D object to create the helper for.
   * @return {BoxHelper} A reference to this instance.
   */
  setFromObject(t) {
    return this.object = t, this.update(), this;
  }
  copy(t, e) {
    return super.copy(t, e), this.object = t.object, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
};
class FM extends oi {
  /**
   * Constructs a new box3 helper.
   *
   * @param {Box3} box - The box to visualize.
   * @param {number|Color|string} [color=0xffff00] - The box's color.
   */
  constructor(t, e = 16776960) {
    const i = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]), n = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1], s = new Ht();
    s.setIndex(new ie(i, 1)), s.setAttribute("position", new wt(n, 3)), super(s, new Pe({ color: e, toneMapped: !1 })), this.box = t, this.type = "Box3Helper", this.geometry.computeBoundingSphere();
  }
  updateMatrixWorld(t) {
    const e = this.box;
    e.isEmpty() || (e.getCenter(this.position), e.getSize(this.scale), this.scale.multiplyScalar(0.5), super.updateMatrixWorld(t));
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
class UM extends Rs {
  /**
   * Constructs a new plane helper.
   *
   * @param {Plane} plane - The plane to be visualized.
   * @param {number} [size=1] - The side length of plane helper.
   * @param {number|Color|string} [hex=0xffff00] - The helper's color.
   */
  constructor(t, e = 1, i = 16776960) {
    const n = i, s = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0], r = new Ht();
    r.setAttribute("position", new wt(s, 3)), r.computeBoundingSphere(), super(r, new Pe({ color: n, toneMapped: !1 })), this.type = "PlaneHelper", this.plane = t, this.size = e;
    const o = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0], l = new Ht();
    l.setAttribute("position", new wt(o, 3)), l.computeBoundingSphere(), this.add(new re(l, new li({ color: n, opacity: 0.2, transparent: !0, depthWrite: !1, toneMapped: !1 })));
  }
  updateMatrixWorld(t) {
    this.position.set(0, 0, 0), this.scale.set(0.5 * this.size, 0.5 * this.size, 1), this.lookAt(this.plane.normal), this.translateZ(-this.plane.constant), super.updateMatrixWorld(t);
  }
  /**
   * Updates the helper to match the position and direction of the
   * light being visualized.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose(), this.children[0].geometry.dispose(), this.children[0].material.dispose();
  }
}
const Bm = /* @__PURE__ */ new E();
let Bl, td;
class BM extends le {
  /**
   * Constructs a new arrow helper.
   *
   * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
   * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
   * @param {number} [length=1] - Length of the arrow in world units.
   * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
   * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
   * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
   */
  constructor(t = new E(0, 0, 1), e = new E(0, 0, 0), i = 1, n = 16776960, s = i * 0.2, r = s * 0.2) {
    super(), this.type = "ArrowHelper", Bl === void 0 && (Bl = new Ht(), Bl.setAttribute("position", new wt([0, 0, 0, 0, 1, 0], 3)), td = new Ca(0.5, 1, 5, 1), td.translate(0, -0.5, 0)), this.position.copy(e), this.line = new Rs(Bl, new Pe({ color: n, toneMapped: !1 })), this.line.matrixAutoUpdate = !1, this.add(this.line), this.cone = new re(td, new li({ color: n, toneMapped: !1 })), this.cone.matrixAutoUpdate = !1, this.add(this.cone), this.setDirection(t), this.setLength(i, s, r);
  }
  /**
   * Sets the direction of the helper.
   *
   * @param {Vector3} dir - The normalized direction vector.
   */
  setDirection(t) {
    if (t.y > 0.99999)
      this.quaternion.set(0, 0, 0, 1);
    else if (t.y < -0.99999)
      this.quaternion.set(1, 0, 0, 0);
    else {
      Bm.set(t.z, 0, -t.x).normalize();
      const e = Math.acos(t.y);
      this.quaternion.setFromAxisAngle(Bm, e);
    }
  }
  /**
   * Sets the length of the helper.
   *
   * @param {number} length - Length of the arrow in world units.
   * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
   * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
   */
  setLength(t, e = t * 0.2, i = e * 0.2) {
    this.line.scale.set(1, Math.max(1e-4, t - e), 1), this.line.updateMatrix(), this.cone.scale.set(i, e, i), this.cone.position.y = t, this.cone.updateMatrix();
  }
  /**
   * Sets the color of the helper.
   *
   * @param {number|Color|string} color - The color to set.
   */
  setColor(t) {
    this.line.material.color.set(t), this.cone.material.color.set(t);
  }
  copy(t) {
    return super.copy(t, !1), this.line.copy(t.line), this.cone.copy(t.cone), this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.line.geometry.dispose(), this.line.material.dispose(), this.cone.geometry.dispose(), this.cone.material.dispose();
  }
}
let zM = class extends oi {
  /**
   * Constructs a new axes helper.
   *
   * @param {number} [size=1] - Size of the lines representing the axes.
   */
  constructor(t = 1) {
    const e = [
      0,
      0,
      0,
      t,
      0,
      0,
      0,
      0,
      0,
      0,
      t,
      0,
      0,
      0,
      0,
      0,
      0,
      t
    ], i = [
      1,
      0,
      0,
      1,
      0.6,
      0,
      0,
      1,
      0,
      0.6,
      1,
      0,
      0,
      0,
      1,
      0,
      0.6,
      1
    ], n = new Ht();
    n.setAttribute("position", new wt(e, 3)), n.setAttribute("color", new wt(i, 3));
    const s = new Pe({ vertexColors: !0, toneMapped: !1 });
    super(n, s), this.type = "AxesHelper";
  }
  /**
   * Defines the colors of the axes helper.
   *
   * @param {number|Color|string} xAxisColor - The color for the x axis.
   * @param {number|Color|string} yAxisColor - The color for the y axis.
   * @param {number|Color|string} zAxisColor - The color for the z axis.
   * @return {AxesHelper} A reference to this axes helper.
   */
  setColors(t, e, i) {
    const n = new ct(), s = this.geometry.attributes.color.array;
    return n.set(t), n.toArray(s, 0), n.toArray(s, 3), n.set(e), n.toArray(s, 6), n.toArray(s, 9), n.set(i), n.toArray(s, 12), n.toArray(s, 15), this.geometry.attributes.color.needsUpdate = !0, this;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
};
class b_ {
  /**
   * Constructs a new shape path.
   */
  constructor() {
    this.type = "ShapePath", this.color = new ct(), this.subPaths = [], this.currentPath = null;
  }
  /**
   * Creates a new path and moves it current point to the given one.
   *
   * @param {number} x - The x coordinate.
   * @param {number} y - The y coordinate.
   * @return {ShapePath} A reference to this shape path.
   */
  moveTo(t, e) {
    return this.currentPath = new xc(), this.subPaths.push(this.currentPath), this.currentPath.moveTo(t, e), this;
  }
  /**
   * Adds an instance of {@link LineCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} x - The x coordinate of the end point.
   * @param {number} y - The y coordinate of the end point.
   * @return {ShapePath} A reference to this shape path.
   */
  lineTo(t, e) {
    return this.currentPath.lineTo(t, e), this;
  }
  /**
   * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} aCPx - The x coordinate of the control point.
   * @param {number} aCPy - The y coordinate of the control point.
   * @param {number} aX - The x coordinate of the end point.
   * @param {number} aY - The y coordinate of the end point.
   * @return {ShapePath} A reference to this shape path.
   */
  quadraticCurveTo(t, e, i, n) {
    return this.currentPath.quadraticCurveTo(t, e, i, n), this;
  }
  /**
   * Adds an instance of {@link CubicBezierCurve} to the path by connecting
   * the current point with the given one.
   *
   * @param {number} aCP1x - The x coordinate of the first control point.
   * @param {number} aCP1y - The y coordinate of the first control point.
   * @param {number} aCP2x - The x coordinate of the second control point.
   * @param {number} aCP2y - The y coordinate of the second control point.
   * @param {number} aX - The x coordinate of the end point.
   * @param {number} aY - The y coordinate of the end point.
   * @return {ShapePath} A reference to this shape path.
   */
  bezierCurveTo(t, e, i, n, s, r) {
    return this.currentPath.bezierCurveTo(t, e, i, n, s, r), this;
  }
  /**
   * Adds an instance of {@link SplineCurve} to the path by connecting
   * the current point with the given list of points.
   *
   * @param {Array<Vector2>} pts - An array of points in 2D space.
   * @return {ShapePath} A reference to this shape path.
   */
  splineThru(t) {
    return this.currentPath.splineThru(t), this;
  }
  /**
   * Converts the paths into an array of shapes.
   *
   * @param {boolean} isCCW - By default solid shapes are  defined clockwise (CW) and holes are defined counterclockwise (CCW).
   * If this flag is set to `true`, then those are flipped.
   * @return {Array<Shape>} An array of shapes.
   */
  toShapes(t) {
    function e(m) {
      const v = [];
      for (let x = 0, _ = m.length; x < _; x++) {
        const S = m[x], w = new As();
        w.curves = S.curves, v.push(w);
      }
      return v;
    }
    function i(m, v) {
      const x = v.length;
      let _ = !1;
      for (let S = x - 1, w = 0; w < x; S = w++) {
        let T = v[S], R = v[w], b = R.x - T.x, M = R.y - T.y;
        if (Math.abs(M) > Number.EPSILON) {
          if (M < 0 && (T = v[w], b = -b, R = v[S], M = -M), m.y < T.y || m.y > R.y) continue;
          if (m.y === T.y) {
            if (m.x === T.x) return !0;
          } else {
            const L = M * (m.x - T.x) - b * (m.y - T.y);
            if (L === 0) return !0;
            if (L < 0) continue;
            _ = !_;
          }
        } else {
          if (m.y !== T.y) continue;
          if (R.x <= m.x && m.x <= T.x || T.x <= m.x && m.x <= R.x) return !0;
        }
      }
      return _;
    }
    const n = dn.isClockWise, s = this.subPaths;
    if (s.length === 0) return [];
    let r, o, l;
    const h = [];
    if (s.length === 1)
      return o = s[0], l = new As(), l.curves = o.curves, h.push(l), h;
    let c = !n(s[0].getPoints());
    c = t ? !c : c;
    const u = [], d = [];
    let p = [], f = 0, y;
    d[f] = void 0, p[f] = [];
    for (let m = 0, v = s.length; m < v; m++)
      o = s[m], y = o.getPoints(), r = n(y), r = t ? !r : r, r ? (!c && d[f] && f++, d[f] = { s: new As(), p: y }, d[f].s.curves = o.curves, c && f++, p[f] = []) : p[f].push({ h: o, p: y[0] });
    if (!d[0]) return e(s);
    if (d.length > 1) {
      let m = !1, v = 0;
      for (let x = 0, _ = d.length; x < _; x++)
        u[x] = [];
      for (let x = 0, _ = d.length; x < _; x++) {
        const S = p[x];
        for (let w = 0; w < S.length; w++) {
          const T = S[w];
          let R = !0;
          for (let b = 0; b < d.length; b++)
            i(T.p, d[b].p) && (x !== b && v++, R ? (R = !1, u[b].push(T)) : m = !0);
          R && u[x].push(T);
        }
      }
      v > 0 && m === !1 && (p = u);
    }
    let g;
    for (let m = 0, v = d.length; m < v; m++) {
      l = d[m].s, h.push(l), g = p[m];
      for (let x = 0, _ = g.length; x < _; x++)
        l.holes.push(g[x].h);
    }
    return h;
  }
}
let NM = class extends Ei {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(t, e = null) {
    super(), this.object = t, this.domElement = e, this.enabled = !0, this.state = -1, this.keys = {}, this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }, this.touches = { ONE: null, TWO: null };
  }
  /**
   * Connects the controls to the DOM. This method has so called "side effects" since
   * it adds the module's event listeners to the DOM.
   *
   * @param {HTMLDOMElement} element - The DOM element to connect to.
   */
  connect(t) {
    if (t === void 0) {
      console.warn("THREE.Controls: connect() now requires an element.");
      return;
    }
    this.domElement !== null && this.disconnect(), this.domElement = t;
  }
  /**
   * Disconnects the controls from the DOM.
   */
  disconnect() {
  }
  /**
   * Call this method if you no longer want use to the controls. It frees all internal
   * resources and removes all event listeners.
   */
  dispose() {
  }
  /**
   * Controls should implement this method if they have to update their internal state
   * per simulation step.
   *
   * @param {number} [delta] - The time delta in seconds.
   */
  update() {
  }
};
function OM(a, t) {
  const e = a.image && a.image.width ? a.image.width / a.image.height : 1;
  return e > t ? (a.repeat.x = 1, a.repeat.y = e / t, a.offset.x = 0, a.offset.y = (1 - a.repeat.y) / 2) : (a.repeat.x = t / e, a.repeat.y = 1, a.offset.x = (1 - a.repeat.x) / 2, a.offset.y = 0), a;
}
function kM(a, t) {
  const e = a.image && a.image.width ? a.image.width / a.image.height : 1;
  return e > t ? (a.repeat.x = t / e, a.repeat.y = 1, a.offset.x = (1 - a.repeat.x) / 2, a.offset.y = 0) : (a.repeat.x = 1, a.repeat.y = e / t, a.offset.x = 0, a.offset.y = (1 - a.repeat.y) / 2), a;
}
function VM(a) {
  return a.repeat.x = 1, a.repeat.y = 1, a.offset.x = 0, a.offset.y = 0, a;
}
function lp(a, t, e, i) {
  const n = HM(i);
  switch (e) {
    case Cp:
      return a * t;
    case Lc:
      return a * t / n.components * n.byteLength;
    case No:
      return a * t / n.components * n.byteLength;
    case Pp:
      return a * t * 2 / n.components * n.byteLength;
    case Dc:
      return a * t * 2 / n.components * n.byteLength;
    case Rp:
      return a * t * 3 / n.components * n.byteLength;
    case gi:
      return a * t * 4 / n.components * n.byteLength;
    case Fc:
      return a * t * 4 / n.components * n.byteLength;
    case ho:
    case co:
      return Math.floor((a + 3) / 4) * Math.floor((t + 3) / 4) * 8;
    case uo:
    case po:
      return Math.floor((a + 3) / 4) * Math.floor((t + 3) / 4) * 16;
    case Vh:
    case Gh:
      return Math.max(a, 16) * Math.max(t, 8) / 4;
    case kh:
    case Hh:
      return Math.max(a, 8) * Math.max(t, 8) / 2;
    case Wh:
    case qh:
      return Math.floor((a + 3) / 4) * Math.floor((t + 3) / 4) * 8;
    case $h:
      return Math.floor((a + 3) / 4) * Math.floor((t + 3) / 4) * 16;
    case Xh:
      return Math.floor((a + 3) / 4) * Math.floor((t + 3) / 4) * 16;
    case Yh:
      return Math.floor((a + 4) / 5) * Math.floor((t + 3) / 4) * 16;
    case Zh:
      return Math.floor((a + 4) / 5) * Math.floor((t + 4) / 5) * 16;
    case jh:
      return Math.floor((a + 5) / 6) * Math.floor((t + 4) / 5) * 16;
    case Jh:
      return Math.floor((a + 5) / 6) * Math.floor((t + 5) / 6) * 16;
    case Kh:
      return Math.floor((a + 7) / 8) * Math.floor((t + 4) / 5) * 16;
    case Qh:
      return Math.floor((a + 7) / 8) * Math.floor((t + 5) / 6) * 16;
    case tc:
      return Math.floor((a + 7) / 8) * Math.floor((t + 7) / 8) * 16;
    case ec:
      return Math.floor((a + 9) / 10) * Math.floor((t + 4) / 5) * 16;
    case ic:
      return Math.floor((a + 9) / 10) * Math.floor((t + 5) / 6) * 16;
    case nc:
      return Math.floor((a + 9) / 10) * Math.floor((t + 7) / 8) * 16;
    case sc:
      return Math.floor((a + 9) / 10) * Math.floor((t + 9) / 10) * 16;
    case rc:
      return Math.floor((a + 11) / 12) * Math.floor((t + 9) / 10) * 16;
    case ac:
      return Math.floor((a + 11) / 12) * Math.floor((t + 11) / 12) * 16;
    case oc:
    case lc:
    case hc:
      return Math.ceil(a / 4) * Math.ceil(t / 4) * 16;
    case cc:
    case uc:
      return Math.ceil(a / 4) * Math.ceil(t / 4) * 8;
    case dc:
    case pc:
      return Math.ceil(a / 4) * Math.ceil(t / 4) * 16;
  }
  throw new Error(
    `Unable to determine texture byte length for ${e} format.`
  );
}
function HM(a) {
  switch (a) {
    case pn:
    case wp:
      return { byteLength: 1, components: 1 };
    case da:
    case Ap:
    case wa:
      return { byteLength: 2, components: 1 };
    case Pc:
    case Ic:
      return { byteLength: 2, components: 4 };
    case ns:
    case Rc:
    case wi:
      return { byteLength: 4, components: 1 };
    case Ep:
    case Tp:
      return { byteLength: 4, components: 3 };
  }
  throw new Error(`Unknown texture type ${a}.`);
}
class GM {
  /**
   * Scales the texture as large as possible within its surface without cropping
   * or stretching the texture. The method preserves the original aspect ratio of
   * the texture. Akin to CSS `object-fit: contain`
   *
   * @param {Texture} texture - The texture.
   * @param {number} aspect - The texture's aspect ratio.
   * @return {Texture} The updated texture.
   */
  static contain(t, e) {
    return OM(t, e);
  }
  /**
   * Scales the texture to the smallest possible size to fill the surface, leaving
   * no empty space. The method preserves the original aspect ratio of the texture.
   * Akin to CSS `object-fit: cover`.
   *
   * @param {Texture} texture - The texture.
   * @param {number} aspect - The texture's aspect ratio.
   * @return {Texture} The updated texture.
   */
  static cover(t, e) {
    return kM(t, e);
  }
  /**
   * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
   *
   * @param {Texture} texture - The texture.
   * @return {Texture} The updated texture.
   */
  static fill(t) {
    return VM(t);
  }
  /**
   * Determines how many bytes must be used to represent the texture.
   *
   * @param {number} width - The width of the texture.
   * @param {number} height - The height of the texture.
   * @param {number} format - The texture's format.
   * @param {number} type - The texture's type.
   * @return {number} The byte length.
   */
  static getByteLength(t, e, i, n) {
    return lp(t, e, i, n);
  }
}
typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: {
  revision: Tc
} }));
typeof window < "u" && (window.__THREE__ ? console.warn("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = Tc);
/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
function M_() {
  let a = null, t = !1, e = null, i = null;
  function n(s, r) {
    e(s, r), i = a.requestAnimationFrame(n);
  }
  return {
    start: function() {
      t !== !0 && e !== null && (i = a.requestAnimationFrame(n), t = !0);
    },
    stop: function() {
      a.cancelAnimationFrame(i), t = !1;
    },
    setAnimationLoop: function(s) {
      e = s;
    },
    setContext: function(s) {
      a = s;
    }
  };
}
function WM(a) {
  const t = /* @__PURE__ */ new WeakMap();
  function e(o, l) {
    const h = o.array, c = o.usage, u = h.byteLength, d = a.createBuffer();
    a.bindBuffer(l, d), a.bufferData(l, h, c), o.onUploadCallback();
    let p;
    if (h instanceof Float32Array)
      p = a.FLOAT;
    else if (typeof Float16Array < "u" && h instanceof Float16Array)
      p = a.HALF_FLOAT;
    else if (h instanceof Uint16Array)
      o.isFloat16BufferAttribute ? p = a.HALF_FLOAT : p = a.UNSIGNED_SHORT;
    else if (h instanceof Int16Array)
      p = a.SHORT;
    else if (h instanceof Uint32Array)
      p = a.UNSIGNED_INT;
    else if (h instanceof Int32Array)
      p = a.INT;
    else if (h instanceof Int8Array)
      p = a.BYTE;
    else if (h instanceof Uint8Array)
      p = a.UNSIGNED_BYTE;
    else if (h instanceof Uint8ClampedArray)
      p = a.UNSIGNED_BYTE;
    else
      throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + h);
    return {
      buffer: d,
      type: p,
      bytesPerElement: h.BYTES_PER_ELEMENT,
      version: o.version,
      size: u
    };
  }
  function i(o, l, h) {
    const c = l.array, u = l.updateRanges;
    if (a.bindBuffer(h, o), u.length === 0)
      a.bufferSubData(h, 0, c);
    else {
      u.sort((p, f) => p.start - f.start);
      let d = 0;
      for (let p = 1; p < u.length; p++) {
        const f = u[d], y = u[p];
        y.start <= f.start + f.count + 1 ? f.count = Math.max(
          f.count,
          y.start + y.count - f.start
        ) : (++d, u[d] = y);
      }
      u.length = d + 1;
      for (let p = 0, f = u.length; p < f; p++) {
        const y = u[p];
        a.bufferSubData(
          h,
          y.start * c.BYTES_PER_ELEMENT,
          c,
          y.start,
          y.count
        );
      }
      l.clearUpdateRanges();
    }
    l.onUploadCallback();
  }
  function n(o) {
    return o.isInterleavedBufferAttribute && (o = o.data), t.get(o);
  }
  function s(o) {
    o.isInterleavedBufferAttribute && (o = o.data);
    const l = t.get(o);
    l && (a.deleteBuffer(l.buffer), t.delete(o));
  }
  function r(o, l) {
    if (o.isInterleavedBufferAttribute && (o = o.data), o.isGLBufferAttribute) {
      const c = t.get(o);
      (!c || c.version < o.version) && t.set(o, {
        buffer: o.buffer,
        type: o.type,
        bytesPerElement: o.elementSize,
        version: o.version
      });
      return;
    }
    const h = t.get(o);
    if (h === void 0)
      t.set(o, e(o, l));
    else if (h.version < o.version) {
      if (h.size !== o.array.byteLength)
        throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");
      i(h.buffer, o, l), h.version = o.version;
    }
  }
  return {
    get: n,
    remove: s,
    update: r
  };
}
var qM = `#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`, $M = `#ifdef USE_ALPHAHASH
	const float ALPHA_HASH_SCALE = 0.05;
	float hash2D( vec2 value ) {
		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
	}
	float hash3D( vec3 value ) {
		return hash2D( vec2( hash2D( value.xy ), value.z ) );
	}
	float getAlphaHashThreshold( vec3 position ) {
		float maxDeriv = max(
			length( dFdx( position.xyz ) ),
			length( dFdy( position.xyz ) )
		);
		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
		vec2 pixScales = vec2(
			exp2( floor( log2( pixScale ) ) ),
			exp2( ceil( log2( pixScale ) ) )
		);
		vec2 alpha = vec2(
			hash3D( floor( pixScales.x * position.xyz ) ),
			hash3D( floor( pixScales.y * position.xyz ) )
		);
		float lerpFactor = fract( log2( pixScale ) );
		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
		float a = min( lerpFactor, 1.0 - lerpFactor );
		vec3 cases = vec3(
			x * x / ( 2.0 * a * ( 1.0 - a ) ),
			( x - 0.5 * a ) / ( 1.0 - a ),
			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
		);
		float threshold = ( x < ( 1.0 - a ) )
			? ( ( x < a ) ? cases.x : cases.y )
			: cases.z;
		return clamp( threshold , 1.0e-6, 1.0 );
	}
#endif`, XM = `#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`, YM = `#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`, ZM = `#ifdef USE_ALPHATEST
	#ifdef ALPHA_TO_COVERAGE
	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
	if ( diffuseColor.a == 0.0 ) discard;
	#else
	if ( diffuseColor.a < alphaTest ) discard;
	#endif
#endif`, jM = `#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`, JM = `#ifdef USE_AOMAP
	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
	reflectedLight.indirectDiffuse *= ambientOcclusion;
	#if defined( USE_CLEARCOAT ) 
		clearcoatSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_SHEEN ) 
		sheenSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD )
		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
	#endif
#endif`, KM = `#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`, QM = `#ifdef USE_BATCHING
	#if ! defined( GL_ANGLE_multi_draw )
	#define gl_DrawID _gl_DrawID
	uniform int _gl_DrawID;
	#endif
	uniform highp sampler2D batchingTexture;
	uniform highp usampler2D batchingIdTexture;
	mat4 getBatchingMatrix( const in float i ) {
		int size = textureSize( batchingTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
	float getIndirectIndex( const in int i ) {
		int size = textureSize( batchingIdTexture, 0 ).x;
		int x = i % size;
		int y = i / size;
		return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
	}
#endif
#ifdef USE_BATCHING_COLOR
	uniform sampler2D batchingColorTexture;
	vec3 getBatchingColor( const in float i ) {
		int size = textureSize( batchingColorTexture, 0 ).x;
		int j = int( i );
		int x = j % size;
		int y = j / size;
		return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
	}
#endif`, tS = `#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`, eS = `vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`, iS = `vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`, nS = `float G_BlinnPhong_Implicit( ) {
	return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( specularColor, 1.0, dotVH );
	float G = G_BlinnPhong_Implicit( );
	float D = D_BlinnPhong( shininess, dotNH );
	return F * ( G * D );
} // validated`, sS = `#ifdef USE_IRIDESCENCE
	const mat3 XYZ_TO_REC709 = mat3(
		 3.2404542, -0.9692660,  0.0556434,
		-1.5371385,  1.8760108, -0.2040259,
		-0.4985314,  0.0415560,  1.0572252
	);
	vec3 Fresnel0ToIor( vec3 fresnel0 ) {
		vec3 sqrtF0 = sqrt( fresnel0 );
		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
	}
	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
	}
	float IorToFresnel0( float transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
	}
	vec3 evalSensitivity( float OPD, vec3 shift ) {
		float phase = 2.0 * PI * OPD * 1.0e-9;
		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
		xyz /= 1.0685e-7;
		vec3 rgb = XYZ_TO_REC709 * xyz;
		return rgb;
	}
	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
		vec3 I;
		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
		float cosTheta2Sq = 1.0 - sinTheta2Sq;
		if ( cosTheta2Sq < 0.0 ) {
			return vec3( 1.0 );
		}
		float cosTheta2 = sqrt( cosTheta2Sq );
		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
		float R12 = F_Schlick( R0, 1.0, cosTheta1 );
		float T121 = 1.0 - R12;
		float phi12 = 0.0;
		if ( iridescenceIOR < outsideIOR ) phi12 = PI;
		float phi21 = PI - phi12;
		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
		vec3 phi23 = vec3( 0.0 );
		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
		vec3 phi = vec3( phi21 ) + phi23;
		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
		vec3 r123 = sqrt( R123 );
		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
		vec3 C0 = R12 + Rs;
		I = C0;
		vec3 Cm = Rs - T121;
		for ( int m = 1; m <= 2; ++ m ) {
			Cm *= r123;
			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
			I += Cm * Sm;
		}
		return max( I, vec3( 0.0 ) );
	}
#endif`, rS = `#ifdef USE_BUMPMAP
	uniform sampler2D bumpMap;
	uniform float bumpScale;
	vec2 dHdxy_fwd() {
		vec2 dSTdx = dFdx( vBumpMapUv );
		vec2 dSTdy = dFdy( vBumpMapUv );
		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
		return vec2( dBx, dBy );
	}
	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
		vec3 vN = surf_norm;
		vec3 R1 = cross( vSigmaY, vN );
		vec3 R2 = cross( vN, vSigmaX );
		float fDet = dot( vSigmaX, R1 ) * faceDirection;
		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
		return normalize( abs( fDet ) * surf_norm - vGrad );
	}
#endif`, aS = `#if NUM_CLIPPING_PLANES > 0
	vec4 plane;
	#ifdef ALPHA_TO_COVERAGE
		float distanceToPlane, distanceGradient;
		float clipOpacity = 1.0;
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
			distanceGradient = fwidth( distanceToPlane ) / 2.0;
			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			if ( clipOpacity == 0.0 ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			float unionClipOpacity = 1.0;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
				distanceGradient = fwidth( distanceToPlane ) / 2.0;
				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			}
			#pragma unroll_loop_end
			clipOpacity *= 1.0 - unionClipOpacity;
		#endif
		diffuseColor.a *= clipOpacity;
		if ( diffuseColor.a == 0.0 ) discard;
	#else
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			bool clipped = true;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
			}
			#pragma unroll_loop_end
			if ( clipped ) discard;
		#endif
	#endif
#endif`, oS = `#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`, lS = `#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`, hS = `#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`, cS = `#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`, uS = `#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`, dS = `#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`, pS = `#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif
#ifdef USE_BATCHING_COLOR
	vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
	vColor.xyz *= batchingColor.xyz;
#endif`, fS = `#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
bool isPerspectiveMatrix( mat4 m ) {
	return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
	return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
	return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`, mS = `#ifdef ENVMAP_TYPE_CUBE_UV
	#define cubeUV_minMipLevel 4.0
	#define cubeUV_minTileSize 16.0
	float getFace( vec3 direction ) {
		vec3 absDirection = abs( direction );
		float face = - 1.0;
		if ( absDirection.x > absDirection.z ) {
			if ( absDirection.x > absDirection.y )
				face = direction.x > 0.0 ? 0.0 : 3.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		} else {
			if ( absDirection.z > absDirection.y )
				face = direction.z > 0.0 ? 2.0 : 5.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		}
		return face;
	}
	vec2 getUV( vec3 direction, float face ) {
		vec2 uv;
		if ( face == 0.0 ) {
			uv = vec2( direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 1.0 ) {
			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
		} else if ( face == 2.0 ) {
			uv = vec2( - direction.x, direction.y ) / abs( direction.z );
		} else if ( face == 3.0 ) {
			uv = vec2( - direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 4.0 ) {
			uv = vec2( - direction.x, direction.z ) / abs( direction.y );
		} else {
			uv = vec2( direction.x, direction.y ) / abs( direction.z );
		}
		return 0.5 * ( uv + 1.0 );
	}
	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
		float face = getFace( direction );
		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
		mipInt = max( mipInt, cubeUV_minMipLevel );
		float faceSize = exp2( mipInt );
		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
		if ( face > 2.0 ) {
			uv.y += faceSize;
			face -= 3.0;
		}
		uv.x += face * faceSize;
		uv.x += filterInt * 3.0 * cubeUV_minTileSize;
		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
		uv.x *= CUBEUV_TEXEL_WIDTH;
		uv.y *= CUBEUV_TEXEL_HEIGHT;
		#ifdef texture2DGradEXT
			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
		#else
			return texture2D( envMap, uv ).rgb;
		#endif
	}
	#define cubeUV_r0 1.0
	#define cubeUV_m0 - 2.0
	#define cubeUV_r1 0.8
	#define cubeUV_m1 - 1.0
	#define cubeUV_r4 0.4
	#define cubeUV_m4 2.0
	#define cubeUV_r5 0.305
	#define cubeUV_m5 3.0
	#define cubeUV_r6 0.21
	#define cubeUV_m6 4.0
	float roughnessToMip( float roughness ) {
		float mip = 0.0;
		if ( roughness >= cubeUV_r1 ) {
			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
		} else if ( roughness >= cubeUV_r4 ) {
			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
		} else if ( roughness >= cubeUV_r5 ) {
			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
		} else if ( roughness >= cubeUV_r6 ) {
			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
		} else {
			mip = - 2.0 * log2( 1.16 * roughness );		}
		return mip;
	}
	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
		float mipF = fract( mip );
		float mipInt = floor( mip );
		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
		if ( mipF == 0.0 ) {
			return vec4( color0, 1.0 );
		} else {
			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
			return vec4( mix( color0, color1, mipF ), 1.0 );
		}
	}
#endif`, gS = `vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`, yS = `#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`, _S = `#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`, xS = `#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
		emissiveColor = sRGBTransferEOTF( emissiveColor );
	#endif
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`, vS = `#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`, bS = "gl_FragColor = linearToOutputTexel( gl_FragColor );", MS = `vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
	return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
vec4 sRGBTransferOETF( in vec4 value ) {
	return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}`, SS = `#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#ifdef ENVMAP_BLENDING_MULTIPLY
		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_MIX )
		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_ADD )
		outgoingLight += envColor.xyz * specularStrength * reflectivity;
	#endif
#endif`, wS = `#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
	
#endif`, AS = `#ifdef USE_ENVMAP
	uniform float reflectivity;
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		varying vec3 vWorldPosition;
		uniform float refractionRatio;
	#else
		varying vec3 vReflect;
	#endif
#endif`, ES = `#ifdef USE_ENVMAP
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		
		varying vec3 vWorldPosition;
	#else
		varying vec3 vReflect;
		uniform float refractionRatio;
	#endif
#endif`, TS = `#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`, CS = `#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`, RS = `#ifdef USE_FOG
	varying float vFogDepth;
#endif`, PS = `#ifdef USE_FOG
	#ifdef FOG_EXP2
		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
	#else
		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
	#endif
	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`, IS = `#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`, LS = `#ifdef USE_GRADIENTMAP
	uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
	float dotNL = dot( normal, lightDirection );
	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
	#ifdef USE_GRADIENTMAP
		return vec3( texture2D( gradientMap, coord ).r );
	#else
		vec2 fw = fwidth( coord ) * 0.5;
		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
	#endif
}`, DS = `#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`, FS = `LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`, US = `varying vec3 vViewPosition;
struct LambertMaterial {
	vec3 diffuseColor;
	float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Lambert
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert`, BS = `uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
	if ( cutoffDistance > 0.0 ) {
		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
	}
	return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`, zS = `#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
			return PI * envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 reflectVec = reflect( - viewDir, normal );
			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`, NS = `ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`, OS = `varying vec3 vViewPosition;
struct ToonMaterial {
	vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Toon
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon`, kS = `BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`, VS = `varying vec3 vViewPosition;
struct BlinnPhongMaterial {
	vec3 diffuseColor;
	vec3 specularColor;
	float specularShininess;
	float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_BlinnPhong
#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong`, HS = `PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
	material.ior = ior;
	#ifdef USE_SPECULAR
		float specularIntensityFactor = specularIntensity;
		vec3 specularColorFactor = specularColor;
		#ifdef USE_SPECULAR_COLORMAP
			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
		#endif
		#ifdef USE_SPECULAR_INTENSITYMAP
			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
		#endif
		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
	#else
		float specularIntensityFactor = 1.0;
		vec3 specularColorFactor = vec3( 1.0 );
		material.specularF90 = 1.0;
	#endif
	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
	material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
	#ifdef USE_SHEEN_ROUGHNESSMAP
		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
	#endif
#endif
#ifdef USE_ANISOTROPY
	#ifdef USE_ANISOTROPYMAP
		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
	#else
		vec2 anisotropyV = anisotropyVector;
	#endif
	material.anisotropy = length( anisotropyV );
	if( material.anisotropy == 0.0 ) {
		anisotropyV = vec2( 1.0, 0.0 );
	} else {
		anisotropyV /= material.anisotropy;
		material.anisotropy = saturate( material.anisotropy );
	}
	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`, GS = `struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	float dispersion;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#endif
	#ifdef USE_SHEEN
		vec3 sheenColor;
		float sheenRoughness;
	#endif
	#ifdef IOR
		float ior;
	#endif
	#ifdef USE_TRANSMISSION
		float transmission;
		float transmissionAlpha;
		float thickness;
		float attenuationDistance;
		vec3 attenuationColor;
	#endif
	#ifdef USE_ANISOTROPY
		float anisotropy;
		float alphaT;
		vec3 anisotropyT;
		vec3 anisotropyB;
	#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
    float x2 = x * x;
    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
	float a2 = pow2( alpha );
	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
	return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
	float a2 = pow2( alpha );
	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
	return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
	float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
		float a2 = alphaT * alphaB;
		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
		highp float v2 = dot( v, v );
		float w2 = a2 / v2;
		return RECIPROCAL_PI * a2 * pow2 ( w2 );
	}
#endif
#ifdef USE_CLEARCOAT
	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
		vec3 f0 = material.clearcoatF0;
		float f90 = material.clearcoatF90;
		float roughness = material.clearcoatRoughness;
		float alpha = pow2( roughness );
		vec3 halfDir = normalize( lightDir + viewDir );
		float dotNL = saturate( dot( normal, lightDir ) );
		float dotNV = saturate( dot( normal, viewDir ) );
		float dotNH = saturate( dot( normal, halfDir ) );
		float dotVH = saturate( dot( viewDir, halfDir ) );
		vec3 F = F_Schlick( f0, f90, dotVH );
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
		return F * ( V * D );
	}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 f0 = material.specularColor;
	float f90 = material.specularF90;
	float roughness = material.roughness;
	float alpha = pow2( roughness );
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( f0, f90, dotVH );
	#ifdef USE_IRIDESCENCE
		F = mix( F, material.iridescenceFresnel, material.iridescence );
	#endif
	#ifdef USE_ANISOTROPY
		float dotTL = dot( material.anisotropyT, lightDir );
		float dotTV = dot( material.anisotropyT, viewDir );
		float dotTH = dot( material.anisotropyT, halfDir );
		float dotBL = dot( material.anisotropyB, lightDir );
		float dotBV = dot( material.anisotropyB, viewDir );
		float dotBH = dot( material.anisotropyB, halfDir );
		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
	#else
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
	#endif
	return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
	const float LUT_SIZE = 64.0;
	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
	const float LUT_BIAS = 0.5 / LUT_SIZE;
	float dotNV = saturate( dot( N, V ) );
	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
	uv = uv * LUT_SCALE + LUT_BIAS;
	return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
	float l = length( f );
	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
	float x = dot( v1, v2 );
	float y = abs( x );
	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
	float b = 3.4175940 + ( 4.1616724 + y ) * y;
	float v = a / b;
	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
	return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
	vec3 lightNormal = cross( v1, v2 );
	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
	vec3 T1, T2;
	T1 = normalize( V - N * dot( V, N ) );
	T2 = - cross( N, T1 );
	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
	vec3 coords[ 4 ];
	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
	coords[ 0 ] = normalize( coords[ 0 ] );
	coords[ 1 ] = normalize( coords[ 1 ] );
	coords[ 2 ] = normalize( coords[ 2 ] );
	coords[ 3 ] = normalize( coords[ 3 ] );
	vec3 vectorFormFactor = vec3( 0.0 );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
	return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
	float alpha = pow2( roughness );
	float invAlpha = 1.0 / alpha;
	float cos2h = dotNH * dotNH;
	float sin2h = max( 1.0 - cos2h, 0.0078125 );
	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float D = D_Charlie( sheenRoughness, dotNH );
	float V = V_Neubelt( dotNV, dotNL );
	return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	float r2 = roughness * roughness;
	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#ifdef USE_IRIDESCENCE
		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
	#else
		vec3 Fr = specularColor;
	#endif
	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
	float Ess = fab.x + fab.y;
	float Ems = 1.0 - Ess;
	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
	singleScatter += FssEss;
	multiScatter += Fms * Ems;
}
#if NUM_RECT_AREA_LIGHTS > 0
	void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
		vec3 normal = geometryNormal;
		vec3 viewDir = geometryViewDir;
		vec3 position = geometryPosition;
		vec3 lightPos = rectAreaLight.position;
		vec3 halfWidth = rectAreaLight.halfWidth;
		vec3 halfHeight = rectAreaLight.halfHeight;
		vec3 lightColor = rectAreaLight.color;
		float roughness = material.roughness;
		vec3 rectCoords[ 4 ];
		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
		vec2 uv = LTC_Uv( normal, viewDir, roughness );
		vec4 t1 = texture2D( ltc_1, uv );
		vec4 t2 = texture2D( ltc_2, uv );
		mat3 mInv = mat3(
			vec3( t1.x, 0, t1.y ),
			vec3(    0, 1,    0 ),
			vec3( t1.z, 0, t1.w )
		);
		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	#ifdef USE_CLEARCOAT
		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
		vec3 ccIrradiance = dotNLcc * directLight.color;
		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
	#ifdef USE_CLEARCOAT
		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#define RE_Direct				RE_Direct_Physical
#define RE_Direct_RectArea		RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular		RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`, WS = `
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`, qS = `#if defined( RE_IndirectDiffuse )
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
		irradiance += lightMapIrradiance;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`, $S = `#if defined( RE_IndirectDiffuse )
	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`, XS = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`, YS = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`, ZS = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`, jS = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`, JS = `#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`, KS = `#ifdef USE_MAP
	uniform sampler2D map;
#endif`, QS = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
	#if defined( USE_POINTS_UV )
		vec2 uv = vUv;
	#else
		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
	#endif
#endif
#ifdef USE_MAP
	diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`, t1 = `#if defined( USE_POINTS_UV )
	varying vec2 vUv;
#else
	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
		uniform mat3 uvTransform;
	#endif
#endif
#ifdef USE_MAP
	uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`, e1 = `float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`, i1 = `#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`, n1 = `#ifdef USE_INSTANCING_MORPH
	float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
	}
#endif`, s1 = `#if defined( USE_MORPHCOLORS )
	vColor *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		#if defined( USE_COLOR_ALPHA )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
		#elif defined( USE_COLOR )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
		#endif
	}
#endif`, r1 = `#ifdef USE_MORPHNORMALS
	objectNormal *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
	}
#endif`, a1 = `#ifdef USE_MORPHTARGETS
	#ifndef USE_INSTANCING_MORPH
		uniform float morphTargetBaseInfluence;
		uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	#endif
	uniform sampler2DArray morphTargetsTexture;
	uniform ivec2 morphTargetsTextureSize;
	vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
		int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
		int y = texelIndex / morphTargetsTextureSize.x;
		int x = texelIndex - y * morphTargetsTextureSize.x;
		ivec3 morphUV = ivec3( x, y, morphTargetIndex );
		return texelFetch( morphTargetsTexture, morphUV, 0 );
	}
#endif`, o1 = `#ifdef USE_MORPHTARGETS
	transformed *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
	}
#endif`, l1 = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`, h1 = `#ifdef USE_NORMALMAP_OBJECTSPACE
	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	#ifdef FLIP_SIDED
		normal = - normal;
	#endif
	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif
	normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`, c1 = `#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`, u1 = `#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`, d1 = `#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`, p1 = `#ifdef USE_NORMALMAP
	uniform sampler2D normalMap;
	uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
	uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
		vec3 q0 = dFdx( eye_pos.xyz );
		vec3 q1 = dFdy( eye_pos.xyz );
		vec2 st0 = dFdx( uv.st );
		vec2 st1 = dFdy( uv.st );
		vec3 N = surf_norm;
		vec3 q1perp = cross( q1, N );
		vec3 q0perp = cross( N, q0 );
		vec3 T = q1perp * st0.x + q0perp * st1.x;
		vec3 B = q1perp * st0.y + q0perp * st1.y;
		float det = max( dot( T, T ), dot( B, B ) );
		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
		return mat3( T * scale, B * scale, N );
	}
#endif`, f1 = `#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`, m1 = `#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`, g1 = `#ifdef USE_CLEARCOATMAP
	uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform sampler2D clearcoatNormalMap;
	uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform sampler2D clearcoatRoughnessMap;
#endif`, y1 = `#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`, _1 = `#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`, x1 = `vec3 packNormalToRGB( const in vec3 normal ) {
	return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
	return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
	if( v <= 0.0 )
		return vec4( 0., 0., 0., 0. );
	if( v >= 1.0 )
		return vec4( 1., 1., 1., 1. );
	float vuf;
	float af = modf( v * PackFactors.a, vuf );
	float bf = modf( vuf * ShiftRight8, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
	if( v <= 0.0 )
		return vec3( 0., 0., 0. );
	if( v >= 1.0 )
		return vec3( 1., 1., 1. );
	float vuf;
	float bf = modf( v * PackFactors.b, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
	if( v <= 0.0 )
		return vec2( 0., 0. );
	if( v >= 1.0 )
		return vec2( 1., 1. );
	float vuf;
	float gf = modf( v * 256., vuf );
	return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
	return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
	return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
	return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in vec2 v ) {
	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( const in vec4 v ) {
	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
	return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return depth * ( near - far ) - near;
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`, v1 = `#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`, b1 = `vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
	mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
	mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`, M1 = `#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`, S1 = `#ifdef DITHERING
	vec3 dithering( vec3 color ) {
		float grid_position = rand( gl_FragCoord.xy );
		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
		return color + dither_shift_RGB;
	}
#endif`, w1 = `float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`, A1 = `#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`, E1 = `#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		float depth = unpackRGBAToDepth( texture2D( depths, uv ) );
		#ifdef USE_REVERSED_DEPTH_BUFFER
			return step( depth, compare );
		#else
			return step( compare, depth );
		#endif
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		#ifdef USE_REVERSED_DEPTH_BUFFER
			float hard_shadow = step( distribution.x, compare );
		#else
			float hard_shadow = step( compare, distribution.x );
		#endif
		if ( hard_shadow != 1.0 ) {
			float distance = compare - distribution.x;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
		float shadow = 1.0;
		shadowCoord.xyz /= shadowCoord.w;
		shadowCoord.z += shadowBias;
		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
		if ( frustumTest ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
#endif`, T1 = `#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`, C1 = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`, R1 = `float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
		pointLight = pointLightShadows[ i ];
		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#endif
	return shadow;
}`, P1 = `#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`, I1 = `#ifdef USE_SKINNING
	uniform mat4 bindMatrix;
	uniform mat4 bindMatrixInverse;
	uniform highp sampler2D boneTexture;
	mat4 getBoneMatrix( const in float i ) {
		int size = textureSize( boneTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`, L1 = `#ifdef USE_SKINNING
	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
	vec4 skinned = vec4( 0.0 );
	skinned += boneMatX * skinVertex * skinWeight.x;
	skinned += boneMatY * skinVertex * skinWeight.y;
	skinned += boneMatZ * skinVertex * skinWeight.z;
	skinned += boneMatW * skinVertex * skinWeight.w;
	transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`, D1 = `#ifdef USE_SKINNING
	mat4 skinMatrix = mat4( 0.0 );
	skinMatrix += skinWeight.x * boneMatX;
	skinMatrix += skinWeight.y * boneMatY;
	skinMatrix += skinWeight.z * boneMatZ;
	skinMatrix += skinWeight.w * boneMatW;
	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
	#ifdef USE_TANGENT
		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
	#endif
#endif`, F1 = `float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`, U1 = `#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`, B1 = `#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`, z1 = `#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
	return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 CineonToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	color = max( vec3( 0.0 ), color - 0.004 );
	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
	return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
	const mat3 ACESInputMat = mat3(
		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),
		vec3( 0.04823, 0.01566, 0.83777 )
	);
	const mat3 ACESOutputMat = mat3(
		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),
		vec3( -0.07367, -0.00605,  1.07602 )
	);
	color *= toneMappingExposure / 0.6;
	color = ACESInputMat * color;
	color = RRTAndODTFit( color );
	color = ACESOutputMat * color;
	return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
	vec3( 1.6605, - 0.1246, - 0.0182 ),
	vec3( - 0.5876, 1.1329, - 0.1006 ),
	vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
	vec3( 0.6274, 0.0691, 0.0164 ),
	vec3( 0.3293, 0.9195, 0.0880 ),
	vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
	vec3 x2 = x * x;
	vec3 x4 = x2 * x2;
	return + 15.5 * x4 * x2
		- 40.14 * x4 * x
		+ 31.96 * x4
		- 6.868 * x2 * x
		+ 0.4298 * x2
		+ 0.1191 * x
		- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
	const mat3 AgXInsetMatrix = mat3(
		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
	);
	const mat3 AgXOutsetMatrix = mat3(
		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
	);
	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;
	color *= toneMappingExposure;
	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
	color = AgXInsetMatrix * color;
	color = max( color, 1e-10 );	color = log2( color );
	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
	color = clamp( color, 0.0, 1.0 );
	color = agxDefaultContrastApprox( color );
	color = AgXOutsetMatrix * color;
	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
	color = clamp( color, 0.0, 1.0 );
	return color;
}
vec3 NeutralToneMapping( vec3 color ) {
	const float StartCompression = 0.8 - 0.04;
	const float Desaturation = 0.15;
	color *= toneMappingExposure;
	float x = min( color.r, min( color.g, color.b ) );
	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
	color -= offset;
	float peak = max( color.r, max( color.g, color.b ) );
	if ( peak < StartCompression ) return color;
	float d = 1. - StartCompression;
	float newPeak = 1. - d * d / ( peak + d - StartCompression );
	color *= newPeak / peak;
	float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
	return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`, N1 = `#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
		pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
		material.attenuationColor, material.attenuationDistance );
	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`, O1 = `#ifdef USE_TRANSMISSION
	uniform float transmission;
	uniform float thickness;
	uniform float attenuationDistance;
	uniform vec3 attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		uniform sampler2D transmissionMap;
	#endif
	#ifdef USE_THICKNESSMAP
		uniform sampler2D thicknessMap;
	#endif
	uniform vec2 transmissionSamplerSize;
	uniform sampler2D transmissionSamplerMap;
	uniform mat4 modelMatrix;
	uniform mat4 projectionMatrix;
	varying vec3 vWorldPosition;
	float w0( float a ) {
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
	}
	float w1( float a ) {
		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );
	}
	float w2( float a ){
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
	}
	float w3( float a ) {
		return ( 1.0 / 6.0 ) * ( a * a * a );
	}
	float g0( float a ) {
		return w0( a ) + w1( a );
	}
	float g1( float a ) {
		return w2( a ) + w3( a );
	}
	float h0( float a ) {
		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
	}
	float h1( float a ) {
		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
	}
	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
		uv = uv * texelSize.zw + 0.5;
		vec2 iuv = floor( uv );
		vec2 fuv = fract( uv );
		float g0x = g0( fuv.x );
		float g1x = g1( fuv.x );
		float h0x = h0( fuv.x );
		float h1x = h1( fuv.x );
		float h0y = h0( fuv.y );
		float h1y = h1( fuv.y );
		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
			g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
	}
	vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
		vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
		vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
		vec2 fLodSizeInv = 1.0 / fLodSize;
		vec2 cLodSizeInv = 1.0 / cLodSize;
		vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
		vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
		return mix( fSample, cSample, fract( lod ) );
	}
	vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
		vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
		vec3 modelScale;
		modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
		modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
		modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
		return normalize( refractionVector ) * thickness * modelScale;
	}
	float applyIorToRoughness( const in float roughness, const in float ior ) {
		return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
	}
	vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
		return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
	}
	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
		if ( isinf( attenuationDistance ) ) {
			return vec3( 1.0 );
		} else {
			vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
			vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );			return transmittance;
		}
	}
	vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
		const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
		const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
		const in vec3 attenuationColor, const in float attenuationDistance ) {
		vec4 transmittedLight;
		vec3 transmittance;
		#ifdef USE_DISPERSION
			float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
			vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
			for ( int i = 0; i < 3; i ++ ) {
				vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
				vec3 refractedRayExit = position + transmissionRay;
				vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
				vec2 refractionCoords = ndcPos.xy / ndcPos.w;
				refractionCoords += 1.0;
				refractionCoords /= 2.0;
				vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
				transmittedLight[ i ] = transmissionSample[ i ];
				transmittedLight.a += transmissionSample.a;
				transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
			}
			transmittedLight.a /= 3.0;
		#else
			vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
			vec3 refractedRayExit = position + transmissionRay;
			vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
			vec2 refractionCoords = ndcPos.xy / ndcPos.w;
			refractionCoords += 1.0;
			refractionCoords /= 2.0;
			transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
			transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
		#endif
		vec3 attenuatedColor = transmittance * transmittedLight.rgb;
		vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
		float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
		return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
	}
#endif`, k1 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`, V1 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	uniform mat3 mapTransform;
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	uniform mat3 alphaMapTransform;
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	uniform mat3 lightMapTransform;
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	uniform mat3 aoMapTransform;
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	uniform mat3 bumpMapTransform;
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	uniform mat3 normalMapTransform;
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
	uniform mat3 displacementMapTransform;
	varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	uniform mat3 emissiveMapTransform;
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	uniform mat3 metalnessMapTransform;
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	uniform mat3 roughnessMapTransform;
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	uniform mat3 anisotropyMapTransform;
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	uniform mat3 clearcoatMapTransform;
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform mat3 clearcoatNormalMapTransform;
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform mat3 clearcoatRoughnessMapTransform;
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	uniform mat3 sheenColorMapTransform;
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	uniform mat3 sheenRoughnessMapTransform;
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	uniform mat3 iridescenceMapTransform;
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform mat3 iridescenceThicknessMapTransform;
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
	uniform mat3 specularMapTransform;
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	uniform mat3 specularColorMapTransform;
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	uniform mat3 specularIntensityMapTransform;
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`, H1 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
	vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
	vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
	vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
	vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
	vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
	vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
	vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
	vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
	vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
	vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
	vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
	vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
	vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
	vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
	vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
	vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
	vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
	vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`, G1 = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
	vec4 worldPosition = vec4( transformed, 1.0 );
	#ifdef USE_BATCHING
		worldPosition = batchingMatrix * worldPosition;
	#endif
	#ifdef USE_INSTANCING
		worldPosition = instanceMatrix * worldPosition;
	#endif
	worldPosition = modelMatrix * worldPosition;
#endif`;
const W1 = `varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`, q1 = `uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
	vec4 texColor = texture2D( t2D, vUv );
	#ifdef DECODE_VIDEO_TEXTURE
		texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`, $1 = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`, X1 = `#ifdef ENVMAP_TYPE_CUBE
	uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
	uniform sampler2D envMap;
#endif
uniform float flipEnvMap;
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
	#ifdef ENVMAP_TYPE_CUBE
		vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
	#elif defined( ENVMAP_TYPE_CUBE_UV )
		vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
	#else
		vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`, Y1 = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`, Z1 = `uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
	vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
	gl_FragColor = texColor;
	gl_FragColor.a *= opacity;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`, j1 = `#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vHighPrecisionZW = gl_Position.zw;
}`, J1 = `#if DEPTH_PACKING == 3200
	uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#if DEPTH_PACKING == 3200
		diffuseColor.a = opacity;
	#endif
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <logdepthbuf_fragment>
	#ifdef USE_REVERSED_DEPTH_BUFFER
		float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];
	#else
		float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;
	#endif
	#if DEPTH_PACKING == 3200
		gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
	#elif DEPTH_PACKING == 3201
		gl_FragColor = packDepthToRGBA( fragCoordZ );
	#elif DEPTH_PACKING == 3202
		gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
	#elif DEPTH_PACKING == 3203
		gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
	#endif
}`, K1 = `#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <worldpos_vertex>
	#include <clipping_planes_vertex>
	vWorldPosition = worldPosition.xyz;
}`, Q1 = `#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	float dist = length( vWorldPosition - referencePosition );
	dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
	dist = saturate( dist );
	gl_FragColor = packDepthToRGBA( dist );
}`, tw = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`, ew = `uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
	vec3 direction = normalize( vWorldDirection );
	vec2 sampleUV = equirectUv( direction );
	gl_FragColor = texture2D( tEquirect, sampleUV );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`, iw = `uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	vLineDistance = scale * lineDistance;
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`, nw = `uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	if ( mod( vLineDistance, totalSize ) > dashSize ) {
		discard;
	}
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`, sw = `#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinbase_vertex>
		#include <skinnormal_vertex>
		#include <defaultnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <fog_vertex>
}`, rw = `uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
	varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
	#else
		reflectedLight.indirectDiffuse += vec3( 1.0 );
	#endif
	#include <aomap_fragment>
	reflectedLight.indirectDiffuse *= diffuseColor.rgb;
	vec3 outgoingLight = reflectedLight.indirectDiffuse;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, aw = `#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`, ow = `#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_lambert_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, lw = `#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
	vViewPosition = - mvPosition.xyz;
}`, hw = `#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	vec3 viewDir = normalize( vViewPosition );
	vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
	vec3 y = cross( viewDir, x );
	vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
	#ifdef USE_MATCAP
		vec4 matcapColor = texture2D( matcap, uv );
	#else
		vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
	#endif
	vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, cw = `#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	vViewPosition = - mvPosition.xyz;
#endif
}`, uw = `#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <packing>
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
	#ifdef OPAQUE
		gl_FragColor.a = 1.0;
	#endif
}`, dw = `#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`, pw = `#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_phong_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, fw = `#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
	varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
#ifdef USE_TRANSMISSION
	vWorldPosition = worldPosition.xyz;
#endif
}`, mw = `#define STANDARD
#ifdef PHYSICAL
	#define IOR
	#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
	uniform float ior;
#endif
#ifdef USE_SPECULAR
	uniform float specularIntensity;
	uniform vec3 specularColor;
	#ifdef USE_SPECULAR_COLORMAP
		uniform sampler2D specularColorMap;
	#endif
	#ifdef USE_SPECULAR_INTENSITYMAP
		uniform sampler2D specularIntensityMap;
	#endif
#endif
#ifdef USE_CLEARCOAT
	uniform float clearcoat;
	uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
	uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
	uniform float iridescence;
	uniform float iridescenceIOR;
	uniform float iridescenceThicknessMinimum;
	uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
	uniform vec3 sheenColor;
	uniform float sheenRoughness;
	#ifdef USE_SHEEN_COLORMAP
		uniform sampler2D sheenColorMap;
	#endif
	#ifdef USE_SHEEN_ROUGHNESSMAP
		uniform sampler2D sheenRoughnessMap;
	#endif
#endif
#ifdef USE_ANISOTROPY
	uniform vec2 anisotropyVector;
	#ifdef USE_ANISOTROPYMAP
		uniform sampler2D anisotropyMap;
	#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <roughnessmap_fragment>
	#include <metalnessmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <clearcoat_normal_fragment_begin>
	#include <clearcoat_normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_physical_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
	#include <transmission_fragment>
	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
	#ifdef USE_SHEEN
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
	#endif
	#ifdef USE_CLEARCOAT
		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
	#endif
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, gw = `#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`, yw = `#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_toon_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, _w = `uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
	varying vec2 vUv;
	uniform mat3 uvTransform;
#endif
void main() {
	#ifdef USE_POINTS_UV
		vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	#endif
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	gl_PointSize = size;
	#ifdef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
	#endif
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <fog_vertex>
}`, xw = `uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`, vw = `#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`, bw = `uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
	#include <logdepthbuf_fragment>
	gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`, Mw = `uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	vec4 mvPosition = modelViewMatrix[ 3 ];
	vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
	#ifndef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) scale *= - mvPosition.z;
	#endif
	vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
	vec2 rotatedPosition;
	rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
	rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
	mvPosition.xy += rotatedPosition;
	gl_Position = projectionMatrix * mvPosition;
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`, Sw = `uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`, Zt = {
  alphahash_fragment: qM,
  alphahash_pars_fragment: $M,
  alphamap_fragment: XM,
  alphamap_pars_fragment: YM,
  alphatest_fragment: ZM,
  alphatest_pars_fragment: jM,
  aomap_fragment: JM,
  aomap_pars_fragment: KM,
  batching_pars_vertex: QM,
  batching_vertex: tS,
  begin_vertex: eS,
  beginnormal_vertex: iS,
  bsdfs: nS,
  iridescence_fragment: sS,
  bumpmap_pars_fragment: rS,
  clipping_planes_fragment: aS,
  clipping_planes_pars_fragment: oS,
  clipping_planes_pars_vertex: lS,
  clipping_planes_vertex: hS,
  color_fragment: cS,
  color_pars_fragment: uS,
  color_pars_vertex: dS,
  color_vertex: pS,
  common: fS,
  cube_uv_reflection_fragment: mS,
  defaultnormal_vertex: gS,
  displacementmap_pars_vertex: yS,
  displacementmap_vertex: _S,
  emissivemap_fragment: xS,
  emissivemap_pars_fragment: vS,
  colorspace_fragment: bS,
  colorspace_pars_fragment: MS,
  envmap_fragment: SS,
  envmap_common_pars_fragment: wS,
  envmap_pars_fragment: AS,
  envmap_pars_vertex: ES,
  envmap_physical_pars_fragment: zS,
  envmap_vertex: TS,
  fog_vertex: CS,
  fog_pars_vertex: RS,
  fog_fragment: PS,
  fog_pars_fragment: IS,
  gradientmap_pars_fragment: LS,
  lightmap_pars_fragment: DS,
  lights_lambert_fragment: FS,
  lights_lambert_pars_fragment: US,
  lights_pars_begin: BS,
  lights_toon_fragment: NS,
  lights_toon_pars_fragment: OS,
  lights_phong_fragment: kS,
  lights_phong_pars_fragment: VS,
  lights_physical_fragment: HS,
  lights_physical_pars_fragment: GS,
  lights_fragment_begin: WS,
  lights_fragment_maps: qS,
  lights_fragment_end: $S,
  logdepthbuf_fragment: XS,
  logdepthbuf_pars_fragment: YS,
  logdepthbuf_pars_vertex: ZS,
  logdepthbuf_vertex: jS,
  map_fragment: JS,
  map_pars_fragment: KS,
  map_particle_fragment: QS,
  map_particle_pars_fragment: t1,
  metalnessmap_fragment: e1,
  metalnessmap_pars_fragment: i1,
  morphinstance_vertex: n1,
  morphcolor_vertex: s1,
  morphnormal_vertex: r1,
  morphtarget_pars_vertex: a1,
  morphtarget_vertex: o1,
  normal_fragment_begin: l1,
  normal_fragment_maps: h1,
  normal_pars_fragment: c1,
  normal_pars_vertex: u1,
  normal_vertex: d1,
  normalmap_pars_fragment: p1,
  clearcoat_normal_fragment_begin: f1,
  clearcoat_normal_fragment_maps: m1,
  clearcoat_pars_fragment: g1,
  iridescence_pars_fragment: y1,
  opaque_fragment: _1,
  packing: x1,
  premultiplied_alpha_fragment: v1,
  project_vertex: b1,
  dithering_fragment: M1,
  dithering_pars_fragment: S1,
  roughnessmap_fragment: w1,
  roughnessmap_pars_fragment: A1,
  shadowmap_pars_fragment: E1,
  shadowmap_pars_vertex: T1,
  shadowmap_vertex: C1,
  shadowmask_pars_fragment: R1,
  skinbase_vertex: P1,
  skinning_pars_vertex: I1,
  skinning_vertex: L1,
  skinnormal_vertex: D1,
  specularmap_fragment: F1,
  specularmap_pars_fragment: U1,
  tonemapping_fragment: B1,
  tonemapping_pars_fragment: z1,
  transmission_fragment: N1,
  transmission_pars_fragment: O1,
  uv_pars_fragment: k1,
  uv_pars_vertex: V1,
  uv_vertex: H1,
  worldpos_vertex: G1,
  background_vert: W1,
  background_frag: q1,
  backgroundCube_vert: $1,
  backgroundCube_frag: X1,
  cube_vert: Y1,
  cube_frag: Z1,
  depth_vert: j1,
  depth_frag: J1,
  distanceRGBA_vert: K1,
  distanceRGBA_frag: Q1,
  equirect_vert: tw,
  equirect_frag: ew,
  linedashed_vert: iw,
  linedashed_frag: nw,
  meshbasic_vert: sw,
  meshbasic_frag: rw,
  meshlambert_vert: aw,
  meshlambert_frag: ow,
  meshmatcap_vert: lw,
  meshmatcap_frag: hw,
  meshnormal_vert: cw,
  meshnormal_frag: uw,
  meshphong_vert: dw,
  meshphong_frag: pw,
  meshphysical_vert: fw,
  meshphysical_frag: mw,
  meshtoon_vert: gw,
  meshtoon_frag: yw,
  points_vert: _w,
  points_frag: xw,
  shadow_vert: vw,
  shadow_frag: bw,
  sprite_vert: Mw,
  sprite_frag: Sw
}, bt = {
  common: {
    diffuse: { value: /* @__PURE__ */ new ct(16777215) },
    opacity: { value: 1 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new Xt() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Xt() },
    alphaTest: { value: 0 }
  },
  specularmap: {
    specularMap: { value: null },
    specularMapTransform: { value: /* @__PURE__ */ new Xt() }
  },
  envmap: {
    envMap: { value: null },
    envMapRotation: { value: /* @__PURE__ */ new Xt() },
    flipEnvMap: { value: -1 },
    reflectivity: { value: 1 },
    // basic, lambert, phong
    ior: { value: 1.5 },
    // physical
    refractionRatio: { value: 0.98 }
    // basic, lambert, phong
  },
  aomap: {
    aoMap: { value: null },
    aoMapIntensity: { value: 1 },
    aoMapTransform: { value: /* @__PURE__ */ new Xt() }
  },
  lightmap: {
    lightMap: { value: null },
    lightMapIntensity: { value: 1 },
    lightMapTransform: { value: /* @__PURE__ */ new Xt() }
  },
  bumpmap: {
    bumpMap: { value: null },
    bumpMapTransform: { value: /* @__PURE__ */ new Xt() },
    bumpScale: { value: 1 }
  },
  normalmap: {
    normalMap: { value: null },
    normalMapTransform: { value: /* @__PURE__ */ new Xt() },
    normalScale: { value: /* @__PURE__ */ new J(1, 1) }
  },
  displacementmap: {
    displacementMap: { value: null },
    displacementMapTransform: { value: /* @__PURE__ */ new Xt() },
    displacementScale: { value: 1 },
    displacementBias: { value: 0 }
  },
  emissivemap: {
    emissiveMap: { value: null },
    emissiveMapTransform: { value: /* @__PURE__ */ new Xt() }
  },
  metalnessmap: {
    metalnessMap: { value: null },
    metalnessMapTransform: { value: /* @__PURE__ */ new Xt() }
  },
  roughnessmap: {
    roughnessMap: { value: null },
    roughnessMapTransform: { value: /* @__PURE__ */ new Xt() }
  },
  gradientmap: {
    gradientMap: { value: null }
  },
  fog: {
    fogDensity: { value: 25e-5 },
    fogNear: { value: 1 },
    fogFar: { value: 2e3 },
    fogColor: { value: /* @__PURE__ */ new ct(16777215) }
  },
  lights: {
    ambientLightColor: { value: [] },
    lightProbe: { value: [] },
    directionalLights: { value: [], properties: {
      direction: {},
      color: {}
    } },
    directionalLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    directionalShadowMap: { value: [] },
    directionalShadowMatrix: { value: [] },
    spotLights: { value: [], properties: {
      color: {},
      position: {},
      direction: {},
      distance: {},
      coneCos: {},
      penumbraCos: {},
      decay: {}
    } },
    spotLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    spotLightMap: { value: [] },
    spotShadowMap: { value: [] },
    spotLightMatrix: { value: [] },
    pointLights: { value: [], properties: {
      color: {},
      position: {},
      decay: {},
      distance: {}
    } },
    pointLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {},
      shadowCameraNear: {},
      shadowCameraFar: {}
    } },
    pointShadowMap: { value: [] },
    pointShadowMatrix: { value: [] },
    hemisphereLights: { value: [], properties: {
      direction: {},
      skyColor: {},
      groundColor: {}
    } },
    // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
    rectAreaLights: { value: [], properties: {
      color: {},
      position: {},
      width: {},
      height: {}
    } },
    ltc_1: { value: null },
    ltc_2: { value: null }
  },
  points: {
    diffuse: { value: /* @__PURE__ */ new ct(16777215) },
    opacity: { value: 1 },
    size: { value: 1 },
    scale: { value: 1 },
    map: { value: null },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Xt() },
    alphaTest: { value: 0 },
    uvTransform: { value: /* @__PURE__ */ new Xt() }
  },
  sprite: {
    diffuse: { value: /* @__PURE__ */ new ct(16777215) },
    opacity: { value: 1 },
    center: { value: /* @__PURE__ */ new J(0.5, 0.5) },
    rotation: { value: 0 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new Xt() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Xt() },
    alphaTest: { value: 0 }
  }
}, fi = {
  basic: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.specularmap,
      bt.envmap,
      bt.aomap,
      bt.lightmap,
      bt.fog
    ]),
    vertexShader: Zt.meshbasic_vert,
    fragmentShader: Zt.meshbasic_frag
  },
  lambert: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.specularmap,
      bt.envmap,
      bt.aomap,
      bt.lightmap,
      bt.emissivemap,
      bt.bumpmap,
      bt.normalmap,
      bt.displacementmap,
      bt.fog,
      bt.lights,
      {
        emissive: { value: /* @__PURE__ */ new ct(0) }
      }
    ]),
    vertexShader: Zt.meshlambert_vert,
    fragmentShader: Zt.meshlambert_frag
  },
  phong: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.specularmap,
      bt.envmap,
      bt.aomap,
      bt.lightmap,
      bt.emissivemap,
      bt.bumpmap,
      bt.normalmap,
      bt.displacementmap,
      bt.fog,
      bt.lights,
      {
        emissive: { value: /* @__PURE__ */ new ct(0) },
        specular: { value: /* @__PURE__ */ new ct(1118481) },
        shininess: { value: 30 }
      }
    ]),
    vertexShader: Zt.meshphong_vert,
    fragmentShader: Zt.meshphong_frag
  },
  standard: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.envmap,
      bt.aomap,
      bt.lightmap,
      bt.emissivemap,
      bt.bumpmap,
      bt.normalmap,
      bt.displacementmap,
      bt.roughnessmap,
      bt.metalnessmap,
      bt.fog,
      bt.lights,
      {
        emissive: { value: /* @__PURE__ */ new ct(0) },
        roughness: { value: 1 },
        metalness: { value: 0 },
        envMapIntensity: { value: 1 }
      }
    ]),
    vertexShader: Zt.meshphysical_vert,
    fragmentShader: Zt.meshphysical_frag
  },
  toon: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.aomap,
      bt.lightmap,
      bt.emissivemap,
      bt.bumpmap,
      bt.normalmap,
      bt.displacementmap,
      bt.gradientmap,
      bt.fog,
      bt.lights,
      {
        emissive: { value: /* @__PURE__ */ new ct(0) }
      }
    ]),
    vertexShader: Zt.meshtoon_vert,
    fragmentShader: Zt.meshtoon_frag
  },
  matcap: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.bumpmap,
      bt.normalmap,
      bt.displacementmap,
      bt.fog,
      {
        matcap: { value: null }
      }
    ]),
    vertexShader: Zt.meshmatcap_vert,
    fragmentShader: Zt.meshmatcap_frag
  },
  points: {
    uniforms: /* @__PURE__ */ pi([
      bt.points,
      bt.fog
    ]),
    vertexShader: Zt.points_vert,
    fragmentShader: Zt.points_frag
  },
  dashed: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.fog,
      {
        scale: { value: 1 },
        dashSize: { value: 1 },
        totalSize: { value: 2 }
      }
    ]),
    vertexShader: Zt.linedashed_vert,
    fragmentShader: Zt.linedashed_frag
  },
  depth: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.displacementmap
    ]),
    vertexShader: Zt.depth_vert,
    fragmentShader: Zt.depth_frag
  },
  normal: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.bumpmap,
      bt.normalmap,
      bt.displacementmap,
      {
        opacity: { value: 1 }
      }
    ]),
    vertexShader: Zt.meshnormal_vert,
    fragmentShader: Zt.meshnormal_frag
  },
  sprite: {
    uniforms: /* @__PURE__ */ pi([
      bt.sprite,
      bt.fog
    ]),
    vertexShader: Zt.sprite_vert,
    fragmentShader: Zt.sprite_frag
  },
  background: {
    uniforms: {
      uvTransform: { value: /* @__PURE__ */ new Xt() },
      t2D: { value: null },
      backgroundIntensity: { value: 1 }
    },
    vertexShader: Zt.background_vert,
    fragmentShader: Zt.background_frag
  },
  backgroundCube: {
    uniforms: {
      envMap: { value: null },
      flipEnvMap: { value: -1 },
      backgroundBlurriness: { value: 0 },
      backgroundIntensity: { value: 1 },
      backgroundRotation: { value: /* @__PURE__ */ new Xt() }
    },
    vertexShader: Zt.backgroundCube_vert,
    fragmentShader: Zt.backgroundCube_frag
  },
  cube: {
    uniforms: {
      tCube: { value: null },
      tFlip: { value: -1 },
      opacity: { value: 1 }
    },
    vertexShader: Zt.cube_vert,
    fragmentShader: Zt.cube_frag
  },
  equirect: {
    uniforms: {
      tEquirect: { value: null }
    },
    vertexShader: Zt.equirect_vert,
    fragmentShader: Zt.equirect_frag
  },
  distanceRGBA: {
    uniforms: /* @__PURE__ */ pi([
      bt.common,
      bt.displacementmap,
      {
        referencePosition: { value: /* @__PURE__ */ new E() },
        nearDistance: { value: 1 },
        farDistance: { value: 1e3 }
      }
    ]),
    vertexShader: Zt.distanceRGBA_vert,
    fragmentShader: Zt.distanceRGBA_frag
  },
  shadow: {
    uniforms: /* @__PURE__ */ pi([
      bt.lights,
      bt.fog,
      {
        color: { value: /* @__PURE__ */ new ct(0) },
        opacity: { value: 1 }
      }
    ]),
    vertexShader: Zt.shadow_vert,
    fragmentShader: Zt.shadow_frag
  }
};
fi.physical = {
  uniforms: /* @__PURE__ */ pi([
    fi.standard.uniforms,
    {
      clearcoat: { value: 0 },
      clearcoatMap: { value: null },
      clearcoatMapTransform: { value: /* @__PURE__ */ new Xt() },
      clearcoatNormalMap: { value: null },
      clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Xt() },
      clearcoatNormalScale: { value: /* @__PURE__ */ new J(1, 1) },
      clearcoatRoughness: { value: 0 },
      clearcoatRoughnessMap: { value: null },
      clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Xt() },
      dispersion: { value: 0 },
      iridescence: { value: 0 },
      iridescenceMap: { value: null },
      iridescenceMapTransform: { value: /* @__PURE__ */ new Xt() },
      iridescenceIOR: { value: 1.3 },
      iridescenceThicknessMinimum: { value: 100 },
      iridescenceThicknessMaximum: { value: 400 },
      iridescenceThicknessMap: { value: null },
      iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Xt() },
      sheen: { value: 0 },
      sheenColor: { value: /* @__PURE__ */ new ct(0) },
      sheenColorMap: { value: null },
      sheenColorMapTransform: { value: /* @__PURE__ */ new Xt() },
      sheenRoughness: { value: 1 },
      sheenRoughnessMap: { value: null },
      sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Xt() },
      transmission: { value: 0 },
      transmissionMap: { value: null },
      transmissionMapTransform: { value: /* @__PURE__ */ new Xt() },
      transmissionSamplerSize: { value: /* @__PURE__ */ new J() },
      transmissionSamplerMap: { value: null },
      thickness: { value: 0 },
      thicknessMap: { value: null },
      thicknessMapTransform: { value: /* @__PURE__ */ new Xt() },
      attenuationDistance: { value: 0 },
      attenuationColor: { value: /* @__PURE__ */ new ct(0) },
      specularColor: { value: /* @__PURE__ */ new ct(1, 1, 1) },
      specularColorMap: { value: null },
      specularColorMapTransform: { value: /* @__PURE__ */ new Xt() },
      specularIntensity: { value: 1 },
      specularIntensityMap: { value: null },
      specularIntensityMapTransform: { value: /* @__PURE__ */ new Xt() },
      anisotropyVector: { value: /* @__PURE__ */ new J() },
      anisotropyMap: { value: null },
      anisotropyMapTransform: { value: /* @__PURE__ */ new Xt() }
    }
  ]),
  vertexShader: Zt.meshphysical_vert,
  fragmentShader: Zt.meshphysical_frag
};
const zl = { r: 0, b: 0, g: 0 }, js = /* @__PURE__ */ new fn(), ww = /* @__PURE__ */ new Vt();
function Aw(a, t, e, i, n, s, r) {
  const o = new ct(0);
  let l = s === !0 ? 0 : 1, h, c, u = null, d = 0, p = null;
  function f(x) {
    let _ = x.isScene === !0 ? x.background : null;
    return _ && _.isTexture && (_ = (x.backgroundBlurriness > 0 ? e : t).get(_)), _;
  }
  function y(x) {
    let _ = !1;
    const S = f(x);
    S === null ? m(o, l) : S && S.isColor && (m(S, 1), _ = !0);
    const w = a.xr.getEnvironmentBlendMode();
    w === "additive" ? i.buffers.color.setClear(0, 0, 0, 1, r) : w === "alpha-blend" && i.buffers.color.setClear(0, 0, 0, 0, r), (a.autoClear || _) && (i.buffers.depth.setTest(!0), i.buffers.depth.setMask(!0), i.buffers.color.setMask(!0), a.clear(a.autoClearColor, a.autoClearDepth, a.autoClearStencil));
  }
  function g(x, _) {
    const S = f(_);
    S && (S.isCubeTexture || S.mapping === Sa) ? (c === void 0 && (c = new re(
      new mr(1, 1, 1),
      new Xi({
        name: "BackgroundCubeMaterial",
        uniforms: _a(fi.backgroundCube.uniforms),
        vertexShader: fi.backgroundCube.vertexShader,
        fragmentShader: fi.backgroundCube.fragmentShader,
        side: He,
        depthTest: !1,
        depthWrite: !1,
        fog: !1,
        allowOverride: !1
      })
    ), c.geometry.deleteAttribute("normal"), c.geometry.deleteAttribute("uv"), c.onBeforeRender = function(w, T, R) {
      this.matrixWorld.copyPosition(R.matrixWorld);
    }, Object.defineProperty(c.material, "envMap", {
      get: function() {
        return this.uniforms.envMap.value;
      }
    }), n.update(c)), js.copy(_.backgroundRotation), js.x *= -1, js.y *= -1, js.z *= -1, S.isCubeTexture && S.isRenderTargetTexture === !1 && (js.y *= -1, js.z *= -1), c.material.uniforms.envMap.value = S, c.material.uniforms.flipEnvMap.value = S.isCubeTexture && S.isRenderTargetTexture === !1 ? -1 : 1, c.material.uniforms.backgroundBlurriness.value = _.backgroundBlurriness, c.material.uniforms.backgroundIntensity.value = _.backgroundIntensity, c.material.uniforms.backgroundRotation.value.setFromMatrix4(ww.makeRotationFromEuler(js)), c.material.toneMapped = ee.getTransfer(S.colorSpace) !== ce, (u !== S || d !== S.version || p !== a.toneMapping) && (c.material.needsUpdate = !0, u = S, d = S.version, p = a.toneMapping), c.layers.enableAll(), x.unshift(c, c.geometry, c.material, 0, 0, null)) : S && S.isTexture && (h === void 0 && (h = new re(
      new Ds(2, 2),
      new Xi({
        name: "BackgroundMaterial",
        uniforms: _a(fi.background.uniforms),
        vertexShader: fi.background.vertexShader,
        fragmentShader: fi.background.fragmentShader,
        side: $i,
        depthTest: !1,
        depthWrite: !1,
        fog: !1,
        allowOverride: !1
      })
    ), h.geometry.deleteAttribute("normal"), Object.defineProperty(h.material, "map", {
      get: function() {
        return this.uniforms.t2D.value;
      }
    }), n.update(h)), h.material.uniforms.t2D.value = S, h.material.uniforms.backgroundIntensity.value = _.backgroundIntensity, h.material.toneMapped = ee.getTransfer(S.colorSpace) !== ce, S.matrixAutoUpdate === !0 && S.updateMatrix(), h.material.uniforms.uvTransform.value.copy(S.matrix), (u !== S || d !== S.version || p !== a.toneMapping) && (h.material.needsUpdate = !0, u = S, d = S.version, p = a.toneMapping), h.layers.enableAll(), x.unshift(h, h.geometry, h.material, 0, 0, null));
  }
  function m(x, _) {
    x.getRGB(zl, wy(a)), i.buffers.color.setClear(zl.r, zl.g, zl.b, _, r);
  }
  function v() {
    c !== void 0 && (c.geometry.dispose(), c.material.dispose(), c = void 0), h !== void 0 && (h.geometry.dispose(), h.material.dispose(), h = void 0);
  }
  return {
    getClearColor: function() {
      return o;
    },
    setClearColor: function(x, _ = 1) {
      o.set(x), l = _, m(o, l);
    },
    getClearAlpha: function() {
      return l;
    },
    setClearAlpha: function(x) {
      l = x, m(o, l);
    },
    render: y,
    addToRenderList: g,
    dispose: v
  };
}
function Ew(a, t) {
  const e = a.getParameter(a.MAX_VERTEX_ATTRIBS), i = {}, n = d(null);
  let s = n, r = !1;
  function o(M, L, U, O, V) {
    let W = !1;
    const G = u(O, U, L);
    s !== G && (s = G, h(s.object)), W = p(M, O, U, V), W && f(M, O, U, V), V !== null && t.update(V, a.ELEMENT_ARRAY_BUFFER), (W || r) && (r = !1, _(M, L, U, O), V !== null && a.bindBuffer(a.ELEMENT_ARRAY_BUFFER, t.get(V).buffer));
  }
  function l() {
    return a.createVertexArray();
  }
  function h(M) {
    return a.bindVertexArray(M);
  }
  function c(M) {
    return a.deleteVertexArray(M);
  }
  function u(M, L, U) {
    const O = U.wireframe === !0;
    let V = i[M.id];
    V === void 0 && (V = {}, i[M.id] = V);
    let W = V[L.id];
    W === void 0 && (W = {}, V[L.id] = W);
    let G = W[O];
    return G === void 0 && (G = d(l()), W[O] = G), G;
  }
  function d(M) {
    const L = [], U = [], O = [];
    for (let V = 0; V < e; V++)
      L[V] = 0, U[V] = 0, O[V] = 0;
    return {
      // for backward compatibility on non-VAO support browser
      geometry: null,
      program: null,
      wireframe: !1,
      newAttributes: L,
      enabledAttributes: U,
      attributeDivisors: O,
      object: M,
      attributes: {},
      index: null
    };
  }
  function p(M, L, U, O) {
    const V = s.attributes, W = L.attributes;
    let G = 0;
    const et = U.getAttributes();
    for (const H in et)
      if (et[H].location >= 0) {
        const pt = V[H];
        let Mt = W[H];
        if (Mt === void 0 && (H === "instanceMatrix" && M.instanceMatrix && (Mt = M.instanceMatrix), H === "instanceColor" && M.instanceColor && (Mt = M.instanceColor)), pt === void 0 || pt.attribute !== Mt || Mt && pt.data !== Mt.data) return !0;
        G++;
      }
    return s.attributesNum !== G || s.index !== O;
  }
  function f(M, L, U, O) {
    const V = {}, W = L.attributes;
    let G = 0;
    const et = U.getAttributes();
    for (const H in et)
      if (et[H].location >= 0) {
        let pt = W[H];
        pt === void 0 && (H === "instanceMatrix" && M.instanceMatrix && (pt = M.instanceMatrix), H === "instanceColor" && M.instanceColor && (pt = M.instanceColor));
        const Mt = {};
        Mt.attribute = pt, pt && pt.data && (Mt.data = pt.data), V[H] = Mt, G++;
      }
    s.attributes = V, s.attributesNum = G, s.index = O;
  }
  function y() {
    const M = s.newAttributes;
    for (let L = 0, U = M.length; L < U; L++)
      M[L] = 0;
  }
  function g(M) {
    m(M, 0);
  }
  function m(M, L) {
    const U = s.newAttributes, O = s.enabledAttributes, V = s.attributeDivisors;
    U[M] = 1, O[M] === 0 && (a.enableVertexAttribArray(M), O[M] = 1), V[M] !== L && (a.vertexAttribDivisor(M, L), V[M] = L);
  }
  function v() {
    const M = s.newAttributes, L = s.enabledAttributes;
    for (let U = 0, O = L.length; U < O; U++)
      L[U] !== M[U] && (a.disableVertexAttribArray(U), L[U] = 0);
  }
  function x(M, L, U, O, V, W, G) {
    G === !0 ? a.vertexAttribIPointer(M, L, U, V, W) : a.vertexAttribPointer(M, L, U, O, V, W);
  }
  function _(M, L, U, O) {
    y();
    const V = O.attributes, W = U.getAttributes(), G = L.defaultAttributeValues;
    for (const et in W) {
      const H = W[et];
      if (H.location >= 0) {
        let at = V[et];
        if (at === void 0 && (et === "instanceMatrix" && M.instanceMatrix && (at = M.instanceMatrix), et === "instanceColor" && M.instanceColor && (at = M.instanceColor)), at !== void 0) {
          const pt = at.normalized, Mt = at.itemSize, Lt = t.get(at);
          if (Lt === void 0) continue;
          const jt = Lt.buffer, ne = Lt.type, Jt = Lt.bytesPerElement, Y = ne === a.INT || ne === a.UNSIGNED_INT || at.gpuType === Rc;
          if (at.isInterleavedBufferAttribute) {
            const st = at.data, Et = st.stride, Ut = at.offset;
            if (st.isInstancedInterleavedBuffer) {
              for (let Pt = 0; Pt < H.locationSize; Pt++)
                m(H.location + Pt, st.meshPerAttribute);
              M.isInstancedMesh !== !0 && O._maxInstanceCount === void 0 && (O._maxInstanceCount = st.meshPerAttribute * st.count);
            } else
              for (let Pt = 0; Pt < H.locationSize; Pt++)
                g(H.location + Pt);
            a.bindBuffer(a.ARRAY_BUFFER, jt);
            for (let Pt = 0; Pt < H.locationSize; Pt++)
              x(
                H.location + Pt,
                Mt / H.locationSize,
                ne,
                pt,
                Et * Jt,
                (Ut + Mt / H.locationSize * Pt) * Jt,
                Y
              );
          } else {
            if (at.isInstancedBufferAttribute) {
              for (let st = 0; st < H.locationSize; st++)
                m(H.location + st, at.meshPerAttribute);
              M.isInstancedMesh !== !0 && O._maxInstanceCount === void 0 && (O._maxInstanceCount = at.meshPerAttribute * at.count);
            } else
              for (let st = 0; st < H.locationSize; st++)
                g(H.location + st);
            a.bindBuffer(a.ARRAY_BUFFER, jt);
            for (let st = 0; st < H.locationSize; st++)
              x(
                H.location + st,
                Mt / H.locationSize,
                ne,
                pt,
                Mt * Jt,
                Mt / H.locationSize * st * Jt,
                Y
              );
          }
        } else if (G !== void 0) {
          const pt = G[et];
          if (pt !== void 0)
            switch (pt.length) {
              case 2:
                a.vertexAttrib2fv(H.location, pt);
                break;
              case 3:
                a.vertexAttrib3fv(H.location, pt);
                break;
              case 4:
                a.vertexAttrib4fv(H.location, pt);
                break;
              default:
                a.vertexAttrib1fv(H.location, pt);
            }
        }
      }
    }
    v();
  }
  function S() {
    R();
    for (const M in i) {
      const L = i[M];
      for (const U in L) {
        const O = L[U];
        for (const V in O)
          c(O[V].object), delete O[V];
        delete L[U];
      }
      delete i[M];
    }
  }
  function w(M) {
    if (i[M.id] === void 0) return;
    const L = i[M.id];
    for (const U in L) {
      const O = L[U];
      for (const V in O)
        c(O[V].object), delete O[V];
      delete L[U];
    }
    delete i[M.id];
  }
  function T(M) {
    for (const L in i) {
      const U = i[L];
      if (U[M.id] === void 0) continue;
      const O = U[M.id];
      for (const V in O)
        c(O[V].object), delete O[V];
      delete U[M.id];
    }
  }
  function R() {
    b(), r = !0, s !== n && (s = n, h(s.object));
  }
  function b() {
    n.geometry = null, n.program = null, n.wireframe = !1;
  }
  return {
    setup: o,
    reset: R,
    resetDefaultState: b,
    dispose: S,
    releaseStatesOfGeometry: w,
    releaseStatesOfProgram: T,
    initAttributes: y,
    enableAttribute: g,
    disableUnusedAttributes: v
  };
}
function Tw(a, t, e) {
  let i;
  function n(h) {
    i = h;
  }
  function s(h, c) {
    a.drawArrays(i, h, c), e.update(c, i, 1);
  }
  function r(h, c, u) {
    u !== 0 && (a.drawArraysInstanced(i, h, c, u), e.update(c, i, u));
  }
  function o(h, c, u) {
    if (u === 0) return;
    t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i, h, 0, c, 0, u);
    let p = 0;
    for (let f = 0; f < u; f++)
      p += c[f];
    e.update(p, i, 1);
  }
  function l(h, c, u, d) {
    if (u === 0) return;
    const p = t.get("WEBGL_multi_draw");
    if (p === null)
      for (let f = 0; f < h.length; f++)
        r(h[f], c[f], d[f]);
    else {
      p.multiDrawArraysInstancedWEBGL(i, h, 0, c, 0, d, 0, u);
      let f = 0;
      for (let y = 0; y < u; y++)
        f += c[y] * d[y];
      e.update(f, i, 1);
    }
  }
  this.setMode = n, this.render = s, this.renderInstances = r, this.renderMultiDraw = o, this.renderMultiDrawInstances = l;
}
function Cw(a, t, e, i) {
  let n;
  function s() {
    if (n !== void 0) return n;
    if (t.has("EXT_texture_filter_anisotropic") === !0) {
      const T = t.get("EXT_texture_filter_anisotropic");
      n = a.getParameter(T.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
    } else
      n = 0;
    return n;
  }
  function r(T) {
    return !(T !== gi && i.convert(T) !== a.getParameter(a.IMPLEMENTATION_COLOR_READ_FORMAT));
  }
  function o(T) {
    const R = T === wa && (t.has("EXT_color_buffer_half_float") || t.has("EXT_color_buffer_float"));
    return !(T !== pn && i.convert(T) !== a.getParameter(a.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
    T !== wi && !R);
  }
  function l(T) {
    if (T === "highp") {
      if (a.getShaderPrecisionFormat(a.VERTEX_SHADER, a.HIGH_FLOAT).precision > 0 && a.getShaderPrecisionFormat(a.FRAGMENT_SHADER, a.HIGH_FLOAT).precision > 0)
        return "highp";
      T = "mediump";
    }
    return T === "mediump" && a.getShaderPrecisionFormat(a.VERTEX_SHADER, a.MEDIUM_FLOAT).precision > 0 && a.getShaderPrecisionFormat(a.FRAGMENT_SHADER, a.MEDIUM_FLOAT).precision > 0 ? "mediump" : "lowp";
  }
  let h = e.precision !== void 0 ? e.precision : "highp";
  const c = l(h);
  c !== h && (console.warn("THREE.WebGLRenderer:", h, "not supported, using", c, "instead."), h = c);
  const u = e.logarithmicDepthBuffer === !0, d = e.reversedDepthBuffer === !0 && t.has("EXT_clip_control"), p = a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS), f = a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS), y = a.getParameter(a.MAX_TEXTURE_SIZE), g = a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE), m = a.getParameter(a.MAX_VERTEX_ATTRIBS), v = a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS), x = a.getParameter(a.MAX_VARYING_VECTORS), _ = a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS), S = f > 0, w = a.getParameter(a.MAX_SAMPLES);
  return {
    isWebGL2: !0,
    // keeping this for backwards compatibility
    getMaxAnisotropy: s,
    getMaxPrecision: l,
    textureFormatReadable: r,
    textureTypeReadable: o,
    precision: h,
    logarithmicDepthBuffer: u,
    reversedDepthBuffer: d,
    maxTextures: p,
    maxVertexTextures: f,
    maxTextureSize: y,
    maxCubemapSize: g,
    maxAttributes: m,
    maxVertexUniforms: v,
    maxVaryings: x,
    maxFragmentUniforms: _,
    vertexTextures: S,
    maxSamples: w
  };
}
function Rw(a) {
  const t = this;
  let e = null, i = 0, n = !1, s = !1;
  const r = new qn(), o = new Xt(), l = { value: null, needsUpdate: !1 };
  this.uniform = l, this.numPlanes = 0, this.numIntersection = 0, this.init = function(u, d) {
    const p = u.length !== 0 || d || // enable state of previous frame - the clipping code has to
    // run another frame in order to reset the state:
    i !== 0 || n;
    return n = d, i = u.length, p;
  }, this.beginShadows = function() {
    s = !0, c(null);
  }, this.endShadows = function() {
    s = !1;
  }, this.setGlobalState = function(u, d) {
    e = c(u, d, 0);
  }, this.setState = function(u, d, p) {
    const f = u.clippingPlanes, y = u.clipIntersection, g = u.clipShadows, m = a.get(u);
    if (!n || f === null || f.length === 0 || s && !g)
      s ? c(null) : h();
    else {
      const v = s ? 0 : i, x = v * 4;
      let _ = m.clippingState || null;
      l.value = _, _ = c(f, d, x, p);
      for (let S = 0; S !== x; ++S)
        _[S] = e[S];
      m.clippingState = _, this.numIntersection = y ? this.numPlanes : 0, this.numPlanes += v;
    }
  };
  function h() {
    l.value !== e && (l.value = e, l.needsUpdate = i > 0), t.numPlanes = i, t.numIntersection = 0;
  }
  function c(u, d, p, f) {
    const y = u !== null ? u.length : 0;
    let g = null;
    if (y !== 0) {
      if (g = l.value, f !== !0 || g === null) {
        const m = p + y * 4, v = d.matrixWorldInverse;
        o.getNormalMatrix(v), (g === null || g.length < m) && (g = new Float32Array(m));
        for (let x = 0, _ = p; x !== y; ++x, _ += 4)
          r.copy(u[x]).applyMatrix4(v, o), r.normal.toArray(g, _), g[_ + 3] = r.constant;
      }
      l.value = g, l.needsUpdate = !0;
    }
    return t.numPlanes = y, t.numIntersection = 0, g;
  }
}
function Pw(a) {
  let t = /* @__PURE__ */ new WeakMap();
  function e(r, o) {
    return o === vo ? r.mapping = is : o === bo && (r.mapping = Ts), r;
  }
  function i(r) {
    if (r && r.isTexture) {
      const o = r.mapping;
      if (o === vo || o === bo)
        if (t.has(r)) {
          const l = t.get(r).texture;
          return e(l, r.mapping);
        } else {
          const l = r.image;
          if (l && l.height > 0) {
            const h = new Ey(l.height);
            return h.fromEquirectangularTexture(a, r), t.set(r, h), r.addEventListener("dispose", n), e(h.texture, r.mapping);
          } else
            return null;
        }
    }
    return r;
  }
  function n(r) {
    const o = r.target;
    o.removeEventListener("dispose", n);
    const l = t.get(o);
    l !== void 0 && (t.delete(o), l.dispose());
  }
  function s() {
    t = /* @__PURE__ */ new WeakMap();
  }
  return {
    get: i,
    dispose: s
  };
}
const aa = 4, zm = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582], nr = 20, ed = /* @__PURE__ */ new Ia(), Nm = /* @__PURE__ */ new ct();
let id = null, nd = 0, sd = 0, rd = !1;
const ir = (1 + Math.sqrt(5)) / 2, kr = 1 / ir, Om = [
  /* @__PURE__ */ new E(-ir, kr, 0),
  /* @__PURE__ */ new E(ir, kr, 0),
  /* @__PURE__ */ new E(-kr, 0, ir),
  /* @__PURE__ */ new E(kr, 0, ir),
  /* @__PURE__ */ new E(0, ir, -kr),
  /* @__PURE__ */ new E(0, ir, kr),
  /* @__PURE__ */ new E(-1, 1, -1),
  /* @__PURE__ */ new E(1, 1, -1),
  /* @__PURE__ */ new E(-1, 1, 1),
  /* @__PURE__ */ new E(1, 1, 1)
], Iw = /* @__PURE__ */ new E();
class hp {
  /**
   * Constructs a new PMREM generator.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   */
  constructor(t) {
    this._renderer = t, this._pingPongRenderTarget = null, this._lodMax = 0, this._cubeSize = 0, this._lodPlanes = [], this._sizeLods = [], this._sigmas = [], this._blurMaterial = null, this._cubemapMaterial = null, this._equirectMaterial = null, this._compileMaterial(this._blurMaterial);
  }
  /**
   * Generates a PMREM from a supplied Scene, which can be faster than using an
   * image if networking bandwidth is low. Optional sigma specifies a blur radius
   * in radians to be applied to the scene before PMREM generation. Optional near
   * and far planes ensure the scene is rendered in its entirety.
   *
   * @param {Scene} scene - The scene to be captured.
   * @param {number} [sigma=0] - The blur radius in radians.
   * @param {number} [near=0.1] - The near plane distance.
   * @param {number} [far=100] - The far plane distance.
   * @param {Object} [options={}] - The configuration options.
   * @param {number} [options.size=256] - The texture size of the PMREM.
   * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
   * @return {WebGLRenderTarget} The resulting PMREM.
   */
  fromScene(t, e = 0, i = 0.1, n = 100, s = {}) {
    const {
      size: r = 256,
      position: o = Iw
    } = s;
    id = this._renderer.getRenderTarget(), nd = this._renderer.getActiveCubeFace(), sd = this._renderer.getActiveMipmapLevel(), rd = this._renderer.xr.enabled, this._renderer.xr.enabled = !1, this._setSize(r);
    const l = this._allocateTargets();
    return l.depthBuffer = !0, this._sceneToCubeUV(t, i, n, l, o), e > 0 && this._blur(l, 0, 0, e), this._applyPMREM(l), this._cleanup(l), l;
  }
  /**
   * Generates a PMREM from an equirectangular texture, which can be either LDR
   * or HDR. The ideal input image size is 1k (1024 x 512),
   * as this matches best with the 256 x 256 cubemap output.
   *
   * @param {Texture} equirectangular - The equirectangular texture to be converted.
   * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
   * @return {WebGLRenderTarget} The resulting PMREM.
   */
  fromEquirectangular(t, e = null) {
    return this._fromTexture(t, e);
  }
  /**
   * Generates a PMREM from an cubemap texture, which can be either LDR
   * or HDR. The ideal input cube size is 256 x 256,
   * as this matches best with the 256 x 256 cubemap output.
   *
   * @param {Texture} cubemap - The cubemap texture to be converted.
   * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
   * @return {WebGLRenderTarget} The resulting PMREM.
   */
  fromCubemap(t, e = null) {
    return this._fromTexture(t, e);
  }
  /**
   * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
   * your texture's network fetch for increased concurrency.
   */
  compileCubemapShader() {
    this._cubemapMaterial === null && (this._cubemapMaterial = Hm(), this._compileMaterial(this._cubemapMaterial));
  }
  /**
   * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
   * your texture's network fetch for increased concurrency.
   */
  compileEquirectangularShader() {
    this._equirectMaterial === null && (this._equirectMaterial = Vm(), this._compileMaterial(this._equirectMaterial));
  }
  /**
   * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
   * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
   * one of them will cause any others to also become unusable.
   */
  dispose() {
    this._dispose(), this._cubemapMaterial !== null && this._cubemapMaterial.dispose(), this._equirectMaterial !== null && this._equirectMaterial.dispose();
  }
  // private interface
  _setSize(t) {
    this._lodMax = Math.floor(Math.log2(t)), this._cubeSize = Math.pow(2, this._lodMax);
  }
  _dispose() {
    this._blurMaterial !== null && this._blurMaterial.dispose(), this._pingPongRenderTarget !== null && this._pingPongRenderTarget.dispose();
    for (let t = 0; t < this._lodPlanes.length; t++)
      this._lodPlanes[t].dispose();
  }
  _cleanup(t) {
    this._renderer.setRenderTarget(id, nd, sd), this._renderer.xr.enabled = rd, t.scissorTest = !1, Nl(t, 0, 0, t.width, t.height);
  }
  _fromTexture(t, e) {
    t.mapping === is || t.mapping === Ts ? this._setSize(t.image.length === 0 ? 16 : t.image[0].width || t.image[0].image.width) : this._setSize(t.image.width / 4), id = this._renderer.getRenderTarget(), nd = this._renderer.getActiveCubeFace(), sd = this._renderer.getActiveMipmapLevel(), rd = this._renderer.xr.enabled, this._renderer.xr.enabled = !1;
    const i = e || this._allocateTargets();
    return this._textureToCubeUV(t, i), this._applyPMREM(i), this._cleanup(i), i;
  }
  _allocateTargets() {
    const t = 3 * Math.max(this._cubeSize, 112), e = 4 * this._cubeSize, i = {
      magFilter: Ce,
      minFilter: Ce,
      generateMipmaps: !1,
      type: wa,
      format: gi,
      colorSpace: Cs,
      depthBuffer: !1
    }, n = km(t, e, i);
    if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== t || this._pingPongRenderTarget.height !== e) {
      this._pingPongRenderTarget !== null && this._dispose(), this._pingPongRenderTarget = km(t, e, i);
      const { _lodMax: s } = this;
      ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = Lw(s)), this._blurMaterial = Dw(s, t, e);
    }
    return n;
  }
  _compileMaterial(t) {
    const e = new re(this._lodPlanes[0], t);
    this._renderer.compile(e, ed);
  }
  _sceneToCubeUV(t, e, i, n, s) {
    const l = new Ve(90, 1, e, i), h = [1, -1, 1, 1, 1, 1], c = [1, 1, 1, -1, -1, -1], u = this._renderer, d = u.autoClear, p = u.toneMapping;
    u.getClearColor(Nm), u.toneMapping = Zn, u.autoClear = !1, u.state.buffers.depth.getReversed() && (u.setRenderTarget(n), u.clearDepth(), u.setRenderTarget(null));
    const y = new li({
      name: "PMREM.Background",
      side: He,
      depthWrite: !1,
      depthTest: !1
    }), g = new re(new mr(), y);
    let m = !1;
    const v = t.background;
    v ? v.isColor && (y.color.copy(v), t.background = null, m = !0) : (y.color.copy(Nm), m = !0);
    for (let x = 0; x < 6; x++) {
      const _ = x % 3;
      _ === 0 ? (l.up.set(0, h[x], 0), l.position.set(s.x, s.y, s.z), l.lookAt(s.x + c[x], s.y, s.z)) : _ === 1 ? (l.up.set(0, 0, h[x]), l.position.set(s.x, s.y, s.z), l.lookAt(s.x, s.y + c[x], s.z)) : (l.up.set(0, h[x], 0), l.position.set(s.x, s.y, s.z), l.lookAt(s.x, s.y, s.z + c[x]));
      const S = this._cubeSize;
      Nl(n, _ * S, x > 2 ? S : 0, S, S), u.setRenderTarget(n), m && u.render(g, l), u.render(t, l);
    }
    g.geometry.dispose(), g.material.dispose(), u.toneMapping = p, u.autoClear = d, t.background = v;
  }
  _textureToCubeUV(t, e) {
    const i = this._renderer, n = t.mapping === is || t.mapping === Ts;
    n ? (this._cubemapMaterial === null && (this._cubemapMaterial = Hm()), this._cubemapMaterial.uniforms.flipEnvMap.value = t.isRenderTargetTexture === !1 ? -1 : 1) : this._equirectMaterial === null && (this._equirectMaterial = Vm());
    const s = n ? this._cubemapMaterial : this._equirectMaterial, r = new re(this._lodPlanes[0], s), o = s.uniforms;
    o.envMap.value = t;
    const l = this._cubeSize;
    Nl(e, 0, 0, 3 * l, 2 * l), i.setRenderTarget(e), i.render(r, ed);
  }
  _applyPMREM(t) {
    const e = this._renderer, i = e.autoClear;
    e.autoClear = !1;
    const n = this._lodPlanes.length;
    for (let s = 1; s < n; s++) {
      const r = Math.sqrt(this._sigmas[s] * this._sigmas[s] - this._sigmas[s - 1] * this._sigmas[s - 1]), o = Om[(n - s - 1) % Om.length];
      this._blur(t, s - 1, s, r, o);
    }
    e.autoClear = i;
  }
  /**
   * This is a two-pass Gaussian blur for a cubemap. Normally this is done
   * vertically and horizontally, but this breaks down on a cube. Here we apply
   * the blur latitudinally (around the poles), and then longitudinally (towards
   * the poles) to approximate the orthogonally-separable blur. It is least
   * accurate at the poles, but still does a decent job.
   *
   * @private
   * @param {WebGLRenderTarget} cubeUVRenderTarget
   * @param {number} lodIn
   * @param {number} lodOut
   * @param {number} sigma
   * @param {Vector3} [poleAxis]
   */
  _blur(t, e, i, n, s) {
    const r = this._pingPongRenderTarget;
    this._halfBlur(
      t,
      r,
      e,
      i,
      n,
      "latitudinal",
      s
    ), this._halfBlur(
      r,
      t,
      i,
      i,
      n,
      "longitudinal",
      s
    );
  }
  _halfBlur(t, e, i, n, s, r, o) {
    const l = this._renderer, h = this._blurMaterial;
    r !== "latitudinal" && r !== "longitudinal" && console.error(
      "blur direction must be either latitudinal or longitudinal!"
    );
    const c = 3, u = new re(this._lodPlanes[n], h), d = h.uniforms, p = this._sizeLods[i] - 1, f = isFinite(s) ? Math.PI / (2 * p) : 2 * Math.PI / (2 * nr - 1), y = s / f, g = isFinite(s) ? 1 + Math.floor(c * y) : nr;
    g > nr && console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${nr}`);
    const m = [];
    let v = 0;
    for (let T = 0; T < nr; ++T) {
      const R = T / y, b = Math.exp(-R * R / 2);
      m.push(b), T === 0 ? v += b : T < g && (v += 2 * b);
    }
    for (let T = 0; T < m.length; T++)
      m[T] = m[T] / v;
    d.envMap.value = t.texture, d.samples.value = g, d.weights.value = m, d.latitudinal.value = r === "latitudinal", o && (d.poleAxis.value = o);
    const { _lodMax: x } = this;
    d.dTheta.value = f, d.mipInt.value = x - i;
    const _ = this._sizeLods[n], S = 3 * _ * (n > x - aa ? n - x + aa : 0), w = 4 * (this._cubeSize - _);
    Nl(e, S, w, 3 * _, 2 * _), l.setRenderTarget(e), l.render(u, ed);
  }
}
function Lw(a) {
  const t = [], e = [], i = [];
  let n = a;
  const s = a - aa + 1 + zm.length;
  for (let r = 0; r < s; r++) {
    const o = Math.pow(2, n);
    e.push(o);
    let l = 1 / o;
    r > a - aa ? l = zm[r - a + aa - 1] : r === 0 && (l = 0), i.push(l);
    const h = 1 / (o - 2), c = -h, u = 1 + h, d = [c, c, u, c, u, u, c, c, u, u, c, u], p = 6, f = 6, y = 3, g = 2, m = 1, v = new Float32Array(y * f * p), x = new Float32Array(g * f * p), _ = new Float32Array(m * f * p);
    for (let w = 0; w < p; w++) {
      const T = w % 3 * 2 / 3 - 1, R = w > 2 ? 0 : -1, b = [
        T,
        R,
        0,
        T + 2 / 3,
        R,
        0,
        T + 2 / 3,
        R + 1,
        0,
        T,
        R,
        0,
        T + 2 / 3,
        R + 1,
        0,
        T,
        R + 1,
        0
      ];
      v.set(b, y * f * w), x.set(d, g * f * w);
      const M = [w, w, w, w, w, w];
      _.set(M, m * f * w);
    }
    const S = new Ht();
    S.setAttribute("position", new ie(v, y)), S.setAttribute("uv", new ie(x, g)), S.setAttribute("faceIndex", new ie(_, m)), t.push(S), n > aa && n--;
  }
  return { lodPlanes: t, sizeLods: e, sigmas: i };
}
function km(a, t, e) {
  const i = new Rn(a, t, e);
  return i.texture.mapping = Sa, i.texture.name = "PMREM.cubeUv", i.scissorTest = !0, i;
}
function Nl(a, t, e, i, n) {
  a.viewport.set(t, e, i, n), a.scissor.set(t, e, i, n);
}
function Dw(a, t, e) {
  const i = new Float32Array(nr), n = new E(0, 1, 0);
  return new Xi({
    name: "SphericalGaussianBlur",
    defines: {
      n: nr,
      CUBEUV_TEXEL_WIDTH: 1 / t,
      CUBEUV_TEXEL_HEIGHT: 1 / e,
      CUBEUV_MAX_MIP: `${a}.0`
    },
    uniforms: {
      envMap: { value: null },
      samples: { value: 1 },
      weights: { value: i },
      latitudinal: { value: !1 },
      dTheta: { value: 0 },
      mipInt: { value: 0 },
      poleAxis: { value: n }
    },
    vertexShader: pf(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform int samples;
			uniform float weights[ n ];
			uniform bool latitudinal;
			uniform float dTheta;
			uniform float mipInt;
			uniform vec3 poleAxis;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			vec3 getSample( float theta, vec3 axis ) {

				float cosTheta = cos( theta );
				// Rodrigues' axis-angle rotation
				vec3 sampleDirection = vOutputDirection * cosTheta
					+ cross( axis, vOutputDirection ) * sin( theta )
					+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );

				return bilinearCubeUV( envMap, sampleDirection, mipInt );

			}

			void main() {

				vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );

				if ( all( equal( axis, vec3( 0.0 ) ) ) ) {

					axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );

				}

				axis = normalize( axis );

				gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
				gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );

				for ( int i = 1; i < n; i++ ) {

					if ( i >= samples ) {

						break;

					}

					float theta = dTheta * float( i );
					gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
					gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );

				}

			}
		`
    ),
    blending: Yn,
    depthTest: !1,
    depthWrite: !1
  });
}
function Vm() {
  return new Xi({
    name: "EquirectangularToCubeUV",
    uniforms: {
      envMap: { value: null }
    },
    vertexShader: pf(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;

			#include <common>

			void main() {

				vec3 outputDirection = normalize( vOutputDirection );
				vec2 uv = equirectUv( outputDirection );

				gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );

			}
		`
    ),
    blending: Yn,
    depthTest: !1,
    depthWrite: !1
  });
}
function Hm() {
  return new Xi({
    name: "CubemapToCubeUV",
    uniforms: {
      envMap: { value: null },
      flipEnvMap: { value: -1 }
    },
    vertexShader: pf(),
    fragmentShader: (
      /* glsl */
      `

			precision mediump float;
			precision mediump int;

			uniform float flipEnvMap;

			varying vec3 vOutputDirection;

			uniform samplerCube envMap;

			void main() {

				gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );

			}
		`
    ),
    blending: Yn,
    depthTest: !1,
    depthWrite: !1
  });
}
function pf() {
  return (
    /* glsl */
    `

		precision mediump float;
		precision mediump int;

		attribute float faceIndex;

		varying vec3 vOutputDirection;

		// RH coordinate system; PMREM face-indexing convention
		vec3 getDirection( vec2 uv, float face ) {

			uv = 2.0 * uv - 1.0;

			vec3 direction = vec3( uv, 1.0 );

			if ( face == 0.0 ) {

				direction = direction.zyx; // ( 1, v, u ) pos x

			} else if ( face == 1.0 ) {

				direction = direction.xzy;
				direction.xz *= -1.0; // ( -u, 1, -v ) pos y

			} else if ( face == 2.0 ) {

				direction.x *= -1.0; // ( -u, v, 1 ) pos z

			} else if ( face == 3.0 ) {

				direction = direction.zyx;
				direction.xz *= -1.0; // ( -1, v, -u ) neg x

			} else if ( face == 4.0 ) {

				direction = direction.xzy;
				direction.xy *= -1.0; // ( -u, -1, v ) neg y

			} else if ( face == 5.0 ) {

				direction.z *= -1.0; // ( u, v, -1 ) neg z

			}

			return direction;

		}

		void main() {

			vOutputDirection = getDirection( uv, faceIndex );
			gl_Position = vec4( position, 1.0 );

		}
	`
  );
}
function Fw(a) {
  let t = /* @__PURE__ */ new WeakMap(), e = null;
  function i(o) {
    if (o && o.isTexture) {
      const l = o.mapping, h = l === vo || l === bo, c = l === is || l === Ts;
      if (h || c) {
        let u = t.get(o);
        const d = u !== void 0 ? u.texture.pmremVersion : 0;
        if (o.isRenderTargetTexture && o.pmremVersion !== d)
          return e === null && (e = new hp(a)), u = h ? e.fromEquirectangular(o, u) : e.fromCubemap(o, u), u.texture.pmremVersion = o.pmremVersion, t.set(o, u), u.texture;
        if (u !== void 0)
          return u.texture;
        {
          const p = o.image;
          return h && p && p.height > 0 || c && p && n(p) ? (e === null && (e = new hp(a)), u = h ? e.fromEquirectangular(o) : e.fromCubemap(o), u.texture.pmremVersion = o.pmremVersion, t.set(o, u), o.addEventListener("dispose", s), u.texture) : null;
        }
      }
    }
    return o;
  }
  function n(o) {
    let l = 0;
    const h = 6;
    for (let c = 0; c < h; c++)
      o[c] !== void 0 && l++;
    return l === h;
  }
  function s(o) {
    const l = o.target;
    l.removeEventListener("dispose", s);
    const h = t.get(l);
    h !== void 0 && (t.delete(l), h.dispose());
  }
  function r() {
    t = /* @__PURE__ */ new WeakMap(), e !== null && (e.dispose(), e = null);
  }
  return {
    get: i,
    dispose: r
  };
}
function Uw(a) {
  const t = {};
  function e(i) {
    if (t[i] !== void 0)
      return t[i];
    let n;
    switch (i) {
      case "WEBGL_depth_texture":
        n = a.getExtension("WEBGL_depth_texture") || a.getExtension("MOZ_WEBGL_depth_texture") || a.getExtension("WEBKIT_WEBGL_depth_texture");
        break;
      case "EXT_texture_filter_anisotropic":
        n = a.getExtension("EXT_texture_filter_anisotropic") || a.getExtension("MOZ_EXT_texture_filter_anisotropic") || a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");
        break;
      case "WEBGL_compressed_texture_s3tc":
        n = a.getExtension("WEBGL_compressed_texture_s3tc") || a.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");
        break;
      case "WEBGL_compressed_texture_pvrtc":
        n = a.getExtension("WEBGL_compressed_texture_pvrtc") || a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");
        break;
      default:
        n = a.getExtension(i);
    }
    return t[i] = n, n;
  }
  return {
    has: function(i) {
      return e(i) !== null;
    },
    init: function() {
      e("EXT_color_buffer_float"), e("WEBGL_clip_cull_distance"), e("OES_texture_float_linear"), e("EXT_color_buffer_half_float"), e("WEBGL_multisampled_render_to_texture"), e("WEBGL_render_shared_exponent");
    },
    get: function(i) {
      const n = e(i);
      return n === null && Po("THREE.WebGLRenderer: " + i + " extension not supported."), n;
    }
  };
}
function Bw(a, t, e, i) {
  const n = {}, s = /* @__PURE__ */ new WeakMap();
  function r(u) {
    const d = u.target;
    d.index !== null && t.remove(d.index);
    for (const f in d.attributes)
      t.remove(d.attributes[f]);
    d.removeEventListener("dispose", r), delete n[d.id];
    const p = s.get(d);
    p && (t.remove(p), s.delete(d)), i.releaseStatesOfGeometry(d), d.isInstancedBufferGeometry === !0 && delete d._maxInstanceCount, e.memory.geometries--;
  }
  function o(u, d) {
    return n[d.id] === !0 || (d.addEventListener("dispose", r), n[d.id] = !0, e.memory.geometries++), d;
  }
  function l(u) {
    const d = u.attributes;
    for (const p in d)
      t.update(d[p], a.ARRAY_BUFFER);
  }
  function h(u) {
    const d = [], p = u.index, f = u.attributes.position;
    let y = 0;
    if (p !== null) {
      const v = p.array;
      y = p.version;
      for (let x = 0, _ = v.length; x < _; x += 3) {
        const S = v[x + 0], w = v[x + 1], T = v[x + 2];
        d.push(S, w, w, T, T, S);
      }
    } else if (f !== void 0) {
      const v = f.array;
      y = f.version;
      for (let x = 0, _ = v.length / 3 - 1; x < _; x += 3) {
        const S = x + 0, w = x + 1, T = x + 2;
        d.push(S, w, w, T, T, S);
      }
    } else
      return;
    const g = new (yy(d) ? Np : zp)(d, 1);
    g.version = y;
    const m = s.get(u);
    m && t.remove(m), s.set(u, g);
  }
  function c(u) {
    const d = s.get(u);
    if (d) {
      const p = u.index;
      p !== null && d.version < p.version && h(u);
    } else
      h(u);
    return s.get(u);
  }
  return {
    get: o,
    update: l,
    getWireframeAttribute: c
  };
}
function zw(a, t, e) {
  let i;
  function n(d) {
    i = d;
  }
  let s, r;
  function o(d) {
    s = d.type, r = d.bytesPerElement;
  }
  function l(d, p) {
    a.drawElements(i, p, s, d * r), e.update(p, i, 1);
  }
  function h(d, p, f) {
    f !== 0 && (a.drawElementsInstanced(i, p, s, d * r, f), e.update(p, i, f));
  }
  function c(d, p, f) {
    if (f === 0) return;
    t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i, p, 0, s, d, 0, f);
    let g = 0;
    for (let m = 0; m < f; m++)
      g += p[m];
    e.update(g, i, 1);
  }
  function u(d, p, f, y) {
    if (f === 0) return;
    const g = t.get("WEBGL_multi_draw");
    if (g === null)
      for (let m = 0; m < d.length; m++)
        h(d[m] / r, p[m], y[m]);
    else {
      g.multiDrawElementsInstancedWEBGL(i, p, 0, s, d, 0, y, 0, f);
      let m = 0;
      for (let v = 0; v < f; v++)
        m += p[v] * y[v];
      e.update(m, i, 1);
    }
  }
  this.setMode = n, this.setIndex = o, this.render = l, this.renderInstances = h, this.renderMultiDraw = c, this.renderMultiDrawInstances = u;
}
function Nw(a) {
  const t = {
    geometries: 0,
    textures: 0
  }, e = {
    frame: 0,
    calls: 0,
    triangles: 0,
    points: 0,
    lines: 0
  };
  function i(s, r, o) {
    switch (e.calls++, r) {
      case a.TRIANGLES:
        e.triangles += o * (s / 3);
        break;
      case a.LINES:
        e.lines += o * (s / 2);
        break;
      case a.LINE_STRIP:
        e.lines += o * (s - 1);
        break;
      case a.LINE_LOOP:
        e.lines += o * s;
        break;
      case a.POINTS:
        e.points += o * s;
        break;
      default:
        console.error("THREE.WebGLInfo: Unknown draw mode:", r);
        break;
    }
  }
  function n() {
    e.calls = 0, e.triangles = 0, e.points = 0, e.lines = 0;
  }
  return {
    memory: t,
    render: e,
    programs: null,
    autoReset: !0,
    reset: n,
    update: i
  };
}
function Ow(a, t, e) {
  const i = /* @__PURE__ */ new WeakMap(), n = new Qt();
  function s(r, o, l) {
    const h = r.morphTargetInfluences, c = o.morphAttributes.position || o.morphAttributes.normal || o.morphAttributes.color, u = c !== void 0 ? c.length : 0;
    let d = i.get(o);
    if (d === void 0 || d.count !== u) {
      let b = function() {
        T.dispose(), i.delete(o), o.removeEventListener("dispose", b);
      };
      d !== void 0 && d.texture.dispose();
      const p = o.morphAttributes.position !== void 0, f = o.morphAttributes.normal !== void 0, y = o.morphAttributes.color !== void 0, g = o.morphAttributes.position || [], m = o.morphAttributes.normal || [], v = o.morphAttributes.color || [];
      let x = 0;
      p === !0 && (x = 1), f === !0 && (x = 2), y === !0 && (x = 3);
      let _ = o.attributes.position.count * x, S = 1;
      _ > t.maxTextureSize && (S = Math.ceil(_ / t.maxTextureSize), _ = t.maxTextureSize);
      const w = new Float32Array(_ * S * 4 * u), T = new Bc(w, _, S, u);
      T.type = wi, T.needsUpdate = !0;
      const R = x * 4;
      for (let M = 0; M < u; M++) {
        const L = g[M], U = m[M], O = v[M], V = _ * S * 4 * M;
        for (let W = 0; W < L.count; W++) {
          const G = W * R;
          p === !0 && (n.fromBufferAttribute(L, W), w[V + G + 0] = n.x, w[V + G + 1] = n.y, w[V + G + 2] = n.z, w[V + G + 3] = 0), f === !0 && (n.fromBufferAttribute(U, W), w[V + G + 4] = n.x, w[V + G + 5] = n.y, w[V + G + 6] = n.z, w[V + G + 7] = 0), y === !0 && (n.fromBufferAttribute(O, W), w[V + G + 8] = n.x, w[V + G + 9] = n.y, w[V + G + 10] = n.z, w[V + G + 11] = O.itemSize === 4 ? n.w : 1);
        }
      }
      d = {
        count: u,
        texture: T,
        size: new J(_, S)
      }, i.set(o, d), o.addEventListener("dispose", b);
    }
    if (r.isInstancedMesh === !0 && r.morphTexture !== null)
      l.getUniforms().setValue(a, "morphTexture", r.morphTexture, e);
    else {
      let p = 0;
      for (let y = 0; y < h.length; y++)
        p += h[y];
      const f = o.morphTargetsRelative ? 1 : 1 - p;
      l.getUniforms().setValue(a, "morphTargetBaseInfluence", f), l.getUniforms().setValue(a, "morphTargetInfluences", h);
    }
    l.getUniforms().setValue(a, "morphTargetsTexture", d.texture, e), l.getUniforms().setValue(a, "morphTargetsTextureSize", d.size);
  }
  return {
    update: s
  };
}
function kw(a, t, e, i) {
  let n = /* @__PURE__ */ new WeakMap();
  function s(l) {
    const h = i.render.frame, c = l.geometry, u = t.get(l, c);
    if (n.get(u) !== h && (t.update(u), n.set(u, h)), l.isInstancedMesh && (l.hasEventListener("dispose", o) === !1 && l.addEventListener("dispose", o), n.get(l) !== h && (e.update(l.instanceMatrix, a.ARRAY_BUFFER), l.instanceColor !== null && e.update(l.instanceColor, a.ARRAY_BUFFER), n.set(l, h))), l.isSkinnedMesh) {
      const d = l.skeleton;
      n.get(d) !== h && (d.update(), n.set(d, h));
    }
    return u;
  }
  function r() {
    n = /* @__PURE__ */ new WeakMap();
  }
  function o(l) {
    const h = l.target;
    h.removeEventListener("dispose", o), e.remove(h.instanceMatrix), h.instanceColor !== null && e.remove(h.instanceColor);
  }
  return {
    update: s,
    dispose: r
  };
}
const S_ = /* @__PURE__ */ new Ne(), Gm = /* @__PURE__ */ new Vp(1, 1), w_ = /* @__PURE__ */ new Bc(), A_ = /* @__PURE__ */ new zc(), E_ = /* @__PURE__ */ new Oo(), Wm = [], qm = [], $m = new Float32Array(16), Xm = new Float32Array(9), Ym = new Float32Array(4);
function La(a, t, e) {
  const i = a[0];
  if (i <= 0 || i > 0) return a;
  const n = t * e;
  let s = Wm[n];
  if (s === void 0 && (s = new Float32Array(n), Wm[n] = s), t !== 0) {
    i.toArray(s, 0);
    for (let r = 1, o = 0; r !== t; ++r)
      o += e, a[r].toArray(s, o);
  }
  return s;
}
function Be(a, t) {
  if (a.length !== t.length) return !1;
  for (let e = 0, i = a.length; e < i; e++)
    if (a[e] !== t[e]) return !1;
  return !0;
}
function ze(a, t) {
  for (let e = 0, i = t.length; e < i; e++)
    a[e] = t[e];
}
function lu(a, t) {
  let e = qm[t];
  e === void 0 && (e = new Int32Array(t), qm[t] = e);
  for (let i = 0; i !== t; ++i)
    e[i] = a.allocateTextureUnit();
  return e;
}
function Vw(a, t) {
  const e = this.cache;
  e[0] !== t && (a.uniform1f(this.addr, t), e[0] = t);
}
function Hw(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y) && (a.uniform2f(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y);
  else {
    if (Be(e, t)) return;
    a.uniform2fv(this.addr, t), ze(e, t);
  }
}
function Gw(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (a.uniform3f(this.addr, t.x, t.y, t.z), e[0] = t.x, e[1] = t.y, e[2] = t.z);
  else if (t.r !== void 0)
    (e[0] !== t.r || e[1] !== t.g || e[2] !== t.b) && (a.uniform3f(this.addr, t.r, t.g, t.b), e[0] = t.r, e[1] = t.g, e[2] = t.b);
  else {
    if (Be(e, t)) return;
    a.uniform3fv(this.addr, t), ze(e, t);
  }
}
function Ww(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z || e[3] !== t.w) && (a.uniform4f(this.addr, t.x, t.y, t.z, t.w), e[0] = t.x, e[1] = t.y, e[2] = t.z, e[3] = t.w);
  else {
    if (Be(e, t)) return;
    a.uniform4fv(this.addr, t), ze(e, t);
  }
}
function qw(a, t) {
  const e = this.cache, i = t.elements;
  if (i === void 0) {
    if (Be(e, t)) return;
    a.uniformMatrix2fv(this.addr, !1, t), ze(e, t);
  } else {
    if (Be(e, i)) return;
    Ym.set(i), a.uniformMatrix2fv(this.addr, !1, Ym), ze(e, i);
  }
}
function $w(a, t) {
  const e = this.cache, i = t.elements;
  if (i === void 0) {
    if (Be(e, t)) return;
    a.uniformMatrix3fv(this.addr, !1, t), ze(e, t);
  } else {
    if (Be(e, i)) return;
    Xm.set(i), a.uniformMatrix3fv(this.addr, !1, Xm), ze(e, i);
  }
}
function Xw(a, t) {
  const e = this.cache, i = t.elements;
  if (i === void 0) {
    if (Be(e, t)) return;
    a.uniformMatrix4fv(this.addr, !1, t), ze(e, t);
  } else {
    if (Be(e, i)) return;
    $m.set(i), a.uniformMatrix4fv(this.addr, !1, $m), ze(e, i);
  }
}
function Yw(a, t) {
  const e = this.cache;
  e[0] !== t && (a.uniform1i(this.addr, t), e[0] = t);
}
function Zw(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y) && (a.uniform2i(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y);
  else {
    if (Be(e, t)) return;
    a.uniform2iv(this.addr, t), ze(e, t);
  }
}
function jw(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (a.uniform3i(this.addr, t.x, t.y, t.z), e[0] = t.x, e[1] = t.y, e[2] = t.z);
  else {
    if (Be(e, t)) return;
    a.uniform3iv(this.addr, t), ze(e, t);
  }
}
function Jw(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z || e[3] !== t.w) && (a.uniform4i(this.addr, t.x, t.y, t.z, t.w), e[0] = t.x, e[1] = t.y, e[2] = t.z, e[3] = t.w);
  else {
    if (Be(e, t)) return;
    a.uniform4iv(this.addr, t), ze(e, t);
  }
}
function Kw(a, t) {
  const e = this.cache;
  e[0] !== t && (a.uniform1ui(this.addr, t), e[0] = t);
}
function Qw(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y) && (a.uniform2ui(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y);
  else {
    if (Be(e, t)) return;
    a.uniform2uiv(this.addr, t), ze(e, t);
  }
}
function tA(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (a.uniform3ui(this.addr, t.x, t.y, t.z), e[0] = t.x, e[1] = t.y, e[2] = t.z);
  else {
    if (Be(e, t)) return;
    a.uniform3uiv(this.addr, t), ze(e, t);
  }
}
function eA(a, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z || e[3] !== t.w) && (a.uniform4ui(this.addr, t.x, t.y, t.z, t.w), e[0] = t.x, e[1] = t.y, e[2] = t.z, e[3] = t.w);
  else {
    if (Be(e, t)) return;
    a.uniform4uiv(this.addr, t), ze(e, t);
  }
}
function iA(a, t, e) {
  const i = this.cache, n = e.allocateTextureUnit();
  i[0] !== n && (a.uniform1i(this.addr, n), i[0] = n);
  let s;
  this.type === a.SAMPLER_2D_SHADOW ? (Gm.compareFunction = Fp, s = Gm) : s = S_, e.setTexture2D(t || s, n);
}
function nA(a, t, e) {
  const i = this.cache, n = e.allocateTextureUnit();
  i[0] !== n && (a.uniform1i(this.addr, n), i[0] = n), e.setTexture3D(t || A_, n);
}
function sA(a, t, e) {
  const i = this.cache, n = e.allocateTextureUnit();
  i[0] !== n && (a.uniform1i(this.addr, n), i[0] = n), e.setTextureCube(t || E_, n);
}
function rA(a, t, e) {
  const i = this.cache, n = e.allocateTextureUnit();
  i[0] !== n && (a.uniform1i(this.addr, n), i[0] = n), e.setTexture2DArray(t || w_, n);
}
function aA(a) {
  switch (a) {
    case 5126:
      return Vw;
    case 35664:
      return Hw;
    case 35665:
      return Gw;
    case 35666:
      return Ww;
    case 35674:
      return qw;
    case 35675:
      return $w;
    case 35676:
      return Xw;
    case 5124:
    case 35670:
      return Yw;
    case 35667:
    case 35671:
      return Zw;
    case 35668:
    case 35672:
      return jw;
    case 35669:
    case 35673:
      return Jw;
    case 5125:
      return Kw;
    case 36294:
      return Qw;
    case 36295:
      return tA;
    case 36296:
      return eA;
    case 35678:
    case 36198:
    case 36298:
    case 36306:
    case 35682:
      return iA;
    case 35679:
    case 36299:
    case 36307:
      return nA;
    case 35680:
    case 36300:
    case 36308:
    case 36293:
      return sA;
    case 36289:
    case 36303:
    case 36311:
    case 36292:
      return rA;
  }
}
function oA(a, t) {
  a.uniform1fv(this.addr, t);
}
function lA(a, t) {
  const e = La(t, this.size, 2);
  a.uniform2fv(this.addr, e);
}
function hA(a, t) {
  const e = La(t, this.size, 3);
  a.uniform3fv(this.addr, e);
}
function cA(a, t) {
  const e = La(t, this.size, 4);
  a.uniform4fv(this.addr, e);
}
function uA(a, t) {
  const e = La(t, this.size, 4);
  a.uniformMatrix2fv(this.addr, !1, e);
}
function dA(a, t) {
  const e = La(t, this.size, 9);
  a.uniformMatrix3fv(this.addr, !1, e);
}
function pA(a, t) {
  const e = La(t, this.size, 16);
  a.uniformMatrix4fv(this.addr, !1, e);
}
function fA(a, t) {
  a.uniform1iv(this.addr, t);
}
function mA(a, t) {
  a.uniform2iv(this.addr, t);
}
function gA(a, t) {
  a.uniform3iv(this.addr, t);
}
function yA(a, t) {
  a.uniform4iv(this.addr, t);
}
function _A(a, t) {
  a.uniform1uiv(this.addr, t);
}
function xA(a, t) {
  a.uniform2uiv(this.addr, t);
}
function vA(a, t) {
  a.uniform3uiv(this.addr, t);
}
function bA(a, t) {
  a.uniform4uiv(this.addr, t);
}
function MA(a, t, e) {
  const i = this.cache, n = t.length, s = lu(e, n);
  Be(i, s) || (a.uniform1iv(this.addr, s), ze(i, s));
  for (let r = 0; r !== n; ++r)
    e.setTexture2D(t[r] || S_, s[r]);
}
function SA(a, t, e) {
  const i = this.cache, n = t.length, s = lu(e, n);
  Be(i, s) || (a.uniform1iv(this.addr, s), ze(i, s));
  for (let r = 0; r !== n; ++r)
    e.setTexture3D(t[r] || A_, s[r]);
}
function wA(a, t, e) {
  const i = this.cache, n = t.length, s = lu(e, n);
  Be(i, s) || (a.uniform1iv(this.addr, s), ze(i, s));
  for (let r = 0; r !== n; ++r)
    e.setTextureCube(t[r] || E_, s[r]);
}
function AA(a, t, e) {
  const i = this.cache, n = t.length, s = lu(e, n);
  Be(i, s) || (a.uniform1iv(this.addr, s), ze(i, s));
  for (let r = 0; r !== n; ++r)
    e.setTexture2DArray(t[r] || w_, s[r]);
}
function EA(a) {
  switch (a) {
    case 5126:
      return oA;
    case 35664:
      return lA;
    case 35665:
      return hA;
    case 35666:
      return cA;
    case 35674:
      return uA;
    case 35675:
      return dA;
    case 35676:
      return pA;
    case 5124:
    case 35670:
      return fA;
    case 35667:
    case 35671:
      return mA;
    case 35668:
    case 35672:
      return gA;
    case 35669:
    case 35673:
      return yA;
    case 5125:
      return _A;
    case 36294:
      return xA;
    case 36295:
      return vA;
    case 36296:
      return bA;
    case 35678:
    case 36198:
    case 36298:
    case 36306:
    case 35682:
      return MA;
    case 35679:
    case 36299:
    case 36307:
      return SA;
    case 35680:
    case 36300:
    case 36308:
    case 36293:
      return wA;
    case 36289:
    case 36303:
    case 36311:
    case 36292:
      return AA;
  }
}
class TA {
  constructor(t, e, i) {
    this.id = t, this.addr = i, this.cache = [], this.type = e.type, this.setValue = aA(e.type);
  }
}
class CA {
  constructor(t, e, i) {
    this.id = t, this.addr = i, this.cache = [], this.type = e.type, this.size = e.size, this.setValue = EA(e.type);
  }
}
class RA {
  constructor(t) {
    this.id = t, this.seq = [], this.map = {};
  }
  setValue(t, e, i) {
    const n = this.seq;
    for (let s = 0, r = n.length; s !== r; ++s) {
      const o = n[s];
      o.setValue(t, e[o.id], i);
    }
  }
}
const ad = /(\w+)(\])?(\[|\.)?/g;
function Zm(a, t) {
  a.seq.push(t), a.map[t.id] = t;
}
function PA(a, t, e) {
  const i = a.name, n = i.length;
  for (ad.lastIndex = 0; ; ) {
    const s = ad.exec(i), r = ad.lastIndex;
    let o = s[1];
    const l = s[2] === "]", h = s[3];
    if (l && (o = o | 0), h === void 0 || h === "[" && r + 2 === n) {
      Zm(e, h === void 0 ? new TA(o, a, t) : new CA(o, a, t));
      break;
    } else {
      let u = e.map[o];
      u === void 0 && (u = new RA(o), Zm(e, u)), e = u;
    }
  }
}
class Ch {
  constructor(t, e) {
    this.seq = [], this.map = {};
    const i = t.getProgramParameter(e, t.ACTIVE_UNIFORMS);
    for (let n = 0; n < i; ++n) {
      const s = t.getActiveUniform(e, n), r = t.getUniformLocation(e, s.name);
      PA(s, r, this);
    }
  }
  setValue(t, e, i, n) {
    const s = this.map[e];
    s !== void 0 && s.setValue(t, i, n);
  }
  setOptional(t, e, i) {
    const n = e[i];
    n !== void 0 && this.setValue(t, i, n);
  }
  static upload(t, e, i, n) {
    for (let s = 0, r = e.length; s !== r; ++s) {
      const o = e[s], l = i[o.id];
      l.needsUpdate !== !1 && o.setValue(t, l.value, n);
    }
  }
  static seqWithValue(t, e) {
    const i = [];
    for (let n = 0, s = t.length; n !== s; ++n) {
      const r = t[n];
      r.id in e && i.push(r);
    }
    return i;
  }
}
function jm(a, t, e) {
  const i = a.createShader(t);
  return a.shaderSource(i, e), a.compileShader(i), i;
}
const IA = 37297;
let LA = 0;
function DA(a, t) {
  const e = a.split(`
`), i = [], n = Math.max(t - 6, 0), s = Math.min(t + 6, e.length);
  for (let r = n; r < s; r++) {
    const o = r + 1;
    i.push(`${o === t ? ">" : " "} ${o}: ${e[r]}`);
  }
  return i.join(`
`);
}
const Jm = /* @__PURE__ */ new Xt();
function FA(a) {
  ee._getMatrix(Jm, ee.workingColorSpace, a);
  const t = `mat3( ${Jm.elements.map((e) => e.toFixed(4))} )`;
  switch (ee.getTransfer(a)) {
    case Eo:
      return [t, "LinearTransferOETF"];
    case ce:
      return [t, "sRGBTransferOETF"];
    default:
      return console.warn("THREE.WebGLProgram: Unsupported color space: ", a), [t, "LinearTransferOETF"];
  }
}
function Km(a, t, e) {
  const i = a.getShaderParameter(t, a.COMPILE_STATUS), s = (a.getShaderInfoLog(t) || "").trim();
  if (i && s === "") return "";
  const r = /ERROR: 0:(\d+)/.exec(s);
  if (r) {
    const o = parseInt(r[1]);
    return e.toUpperCase() + `

` + s + `

` + DA(a.getShaderSource(t), o);
  } else
    return s;
}
function UA(a, t) {
  const e = FA(t);
  return [
    `vec4 ${a}( vec4 value ) {`,
    `	return ${e[1]}( vec4( value.rgb * ${e[0]}, value.a ) );`,
    "}"
  ].join(`
`);
}
function BA(a, t) {
  let e;
  switch (t) {
    case X0:
      e = "Linear";
      break;
    case Y0:
      e = "Reinhard";
      break;
    case Z0:
      e = "Cineon";
      break;
    case j0:
      e = "ACESFilmic";
      break;
    case K0:
      e = "AgX";
      break;
    case Q0:
      e = "Neutral";
      break;
    case J0:
      e = "Custom";
      break;
    default:
      console.warn("THREE.WebGLProgram: Unsupported toneMapping:", t), e = "Linear";
  }
  return "vec3 " + a + "( vec3 color ) { return " + e + "ToneMapping( color ); }";
}
const Ol = /* @__PURE__ */ new E();
function zA() {
  ee.getLuminanceCoefficients(Ol);
  const a = Ol.x.toFixed(4), t = Ol.y.toFixed(4), e = Ol.z.toFixed(4);
  return [
    "float luminance( const in vec3 rgb ) {",
    `	const vec3 weights = vec3( ${a}, ${t}, ${e} );`,
    "	return dot( weights, rgb );",
    "}"
  ].join(`
`);
}
function NA(a) {
  return [
    a.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "",
    a.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : ""
  ].filter(ro).join(`
`);
}
function OA(a) {
  const t = [];
  for (const e in a) {
    const i = a[e];
    i !== !1 && t.push("#define " + e + " " + i);
  }
  return t.join(`
`);
}
function kA(a, t) {
  const e = {}, i = a.getProgramParameter(t, a.ACTIVE_ATTRIBUTES);
  for (let n = 0; n < i; n++) {
    const s = a.getActiveAttrib(t, n), r = s.name;
    let o = 1;
    s.type === a.FLOAT_MAT2 && (o = 2), s.type === a.FLOAT_MAT3 && (o = 3), s.type === a.FLOAT_MAT4 && (o = 4), e[r] = {
      type: s.type,
      location: a.getAttribLocation(t, r),
      locationSize: o
    };
  }
  return e;
}
function ro(a) {
  return a !== "";
}
function Qm(a, t) {
  const e = t.numSpotLightShadows + t.numSpotLightMaps - t.numSpotLightShadowsWithMaps;
  return a.replace(/NUM_DIR_LIGHTS/g, t.numDirLights).replace(/NUM_SPOT_LIGHTS/g, t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, e).replace(/NUM_RECT_AREA_LIGHTS/g, t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, t.numPointLights).replace(/NUM_HEMI_LIGHTS/g, t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, t.numPointLightShadows);
}
function tg(a, t) {
  return a.replace(/NUM_CLIPPING_PLANES/g, t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, t.numClippingPlanes - t.numClipIntersection);
}
const VA = /^[ \t]*#include +<([\w\d./]+)>/gm;
function cp(a) {
  return a.replace(VA, GA);
}
const HA = /* @__PURE__ */ new Map();
function GA(a, t) {
  let e = Zt[t];
  if (e === void 0) {
    const i = HA.get(t);
    if (i !== void 0)
      e = Zt[i], console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', t, i);
    else
      throw new Error("Can not resolve #include <" + t + ">");
  }
  return cp(e);
}
const WA = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
function eg(a) {
  return a.replace(WA, qA);
}
function qA(a, t, e, i) {
  let n = "";
  for (let s = parseInt(t); s < parseInt(e); s++)
    n += i.replace(/\[\s*i\s*\]/g, "[ " + s + " ]").replace(/UNROLLED_LOOP_INDEX/g, s);
  return n;
}
function ig(a) {
  let t = `precision ${a.precision} float;
	precision ${a.precision} int;
	precision ${a.precision} sampler2D;
	precision ${a.precision} samplerCube;
	precision ${a.precision} sampler3D;
	precision ${a.precision} sampler2DArray;
	precision ${a.precision} sampler2DShadow;
	precision ${a.precision} samplerCubeShadow;
	precision ${a.precision} sampler2DArrayShadow;
	precision ${a.precision} isampler2D;
	precision ${a.precision} isampler3D;
	precision ${a.precision} isamplerCube;
	precision ${a.precision} isampler2DArray;
	precision ${a.precision} usampler2D;
	precision ${a.precision} usampler3D;
	precision ${a.precision} usamplerCube;
	precision ${a.precision} usampler2DArray;
	`;
  return a.precision === "highp" ? t += `
#define HIGH_PRECISION` : a.precision === "mediump" ? t += `
#define MEDIUM_PRECISION` : a.precision === "lowp" && (t += `
#define LOW_PRECISION`), t;
}
function $A(a) {
  let t = "SHADOWMAP_TYPE_BASIC";
  return a.shadowMapType === Mp ? t = "SHADOWMAP_TYPE_PCF" : a.shadowMapType === E0 ? t = "SHADOWMAP_TYPE_PCF_SOFT" : a.shadowMapType === Sn && (t = "SHADOWMAP_TYPE_VSM"), t;
}
function XA(a) {
  let t = "ENVMAP_TYPE_CUBE";
  if (a.envMap)
    switch (a.envMapMode) {
      case is:
      case Ts:
        t = "ENVMAP_TYPE_CUBE";
        break;
      case Sa:
        t = "ENVMAP_TYPE_CUBE_UV";
        break;
    }
  return t;
}
function YA(a) {
  let t = "ENVMAP_MODE_REFLECTION";
  if (a.envMap)
    switch (a.envMapMode) {
      case Ts:
        t = "ENVMAP_MODE_REFRACTION";
        break;
    }
  return t;
}
function ZA(a) {
  let t = "ENVMAP_BLENDING_NONE";
  if (a.envMap)
    switch (a.combine) {
      case zo:
        t = "ENVMAP_BLENDING_MULTIPLY";
        break;
      case q0:
        t = "ENVMAP_BLENDING_MIX";
        break;
      case $0:
        t = "ENVMAP_BLENDING_ADD";
        break;
    }
  return t;
}
function jA(a) {
  const t = a.envMapCubeUVHeight;
  if (t === null) return null;
  const e = Math.log2(t) - 2, i = 1 / t;
  return { texelWidth: 1 / (3 * Math.max(Math.pow(2, e), 7 * 16)), texelHeight: i, maxMip: e };
}
function JA(a, t, e, i) {
  const n = a.getContext(), s = e.defines;
  let r = e.vertexShader, o = e.fragmentShader;
  const l = $A(e), h = XA(e), c = YA(e), u = ZA(e), d = jA(e), p = NA(e), f = OA(s), y = n.createProgram();
  let g, m, v = e.glslVersion ? "#version " + e.glslVersion + `
` : "";
  e.isRawShaderMaterial ? (g = [
    "#define SHADER_TYPE " + e.shaderType,
    "#define SHADER_NAME " + e.shaderName,
    f
  ].filter(ro).join(`
`), g.length > 0 && (g += `
`), m = [
    "#define SHADER_TYPE " + e.shaderType,
    "#define SHADER_NAME " + e.shaderName,
    f
  ].filter(ro).join(`
`), m.length > 0 && (m += `
`)) : (g = [
    ig(e),
    "#define SHADER_TYPE " + e.shaderType,
    "#define SHADER_NAME " + e.shaderName,
    f,
    e.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "",
    e.batching ? "#define USE_BATCHING" : "",
    e.batchingColor ? "#define USE_BATCHING_COLOR" : "",
    e.instancing ? "#define USE_INSTANCING" : "",
    e.instancingColor ? "#define USE_INSTANCING_COLOR" : "",
    e.instancingMorph ? "#define USE_INSTANCING_MORPH" : "",
    e.useFog && e.fog ? "#define USE_FOG" : "",
    e.useFog && e.fogExp2 ? "#define FOG_EXP2" : "",
    e.map ? "#define USE_MAP" : "",
    e.envMap ? "#define USE_ENVMAP" : "",
    e.envMap ? "#define " + c : "",
    e.lightMap ? "#define USE_LIGHTMAP" : "",
    e.aoMap ? "#define USE_AOMAP" : "",
    e.bumpMap ? "#define USE_BUMPMAP" : "",
    e.normalMap ? "#define USE_NORMALMAP" : "",
    e.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
    e.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
    e.displacementMap ? "#define USE_DISPLACEMENTMAP" : "",
    e.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
    e.anisotropy ? "#define USE_ANISOTROPY" : "",
    e.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
    e.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
    e.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
    e.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
    e.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
    e.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
    e.specularMap ? "#define USE_SPECULARMAP" : "",
    e.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
    e.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
    e.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
    e.metalnessMap ? "#define USE_METALNESSMAP" : "",
    e.alphaMap ? "#define USE_ALPHAMAP" : "",
    e.alphaHash ? "#define USE_ALPHAHASH" : "",
    e.transmission ? "#define USE_TRANSMISSION" : "",
    e.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
    e.thicknessMap ? "#define USE_THICKNESSMAP" : "",
    e.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
    e.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
    //
    e.mapUv ? "#define MAP_UV " + e.mapUv : "",
    e.alphaMapUv ? "#define ALPHAMAP_UV " + e.alphaMapUv : "",
    e.lightMapUv ? "#define LIGHTMAP_UV " + e.lightMapUv : "",
    e.aoMapUv ? "#define AOMAP_UV " + e.aoMapUv : "",
    e.emissiveMapUv ? "#define EMISSIVEMAP_UV " + e.emissiveMapUv : "",
    e.bumpMapUv ? "#define BUMPMAP_UV " + e.bumpMapUv : "",
    e.normalMapUv ? "#define NORMALMAP_UV " + e.normalMapUv : "",
    e.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + e.displacementMapUv : "",
    e.metalnessMapUv ? "#define METALNESSMAP_UV " + e.metalnessMapUv : "",
    e.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + e.roughnessMapUv : "",
    e.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + e.anisotropyMapUv : "",
    e.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + e.clearcoatMapUv : "",
    e.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + e.clearcoatNormalMapUv : "",
    e.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + e.clearcoatRoughnessMapUv : "",
    e.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + e.iridescenceMapUv : "",
    e.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + e.iridescenceThicknessMapUv : "",
    e.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + e.sheenColorMapUv : "",
    e.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + e.sheenRoughnessMapUv : "",
    e.specularMapUv ? "#define SPECULARMAP_UV " + e.specularMapUv : "",
    e.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + e.specularColorMapUv : "",
    e.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + e.specularIntensityMapUv : "",
    e.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + e.transmissionMapUv : "",
    e.thicknessMapUv ? "#define THICKNESSMAP_UV " + e.thicknessMapUv : "",
    //
    e.vertexTangents && e.flatShading === !1 ? "#define USE_TANGENT" : "",
    e.vertexColors ? "#define USE_COLOR" : "",
    e.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
    e.vertexUv1s ? "#define USE_UV1" : "",
    e.vertexUv2s ? "#define USE_UV2" : "",
    e.vertexUv3s ? "#define USE_UV3" : "",
    e.pointsUvs ? "#define USE_POINTS_UV" : "",
    e.flatShading ? "#define FLAT_SHADED" : "",
    e.skinning ? "#define USE_SKINNING" : "",
    e.morphTargets ? "#define USE_MORPHTARGETS" : "",
    e.morphNormals && e.flatShading === !1 ? "#define USE_MORPHNORMALS" : "",
    e.morphColors ? "#define USE_MORPHCOLORS" : "",
    e.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + e.morphTextureStride : "",
    e.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + e.morphTargetsCount : "",
    e.doubleSided ? "#define DOUBLE_SIDED" : "",
    e.flipSided ? "#define FLIP_SIDED" : "",
    e.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
    e.shadowMapEnabled ? "#define " + l : "",
    e.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
    e.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
    e.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "",
    e.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "",
    "uniform mat4 modelMatrix;",
    "uniform mat4 modelViewMatrix;",
    "uniform mat4 projectionMatrix;",
    "uniform mat4 viewMatrix;",
    "uniform mat3 normalMatrix;",
    "uniform vec3 cameraPosition;",
    "uniform bool isOrthographic;",
    "#ifdef USE_INSTANCING",
    "	attribute mat4 instanceMatrix;",
    "#endif",
    "#ifdef USE_INSTANCING_COLOR",
    "	attribute vec3 instanceColor;",
    "#endif",
    "#ifdef USE_INSTANCING_MORPH",
    "	uniform sampler2D morphTexture;",
    "#endif",
    "attribute vec3 position;",
    "attribute vec3 normal;",
    "attribute vec2 uv;",
    "#ifdef USE_UV1",
    "	attribute vec2 uv1;",
    "#endif",
    "#ifdef USE_UV2",
    "	attribute vec2 uv2;",
    "#endif",
    "#ifdef USE_UV3",
    "	attribute vec2 uv3;",
    "#endif",
    "#ifdef USE_TANGENT",
    "	attribute vec4 tangent;",
    "#endif",
    "#if defined( USE_COLOR_ALPHA )",
    "	attribute vec4 color;",
    "#elif defined( USE_COLOR )",
    "	attribute vec3 color;",
    "#endif",
    "#ifdef USE_SKINNING",
    "	attribute vec4 skinIndex;",
    "	attribute vec4 skinWeight;",
    "#endif",
    `
`
  ].filter(ro).join(`
`), m = [
    ig(e),
    "#define SHADER_TYPE " + e.shaderType,
    "#define SHADER_NAME " + e.shaderName,
    f,
    e.useFog && e.fog ? "#define USE_FOG" : "",
    e.useFog && e.fogExp2 ? "#define FOG_EXP2" : "",
    e.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "",
    e.map ? "#define USE_MAP" : "",
    e.matcap ? "#define USE_MATCAP" : "",
    e.envMap ? "#define USE_ENVMAP" : "",
    e.envMap ? "#define " + h : "",
    e.envMap ? "#define " + c : "",
    e.envMap ? "#define " + u : "",
    d ? "#define CUBEUV_TEXEL_WIDTH " + d.texelWidth : "",
    d ? "#define CUBEUV_TEXEL_HEIGHT " + d.texelHeight : "",
    d ? "#define CUBEUV_MAX_MIP " + d.maxMip + ".0" : "",
    e.lightMap ? "#define USE_LIGHTMAP" : "",
    e.aoMap ? "#define USE_AOMAP" : "",
    e.bumpMap ? "#define USE_BUMPMAP" : "",
    e.normalMap ? "#define USE_NORMALMAP" : "",
    e.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
    e.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
    e.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
    e.anisotropy ? "#define USE_ANISOTROPY" : "",
    e.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
    e.clearcoat ? "#define USE_CLEARCOAT" : "",
    e.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
    e.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
    e.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
    e.dispersion ? "#define USE_DISPERSION" : "",
    e.iridescence ? "#define USE_IRIDESCENCE" : "",
    e.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
    e.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
    e.specularMap ? "#define USE_SPECULARMAP" : "",
    e.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
    e.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
    e.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
    e.metalnessMap ? "#define USE_METALNESSMAP" : "",
    e.alphaMap ? "#define USE_ALPHAMAP" : "",
    e.alphaTest ? "#define USE_ALPHATEST" : "",
    e.alphaHash ? "#define USE_ALPHAHASH" : "",
    e.sheen ? "#define USE_SHEEN" : "",
    e.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
    e.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
    e.transmission ? "#define USE_TRANSMISSION" : "",
    e.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
    e.thicknessMap ? "#define USE_THICKNESSMAP" : "",
    e.vertexTangents && e.flatShading === !1 ? "#define USE_TANGENT" : "",
    e.vertexColors || e.instancingColor || e.batchingColor ? "#define USE_COLOR" : "",
    e.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
    e.vertexUv1s ? "#define USE_UV1" : "",
    e.vertexUv2s ? "#define USE_UV2" : "",
    e.vertexUv3s ? "#define USE_UV3" : "",
    e.pointsUvs ? "#define USE_POINTS_UV" : "",
    e.gradientMap ? "#define USE_GRADIENTMAP" : "",
    e.flatShading ? "#define FLAT_SHADED" : "",
    e.doubleSided ? "#define DOUBLE_SIDED" : "",
    e.flipSided ? "#define FLIP_SIDED" : "",
    e.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
    e.shadowMapEnabled ? "#define " + l : "",
    e.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "",
    e.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
    e.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "",
    e.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "",
    e.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "",
    e.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "",
    "uniform mat4 viewMatrix;",
    "uniform vec3 cameraPosition;",
    "uniform bool isOrthographic;",
    e.toneMapping !== Zn ? "#define TONE_MAPPING" : "",
    e.toneMapping !== Zn ? Zt.tonemapping_pars_fragment : "",
    // this code is required here because it is used by the toneMapping() function defined below
    e.toneMapping !== Zn ? BA("toneMapping", e.toneMapping) : "",
    e.dithering ? "#define DITHERING" : "",
    e.opaque ? "#define OPAQUE" : "",
    Zt.colorspace_pars_fragment,
    // this code is required here because it is used by the various encoding/decoding function defined below
    UA("linearToOutputTexel", e.outputColorSpace),
    zA(),
    e.useDepthPacking ? "#define DEPTH_PACKING " + e.depthPacking : "",
    `
`
  ].filter(ro).join(`
`)), r = cp(r), r = Qm(r, e), r = tg(r, e), o = cp(o), o = Qm(o, e), o = tg(o, e), r = eg(r), o = eg(o), e.isRawShaderMaterial !== !0 && (v = `#version 300 es
`, g = [
    p,
    "#define attribute in",
    "#define varying out",
    "#define texture2D texture"
  ].join(`
`) + `
` + g, m = [
    "#define varying in",
    e.glslVersion === Qd ? "" : "layout(location = 0) out highp vec4 pc_fragColor;",
    e.glslVersion === Qd ? "" : "#define gl_FragColor pc_fragColor",
    "#define gl_FragDepthEXT gl_FragDepth",
    "#define texture2D texture",
    "#define textureCube texture",
    "#define texture2DProj textureProj",
    "#define texture2DLodEXT textureLod",
    "#define texture2DProjLodEXT textureProjLod",
    "#define textureCubeLodEXT textureLod",
    "#define texture2DGradEXT textureGrad",
    "#define texture2DProjGradEXT textureProjGrad",
    "#define textureCubeGradEXT textureGrad"
  ].join(`
`) + `
` + m);
  const x = v + g + r, _ = v + m + o, S = jm(n, n.VERTEX_SHADER, x), w = jm(n, n.FRAGMENT_SHADER, _);
  n.attachShader(y, S), n.attachShader(y, w), e.index0AttributeName !== void 0 ? n.bindAttribLocation(y, 0, e.index0AttributeName) : e.morphTargets === !0 && n.bindAttribLocation(y, 0, "position"), n.linkProgram(y);
  function T(L) {
    if (a.debug.checkShaderErrors) {
      const U = n.getProgramInfoLog(y) || "", O = n.getShaderInfoLog(S) || "", V = n.getShaderInfoLog(w) || "", W = U.trim(), G = O.trim(), et = V.trim();
      let H = !0, at = !0;
      if (n.getProgramParameter(y, n.LINK_STATUS) === !1)
        if (H = !1, typeof a.debug.onShaderError == "function")
          a.debug.onShaderError(n, y, S, w);
        else {
          const pt = Km(n, S, "vertex"), Mt = Km(n, w, "fragment");
          console.error(
            "THREE.WebGLProgram: Shader Error " + n.getError() + " - VALIDATE_STATUS " + n.getProgramParameter(y, n.VALIDATE_STATUS) + `

Material Name: ` + L.name + `
Material Type: ` + L.type + `

Program Info Log: ` + W + `
` + pt + `
` + Mt
          );
        }
      else W !== "" ? console.warn("THREE.WebGLProgram: Program Info Log:", W) : (G === "" || et === "") && (at = !1);
      at && (L.diagnostics = {
        runnable: H,
        programLog: W,
        vertexShader: {
          log: G,
          prefix: g
        },
        fragmentShader: {
          log: et,
          prefix: m
        }
      });
    }
    n.deleteShader(S), n.deleteShader(w), R = new Ch(n, y), b = kA(n, y);
  }
  let R;
  this.getUniforms = function() {
    return R === void 0 && T(this), R;
  };
  let b;
  this.getAttributes = function() {
    return b === void 0 && T(this), b;
  };
  let M = e.rendererExtensionParallelShaderCompile === !1;
  return this.isReady = function() {
    return M === !1 && (M = n.getProgramParameter(y, IA)), M;
  }, this.destroy = function() {
    i.releaseStatesOfProgram(this), n.deleteProgram(y), this.program = void 0;
  }, this.type = e.shaderType, this.name = e.shaderName, this.id = LA++, this.cacheKey = t, this.usedTimes = 1, this.program = y, this.vertexShader = S, this.fragmentShader = w, this;
}
let KA = 0;
class QA {
  constructor() {
    this.shaderCache = /* @__PURE__ */ new Map(), this.materialCache = /* @__PURE__ */ new Map();
  }
  update(t) {
    const e = t.vertexShader, i = t.fragmentShader, n = this._getShaderStage(e), s = this._getShaderStage(i), r = this._getShaderCacheForMaterial(t);
    return r.has(n) === !1 && (r.add(n), n.usedTimes++), r.has(s) === !1 && (r.add(s), s.usedTimes++), this;
  }
  remove(t) {
    const e = this.materialCache.get(t);
    for (const i of e)
      i.usedTimes--, i.usedTimes === 0 && this.shaderCache.delete(i.code);
    return this.materialCache.delete(t), this;
  }
  getVertexShaderID(t) {
    return this._getShaderStage(t.vertexShader).id;
  }
  getFragmentShaderID(t) {
    return this._getShaderStage(t.fragmentShader).id;
  }
  dispose() {
    this.shaderCache.clear(), this.materialCache.clear();
  }
  _getShaderCacheForMaterial(t) {
    const e = this.materialCache;
    let i = e.get(t);
    return i === void 0 && (i = /* @__PURE__ */ new Set(), e.set(t, i)), i;
  }
  _getShaderStage(t) {
    const e = this.shaderCache;
    let i = e.get(t);
    return i === void 0 && (i = new tE(t), e.set(t, i)), i;
  }
}
class tE {
  constructor(t) {
    this.id = KA++, this.code = t, this.usedTimes = 0;
  }
}
function eE(a, t, e, i, n, s, r) {
  const o = new Nc(), l = new QA(), h = /* @__PURE__ */ new Set(), c = [], u = n.logarithmicDepthBuffer, d = n.vertexTextures;
  let p = n.precision;
  const f = {
    MeshDepthMaterial: "depth",
    MeshDistanceMaterial: "distanceRGBA",
    MeshNormalMaterial: "normal",
    MeshBasicMaterial: "basic",
    MeshLambertMaterial: "lambert",
    MeshPhongMaterial: "phong",
    MeshToonMaterial: "toon",
    MeshStandardMaterial: "physical",
    MeshPhysicalMaterial: "physical",
    MeshMatcapMaterial: "matcap",
    LineBasicMaterial: "basic",
    LineDashedMaterial: "dashed",
    PointsMaterial: "points",
    ShadowMaterial: "shadow",
    SpriteMaterial: "sprite"
  };
  function y(b) {
    return h.add(b), b === 0 ? "uv" : `uv${b}`;
  }
  function g(b, M, L, U, O) {
    const V = U.fog, W = O.geometry, G = b.isMeshStandardMaterial ? U.environment : null, et = (b.isMeshStandardMaterial ? e : t).get(b.envMap || G), H = et && et.mapping === Sa ? et.image.height : null, at = f[b.type];
    b.precision !== null && (p = n.getMaxPrecision(b.precision), p !== b.precision && console.warn("THREE.WebGLProgram.getParameters:", b.precision, "not supported, using", p, "instead."));
    const pt = W.morphAttributes.position || W.morphAttributes.normal || W.morphAttributes.color, Mt = pt !== void 0 ? pt.length : 0;
    let Lt = 0;
    W.morphAttributes.position !== void 0 && (Lt = 1), W.morphAttributes.normal !== void 0 && (Lt = 2), W.morphAttributes.color !== void 0 && (Lt = 3);
    let jt, ne, Jt, Y;
    if (at) {
      const oe = fi[at];
      jt = oe.vertexShader, ne = oe.fragmentShader;
    } else
      jt = b.vertexShader, ne = b.fragmentShader, l.update(b), Jt = l.getVertexShaderID(b), Y = l.getFragmentShaderID(b);
    const st = a.getRenderTarget(), Et = a.state.buffers.depth.getReversed(), Ut = O.isInstancedMesh === !0, Pt = O.isBatchedMesh === !0, Kt = !!b.map, he = !!b.matcap, D = !!et, ot = !!b.aoMap, it = !!b.lightMap, Q = !!b.bumpMap, K = !!b.normalMap, yt = !!b.displacementMap, ut = !!b.emissiveMap, xt = !!b.metalnessMap, Wt = !!b.roughnessMap, Nt = b.anisotropy > 0, P = b.clearcoat > 0, A = b.dispersion > 0, N = b.iridescence > 0, X = b.sheen > 0, rt = b.transmission > 0, Z = Nt && !!b.anisotropyMap, It = P && !!b.clearcoatMap, I = P && !!b.clearcoatNormalMap, lt = P && !!b.clearcoatRoughnessMap, gt = N && !!b.iridescenceMap, j = N && !!b.iridescenceThicknessMap, mt = X && !!b.sheenColorMap, At = X && !!b.sheenRoughnessMap, Tt = !!b.specularMap, vt = !!b.specularColorMap, $t = !!b.specularIntensityMap, F = rt && !!b.transmissionMap, ht = rt && !!b.thicknessMap, _t = !!b.gradientMap, Rt = !!b.alphaMap, dt = b.alphaTest > 0, nt = !!b.alphaHash, Ft = !!b.extensions;
    let qt = Zn;
    b.toneMapped && (st === null || st.isXRRenderTarget === !0) && (qt = a.toneMapping);
    const ge = {
      shaderID: at,
      shaderType: b.type,
      shaderName: b.name,
      vertexShader: jt,
      fragmentShader: ne,
      defines: b.defines,
      customVertexShaderID: Jt,
      customFragmentShaderID: Y,
      isRawShaderMaterial: b.isRawShaderMaterial === !0,
      glslVersion: b.glslVersion,
      precision: p,
      batching: Pt,
      batchingColor: Pt && O._colorsTexture !== null,
      instancing: Ut,
      instancingColor: Ut && O.instanceColor !== null,
      instancingMorph: Ut && O.morphTexture !== null,
      supportsVertexTextures: d,
      outputColorSpace: st === null ? a.outputColorSpace : st.isXRRenderTarget === !0 ? st.texture.colorSpace : Cs,
      alphaToCoverage: !!b.alphaToCoverage,
      map: Kt,
      matcap: he,
      envMap: D,
      envMapMode: D && et.mapping,
      envMapCubeUVHeight: H,
      aoMap: ot,
      lightMap: it,
      bumpMap: Q,
      normalMap: K,
      displacementMap: d && yt,
      emissiveMap: ut,
      normalMapObjectSpace: K && b.normalMapType === sy,
      normalMapTangentSpace: K && b.normalMapType === Is,
      metalnessMap: xt,
      roughnessMap: Wt,
      anisotropy: Nt,
      anisotropyMap: Z,
      clearcoat: P,
      clearcoatMap: It,
      clearcoatNormalMap: I,
      clearcoatRoughnessMap: lt,
      dispersion: A,
      iridescence: N,
      iridescenceMap: gt,
      iridescenceThicknessMap: j,
      sheen: X,
      sheenColorMap: mt,
      sheenRoughnessMap: At,
      specularMap: Tt,
      specularColorMap: vt,
      specularIntensityMap: $t,
      transmission: rt,
      transmissionMap: F,
      thicknessMap: ht,
      gradientMap: _t,
      opaque: b.transparent === !1 && b.blending === ws && b.alphaToCoverage === !1,
      alphaMap: Rt,
      alphaTest: dt,
      alphaHash: nt,
      combine: b.combine,
      //
      mapUv: Kt && y(b.map.channel),
      aoMapUv: ot && y(b.aoMap.channel),
      lightMapUv: it && y(b.lightMap.channel),
      bumpMapUv: Q && y(b.bumpMap.channel),
      normalMapUv: K && y(b.normalMap.channel),
      displacementMapUv: yt && y(b.displacementMap.channel),
      emissiveMapUv: ut && y(b.emissiveMap.channel),
      metalnessMapUv: xt && y(b.metalnessMap.channel),
      roughnessMapUv: Wt && y(b.roughnessMap.channel),
      anisotropyMapUv: Z && y(b.anisotropyMap.channel),
      clearcoatMapUv: It && y(b.clearcoatMap.channel),
      clearcoatNormalMapUv: I && y(b.clearcoatNormalMap.channel),
      clearcoatRoughnessMapUv: lt && y(b.clearcoatRoughnessMap.channel),
      iridescenceMapUv: gt && y(b.iridescenceMap.channel),
      iridescenceThicknessMapUv: j && y(b.iridescenceThicknessMap.channel),
      sheenColorMapUv: mt && y(b.sheenColorMap.channel),
      sheenRoughnessMapUv: At && y(b.sheenRoughnessMap.channel),
      specularMapUv: Tt && y(b.specularMap.channel),
      specularColorMapUv: vt && y(b.specularColorMap.channel),
      specularIntensityMapUv: $t && y(b.specularIntensityMap.channel),
      transmissionMapUv: F && y(b.transmissionMap.channel),
      thicknessMapUv: ht && y(b.thicknessMap.channel),
      alphaMapUv: Rt && y(b.alphaMap.channel),
      //
      vertexTangents: !!W.attributes.tangent && (K || Nt),
      vertexColors: b.vertexColors,
      vertexAlphas: b.vertexColors === !0 && !!W.attributes.color && W.attributes.color.itemSize === 4,
      pointsUvs: O.isPoints === !0 && !!W.attributes.uv && (Kt || Rt),
      fog: !!V,
      useFog: b.fog === !0,
      fogExp2: !!V && V.isFogExp2,
      flatShading: b.flatShading === !0 && b.wireframe === !1,
      sizeAttenuation: b.sizeAttenuation === !0,
      logarithmicDepthBuffer: u,
      reversedDepthBuffer: Et,
      skinning: O.isSkinnedMesh === !0,
      morphTargets: W.morphAttributes.position !== void 0,
      morphNormals: W.morphAttributes.normal !== void 0,
      morphColors: W.morphAttributes.color !== void 0,
      morphTargetsCount: Mt,
      morphTextureStride: Lt,
      numDirLights: M.directional.length,
      numPointLights: M.point.length,
      numSpotLights: M.spot.length,
      numSpotLightMaps: M.spotLightMap.length,
      numRectAreaLights: M.rectArea.length,
      numHemiLights: M.hemi.length,
      numDirLightShadows: M.directionalShadowMap.length,
      numPointLightShadows: M.pointShadowMap.length,
      numSpotLightShadows: M.spotShadowMap.length,
      numSpotLightShadowsWithMaps: M.numSpotLightShadowsWithMaps,
      numLightProbes: M.numLightProbes,
      numClippingPlanes: r.numPlanes,
      numClipIntersection: r.numIntersection,
      dithering: b.dithering,
      shadowMapEnabled: a.shadowMap.enabled && L.length > 0,
      shadowMapType: a.shadowMap.type,
      toneMapping: qt,
      decodeVideoTexture: Kt && b.map.isVideoTexture === !0 && ee.getTransfer(b.map.colorSpace) === ce,
      decodeVideoTextureEmissive: ut && b.emissiveMap.isVideoTexture === !0 && ee.getTransfer(b.emissiveMap.colorSpace) === ce,
      premultipliedAlpha: b.premultipliedAlpha,
      doubleSided: b.side === Mi,
      flipSided: b.side === He,
      useDepthPacking: b.depthPacking >= 0,
      depthPacking: b.depthPacking || 0,
      index0AttributeName: b.index0AttributeName,
      extensionClipCullDistance: Ft && b.extensions.clipCullDistance === !0 && i.has("WEBGL_clip_cull_distance"),
      extensionMultiDraw: (Ft && b.extensions.multiDraw === !0 || Pt) && i.has("WEBGL_multi_draw"),
      rendererExtensionParallelShaderCompile: i.has("KHR_parallel_shader_compile"),
      customProgramCacheKey: b.customProgramCacheKey()
    };
    return ge.vertexUv1s = h.has(1), ge.vertexUv2s = h.has(2), ge.vertexUv3s = h.has(3), h.clear(), ge;
  }
  function m(b) {
    const M = [];
    if (b.shaderID ? M.push(b.shaderID) : (M.push(b.customVertexShaderID), M.push(b.customFragmentShaderID)), b.defines !== void 0)
      for (const L in b.defines)
        M.push(L), M.push(b.defines[L]);
    return b.isRawShaderMaterial === !1 && (v(M, b), x(M, b), M.push(a.outputColorSpace)), M.push(b.customProgramCacheKey), M.join();
  }
  function v(b, M) {
    b.push(M.precision), b.push(M.outputColorSpace), b.push(M.envMapMode), b.push(M.envMapCubeUVHeight), b.push(M.mapUv), b.push(M.alphaMapUv), b.push(M.lightMapUv), b.push(M.aoMapUv), b.push(M.bumpMapUv), b.push(M.normalMapUv), b.push(M.displacementMapUv), b.push(M.emissiveMapUv), b.push(M.metalnessMapUv), b.push(M.roughnessMapUv), b.push(M.anisotropyMapUv), b.push(M.clearcoatMapUv), b.push(M.clearcoatNormalMapUv), b.push(M.clearcoatRoughnessMapUv), b.push(M.iridescenceMapUv), b.push(M.iridescenceThicknessMapUv), b.push(M.sheenColorMapUv), b.push(M.sheenRoughnessMapUv), b.push(M.specularMapUv), b.push(M.specularColorMapUv), b.push(M.specularIntensityMapUv), b.push(M.transmissionMapUv), b.push(M.thicknessMapUv), b.push(M.combine), b.push(M.fogExp2), b.push(M.sizeAttenuation), b.push(M.morphTargetsCount), b.push(M.morphAttributeCount), b.push(M.numDirLights), b.push(M.numPointLights), b.push(M.numSpotLights), b.push(M.numSpotLightMaps), b.push(M.numHemiLights), b.push(M.numRectAreaLights), b.push(M.numDirLightShadows), b.push(M.numPointLightShadows), b.push(M.numSpotLightShadows), b.push(M.numSpotLightShadowsWithMaps), b.push(M.numLightProbes), b.push(M.shadowMapType), b.push(M.toneMapping), b.push(M.numClippingPlanes), b.push(M.numClipIntersection), b.push(M.depthPacking);
  }
  function x(b, M) {
    o.disableAll(), M.supportsVertexTextures && o.enable(0), M.instancing && o.enable(1), M.instancingColor && o.enable(2), M.instancingMorph && o.enable(3), M.matcap && o.enable(4), M.envMap && o.enable(5), M.normalMapObjectSpace && o.enable(6), M.normalMapTangentSpace && o.enable(7), M.clearcoat && o.enable(8), M.iridescence && o.enable(9), M.alphaTest && o.enable(10), M.vertexColors && o.enable(11), M.vertexAlphas && o.enable(12), M.vertexUv1s && o.enable(13), M.vertexUv2s && o.enable(14), M.vertexUv3s && o.enable(15), M.vertexTangents && o.enable(16), M.anisotropy && o.enable(17), M.alphaHash && o.enable(18), M.batching && o.enable(19), M.dispersion && o.enable(20), M.batchingColor && o.enable(21), M.gradientMap && o.enable(22), b.push(o.mask), o.disableAll(), M.fog && o.enable(0), M.useFog && o.enable(1), M.flatShading && o.enable(2), M.logarithmicDepthBuffer && o.enable(3), M.reversedDepthBuffer && o.enable(4), M.skinning && o.enable(5), M.morphTargets && o.enable(6), M.morphNormals && o.enable(7), M.morphColors && o.enable(8), M.premultipliedAlpha && o.enable(9), M.shadowMapEnabled && o.enable(10), M.doubleSided && o.enable(11), M.flipSided && o.enable(12), M.useDepthPacking && o.enable(13), M.dithering && o.enable(14), M.transmission && o.enable(15), M.sheen && o.enable(16), M.opaque && o.enable(17), M.pointsUvs && o.enable(18), M.decodeVideoTexture && o.enable(19), M.decodeVideoTextureEmissive && o.enable(20), M.alphaToCoverage && o.enable(21), b.push(o.mask);
  }
  function _(b) {
    const M = f[b.type];
    let L;
    if (M) {
      const U = fi[M];
      L = Oc.clone(U.uniforms);
    } else
      L = b.uniforms;
    return L;
  }
  function S(b, M) {
    let L;
    for (let U = 0, O = c.length; U < O; U++) {
      const V = c[U];
      if (V.cacheKey === M) {
        L = V, ++L.usedTimes;
        break;
      }
    }
    return L === void 0 && (L = new JA(a, M, b, s), c.push(L)), L;
  }
  function w(b) {
    if (--b.usedTimes === 0) {
      const M = c.indexOf(b);
      c[M] = c[c.length - 1], c.pop(), b.destroy();
    }
  }
  function T(b) {
    l.remove(b);
  }
  function R() {
    l.dispose();
  }
  return {
    getParameters: g,
    getProgramCacheKey: m,
    getUniforms: _,
    acquireProgram: S,
    releaseProgram: w,
    releaseShaderCache: T,
    // Exposed for resource monitoring & error feedback via renderer.info:
    programs: c,
    dispose: R
  };
}
function iE() {
  let a = /* @__PURE__ */ new WeakMap();
  function t(r) {
    return a.has(r);
  }
  function e(r) {
    let o = a.get(r);
    return o === void 0 && (o = {}, a.set(r, o)), o;
  }
  function i(r) {
    a.delete(r);
  }
  function n(r, o, l) {
    a.get(r)[o] = l;
  }
  function s() {
    a = /* @__PURE__ */ new WeakMap();
  }
  return {
    has: t,
    get: e,
    remove: i,
    update: n,
    dispose: s
  };
}
function nE(a, t) {
  return a.groupOrder !== t.groupOrder ? a.groupOrder - t.groupOrder : a.renderOrder !== t.renderOrder ? a.renderOrder - t.renderOrder : a.material.id !== t.material.id ? a.material.id - t.material.id : a.z !== t.z ? a.z - t.z : a.id - t.id;
}
function ng(a, t) {
  return a.groupOrder !== t.groupOrder ? a.groupOrder - t.groupOrder : a.renderOrder !== t.renderOrder ? a.renderOrder - t.renderOrder : a.z !== t.z ? t.z - a.z : a.id - t.id;
}
function sg() {
  const a = [];
  let t = 0;
  const e = [], i = [], n = [];
  function s() {
    t = 0, e.length = 0, i.length = 0, n.length = 0;
  }
  function r(u, d, p, f, y, g) {
    let m = a[t];
    return m === void 0 ? (m = {
      id: u.id,
      object: u,
      geometry: d,
      material: p,
      groupOrder: f,
      renderOrder: u.renderOrder,
      z: y,
      group: g
    }, a[t] = m) : (m.id = u.id, m.object = u, m.geometry = d, m.material = p, m.groupOrder = f, m.renderOrder = u.renderOrder, m.z = y, m.group = g), t++, m;
  }
  function o(u, d, p, f, y, g) {
    const m = r(u, d, p, f, y, g);
    p.transmission > 0 ? i.push(m) : p.transparent === !0 ? n.push(m) : e.push(m);
  }
  function l(u, d, p, f, y, g) {
    const m = r(u, d, p, f, y, g);
    p.transmission > 0 ? i.unshift(m) : p.transparent === !0 ? n.unshift(m) : e.unshift(m);
  }
  function h(u, d) {
    e.length > 1 && e.sort(u || nE), i.length > 1 && i.sort(d || ng), n.length > 1 && n.sort(d || ng);
  }
  function c() {
    for (let u = t, d = a.length; u < d; u++) {
      const p = a[u];
      if (p.id === null) break;
      p.id = null, p.object = null, p.geometry = null, p.material = null, p.group = null;
    }
  }
  return {
    opaque: e,
    transmissive: i,
    transparent: n,
    init: s,
    push: o,
    unshift: l,
    finish: c,
    sort: h
  };
}
function sE() {
  let a = /* @__PURE__ */ new WeakMap();
  function t(i, n) {
    const s = a.get(i);
    let r;
    return s === void 0 ? (r = new sg(), a.set(i, [r])) : n >= s.length ? (r = new sg(), s.push(r)) : r = s[n], r;
  }
  function e() {
    a = /* @__PURE__ */ new WeakMap();
  }
  return {
    get: t,
    dispose: e
  };
}
function rE() {
  const a = {};
  return {
    get: function(t) {
      if (a[t.id] !== void 0)
        return a[t.id];
      let e;
      switch (t.type) {
        case "DirectionalLight":
          e = {
            direction: new E(),
            color: new ct()
          };
          break;
        case "SpotLight":
          e = {
            position: new E(),
            direction: new E(),
            color: new ct(),
            distance: 0,
            coneCos: 0,
            penumbraCos: 0,
            decay: 0
          };
          break;
        case "PointLight":
          e = {
            position: new E(),
            color: new ct(),
            distance: 0,
            decay: 0
          };
          break;
        case "HemisphereLight":
          e = {
            direction: new E(),
            skyColor: new ct(),
            groundColor: new ct()
          };
          break;
        case "RectAreaLight":
          e = {
            color: new ct(),
            position: new E(),
            halfWidth: new E(),
            halfHeight: new E()
          };
          break;
      }
      return a[t.id] = e, e;
    }
  };
}
function aE() {
  const a = {};
  return {
    get: function(t) {
      if (a[t.id] !== void 0)
        return a[t.id];
      let e;
      switch (t.type) {
        case "DirectionalLight":
          e = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new J()
          };
          break;
        case "SpotLight":
          e = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new J()
          };
          break;
        case "PointLight":
          e = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new J(),
            shadowCameraNear: 1,
            shadowCameraFar: 1e3
          };
          break;
      }
      return a[t.id] = e, e;
    }
  };
}
let oE = 0;
function lE(a, t) {
  return (t.castShadow ? 2 : 0) - (a.castShadow ? 2 : 0) + (t.map ? 1 : 0) - (a.map ? 1 : 0);
}
function hE(a) {
  const t = new rE(), e = aE(), i = {
    version: 0,
    hash: {
      directionalLength: -1,
      pointLength: -1,
      spotLength: -1,
      rectAreaLength: -1,
      hemiLength: -1,
      numDirectionalShadows: -1,
      numPointShadows: -1,
      numSpotShadows: -1,
      numSpotMaps: -1,
      numLightProbes: -1
    },
    ambient: [0, 0, 0],
    probe: [],
    directional: [],
    directionalShadow: [],
    directionalShadowMap: [],
    directionalShadowMatrix: [],
    spot: [],
    spotLightMap: [],
    spotShadow: [],
    spotShadowMap: [],
    spotLightMatrix: [],
    rectArea: [],
    rectAreaLTC1: null,
    rectAreaLTC2: null,
    point: [],
    pointShadow: [],
    pointShadowMap: [],
    pointShadowMatrix: [],
    hemi: [],
    numSpotLightShadowsWithMaps: 0,
    numLightProbes: 0
  };
  for (let h = 0; h < 9; h++) i.probe.push(new E());
  const n = new E(), s = new Vt(), r = new Vt();
  function o(h) {
    let c = 0, u = 0, d = 0;
    for (let b = 0; b < 9; b++) i.probe[b].set(0, 0, 0);
    let p = 0, f = 0, y = 0, g = 0, m = 0, v = 0, x = 0, _ = 0, S = 0, w = 0, T = 0;
    h.sort(lE);
    for (let b = 0, M = h.length; b < M; b++) {
      const L = h[b], U = L.color, O = L.intensity, V = L.distance, W = L.shadow && L.shadow.map ? L.shadow.map.texture : null;
      if (L.isAmbientLight)
        c += U.r * O, u += U.g * O, d += U.b * O;
      else if (L.isLightProbe) {
        for (let G = 0; G < 9; G++)
          i.probe[G].addScaledVector(L.sh.coefficients[G], O);
        T++;
      } else if (L.isDirectionalLight) {
        const G = t.get(L);
        if (G.color.copy(L.color).multiplyScalar(L.intensity), L.castShadow) {
          const et = L.shadow, H = e.get(L);
          H.shadowIntensity = et.intensity, H.shadowBias = et.bias, H.shadowNormalBias = et.normalBias, H.shadowRadius = et.radius, H.shadowMapSize = et.mapSize, i.directionalShadow[p] = H, i.directionalShadowMap[p] = W, i.directionalShadowMatrix[p] = L.shadow.matrix, v++;
        }
        i.directional[p] = G, p++;
      } else if (L.isSpotLight) {
        const G = t.get(L);
        G.position.setFromMatrixPosition(L.matrixWorld), G.color.copy(U).multiplyScalar(O), G.distance = V, G.coneCos = Math.cos(L.angle), G.penumbraCos = Math.cos(L.angle * (1 - L.penumbra)), G.decay = L.decay, i.spot[y] = G;
        const et = L.shadow;
        if (L.map && (i.spotLightMap[S] = L.map, S++, et.updateMatrices(L), L.castShadow && w++), i.spotLightMatrix[y] = et.matrix, L.castShadow) {
          const H = e.get(L);
          H.shadowIntensity = et.intensity, H.shadowBias = et.bias, H.shadowNormalBias = et.normalBias, H.shadowRadius = et.radius, H.shadowMapSize = et.mapSize, i.spotShadow[y] = H, i.spotShadowMap[y] = W, _++;
        }
        y++;
      } else if (L.isRectAreaLight) {
        const G = t.get(L);
        G.color.copy(U).multiplyScalar(O), G.halfWidth.set(L.width * 0.5, 0, 0), G.halfHeight.set(0, L.height * 0.5, 0), i.rectArea[g] = G, g++;
      } else if (L.isPointLight) {
        const G = t.get(L);
        if (G.color.copy(L.color).multiplyScalar(L.intensity), G.distance = L.distance, G.decay = L.decay, L.castShadow) {
          const et = L.shadow, H = e.get(L);
          H.shadowIntensity = et.intensity, H.shadowBias = et.bias, H.shadowNormalBias = et.normalBias, H.shadowRadius = et.radius, H.shadowMapSize = et.mapSize, H.shadowCameraNear = et.camera.near, H.shadowCameraFar = et.camera.far, i.pointShadow[f] = H, i.pointShadowMap[f] = W, i.pointShadowMatrix[f] = L.shadow.matrix, x++;
        }
        i.point[f] = G, f++;
      } else if (L.isHemisphereLight) {
        const G = t.get(L);
        G.skyColor.copy(L.color).multiplyScalar(O), G.groundColor.copy(L.groundColor).multiplyScalar(O), i.hemi[m] = G, m++;
      }
    }
    g > 0 && (a.has("OES_texture_float_linear") === !0 ? (i.rectAreaLTC1 = bt.LTC_FLOAT_1, i.rectAreaLTC2 = bt.LTC_FLOAT_2) : (i.rectAreaLTC1 = bt.LTC_HALF_1, i.rectAreaLTC2 = bt.LTC_HALF_2)), i.ambient[0] = c, i.ambient[1] = u, i.ambient[2] = d;
    const R = i.hash;
    (R.directionalLength !== p || R.pointLength !== f || R.spotLength !== y || R.rectAreaLength !== g || R.hemiLength !== m || R.numDirectionalShadows !== v || R.numPointShadows !== x || R.numSpotShadows !== _ || R.numSpotMaps !== S || R.numLightProbes !== T) && (i.directional.length = p, i.spot.length = y, i.rectArea.length = g, i.point.length = f, i.hemi.length = m, i.directionalShadow.length = v, i.directionalShadowMap.length = v, i.pointShadow.length = x, i.pointShadowMap.length = x, i.spotShadow.length = _, i.spotShadowMap.length = _, i.directionalShadowMatrix.length = v, i.pointShadowMatrix.length = x, i.spotLightMatrix.length = _ + S - w, i.spotLightMap.length = S, i.numSpotLightShadowsWithMaps = w, i.numLightProbes = T, R.directionalLength = p, R.pointLength = f, R.spotLength = y, R.rectAreaLength = g, R.hemiLength = m, R.numDirectionalShadows = v, R.numPointShadows = x, R.numSpotShadows = _, R.numSpotMaps = S, R.numLightProbes = T, i.version = oE++);
  }
  function l(h, c) {
    let u = 0, d = 0, p = 0, f = 0, y = 0;
    const g = c.matrixWorldInverse;
    for (let m = 0, v = h.length; m < v; m++) {
      const x = h[m];
      if (x.isDirectionalLight) {
        const _ = i.directional[u];
        _.direction.setFromMatrixPosition(x.matrixWorld), n.setFromMatrixPosition(x.target.matrixWorld), _.direction.sub(n), _.direction.transformDirection(g), u++;
      } else if (x.isSpotLight) {
        const _ = i.spot[p];
        _.position.setFromMatrixPosition(x.matrixWorld), _.position.applyMatrix4(g), _.direction.setFromMatrixPosition(x.matrixWorld), n.setFromMatrixPosition(x.target.matrixWorld), _.direction.sub(n), _.direction.transformDirection(g), p++;
      } else if (x.isRectAreaLight) {
        const _ = i.rectArea[f];
        _.position.setFromMatrixPosition(x.matrixWorld), _.position.applyMatrix4(g), r.identity(), s.copy(x.matrixWorld), s.premultiply(g), r.extractRotation(s), _.halfWidth.set(x.width * 0.5, 0, 0), _.halfHeight.set(0, x.height * 0.5, 0), _.halfWidth.applyMatrix4(r), _.halfHeight.applyMatrix4(r), f++;
      } else if (x.isPointLight) {
        const _ = i.point[d];
        _.position.setFromMatrixPosition(x.matrixWorld), _.position.applyMatrix4(g), d++;
      } else if (x.isHemisphereLight) {
        const _ = i.hemi[y];
        _.direction.setFromMatrixPosition(x.matrixWorld), _.direction.transformDirection(g), y++;
      }
    }
  }
  return {
    setup: o,
    setupView: l,
    state: i
  };
}
function rg(a) {
  const t = new hE(a), e = [], i = [];
  function n(c) {
    h.camera = c, e.length = 0, i.length = 0;
  }
  function s(c) {
    e.push(c);
  }
  function r(c) {
    i.push(c);
  }
  function o() {
    t.setup(e);
  }
  function l(c) {
    t.setupView(e, c);
  }
  const h = {
    lightsArray: e,
    shadowsArray: i,
    camera: null,
    lights: t,
    transmissionRenderTarget: {}
  };
  return {
    init: n,
    state: h,
    setupLights: o,
    setupLightsView: l,
    pushLight: s,
    pushShadow: r
  };
}
function cE(a) {
  let t = /* @__PURE__ */ new WeakMap();
  function e(n, s = 0) {
    const r = t.get(n);
    let o;
    return r === void 0 ? (o = new rg(a), t.set(n, [o])) : s >= r.length ? (o = new rg(a), r.push(o)) : o = r[s], o;
  }
  function i() {
    t = /* @__PURE__ */ new WeakMap();
  }
  return {
    get: e,
    dispose: i
  };
}
const uE = `void main() {
	gl_Position = vec4( position, 1.0 );
}`, dE = `uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
void main() {
	const float samples = float( VSM_SAMPLES );
	float mean = 0.0;
	float squared_mean = 0.0;
	float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
	float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
	for ( float i = 0.0; i < samples; i ++ ) {
		float uvOffset = uvStart + i * uvStride;
		#ifdef HORIZONTAL_PASS
			vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
			mean += distribution.x;
			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
		#else
			float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
			mean += depth;
			squared_mean += depth * depth;
		#endif
	}
	mean = mean / samples;
	squared_mean = squared_mean / samples;
	float std_dev = sqrt( squared_mean - mean * mean );
	gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
}`;
function pE(a, t, e) {
  let i = new Ea();
  const n = new J(), s = new J(), r = new Qt(), o = new jp({ depthPacking: ny }), l = new Jp(), h = {}, c = e.maxTextureSize, u = { [$i]: He, [He]: $i, [Mi]: Mi }, d = new Xi({
    defines: {
      VSM_SAMPLES: 8
    },
    uniforms: {
      shadow_pass: { value: null },
      resolution: { value: new J() },
      radius: { value: 4 }
    },
    vertexShader: uE,
    fragmentShader: dE
  }), p = d.clone();
  p.defines.HORIZONTAL_PASS = 1;
  const f = new Ht();
  f.setAttribute(
    "position",
    new ie(
      new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]),
      3
    )
  );
  const y = new re(f, d), g = this;
  this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = Mp;
  let m = this.type;
  this.render = function(w, T, R) {
    if (g.enabled === !1 || g.autoUpdate === !1 && g.needsUpdate === !1 || w.length === 0) return;
    const b = a.getRenderTarget(), M = a.getActiveCubeFace(), L = a.getActiveMipmapLevel(), U = a.state;
    U.setBlending(Yn), U.buffers.depth.getReversed() === !0 ? U.buffers.color.setClear(0, 0, 0, 0) : U.buffers.color.setClear(1, 1, 1, 1), U.buffers.depth.setTest(!0), U.setScissorTest(!1);
    const O = m !== Sn && this.type === Sn, V = m === Sn && this.type !== Sn;
    for (let W = 0, G = w.length; W < G; W++) {
      const et = w[W], H = et.shadow;
      if (H === void 0) {
        console.warn("THREE.WebGLShadowMap:", et, "has no shadow.");
        continue;
      }
      if (H.autoUpdate === !1 && H.needsUpdate === !1) continue;
      n.copy(H.mapSize);
      const at = H.getFrameExtents();
      if (n.multiply(at), s.copy(H.mapSize), (n.x > c || n.y > c) && (n.x > c && (s.x = Math.floor(c / at.x), n.x = s.x * at.x, H.mapSize.x = s.x), n.y > c && (s.y = Math.floor(c / at.y), n.y = s.y * at.y, H.mapSize.y = s.y)), H.map === null || O === !0 || V === !0) {
        const Mt = this.type !== Sn ? { minFilter: je, magFilter: je } : {};
        H.map !== null && H.map.dispose(), H.map = new Rn(n.x, n.y, Mt), H.map.texture.name = et.name + ".shadowMap", H.camera.updateProjectionMatrix();
      }
      a.setRenderTarget(H.map), a.clear();
      const pt = H.getViewportCount();
      for (let Mt = 0; Mt < pt; Mt++) {
        const Lt = H.getViewport(Mt);
        r.set(
          s.x * Lt.x,
          s.y * Lt.y,
          s.x * Lt.z,
          s.y * Lt.w
        ), U.viewport(r), H.updateMatrices(et, Mt), i = H.getFrustum(), _(T, R, H.camera, et, this.type);
      }
      H.isPointLightShadow !== !0 && this.type === Sn && v(H, R), H.needsUpdate = !1;
    }
    m = this.type, g.needsUpdate = !1, a.setRenderTarget(b, M, L);
  };
  function v(w, T) {
    const R = t.update(y);
    d.defines.VSM_SAMPLES !== w.blurSamples && (d.defines.VSM_SAMPLES = w.blurSamples, p.defines.VSM_SAMPLES = w.blurSamples, d.needsUpdate = !0, p.needsUpdate = !0), w.mapPass === null && (w.mapPass = new Rn(n.x, n.y)), d.uniforms.shadow_pass.value = w.map.texture, d.uniforms.resolution.value = w.mapSize, d.uniforms.radius.value = w.radius, a.setRenderTarget(w.mapPass), a.clear(), a.renderBufferDirect(T, null, R, d, y, null), p.uniforms.shadow_pass.value = w.mapPass.texture, p.uniforms.resolution.value = w.mapSize, p.uniforms.radius.value = w.radius, a.setRenderTarget(w.map), a.clear(), a.renderBufferDirect(T, null, R, p, y, null);
  }
  function x(w, T, R, b) {
    let M = null;
    const L = R.isPointLight === !0 ? w.customDistanceMaterial : w.customDepthMaterial;
    if (L !== void 0)
      M = L;
    else if (M = R.isPointLight === !0 ? l : o, a.localClippingEnabled && T.clipShadows === !0 && Array.isArray(T.clippingPlanes) && T.clippingPlanes.length !== 0 || T.displacementMap && T.displacementScale !== 0 || T.alphaMap && T.alphaTest > 0 || T.map && T.alphaTest > 0 || T.alphaToCoverage === !0) {
      const U = M.uuid, O = T.uuid;
      let V = h[U];
      V === void 0 && (V = {}, h[U] = V);
      let W = V[O];
      W === void 0 && (W = M.clone(), V[O] = W, T.addEventListener("dispose", S)), M = W;
    }
    if (M.visible = T.visible, M.wireframe = T.wireframe, b === Sn ? M.side = T.shadowSide !== null ? T.shadowSide : T.side : M.side = T.shadowSide !== null ? T.shadowSide : u[T.side], M.alphaMap = T.alphaMap, M.alphaTest = T.alphaToCoverage === !0 ? 0.5 : T.alphaTest, M.map = T.map, M.clipShadows = T.clipShadows, M.clippingPlanes = T.clippingPlanes, M.clipIntersection = T.clipIntersection, M.displacementMap = T.displacementMap, M.displacementScale = T.displacementScale, M.displacementBias = T.displacementBias, M.wireframeLinewidth = T.wireframeLinewidth, M.linewidth = T.linewidth, R.isPointLight === !0 && M.isMeshDistanceMaterial === !0) {
      const U = a.properties.get(M);
      U.light = R;
    }
    return M;
  }
  function _(w, T, R, b, M) {
    if (w.visible === !1) return;
    if (w.layers.test(T.layers) && (w.isMesh || w.isLine || w.isPoints) && (w.castShadow || w.receiveShadow && M === Sn) && (!w.frustumCulled || i.intersectsObject(w))) {
      w.modelViewMatrix.multiplyMatrices(R.matrixWorldInverse, w.matrixWorld);
      const O = t.update(w), V = w.material;
      if (Array.isArray(V)) {
        const W = O.groups;
        for (let G = 0, et = W.length; G < et; G++) {
          const H = W[G], at = V[H.materialIndex];
          if (at && at.visible) {
            const pt = x(w, at, b, M);
            w.onBeforeShadow(a, w, T, R, O, pt, H), a.renderBufferDirect(R, null, O, pt, w, H), w.onAfterShadow(a, w, T, R, O, pt, H);
          }
        }
      } else if (V.visible) {
        const W = x(w, V, b, M);
        w.onBeforeShadow(a, w, T, R, O, W, null), a.renderBufferDirect(R, null, O, W, w, null), w.onAfterShadow(a, w, T, R, O, W, null);
      }
    }
    const U = w.children;
    for (let O = 0, V = U.length; O < V; O++)
      _(U[O], T, R, b, M);
  }
  function S(w) {
    w.target.removeEventListener("dispose", S);
    for (const R in h) {
      const b = h[R], M = w.target.uuid;
      M in b && (b[M].dispose(), delete b[M]);
    }
  }
}
const fE = {
  [Dh]: Fh,
  [Uh]: Nh,
  [Bh]: Oh,
  [pr]: zh,
  [Fh]: Dh,
  [Nh]: Uh,
  [Oh]: Bh,
  [zh]: pr
};
function mE(a, t) {
  function e() {
    let F = !1;
    const ht = new Qt();
    let _t = null;
    const Rt = new Qt(0, 0, 0, 0);
    return {
      setMask: function(dt) {
        _t !== dt && !F && (a.colorMask(dt, dt, dt, dt), _t = dt);
      },
      setLocked: function(dt) {
        F = dt;
      },
      setClear: function(dt, nt, Ft, qt, ge) {
        ge === !0 && (dt *= qt, nt *= qt, Ft *= qt), ht.set(dt, nt, Ft, qt), Rt.equals(ht) === !1 && (a.clearColor(dt, nt, Ft, qt), Rt.copy(ht));
      },
      reset: function() {
        F = !1, _t = null, Rt.set(-1, 0, 0, 0);
      }
    };
  }
  function i() {
    let F = !1, ht = !1, _t = null, Rt = null, dt = null;
    return {
      setReversed: function(nt) {
        if (ht !== nt) {
          const Ft = t.get("EXT_clip_control");
          nt ? Ft.clipControlEXT(Ft.LOWER_LEFT_EXT, Ft.ZERO_TO_ONE_EXT) : Ft.clipControlEXT(Ft.LOWER_LEFT_EXT, Ft.NEGATIVE_ONE_TO_ONE_EXT), ht = nt;
          const qt = dt;
          dt = null, this.setClear(qt);
        }
      },
      getReversed: function() {
        return ht;
      },
      setTest: function(nt) {
        nt ? st(a.DEPTH_TEST) : Et(a.DEPTH_TEST);
      },
      setMask: function(nt) {
        _t !== nt && !F && (a.depthMask(nt), _t = nt);
      },
      setFunc: function(nt) {
        if (ht && (nt = fE[nt]), Rt !== nt) {
          switch (nt) {
            case Dh:
              a.depthFunc(a.NEVER);
              break;
            case Fh:
              a.depthFunc(a.ALWAYS);
              break;
            case Uh:
              a.depthFunc(a.LESS);
              break;
            case pr:
              a.depthFunc(a.LEQUAL);
              break;
            case Bh:
              a.depthFunc(a.EQUAL);
              break;
            case zh:
              a.depthFunc(a.GEQUAL);
              break;
            case Nh:
              a.depthFunc(a.GREATER);
              break;
            case Oh:
              a.depthFunc(a.NOTEQUAL);
              break;
            default:
              a.depthFunc(a.LEQUAL);
          }
          Rt = nt;
        }
      },
      setLocked: function(nt) {
        F = nt;
      },
      setClear: function(nt) {
        dt !== nt && (ht && (nt = 1 - nt), a.clearDepth(nt), dt = nt);
      },
      reset: function() {
        F = !1, _t = null, Rt = null, dt = null, ht = !1;
      }
    };
  }
  function n() {
    let F = !1, ht = null, _t = null, Rt = null, dt = null, nt = null, Ft = null, qt = null, ge = null;
    return {
      setTest: function(oe) {
        F || (oe ? st(a.STENCIL_TEST) : Et(a.STENCIL_TEST));
      },
      setMask: function(oe) {
        ht !== oe && !F && (a.stencilMask(oe), ht = oe);
      },
      setFunc: function(oe, In, gn) {
        (_t !== oe || Rt !== In || dt !== gn) && (a.stencilFunc(oe, In, gn), _t = oe, Rt = In, dt = gn);
      },
      setOp: function(oe, In, gn) {
        (nt !== oe || Ft !== In || qt !== gn) && (a.stencilOp(oe, In, gn), nt = oe, Ft = In, qt = gn);
      },
      setLocked: function(oe) {
        F = oe;
      },
      setClear: function(oe) {
        ge !== oe && (a.clearStencil(oe), ge = oe);
      },
      reset: function() {
        F = !1, ht = null, _t = null, Rt = null, dt = null, nt = null, Ft = null, qt = null, ge = null;
      }
    };
  }
  const s = new e(), r = new i(), o = new n(), l = /* @__PURE__ */ new WeakMap(), h = /* @__PURE__ */ new WeakMap();
  let c = {}, u = {}, d = /* @__PURE__ */ new WeakMap(), p = [], f = null, y = !1, g = null, m = null, v = null, x = null, _ = null, S = null, w = null, T = new ct(0, 0, 0), R = 0, b = !1, M = null, L = null, U = null, O = null, V = null;
  const W = a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  let G = !1, et = 0;
  const H = a.getParameter(a.VERSION);
  H.indexOf("WebGL") !== -1 ? (et = parseFloat(/^WebGL (\d)/.exec(H)[1]), G = et >= 1) : H.indexOf("OpenGL ES") !== -1 && (et = parseFloat(/^OpenGL ES (\d)/.exec(H)[1]), G = et >= 2);
  let at = null, pt = {};
  const Mt = a.getParameter(a.SCISSOR_BOX), Lt = a.getParameter(a.VIEWPORT), jt = new Qt().fromArray(Mt), ne = new Qt().fromArray(Lt);
  function Jt(F, ht, _t, Rt) {
    const dt = new Uint8Array(4), nt = a.createTexture();
    a.bindTexture(F, nt), a.texParameteri(F, a.TEXTURE_MIN_FILTER, a.NEAREST), a.texParameteri(F, a.TEXTURE_MAG_FILTER, a.NEAREST);
    for (let Ft = 0; Ft < _t; Ft++)
      F === a.TEXTURE_3D || F === a.TEXTURE_2D_ARRAY ? a.texImage3D(ht, 0, a.RGBA, 1, 1, Rt, 0, a.RGBA, a.UNSIGNED_BYTE, dt) : a.texImage2D(ht + Ft, 0, a.RGBA, 1, 1, 0, a.RGBA, a.UNSIGNED_BYTE, dt);
    return nt;
  }
  const Y = {};
  Y[a.TEXTURE_2D] = Jt(a.TEXTURE_2D, a.TEXTURE_2D, 1), Y[a.TEXTURE_CUBE_MAP] = Jt(a.TEXTURE_CUBE_MAP, a.TEXTURE_CUBE_MAP_POSITIVE_X, 6), Y[a.TEXTURE_2D_ARRAY] = Jt(a.TEXTURE_2D_ARRAY, a.TEXTURE_2D_ARRAY, 1, 1), Y[a.TEXTURE_3D] = Jt(a.TEXTURE_3D, a.TEXTURE_3D, 1, 1), s.setClear(0, 0, 0, 1), r.setClear(1), o.setClear(0), st(a.DEPTH_TEST), r.setFunc(pr), Q(!1), K(Yd), st(a.CULL_FACE), ot(Yn);
  function st(F) {
    c[F] !== !0 && (a.enable(F), c[F] = !0);
  }
  function Et(F) {
    c[F] !== !1 && (a.disable(F), c[F] = !1);
  }
  function Ut(F, ht) {
    return u[F] !== ht ? (a.bindFramebuffer(F, ht), u[F] = ht, F === a.DRAW_FRAMEBUFFER && (u[a.FRAMEBUFFER] = ht), F === a.FRAMEBUFFER && (u[a.DRAW_FRAMEBUFFER] = ht), !0) : !1;
  }
  function Pt(F, ht) {
    let _t = p, Rt = !1;
    if (F) {
      _t = d.get(ht), _t === void 0 && (_t = [], d.set(ht, _t));
      const dt = F.textures;
      if (_t.length !== dt.length || _t[0] !== a.COLOR_ATTACHMENT0) {
        for (let nt = 0, Ft = dt.length; nt < Ft; nt++)
          _t[nt] = a.COLOR_ATTACHMENT0 + nt;
        _t.length = dt.length, Rt = !0;
      }
    } else
      _t[0] !== a.BACK && (_t[0] = a.BACK, Rt = !0);
    Rt && a.drawBuffers(_t);
  }
  function Kt(F) {
    return f !== F ? (a.useProgram(F), f = F, !0) : !1;
  }
  const he = {
    [vs]: a.FUNC_ADD,
    [C0]: a.FUNC_SUBTRACT,
    [R0]: a.FUNC_REVERSE_SUBTRACT
  };
  he[P0] = a.MIN, he[I0] = a.MAX;
  const D = {
    [L0]: a.ZERO,
    [D0]: a.ONE,
    [F0]: a.SRC_COLOR,
    [Ih]: a.SRC_ALPHA,
    [k0]: a.SRC_ALPHA_SATURATE,
    [N0]: a.DST_COLOR,
    [B0]: a.DST_ALPHA,
    [U0]: a.ONE_MINUS_SRC_COLOR,
    [Lh]: a.ONE_MINUS_SRC_ALPHA,
    [O0]: a.ONE_MINUS_DST_COLOR,
    [z0]: a.ONE_MINUS_DST_ALPHA,
    [V0]: a.CONSTANT_COLOR,
    [H0]: a.ONE_MINUS_CONSTANT_COLOR,
    [G0]: a.CONSTANT_ALPHA,
    [W0]: a.ONE_MINUS_CONSTANT_ALPHA
  };
  function ot(F, ht, _t, Rt, dt, nt, Ft, qt, ge, oe) {
    if (F === Yn) {
      y === !0 && (Et(a.BLEND), y = !1);
      return;
    }
    if (y === !1 && (st(a.BLEND), y = !0), F !== T0) {
      if (F !== g || oe !== b) {
        if ((m !== vs || _ !== vs) && (a.blendEquation(a.FUNC_ADD), m = vs, _ = vs), oe)
          switch (F) {
            case ws:
              a.blendFuncSeparate(a.ONE, a.ONE_MINUS_SRC_ALPHA, a.ONE, a.ONE_MINUS_SRC_ALPHA);
              break;
            case Zd:
              a.blendFunc(a.ONE, a.ONE);
              break;
            case jd:
              a.blendFuncSeparate(a.ZERO, a.ONE_MINUS_SRC_COLOR, a.ZERO, a.ONE);
              break;
            case Jd:
              a.blendFuncSeparate(a.DST_COLOR, a.ONE_MINUS_SRC_ALPHA, a.ZERO, a.ONE);
              break;
            default:
              console.error("THREE.WebGLState: Invalid blending: ", F);
              break;
          }
        else
          switch (F) {
            case ws:
              a.blendFuncSeparate(a.SRC_ALPHA, a.ONE_MINUS_SRC_ALPHA, a.ONE, a.ONE_MINUS_SRC_ALPHA);
              break;
            case Zd:
              a.blendFuncSeparate(a.SRC_ALPHA, a.ONE, a.ONE, a.ONE);
              break;
            case jd:
              console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");
              break;
            case Jd:
              console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");
              break;
            default:
              console.error("THREE.WebGLState: Invalid blending: ", F);
              break;
          }
        v = null, x = null, S = null, w = null, T.set(0, 0, 0), R = 0, g = F, b = oe;
      }
      return;
    }
    dt = dt || ht, nt = nt || _t, Ft = Ft || Rt, (ht !== m || dt !== _) && (a.blendEquationSeparate(he[ht], he[dt]), m = ht, _ = dt), (_t !== v || Rt !== x || nt !== S || Ft !== w) && (a.blendFuncSeparate(D[_t], D[Rt], D[nt], D[Ft]), v = _t, x = Rt, S = nt, w = Ft), (qt.equals(T) === !1 || ge !== R) && (a.blendColor(qt.r, qt.g, qt.b, ge), T.copy(qt), R = ge), g = F, b = !1;
  }
  function it(F, ht) {
    F.side === Mi ? Et(a.CULL_FACE) : st(a.CULL_FACE);
    let _t = F.side === He;
    ht && (_t = !_t), Q(_t), F.blending === ws && F.transparent === !1 ? ot(Yn) : ot(F.blending, F.blendEquation, F.blendSrc, F.blendDst, F.blendEquationAlpha, F.blendSrcAlpha, F.blendDstAlpha, F.blendColor, F.blendAlpha, F.premultipliedAlpha), r.setFunc(F.depthFunc), r.setTest(F.depthTest), r.setMask(F.depthWrite), s.setMask(F.colorWrite);
    const Rt = F.stencilWrite;
    o.setTest(Rt), Rt && (o.setMask(F.stencilWriteMask), o.setFunc(F.stencilFunc, F.stencilRef, F.stencilFuncMask), o.setOp(F.stencilFail, F.stencilZFail, F.stencilZPass)), ut(F.polygonOffset, F.polygonOffsetFactor, F.polygonOffsetUnits), F.alphaToCoverage === !0 ? st(a.SAMPLE_ALPHA_TO_COVERAGE) : Et(a.SAMPLE_ALPHA_TO_COVERAGE);
  }
  function Q(F) {
    M !== F && (F ? a.frontFace(a.CW) : a.frontFace(a.CCW), M = F);
  }
  function K(F) {
    F !== w0 ? (st(a.CULL_FACE), F !== L && (F === Yd ? a.cullFace(a.BACK) : F === A0 ? a.cullFace(a.FRONT) : a.cullFace(a.FRONT_AND_BACK))) : Et(a.CULL_FACE), L = F;
  }
  function yt(F) {
    F !== U && (G && a.lineWidth(F), U = F);
  }
  function ut(F, ht, _t) {
    F ? (st(a.POLYGON_OFFSET_FILL), (O !== ht || V !== _t) && (a.polygonOffset(ht, _t), O = ht, V = _t)) : Et(a.POLYGON_OFFSET_FILL);
  }
  function xt(F) {
    F ? st(a.SCISSOR_TEST) : Et(a.SCISSOR_TEST);
  }
  function Wt(F) {
    F === void 0 && (F = a.TEXTURE0 + W - 1), at !== F && (a.activeTexture(F), at = F);
  }
  function Nt(F, ht, _t) {
    _t === void 0 && (at === null ? _t = a.TEXTURE0 + W - 1 : _t = at);
    let Rt = pt[_t];
    Rt === void 0 && (Rt = { type: void 0, texture: void 0 }, pt[_t] = Rt), (Rt.type !== F || Rt.texture !== ht) && (at !== _t && (a.activeTexture(_t), at = _t), a.bindTexture(F, ht || Y[F]), Rt.type = F, Rt.texture = ht);
  }
  function P() {
    const F = pt[at];
    F !== void 0 && F.type !== void 0 && (a.bindTexture(F.type, null), F.type = void 0, F.texture = void 0);
  }
  function A() {
    try {
      a.compressedTexImage2D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function N() {
    try {
      a.compressedTexImage3D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function X() {
    try {
      a.texSubImage2D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function rt() {
    try {
      a.texSubImage3D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function Z() {
    try {
      a.compressedTexSubImage2D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function It() {
    try {
      a.compressedTexSubImage3D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function I() {
    try {
      a.texStorage2D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function lt() {
    try {
      a.texStorage3D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function gt() {
    try {
      a.texImage2D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function j() {
    try {
      a.texImage3D(...arguments);
    } catch (F) {
      console.error("THREE.WebGLState:", F);
    }
  }
  function mt(F) {
    jt.equals(F) === !1 && (a.scissor(F.x, F.y, F.z, F.w), jt.copy(F));
  }
  function At(F) {
    ne.equals(F) === !1 && (a.viewport(F.x, F.y, F.z, F.w), ne.copy(F));
  }
  function Tt(F, ht) {
    let _t = h.get(ht);
    _t === void 0 && (_t = /* @__PURE__ */ new WeakMap(), h.set(ht, _t));
    let Rt = _t.get(F);
    Rt === void 0 && (Rt = a.getUniformBlockIndex(ht, F.name), _t.set(F, Rt));
  }
  function vt(F, ht) {
    const Rt = h.get(ht).get(F);
    l.get(ht) !== Rt && (a.uniformBlockBinding(ht, Rt, F.__bindingPointIndex), l.set(ht, Rt));
  }
  function $t() {
    a.disable(a.BLEND), a.disable(a.CULL_FACE), a.disable(a.DEPTH_TEST), a.disable(a.POLYGON_OFFSET_FILL), a.disable(a.SCISSOR_TEST), a.disable(a.STENCIL_TEST), a.disable(a.SAMPLE_ALPHA_TO_COVERAGE), a.blendEquation(a.FUNC_ADD), a.blendFunc(a.ONE, a.ZERO), a.blendFuncSeparate(a.ONE, a.ZERO, a.ONE, a.ZERO), a.blendColor(0, 0, 0, 0), a.colorMask(!0, !0, !0, !0), a.clearColor(0, 0, 0, 0), a.depthMask(!0), a.depthFunc(a.LESS), r.setReversed(!1), a.clearDepth(1), a.stencilMask(4294967295), a.stencilFunc(a.ALWAYS, 0, 4294967295), a.stencilOp(a.KEEP, a.KEEP, a.KEEP), a.clearStencil(0), a.cullFace(a.BACK), a.frontFace(a.CCW), a.polygonOffset(0, 0), a.activeTexture(a.TEXTURE0), a.bindFramebuffer(a.FRAMEBUFFER, null), a.bindFramebuffer(a.DRAW_FRAMEBUFFER, null), a.bindFramebuffer(a.READ_FRAMEBUFFER, null), a.useProgram(null), a.lineWidth(1), a.scissor(0, 0, a.canvas.width, a.canvas.height), a.viewport(0, 0, a.canvas.width, a.canvas.height), c = {}, at = null, pt = {}, u = {}, d = /* @__PURE__ */ new WeakMap(), p = [], f = null, y = !1, g = null, m = null, v = null, x = null, _ = null, S = null, w = null, T = new ct(0, 0, 0), R = 0, b = !1, M = null, L = null, U = null, O = null, V = null, jt.set(0, 0, a.canvas.width, a.canvas.height), ne.set(0, 0, a.canvas.width, a.canvas.height), s.reset(), r.reset(), o.reset();
  }
  return {
    buffers: {
      color: s,
      depth: r,
      stencil: o
    },
    enable: st,
    disable: Et,
    bindFramebuffer: Ut,
    drawBuffers: Pt,
    useProgram: Kt,
    setBlending: ot,
    setMaterial: it,
    setFlipSided: Q,
    setCullFace: K,
    setLineWidth: yt,
    setPolygonOffset: ut,
    setScissorTest: xt,
    activeTexture: Wt,
    bindTexture: Nt,
    unbindTexture: P,
    compressedTexImage2D: A,
    compressedTexImage3D: N,
    texImage2D: gt,
    texImage3D: j,
    updateUBOMapping: Tt,
    uniformBlockBinding: vt,
    texStorage2D: I,
    texStorage3D: lt,
    texSubImage2D: X,
    texSubImage3D: rt,
    compressedTexSubImage2D: Z,
    compressedTexSubImage3D: It,
    scissor: mt,
    viewport: At,
    reset: $t
  };
}
function gE(a, t, e, i, n, s, r) {
  const o = t.has("WEBGL_multisampled_render_to_texture") ? t.get("WEBGL_multisampled_render_to_texture") : null, l = typeof navigator > "u" ? !1 : /OculusBrowser/g.test(navigator.userAgent), h = new J(), c = /* @__PURE__ */ new WeakMap();
  let u;
  const d = /* @__PURE__ */ new WeakMap();
  let p = !1;
  try {
    p = typeof OffscreenCanvas < "u" && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  } catch {
  }
  function f(P, A) {
    return p ? (
      // eslint-disable-next-line compat/compat
      new OffscreenCanvas(P, A)
    ) : Ro("canvas");
  }
  function y(P, A, N) {
    let X = 1;
    const rt = Nt(P);
    if ((rt.width > N || rt.height > N) && (X = N / Math.max(rt.width, rt.height)), X < 1)
      if (typeof HTMLImageElement < "u" && P instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && P instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && P instanceof ImageBitmap || typeof VideoFrame < "u" && P instanceof VideoFrame) {
        const Z = Math.floor(X * rt.width), It = Math.floor(X * rt.height);
        u === void 0 && (u = f(Z, It));
        const I = A ? f(Z, It) : u;
        return I.width = Z, I.height = It, I.getContext("2d").drawImage(P, 0, 0, Z, It), console.warn("THREE.WebGLRenderer: Texture has been resized from (" + rt.width + "x" + rt.height + ") to (" + Z + "x" + It + ")."), I;
      } else
        return "data" in P && console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + rt.width + "x" + rt.height + ")."), P;
    return P;
  }
  function g(P) {
    return P.generateMipmaps;
  }
  function m(P) {
    a.generateMipmap(P);
  }
  function v(P) {
    return P.isWebGLCubeRenderTarget ? a.TEXTURE_CUBE_MAP : P.isWebGL3DRenderTarget ? a.TEXTURE_3D : P.isWebGLArrayRenderTarget || P.isCompressedArrayTexture ? a.TEXTURE_2D_ARRAY : a.TEXTURE_2D;
  }
  function x(P, A, N, X, rt = !1) {
    if (P !== null) {
      if (a[P] !== void 0) return a[P];
      console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + P + "'");
    }
    let Z = A;
    if (A === a.RED && (N === a.FLOAT && (Z = a.R32F), N === a.HALF_FLOAT && (Z = a.R16F), N === a.UNSIGNED_BYTE && (Z = a.R8)), A === a.RED_INTEGER && (N === a.UNSIGNED_BYTE && (Z = a.R8UI), N === a.UNSIGNED_SHORT && (Z = a.R16UI), N === a.UNSIGNED_INT && (Z = a.R32UI), N === a.BYTE && (Z = a.R8I), N === a.SHORT && (Z = a.R16I), N === a.INT && (Z = a.R32I)), A === a.RG && (N === a.FLOAT && (Z = a.RG32F), N === a.HALF_FLOAT && (Z = a.RG16F), N === a.UNSIGNED_BYTE && (Z = a.RG8)), A === a.RG_INTEGER && (N === a.UNSIGNED_BYTE && (Z = a.RG8UI), N === a.UNSIGNED_SHORT && (Z = a.RG16UI), N === a.UNSIGNED_INT && (Z = a.RG32UI), N === a.BYTE && (Z = a.RG8I), N === a.SHORT && (Z = a.RG16I), N === a.INT && (Z = a.RG32I)), A === a.RGB_INTEGER && (N === a.UNSIGNED_BYTE && (Z = a.RGB8UI), N === a.UNSIGNED_SHORT && (Z = a.RGB16UI), N === a.UNSIGNED_INT && (Z = a.RGB32UI), N === a.BYTE && (Z = a.RGB8I), N === a.SHORT && (Z = a.RGB16I), N === a.INT && (Z = a.RGB32I)), A === a.RGBA_INTEGER && (N === a.UNSIGNED_BYTE && (Z = a.RGBA8UI), N === a.UNSIGNED_SHORT && (Z = a.RGBA16UI), N === a.UNSIGNED_INT && (Z = a.RGBA32UI), N === a.BYTE && (Z = a.RGBA8I), N === a.SHORT && (Z = a.RGBA16I), N === a.INT && (Z = a.RGBA32I)), A === a.RGB && (N === a.UNSIGNED_INT_5_9_9_9_REV && (Z = a.RGB9_E5), N === a.UNSIGNED_INT_10F_11F_11F_REV && (Z = a.R11F_G11F_B10F)), A === a.RGBA) {
      const It = rt ? Eo : ee.getTransfer(X);
      N === a.FLOAT && (Z = a.RGBA32F), N === a.HALF_FLOAT && (Z = a.RGBA16F), N === a.UNSIGNED_BYTE && (Z = It === ce ? a.SRGB8_ALPHA8 : a.RGBA8), N === a.UNSIGNED_SHORT_4_4_4_4 && (Z = a.RGBA4), N === a.UNSIGNED_SHORT_5_5_5_1 && (Z = a.RGB5_A1);
    }
    return (Z === a.R16F || Z === a.R32F || Z === a.RG16F || Z === a.RG32F || Z === a.RGBA16F || Z === a.RGBA32F) && t.get("EXT_color_buffer_float"), Z;
  }
  function _(P, A) {
    let N;
    return P ? A === null || A === ns || A === pa ? N = a.DEPTH24_STENCIL8 : A === wi ? N = a.DEPTH32F_STENCIL8 : A === da && (N = a.DEPTH24_STENCIL8, console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")) : A === null || A === ns || A === pa ? N = a.DEPTH_COMPONENT24 : A === wi ? N = a.DEPTH_COMPONENT32F : A === da && (N = a.DEPTH_COMPONENT16), N;
  }
  function S(P, A) {
    return g(P) === !0 || P.isFramebufferTexture && P.minFilter !== je && P.minFilter !== Ce ? Math.log2(Math.max(A.width, A.height)) + 1 : P.mipmaps !== void 0 && P.mipmaps.length > 0 ? P.mipmaps.length : P.isCompressedTexture && Array.isArray(P.image) ? A.mipmaps.length : 1;
  }
  function w(P) {
    const A = P.target;
    A.removeEventListener("dispose", w), R(A), A.isVideoTexture && c.delete(A);
  }
  function T(P) {
    const A = P.target;
    A.removeEventListener("dispose", T), M(A);
  }
  function R(P) {
    const A = i.get(P);
    if (A.__webglInit === void 0) return;
    const N = P.source, X = d.get(N);
    if (X) {
      const rt = X[A.__cacheKey];
      rt.usedTimes--, rt.usedTimes === 0 && b(P), Object.keys(X).length === 0 && d.delete(N);
    }
    i.remove(P);
  }
  function b(P) {
    const A = i.get(P);
    a.deleteTexture(A.__webglTexture);
    const N = P.source, X = d.get(N);
    delete X[A.__cacheKey], r.memory.textures--;
  }
  function M(P) {
    const A = i.get(P);
    if (P.depthTexture && (P.depthTexture.dispose(), i.remove(P.depthTexture)), P.isWebGLCubeRenderTarget)
      for (let X = 0; X < 6; X++) {
        if (Array.isArray(A.__webglFramebuffer[X]))
          for (let rt = 0; rt < A.__webglFramebuffer[X].length; rt++) a.deleteFramebuffer(A.__webglFramebuffer[X][rt]);
        else
          a.deleteFramebuffer(A.__webglFramebuffer[X]);
        A.__webglDepthbuffer && a.deleteRenderbuffer(A.__webglDepthbuffer[X]);
      }
    else {
      if (Array.isArray(A.__webglFramebuffer))
        for (let X = 0; X < A.__webglFramebuffer.length; X++) a.deleteFramebuffer(A.__webglFramebuffer[X]);
      else
        a.deleteFramebuffer(A.__webglFramebuffer);
      if (A.__webglDepthbuffer && a.deleteRenderbuffer(A.__webglDepthbuffer), A.__webglMultisampledFramebuffer && a.deleteFramebuffer(A.__webglMultisampledFramebuffer), A.__webglColorRenderbuffer)
        for (let X = 0; X < A.__webglColorRenderbuffer.length; X++)
          A.__webglColorRenderbuffer[X] && a.deleteRenderbuffer(A.__webglColorRenderbuffer[X]);
      A.__webglDepthRenderbuffer && a.deleteRenderbuffer(A.__webglDepthRenderbuffer);
    }
    const N = P.textures;
    for (let X = 0, rt = N.length; X < rt; X++) {
      const Z = i.get(N[X]);
      Z.__webglTexture && (a.deleteTexture(Z.__webglTexture), r.memory.textures--), i.remove(N[X]);
    }
    i.remove(P);
  }
  let L = 0;
  function U() {
    L = 0;
  }
  function O() {
    const P = L;
    return P >= n.maxTextures && console.warn("THREE.WebGLTextures: Trying to use " + P + " texture units while this GPU supports only " + n.maxTextures), L += 1, P;
  }
  function V(P) {
    const A = [];
    return A.push(P.wrapS), A.push(P.wrapT), A.push(P.wrapR || 0), A.push(P.magFilter), A.push(P.minFilter), A.push(P.anisotropy), A.push(P.internalFormat), A.push(P.format), A.push(P.type), A.push(P.generateMipmaps), A.push(P.premultiplyAlpha), A.push(P.flipY), A.push(P.unpackAlignment), A.push(P.colorSpace), A.join();
  }
  function W(P, A) {
    const N = i.get(P);
    if (P.isVideoTexture && xt(P), P.isRenderTargetTexture === !1 && P.isExternalTexture !== !0 && P.version > 0 && N.__version !== P.version) {
      const X = P.image;
      if (X === null)
        console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");
      else if (X.complete === !1)
        console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");
      else {
        Y(N, P, A);
        return;
      }
    } else P.isExternalTexture && (N.__webglTexture = P.sourceTexture ? P.sourceTexture : null);
    e.bindTexture(a.TEXTURE_2D, N.__webglTexture, a.TEXTURE0 + A);
  }
  function G(P, A) {
    const N = i.get(P);
    if (P.isRenderTargetTexture === !1 && P.version > 0 && N.__version !== P.version) {
      Y(N, P, A);
      return;
    }
    e.bindTexture(a.TEXTURE_2D_ARRAY, N.__webglTexture, a.TEXTURE0 + A);
  }
  function et(P, A) {
    const N = i.get(P);
    if (P.isRenderTargetTexture === !1 && P.version > 0 && N.__version !== P.version) {
      Y(N, P, A);
      return;
    }
    e.bindTexture(a.TEXTURE_3D, N.__webglTexture, a.TEXTURE0 + A);
  }
  function H(P, A) {
    const N = i.get(P);
    if (P.version > 0 && N.__version !== P.version) {
      st(N, P, A);
      return;
    }
    e.bindTexture(a.TEXTURE_CUBE_MAP, N.__webglTexture, a.TEXTURE0 + A);
  }
  const at = {
    [Mo]: a.REPEAT,
    [Si]: a.CLAMP_TO_EDGE,
    [So]: a.MIRRORED_REPEAT
  }, pt = {
    [je]: a.NEAREST,
    [Sp]: a.NEAREST_MIPMAP_NEAREST,
    [sa]: a.NEAREST_MIPMAP_LINEAR,
    [Ce]: a.LINEAR,
    [lo]: a.LINEAR_MIPMAP_NEAREST,
    [En]: a.LINEAR_MIPMAP_LINEAR
  }, Mt = {
    [ay]: a.NEVER,
    [dy]: a.ALWAYS,
    [oy]: a.LESS,
    [Fp]: a.LEQUAL,
    [ly]: a.EQUAL,
    [uy]: a.GEQUAL,
    [hy]: a.GREATER,
    [cy]: a.NOTEQUAL
  };
  function Lt(P, A) {
    if (A.type === wi && t.has("OES_texture_float_linear") === !1 && (A.magFilter === Ce || A.magFilter === lo || A.magFilter === sa || A.magFilter === En || A.minFilter === Ce || A.minFilter === lo || A.minFilter === sa || A.minFilter === En) && console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."), a.texParameteri(P, a.TEXTURE_WRAP_S, at[A.wrapS]), a.texParameteri(P, a.TEXTURE_WRAP_T, at[A.wrapT]), (P === a.TEXTURE_3D || P === a.TEXTURE_2D_ARRAY) && a.texParameteri(P, a.TEXTURE_WRAP_R, at[A.wrapR]), a.texParameteri(P, a.TEXTURE_MAG_FILTER, pt[A.magFilter]), a.texParameteri(P, a.TEXTURE_MIN_FILTER, pt[A.minFilter]), A.compareFunction && (a.texParameteri(P, a.TEXTURE_COMPARE_MODE, a.COMPARE_REF_TO_TEXTURE), a.texParameteri(P, a.TEXTURE_COMPARE_FUNC, Mt[A.compareFunction])), t.has("EXT_texture_filter_anisotropic") === !0) {
      if (A.magFilter === je || A.minFilter !== sa && A.minFilter !== En || A.type === wi && t.has("OES_texture_float_linear") === !1) return;
      if (A.anisotropy > 1 || i.get(A).__currentAnisotropy) {
        const N = t.get("EXT_texture_filter_anisotropic");
        a.texParameterf(P, N.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(A.anisotropy, n.getMaxAnisotropy())), i.get(A).__currentAnisotropy = A.anisotropy;
      }
    }
  }
  function jt(P, A) {
    let N = !1;
    P.__webglInit === void 0 && (P.__webglInit = !0, A.addEventListener("dispose", w));
    const X = A.source;
    let rt = d.get(X);
    rt === void 0 && (rt = {}, d.set(X, rt));
    const Z = V(A);
    if (Z !== P.__cacheKey) {
      rt[Z] === void 0 && (rt[Z] = {
        texture: a.createTexture(),
        usedTimes: 0
      }, r.memory.textures++, N = !0), rt[Z].usedTimes++;
      const It = rt[P.__cacheKey];
      It !== void 0 && (rt[P.__cacheKey].usedTimes--, It.usedTimes === 0 && b(A)), P.__cacheKey = Z, P.__webglTexture = rt[Z].texture;
    }
    return N;
  }
  function ne(P, A, N) {
    return Math.floor(Math.floor(P / N) / A);
  }
  function Jt(P, A, N, X) {
    const Z = P.updateRanges;
    if (Z.length === 0)
      e.texSubImage2D(a.TEXTURE_2D, 0, 0, 0, A.width, A.height, N, X, A.data);
    else {
      Z.sort((j, mt) => j.start - mt.start);
      let It = 0;
      for (let j = 1; j < Z.length; j++) {
        const mt = Z[It], At = Z[j], Tt = mt.start + mt.count, vt = ne(At.start, A.width, 4), $t = ne(mt.start, A.width, 4);
        At.start <= Tt + 1 && vt === $t && ne(At.start + At.count - 1, A.width, 4) === vt ? mt.count = Math.max(
          mt.count,
          At.start + At.count - mt.start
        ) : (++It, Z[It] = At);
      }
      Z.length = It + 1;
      const I = a.getParameter(a.UNPACK_ROW_LENGTH), lt = a.getParameter(a.UNPACK_SKIP_PIXELS), gt = a.getParameter(a.UNPACK_SKIP_ROWS);
      a.pixelStorei(a.UNPACK_ROW_LENGTH, A.width);
      for (let j = 0, mt = Z.length; j < mt; j++) {
        const At = Z[j], Tt = Math.floor(At.start / 4), vt = Math.ceil(At.count / 4), $t = Tt % A.width, F = Math.floor(Tt / A.width), ht = vt, _t = 1;
        a.pixelStorei(a.UNPACK_SKIP_PIXELS, $t), a.pixelStorei(a.UNPACK_SKIP_ROWS, F), e.texSubImage2D(a.TEXTURE_2D, 0, $t, F, ht, _t, N, X, A.data);
      }
      P.clearUpdateRanges(), a.pixelStorei(a.UNPACK_ROW_LENGTH, I), a.pixelStorei(a.UNPACK_SKIP_PIXELS, lt), a.pixelStorei(a.UNPACK_SKIP_ROWS, gt);
    }
  }
  function Y(P, A, N) {
    let X = a.TEXTURE_2D;
    (A.isDataArrayTexture || A.isCompressedArrayTexture) && (X = a.TEXTURE_2D_ARRAY), A.isData3DTexture && (X = a.TEXTURE_3D);
    const rt = jt(P, A), Z = A.source;
    e.bindTexture(X, P.__webglTexture, a.TEXTURE0 + N);
    const It = i.get(Z);
    if (Z.version !== It.__version || rt === !0) {
      e.activeTexture(a.TEXTURE0 + N);
      const I = ee.getPrimaries(ee.workingColorSpace), lt = A.colorSpace === $n ? null : ee.getPrimaries(A.colorSpace), gt = A.colorSpace === $n || I === lt ? a.NONE : a.BROWSER_DEFAULT_WEBGL;
      a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL, A.flipY), a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL, A.premultiplyAlpha), a.pixelStorei(a.UNPACK_ALIGNMENT, A.unpackAlignment), a.pixelStorei(a.UNPACK_COLORSPACE_CONVERSION_WEBGL, gt);
      let j = y(A.image, !1, n.maxTextureSize);
      j = Wt(A, j);
      const mt = s.convert(A.format, A.colorSpace), At = s.convert(A.type);
      let Tt = x(A.internalFormat, mt, At, A.colorSpace, A.isVideoTexture);
      Lt(X, A);
      let vt;
      const $t = A.mipmaps, F = A.isVideoTexture !== !0, ht = It.__version === void 0 || rt === !0, _t = Z.dataReady, Rt = S(A, j);
      if (A.isDepthTexture)
        Tt = _(A.format === ma, A.type), ht && (F ? e.texStorage2D(a.TEXTURE_2D, 1, Tt, j.width, j.height) : e.texImage2D(a.TEXTURE_2D, 0, Tt, j.width, j.height, 0, mt, At, null));
      else if (A.isDataTexture)
        if ($t.length > 0) {
          F && ht && e.texStorage2D(a.TEXTURE_2D, Rt, Tt, $t[0].width, $t[0].height);
          for (let dt = 0, nt = $t.length; dt < nt; dt++)
            vt = $t[dt], F ? _t && e.texSubImage2D(a.TEXTURE_2D, dt, 0, 0, vt.width, vt.height, mt, At, vt.data) : e.texImage2D(a.TEXTURE_2D, dt, Tt, vt.width, vt.height, 0, mt, At, vt.data);
          A.generateMipmaps = !1;
        } else
          F ? (ht && e.texStorage2D(a.TEXTURE_2D, Rt, Tt, j.width, j.height), _t && Jt(A, j, mt, At)) : e.texImage2D(a.TEXTURE_2D, 0, Tt, j.width, j.height, 0, mt, At, j.data);
      else if (A.isCompressedTexture)
        if (A.isCompressedArrayTexture) {
          F && ht && e.texStorage3D(a.TEXTURE_2D_ARRAY, Rt, Tt, $t[0].width, $t[0].height, j.depth);
          for (let dt = 0, nt = $t.length; dt < nt; dt++)
            if (vt = $t[dt], A.format !== gi)
              if (mt !== null)
                if (F) {
                  if (_t)
                    if (A.layerUpdates.size > 0) {
                      const Ft = lp(vt.width, vt.height, A.format, A.type);
                      for (const qt of A.layerUpdates) {
                        const ge = vt.data.subarray(
                          qt * Ft / vt.data.BYTES_PER_ELEMENT,
                          (qt + 1) * Ft / vt.data.BYTES_PER_ELEMENT
                        );
                        e.compressedTexSubImage3D(a.TEXTURE_2D_ARRAY, dt, 0, 0, qt, vt.width, vt.height, 1, mt, ge);
                      }
                      A.clearLayerUpdates();
                    } else
                      e.compressedTexSubImage3D(a.TEXTURE_2D_ARRAY, dt, 0, 0, 0, vt.width, vt.height, j.depth, mt, vt.data);
                } else
                  e.compressedTexImage3D(a.TEXTURE_2D_ARRAY, dt, Tt, vt.width, vt.height, j.depth, 0, vt.data, 0, 0);
              else
                console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");
            else
              F ? _t && e.texSubImage3D(a.TEXTURE_2D_ARRAY, dt, 0, 0, 0, vt.width, vt.height, j.depth, mt, At, vt.data) : e.texImage3D(a.TEXTURE_2D_ARRAY, dt, Tt, vt.width, vt.height, j.depth, 0, mt, At, vt.data);
        } else {
          F && ht && e.texStorage2D(a.TEXTURE_2D, Rt, Tt, $t[0].width, $t[0].height);
          for (let dt = 0, nt = $t.length; dt < nt; dt++)
            vt = $t[dt], A.format !== gi ? mt !== null ? F ? _t && e.compressedTexSubImage2D(a.TEXTURE_2D, dt, 0, 0, vt.width, vt.height, mt, vt.data) : e.compressedTexImage2D(a.TEXTURE_2D, dt, Tt, vt.width, vt.height, 0, vt.data) : console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()") : F ? _t && e.texSubImage2D(a.TEXTURE_2D, dt, 0, 0, vt.width, vt.height, mt, At, vt.data) : e.texImage2D(a.TEXTURE_2D, dt, Tt, vt.width, vt.height, 0, mt, At, vt.data);
        }
      else if (A.isDataArrayTexture)
        if (F) {
          if (ht && e.texStorage3D(a.TEXTURE_2D_ARRAY, Rt, Tt, j.width, j.height, j.depth), _t)
            if (A.layerUpdates.size > 0) {
              const dt = lp(j.width, j.height, A.format, A.type);
              for (const nt of A.layerUpdates) {
                const Ft = j.data.subarray(
                  nt * dt / j.data.BYTES_PER_ELEMENT,
                  (nt + 1) * dt / j.data.BYTES_PER_ELEMENT
                );
                e.texSubImage3D(a.TEXTURE_2D_ARRAY, 0, 0, 0, nt, j.width, j.height, 1, mt, At, Ft);
              }
              A.clearLayerUpdates();
            } else
              e.texSubImage3D(a.TEXTURE_2D_ARRAY, 0, 0, 0, 0, j.width, j.height, j.depth, mt, At, j.data);
        } else
          e.texImage3D(a.TEXTURE_2D_ARRAY, 0, Tt, j.width, j.height, j.depth, 0, mt, At, j.data);
      else if (A.isData3DTexture)
        F ? (ht && e.texStorage3D(a.TEXTURE_3D, Rt, Tt, j.width, j.height, j.depth), _t && e.texSubImage3D(a.TEXTURE_3D, 0, 0, 0, 0, j.width, j.height, j.depth, mt, At, j.data)) : e.texImage3D(a.TEXTURE_3D, 0, Tt, j.width, j.height, j.depth, 0, mt, At, j.data);
      else if (A.isFramebufferTexture) {
        if (ht)
          if (F)
            e.texStorage2D(a.TEXTURE_2D, Rt, Tt, j.width, j.height);
          else {
            let dt = j.width, nt = j.height;
            for (let Ft = 0; Ft < Rt; Ft++)
              e.texImage2D(a.TEXTURE_2D, Ft, Tt, dt, nt, 0, mt, At, null), dt >>= 1, nt >>= 1;
          }
      } else if ($t.length > 0) {
        if (F && ht) {
          const dt = Nt($t[0]);
          e.texStorage2D(a.TEXTURE_2D, Rt, Tt, dt.width, dt.height);
        }
        for (let dt = 0, nt = $t.length; dt < nt; dt++)
          vt = $t[dt], F ? _t && e.texSubImage2D(a.TEXTURE_2D, dt, 0, 0, mt, At, vt) : e.texImage2D(a.TEXTURE_2D, dt, Tt, mt, At, vt);
        A.generateMipmaps = !1;
      } else if (F) {
        if (ht) {
          const dt = Nt(j);
          e.texStorage2D(a.TEXTURE_2D, Rt, Tt, dt.width, dt.height);
        }
        _t && e.texSubImage2D(a.TEXTURE_2D, 0, 0, 0, mt, At, j);
      } else
        e.texImage2D(a.TEXTURE_2D, 0, Tt, mt, At, j);
      g(A) && m(X), It.__version = Z.version, A.onUpdate && A.onUpdate(A);
    }
    P.__version = A.version;
  }
  function st(P, A, N) {
    if (A.image.length !== 6) return;
    const X = jt(P, A), rt = A.source;
    e.bindTexture(a.TEXTURE_CUBE_MAP, P.__webglTexture, a.TEXTURE0 + N);
    const Z = i.get(rt);
    if (rt.version !== Z.__version || X === !0) {
      e.activeTexture(a.TEXTURE0 + N);
      const It = ee.getPrimaries(ee.workingColorSpace), I = A.colorSpace === $n ? null : ee.getPrimaries(A.colorSpace), lt = A.colorSpace === $n || It === I ? a.NONE : a.BROWSER_DEFAULT_WEBGL;
      a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL, A.flipY), a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL, A.premultiplyAlpha), a.pixelStorei(a.UNPACK_ALIGNMENT, A.unpackAlignment), a.pixelStorei(a.UNPACK_COLORSPACE_CONVERSION_WEBGL, lt);
      const gt = A.isCompressedTexture || A.image[0].isCompressedTexture, j = A.image[0] && A.image[0].isDataTexture, mt = [];
      for (let nt = 0; nt < 6; nt++)
        !gt && !j ? mt[nt] = y(A.image[nt], !0, n.maxCubemapSize) : mt[nt] = j ? A.image[nt].image : A.image[nt], mt[nt] = Wt(A, mt[nt]);
      const At = mt[0], Tt = s.convert(A.format, A.colorSpace), vt = s.convert(A.type), $t = x(A.internalFormat, Tt, vt, A.colorSpace), F = A.isVideoTexture !== !0, ht = Z.__version === void 0 || X === !0, _t = rt.dataReady;
      let Rt = S(A, At);
      Lt(a.TEXTURE_CUBE_MAP, A);
      let dt;
      if (gt) {
        F && ht && e.texStorage2D(a.TEXTURE_CUBE_MAP, Rt, $t, At.width, At.height);
        for (let nt = 0; nt < 6; nt++) {
          dt = mt[nt].mipmaps;
          for (let Ft = 0; Ft < dt.length; Ft++) {
            const qt = dt[Ft];
            A.format !== gi ? Tt !== null ? F ? _t && e.compressedTexSubImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, Ft, 0, 0, qt.width, qt.height, Tt, qt.data) : e.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, Ft, $t, qt.width, qt.height, 0, qt.data) : console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()") : F ? _t && e.texSubImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, Ft, 0, 0, qt.width, qt.height, Tt, vt, qt.data) : e.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, Ft, $t, qt.width, qt.height, 0, Tt, vt, qt.data);
          }
        }
      } else {
        if (dt = A.mipmaps, F && ht) {
          dt.length > 0 && Rt++;
          const nt = Nt(mt[0]);
          e.texStorage2D(a.TEXTURE_CUBE_MAP, Rt, $t, nt.width, nt.height);
        }
        for (let nt = 0; nt < 6; nt++)
          if (j) {
            F ? _t && e.texSubImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, 0, 0, 0, mt[nt].width, mt[nt].height, Tt, vt, mt[nt].data) : e.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, 0, $t, mt[nt].width, mt[nt].height, 0, Tt, vt, mt[nt].data);
            for (let Ft = 0; Ft < dt.length; Ft++) {
              const ge = dt[Ft].image[nt].image;
              F ? _t && e.texSubImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, Ft + 1, 0, 0, ge.width, ge.height, Tt, vt, ge.data) : e.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, Ft + 1, $t, ge.width, ge.height, 0, Tt, vt, ge.data);
            }
          } else {
            F ? _t && e.texSubImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, 0, 0, 0, Tt, vt, mt[nt]) : e.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, 0, $t, Tt, vt, mt[nt]);
            for (let Ft = 0; Ft < dt.length; Ft++) {
              const qt = dt[Ft];
              F ? _t && e.texSubImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, Ft + 1, 0, 0, Tt, vt, qt.image[nt]) : e.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X + nt, Ft + 1, $t, Tt, vt, qt.image[nt]);
            }
          }
      }
      g(A) && m(a.TEXTURE_CUBE_MAP), Z.__version = rt.version, A.onUpdate && A.onUpdate(A);
    }
    P.__version = A.version;
  }
  function Et(P, A, N, X, rt, Z) {
    const It = s.convert(N.format, N.colorSpace), I = s.convert(N.type), lt = x(N.internalFormat, It, I, N.colorSpace), gt = i.get(A), j = i.get(N);
    if (j.__renderTarget = A, !gt.__hasExternalTextures) {
      const mt = Math.max(1, A.width >> Z), At = Math.max(1, A.height >> Z);
      rt === a.TEXTURE_3D || rt === a.TEXTURE_2D_ARRAY ? e.texImage3D(rt, Z, lt, mt, At, A.depth, 0, It, I, null) : e.texImage2D(rt, Z, lt, mt, At, 0, It, I, null);
    }
    e.bindFramebuffer(a.FRAMEBUFFER, P), ut(A) ? o.framebufferTexture2DMultisampleEXT(a.FRAMEBUFFER, X, rt, j.__webglTexture, 0, yt(A)) : (rt === a.TEXTURE_2D || rt >= a.TEXTURE_CUBE_MAP_POSITIVE_X && rt <= a.TEXTURE_CUBE_MAP_NEGATIVE_Z) && a.framebufferTexture2D(a.FRAMEBUFFER, X, rt, j.__webglTexture, Z), e.bindFramebuffer(a.FRAMEBUFFER, null);
  }
  function Ut(P, A, N) {
    if (a.bindRenderbuffer(a.RENDERBUFFER, P), A.depthBuffer) {
      const X = A.depthTexture, rt = X && X.isDepthTexture ? X.type : null, Z = _(A.stencilBuffer, rt), It = A.stencilBuffer ? a.DEPTH_STENCIL_ATTACHMENT : a.DEPTH_ATTACHMENT, I = yt(A);
      ut(A) ? o.renderbufferStorageMultisampleEXT(a.RENDERBUFFER, I, Z, A.width, A.height) : N ? a.renderbufferStorageMultisample(a.RENDERBUFFER, I, Z, A.width, A.height) : a.renderbufferStorage(a.RENDERBUFFER, Z, A.width, A.height), a.framebufferRenderbuffer(a.FRAMEBUFFER, It, a.RENDERBUFFER, P);
    } else {
      const X = A.textures;
      for (let rt = 0; rt < X.length; rt++) {
        const Z = X[rt], It = s.convert(Z.format, Z.colorSpace), I = s.convert(Z.type), lt = x(Z.internalFormat, It, I, Z.colorSpace), gt = yt(A);
        N && ut(A) === !1 ? a.renderbufferStorageMultisample(a.RENDERBUFFER, gt, lt, A.width, A.height) : ut(A) ? o.renderbufferStorageMultisampleEXT(a.RENDERBUFFER, gt, lt, A.width, A.height) : a.renderbufferStorage(a.RENDERBUFFER, lt, A.width, A.height);
      }
    }
    a.bindRenderbuffer(a.RENDERBUFFER, null);
  }
  function Pt(P, A) {
    if (A && A.isWebGLCubeRenderTarget) throw new Error("Depth Texture with cube render targets is not supported");
    if (e.bindFramebuffer(a.FRAMEBUFFER, P), !(A.depthTexture && A.depthTexture.isDepthTexture))
      throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");
    const X = i.get(A.depthTexture);
    X.__renderTarget = A, (!X.__webglTexture || A.depthTexture.image.width !== A.width || A.depthTexture.image.height !== A.height) && (A.depthTexture.image.width = A.width, A.depthTexture.image.height = A.height, A.depthTexture.needsUpdate = !0), W(A.depthTexture, 0);
    const rt = X.__webglTexture, Z = yt(A);
    if (A.depthTexture.format === fa)
      ut(A) ? o.framebufferTexture2DMultisampleEXT(a.FRAMEBUFFER, a.DEPTH_ATTACHMENT, a.TEXTURE_2D, rt, 0, Z) : a.framebufferTexture2D(a.FRAMEBUFFER, a.DEPTH_ATTACHMENT, a.TEXTURE_2D, rt, 0);
    else if (A.depthTexture.format === ma)
      ut(A) ? o.framebufferTexture2DMultisampleEXT(a.FRAMEBUFFER, a.DEPTH_STENCIL_ATTACHMENT, a.TEXTURE_2D, rt, 0, Z) : a.framebufferTexture2D(a.FRAMEBUFFER, a.DEPTH_STENCIL_ATTACHMENT, a.TEXTURE_2D, rt, 0);
    else
      throw new Error("Unknown depthTexture format");
  }
  function Kt(P) {
    const A = i.get(P), N = P.isWebGLCubeRenderTarget === !0;
    if (A.__boundDepthTexture !== P.depthTexture) {
      const X = P.depthTexture;
      if (A.__depthDisposeCallback && A.__depthDisposeCallback(), X) {
        const rt = () => {
          delete A.__boundDepthTexture, delete A.__depthDisposeCallback, X.removeEventListener("dispose", rt);
        };
        X.addEventListener("dispose", rt), A.__depthDisposeCallback = rt;
      }
      A.__boundDepthTexture = X;
    }
    if (P.depthTexture && !A.__autoAllocateDepthBuffer) {
      if (N) throw new Error("target.depthTexture not supported in Cube render targets");
      const X = P.texture.mipmaps;
      X && X.length > 0 ? Pt(A.__webglFramebuffer[0], P) : Pt(A.__webglFramebuffer, P);
    } else if (N) {
      A.__webglDepthbuffer = [];
      for (let X = 0; X < 6; X++)
        if (e.bindFramebuffer(a.FRAMEBUFFER, A.__webglFramebuffer[X]), A.__webglDepthbuffer[X] === void 0)
          A.__webglDepthbuffer[X] = a.createRenderbuffer(), Ut(A.__webglDepthbuffer[X], P, !1);
        else {
          const rt = P.stencilBuffer ? a.DEPTH_STENCIL_ATTACHMENT : a.DEPTH_ATTACHMENT, Z = A.__webglDepthbuffer[X];
          a.bindRenderbuffer(a.RENDERBUFFER, Z), a.framebufferRenderbuffer(a.FRAMEBUFFER, rt, a.RENDERBUFFER, Z);
        }
    } else {
      const X = P.texture.mipmaps;
      if (X && X.length > 0 ? e.bindFramebuffer(a.FRAMEBUFFER, A.__webglFramebuffer[0]) : e.bindFramebuffer(a.FRAMEBUFFER, A.__webglFramebuffer), A.__webglDepthbuffer === void 0)
        A.__webglDepthbuffer = a.createRenderbuffer(), Ut(A.__webglDepthbuffer, P, !1);
      else {
        const rt = P.stencilBuffer ? a.DEPTH_STENCIL_ATTACHMENT : a.DEPTH_ATTACHMENT, Z = A.__webglDepthbuffer;
        a.bindRenderbuffer(a.RENDERBUFFER, Z), a.framebufferRenderbuffer(a.FRAMEBUFFER, rt, a.RENDERBUFFER, Z);
      }
    }
    e.bindFramebuffer(a.FRAMEBUFFER, null);
  }
  function he(P, A, N) {
    const X = i.get(P);
    A !== void 0 && Et(X.__webglFramebuffer, P, P.texture, a.COLOR_ATTACHMENT0, a.TEXTURE_2D, 0), N !== void 0 && Kt(P);
  }
  function D(P) {
    const A = P.texture, N = i.get(P), X = i.get(A);
    P.addEventListener("dispose", T);
    const rt = P.textures, Z = P.isWebGLCubeRenderTarget === !0, It = rt.length > 1;
    if (It || (X.__webglTexture === void 0 && (X.__webglTexture = a.createTexture()), X.__version = A.version, r.memory.textures++), Z) {
      N.__webglFramebuffer = [];
      for (let I = 0; I < 6; I++)
        if (A.mipmaps && A.mipmaps.length > 0) {
          N.__webglFramebuffer[I] = [];
          for (let lt = 0; lt < A.mipmaps.length; lt++)
            N.__webglFramebuffer[I][lt] = a.createFramebuffer();
        } else
          N.__webglFramebuffer[I] = a.createFramebuffer();
    } else {
      if (A.mipmaps && A.mipmaps.length > 0) {
        N.__webglFramebuffer = [];
        for (let I = 0; I < A.mipmaps.length; I++)
          N.__webglFramebuffer[I] = a.createFramebuffer();
      } else
        N.__webglFramebuffer = a.createFramebuffer();
      if (It)
        for (let I = 0, lt = rt.length; I < lt; I++) {
          const gt = i.get(rt[I]);
          gt.__webglTexture === void 0 && (gt.__webglTexture = a.createTexture(), r.memory.textures++);
        }
      if (P.samples > 0 && ut(P) === !1) {
        N.__webglMultisampledFramebuffer = a.createFramebuffer(), N.__webglColorRenderbuffer = [], e.bindFramebuffer(a.FRAMEBUFFER, N.__webglMultisampledFramebuffer);
        for (let I = 0; I < rt.length; I++) {
          const lt = rt[I];
          N.__webglColorRenderbuffer[I] = a.createRenderbuffer(), a.bindRenderbuffer(a.RENDERBUFFER, N.__webglColorRenderbuffer[I]);
          const gt = s.convert(lt.format, lt.colorSpace), j = s.convert(lt.type), mt = x(lt.internalFormat, gt, j, lt.colorSpace, P.isXRRenderTarget === !0), At = yt(P);
          a.renderbufferStorageMultisample(a.RENDERBUFFER, At, mt, P.width, P.height), a.framebufferRenderbuffer(a.FRAMEBUFFER, a.COLOR_ATTACHMENT0 + I, a.RENDERBUFFER, N.__webglColorRenderbuffer[I]);
        }
        a.bindRenderbuffer(a.RENDERBUFFER, null), P.depthBuffer && (N.__webglDepthRenderbuffer = a.createRenderbuffer(), Ut(N.__webglDepthRenderbuffer, P, !0)), e.bindFramebuffer(a.FRAMEBUFFER, null);
      }
    }
    if (Z) {
      e.bindTexture(a.TEXTURE_CUBE_MAP, X.__webglTexture), Lt(a.TEXTURE_CUBE_MAP, A);
      for (let I = 0; I < 6; I++)
        if (A.mipmaps && A.mipmaps.length > 0)
          for (let lt = 0; lt < A.mipmaps.length; lt++)
            Et(N.__webglFramebuffer[I][lt], P, A, a.COLOR_ATTACHMENT0, a.TEXTURE_CUBE_MAP_POSITIVE_X + I, lt);
        else
          Et(N.__webglFramebuffer[I], P, A, a.COLOR_ATTACHMENT0, a.TEXTURE_CUBE_MAP_POSITIVE_X + I, 0);
      g(A) && m(a.TEXTURE_CUBE_MAP), e.unbindTexture();
    } else if (It) {
      for (let I = 0, lt = rt.length; I < lt; I++) {
        const gt = rt[I], j = i.get(gt);
        let mt = a.TEXTURE_2D;
        (P.isWebGL3DRenderTarget || P.isWebGLArrayRenderTarget) && (mt = P.isWebGL3DRenderTarget ? a.TEXTURE_3D : a.TEXTURE_2D_ARRAY), e.bindTexture(mt, j.__webglTexture), Lt(mt, gt), Et(N.__webglFramebuffer, P, gt, a.COLOR_ATTACHMENT0 + I, mt, 0), g(gt) && m(mt);
      }
      e.unbindTexture();
    } else {
      let I = a.TEXTURE_2D;
      if ((P.isWebGL3DRenderTarget || P.isWebGLArrayRenderTarget) && (I = P.isWebGL3DRenderTarget ? a.TEXTURE_3D : a.TEXTURE_2D_ARRAY), e.bindTexture(I, X.__webglTexture), Lt(I, A), A.mipmaps && A.mipmaps.length > 0)
        for (let lt = 0; lt < A.mipmaps.length; lt++)
          Et(N.__webglFramebuffer[lt], P, A, a.COLOR_ATTACHMENT0, I, lt);
      else
        Et(N.__webglFramebuffer, P, A, a.COLOR_ATTACHMENT0, I, 0);
      g(A) && m(I), e.unbindTexture();
    }
    P.depthBuffer && Kt(P);
  }
  function ot(P) {
    const A = P.textures;
    for (let N = 0, X = A.length; N < X; N++) {
      const rt = A[N];
      if (g(rt)) {
        const Z = v(P), It = i.get(rt).__webglTexture;
        e.bindTexture(Z, It), m(Z), e.unbindTexture();
      }
    }
  }
  const it = [], Q = [];
  function K(P) {
    if (P.samples > 0) {
      if (ut(P) === !1) {
        const A = P.textures, N = P.width, X = P.height;
        let rt = a.COLOR_BUFFER_BIT;
        const Z = P.stencilBuffer ? a.DEPTH_STENCIL_ATTACHMENT : a.DEPTH_ATTACHMENT, It = i.get(P), I = A.length > 1;
        if (I)
          for (let gt = 0; gt < A.length; gt++)
            e.bindFramebuffer(a.FRAMEBUFFER, It.__webglMultisampledFramebuffer), a.framebufferRenderbuffer(a.FRAMEBUFFER, a.COLOR_ATTACHMENT0 + gt, a.RENDERBUFFER, null), e.bindFramebuffer(a.FRAMEBUFFER, It.__webglFramebuffer), a.framebufferTexture2D(a.DRAW_FRAMEBUFFER, a.COLOR_ATTACHMENT0 + gt, a.TEXTURE_2D, null, 0);
        e.bindFramebuffer(a.READ_FRAMEBUFFER, It.__webglMultisampledFramebuffer);
        const lt = P.texture.mipmaps;
        lt && lt.length > 0 ? e.bindFramebuffer(a.DRAW_FRAMEBUFFER, It.__webglFramebuffer[0]) : e.bindFramebuffer(a.DRAW_FRAMEBUFFER, It.__webglFramebuffer);
        for (let gt = 0; gt < A.length; gt++) {
          if (P.resolveDepthBuffer && (P.depthBuffer && (rt |= a.DEPTH_BUFFER_BIT), P.stencilBuffer && P.resolveStencilBuffer && (rt |= a.STENCIL_BUFFER_BIT)), I) {
            a.framebufferRenderbuffer(a.READ_FRAMEBUFFER, a.COLOR_ATTACHMENT0, a.RENDERBUFFER, It.__webglColorRenderbuffer[gt]);
            const j = i.get(A[gt]).__webglTexture;
            a.framebufferTexture2D(a.DRAW_FRAMEBUFFER, a.COLOR_ATTACHMENT0, a.TEXTURE_2D, j, 0);
          }
          a.blitFramebuffer(0, 0, N, X, 0, 0, N, X, rt, a.NEAREST), l === !0 && (it.length = 0, Q.length = 0, it.push(a.COLOR_ATTACHMENT0 + gt), P.depthBuffer && P.resolveDepthBuffer === !1 && (it.push(Z), Q.push(Z), a.invalidateFramebuffer(a.DRAW_FRAMEBUFFER, Q)), a.invalidateFramebuffer(a.READ_FRAMEBUFFER, it));
        }
        if (e.bindFramebuffer(a.READ_FRAMEBUFFER, null), e.bindFramebuffer(a.DRAW_FRAMEBUFFER, null), I)
          for (let gt = 0; gt < A.length; gt++) {
            e.bindFramebuffer(a.FRAMEBUFFER, It.__webglMultisampledFramebuffer), a.framebufferRenderbuffer(a.FRAMEBUFFER, a.COLOR_ATTACHMENT0 + gt, a.RENDERBUFFER, It.__webglColorRenderbuffer[gt]);
            const j = i.get(A[gt]).__webglTexture;
            e.bindFramebuffer(a.FRAMEBUFFER, It.__webglFramebuffer), a.framebufferTexture2D(a.DRAW_FRAMEBUFFER, a.COLOR_ATTACHMENT0 + gt, a.TEXTURE_2D, j, 0);
          }
        e.bindFramebuffer(a.DRAW_FRAMEBUFFER, It.__webglMultisampledFramebuffer);
      } else if (P.depthBuffer && P.resolveDepthBuffer === !1 && l) {
        const A = P.stencilBuffer ? a.DEPTH_STENCIL_ATTACHMENT : a.DEPTH_ATTACHMENT;
        a.invalidateFramebuffer(a.DRAW_FRAMEBUFFER, [A]);
      }
    }
  }
  function yt(P) {
    return Math.min(n.maxSamples, P.samples);
  }
  function ut(P) {
    const A = i.get(P);
    return P.samples > 0 && t.has("WEBGL_multisampled_render_to_texture") === !0 && A.__useRenderToTexture !== !1;
  }
  function xt(P) {
    const A = r.render.frame;
    c.get(P) !== A && (c.set(P, A), P.update());
  }
  function Wt(P, A) {
    const N = P.colorSpace, X = P.format, rt = P.type;
    return P.isCompressedTexture === !0 || P.isVideoTexture === !0 || N !== Cs && N !== $n && (ee.getTransfer(N) === ce ? (X !== gi || rt !== pn) && console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.") : console.error("THREE.WebGLTextures: Unsupported texture color space:", N)), A;
  }
  function Nt(P) {
    return typeof HTMLImageElement < "u" && P instanceof HTMLImageElement ? (h.width = P.naturalWidth || P.width, h.height = P.naturalHeight || P.height) : typeof VideoFrame < "u" && P instanceof VideoFrame ? (h.width = P.displayWidth, h.height = P.displayHeight) : (h.width = P.width, h.height = P.height), h;
  }
  this.allocateTextureUnit = O, this.resetTextureUnits = U, this.setTexture2D = W, this.setTexture2DArray = G, this.setTexture3D = et, this.setTextureCube = H, this.rebindTextures = he, this.setupRenderTarget = D, this.updateRenderTargetMipmap = ot, this.updateMultisampleRenderTarget = K, this.setupDepthRenderbuffer = Kt, this.setupFrameBufferTexture = Et, this.useMultisampledRTT = ut;
}
function T_(a, t) {
  function e(i, n = $n) {
    let s;
    const r = ee.getTransfer(n);
    if (i === pn) return a.UNSIGNED_BYTE;
    if (i === Pc) return a.UNSIGNED_SHORT_4_4_4_4;
    if (i === Ic) return a.UNSIGNED_SHORT_5_5_5_1;
    if (i === Ep) return a.UNSIGNED_INT_5_9_9_9_REV;
    if (i === Tp) return a.UNSIGNED_INT_10F_11F_11F_REV;
    if (i === wp) return a.BYTE;
    if (i === Ap) return a.SHORT;
    if (i === da) return a.UNSIGNED_SHORT;
    if (i === Rc) return a.INT;
    if (i === ns) return a.UNSIGNED_INT;
    if (i === wi) return a.FLOAT;
    if (i === wa) return a.HALF_FLOAT;
    if (i === Cp) return a.ALPHA;
    if (i === Rp) return a.RGB;
    if (i === gi) return a.RGBA;
    if (i === fa) return a.DEPTH_COMPONENT;
    if (i === ma) return a.DEPTH_STENCIL;
    if (i === Lc) return a.RED;
    if (i === No) return a.RED_INTEGER;
    if (i === Pp) return a.RG;
    if (i === Dc) return a.RG_INTEGER;
    if (i === Fc) return a.RGBA_INTEGER;
    if (i === ho || i === co || i === uo || i === po)
      if (r === ce)
        if (s = t.get("WEBGL_compressed_texture_s3tc_srgb"), s !== null) {
          if (i === ho) return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          if (i === co) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          if (i === uo) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          if (i === po) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
        } else
          return null;
      else if (s = t.get("WEBGL_compressed_texture_s3tc"), s !== null) {
        if (i === ho) return s.COMPRESSED_RGB_S3TC_DXT1_EXT;
        if (i === co) return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;
        if (i === uo) return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;
        if (i === po) return s.COMPRESSED_RGBA_S3TC_DXT5_EXT;
      } else
        return null;
    if (i === kh || i === Vh || i === Hh || i === Gh)
      if (s = t.get("WEBGL_compressed_texture_pvrtc"), s !== null) {
        if (i === kh) return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
        if (i === Vh) return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
        if (i === Hh) return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
        if (i === Gh) return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
      } else
        return null;
    if (i === Wh || i === qh || i === $h)
      if (s = t.get("WEBGL_compressed_texture_etc"), s !== null) {
        if (i === Wh || i === qh) return r === ce ? s.COMPRESSED_SRGB8_ETC2 : s.COMPRESSED_RGB8_ETC2;
        if (i === $h) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : s.COMPRESSED_RGBA8_ETC2_EAC;
      } else
        return null;
    if (i === Xh || i === Yh || i === Zh || i === jh || i === Jh || i === Kh || i === Qh || i === tc || i === ec || i === ic || i === nc || i === sc || i === rc || i === ac)
      if (s = t.get("WEBGL_compressed_texture_astc"), s !== null) {
        if (i === Xh) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : s.COMPRESSED_RGBA_ASTC_4x4_KHR;
        if (i === Yh) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : s.COMPRESSED_RGBA_ASTC_5x4_KHR;
        if (i === Zh) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : s.COMPRESSED_RGBA_ASTC_5x5_KHR;
        if (i === jh) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : s.COMPRESSED_RGBA_ASTC_6x5_KHR;
        if (i === Jh) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : s.COMPRESSED_RGBA_ASTC_6x6_KHR;
        if (i === Kh) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : s.COMPRESSED_RGBA_ASTC_8x5_KHR;
        if (i === Qh) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : s.COMPRESSED_RGBA_ASTC_8x6_KHR;
        if (i === tc) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : s.COMPRESSED_RGBA_ASTC_8x8_KHR;
        if (i === ec) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : s.COMPRESSED_RGBA_ASTC_10x5_KHR;
        if (i === ic) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : s.COMPRESSED_RGBA_ASTC_10x6_KHR;
        if (i === nc) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : s.COMPRESSED_RGBA_ASTC_10x8_KHR;
        if (i === sc) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : s.COMPRESSED_RGBA_ASTC_10x10_KHR;
        if (i === rc) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : s.COMPRESSED_RGBA_ASTC_12x10_KHR;
        if (i === ac) return r === ce ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : s.COMPRESSED_RGBA_ASTC_12x12_KHR;
      } else
        return null;
    if (i === oc || i === lc || i === hc)
      if (s = t.get("EXT_texture_compression_bptc"), s !== null) {
        if (i === oc) return r === ce ? s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : s.COMPRESSED_RGBA_BPTC_UNORM_EXT;
        if (i === lc) return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
        if (i === hc) return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
      } else
        return null;
    if (i === cc || i === uc || i === dc || i === pc)
      if (s = t.get("EXT_texture_compression_rgtc"), s !== null) {
        if (i === cc) return s.COMPRESSED_RED_RGTC1_EXT;
        if (i === uc) return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;
        if (i === dc) return s.COMPRESSED_RED_GREEN_RGTC2_EXT;
        if (i === pc) return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
      } else
        return null;
    return i === pa ? a.UNSIGNED_INT_24_8 : a[i] !== void 0 ? a[i] : null;
  }
  return { convert: e };
}
const yE = `
void main() {

	gl_Position = vec4( position, 1.0 );

}`, _E = `
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;

void main() {

	vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );

	if ( coord.x >= 1.0 ) {

		gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;

	} else {

		gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;

	}

}`;
class xE {
  /**
   * Constructs a new depth sensing module.
   */
  constructor() {
    this.texture = null, this.mesh = null, this.depthNear = 0, this.depthFar = 0;
  }
  /**
   * Inits the depth sensing module
   *
   * @param {XRWebGLDepthInformation} depthData - The XR depth data.
   * @param {XRRenderState} renderState - The XR render state.
   */
  init(t, e) {
    if (this.texture === null) {
      const i = new Hp(t.texture);
      (t.depthNear !== e.depthNear || t.depthFar !== e.depthFar) && (this.depthNear = t.depthNear, this.depthFar = t.depthFar), this.texture = i;
    }
  }
  /**
   * Returns a plane mesh that visualizes the depth texture.
   *
   * @param {ArrayCamera} cameraXR - The XR camera.
   * @return {?Mesh} The plane mesh.
   */
  getMesh(t) {
    if (this.texture !== null && this.mesh === null) {
      const e = t.cameras[0].viewport, i = new Xi({
        vertexShader: yE,
        fragmentShader: _E,
        uniforms: {
          depthColor: { value: this.texture },
          depthWidth: { value: e.z },
          depthHeight: { value: e.w }
        }
      });
      this.mesh = new re(new Ds(20, 20), i);
    }
    return this.mesh;
  }
  /**
   * Resets the module
   */
  reset() {
    this.texture = null, this.mesh = null;
  }
  /**
   * Returns a texture representing the depth of the user's environment.
   *
   * @return {?ExternalTexture} The depth texture.
   */
  getDepthTexture() {
    return this.texture;
  }
}
class vE extends Ei {
  /**
   * Constructs a new WebGL renderer.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGL2RenderingContext} gl - The rendering context.
   */
  constructor(t, e) {
    super();
    const i = this;
    let n = null, s = 1, r = null, o = "local-floor", l = 1, h = null, c = null, u = null, d = null, p = null, f = null;
    const y = typeof XRWebGLBinding < "u", g = new xE(), m = {}, v = e.getContextAttributes();
    let x = null, _ = null;
    const S = [], w = [], T = new J();
    let R = null;
    const b = new Ve();
    b.viewport = new Qt();
    const M = new Ve();
    M.viewport = new Qt();
    const L = [b, M], U = new p_();
    let O = null, V = null;
    this.cameraAutoUpdate = !0, this.enabled = !1, this.isPresenting = !1, this.getController = function(Y) {
      let st = S[Y];
      return st === void 0 && (st = new Th(), S[Y] = st), st.getTargetRaySpace();
    }, this.getControllerGrip = function(Y) {
      let st = S[Y];
      return st === void 0 && (st = new Th(), S[Y] = st), st.getGripSpace();
    }, this.getHand = function(Y) {
      let st = S[Y];
      return st === void 0 && (st = new Th(), S[Y] = st), st.getHandSpace();
    };
    function W(Y) {
      const st = w.indexOf(Y.inputSource);
      if (st === -1)
        return;
      const Et = S[st];
      Et !== void 0 && (Et.update(Y.inputSource, Y.frame, h || r), Et.dispatchEvent({ type: Y.type, data: Y.inputSource }));
    }
    function G() {
      n.removeEventListener("select", W), n.removeEventListener("selectstart", W), n.removeEventListener("selectend", W), n.removeEventListener("squeeze", W), n.removeEventListener("squeezestart", W), n.removeEventListener("squeezeend", W), n.removeEventListener("end", G), n.removeEventListener("inputsourceschange", et);
      for (let Y = 0; Y < S.length; Y++) {
        const st = w[Y];
        st !== null && (w[Y] = null, S[Y].disconnect(st));
      }
      O = null, V = null, g.reset();
      for (const Y in m)
        delete m[Y];
      t.setRenderTarget(x), p = null, d = null, u = null, n = null, _ = null, Jt.stop(), i.isPresenting = !1, t.setPixelRatio(R), t.setSize(T.width, T.height, !1), i.dispatchEvent({ type: "sessionend" });
    }
    this.setFramebufferScaleFactor = function(Y) {
      s = Y, i.isPresenting === !0 && console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.");
    }, this.setReferenceSpaceType = function(Y) {
      o = Y, i.isPresenting === !0 && console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.");
    }, this.getReferenceSpace = function() {
      return h || r;
    }, this.setReferenceSpace = function(Y) {
      h = Y;
    }, this.getBaseLayer = function() {
      return d !== null ? d : p;
    }, this.getBinding = function() {
      return u === null && y && (u = new XRWebGLBinding(n, e)), u;
    }, this.getFrame = function() {
      return f;
    }, this.getSession = function() {
      return n;
    }, this.setSession = async function(Y) {
      if (n = Y, n !== null) {
        if (x = t.getRenderTarget(), n.addEventListener("select", W), n.addEventListener("selectstart", W), n.addEventListener("selectend", W), n.addEventListener("squeeze", W), n.addEventListener("squeezestart", W), n.addEventListener("squeezeend", W), n.addEventListener("end", G), n.addEventListener("inputsourceschange", et), v.xrCompatible !== !0 && await e.makeXRCompatible(), R = t.getPixelRatio(), t.getSize(T), y && "createProjectionLayer" in XRWebGLBinding.prototype) {
          let Et = null, Ut = null, Pt = null;
          v.depth && (Pt = v.stencil ? e.DEPTH24_STENCIL8 : e.DEPTH_COMPONENT24, Et = v.stencil ? ma : fa, Ut = v.stencil ? pa : ns);
          const Kt = {
            colorFormat: e.RGBA8,
            depthFormat: Pt,
            scaleFactor: s
          };
          u = this.getBinding(), d = u.createProjectionLayer(Kt), n.updateRenderState({ layers: [d] }), t.setPixelRatio(1), t.setSize(d.textureWidth, d.textureHeight, !1), _ = new Rn(
            d.textureWidth,
            d.textureHeight,
            {
              format: gi,
              type: pn,
              depthTexture: new Vp(d.textureWidth, d.textureHeight, Ut, void 0, void 0, void 0, void 0, void 0, void 0, Et),
              stencilBuffer: v.stencil,
              colorSpace: t.outputColorSpace,
              samples: v.antialias ? 4 : 0,
              resolveDepthBuffer: d.ignoreDepthValues === !1,
              resolveStencilBuffer: d.ignoreDepthValues === !1
            }
          );
        } else {
          const Et = {
            antialias: v.antialias,
            alpha: !0,
            depth: v.depth,
            stencil: v.stencil,
            framebufferScaleFactor: s
          };
          p = new XRWebGLLayer(n, e, Et), n.updateRenderState({ baseLayer: p }), t.setPixelRatio(1), t.setSize(p.framebufferWidth, p.framebufferHeight, !1), _ = new Rn(
            p.framebufferWidth,
            p.framebufferHeight,
            {
              format: gi,
              type: pn,
              colorSpace: t.outputColorSpace,
              stencilBuffer: v.stencil,
              resolveDepthBuffer: p.ignoreDepthValues === !1,
              resolveStencilBuffer: p.ignoreDepthValues === !1
            }
          );
        }
        _.isXRRenderTarget = !0, this.setFoveation(l), h = null, r = await n.requestReferenceSpace(o), Jt.setContext(n), Jt.start(), i.isPresenting = !0, i.dispatchEvent({ type: "sessionstart" });
      }
    }, this.getEnvironmentBlendMode = function() {
      if (n !== null)
        return n.environmentBlendMode;
    }, this.getDepthTexture = function() {
      return g.getDepthTexture();
    };
    function et(Y) {
      for (let st = 0; st < Y.removed.length; st++) {
        const Et = Y.removed[st], Ut = w.indexOf(Et);
        Ut >= 0 && (w[Ut] = null, S[Ut].disconnect(Et));
      }
      for (let st = 0; st < Y.added.length; st++) {
        const Et = Y.added[st];
        let Ut = w.indexOf(Et);
        if (Ut === -1) {
          for (let Kt = 0; Kt < S.length; Kt++)
            if (Kt >= w.length) {
              w.push(Et), Ut = Kt;
              break;
            } else if (w[Kt] === null) {
              w[Kt] = Et, Ut = Kt;
              break;
            }
          if (Ut === -1) break;
        }
        const Pt = S[Ut];
        Pt && Pt.connect(Et);
      }
    }
    const H = new E(), at = new E();
    function pt(Y, st, Et) {
      H.setFromMatrixPosition(st.matrixWorld), at.setFromMatrixPosition(Et.matrixWorld);
      const Ut = H.distanceTo(at), Pt = st.projectionMatrix.elements, Kt = Et.projectionMatrix.elements, he = Pt[14] / (Pt[10] - 1), D = Pt[14] / (Pt[10] + 1), ot = (Pt[9] + 1) / Pt[5], it = (Pt[9] - 1) / Pt[5], Q = (Pt[8] - 1) / Pt[0], K = (Kt[8] + 1) / Kt[0], yt = he * Q, ut = he * K, xt = Ut / (-Q + K), Wt = xt * -Q;
      if (st.matrixWorld.decompose(Y.position, Y.quaternion, Y.scale), Y.translateX(Wt), Y.translateZ(xt), Y.matrixWorld.compose(Y.position, Y.quaternion, Y.scale), Y.matrixWorldInverse.copy(Y.matrixWorld).invert(), Pt[10] === -1)
        Y.projectionMatrix.copy(st.projectionMatrix), Y.projectionMatrixInverse.copy(st.projectionMatrixInverse);
      else {
        const Nt = he + xt, P = D + xt, A = yt - Wt, N = ut + (Ut - Wt), X = ot * D / P * Nt, rt = it * D / P * Nt;
        Y.projectionMatrix.makePerspective(A, N, X, rt, Nt, P), Y.projectionMatrixInverse.copy(Y.projectionMatrix).invert();
      }
    }
    function Mt(Y, st) {
      st === null ? Y.matrixWorld.copy(Y.matrix) : Y.matrixWorld.multiplyMatrices(st.matrixWorld, Y.matrix), Y.matrixWorldInverse.copy(Y.matrixWorld).invert();
    }
    this.updateCamera = function(Y) {
      if (n === null) return;
      let st = Y.near, Et = Y.far;
      g.texture !== null && (g.depthNear > 0 && (st = g.depthNear), g.depthFar > 0 && (Et = g.depthFar)), U.near = M.near = b.near = st, U.far = M.far = b.far = Et, (O !== U.near || V !== U.far) && (n.updateRenderState({
        depthNear: U.near,
        depthFar: U.far
      }), O = U.near, V = U.far), U.layers.mask = Y.layers.mask | 6, b.layers.mask = U.layers.mask & 3, M.layers.mask = U.layers.mask & 5;
      const Ut = Y.parent, Pt = U.cameras;
      Mt(U, Ut);
      for (let Kt = 0; Kt < Pt.length; Kt++)
        Mt(Pt[Kt], Ut);
      Pt.length === 2 ? pt(U, b, M) : U.projectionMatrix.copy(b.projectionMatrix), Lt(Y, U, Ut);
    };
    function Lt(Y, st, Et) {
      Et === null ? Y.matrix.copy(st.matrixWorld) : (Y.matrix.copy(Et.matrixWorld), Y.matrix.invert(), Y.matrix.multiply(st.matrixWorld)), Y.matrix.decompose(Y.position, Y.quaternion, Y.scale), Y.updateMatrixWorld(!0), Y.projectionMatrix.copy(st.projectionMatrix), Y.projectionMatrixInverse.copy(st.projectionMatrixInverse), Y.isPerspectiveCamera && (Y.fov = ya * 2 * Math.atan(1 / Y.projectionMatrix.elements[5]), Y.zoom = 1);
    }
    this.getCamera = function() {
      return U;
    }, this.getFoveation = function() {
      if (!(d === null && p === null))
        return l;
    }, this.setFoveation = function(Y) {
      l = Y, d !== null && (d.fixedFoveation = Y), p !== null && p.fixedFoveation !== void 0 && (p.fixedFoveation = Y);
    }, this.hasDepthSensing = function() {
      return g.texture !== null;
    }, this.getDepthSensingMesh = function() {
      return g.getMesh(U);
    }, this.getCameraTexture = function(Y) {
      return m[Y];
    };
    let jt = null;
    function ne(Y, st) {
      if (c = st.getViewerPose(h || r), f = st, c !== null) {
        const Et = c.views;
        p !== null && (t.setRenderTargetFramebuffer(_, p.framebuffer), t.setRenderTarget(_));
        let Ut = !1;
        Et.length !== U.cameras.length && (U.cameras.length = 0, Ut = !0);
        for (let D = 0; D < Et.length; D++) {
          const ot = Et[D];
          let it = null;
          if (p !== null)
            it = p.getViewport(ot);
          else {
            const K = u.getViewSubImage(d, ot);
            it = K.viewport, D === 0 && (t.setRenderTargetTextures(
              _,
              K.colorTexture,
              K.depthStencilTexture
            ), t.setRenderTarget(_));
          }
          let Q = L[D];
          Q === void 0 && (Q = new Ve(), Q.layers.enable(D), Q.viewport = new Qt(), L[D] = Q), Q.matrix.fromArray(ot.transform.matrix), Q.matrix.decompose(Q.position, Q.quaternion, Q.scale), Q.projectionMatrix.fromArray(ot.projectionMatrix), Q.projectionMatrixInverse.copy(Q.projectionMatrix).invert(), Q.viewport.set(it.x, it.y, it.width, it.height), D === 0 && (U.matrix.copy(Q.matrix), U.matrix.decompose(U.position, U.quaternion, U.scale)), Ut === !0 && U.cameras.push(Q);
        }
        const Pt = n.enabledFeatures;
        if (Pt && Pt.includes("depth-sensing") && n.depthUsage == "gpu-optimized" && y) {
          u = i.getBinding();
          const D = u.getDepthInformation(Et[0]);
          D && D.isValid && D.texture && g.init(D, n.renderState);
        }
        if (Pt && Pt.includes("camera-access") && y) {
          t.state.unbindTexture(), u = i.getBinding();
          for (let D = 0; D < Et.length; D++) {
            const ot = Et[D].camera;
            if (ot) {
              let it = m[ot];
              it || (it = new Hp(), m[ot] = it);
              const Q = u.getCameraImage(ot);
              it.sourceTexture = Q;
            }
          }
        }
      }
      for (let Et = 0; Et < S.length; Et++) {
        const Ut = w[Et], Pt = S[Et];
        Ut !== null && Pt !== void 0 && Pt.update(Ut, st, h || r);
      }
      jt && jt(Y, st), st.detectedPlanes && i.dispatchEvent({ type: "planesdetected", data: st }), f = null;
    }
    const Jt = new M_();
    Jt.setAnimationLoop(ne), this.setAnimationLoop = function(Y) {
      jt = Y;
    }, this.dispose = function() {
    };
  }
}
const Js = /* @__PURE__ */ new fn(), bE = /* @__PURE__ */ new Vt();
function ME(a, t) {
  function e(g, m) {
    g.matrixAutoUpdate === !0 && g.updateMatrix(), m.value.copy(g.matrix);
  }
  function i(g, m) {
    m.color.getRGB(g.fogColor.value, wy(a)), m.isFog ? (g.fogNear.value = m.near, g.fogFar.value = m.far) : m.isFogExp2 && (g.fogDensity.value = m.density);
  }
  function n(g, m, v, x, _) {
    m.isMeshBasicMaterial || m.isMeshLambertMaterial ? s(g, m) : m.isMeshToonMaterial ? (s(g, m), u(g, m)) : m.isMeshPhongMaterial ? (s(g, m), c(g, m)) : m.isMeshStandardMaterial ? (s(g, m), d(g, m), m.isMeshPhysicalMaterial && p(g, m, _)) : m.isMeshMatcapMaterial ? (s(g, m), f(g, m)) : m.isMeshDepthMaterial ? s(g, m) : m.isMeshDistanceMaterial ? (s(g, m), y(g, m)) : m.isMeshNormalMaterial ? s(g, m) : m.isLineBasicMaterial ? (r(g, m), m.isLineDashedMaterial && o(g, m)) : m.isPointsMaterial ? l(g, m, v, x) : m.isSpriteMaterial ? h(g, m) : m.isShadowMaterial ? (g.color.value.copy(m.color), g.opacity.value = m.opacity) : m.isShaderMaterial && (m.uniformsNeedUpdate = !1);
  }
  function s(g, m) {
    g.opacity.value = m.opacity, m.color && g.diffuse.value.copy(m.color), m.emissive && g.emissive.value.copy(m.emissive).multiplyScalar(m.emissiveIntensity), m.map && (g.map.value = m.map, e(m.map, g.mapTransform)), m.alphaMap && (g.alphaMap.value = m.alphaMap, e(m.alphaMap, g.alphaMapTransform)), m.bumpMap && (g.bumpMap.value = m.bumpMap, e(m.bumpMap, g.bumpMapTransform), g.bumpScale.value = m.bumpScale, m.side === He && (g.bumpScale.value *= -1)), m.normalMap && (g.normalMap.value = m.normalMap, e(m.normalMap, g.normalMapTransform), g.normalScale.value.copy(m.normalScale), m.side === He && g.normalScale.value.negate()), m.displacementMap && (g.displacementMap.value = m.displacementMap, e(m.displacementMap, g.displacementMapTransform), g.displacementScale.value = m.displacementScale, g.displacementBias.value = m.displacementBias), m.emissiveMap && (g.emissiveMap.value = m.emissiveMap, e(m.emissiveMap, g.emissiveMapTransform)), m.specularMap && (g.specularMap.value = m.specularMap, e(m.specularMap, g.specularMapTransform)), m.alphaTest > 0 && (g.alphaTest.value = m.alphaTest);
    const v = t.get(m), x = v.envMap, _ = v.envMapRotation;
    x && (g.envMap.value = x, Js.copy(_), Js.x *= -1, Js.y *= -1, Js.z *= -1, x.isCubeTexture && x.isRenderTargetTexture === !1 && (Js.y *= -1, Js.z *= -1), g.envMapRotation.value.setFromMatrix4(bE.makeRotationFromEuler(Js)), g.flipEnvMap.value = x.isCubeTexture && x.isRenderTargetTexture === !1 ? -1 : 1, g.reflectivity.value = m.reflectivity, g.ior.value = m.ior, g.refractionRatio.value = m.refractionRatio), m.lightMap && (g.lightMap.value = m.lightMap, g.lightMapIntensity.value = m.lightMapIntensity, e(m.lightMap, g.lightMapTransform)), m.aoMap && (g.aoMap.value = m.aoMap, g.aoMapIntensity.value = m.aoMapIntensity, e(m.aoMap, g.aoMapTransform));
  }
  function r(g, m) {
    g.diffuse.value.copy(m.color), g.opacity.value = m.opacity, m.map && (g.map.value = m.map, e(m.map, g.mapTransform));
  }
  function o(g, m) {
    g.dashSize.value = m.dashSize, g.totalSize.value = m.dashSize + m.gapSize, g.scale.value = m.scale;
  }
  function l(g, m, v, x) {
    g.diffuse.value.copy(m.color), g.opacity.value = m.opacity, g.size.value = m.size * v, g.scale.value = x * 0.5, m.map && (g.map.value = m.map, e(m.map, g.uvTransform)), m.alphaMap && (g.alphaMap.value = m.alphaMap, e(m.alphaMap, g.alphaMapTransform)), m.alphaTest > 0 && (g.alphaTest.value = m.alphaTest);
  }
  function h(g, m) {
    g.diffuse.value.copy(m.color), g.opacity.value = m.opacity, g.rotation.value = m.rotation, m.map && (g.map.value = m.map, e(m.map, g.mapTransform)), m.alphaMap && (g.alphaMap.value = m.alphaMap, e(m.alphaMap, g.alphaMapTransform)), m.alphaTest > 0 && (g.alphaTest.value = m.alphaTest);
  }
  function c(g, m) {
    g.specular.value.copy(m.specular), g.shininess.value = Math.max(m.shininess, 1e-4);
  }
  function u(g, m) {
    m.gradientMap && (g.gradientMap.value = m.gradientMap);
  }
  function d(g, m) {
    g.metalness.value = m.metalness, m.metalnessMap && (g.metalnessMap.value = m.metalnessMap, e(m.metalnessMap, g.metalnessMapTransform)), g.roughness.value = m.roughness, m.roughnessMap && (g.roughnessMap.value = m.roughnessMap, e(m.roughnessMap, g.roughnessMapTransform)), m.envMap && (g.envMapIntensity.value = m.envMapIntensity);
  }
  function p(g, m, v) {
    g.ior.value = m.ior, m.sheen > 0 && (g.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen), g.sheenRoughness.value = m.sheenRoughness, m.sheenColorMap && (g.sheenColorMap.value = m.sheenColorMap, e(m.sheenColorMap, g.sheenColorMapTransform)), m.sheenRoughnessMap && (g.sheenRoughnessMap.value = m.sheenRoughnessMap, e(m.sheenRoughnessMap, g.sheenRoughnessMapTransform))), m.clearcoat > 0 && (g.clearcoat.value = m.clearcoat, g.clearcoatRoughness.value = m.clearcoatRoughness, m.clearcoatMap && (g.clearcoatMap.value = m.clearcoatMap, e(m.clearcoatMap, g.clearcoatMapTransform)), m.clearcoatRoughnessMap && (g.clearcoatRoughnessMap.value = m.clearcoatRoughnessMap, e(m.clearcoatRoughnessMap, g.clearcoatRoughnessMapTransform)), m.clearcoatNormalMap && (g.clearcoatNormalMap.value = m.clearcoatNormalMap, e(m.clearcoatNormalMap, g.clearcoatNormalMapTransform), g.clearcoatNormalScale.value.copy(m.clearcoatNormalScale), m.side === He && g.clearcoatNormalScale.value.negate())), m.dispersion > 0 && (g.dispersion.value = m.dispersion), m.iridescence > 0 && (g.iridescence.value = m.iridescence, g.iridescenceIOR.value = m.iridescenceIOR, g.iridescenceThicknessMinimum.value = m.iridescenceThicknessRange[0], g.iridescenceThicknessMaximum.value = m.iridescenceThicknessRange[1], m.iridescenceMap && (g.iridescenceMap.value = m.iridescenceMap, e(m.iridescenceMap, g.iridescenceMapTransform)), m.iridescenceThicknessMap && (g.iridescenceThicknessMap.value = m.iridescenceThicknessMap, e(m.iridescenceThicknessMap, g.iridescenceThicknessMapTransform))), m.transmission > 0 && (g.transmission.value = m.transmission, g.transmissionSamplerMap.value = v.texture, g.transmissionSamplerSize.value.set(v.width, v.height), m.transmissionMap && (g.transmissionMap.value = m.transmissionMap, e(m.transmissionMap, g.transmissionMapTransform)), g.thickness.value = m.thickness, m.thicknessMap && (g.thicknessMap.value = m.thicknessMap, e(m.thicknessMap, g.thicknessMapTransform)), g.attenuationDistance.value = m.attenuationDistance, g.attenuationColor.value.copy(m.attenuationColor)), m.anisotropy > 0 && (g.anisotropyVector.value.set(m.anisotropy * Math.cos(m.anisotropyRotation), m.anisotropy * Math.sin(m.anisotropyRotation)), m.anisotropyMap && (g.anisotropyMap.value = m.anisotropyMap, e(m.anisotropyMap, g.anisotropyMapTransform))), g.specularIntensity.value = m.specularIntensity, g.specularColor.value.copy(m.specularColor), m.specularColorMap && (g.specularColorMap.value = m.specularColorMap, e(m.specularColorMap, g.specularColorMapTransform)), m.specularIntensityMap && (g.specularIntensityMap.value = m.specularIntensityMap, e(m.specularIntensityMap, g.specularIntensityMapTransform));
  }
  function f(g, m) {
    m.matcap && (g.matcap.value = m.matcap);
  }
  function y(g, m) {
    const v = t.get(m).light;
    g.referencePosition.value.setFromMatrixPosition(v.matrixWorld), g.nearDistance.value = v.shadow.camera.near, g.farDistance.value = v.shadow.camera.far;
  }
  return {
    refreshFogUniforms: i,
    refreshMaterialUniforms: n
  };
}
function SE(a, t, e, i) {
  let n = {}, s = {}, r = [];
  const o = a.getParameter(a.MAX_UNIFORM_BUFFER_BINDINGS);
  function l(v, x) {
    const _ = x.program;
    i.uniformBlockBinding(v, _);
  }
  function h(v, x) {
    let _ = n[v.id];
    _ === void 0 && (f(v), _ = c(v), n[v.id] = _, v.addEventListener("dispose", g));
    const S = x.program;
    i.updateUBOMapping(v, S);
    const w = t.render.frame;
    s[v.id] !== w && (d(v), s[v.id] = w);
  }
  function c(v) {
    const x = u();
    v.__bindingPointIndex = x;
    const _ = a.createBuffer(), S = v.__size, w = v.usage;
    return a.bindBuffer(a.UNIFORM_BUFFER, _), a.bufferData(a.UNIFORM_BUFFER, S, w), a.bindBuffer(a.UNIFORM_BUFFER, null), a.bindBufferBase(a.UNIFORM_BUFFER, x, _), _;
  }
  function u() {
    for (let v = 0; v < o; v++)
      if (r.indexOf(v) === -1)
        return r.push(v), v;
    return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."), 0;
  }
  function d(v) {
    const x = n[v.id], _ = v.uniforms, S = v.__cache;
    a.bindBuffer(a.UNIFORM_BUFFER, x);
    for (let w = 0, T = _.length; w < T; w++) {
      const R = Array.isArray(_[w]) ? _[w] : [_[w]];
      for (let b = 0, M = R.length; b < M; b++) {
        const L = R[b];
        if (p(L, w, b, S) === !0) {
          const U = L.__offset, O = Array.isArray(L.value) ? L.value : [L.value];
          let V = 0;
          for (let W = 0; W < O.length; W++) {
            const G = O[W], et = y(G);
            typeof G == "number" || typeof G == "boolean" ? (L.__data[0] = G, a.bufferSubData(a.UNIFORM_BUFFER, U + V, L.__data)) : G.isMatrix3 ? (L.__data[0] = G.elements[0], L.__data[1] = G.elements[1], L.__data[2] = G.elements[2], L.__data[3] = 0, L.__data[4] = G.elements[3], L.__data[5] = G.elements[4], L.__data[6] = G.elements[5], L.__data[7] = 0, L.__data[8] = G.elements[6], L.__data[9] = G.elements[7], L.__data[10] = G.elements[8], L.__data[11] = 0) : (G.toArray(L.__data, V), V += et.storage / Float32Array.BYTES_PER_ELEMENT);
          }
          a.bufferSubData(a.UNIFORM_BUFFER, U, L.__data);
        }
      }
    }
    a.bindBuffer(a.UNIFORM_BUFFER, null);
  }
  function p(v, x, _, S) {
    const w = v.value, T = x + "_" + _;
    if (S[T] === void 0)
      return typeof w == "number" || typeof w == "boolean" ? S[T] = w : S[T] = w.clone(), !0;
    {
      const R = S[T];
      if (typeof w == "number" || typeof w == "boolean") {
        if (R !== w)
          return S[T] = w, !0;
      } else if (R.equals(w) === !1)
        return R.copy(w), !0;
    }
    return !1;
  }
  function f(v) {
    const x = v.uniforms;
    let _ = 0;
    const S = 16;
    for (let T = 0, R = x.length; T < R; T++) {
      const b = Array.isArray(x[T]) ? x[T] : [x[T]];
      for (let M = 0, L = b.length; M < L; M++) {
        const U = b[M], O = Array.isArray(U.value) ? U.value : [U.value];
        for (let V = 0, W = O.length; V < W; V++) {
          const G = O[V], et = y(G), H = _ % S, at = H % et.boundary, pt = H + at;
          _ += at, pt !== 0 && S - pt < et.storage && (_ += S - pt), U.__data = new Float32Array(et.storage / Float32Array.BYTES_PER_ELEMENT), U.__offset = _, _ += et.storage;
        }
      }
    }
    const w = _ % S;
    return w > 0 && (_ += S - w), v.__size = _, v.__cache = {}, this;
  }
  function y(v) {
    const x = {
      boundary: 0,
      // bytes
      storage: 0
      // bytes
    };
    return typeof v == "number" || typeof v == "boolean" ? (x.boundary = 4, x.storage = 4) : v.isVector2 ? (x.boundary = 8, x.storage = 8) : v.isVector3 || v.isColor ? (x.boundary = 16, x.storage = 12) : v.isVector4 ? (x.boundary = 16, x.storage = 16) : v.isMatrix3 ? (x.boundary = 48, x.storage = 48) : v.isMatrix4 ? (x.boundary = 64, x.storage = 64) : v.isTexture ? console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.") : console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", v), x;
  }
  function g(v) {
    const x = v.target;
    x.removeEventListener("dispose", g);
    const _ = r.indexOf(x.__bindingPointIndex);
    r.splice(_, 1), a.deleteBuffer(n[x.id]), delete n[x.id], delete s[x.id];
  }
  function m() {
    for (const v in n)
      a.deleteBuffer(n[v]);
    r = [], n = {}, s = {};
  }
  return {
    bind: l,
    update: h,
    dispose: m
  };
}
class C_ {
  /**
   * Constructs a new WebGL renderer.
   *
   * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
   */
  constructor(t = {}) {
    const {
      canvas: e = _y(),
      context: i = null,
      depth: n = !0,
      stencil: s = !1,
      alpha: r = !1,
      antialias: o = !1,
      premultipliedAlpha: l = !0,
      preserveDrawingBuffer: h = !1,
      powerPreference: c = "default",
      failIfMajorPerformanceCaveat: u = !1,
      reversedDepthBuffer: d = !1
    } = t;
    this.isWebGLRenderer = !0;
    let p;
    if (i !== null) {
      if (typeof WebGLRenderingContext < "u" && i instanceof WebGLRenderingContext)
        throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");
      p = i.getContextAttributes().alpha;
    } else
      p = r;
    const f = new Uint32Array(4), y = new Int32Array(4);
    let g = null, m = null;
    const v = [], x = [];
    this.domElement = e, this.debug = {
      /**
       * Enables error checking and reporting when shader programs are being compiled.
       * @type {boolean}
       */
      checkShaderErrors: !0,
      /**
       * Callback for custom error reporting.
       * @type {?Function}
       */
      onShaderError: null
    }, this.autoClear = !0, this.autoClearColor = !0, this.autoClearDepth = !0, this.autoClearStencil = !0, this.sortObjects = !0, this.clippingPlanes = [], this.localClippingEnabled = !1, this.toneMapping = Zn, this.toneMappingExposure = 1, this.transmissionResolutionScale = 1;
    const _ = this;
    let S = !1;
    this._outputColorSpace = ri;
    let w = 0, T = 0, R = null, b = -1, M = null;
    const L = new Qt(), U = new Qt();
    let O = null;
    const V = new ct(0);
    let W = 0, G = e.width, et = e.height, H = 1, at = null, pt = null;
    const Mt = new Qt(0, 0, G, et), Lt = new Qt(0, 0, G, et);
    let jt = !1;
    const ne = new Ea();
    let Jt = !1, Y = !1;
    const st = new Vt(), Et = new E(), Ut = new Qt(), Pt = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: !0 };
    let Kt = !1;
    function he() {
      return R === null ? H : 1;
    }
    let D = i;
    function ot(C, B) {
      return e.getContext(C, B);
    }
    try {
      const C = {
        alpha: !0,
        depth: n,
        stencil: s,
        antialias: o,
        premultipliedAlpha: l,
        preserveDrawingBuffer: h,
        powerPreference: c,
        failIfMajorPerformanceCaveat: u
      };
      if ("setAttribute" in e && e.setAttribute("data-engine", `three.js r${Tc}`), e.addEventListener("webglcontextlost", _t, !1), e.addEventListener("webglcontextrestored", Rt, !1), e.addEventListener("webglcontextcreationerror", dt, !1), D === null) {
        const B = "webgl2";
        if (D = ot(B, C), D === null)
          throw ot(B) ? new Error("Error creating WebGL context with your selected attributes.") : new Error("Error creating WebGL context.");
      }
    } catch (C) {
      throw console.error("THREE.WebGLRenderer: " + C.message), C;
    }
    let it, Q, K, yt, ut, xt, Wt, Nt, P, A, N, X, rt, Z, It, I, lt, gt, j, mt, At, Tt, vt, $t;
    function F() {
      it = new Uw(D), it.init(), Tt = new T_(D, it), Q = new Cw(D, it, t, Tt), K = new mE(D, it), Q.reversedDepthBuffer && d && K.buffers.depth.setReversed(!0), yt = new Nw(D), ut = new iE(), xt = new gE(D, it, K, ut, Q, Tt, yt), Wt = new Pw(_), Nt = new Fw(_), P = new WM(D), vt = new Ew(D, P), A = new Bw(D, P, yt, vt), N = new kw(D, A, P, yt), j = new Ow(D, Q, xt), I = new Rw(ut), X = new eE(_, Wt, Nt, it, Q, vt, I), rt = new ME(_, ut), Z = new sE(), It = new cE(it), gt = new Aw(_, Wt, Nt, K, N, p, l), lt = new pE(_, N, Q), $t = new SE(D, yt, Q, K), mt = new Tw(D, it, yt), At = new zw(D, it, yt), yt.programs = X.programs, _.capabilities = Q, _.extensions = it, _.properties = ut, _.renderLists = Z, _.shadowMap = lt, _.state = K, _.info = yt;
    }
    F();
    const ht = new vE(_, D);
    this.xr = ht, this.getContext = function() {
      return D;
    }, this.getContextAttributes = function() {
      return D.getContextAttributes();
    }, this.forceContextLoss = function() {
      const C = it.get("WEBGL_lose_context");
      C && C.loseContext();
    }, this.forceContextRestore = function() {
      const C = it.get("WEBGL_lose_context");
      C && C.restoreContext();
    }, this.getPixelRatio = function() {
      return H;
    }, this.setPixelRatio = function(C) {
      C !== void 0 && (H = C, this.setSize(G, et, !1));
    }, this.getSize = function(C) {
      return C.set(G, et);
    }, this.setSize = function(C, B, q = !0) {
      if (ht.isPresenting) {
        console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");
        return;
      }
      G = C, et = B, e.width = Math.floor(C * H), e.height = Math.floor(B * H), q === !0 && (e.style.width = C + "px", e.style.height = B + "px"), this.setViewport(0, 0, C, B);
    }, this.getDrawingBufferSize = function(C) {
      return C.set(G * H, et * H).floor();
    }, this.setDrawingBufferSize = function(C, B, q) {
      G = C, et = B, H = q, e.width = Math.floor(C * q), e.height = Math.floor(B * q), this.setViewport(0, 0, C, B);
    }, this.getCurrentViewport = function(C) {
      return C.copy(L);
    }, this.getViewport = function(C) {
      return C.copy(Mt);
    }, this.setViewport = function(C, B, q, $) {
      C.isVector4 ? Mt.set(C.x, C.y, C.z, C.w) : Mt.set(C, B, q, $), K.viewport(L.copy(Mt).multiplyScalar(H).round());
    }, this.getScissor = function(C) {
      return C.copy(Lt);
    }, this.setScissor = function(C, B, q, $) {
      C.isVector4 ? Lt.set(C.x, C.y, C.z, C.w) : Lt.set(C, B, q, $), K.scissor(U.copy(Lt).multiplyScalar(H).round());
    }, this.getScissorTest = function() {
      return jt;
    }, this.setScissorTest = function(C) {
      K.setScissorTest(jt = C);
    }, this.setOpaqueSort = function(C) {
      at = C;
    }, this.setTransparentSort = function(C) {
      pt = C;
    }, this.getClearColor = function(C) {
      return C.copy(gt.getClearColor());
    }, this.setClearColor = function() {
      gt.setClearColor(...arguments);
    }, this.getClearAlpha = function() {
      return gt.getClearAlpha();
    }, this.setClearAlpha = function() {
      gt.setClearAlpha(...arguments);
    }, this.clear = function(C = !0, B = !0, q = !0) {
      let $ = 0;
      if (C) {
        let z = !1;
        if (R !== null) {
          const ft = R.texture.format;
          z = ft === Fc || ft === Dc || ft === No;
        }
        if (z) {
          const ft = R.texture.type, St = ft === pn || ft === ns || ft === da || ft === pa || ft === Pc || ft === Ic, Dt = gt.getClearColor(), Ct = gt.getClearAlpha(), Ot = Dt.r, Gt = Dt.g, Bt = Dt.b;
          St ? (f[0] = Ot, f[1] = Gt, f[2] = Bt, f[3] = Ct, D.clearBufferuiv(D.COLOR, 0, f)) : (y[0] = Ot, y[1] = Gt, y[2] = Bt, y[3] = Ct, D.clearBufferiv(D.COLOR, 0, y));
        } else
          $ |= D.COLOR_BUFFER_BIT;
      }
      B && ($ |= D.DEPTH_BUFFER_BIT), q && ($ |= D.STENCIL_BUFFER_BIT, this.state.buffers.stencil.setMask(4294967295)), D.clear($);
    }, this.clearColor = function() {
      this.clear(!0, !1, !1);
    }, this.clearDepth = function() {
      this.clear(!1, !0, !1);
    }, this.clearStencil = function() {
      this.clear(!1, !1, !0);
    }, this.dispose = function() {
      e.removeEventListener("webglcontextlost", _t, !1), e.removeEventListener("webglcontextrestored", Rt, !1), e.removeEventListener("webglcontextcreationerror", dt, !1), gt.dispose(), Z.dispose(), It.dispose(), ut.dispose(), Wt.dispose(), Nt.dispose(), N.dispose(), vt.dispose(), $t.dispose(), X.dispose(), ht.dispose(), ht.removeEventListener("sessionstart", gn), ht.removeEventListener("sessionend", wf), Bs.stop();
    };
    function _t(C) {
      C.preventDefault(), console.log("THREE.WebGLRenderer: Context Lost."), S = !0;
    }
    function Rt() {
      console.log("THREE.WebGLRenderer: Context Restored."), S = !1;
      const C = yt.autoReset, B = lt.enabled, q = lt.autoUpdate, $ = lt.needsUpdate, z = lt.type;
      F(), yt.autoReset = C, lt.enabled = B, lt.autoUpdate = q, lt.needsUpdate = $, lt.type = z;
    }
    function dt(C) {
      console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", C.statusMessage);
    }
    function nt(C) {
      const B = C.target;
      B.removeEventListener("dispose", nt), Ft(B);
    }
    function Ft(C) {
      qt(C), ut.remove(C);
    }
    function qt(C) {
      const B = ut.get(C).programs;
      B !== void 0 && (B.forEach(function(q) {
        X.releaseProgram(q);
      }), C.isShaderMaterial && X.releaseShaderCache(C));
    }
    this.renderBufferDirect = function(C, B, q, $, z, ft) {
      B === null && (B = Pt);
      const St = z.isMesh && z.matrixWorld.determinant() < 0, Dt = lx(C, B, q, $, z);
      K.setMaterial($, St);
      let Ct = q.index, Ot = 1;
      if ($.wireframe === !0) {
        if (Ct = A.getWireframeAttribute(q), Ct === void 0) return;
        Ot = 2;
      }
      const Gt = q.drawRange, Bt = q.attributes.position;
      let te = Gt.start * Ot, pe = (Gt.start + Gt.count) * Ot;
      ft !== null && (te = Math.max(te, ft.start * Ot), pe = Math.min(pe, (ft.start + ft.count) * Ot)), Ct !== null ? (te = Math.max(te, 0), pe = Math.min(pe, Ct.count)) : Bt != null && (te = Math.max(te, 0), pe = Math.min(pe, Bt.count));
      const Ae = pe - te;
      if (Ae < 0 || Ae === 1 / 0) return;
      vt.setup(z, $, Dt, q, Ct);
      let _e, fe = mt;
      if (Ct !== null && (_e = P.get(Ct), fe = At, fe.setIndex(_e)), z.isMesh)
        $.wireframe === !0 ? (K.setLineWidth($.wireframeLinewidth * he()), fe.setMode(D.LINES)) : fe.setMode(D.TRIANGLES);
      else if (z.isLine) {
        let zt = $.linewidth;
        zt === void 0 && (zt = 1), K.setLineWidth(zt * he()), z.isLineSegments ? fe.setMode(D.LINES) : z.isLineLoop ? fe.setMode(D.LINE_LOOP) : fe.setMode(D.LINE_STRIP);
      } else z.isPoints ? fe.setMode(D.POINTS) : z.isSprite && fe.setMode(D.TRIANGLES);
      if (z.isBatchedMesh)
        if (z._multiDrawInstances !== null)
          Po("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."), fe.renderMultiDrawInstances(z._multiDrawStarts, z._multiDrawCounts, z._multiDrawCount, z._multiDrawInstances);
        else if (it.get("WEBGL_multi_draw"))
          fe.renderMultiDraw(z._multiDrawStarts, z._multiDrawCounts, z._multiDrawCount);
        else {
          const zt = z._multiDrawStarts, be = z._multiDrawCounts, ae = z._multiDrawCount, Ci = Ct ? P.get(Ct).bytesPerElement : 1, xr = ut.get($).currentProgram.getUniforms();
          for (let Ri = 0; Ri < ae; Ri++)
            xr.setValue(D, "_gl_DrawID", Ri), fe.render(zt[Ri] / Ci, be[Ri]);
        }
      else if (z.isInstancedMesh)
        fe.renderInstances(te, Ae, z.count);
      else if (q.isInstancedBufferGeometry) {
        const zt = q._maxInstanceCount !== void 0 ? q._maxInstanceCount : 1 / 0, be = Math.min(q.instanceCount, zt);
        fe.renderInstances(te, Ae, be);
      } else
        fe.render(te, Ae);
    };
    function ge(C, B, q) {
      C.transparent === !0 && C.side === Mi && C.forceSinglePass === !1 ? (C.side = He, C.needsUpdate = !0, Yo(C, B, q), C.side = $i, C.needsUpdate = !0, Yo(C, B, q), C.side = Mi) : Yo(C, B, q);
    }
    this.compile = function(C, B, q = null) {
      q === null && (q = C), m = It.get(q), m.init(B), x.push(m), q.traverseVisible(function(z) {
        z.isLight && z.layers.test(B.layers) && (m.pushLight(z), z.castShadow && m.pushShadow(z));
      }), C !== q && C.traverseVisible(function(z) {
        z.isLight && z.layers.test(B.layers) && (m.pushLight(z), z.castShadow && m.pushShadow(z));
      }), m.setupLights();
      const $ = /* @__PURE__ */ new Set();
      return C.traverse(function(z) {
        if (!(z.isMesh || z.isPoints || z.isLine || z.isSprite))
          return;
        const ft = z.material;
        if (ft)
          if (Array.isArray(ft))
            for (let St = 0; St < ft.length; St++) {
              const Dt = ft[St];
              ge(Dt, q, z), $.add(Dt);
            }
          else
            ge(ft, q, z), $.add(ft);
      }), m = x.pop(), $;
    }, this.compileAsync = function(C, B, q = null) {
      const $ = this.compile(C, B, q);
      return new Promise((z) => {
        function ft() {
          if ($.forEach(function(St) {
            ut.get(St).currentProgram.isReady() && $.delete(St);
          }), $.size === 0) {
            z(C);
            return;
          }
          setTimeout(ft, 10);
        }
        it.get("KHR_parallel_shader_compile") !== null ? ft() : setTimeout(ft, 10);
      });
    };
    let oe = null;
    function In(C) {
      oe && oe(C);
    }
    function gn() {
      Bs.stop();
    }
    function wf() {
      Bs.start();
    }
    const Bs = new M_();
    Bs.setAnimationLoop(In), typeof self < "u" && Bs.setContext(self), this.setAnimationLoop = function(C) {
      oe = C, ht.setAnimationLoop(C), C === null ? Bs.stop() : Bs.start();
    }, ht.addEventListener("sessionstart", gn), ht.addEventListener("sessionend", wf), this.render = function(C, B) {
      if (B !== void 0 && B.isCamera !== !0) {
        console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");
        return;
      }
      if (S === !0) return;
      if (C.matrixWorldAutoUpdate === !0 && C.updateMatrixWorld(), B.parent === null && B.matrixWorldAutoUpdate === !0 && B.updateMatrixWorld(), ht.enabled === !0 && ht.isPresenting === !0 && (ht.cameraAutoUpdate === !0 && ht.updateCamera(B), B = ht.getCamera()), C.isScene === !0 && C.onBeforeRender(_, C, B, R), m = It.get(C, x.length), m.init(B), x.push(m), st.multiplyMatrices(B.projectionMatrix, B.matrixWorldInverse), ne.setFromProjectionMatrix(st, Ni, B.reversedDepth), Y = this.localClippingEnabled, Jt = I.init(this.clippingPlanes, Y), g = Z.get(C, v.length), g.init(), v.push(g), ht.enabled === !0 && ht.isPresenting === !0) {
        const ft = _.xr.getDepthSensingMesh();
        ft !== null && mu(ft, B, -1 / 0, _.sortObjects);
      }
      mu(C, B, 0, _.sortObjects), g.finish(), _.sortObjects === !0 && g.sort(at, pt), Kt = ht.enabled === !1 || ht.isPresenting === !1 || ht.hasDepthSensing() === !1, Kt && gt.addToRenderList(g, C), this.info.render.frame++, Jt === !0 && I.beginShadows();
      const q = m.state.shadowsArray;
      lt.render(q, C, B), Jt === !0 && I.endShadows(), this.info.autoReset === !0 && this.info.reset();
      const $ = g.opaque, z = g.transmissive;
      if (m.setupLights(), B.isArrayCamera) {
        const ft = B.cameras;
        if (z.length > 0)
          for (let St = 0, Dt = ft.length; St < Dt; St++) {
            const Ct = ft[St];
            Ef($, z, C, Ct);
          }
        Kt && gt.render(C);
        for (let St = 0, Dt = ft.length; St < Dt; St++) {
          const Ct = ft[St];
          Af(g, C, Ct, Ct.viewport);
        }
      } else
        z.length > 0 && Ef($, z, C, B), Kt && gt.render(C), Af(g, C, B);
      R !== null && T === 0 && (xt.updateMultisampleRenderTarget(R), xt.updateRenderTargetMipmap(R)), C.isScene === !0 && C.onAfterRender(_, C, B), vt.resetDefaultState(), b = -1, M = null, x.pop(), x.length > 0 ? (m = x[x.length - 1], Jt === !0 && I.setGlobalState(_.clippingPlanes, m.state.camera)) : m = null, v.pop(), v.length > 0 ? g = v[v.length - 1] : g = null;
    };
    function mu(C, B, q, $) {
      if (C.visible === !1) return;
      if (C.layers.test(B.layers)) {
        if (C.isGroup)
          q = C.renderOrder;
        else if (C.isLOD)
          C.autoUpdate === !0 && C.update(B);
        else if (C.isLight)
          m.pushLight(C), C.castShadow && m.pushShadow(C);
        else if (C.isSprite) {
          if (!C.frustumCulled || ne.intersectsSprite(C)) {
            $ && Ut.setFromMatrixPosition(C.matrixWorld).applyMatrix4(st);
            const St = N.update(C), Dt = C.material;
            Dt.visible && g.push(C, St, Dt, q, Ut.z, null);
          }
        } else if ((C.isMesh || C.isLine || C.isPoints) && (!C.frustumCulled || ne.intersectsObject(C))) {
          const St = N.update(C), Dt = C.material;
          if ($ && (C.boundingSphere !== void 0 ? (C.boundingSphere === null && C.computeBoundingSphere(), Ut.copy(C.boundingSphere.center)) : (St.boundingSphere === null && St.computeBoundingSphere(), Ut.copy(St.boundingSphere.center)), Ut.applyMatrix4(C.matrixWorld).applyMatrix4(st)), Array.isArray(Dt)) {
            const Ct = St.groups;
            for (let Ot = 0, Gt = Ct.length; Ot < Gt; Ot++) {
              const Bt = Ct[Ot], te = Dt[Bt.materialIndex];
              te && te.visible && g.push(C, St, te, q, Ut.z, Bt);
            }
          } else Dt.visible && g.push(C, St, Dt, q, Ut.z, null);
        }
      }
      const ft = C.children;
      for (let St = 0, Dt = ft.length; St < Dt; St++)
        mu(ft[St], B, q, $);
    }
    function Af(C, B, q, $) {
      const z = C.opaque, ft = C.transmissive, St = C.transparent;
      m.setupLightsView(q), Jt === !0 && I.setGlobalState(_.clippingPlanes, q), $ && K.viewport(L.copy($)), z.length > 0 && Xo(z, B, q), ft.length > 0 && Xo(ft, B, q), St.length > 0 && Xo(St, B, q), K.buffers.depth.setTest(!0), K.buffers.depth.setMask(!0), K.buffers.color.setMask(!0), K.setPolygonOffset(!1);
    }
    function Ef(C, B, q, $) {
      if ((q.isScene === !0 ? q.overrideMaterial : null) !== null)
        return;
      m.state.transmissionRenderTarget[$.id] === void 0 && (m.state.transmissionRenderTarget[$.id] = new Rn(1, 1, {
        generateMipmaps: !0,
        type: it.has("EXT_color_buffer_half_float") || it.has("EXT_color_buffer_float") ? wa : pn,
        minFilter: En,
        samples: 4,
        stencilBuffer: s,
        resolveDepthBuffer: !1,
        resolveStencilBuffer: !1,
        colorSpace: ee.workingColorSpace
      }));
      const ft = m.state.transmissionRenderTarget[$.id], St = $.viewport || L;
      ft.setSize(St.z * _.transmissionResolutionScale, St.w * _.transmissionResolutionScale);
      const Dt = _.getRenderTarget(), Ct = _.getActiveCubeFace(), Ot = _.getActiveMipmapLevel();
      _.setRenderTarget(ft), _.getClearColor(V), W = _.getClearAlpha(), W < 1 && _.setClearColor(16777215, 0.5), _.clear(), Kt && gt.render(q);
      const Gt = _.toneMapping;
      _.toneMapping = Zn;
      const Bt = $.viewport;
      if ($.viewport !== void 0 && ($.viewport = void 0), m.setupLightsView($), Jt === !0 && I.setGlobalState(_.clippingPlanes, $), Xo(C, q, $), xt.updateMultisampleRenderTarget(ft), xt.updateRenderTargetMipmap(ft), it.has("WEBGL_multisampled_render_to_texture") === !1) {
        let te = !1;
        for (let pe = 0, Ae = B.length; pe < Ae; pe++) {
          const _e = B[pe], fe = _e.object, zt = _e.geometry, be = _e.material, ae = _e.group;
          if (be.side === Mi && fe.layers.test($.layers)) {
            const Ci = be.side;
            be.side = He, be.needsUpdate = !0, Tf(fe, q, $, zt, be, ae), be.side = Ci, be.needsUpdate = !0, te = !0;
          }
        }
        te === !0 && (xt.updateMultisampleRenderTarget(ft), xt.updateRenderTargetMipmap(ft));
      }
      _.setRenderTarget(Dt, Ct, Ot), _.setClearColor(V, W), Bt !== void 0 && ($.viewport = Bt), _.toneMapping = Gt;
    }
    function Xo(C, B, q) {
      const $ = B.isScene === !0 ? B.overrideMaterial : null;
      for (let z = 0, ft = C.length; z < ft; z++) {
        const St = C[z], Dt = St.object, Ct = St.geometry, Ot = St.group;
        let Gt = St.material;
        Gt.allowOverride === !0 && $ !== null && (Gt = $), Dt.layers.test(q.layers) && Tf(Dt, B, q, Ct, Gt, Ot);
      }
    }
    function Tf(C, B, q, $, z, ft) {
      C.onBeforeRender(_, B, q, $, z, ft), C.modelViewMatrix.multiplyMatrices(q.matrixWorldInverse, C.matrixWorld), C.normalMatrix.getNormalMatrix(C.modelViewMatrix), z.onBeforeRender(_, B, q, $, C, ft), z.transparent === !0 && z.side === Mi && z.forceSinglePass === !1 ? (z.side = He, z.needsUpdate = !0, _.renderBufferDirect(q, B, $, z, C, ft), z.side = $i, z.needsUpdate = !0, _.renderBufferDirect(q, B, $, z, C, ft), z.side = Mi) : _.renderBufferDirect(q, B, $, z, C, ft), C.onAfterRender(_, B, q, $, z, ft);
    }
    function Yo(C, B, q) {
      B.isScene !== !0 && (B = Pt);
      const $ = ut.get(C), z = m.state.lights, ft = m.state.shadowsArray, St = z.state.version, Dt = X.getParameters(C, z.state, ft, B, q), Ct = X.getProgramCacheKey(Dt);
      let Ot = $.programs;
      $.environment = C.isMeshStandardMaterial ? B.environment : null, $.fog = B.fog, $.envMap = (C.isMeshStandardMaterial ? Nt : Wt).get(C.envMap || $.environment), $.envMapRotation = $.environment !== null && C.envMap === null ? B.environmentRotation : C.envMapRotation, Ot === void 0 && (C.addEventListener("dispose", nt), Ot = /* @__PURE__ */ new Map(), $.programs = Ot);
      let Gt = Ot.get(Ct);
      if (Gt !== void 0) {
        if ($.currentProgram === Gt && $.lightsStateVersion === St)
          return Rf(C, Dt), Gt;
      } else
        Dt.uniforms = X.getUniforms(C), C.onBeforeCompile(Dt, _), Gt = X.acquireProgram(Dt, Ct), Ot.set(Ct, Gt), $.uniforms = Dt.uniforms;
      const Bt = $.uniforms;
      return (!C.isShaderMaterial && !C.isRawShaderMaterial || C.clipping === !0) && (Bt.clippingPlanes = I.uniform), Rf(C, Dt), $.needsLights = cx(C), $.lightsStateVersion = St, $.needsLights && (Bt.ambientLightColor.value = z.state.ambient, Bt.lightProbe.value = z.state.probe, Bt.directionalLights.value = z.state.directional, Bt.directionalLightShadows.value = z.state.directionalShadow, Bt.spotLights.value = z.state.spot, Bt.spotLightShadows.value = z.state.spotShadow, Bt.rectAreaLights.value = z.state.rectArea, Bt.ltc_1.value = z.state.rectAreaLTC1, Bt.ltc_2.value = z.state.rectAreaLTC2, Bt.pointLights.value = z.state.point, Bt.pointLightShadows.value = z.state.pointShadow, Bt.hemisphereLights.value = z.state.hemi, Bt.directionalShadowMap.value = z.state.directionalShadowMap, Bt.directionalShadowMatrix.value = z.state.directionalShadowMatrix, Bt.spotShadowMap.value = z.state.spotShadowMap, Bt.spotLightMatrix.value = z.state.spotLightMatrix, Bt.spotLightMap.value = z.state.spotLightMap, Bt.pointShadowMap.value = z.state.pointShadowMap, Bt.pointShadowMatrix.value = z.state.pointShadowMatrix), $.currentProgram = Gt, $.uniformsList = null, Gt;
    }
    function Cf(C) {
      if (C.uniformsList === null) {
        const B = C.currentProgram.getUniforms();
        C.uniformsList = Ch.seqWithValue(B.seq, C.uniforms);
      }
      return C.uniformsList;
    }
    function Rf(C, B) {
      const q = ut.get(C);
      q.outputColorSpace = B.outputColorSpace, q.batching = B.batching, q.batchingColor = B.batchingColor, q.instancing = B.instancing, q.instancingColor = B.instancingColor, q.instancingMorph = B.instancingMorph, q.skinning = B.skinning, q.morphTargets = B.morphTargets, q.morphNormals = B.morphNormals, q.morphColors = B.morphColors, q.morphTargetsCount = B.morphTargetsCount, q.numClippingPlanes = B.numClippingPlanes, q.numIntersection = B.numClipIntersection, q.vertexAlphas = B.vertexAlphas, q.vertexTangents = B.vertexTangents, q.toneMapping = B.toneMapping;
    }
    function lx(C, B, q, $, z) {
      B.isScene !== !0 && (B = Pt), xt.resetTextureUnits();
      const ft = B.fog, St = $.isMeshStandardMaterial ? B.environment : null, Dt = R === null ? _.outputColorSpace : R.isXRRenderTarget === !0 ? R.texture.colorSpace : Cs, Ct = ($.isMeshStandardMaterial ? Nt : Wt).get($.envMap || St), Ot = $.vertexColors === !0 && !!q.attributes.color && q.attributes.color.itemSize === 4, Gt = !!q.attributes.tangent && (!!$.normalMap || $.anisotropy > 0), Bt = !!q.morphAttributes.position, te = !!q.morphAttributes.normal, pe = !!q.morphAttributes.color;
      let Ae = Zn;
      $.toneMapped && (R === null || R.isXRRenderTarget === !0) && (Ae = _.toneMapping);
      const _e = q.morphAttributes.position || q.morphAttributes.normal || q.morphAttributes.color, fe = _e !== void 0 ? _e.length : 0, zt = ut.get($), be = m.state.lights;
      if (Jt === !0 && (Y === !0 || C !== M)) {
        const ci = C === M && $.id === b;
        I.setState($, C, ci);
      }
      let ae = !1;
      $.version === zt.__version ? (zt.needsLights && zt.lightsStateVersion !== be.state.version || zt.outputColorSpace !== Dt || z.isBatchedMesh && zt.batching === !1 || !z.isBatchedMesh && zt.batching === !0 || z.isBatchedMesh && zt.batchingColor === !0 && z.colorTexture === null || z.isBatchedMesh && zt.batchingColor === !1 && z.colorTexture !== null || z.isInstancedMesh && zt.instancing === !1 || !z.isInstancedMesh && zt.instancing === !0 || z.isSkinnedMesh && zt.skinning === !1 || !z.isSkinnedMesh && zt.skinning === !0 || z.isInstancedMesh && zt.instancingColor === !0 && z.instanceColor === null || z.isInstancedMesh && zt.instancingColor === !1 && z.instanceColor !== null || z.isInstancedMesh && zt.instancingMorph === !0 && z.morphTexture === null || z.isInstancedMesh && zt.instancingMorph === !1 && z.morphTexture !== null || zt.envMap !== Ct || $.fog === !0 && zt.fog !== ft || zt.numClippingPlanes !== void 0 && (zt.numClippingPlanes !== I.numPlanes || zt.numIntersection !== I.numIntersection) || zt.vertexAlphas !== Ot || zt.vertexTangents !== Gt || zt.morphTargets !== Bt || zt.morphNormals !== te || zt.morphColors !== pe || zt.toneMapping !== Ae || zt.morphTargetsCount !== fe) && (ae = !0) : (ae = !0, zt.__version = $.version);
      let Ci = zt.currentProgram;
      ae === !0 && (Ci = Yo($, B, z));
      let xr = !1, Ri = !1, Ua = !1;
      const Me = Ci.getUniforms(), ki = zt.uniforms;
      if (K.useProgram(Ci.program) && (xr = !0, Ri = !0, Ua = !0), $.id !== b && (b = $.id, Ri = !0), xr || M !== C) {
        K.buffers.depth.getReversed() && C.reversedDepth !== !0 && (C._reversedDepth = !0, C.updateProjectionMatrix()), Me.setValue(D, "projectionMatrix", C.projectionMatrix), Me.setValue(D, "viewMatrix", C.matrixWorldInverse);
        const xi = Me.map.cameraPosition;
        xi !== void 0 && xi.setValue(D, Et.setFromMatrixPosition(C.matrixWorld)), Q.logarithmicDepthBuffer && Me.setValue(
          D,
          "logDepthBufFC",
          2 / (Math.log(C.far + 1) / Math.LN2)
        ), ($.isMeshPhongMaterial || $.isMeshToonMaterial || $.isMeshLambertMaterial || $.isMeshBasicMaterial || $.isMeshStandardMaterial || $.isShaderMaterial) && Me.setValue(D, "isOrthographic", C.isOrthographicCamera === !0), M !== C && (M = C, Ri = !0, Ua = !0);
      }
      if (z.isSkinnedMesh) {
        Me.setOptional(D, z, "bindMatrix"), Me.setOptional(D, z, "bindMatrixInverse");
        const ci = z.skeleton;
        ci && (ci.boneTexture === null && ci.computeBoneTexture(), Me.setValue(D, "boneTexture", ci.boneTexture, xt));
      }
      z.isBatchedMesh && (Me.setOptional(D, z, "batchingTexture"), Me.setValue(D, "batchingTexture", z._matricesTexture, xt), Me.setOptional(D, z, "batchingIdTexture"), Me.setValue(D, "batchingIdTexture", z._indirectTexture, xt), Me.setOptional(D, z, "batchingColorTexture"), z._colorsTexture !== null && Me.setValue(D, "batchingColorTexture", z._colorsTexture, xt));
      const Vi = q.morphAttributes;
      if ((Vi.position !== void 0 || Vi.normal !== void 0 || Vi.color !== void 0) && j.update(z, q, Ci), (Ri || zt.receiveShadow !== z.receiveShadow) && (zt.receiveShadow = z.receiveShadow, Me.setValue(D, "receiveShadow", z.receiveShadow)), $.isMeshGouraudMaterial && $.envMap !== null && (ki.envMap.value = Ct, ki.flipEnvMap.value = Ct.isCubeTexture && Ct.isRenderTargetTexture === !1 ? -1 : 1), $.isMeshStandardMaterial && $.envMap === null && B.environment !== null && (ki.envMapIntensity.value = B.environmentIntensity), Ri && (Me.setValue(D, "toneMappingExposure", _.toneMappingExposure), zt.needsLights && hx(ki, Ua), ft && $.fog === !0 && rt.refreshFogUniforms(ki, ft), rt.refreshMaterialUniforms(ki, $, H, et, m.state.transmissionRenderTarget[C.id]), Ch.upload(D, Cf(zt), ki, xt)), $.isShaderMaterial && $.uniformsNeedUpdate === !0 && (Ch.upload(D, Cf(zt), ki, xt), $.uniformsNeedUpdate = !1), $.isSpriteMaterial && Me.setValue(D, "center", z.center), Me.setValue(D, "modelViewMatrix", z.modelViewMatrix), Me.setValue(D, "normalMatrix", z.normalMatrix), Me.setValue(D, "modelMatrix", z.matrixWorld), $.isShaderMaterial || $.isRawShaderMaterial) {
        const ci = $.uniformsGroups;
        for (let xi = 0, gu = ci.length; xi < gu; xi++) {
          const zs = ci[xi];
          $t.update(zs, Ci), $t.bind(zs, Ci);
        }
      }
      return Ci;
    }
    function hx(C, B) {
      C.ambientLightColor.needsUpdate = B, C.lightProbe.needsUpdate = B, C.directionalLights.needsUpdate = B, C.directionalLightShadows.needsUpdate = B, C.pointLights.needsUpdate = B, C.pointLightShadows.needsUpdate = B, C.spotLights.needsUpdate = B, C.spotLightShadows.needsUpdate = B, C.rectAreaLights.needsUpdate = B, C.hemisphereLights.needsUpdate = B;
    }
    function cx(C) {
      return C.isMeshLambertMaterial || C.isMeshToonMaterial || C.isMeshPhongMaterial || C.isMeshStandardMaterial || C.isShadowMaterial || C.isShaderMaterial && C.lights === !0;
    }
    this.getActiveCubeFace = function() {
      return w;
    }, this.getActiveMipmapLevel = function() {
      return T;
    }, this.getRenderTarget = function() {
      return R;
    }, this.setRenderTargetTextures = function(C, B, q) {
      const $ = ut.get(C);
      $.__autoAllocateDepthBuffer = C.resolveDepthBuffer === !1, $.__autoAllocateDepthBuffer === !1 && ($.__useRenderToTexture = !1), ut.get(C.texture).__webglTexture = B, ut.get(C.depthTexture).__webglTexture = $.__autoAllocateDepthBuffer ? void 0 : q, $.__hasExternalTextures = !0;
    }, this.setRenderTargetFramebuffer = function(C, B) {
      const q = ut.get(C);
      q.__webglFramebuffer = B, q.__useDefaultFramebuffer = B === void 0;
    };
    const ux = D.createFramebuffer();
    this.setRenderTarget = function(C, B = 0, q = 0) {
      R = C, w = B, T = q;
      let $ = !0, z = null, ft = !1, St = !1;
      if (C) {
        const Ct = ut.get(C);
        if (Ct.__useDefaultFramebuffer !== void 0)
          K.bindFramebuffer(D.FRAMEBUFFER, null), $ = !1;
        else if (Ct.__webglFramebuffer === void 0)
          xt.setupRenderTarget(C);
        else if (Ct.__hasExternalTextures)
          xt.rebindTextures(C, ut.get(C.texture).__webglTexture, ut.get(C.depthTexture).__webglTexture);
        else if (C.depthBuffer) {
          const Bt = C.depthTexture;
          if (Ct.__boundDepthTexture !== Bt) {
            if (Bt !== null && ut.has(Bt) && (C.width !== Bt.image.width || C.height !== Bt.image.height))
              throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");
            xt.setupDepthRenderbuffer(C);
          }
        }
        const Ot = C.texture;
        (Ot.isData3DTexture || Ot.isDataArrayTexture || Ot.isCompressedArrayTexture) && (St = !0);
        const Gt = ut.get(C).__webglFramebuffer;
        C.isWebGLCubeRenderTarget ? (Array.isArray(Gt[B]) ? z = Gt[B][q] : z = Gt[B], ft = !0) : C.samples > 0 && xt.useMultisampledRTT(C) === !1 ? z = ut.get(C).__webglMultisampledFramebuffer : Array.isArray(Gt) ? z = Gt[q] : z = Gt, L.copy(C.viewport), U.copy(C.scissor), O = C.scissorTest;
      } else
        L.copy(Mt).multiplyScalar(H).floor(), U.copy(Lt).multiplyScalar(H).floor(), O = jt;
      if (q !== 0 && (z = ux), K.bindFramebuffer(D.FRAMEBUFFER, z) && $ && K.drawBuffers(C, z), K.viewport(L), K.scissor(U), K.setScissorTest(O), ft) {
        const Ct = ut.get(C.texture);
        D.framebufferTexture2D(D.FRAMEBUFFER, D.COLOR_ATTACHMENT0, D.TEXTURE_CUBE_MAP_POSITIVE_X + B, Ct.__webglTexture, q);
      } else if (St) {
        const Ct = B;
        for (let Ot = 0; Ot < C.textures.length; Ot++) {
          const Gt = ut.get(C.textures[Ot]);
          D.framebufferTextureLayer(D.FRAMEBUFFER, D.COLOR_ATTACHMENT0 + Ot, Gt.__webglTexture, q, Ct);
        }
      } else if (C !== null && q !== 0) {
        const Ct = ut.get(C.texture);
        D.framebufferTexture2D(D.FRAMEBUFFER, D.COLOR_ATTACHMENT0, D.TEXTURE_2D, Ct.__webglTexture, q);
      }
      b = -1;
    }, this.readRenderTargetPixels = function(C, B, q, $, z, ft, St, Dt = 0) {
      if (!(C && C.isWebGLRenderTarget)) {
        console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
        return;
      }
      let Ct = ut.get(C).__webglFramebuffer;
      if (C.isWebGLCubeRenderTarget && St !== void 0 && (Ct = Ct[St]), Ct) {
        K.bindFramebuffer(D.FRAMEBUFFER, Ct);
        try {
          const Ot = C.textures[Dt], Gt = Ot.format, Bt = Ot.type;
          if (!Q.textureFormatReadable(Gt)) {
            console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");
            return;
          }
          if (!Q.textureTypeReadable(Bt)) {
            console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");
            return;
          }
          B >= 0 && B <= C.width - $ && q >= 0 && q <= C.height - z && (C.textures.length > 1 && D.readBuffer(D.COLOR_ATTACHMENT0 + Dt), D.readPixels(B, q, $, z, Tt.convert(Gt), Tt.convert(Bt), ft));
        } finally {
          const Ot = R !== null ? ut.get(R).__webglFramebuffer : null;
          K.bindFramebuffer(D.FRAMEBUFFER, Ot);
        }
      }
    }, this.readRenderTargetPixelsAsync = async function(C, B, q, $, z, ft, St, Dt = 0) {
      if (!(C && C.isWebGLRenderTarget))
        throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
      let Ct = ut.get(C).__webglFramebuffer;
      if (C.isWebGLCubeRenderTarget && St !== void 0 && (Ct = Ct[St]), Ct)
        if (B >= 0 && B <= C.width - $ && q >= 0 && q <= C.height - z) {
          K.bindFramebuffer(D.FRAMEBUFFER, Ct);
          const Ot = C.textures[Dt], Gt = Ot.format, Bt = Ot.type;
          if (!Q.textureFormatReadable(Gt))
            throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");
          if (!Q.textureTypeReadable(Bt))
            throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");
          const te = D.createBuffer();
          D.bindBuffer(D.PIXEL_PACK_BUFFER, te), D.bufferData(D.PIXEL_PACK_BUFFER, ft.byteLength, D.STREAM_READ), C.textures.length > 1 && D.readBuffer(D.COLOR_ATTACHMENT0 + Dt), D.readPixels(B, q, $, z, Tt.convert(Gt), Tt.convert(Bt), 0);
          const pe = R !== null ? ut.get(R).__webglFramebuffer : null;
          K.bindFramebuffer(D.FRAMEBUFFER, pe);
          const Ae = D.fenceSync(D.SYNC_GPU_COMMANDS_COMPLETE, 0);
          return D.flush(), await pv(D, Ae, 4), D.bindBuffer(D.PIXEL_PACK_BUFFER, te), D.getBufferSubData(D.PIXEL_PACK_BUFFER, 0, ft), D.deleteBuffer(te), D.deleteSync(Ae), ft;
        } else
          throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.");
    }, this.copyFramebufferToTexture = function(C, B = null, q = 0) {
      const $ = Math.pow(2, -q), z = Math.floor(C.image.width * $), ft = Math.floor(C.image.height * $), St = B !== null ? B.x : 0, Dt = B !== null ? B.y : 0;
      xt.setTexture2D(C, 0), D.copyTexSubImage2D(D.TEXTURE_2D, q, 0, 0, St, Dt, z, ft), K.unbindTexture();
    };
    const dx = D.createFramebuffer(), px = D.createFramebuffer();
    this.copyTextureToTexture = function(C, B, q = null, $ = null, z = 0, ft = null) {
      ft === null && (z !== 0 ? (Po("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."), ft = z, z = 0) : ft = 0);
      let St, Dt, Ct, Ot, Gt, Bt, te, pe, Ae;
      const _e = C.isCompressedTexture ? C.mipmaps[ft] : C.image;
      if (q !== null)
        St = q.max.x - q.min.x, Dt = q.max.y - q.min.y, Ct = q.isBox3 ? q.max.z - q.min.z : 1, Ot = q.min.x, Gt = q.min.y, Bt = q.isBox3 ? q.min.z : 0;
      else {
        const Vi = Math.pow(2, -z);
        St = Math.floor(_e.width * Vi), Dt = Math.floor(_e.height * Vi), C.isDataArrayTexture ? Ct = _e.depth : C.isData3DTexture ? Ct = Math.floor(_e.depth * Vi) : Ct = 1, Ot = 0, Gt = 0, Bt = 0;
      }
      $ !== null ? (te = $.x, pe = $.y, Ae = $.z) : (te = 0, pe = 0, Ae = 0);
      const fe = Tt.convert(B.format), zt = Tt.convert(B.type);
      let be;
      B.isData3DTexture ? (xt.setTexture3D(B, 0), be = D.TEXTURE_3D) : B.isDataArrayTexture || B.isCompressedArrayTexture ? (xt.setTexture2DArray(B, 0), be = D.TEXTURE_2D_ARRAY) : (xt.setTexture2D(B, 0), be = D.TEXTURE_2D), D.pixelStorei(D.UNPACK_FLIP_Y_WEBGL, B.flipY), D.pixelStorei(D.UNPACK_PREMULTIPLY_ALPHA_WEBGL, B.premultiplyAlpha), D.pixelStorei(D.UNPACK_ALIGNMENT, B.unpackAlignment);
      const ae = D.getParameter(D.UNPACK_ROW_LENGTH), Ci = D.getParameter(D.UNPACK_IMAGE_HEIGHT), xr = D.getParameter(D.UNPACK_SKIP_PIXELS), Ri = D.getParameter(D.UNPACK_SKIP_ROWS), Ua = D.getParameter(D.UNPACK_SKIP_IMAGES);
      D.pixelStorei(D.UNPACK_ROW_LENGTH, _e.width), D.pixelStorei(D.UNPACK_IMAGE_HEIGHT, _e.height), D.pixelStorei(D.UNPACK_SKIP_PIXELS, Ot), D.pixelStorei(D.UNPACK_SKIP_ROWS, Gt), D.pixelStorei(D.UNPACK_SKIP_IMAGES, Bt);
      const Me = C.isDataArrayTexture || C.isData3DTexture, ki = B.isDataArrayTexture || B.isData3DTexture;
      if (C.isDepthTexture) {
        const Vi = ut.get(C), ci = ut.get(B), xi = ut.get(Vi.__renderTarget), gu = ut.get(ci.__renderTarget);
        K.bindFramebuffer(D.READ_FRAMEBUFFER, xi.__webglFramebuffer), K.bindFramebuffer(D.DRAW_FRAMEBUFFER, gu.__webglFramebuffer);
        for (let zs = 0; zs < Ct; zs++)
          Me && (D.framebufferTextureLayer(D.READ_FRAMEBUFFER, D.COLOR_ATTACHMENT0, ut.get(C).__webglTexture, z, Bt + zs), D.framebufferTextureLayer(D.DRAW_FRAMEBUFFER, D.COLOR_ATTACHMENT0, ut.get(B).__webglTexture, ft, Ae + zs)), D.blitFramebuffer(Ot, Gt, St, Dt, te, pe, St, Dt, D.DEPTH_BUFFER_BIT, D.NEAREST);
        K.bindFramebuffer(D.READ_FRAMEBUFFER, null), K.bindFramebuffer(D.DRAW_FRAMEBUFFER, null);
      } else if (z !== 0 || C.isRenderTargetTexture || ut.has(C)) {
        const Vi = ut.get(C), ci = ut.get(B);
        K.bindFramebuffer(D.READ_FRAMEBUFFER, dx), K.bindFramebuffer(D.DRAW_FRAMEBUFFER, px);
        for (let xi = 0; xi < Ct; xi++)
          Me ? D.framebufferTextureLayer(D.READ_FRAMEBUFFER, D.COLOR_ATTACHMENT0, Vi.__webglTexture, z, Bt + xi) : D.framebufferTexture2D(D.READ_FRAMEBUFFER, D.COLOR_ATTACHMENT0, D.TEXTURE_2D, Vi.__webglTexture, z), ki ? D.framebufferTextureLayer(D.DRAW_FRAMEBUFFER, D.COLOR_ATTACHMENT0, ci.__webglTexture, ft, Ae + xi) : D.framebufferTexture2D(D.DRAW_FRAMEBUFFER, D.COLOR_ATTACHMENT0, D.TEXTURE_2D, ci.__webglTexture, ft), z !== 0 ? D.blitFramebuffer(Ot, Gt, St, Dt, te, pe, St, Dt, D.COLOR_BUFFER_BIT, D.NEAREST) : ki ? D.copyTexSubImage3D(be, ft, te, pe, Ae + xi, Ot, Gt, St, Dt) : D.copyTexSubImage2D(be, ft, te, pe, Ot, Gt, St, Dt);
        K.bindFramebuffer(D.READ_FRAMEBUFFER, null), K.bindFramebuffer(D.DRAW_FRAMEBUFFER, null);
      } else
        ki ? C.isDataTexture || C.isData3DTexture ? D.texSubImage3D(be, ft, te, pe, Ae, St, Dt, Ct, fe, zt, _e.data) : B.isCompressedArrayTexture ? D.compressedTexSubImage3D(be, ft, te, pe, Ae, St, Dt, Ct, fe, _e.data) : D.texSubImage3D(be, ft, te, pe, Ae, St, Dt, Ct, fe, zt, _e) : C.isDataTexture ? D.texSubImage2D(D.TEXTURE_2D, ft, te, pe, St, Dt, fe, zt, _e.data) : C.isCompressedTexture ? D.compressedTexSubImage2D(D.TEXTURE_2D, ft, te, pe, _e.width, _e.height, fe, _e.data) : D.texSubImage2D(D.TEXTURE_2D, ft, te, pe, St, Dt, fe, zt, _e);
      D.pixelStorei(D.UNPACK_ROW_LENGTH, ae), D.pixelStorei(D.UNPACK_IMAGE_HEIGHT, Ci), D.pixelStorei(D.UNPACK_SKIP_PIXELS, xr), D.pixelStorei(D.UNPACK_SKIP_ROWS, Ri), D.pixelStorei(D.UNPACK_SKIP_IMAGES, Ua), ft === 0 && B.generateMipmaps && D.generateMipmap(be), K.unbindTexture();
    }, this.initRenderTarget = function(C) {
      ut.get(C).__webglFramebuffer === void 0 && xt.setupRenderTarget(C);
    }, this.initTexture = function(C) {
      C.isCubeTexture ? xt.setTextureCube(C, 0) : C.isData3DTexture ? xt.setTexture3D(C, 0) : C.isDataArrayTexture || C.isCompressedArrayTexture ? xt.setTexture2DArray(C, 0) : xt.setTexture2D(C, 0), K.unbindTexture();
    }, this.resetState = function() {
      w = 0, T = 0, R = null, K.reset(), vt.reset();
    }, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this }));
  }
  /**
   * Defines the coordinate system of the renderer.
   *
   * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
   *
   * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
   * @default WebGLCoordinateSystem
   * @readonly
   */
  get coordinateSystem() {
    return Ni;
  }
  /**
   * Defines the output color space of the renderer.
   *
   * @type {SRGBColorSpace|LinearSRGBColorSpace}
   * @default SRGBColorSpace
   */
  get outputColorSpace() {
    return this._outputColorSpace;
  }
  set outputColorSpace(t) {
    this._outputColorSpace = t;
    const e = this.getContext();
    e.drawingBufferColorSpace = ee._getDrawingBufferColorSpace(t), e.unpackColorSpace = ee._getUnpackColorSpace();
  }
}
var wE = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ACESFilmicToneMapping: j0,
  AddEquation: vs,
  AddOperation: $0,
  AdditiveAnimationBlendMode: Dp,
  AdditiveBlending: Zd,
  AgXToneMapping: K0,
  AlphaFormat: Cp,
  AlwaysCompare: dy,
  AlwaysDepth: Fh,
  AlwaysStencilFunc: To,
  AmbientLight: af,
  AnimationAction: g_,
  AnimationClip: Ma,
  AnimationLoader: Ob,
  AnimationMixer: y_,
  AnimationObjectGroup: dM,
  AnimationUtils: Ub,
  ArcCurve: zy,
  ArrayCamera: p_,
  ArrowHelper: BM,
  AttachedBindMode: Kd,
  Audio: f_,
  AudioAnalyser: iM,
  AudioContext: of,
  AudioListener: Qb,
  AudioLoader: jb,
  AxesHelper: zM,
  BackSide: He,
  BasicDepthPacking: iy,
  BasicShadowMap: yx,
  BatchedMesh: Ly,
  Bone: Op,
  BooleanKeyframeTrack: gr,
  Box2: bM,
  Box3: we,
  Box3Helper: FM,
  BoxGeometry: mr,
  BoxHelper: DM,
  BufferAttribute: ie,
  BufferGeometry: Ht,
  BufferGeometryLoader: d_,
  ByteType: wp,
  Cache: Tn,
  Camera: kc,
  CameraHelper: LM,
  CanvasTexture: Uy,
  CapsuleGeometry: Zc,
  CatmullRomCurve3: Ny,
  CineonToneMapping: Z0,
  CircleGeometry: jc,
  ClampToEdgeWrapping: Si,
  Clock: lf,
  Color: ct,
  ColorKeyframeTrack: ef,
  ColorManagement: ee,
  CompressedArrayTexture: nb,
  CompressedCubeTexture: sb,
  CompressedTexture: Yc,
  CompressedTextureLoader: kb,
  ConeGeometry: Ca,
  ConstantAlphaFactor: G0,
  ConstantColorFactor: V0,
  Controls: NM,
  CubeCamera: Ay,
  CubeReflectionMapping: is,
  CubeRefractionMapping: Ts,
  CubeTexture: Oo,
  CubeTextureLoader: Vb,
  CubeUVReflectionMapping: Sa,
  CubicBezierCurve: Wp,
  CubicBezierCurve3: Oy,
  CubicInterpolant: i_,
  CullFaceBack: Yd,
  CullFaceFront: A0,
  CullFaceFrontBack: gx,
  CullFaceNone: w0,
  Curve: mn,
  CurvePath: Vy,
  CustomBlending: T0,
  CustomToneMapping: J0,
  CylinderGeometry: Ta,
  Cylindrical: vM,
  Data3DTexture: zc,
  DataArrayTexture: Bc,
  DataTexture: Cn,
  DataTextureLoader: Hb,
  DataUtils: Cv,
  DecrementStencilOp: Px,
  DecrementWrapStencilOp: wh,
  DefaultLoadingManager: r_,
  DepthFormat: fa,
  DepthStencilFormat: ma,
  DepthTexture: Vp,
  DetachedBindMode: ty,
  DirectionalLight: rf,
  DirectionalLightHelper: IM,
  DiscreteInterpolant: n_,
  DodecahedronGeometry: Jc,
  DoubleSide: Mi,
  DstAlphaFactor: B0,
  DstColorFactor: N0,
  DynamicCopyUsage: Wx,
  DynamicDrawUsage: Nx,
  DynamicReadUsage: Vx,
  EdgesGeometry: By,
  EllipseCurve: Kc,
  EqualCompare: ly,
  EqualDepth: Bh,
  EqualStencilFunc: Fx,
  EquirectangularReflectionMapping: vo,
  EquirectangularRefractionMapping: bo,
  Euler: fn,
  EventDispatcher: Ei,
  ExternalTexture: Hp,
  ExtrudeGeometry: Vo,
  FileLoader: ss,
  Float16BufferAttribute: Uv,
  Float32BufferAttribute: wt,
  FloatType: wi,
  Fog: Hc,
  FogExp2: Vc,
  FramebufferTexture: ib,
  FrontSide: $i,
  Frustum: Ea,
  FrustumArray: $c,
  GLBufferAttribute: yM,
  GLSL1: $x,
  GLSL3: Qd,
  GreaterCompare: hy,
  GreaterDepth: Nh,
  GreaterEqualCompare: uy,
  GreaterEqualDepth: zh,
  GreaterEqualStencilFunc: zx,
  GreaterStencilFunc: Bx,
  GridHelper: RM,
  Group: yi,
  HalfFloatType: wa,
  HemisphereLight: a_,
  HemisphereLightHelper: CM,
  IcosahedronGeometry: Qc,
  ImageBitmapLoader: Zb,
  ImageLoader: Uo,
  ImageUtils: xy,
  IncrementStencilOp: Rx,
  IncrementWrapStencilOp: Sh,
  InstancedBufferAttribute: xa,
  InstancedBufferGeometry: ou,
  InstancedInterleavedBuffer: vc,
  InstancedMesh: Iy,
  Int16BufferAttribute: Dv,
  Int32BufferAttribute: Fv,
  Int8BufferAttribute: Pv,
  IntType: Rc,
  InterleavedBuffer: Gc,
  InterleavedBufferAttribute: un,
  Interpolant: Wo,
  InterpolateDiscrete: wo,
  InterpolateLinear: fc,
  InterpolateSmooth: bh,
  InterpolationSamplingMode: Zx,
  InterpolationSamplingType: Yx,
  InvertStencilOp: Ix,
  KeepStencilOp: er,
  KeyframeTrack: Yi,
  LOD: Ry,
  LatheGeometry: tu,
  Layers: Nc,
  LessCompare: oy,
  LessDepth: Uh,
  LessEqualCompare: Fp,
  LessEqualDepth: pr,
  LessEqualStencilFunc: Ux,
  LessStencilFunc: Dx,
  Light: Fs,
  LightProbe: u_,
  Line: Rs,
  Line3: x_,
  LineBasicMaterial: Pe,
  LineCurve: qp,
  LineCurve3: ky,
  LineDashedMaterial: Kp,
  LineLoop: Dy,
  LineSegments: oi,
  LinearFilter: Ce,
  LinearInterpolant: tf,
  LinearMipMapLinearFilter: bx,
  LinearMipMapNearestFilter: vx,
  LinearMipmapLinearFilter: En,
  LinearMipmapNearestFilter: lo,
  LinearSRGBColorSpace: Cs,
  LinearToneMapping: X0,
  LinearTransfer: Eo,
  Loader: Ti,
  LoaderUtils: rp,
  LoadingManager: nf,
  LoopOnce: ey,
  LoopPingPong: Lp,
  LoopRepeat: Ip,
  MOUSE: Ze,
  Material: hi,
  MaterialLoader: au,
  MathUtils: py,
  Matrix2: df,
  Matrix3: Xt,
  Matrix4: Vt,
  MaxEquation: I0,
  Mesh: re,
  MeshBasicMaterial: li,
  MeshDepthMaterial: jp,
  MeshDistanceMaterial: Jp,
  MeshLambertMaterial: Ky,
  MeshMatcapMaterial: Qy,
  MeshNormalMaterial: Jy,
  MeshPhongMaterial: Zy,
  MeshPhysicalMaterial: Yy,
  MeshStandardMaterial: hr,
  MeshToonMaterial: jy,
  MinEquation: P0,
  MirroredRepeatWrapping: So,
  MixOperation: q0,
  MultiplyBlending: Jd,
  MultiplyOperation: zo,
  NearestFilter: je,
  NearestMipMapLinearFilter: xx,
  NearestMipMapNearestFilter: _x,
  NearestMipmapLinearFilter: sa,
  NearestMipmapNearestFilter: Sp,
  NeutralToneMapping: Q0,
  NeverCompare: ay,
  NeverDepth: Dh,
  NeverStencilFunc: Lx,
  NoBlending: Yn,
  NoColorSpace: $n,
  NoToneMapping: Zn,
  NormalAnimationBlendMode: Uc,
  NormalBlending: ws,
  NotEqualCompare: cy,
  NotEqualDepth: Oh,
  NotEqualStencilFunc: ry,
  NumberKeyframeTrack: Fo,
  Object3D: le,
  ObjectLoader: Xb,
  ObjectSpaceNormalMap: sy,
  OctahedronGeometry: Ho,
  OneFactor: D0,
  OneMinusConstantAlphaFactor: W0,
  OneMinusConstantColorFactor: H0,
  OneMinusDstAlphaFactor: z0,
  OneMinusDstColorFactor: O0,
  OneMinusSrcAlphaFactor: Lh,
  OneMinusSrcColorFactor: U0,
  OrthographicCamera: Ia,
  PCFShadowMap: Mp,
  PCFSoftShadowMap: E0,
  PMREMGenerator: hp,
  Path: xc,
  PerspectiveCamera: Ve,
  Plane: qn,
  PlaneGeometry: Ds,
  PlaneHelper: UM,
  PointLight: l_,
  PointLightHelper: EM,
  Points: kp,
  PointsMaterial: Xc,
  PolarGridHelper: PM,
  PolyhedronGeometry: Ls,
  PositionalAudio: eM,
  PropertyBinding: se,
  PropertyMixer: m_,
  QuadraticBezierCurve: $p,
  QuadraticBezierCurve3: Xp,
  Quaternion: ve,
  QuaternionKeyframeTrack: Pa,
  QuaternionLinearInterpolant: s_,
  RED_GREEN_RGTC2_Format: dc,
  RED_RGTC1_Format: cc,
  REVISION: Tc,
  RGBADepthPacking: ny,
  RGBAFormat: gi,
  RGBAIntegerFormat: Fc,
  RGBA_ASTC_10x10_Format: sc,
  RGBA_ASTC_10x5_Format: ec,
  RGBA_ASTC_10x6_Format: ic,
  RGBA_ASTC_10x8_Format: nc,
  RGBA_ASTC_12x10_Format: rc,
  RGBA_ASTC_12x12_Format: ac,
  RGBA_ASTC_4x4_Format: Xh,
  RGBA_ASTC_5x4_Format: Yh,
  RGBA_ASTC_5x5_Format: Zh,
  RGBA_ASTC_6x5_Format: jh,
  RGBA_ASTC_6x6_Format: Jh,
  RGBA_ASTC_8x5_Format: Kh,
  RGBA_ASTC_8x6_Format: Qh,
  RGBA_ASTC_8x8_Format: tc,
  RGBA_BPTC_Format: oc,
  RGBA_ETC2_EAC_Format: $h,
  RGBA_PVRTC_2BPPV1_Format: Gh,
  RGBA_PVRTC_4BPPV1_Format: Hh,
  RGBA_S3TC_DXT1_Format: co,
  RGBA_S3TC_DXT3_Format: uo,
  RGBA_S3TC_DXT5_Format: po,
  RGBDepthPacking: Ex,
  RGBFormat: Rp,
  RGBIntegerFormat: Mx,
  RGB_BPTC_SIGNED_Format: lc,
  RGB_BPTC_UNSIGNED_Format: hc,
  RGB_ETC1_Format: Wh,
  RGB_ETC2_Format: qh,
  RGB_PVRTC_2BPPV1_Format: Vh,
  RGB_PVRTC_4BPPV1_Format: kh,
  RGB_S3TC_DXT1_Format: ho,
  RGDepthPacking: Tx,
  RGFormat: Pp,
  RGIntegerFormat: Dc,
  RawShaderMaterial: Xy,
  Ray: Aa,
  Raycaster: __,
  RectAreaLight: h_,
  RedFormat: Lc,
  RedIntegerFormat: No,
  ReinhardToneMapping: Y0,
  RenderTarget: Bp,
  RenderTarget3D: fM,
  RepeatWrapping: Mo,
  ReplaceStencilOp: Mh,
  ReverseSubtractEquation: R0,
  RingGeometry: eu,
  SIGNED_RED_GREEN_RGTC2_Format: pc,
  SIGNED_RED_RGTC1_Format: uc,
  SRGBColorSpace: ri,
  SRGBTransfer: ce,
  Scene: ko,
  ShaderChunk: Zt,
  ShaderLib: fi,
  ShaderMaterial: Xi,
  ShadowMaterial: $y,
  Shape: As,
  ShapeGeometry: Go,
  ShapePath: b_,
  ShapeUtils: dn,
  ShortType: Ap,
  Skeleton: qc,
  SkeletonHelper: AM,
  SkinnedMesh: Py,
  Source: Ms,
  Sphere: Re,
  SphereGeometry: Ra,
  Spherical: op,
  SphericalHarmonics3: c_,
  SplineCurve: Yp,
  SpotLight: o_,
  SpotLightHelper: wM,
  Sprite: mc,
  SpriteMaterial: Wc,
  SrcAlphaFactor: Ih,
  SrcAlphaSaturateFactor: k0,
  SrcColorFactor: F0,
  StaticCopyUsage: Gx,
  StaticDrawUsage: Co,
  StaticReadUsage: kx,
  StereoCamera: Jb,
  StreamCopyUsage: qx,
  StreamDrawUsage: Ox,
  StreamReadUsage: Hx,
  StringKeyframeTrack: yr,
  SubtractEquation: C0,
  SubtractiveBlending: jd,
  TOUCH: zi,
  TangentSpaceNormalMap: Is,
  TetrahedronGeometry: iu,
  Texture: Ne,
  TextureLoader: Gb,
  TextureUtils: GM,
  Timer: _M,
  TimestampQuery: Xx,
  TorusGeometry: nu,
  TorusKnotGeometry: su,
  Triangle: bs,
  TriangleFanDrawMode: Ax,
  TriangleStripDrawMode: wx,
  TrianglesDrawMode: Sx,
  TubeGeometry: ru,
  UVMapping: Cc,
  Uint16BufferAttribute: zp,
  Uint32BufferAttribute: Np,
  Uint8BufferAttribute: Iv,
  Uint8ClampedBufferAttribute: Lv,
  Uniform: uf,
  UniformsGroup: gM,
  UniformsLib: bt,
  UniformsUtils: Oc,
  UnsignedByteType: pn,
  UnsignedInt101111Type: Tp,
  UnsignedInt248Type: pa,
  UnsignedInt5999Type: Ep,
  UnsignedIntType: ns,
  UnsignedShort4444Type: Pc,
  UnsignedShort5551Type: Ic,
  UnsignedShortType: da,
  VSMShadowMap: Sn,
  Vector2: J,
  Vector3: E,
  Vector4: Qt,
  VectorKeyframeTrack: ba,
  VideoFrameTexture: eb,
  VideoTexture: Fy,
  WebGL3DRenderTarget: _v,
  WebGLArrayRenderTarget: yv,
  WebGLCoordinateSystem: Ni,
  WebGLCubeRenderTarget: Ey,
  WebGLRenderTarget: Rn,
  WebGLRenderer: C_,
  WebGLUtils: T_,
  WebGPUCoordinateSystem: ga,
  WebXRController: Th,
  WireframeGeometry: Zp,
  WrapAroundEnding: Ao,
  ZeroCurvatureEnding: sr,
  ZeroFactor: L0,
  ZeroSlopeEnding: rr,
  ZeroStencilOp: Cx,
  createCanvasElement: _y
});
function bc(a) {
  if (Array.isArray(a))
    return a.map((n) => bc(n));
  if (typeof a == "object") {
    var t = {};
    for (var [e, i] of Object.entries(a))
      t[e] = bc(i);
    return t;
  } else
    return a;
}
function xs(a, t = 1) {
  return Array.isArray(a) ? a.flat(t) : a;
}
function up(a, t, e = 1e-9) {
  if (Array.isArray(a) && Array.isArray(t))
    return a.length === t.length && a.every((s, r) => up(s, t[r]));
  if (typeof a == "object" && typeof t == "object") {
    var i = Object.keys(a), n = Object.keys(t);
    return i.length == n.length && i.every((s) => Object.prototype.hasOwnProperty.call(t, s)) ? i.every((s) => up(a[s], t[s])) : !1;
  } else
    return Number(a) === a && Number(t) === t ? Math.abs(a - t) < e : a === t;
}
function R_(a, t) {
  a && (t(a), a.children && a.children.length > 0 && a.children.forEach((e) => {
    R_(e, t);
  }));
}
function P_(a) {
  var t;
  if (a) {
    a.dispose();
    for (const e of Object.values(a.attributes))
      (t = e == null ? void 0 : e.dispose) == null || t.call(e);
  }
}
function AE(a) {
  a.geometry && P_(a.geometry), a.material && (Array.isArray(a.material) ? a.material.forEach((t) => t.dispose()) : a.material.dispose());
}
function me(a) {
  a && (Array.isArray(a.children) && a.children.forEach(me), a.dispose ? a.dispose() : Array.isArray(a) ? a.forEach(me) : (a.isMesh || a.isLine) && AE(a));
}
class EE {
  constructor() {
    k(this, "getshortcuts", (t) => this.keyMapping[t].replace("Key", ""));
    k(this, "get", (t, e) => t[this.keyMapping[e]]);
    k(this, "set", (t) => {
      for (var e in t)
        this.keyMapping[e] = t[e];
    });
    this.keyMapping = {
      shift: "ctrlKey",
      ctrl: "shiftKey",
      meta: "altKey",
      alt: "metaKey"
    };
  }
  get_config() {
    return Object.assign({}, this.keyMapping);
  }
}
function kl(a) {
  return Math.round(Math.PI * a);
}
const De = new EE();
class TE {
  constructor() {
    k(this, "add", (t, e, i, n = !1) => {
      t.addEventListener(e, i, n), this.listeners.push({
        target: t,
        event: e,
        handler: i,
        options: n
      });
    });
    this.listeners = [];
  }
  dispose() {
    this.listeners.forEach(({ target: t, event: e, handler: i, options: n }) => {
      t.removeEventListener(e, i, n);
    }), this.listeners = [];
  }
}
class Ya {
  constructor(t, e, i, n) {
    k(this, "_notify", (t, e = !0) => {
      if (this.type == "plane") {
        const i = {};
        i[`clip_slider_${this.index - 1}`] = parseFloat(t), this.display.viewer.checkChanges(i, e);
      }
    });
    k(this, "sliderChange", (t) => {
      const e = t.target.value;
      this.input.value = Math.round(1e3 * e) / 1e3, this._handle(this.type, this.index, this.input.value), this._notify(e);
    });
    k(this, "inputChange", (t) => {
      const e = Math.max(
        Math.min(t.target.value, this.slider.max),
        this.slider.min
      );
      this.slider.value = e, this._handle(this.type, this.index, this.input.value), this._notify(e);
    });
    t.startsWith("plane") ? (this.index = parseInt(t.substring(5)), this.type = "plane") : (this.index = void 0, this.type = t), this.display = n, this.slider = n.container.getElementsByClassName(
      `tcv_sld_value_${t}`
    )[0], this.slider.min = e, this.slider.max = i, this.input = n.container.getElementsByClassName(
      `tcv_inp_value_${t}`
    )[0], this.input.value = i, this.slider.oninput = this.sliderChange, this.input.addEventListener("change", this.inputChange);
  }
  _handle(t, e, i) {
    t == "plane" ? this.display.refreshPlane(e, i) : t === "ambientlight" ? this.display.viewer.ready && this.display.viewer.setAmbientLight(i / 100) : t === "pointlight" ? this.display.viewer.ready && this.display.viewer.setDirectLight(i / 100) : t === "metalness" ? this.display.viewer.ready && this.display.viewer.setMetalness(i / 100) : t === "roughness" && this.display.viewer.ready && this.display.viewer.setRoughness(i / 100);
  }
  setSlider(t) {
    const e = Math.abs(Math.round(Math.log10(2 * t)));
    this.slider.min = -t, this.slider.max = t, this.slider.step = Math.pow(10, -(3 - e)), this.slider.value = t, this.input.value = Math.round(1e3 * this.slider.max) / 1e3, this.display.refreshPlane(this.index, this.input.value);
  }
  getValue() {
    return parseFloat(this.input.value);
  }
  setValue(t, e = !0) {
    const i = Math.max(
      Math.min(t, this.slider.max),
      this.slider.min
    );
    this.input.value = Math.round(1e3 * i) / 1e3, this.slider.value = t, this._handle(this.type, this.index, this.input.value), this._notify(t, e);
  }
}
class CE {
  constructor(t, e, i) {
    k(this, "minimize", (t = null) => {
      this._toggle(!0, t);
    });
    k(this, "maximize", (t = null) => {
      this._toggle(!0), this._toggle(!1, t);
    });
    this.id = e, this.container = t, this.display = i, this.container.addEventListener("mouseleave", (n) => {
      (this.display.glass ? this.display.cadWidth : this.display.cadWidth + this.display.treeWidth) < this.display.widthThreshold() && this.minimize();
    }), this.buttons = {}, this.ellipses = [], this.toggles = { 0: [], 1: [], 2: [], 3: [] };
  }
  addButton(t, e) {
    t.setId(this.id), this.buttons[t.name] = t, e != -1 && this.toggles[e].push(t), this.container.appendChild(t.html);
  }
  addSeparator() {
    var t = document.createElement("span");
    t.className = "tcv_separator", this.container.appendChild(t);
  }
  addEllipsis(t) {
    this.container.appendChild(t.html), this.ellipses.push(t.html);
  }
  defineGroup(t) {
    for (var e of t)
      for (var i of t)
        i != e && e.addGroupMember(i);
  }
  _toggle(t, e = null) {
    var i, n;
    e == null ? (i = this.toggles, n = this.ellipses) : (i = {}, i[e] = this.toggles[e], n = [this.ellipses[e]]);
    for (var s of n)
      t ? s.classList.remove("tcv_unvisible") : s.classList.add("tcv_unvisible");
    for (var r in i)
      for (var o of i[r])
        !t && (o.name === "distance" && !this.display.measureTools || o.name === "properties" && !this.display.measureTools || o.name === "select" && !this.display.selectTool || o.name === "explode" && !this.display.explodeTool) || o.show(!t);
  }
}
class Vl {
  constructor(t, e) {
    this.id = t, this.action = e;
    var i = document.createElement("span");
    i.innerHTML = "...", i.className = "tcv_ellipsis tcv_unvisible", this.html = i, this.html.addEventListener("mouseenter", (n) => {
      this.action(this.id);
    });
  }
}
class I_ {
  constructor(t, e, i) {
    // eslint-disable-next-line no-unused-vars
    k(this, "handler", (t) => {
      console.log("not implemented yet");
    });
    this.name = e;
    var n = document.createElement("span");
    n.className = "tcv_tooltip", n.setAttribute("data-tooltip", i);
    var s = n.appendChild(document.createElement("span"));
    s.className = "tcv_button_frame", s.appendChild(document.createElement("input")), s.children[0].className = "tcv_reset tcv_btn", s.children[0].type = "button", s.children[0].classList.add(`tcv_button_${e}`), this.html = n, this.html.addEventListener("click", (r) => {
      this.handler(r);
    });
  }
  dispose() {
    this.html = "", this.container.removeEventListener("click", this.handler);
  }
  setId(t) {
    this.containerId = t;
  }
  alignRight() {
    this.html.classList.add("tcv_align_right");
  }
  show(t) {
    this.html.style.display = t ? "inline-block" : "none";
  }
}
class Ki extends I_ {
  constructor(e, i, n, s) {
    super(e, i, n);
    // eslint-disable-next-line no-unused-vars
    k(this, "handler", (e) => {
      this.action(this.name, De.get(e, "shift"));
    });
    k(this, "highlight", (e) => {
      e ? this.html.firstChild.classList.add("tcv_btn_highlight") : this.html.firstChild.classList.remove("tcv_btn_highlight");
    });
    this.action = s;
  }
}
class Qi extends I_ {
  constructor(e, i, n, s, r = !1, o = null) {
    super(e, i, n);
    k(this, "get", () => this.state);
    k(this, "set", (e) => {
      this.state = e, this.html.children[0].classList.toggle("tcv_btn_click2", this.state);
    });
    k(this, "clearGroup", () => {
      for (var e of this.sameGroup)
        e.state && (e.state = !1, e.html.children[0].classList.remove("tcv_btn_click2"), e.action(this.name, !1));
    });
    k(this, "extractIdFromName", (e) => {
      const i = "grid-", n = e.indexOf(i) + i.length, s = e.indexOf("_", n);
      return e.slice(n, s);
    });
    k(this, "handler", (e) => {
      const i = this.extractIdFromName(e.target.id);
      if (this.dropdown != null && i && this.dropdown.includes(i)) {
        const n = e.target.checked;
        this.action(`grid-${i}`, n), this.checkElems[i].checked = n;
      } else e.target.type === "button" && (this.state || this.clearGroup(), this.set(!this.state), this.action(this.name, this.state));
    });
    if (this.action = s, this.state = r, this.dropdown = o, this.sameGroup = [], this.checkElems = {}, o != null) {
      const h = document.createElement("span");
      h.classList.add("tcv_grid-content"), h.classList.add("tcv_dropdown-content"), h.classList.add("tcv_round");
      for (var l of o) {
        const c = document.createElement("div");
        c.className = "tcv_tooltip", c.setAttribute("data-tooltip", `${n} ${l}`), c.innerHTML = `<input class='tcv_grid-${l} tcv_check tcv_dropdown-entry' id='tcv_grid-${l}_${this.containerId}' type="checkbox"><label for='tcv_grid-${l}_${this.containerId}' class="tcv_label tcv_dropdown-entry">${l}</label>`, h.appendChild(c), this.checkElems[l] = c.children[0];
      }
      this.html.children[0].appendChild(h), this.html.children[0].classList.add("tcv_grid-dropdown");
    }
  }
  addGroupMember(e) {
    this.sameGroup.push(e);
  }
}
const ag = new we(), Hl = new E();
let ff = class extends ou {
  /**
   * Constructs a new line segments geometry.
   */
  constructor() {
    super(), this.isLineSegmentsGeometry = !0, this.type = "LineSegmentsGeometry";
    const t = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0], e = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2], i = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5];
    this.setIndex(i), this.setAttribute("position", new wt(t, 3)), this.setAttribute("uv", new wt(e, 2));
  }
  /**
   * Applies the given 4x4 transformation matrix to the geometry.
   *
   * @param {Matrix4} matrix - The matrix to apply.
   * @return {LineSegmentsGeometry} A reference to this instance.
   */
  applyMatrix4(t) {
    const e = this.attributes.instanceStart, i = this.attributes.instanceEnd;
    return e !== void 0 && (e.applyMatrix4(t), i.applyMatrix4(t), e.needsUpdate = !0), this.boundingBox !== null && this.computeBoundingBox(), this.boundingSphere !== null && this.computeBoundingSphere(), this;
  }
  /**
   * Sets the given line positions for this geometry. The length must be a multiple of six since
   * each line segment is defined by a start end vertex in the pattern `(xyz xyz)`.
   *
   * @param {Float32Array|Array<number>} array - The position data to set.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  setPositions(t) {
    let e;
    t instanceof Float32Array ? e = t : Array.isArray(t) && (e = new Float32Array(t));
    const i = new vc(e, 6, 1);
    return this.setAttribute("instanceStart", new un(i, 3, 0)), this.setAttribute("instanceEnd", new un(i, 3, 3)), this.instanceCount = this.attributes.instanceStart.count, this.computeBoundingBox(), this.computeBoundingSphere(), this;
  }
  /**
   * Sets the given line colors for this geometry. The length must be a multiple of six since
   * each line segment is defined by a start end color in the pattern `(rgb rgb)`.
   *
   * @param {Float32Array|Array<number>} array - The position data to set.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  setColors(t) {
    let e;
    t instanceof Float32Array ? e = t : Array.isArray(t) && (e = new Float32Array(t));
    const i = new vc(e, 6, 1);
    return this.setAttribute("instanceColorStart", new un(i, 3, 0)), this.setAttribute("instanceColorEnd", new un(i, 3, 3)), this;
  }
  /**
   * Setups this line segments geometry from the given wireframe geometry.
   *
   * @param {WireframeGeometry} geometry - The geometry that should be used as a data source for this geometry.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  fromWireframeGeometry(t) {
    return this.setPositions(t.attributes.position.array), this;
  }
  /**
   * Setups this line segments geometry from the given edges geometry.
   *
   * @param {EdgesGeometry} geometry - The geometry that should be used as a data source for this geometry.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  fromEdgesGeometry(t) {
    return this.setPositions(t.attributes.position.array), this;
  }
  /**
   * Setups this line segments geometry from the given mesh.
   *
   * @param {Mesh} mesh - The mesh geometry that should be used as a data source for this geometry.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  fromMesh(t) {
    return this.fromWireframeGeometry(new Zp(t.geometry)), this;
  }
  /**
   * Setups this line segments geometry from the given line segments.
   *
   * @param {LineSegments} lineSegments - The line segments that should be used as a data source for this geometry.
   * Assumes the source geometry is not using indices.
   * @return {LineSegmentsGeometry} A reference to this geometry.
   */
  fromLineSegments(t) {
    const e = t.geometry;
    return this.setPositions(e.attributes.position.array), this;
  }
  computeBoundingBox() {
    this.boundingBox === null && (this.boundingBox = new we());
    const t = this.attributes.instanceStart, e = this.attributes.instanceEnd;
    t !== void 0 && e !== void 0 && (this.boundingBox.setFromBufferAttribute(t), ag.setFromBufferAttribute(e), this.boundingBox.union(ag));
  }
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new Re()), this.boundingBox === null && this.computeBoundingBox();
    const t = this.attributes.instanceStart, e = this.attributes.instanceEnd;
    if (t !== void 0 && e !== void 0) {
      const i = this.boundingSphere.center;
      this.boundingBox.getCenter(i);
      let n = 0;
      for (let s = 0, r = t.count; s < r; s++)
        Hl.fromBufferAttribute(t, s), n = Math.max(n, i.distanceToSquared(Hl)), Hl.fromBufferAttribute(e, s), n = Math.max(n, i.distanceToSquared(Hl));
      this.boundingSphere.radius = Math.sqrt(n), isNaN(this.boundingSphere.radius) && console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.", this);
    }
  }
  toJSON() {
  }
};
bt.line = {
  worldUnits: { value: 1 },
  linewidth: { value: 1 },
  resolution: { value: new J(1, 1) },
  dashOffset: { value: 0 },
  dashScale: { value: 1 },
  dashSize: { value: 1 },
  gapSize: { value: 1 }
  // todo FIX - maybe change to totalSize
};
fi.line = {
  uniforms: Oc.merge([
    bt.common,
    bt.fog,
    bt.line
  ]),
  vertexShader: (
    /* glsl */
    `
		#include <common>
		#include <color_pars_vertex>
		#include <fog_pars_vertex>
		#include <logdepthbuf_pars_vertex>
		#include <clipping_planes_pars_vertex>

		uniform float linewidth;
		uniform vec2 resolution;

		attribute vec3 instanceStart;
		attribute vec3 instanceEnd;

		attribute vec3 instanceColorStart;
		attribute vec3 instanceColorEnd;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#ifdef USE_DASH

			uniform float dashScale;
			attribute float instanceDistanceStart;
			attribute float instanceDistanceEnd;
			varying float vLineDistance;

		#endif

		void trimSegment( const in vec4 start, inout vec4 end ) {

			// trim end segment so it terminates between the camera plane and the near plane

			// conservative estimate of the near plane
			float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
			float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
			float nearEstimate = - 0.5 * b / a;

			float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );

			end.xyz = mix( start.xyz, end.xyz, alpha );

		}

		void main() {

			#ifdef USE_COLOR

				vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;

			#endif

			#ifdef USE_DASH

				vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
				vUv = uv;

			#endif

			float aspect = resolution.x / resolution.y;

			// camera space
			vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
			vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );

			#ifdef WORLD_UNITS

				worldStart = start.xyz;
				worldEnd = end.xyz;

			#else

				vUv = uv;

			#endif

			// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
			// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
			// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
			// perhaps there is a more elegant solution -- WestLangley

			bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column

			if ( perspective ) {

				if ( start.z < 0.0 && end.z >= 0.0 ) {

					trimSegment( start, end );

				} else if ( end.z < 0.0 && start.z >= 0.0 ) {

					trimSegment( end, start );

				}

			}

			// clip space
			vec4 clipStart = projectionMatrix * start;
			vec4 clipEnd = projectionMatrix * end;

			// ndc space
			vec3 ndcStart = clipStart.xyz / clipStart.w;
			vec3 ndcEnd = clipEnd.xyz / clipEnd.w;

			// direction
			vec2 dir = ndcEnd.xy - ndcStart.xy;

			// account for clip-space aspect ratio
			dir.x *= aspect;
			dir = normalize( dir );

			#ifdef WORLD_UNITS

				vec3 worldDir = normalize( end.xyz - start.xyz );
				vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );
				vec3 worldUp = normalize( cross( worldDir, tmpFwd ) );
				vec3 worldFwd = cross( worldDir, worldUp );
				worldPos = position.y < 0.5 ? start: end;

				// height offset
				float hw = linewidth * 0.5;
				worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;

				// don't extend the line if we're rendering dashes because we
				// won't be rendering the endcaps
				#ifndef USE_DASH

					// cap extension
					worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;

					// add width to the box
					worldPos.xyz += worldFwd * hw;

					// endcaps
					if ( position.y > 1.0 || position.y < 0.0 ) {

						worldPos.xyz -= worldFwd * 2.0 * hw;

					}

				#endif

				// project the worldpos
				vec4 clip = projectionMatrix * worldPos;

				// shift the depth of the projected points so the line
				// segments overlap neatly
				vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
				clip.z = clipPose.z * clip.w;

			#else

				vec2 offset = vec2( dir.y, - dir.x );
				// undo aspect ratio adjustment
				dir.x /= aspect;
				offset.x /= aspect;

				// sign flip
				if ( position.x < 0.0 ) offset *= - 1.0;

				// endcaps
				if ( position.y < 0.0 ) {

					offset += - dir;

				} else if ( position.y > 1.0 ) {

					offset += dir;

				}

				// adjust for linewidth
				offset *= linewidth;

				// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
				offset /= resolution.y;

				// select end
				vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;

				// back to clip space
				offset *= clip.w;

				clip.xy += offset;

			#endif

			gl_Position = clip;

			vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation

			#include <logdepthbuf_vertex>
			#include <clipping_planes_vertex>
			#include <fog_vertex>

		}
		`
  ),
  fragmentShader: (
    /* glsl */
    `
		uniform vec3 diffuse;
		uniform float opacity;
		uniform float linewidth;

		#ifdef USE_DASH

			uniform float dashOffset;
			uniform float dashSize;
			uniform float gapSize;

		#endif

		varying float vLineDistance;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#include <common>
		#include <color_pars_fragment>
		#include <fog_pars_fragment>
		#include <logdepthbuf_pars_fragment>
		#include <clipping_planes_pars_fragment>

		vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {

			float mua;
			float mub;

			vec3 p13 = p1 - p3;
			vec3 p43 = p4 - p3;

			vec3 p21 = p2 - p1;

			float d1343 = dot( p13, p43 );
			float d4321 = dot( p43, p21 );
			float d1321 = dot( p13, p21 );
			float d4343 = dot( p43, p43 );
			float d2121 = dot( p21, p21 );

			float denom = d2121 * d4343 - d4321 * d4321;

			float numer = d1343 * d4321 - d1321 * d4343;

			mua = numer / denom;
			mua = clamp( mua, 0.0, 1.0 );
			mub = ( d1343 + d4321 * ( mua ) ) / d4343;
			mub = clamp( mub, 0.0, 1.0 );

			return vec2( mua, mub );

		}

		void main() {

			float alpha = opacity;
			vec4 diffuseColor = vec4( diffuse, alpha );

			#include <clipping_planes_fragment>

			#ifdef USE_DASH

				if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps

				if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX

			#endif

			#ifdef WORLD_UNITS

				// Find the closest points on the view ray and the line segment
				vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
				vec3 lineDir = worldEnd - worldStart;
				vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );

				vec3 p1 = worldStart + lineDir * params.x;
				vec3 p2 = rayEnd * params.y;
				vec3 delta = p1 - p2;
				float len = length( delta );
				float norm = len / linewidth;

				#ifndef USE_DASH

					#ifdef USE_ALPHA_TO_COVERAGE

						float dnorm = fwidth( norm );
						alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );

					#else

						if ( norm > 0.5 ) {

							discard;

						}

					#endif

				#endif

			#else

				#ifdef USE_ALPHA_TO_COVERAGE

					// artifacts appear on some hardware if a derivative is taken within a conditional
					float a = vUv.x;
					float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
					float len2 = a * a + b * b;
					float dlen = fwidth( len2 );

					if ( abs( vUv.y ) > 1.0 ) {

						alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );

					}

				#else

					if ( abs( vUv.y ) > 1.0 ) {

						float a = vUv.x;
						float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
						float len2 = a * a + b * b;

						if ( len2 > 1.0 ) discard;

					}

				#endif

			#endif

			#include <logdepthbuf_fragment>
			#include <color_fragment>

			gl_FragColor = vec4( diffuseColor.rgb, alpha );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>
			#include <fog_fragment>
			#include <premultiplied_alpha_fragment>

		}
		`
  )
};
let hu = class extends Xi {
  /**
   * Constructs a new line segments geometry.
   *
   * @param {Object} [parameters] - An object with one or more properties
   * defining the material's appearance. Any property of the material
   * (including any property from inherited materials) can be passed
   * in here. Color values can be passed any type of value accepted
   * by {@link Color#set}.
   */
  constructor(t) {
    super({
      type: "LineMaterial",
      uniforms: Oc.clone(fi.line.uniforms),
      vertexShader: fi.line.vertexShader,
      fragmentShader: fi.line.fragmentShader,
      clipping: !0
      // required for clipping support
    }), this.isLineMaterial = !0, this.setValues(t);
  }
  /**
   * The material's color.
   *
   * @type {Color}
   * @default (1,1,1)
   */
  get color() {
    return this.uniforms.diffuse.value;
  }
  set color(t) {
    this.uniforms.diffuse.value = t;
  }
  /**
   * Whether the material's sizes (width, dash gaps) are in world units.
   *
   * @type {boolean}
   * @default false
   */
  get worldUnits() {
    return "WORLD_UNITS" in this.defines;
  }
  set worldUnits(t) {
    t === !0 ? this.defines.WORLD_UNITS = "" : delete this.defines.WORLD_UNITS;
  }
  /**
   * Controls line thickness in CSS pixel units when `worldUnits` is `false` (default),
   * or in world units when `worldUnits` is `true`.
   *
   * @type {number}
   * @default 1
   */
  get linewidth() {
    return this.uniforms.linewidth.value;
  }
  set linewidth(t) {
    this.uniforms.linewidth && (this.uniforms.linewidth.value = t);
  }
  /**
   * Whether the line is dashed, or solid.
   *
   * @type {boolean}
   * @default false
   */
  get dashed() {
    return "USE_DASH" in this.defines;
  }
  set dashed(t) {
    t === !0 !== this.dashed && (this.needsUpdate = !0), t === !0 ? this.defines.USE_DASH = "" : delete this.defines.USE_DASH;
  }
  /**
   * The scale of the dashes and gaps.
   *
   * @type {number}
   * @default 1
   */
  get dashScale() {
    return this.uniforms.dashScale.value;
  }
  set dashScale(t) {
    this.uniforms.dashScale.value = t;
  }
  /**
   * The size of the dash.
   *
   * @type {number}
   * @default 1
   */
  get dashSize() {
    return this.uniforms.dashSize.value;
  }
  set dashSize(t) {
    this.uniforms.dashSize.value = t;
  }
  /**
   * Where in the dash cycle the dash starts.
   *
   * @type {number}
   * @default 0
   */
  get dashOffset() {
    return this.uniforms.dashOffset.value;
  }
  set dashOffset(t) {
    this.uniforms.dashOffset.value = t;
  }
  /**
   * The size of the gap.
   *
   * @type {number}
   * @default 0
   */
  get gapSize() {
    return this.uniforms.gapSize.value;
  }
  set gapSize(t) {
    this.uniforms.gapSize.value = t;
  }
  /**
   * The opacity.
   *
   * @type {number}
   * @default 1
   */
  get opacity() {
    return this.uniforms.opacity.value;
  }
  set opacity(t) {
    this.uniforms && (this.uniforms.opacity.value = t);
  }
  /**
   * The size of the viewport, in screen pixels. This must be kept updated to make
   * screen-space rendering accurate.The `LineSegments2.onBeforeRender` callback
   * performs the update for visible objects.
   *
   * @type {Vector2}
   */
  get resolution() {
    return this.uniforms.resolution.value;
  }
  set resolution(t) {
    this.uniforms.resolution.value.copy(t);
  }
  /**
   * Whether to use alphaToCoverage or not. When enabled, this can improve the
   * anti-aliasing of line edges when using MSAA.
   *
   * @type {boolean}
   */
  get alphaToCoverage() {
    return "USE_ALPHA_TO_COVERAGE" in this.defines;
  }
  set alphaToCoverage(t) {
    this.defines && (t === !0 !== this.alphaToCoverage && (this.needsUpdate = !0), t === !0 ? this.defines.USE_ALPHA_TO_COVERAGE = "" : delete this.defines.USE_ALPHA_TO_COVERAGE);
  }
};
const od = new Qt(), og = new E(), lg = new E(), Ge = new Qt(), We = new Qt(), xn = new Qt(), ld = new E(), hd = new Vt(), Xe = new x_(), hg = new E(), Gl = new we(), Wl = new Re(), vn = new Qt();
let wn, cr;
function cg(a, t, e) {
  return vn.set(0, 0, -t, 1).applyMatrix4(a.projectionMatrix), vn.multiplyScalar(1 / vn.w), vn.x = cr / e.width, vn.y = cr / e.height, vn.applyMatrix4(a.projectionMatrixInverse), vn.multiplyScalar(1 / vn.w), Math.abs(Math.max(vn.x, vn.y));
}
function RE(a, t) {
  const e = a.matrixWorld, i = a.geometry, n = i.attributes.instanceStart, s = i.attributes.instanceEnd, r = Math.min(i.instanceCount, n.count);
  for (let o = 0, l = r; o < l; o++) {
    Xe.start.fromBufferAttribute(n, o), Xe.end.fromBufferAttribute(s, o), Xe.applyMatrix4(e);
    const h = new E(), c = new E();
    wn.distanceSqToSegment(Xe.start, Xe.end, c, h), c.distanceTo(h) < cr * 0.5 && t.push({
      point: c,
      pointOnLine: h,
      distance: wn.origin.distanceTo(c),
      object: a,
      face: null,
      faceIndex: o,
      uv: null,
      uv1: null
    });
  }
}
function PE(a, t, e) {
  const i = t.projectionMatrix, s = a.material.resolution, r = a.matrixWorld, o = a.geometry, l = o.attributes.instanceStart, h = o.attributes.instanceEnd, c = Math.min(o.instanceCount, l.count), u = -t.near;
  wn.at(1, xn), xn.w = 1, xn.applyMatrix4(t.matrixWorldInverse), xn.applyMatrix4(i), xn.multiplyScalar(1 / xn.w), xn.x *= s.x / 2, xn.y *= s.y / 2, xn.z = 0, ld.copy(xn), hd.multiplyMatrices(t.matrixWorldInverse, r);
  for (let d = 0, p = c; d < p; d++) {
    if (Ge.fromBufferAttribute(l, d), We.fromBufferAttribute(h, d), Ge.w = 1, We.w = 1, Ge.applyMatrix4(hd), We.applyMatrix4(hd), Ge.z > u && We.z > u)
      continue;
    if (Ge.z > u) {
      const x = Ge.z - We.z, _ = (Ge.z - u) / x;
      Ge.lerp(We, _);
    } else if (We.z > u) {
      const x = We.z - Ge.z, _ = (We.z - u) / x;
      We.lerp(Ge, _);
    }
    Ge.applyMatrix4(i), We.applyMatrix4(i), Ge.multiplyScalar(1 / Ge.w), We.multiplyScalar(1 / We.w), Ge.x *= s.x / 2, Ge.y *= s.y / 2, We.x *= s.x / 2, We.y *= s.y / 2, Xe.start.copy(Ge), Xe.start.z = 0, Xe.end.copy(We), Xe.end.z = 0;
    const y = Xe.closestPointToPointParameter(ld, !0);
    Xe.at(y, hg);
    const g = py.lerp(Ge.z, We.z, y), m = g >= -1 && g <= 1, v = ld.distanceTo(hg) < cr * 0.5;
    if (m && v) {
      Xe.start.fromBufferAttribute(l, d), Xe.end.fromBufferAttribute(h, d), Xe.start.applyMatrix4(r), Xe.end.applyMatrix4(r);
      const x = new E(), _ = new E();
      wn.distanceSqToSegment(Xe.start, Xe.end, _, x), e.push({
        point: _,
        pointOnLine: x,
        distance: wn.origin.distanceTo(_),
        object: a,
        face: null,
        faceIndex: d,
        uv: null,
        uv1: null
      });
    }
  }
}
let mf = class extends re {
  /**
   * Constructs a new wide line.
   *
   * @param {LineSegmentsGeometry} [geometry] - The line geometry.
   * @param {LineMaterial} [material] - The line material.
   */
  constructor(t = new ff(), e = new hu({ color: Math.random() * 16777215 })) {
    super(t, e), this.isLineSegments2 = !0, this.type = "LineSegments2";
  }
  /**
   * Computes an array of distance values which are necessary for rendering dashed lines.
   * For each vertex in the geometry, the method calculates the cumulative length from the
   * current point to the very beginning of the line.
   *
   * @return {LineSegments2} A reference to this instance.
   */
  computeLineDistances() {
    const t = this.geometry, e = t.attributes.instanceStart, i = t.attributes.instanceEnd, n = new Float32Array(2 * e.count);
    for (let r = 0, o = 0, l = e.count; r < l; r++, o += 2)
      og.fromBufferAttribute(e, r), lg.fromBufferAttribute(i, r), n[o] = o === 0 ? 0 : n[o - 1], n[o + 1] = n[o] + og.distanceTo(lg);
    const s = new vc(n, 2, 1);
    return t.setAttribute("instanceDistanceStart", new un(s, 1, 0)), t.setAttribute("instanceDistanceEnd", new un(s, 1, 1)), this;
  }
  /**
   * Computes intersection points between a casted ray and this instance.
   *
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - The target array that holds the intersection points.
   */
  raycast(t, e) {
    const i = this.material.worldUnits, n = t.camera;
    n === null && !i && console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');
    const s = t.params.Line2 !== void 0 && t.params.Line2.threshold || 0;
    wn = t.ray;
    const r = this.matrixWorld, o = this.geometry, l = this.material;
    cr = l.linewidth + s, o.boundingSphere === null && o.computeBoundingSphere(), Wl.copy(o.boundingSphere).applyMatrix4(r);
    let h;
    if (i)
      h = cr * 0.5;
    else {
      const u = Math.max(n.near, Wl.distanceToPoint(wn.origin));
      h = cg(n, u, l.resolution);
    }
    if (Wl.radius += h, wn.intersectsSphere(Wl) === !1)
      return;
    o.boundingBox === null && o.computeBoundingBox(), Gl.copy(o.boundingBox).applyMatrix4(r);
    let c;
    if (i)
      c = cr * 0.5;
    else {
      const u = Math.max(n.near, Gl.distanceToPoint(wn.origin));
      c = cg(n, u, l.resolution);
    }
    Gl.expandByScalar(c), wn.intersectsBox(Gl) !== !1 && (i ? RE(this, e) : PE(this, n, e));
  }
  onBeforeRender(t) {
    const e = this.material.uniforms;
    e && e.resolution && (t.getViewport(od), this.material.uniforms.resolution.value.set(od.z, od.w));
  }
};
const la = {
  none: null,
  vertex: "vertex",
  edge: "edge",
  face: "face",
  solid: "solid"
}, IE = {
  face: [
    "plane",
    "cylinder",
    "cone",
    "sphere",
    "torus",
    "bezier",
    "bspline",
    "revolution",
    "extrusion",
    "offset",
    "other"
  ],
  edge: [
    "line",
    "circle",
    "ellipse",
    "hyperbola",
    "parabola",
    "bezier",
    "bspline",
    "offset",
    "other"
  ]
};
class LE {
  constructor(t, e) {
    this.obj = t, this.fromSolid = e;
  }
  /**
   * Returns all the faces ObjectGroups that define the solid from the picked object.
   */
  _getSolidObjectGroups(t) {
    const e = t.parent.parent;
    let i;
    for (let n = 0; n < e.children.length; n++) {
      const s = e.children[n];
      if (s.name === e.name + "|faces") {
        i = s;
        break;
      }
    }
    return i.children;
  }
  /**
   * If the picked object is part of a solid, returns all the faces ObjectGroups that define the solid.
   * Otherwise, returns the picked object.
   * @returns {ObjectGroup[]} The picked objects.
   */
  objs() {
    return this.fromSolid ? this._getSolidObjectGroups(this.obj) : [this.obj];
  }
}
class ug {
  constructor(t, e, i, n, s, r, o) {
    /**
     * Handle left mouse button down event
     * @function
     * @param {MouseEvent} e - a DOM MouseEvent
     */
    k(this, "onMouseKeyDown", (t) => {
      this.raycastMode && (t.button == Ze.LEFT || t.button == Ze.RIGHT) && (this.lastPosition = this.camera.getPosition().clone());
    });
    /**
     * Handle left mouse button up event
     * @function
     * @param {MouseEvent} e - a DOM MouseEvent
     */
    k(this, "onMouseKeyUp", (t) => {
      this.raycastMode && (t.button == Ze.LEFT ? this.lastPosition.distanceTo(this.camera.getPosition()) < 1e-6 && this.callback({ mouse: "left", shift: De.get(t, "shift") }) : t.button == Ze.RIGHT && this.lastPosition.distanceTo(this.camera.getPosition()) < 1e-6 && this.callback({ mouse: "right" }));
    });
    /**
     * Handle key down event
     * @function
     * @param {MouseEvent} e - a DOM MouseEvent
     */
    k(this, "onKeyDown", (t) => {
      this.raycastMode && (t.key == "Backspace" ? this.callback({ key: "Backspace" }) : t.key == "Escape" && this.callback({ key: "Escape" }));
    });
    /**
     * Get the current mouse position
     * @function
     * @param {MouseEvent} e - a DOM MouseEvent
     */
    k(this, "onPointerMove", (t) => {
      const e = this.domElement.getBoundingClientRect(), i = e.x + window.scrollX, n = e.y + window.scrollY;
      this.mouse.x = (t.pageX - i) / this.width * 2 - 1, this.mouse.y = -((t.pageY - n) / this.height) * 2 + 1, this.mouseMoved = !0;
    });
    this.camera = t, this.group = r, this.domElement = e, this.width = i, this.height = n, this.threshold = s, this.callback = o, this.raycaster = new __(), this.raycastMode = !1, this.lastPosition = null, this.mouse = new J(), this.mouseMoved = !1, this.filters = {
      topoFilter: [la.none]
    };
  }
  dispose() {
    this.domElement.removeEventListener("mousemove", this.onPointerMove), this.domElement.removeEventListener("mouseup", this.mouseKetUp), this.domElement.removeEventListener("mousedown", this.onMouseKeyDown), this.domElement.removeEventListener("keydown", this.onKeyDown), this.raycastMode = !1, this.groups = null, this.domElement = null, this.camera = null;
  }
  init() {
    this.domElement.addEventListener("mousemove", this.onPointerMove), this.domElement.addEventListener("mouseup", this.onMouseKeyUp, !1), this.domElement.addEventListener("mousedown", this.onMouseKeyDown, !1), this.domElement.addEventListener("keydown", this.onKeyDown, !1), this.raycastMode = !0;
  }
  /**
   * Retrieve all the valid intersected objects by a ray caster from the mouse.
   */
  getIntersectedObjs() {
    this.raycaster.setFromCamera(this.mouse, this.camera.getCamera()), this.raycaster.params.Points.threshold = this.threshold / this.camera.getZoom(), this.raycaster.params.Line2 = { threshold: 4 };
    var t = this.raycaster.intersectObjects(this.group, !0), e = [];
    for (var i in t)
      t[i].object.material.visible && e.push(t[i]);
    return e;
  }
  /**
   * Retrieve all the valid intersected objects by a ray caster from the mouse.
   * The objects are sorted by their distance from the ray. (The closest first)
   */
  getValidIntersectedObjs() {
    var t = [];
    if (this.mouseMoved) {
      const i = this.getIntersectedObjs();
      for (var e of i)
        if (e.object.material.visible) {
          const n = e.object.parent;
          if (n == null || !n.shapeInfo) continue;
          const s = n.shapeInfo.topo;
          s !== "vertex" && IE[s][n.shapeInfo.geomtype];
          const r = n.subtype === "solid";
          (this.filters.topoFilter.includes(la.solid) && r || this.filters.topoFilter.includes(la.none) || this.filters.topoFilter.includes(s)) && t.push(e);
        }
    }
    return t;
  }
}
function dp(a, t) {
  const e = [
    "tcv_x_measure_val",
    "tcv_y_measure_val",
    "tcv_z_measure_val"
  ], i = document.createElement("tr"), n = document.createElement("th");
  n.textContent = a, n.classList.add("tcv_measure_key"), n.classList.add("tcv_measure_cell"), i.appendChild(n);
  const s = document.createElement("td");
  s.textContent = "(", s.classList.add("tcv_measure_cell_bracket"), i.appendChild(s);
  for (let o = 0; o < 3; ++o) {
    const l = document.createElement("td");
    l.textContent = t[o].toFixed(3), l.classList.add("tcv_measure_val"), l.classList.add("tcv_measure_cell"), l.classList.add(e[o]), i.appendChild(l);
  }
  const r = document.createElement("td");
  return r.textContent = ")", r.classList.add("tcv_measure_cell_bracket"), i.appendChild(r), i;
}
function dg(a, t) {
  const e = document.createElement("tr"), i = document.createElement("th"), n = document.createElement("td");
  return i.textContent = a, i.classList.add("tcv_measure_key"), i.classList.add("tcv_measure_cell"), e.appendChild(i), n.textContent = t, n.classList.add("tcv_measure_val_center"), n.classList.add("tcv_measure_cell"), n.colSpan = 5, e.appendChild(n), e;
}
function pp(a, t, e = null) {
  const i = document.createElement("tr"), n = document.createElement("th"), s = document.createElement("td");
  n.textContent = a, n.classList.add("tcv_measure_key"), n.classList.add("tcv_measure_cell"), i.appendChild(n);
  for (var r = 0; r < 2; r++) {
    const o = document.createElement("td");
    i.appendChild(o);
  }
  if (s.textContent = t.toFixed(3), s.classList.add("tcv_measure_val"), s.classList.add("tcv_measure_cell"), i.appendChild(s), e == null)
    for (var r = 0; r < 2; r++) {
      const l = document.createElement("td");
      i.appendChild(l);
    }
  else {
    const o = document.createElement("td");
    o.textContent = `(${e})`, o.classList.add("tcv_measure_cell"), i.appendChild(o);
    const l = document.createElement("td");
    i.appendChild(l);
  }
  return i;
}
class L_ {
  /**
   * @param {import ("../display.js").Display} display
   */
  constructor(t) {
    /**
     * Show or hide the panel
     * @param {boolean} flag
     */
    k(this, "show", (t) => {
      this.html.style.display = t ? "inline-block" : "none";
    });
    /**
     * Get status of the panel
     */
    k(this, "isVisible", () => this.html.style.display == "inline-block");
    /**
     * Sets the position of the panel (with the top left corner at the specified coordinates)
     * @param {number} x
     * @param {number} y
     */
    k(this, "relocate", (t, e) => {
      this.html.style.left = `${t}px`, this.html.style.top = `${e}px`;
    });
    this.display = t, this.html = this._getHtml(), this.finished = !1, this.callbacks = [], this.html.addEventListener("contextmenu", (e) => {
      e.preventDefault();
    });
  }
  _removeTable() {
    const t = this.html.getElementsByTagName("table");
    t.length > 0 && t[0].remove(), this.finished = !1;
  }
  _getHtml() {
    throw new Error("Not implemented");
  }
  /**
   * Register a callback for a specific event type
   * @param {string} eventType - The type of event to register the callback for
   * @param {CallableFunction} callback - The callback function to register
   */
  registerCallback(t, e) {
    this.callbacks.push({ callback: e, type: t }), this.html.addEventListener(t, e);
  }
  dispose() {
    for (var t of this.callbacks)
      this.html.removeEventListener(t.type, t.callback);
  }
}
class DE extends L_ {
  constructor(t) {
    super(t);
  }
  _getHtml() {
    return this.display._getElement("tcv_distance_measurement_panel");
  }
  createTable(t) {
    if (this.finished) return;
    this._removeTable();
    const e = document.createElement("table");
    e.classList.add("tcv_properties_table");
    const i = document.createElement("tbody");
    for (var n in t) {
      if (!t.hasOwnProperty(n) || [
        "shape_type",
        "geom_type",
        "type",
        "type",
        "tool_type",
        "subtype",
        "info",
        "info1",
        "info2",
        "refpoint1",
        "refpoint2"
      ].includes(n.toLowerCase()))
        continue;
      const r = t[n];
      var s;
      Array.isArray(r) && r.length === 3 ? (s = dp(n, r), i.appendChild(s)) : (n.toLowerCase() === "distance" ? s = pp(n, r, t.info) : s = pp(n, r), i.appendChild(s), n.toLowerCase() == "angle" && (s.classList.add("tcv_measure_cell_top_border"), s = dg("Reference 1", t.info1), i.appendChild(s), s = dg("Reference 2", t.info2), i.appendChild(s))), i.appendChild(s);
    }
    e.appendChild(i), this.html.append(e), this.finished = !0;
  }
}
class FE extends L_ {
  constructor(t) {
    super(t);
  }
  _getHtml() {
    return this.display._getElement("tcv_properties_measurement_panel");
  }
  _setSubHeader(t) {
    this.html.getElementsByClassName("tcv_measure_subheader")[0].textContent = t;
  }
  createTable(t) {
    if (this.finished) return;
    this._removeTable(), this._setSubHeader(
      `${t.shape_type} / ${t.geom_type}`
    );
    const e = document.createElement("table");
    e.classList.add("tcv_properties_table");
    const i = document.createElement("tbody");
    for (var n in t) {
      if (!t.hasOwnProperty(n) || [
        "shape_type",
        "geom_type",
        "type",
        "tool_type",
        "subtype",
        "refpoint"
      ].includes(n.toLowerCase()))
        continue;
      const o = t[n];
      var s;
      if (n.toLowerCase() === "bb")
        for (var r in o) {
          const l = dp(`BB ${r}`, o[r]);
          r === "min" && l.classList.add("tcv_measure_cell_top_border"), i.appendChild(l);
        }
      else Array.isArray(o) && o.length === 3 ? (s = dp(n, o), i.appendChild(s)) : (s = pp(n, o), i.appendChild(s));
      ["length", "area", "volume", "start"].includes(n.toLowerCase()) && s.classList.add("tcv_measure_cell_top_border");
    }
    e.appendChild(i), this.html.append(e), this.finished = !0;
  }
}
class UE {
  /**
   * Initialize a new filter drop down menu, it needs the raycast to update interactively the filter mode
   */
  constructor(t) {
    k(this, "_setValue", (t) => {
      this.raycaster != null && (this.display._getElement("tcv_filter_value").innerText = t, t == "none" ? this.raycaster.filters.topoFilter = [la.none] : this.raycaster.filters.topoFilter = [
        la[t.toLowerCase()]
      ]);
    });
    k(this, "_toggleDropdown", (t) => {
      t != null && t.stopPropagation(), this.dropdownElement.classList.contains("tcv_filter_dropdown_active") ? (this.dropdownElement.classList.remove("tcv_filter_dropdown_active"), this.arrowElement.innerText = "⏶") : (this.dropdownElement.classList.add("tcv_filter_dropdown_active"), this.arrowElement.innerText = "⏷");
    });
    k(this, "_closeDropdown", (t) => {
      this.dropdownElement.classList.contains("tcv_filter_dropdown_active") && this._toggleDropdown(t);
    });
    k(this, "handleSelection", (t) => {
      const e = t.target.innerText;
      this._setValue(e), this._toggleDropdown(t);
    });
    k(this, "reset", () => {
      this._setValue("None");
    });
    k(this, "_keybindSelect", (t) => {
      ["n", "v", "e", "f", "s", "Escape"].indexOf(t.key) !== -1 && (t.key == "n" ? this._setValue("None") : t.key == "v" ? this._setValue("Vertex") : t.key == "e" ? this._setValue("Edge") : t.key == "f" ? this._setValue("Face") : t.key == "s" ? this._setValue("Solid") : t.key == "Escape" && this._closeDropdown());
    });
    this.display = t, this.selectElement = t._getElement("tcv_shape_filter"), this.dropdownElement = t._getElement("tcv_filter_dropdown"), this.arrowElement = t._getElement("tcv_filter_icon"), this.options = ["none", "vertex", "edge", "face", "solid"], this.selectElement.style.display = "none", this.raycaster = null;
  }
  /**
   * Set the raycaster to update the filter mode
   * @param {import ("./../raycast.js").Raycaster } raycaster
   */
  setRaycaster(t) {
    this.raycaster = t;
  }
  /**
   * Show or hide the drop down menu
   * @param {boolean} flag
   */
  show(t) {
    if (t) {
      this.display.container.addEventListener("keydown", this._keybindSelect), this.display.container.addEventListener("click", this._closeDropdown);
      let e = this.display._getElement("tcv_filter_content");
      e.addEventListener("click", this._toggleDropdown);
      for (const i of this.options)
        e = this.display._getElement(`tvc_filter_${i}`), e.addEventListener("click", this.handleSelection);
    } else {
      this.display.container.removeEventListener(
        "keydown",
        this._keybindSelect
      ), this.display.container.removeEventListener("click", this._closeDropdown);
      let e = this.display._getElement("tcv_filter_content");
      e.removeEventListener("click", this._toggleDropdown);
      for (const i of this.options)
        e = this.display._getElement(`tvc_filter_${i}`), e.removeEventListener("click", this.handleSelection);
    }
    this.selectElement.style.display = t ? "block" : "none";
  }
}
class fp extends yi {
  /**
   *
   * @param {THREE.Vector3} point1 The start point of the line
   * @param {THREE.Vector3} point2 The end point of the line
   * @param {number} linewidth The thickness of the line
   * @param {THREE.Color} color The color of the line
   * @param {boolean} arrowStart If true, a cone is added at the start of the line
   * @param {boolean} arrowEnd If true, a cone is added at the end of the line
   */
  constructor(t, e, i, n, s, r = !0, o = !0) {
    super(), this.coneLength = t, this.point1 = e, this.point2 = i, this.linewidth = n, this.color = s, this.arrowStart = r, this.arrowEnd = o, this.type = "DistanceLineArrow", this.lineVec = void 0, this.initialize();
  }
  initialize() {
    const t = this.coneLength;
    this.lineVec = this.point1.clone().sub(this.point2.clone()).normalize();
    let e, i;
    this.arrowStart ? e = this.point1.clone().sub(this.lineVec.clone().multiplyScalar(t / 2)) : e = this.point1.clone(), this.arrowEnd ? i = this.point2.clone().sub(this.lineVec.clone().multiplyScalar(-t / 2)) : i = this.point2.clone();
    const n = new hu({
      linewidth: this.linewidth,
      color: this.color
    }), s = new ff();
    s.setPositions([...e.toArray(), ...i.toArray()]);
    const r = new mf(s, n), o = new Ca(t / 4, t, 10), l = new li({ color: this.color }), h = new re(o, l), c = new re(o, l);
    h.name = "startCone", c.name = "endCone";
    const u = new Vt(), d = new ve();
    u.lookAt(this.point1, this.point2, h.up), d.setFromRotationMatrix(u), h.setRotationFromQuaternion(d), u.lookAt(this.point2, this.point1, c.up), d.setFromRotationMatrix(u), c.setRotationFromQuaternion(d), h.rotateX(90 * Math.PI / 180), c.rotateX(90 * Math.PI / 180), h.position.copy(e), c.position.copy(i), this.arrowStart && this.add(h), this.arrowEnd && this.add(c), this.add(r);
  }
  /**
   * Update the arrow so it keeps the same size on the screen.
   * @param {number} scaleFactor
   */
  update(t) {
    const e = this.point1.clone().sub(
      this.lineVec.clone().multiplyScalar(t * this.coneLength / 2)
    ), i = this.point2.clone().sub(
      this.lineVec.clone().multiplyScalar(-t * this.coneLength / 2)
    );
    if (this.children.find((s) => s.type == "LineSegments2").geometry.setPositions([
      ...this.arrowStart ? e.toArray() : this.point1,
      ...this.arrowEnd ? i.toArray() : this.point2
    ]), this.arrowStart) {
      const s = this.children.find(
        (r) => r.type == "Mesh" && r.name == "startCone"
      );
      s.position.copy(e), s.scale.set(t, t, t);
    }
    if (this.arrowEnd) {
      const s = this.children.find(
        (r) => r.type == "Mesh" && r.name == "endCone"
      );
      s.position.copy(i), s.scale.set(t, t, t);
    }
  }
}
class D_ {
  /**
   *
   * @param {import ("../viewer.js").Viewer} viewer The viewer instance
   * @param {DistancePanel | PropertiesPanel } panel The panel to display the measurement
   */
  constructor(t, e) {
    /**
     * React to each new selected element in the viewer.
     * obj: ObjectGroup
     * fromSolid: boolean
     * @param {object} selectedObj The selected obj.
     */
    k(this, "handleSelection", (t, e = !1) => {
      this.shift = e, this.selectedShapes.find((i) => i.obj.name === t.obj.name) !== void 0 ? this.selectedShapes.splice(this.selectedShapes.indexOf(t), 1) : this.selectedShapes.push(t), this.panel.finished = !1, this._updateMeasurement();
    });
    k(this, "_mouseup", (t) => {
      this.panelDragData.clicked = !1, t.stopPropagation();
    });
    k(this, "_movePanel", () => {
      if (!this.panel.isVisible()) return;
      const t = this.viewer.renderer.domElement.getBoundingClientRect(), e = this.panel.html.getBoundingClientRect();
      if (this.panelX == null && this.middlePoint != null) {
        let c = this.middlePoint.clone().project(this.viewer.camera.getCamera()), u = (c.x + 1) * (t.width / 2), d = (1 - c.y) * (t.height / 2);
        u < t.width / 2 ? this.panelX = u + e.width / 2 : this.panelX = u - e.width - e.width / 2, this.panelX = Math.max(
          0,
          Math.min(t.width - e.width, this.panelX)
        ), this.panelY = d, this.panelY = Math.max(
          0,
          Math.min(t.height - e.height, this.panelY)
        );
      }
      this.panel.relocate(this.panelX, this.panelY);
      const i = this.panelX + e.width / 2, n = this.panelY + e.height / 2, s = i / (t.width / 2) - 1, r = 1 - n / (t.height / 2), o = this.viewer.ortho ? -0.9 : 1;
      var l = new E(s, r, o);
      const h = this.viewer.camera.getCamera();
      h.updateProjectionMatrix(), h.updateMatrixWorld(), this.panelCenter = l.unproject(h), this.scene.children.length > 0 && this._updateConnectionLine();
    });
    /**
     * This handler is responsible to update the panel center vector when the user drag the panel on the screen.
     * @param {Event} e
     * @returns
     */
    k(this, "_dragPanel", (t) => {
      if (!this.panelDragData.clicked) return;
      const e = this.panel.html.getBoundingClientRect(), i = this.viewer.renderer.domElement.getBoundingClientRect();
      let n = t.clientX - this.panelDragData.x, s = t.clientY - this.panelDragData.y;
      e.x + n < i.x && t.movementX <= 0 || e.x + n > i.x + i.width - e.width && t.movementX >= 0 || (this.panelX += n), e.y + s < i.y && t.movementY <= 0 || e.y + s > i.y + i.height - e.height && t.movementY >= 0 || (this.panelY += s), this._updateMeasurement(), this.panelDragData.x = t.clientX, this.panelDragData.y = t.clientY;
    });
    this.selectedShapes = [], this.point1 = null, this.point2 = null, this.middlePoint = null, this.contextEnabled = !1, this.viewer = t, this.scene = new ko(), this.panel = e, this.panelCenter = null, this.panelX = null, this.panelY = null, this.panelShown = !1, this.responseData = null, this.measurementLineColor = 0, this.connectingLineColor = 8388736, this.coneLength = void 0, this.panelDragData = { x: null, y: null, clicked: !1 }, this.panel.registerCallback("mousedown", (i) => {
      this.panelDragData.clicked = !0, this.panelDragData.x = i.clientX, this.panelDragData.y = i.clientY, i.stopPropagation();
    }), this.shift = !1;
  }
  enableContext() {
    this.contextEnabled = !0, this.panelCenter = new E(1, 0, 0), document.addEventListener("mouseup", this._mouseup), document.addEventListener("mousemove", this._dragPanel);
  }
  disableContext() {
    this._hideMeasurement(), this.contextEnabled = !1, this.responseData = null;
    for (var t of this.selectedShapes)
      t.obj.clearHighlights();
    this.selectedShapes = [], document.removeEventListener("mouseup", this._mouseup), document.removeEventListener("mousemove", this._dragPanel), this.viewer.checkChanges({ selectedShapeIDs: [] });
  }
  _hideMeasurement() {
    this.panel.show(!1), this.disposeArrows(), this.scene.clear();
  }
  /**
   * Response handler for the measure context
   * @param {object} response
   */
  handleResponse(t) {
  }
  _createPanel() {
    throw new Error("Subclass needs to override this method");
  }
  _makeLines() {
    throw new Error("Subclass needs to override this method");
  }
  _updateConnectionLine() {
    throw new Error("Subclass needs to override this method");
  }
  /**
   * Get the maximum number of selected obj this measurement can handle
   * @returns {int} The numbers of obj handled by the measurement
   */
  _getMaxObjSelected() {
    throw new Error("Subclass needs to override this method");
  }
  /**
   * Wait for the backend to send the data needed to display the real BREP measurement.
   * @param {*} resolve
   * @param {*} reject
   */
  _waitResponse(t, e) {
    this.responseData ? t(this.responseData) : setTimeout(() => {
      this._waitResponse(t, e);
    }, 100);
  }
  /**
   * Update the measurement panel, if enough shapes have been selected for the current tool,
   * ask the backend for the real measurement data and display it.
   * @returns
   */
  _updateMeasurement() {
    let t = (n) => n.fromSolid ? n.obj.name.replace(/\|faces.*$/, "").replace(/\|edges.*$/, "").replace(/\|vertices.*$/, "").replaceAll("|", "/") : n.obj.name.replaceAll("|", "/");
    const e = this.selectedShapes.map(t);
    if (this.responseData = null, this.debug) {
      const n = 50 + Math.floor(Math.random() * 200);
      setTimeout(() => {
        if (this.selectedShapes.length == 0) return;
        let s;
        if (this instanceof F_) {
          if (this.selectedShapes.length < 2) return;
          var r = this.selectedShapes[0].obj, o = this.selectedShapes[1].obj;
          this.point1 = r.children[0].geometry.boundingSphere.center.clone(), this.point1 = r.localToWorld(this.point1), this.point2 = o.children[0].geometry.boundingSphere.center.clone(), this.point2 = o.localToWorld(this.point2), s = {
            type: "backend_response",
            Distance: 2.345,
            info: "center",
            refpoint1: this.point1.toArray(),
            refpoint2: this.point2.toArray(),
            Angle: 43.21,
            info1: "Plane (Face)",
            info2: "Plane (Face)"
          };
        } else if (this instanceof U_) {
          const l = this.selectedShapes[0].obj, h = l.children[0].geometry.boundingSphere.center.clone();
          this.point1 = l.localToWorld(h), s = {
            type: "backend_response",
            shape_type: "Edge",
            geom_type: "EllipseArc",
            "Major radius": 0.4,
            "Minor radius": 0.2,
            Length: 0.6868592404716374,
            Start: [2.4, -1, 0],
            Center: this.point1.toArray(),
            refpoint: this.point1.toArray(),
            End: [1.8, -0.8267949192431111, 0],
            bb: {
              min: [1.8, -1, 0],
              center: [2.1, -0.9, 0],
              max: [2.4, -0.8, 0],
              size: [0.56, 0.2, 0]
            }
          };
        }
        this.handleResponse(s);
      }, n);
    } else
      this.viewer.checkChanges({
        selectedShapeIDs: [...e, this.shift]
      });
    if (this.selectedShapes.length != this._getMaxObjSelected()) {
      this._hideMeasurement();
      return;
    }
    new Promise((n, s) => {
      this._waitResponse(n, s);
    }).then((n) => {
      this._createPanel(), this._makeLines(), this.panel.show(!0), this._movePanel();
    });
  }
  removeLastSelectedObj(t = !1) {
    if (t || this.selectedShapes.length == this._getMaxObjSelected()) {
      const e = this.selectedShapes.pop();
      if (e) {
        let i = e.objs();
        for (let n of i)
          n.clearHighlights();
      }
      this._updateMeasurement();
    }
  }
  /**
   * Adjust the arrow cones scale factor to ensure they keep the same size on the screen.
   * @param {number} zoom
   */
  _adjustArrowsScaleFactor(t) {
    const e = 1 / t;
    this.scene.children.forEach((i) => i.update(e));
  }
  update() {
    const t = this.viewer.camera.getCamera(), e = this.viewer.camera.getZoom();
    this.coneLength = this.viewer.bb_radius / (Math.max(this.viewer.cadWidth, this.viewer.height) / 60), this._adjustArrowsScaleFactor(e), this.viewer.renderer.clearDepth(), this._movePanel(), this.viewer.renderer.render(this.scene, t);
  }
  disposeArrows() {
    me(this.scene), this.scene.clear();
  }
  dispose() {
    this.panel && (this.panel.show(!1), me(this.panel)), this.disposeArrows(), this.panel = null, this.viewer = null, this.scene = null;
  }
}
class F_ extends D_ {
  constructor(t, e) {
    super(t, new DE(t.display)), this.point1 = null, this.point2 = null, this.middlePoint = null, this.debug = e;
  }
  _createPanel() {
    this.panel.createTable(this.responseData);
  }
  _getMaxObjSelected() {
    return 2;
  }
  _getPoints() {
    this.point1 = new E(...this.responseData.refpoint1), this.point2 = new E(...this.responseData.refpoint2);
  }
  _makeLines() {
    if (this.scene.children.length === 0) {
      const e = new fp(
        this.coneLength,
        this.point1,
        this.point2,
        3,
        this.measurementLineColor
      );
      this.scene.add(e), this.middlePoint = new E().addVectors(this.point1, this.point2).multiplyScalar(0.5);
      const i = new fp(
        this.coneLength,
        this.panelCenter,
        this.middlePoint,
        1.5,
        this.connectingLineColor,
        !1,
        !1
      );
      this.scene.add(i);
    }
  }
  _updateConnectionLine() {
    this.scene.children[1].children[0].geometry.setPositions([
      ...this.middlePoint,
      ...this.panelCenter
    ]);
  }
  /**
   * Handle the response from the backend.
   * @param {object} response
   */
  handleResponse(t) {
    this.responseData = { ...t }, this._getPoints();
  }
}
class U_ extends D_ {
  constructor(t, e) {
    super(t, new FE(t.display)), this.middlePoint = null, this.debug = e;
  }
  _createPanel() {
    this.panel.createTable(this.responseData);
  }
  _getMaxObjSelected() {
    return 1;
  }
  _getPoint() {
    this.point1 = new E(...this.responseData.refpoint);
  }
  _makeLines() {
    if (this.scene.children.length === 0) {
      this.middlePoint = this.point1;
      const t = 1.5, e = new fp(
        this.coneLength,
        this.panelCenter,
        this.middlePoint,
        t,
        this.connectingLineColor,
        !1,
        !1
      );
      this.scene.add(e);
    }
  }
  _updateConnectionLine() {
    this.scene.children[0].children[0].geometry.setPositions([
      ...this.middlePoint,
      ...this.panelCenter
    ]);
  }
  /**
   * Handle the response from the backend.
   * @param {object} response
   */
  handleResponse(t) {
    this.responseData = { ...t }, this._getPoint();
  }
}
class BE {
  constructor(t) {
    this.viewer = t, this.selectedShapes = [], this.contextEnabled = !1;
  }
  enableContext() {
    this.contextEnabled = !0;
  }
  disableContext() {
    this.contextEnabled = !1;
    for (var t of this.selectedShapes)
      t.obj.clearHighlights();
    this.selectedShapes = [];
  }
  _getMaxObjSelected() {
    return null;
  }
  _getIndex(t) {
    const e = t.split("|");
    return e[e.length - 1].split("_")[1];
  }
  _includes(t) {
    for (var e of this.selectedShapes)
      if (t === e.obj.name)
        return !0;
    return !1;
  }
  notify() {
    var t = [];
    for (let i of this.selectedShapes) {
      var e = i.obj.name;
      t.push(this._getIndex(e));
    }
    this.viewer.checkChanges({ selected: t }, !0);
  }
  handleSelection(t) {
    if (t) {
      var e = t.obj.name;
      this._includes(e) ? this.selectedShapes = this.selectedShapes.filter(
        (i) => i.obj.name !== e
      ) : this.selectedShapes.push(t), this.notify();
    }
  }
  _removeLastSelectedObj(t) {
    if (t) {
      let e = t.objs();
      for (let i of e)
        i.clearHighlights();
    }
    this.notify();
  }
  removeLastSelectedObj(t) {
    if (t) {
      for (var e of this.selectedShapes)
        this._removeLastSelectedObj(e);
      this.selectedShapes = [];
    } else {
      const i = this.selectedShapes.pop();
      this._removeLastSelectedObj(i), this.notify();
    }
  }
  update() {
  }
  dispose() {
    this.disableContext();
  }
}
const Ue = {
  NONE: "None",
  DISTANCE: "DistanceMeasurement",
  PROPERTIES: "PropertiesMeasurement",
  SELECT: "SelectObjects"
};
class zE {
  /**
   *
   * @param {import ("../viewer.js").Viewer} viewer The viewer instance
   */
  constructor(t, e) {
    this.viewer = t, this.distanceMeasurement = new F_(t, e), this.propertiesMeasurement = new U_(t, e), this.selectObject = new BE(t), this.enabledTool = null;
  }
  /**
   * Enables a specific tool. (Disables the currently enabled tool if any)
   * @param {ToolTypes} toolType - The type of tool to enable.
   */
  enable(t) {
    switch (this.enabledTool && this.disable(), t) {
      case Ue.DISTANCE:
        this.distanceMeasurement.enableContext();
        break;
      case Ue.PROPERTIES:
        this.propertiesMeasurement.enableContext();
        break;
      case Ue.SELECT:
        this.selectObject.enableContext();
        break;
      default:
        throw new Error(`Unknown tool type: ${t}`);
    }
    this.enabledTool = t;
  }
  disable() {
    this.enabledTool && (this.viewer.display.shapeFilterDropDownMenu.reset(), this._disable());
  }
  /**
   * Disables the currently enabled tool.
   */
  _disable() {
    if (this.enabledTool) {
      switch (this.enabledTool) {
        case Ue.DISTANCE:
          this.distanceMeasurement.disableContext();
          break;
        case Ue.PROPERTIES:
          this.propertiesMeasurement.disableContext();
          break;
        case Ue.SELECT:
          this.selectObject.disableContext();
          break;
        default:
          throw new Error(`Unknown tool type: ${this.enabledTool}`);
      }
      this.enabledTool = null;
    }
  }
  handleRemoveLastSelection(t = !1) {
    this.distanceMeasurement.contextEnabled ? this.distanceMeasurement.removeLastSelectedObj(t) : this.propertiesMeasurement.contextEnabled ? this.propertiesMeasurement.removeLastSelectedObj(t) : this.selectObject.contextEnabled && this.selectObject.removeLastSelectedObj(!1);
  }
  /**
   * obj: ObjectGroup
   * @param {object} selectedObj The selected obj.
   */
  handleSelectedObj(t, e, i) {
    this.distanceMeasurement.contextEnabled ? (e && this.distanceMeasurement.removeLastSelectedObj(), this.distanceMeasurement.handleSelection(t, i)) : this.propertiesMeasurement.contextEnabled ? (e && this.propertiesMeasurement.removeLastSelectedObj(), this.propertiesMeasurement.handleSelection(t)) : this.selectObject.contextEnabled && this.selectObject.handleSelection(t);
  }
  handleResetSelection() {
    this.distanceMeasurement.contextEnabled ? (this.distanceMeasurement.removeLastSelectedObj(!0), this.distanceMeasurement.removeLastSelectedObj(!0)) : this.propertiesMeasurement.contextEnabled ? this.propertiesMeasurement.removeLastSelectedObj(!0) : this.selectObject.contextEnabled && this.selectObject.removeLastSelectedObj(!0);
  }
  /**
   * Handle the response from the backend.
   * @param {Object} response
   */
  handleResponse(t) {
    switch (t.tool_type) {
      case Ue.DISTANCE:
        this.distanceMeasurement.handleResponse(t);
        break;
      case Ue.PROPERTIES:
        this.propertiesMeasurement.handleResponse(t);
        break;
      case Ue.SELECT:
        this.selectObject.handleResponse(t);
        break;
    }
  }
  /**
   * This is called each time the viewer gets updated
   */
  update() {
    this.distanceMeasurement.contextEnabled ? this.distanceMeasurement.update() : this.propertiesMeasurement.contextEnabled ? this.propertiesMeasurement.update() : this.selectObject.contextEnabled && this.selectObject.update();
  }
  dispose() {
    this.distanceMeasurement.dispose(), this.propertiesMeasurement.dispose(), this.selectObject.dispose();
  }
}
var NE = `<div class="tcv_cad_viewer">
    <div class="tcv_cad_toolbar tcv_round"></div>

    <div class="tcv_cad_body">
        <div class="tcv_cad_navigation">
            <div class="tcv_cad_tree tcv_round">
                <div class="tcv_tabnav">
                    <input class='tcv_tab_tree tcv_tab tcv_tab-left tcv_tab-selected' value="Tree" type="button" />
                    <input class='tcv_tab_clip tcv_tab tcv_tab-right tcv_tab-unselected' value="Clipping"
                        type="button" />
                    <input class='tcv_tab_material tcv_tab tcv_tab-right tcv_tab-unselected' value="Material"
                        type="button" />
                </div>
                <div class="tcv_cad_tree_toggles">
                    <span class="tcv_tooltip" data-tooltip="Collpase nodes with a single leaf">
                        <input class='tcv_collapse_singles tcv_btn tcv_small_btn' value="1" type="button" />
                    </span>
                    <span class="tcv_tooltip" data-tooltip="Expand root node only">
                        <input class='tcv_expand_root tcv_btn tcv_small_btn' value="R" type="button" />
                    </span>
                    <span class="tcv_tooltip" data-tooltip="Collpase tree">
                        <input class='tcv_collapse_all tcv_btn tcv_small_btn' value="C" type="button" />
                    </span>
                    <span class="tcv_tooltip" data-tooltip="Expand tree">
                        <input class='tcv_expand tcv_btn tcv_small_btn' value="E" type="button" />
                    </span>
                </div>
                <div class="tcv_box_content tcv_mac-scrollbar tcv_scroller">
                    <div class="tcv_cad_tree_container"></div>
                    <div class="tcv_cad_clip_container">
                        <div class="tcv_slider_group">
                            <div>
                                <span class="tcv_tooltip" data-tooltip="Set red clipping plane to view direction">
                                    <input class='tcv_btn_norm_plane1 tcv_btn tcv_plane' type="button" />
                                </span>
                                <span class="tcv_lbl_norm_plane1 tcv_label">N1 = (n/a, n/a, n/a)</span>
                            </div>
                            <div>
                                <input type="range" min="1" max="100" value="50"
                                    class="tcv_sld_value_plane1 tcv_clip_slider">
                                <input value=50 class="tcv_inp_value_plane1 tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <span class="tooltip" data-tooltip="Set green clipping plane to view direction">
                                    <input class='tcv_btn_norm_plane2 tcv_btn tcv_plane' type="button" />
                                </span>
                                <span class="tcv_lbl_norm_plane2 tcv_label">N2 = (n/a, n/a, n/a)</span>
                            </div>
                            <div>
                                <input type="range" min="1" max="100" value="50"
                                    class="tcv_sld_value_plane2 tcv_clip_slider">
                                <input value=50 class="tcv_inp_value_plane2 tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <span class="tooltip" data-tooltip="Set blue clipping plane to view direction">
                                    <input class='tcv_btn_norm_plane3 tcv_btn tcv_plane' type="button" />
                                </span>
                                <span class="tcv_lbl_norm_plane3 tcv_label">N3 = (n/a, n/a, n/a)</span>
                            </div>
                            <div>
                                <input type="range" min="1" max="100" value="50"
                                    class="tcv_sld_value_plane3 tcv_clip_slider">
                                <input value=50 class="tcv_inp_value_plane3 tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_clip_checks">
                            <div>
                                <span class="tcv_tooltip" data-tooltip="Use intersection clipping">
                                    <input class='tcv_clip_intersection tcv_check' type="checkbox" />
                                    <span class="tcv_label">Intersection</span>
                                </span>
                                <span class="tcv_tooltip" data-tooltip="Show clipping planes">
                                    <input class='tcv_clip_plane_helpers tcv_axes0 tcv_check' type="checkbox" />
                                    <span class="tcv_label">Planes</span>
                                </span>
                            </div>
                            <span class="tcv_tooltip" data-tooltip="Use object color caps instead of RGB">
                                <input class='tcv_clip_caps tcv_axes0 tcv_check' type="checkbox" />
                                <span class="tcv_label">Use object color caps</span>
                            </span>
                        </div>
                    </div>
                    <div class="tcv_cad_material_container">
                        <div class="tcv_cad_tree_toggles">
                            <span class="tcv_tooltip" data-tooltip="Reset to original values">
                                <input class='tcv_material_reset tcv_btn tcv_small_btn' value="R" type="button" />
                            </span>
                        </div>
                        <div class="tcv_material_ambientlight tcv_label">
                            Ambient light intensity (%)
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="20" value="1"
                                    class="tcv_sld_value_ambientlight tcv_clip_slider">
                                <input value=1 class="tcv_inp_value_ambientlight tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_material_pointlight tcv_label">
                            Directional light intensity (%)
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="40" value="1"
                                    class="tcv_sld_value_pointlight tcv_clip_slider">
                                <input value=1 class="tcv_inp_value_pointlight tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_material_metalness tcv_label">
                            Metalness (%)
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="100" value="40"
                                    class="tcv_sld_value_metalness tcv_clip_slider">
                                <input value=40 class="tcv_inp_value_metalness tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_material_roughness tcv_label">
                            Roughness (%)
                        </div>
                        <div class="tcv_slider_group">
                            <div>
                                <input type="range" min="0" max="100" value="40"
                                    class="tcv_sld_value_roughness tcv_clip_slider">
                                <input value=40 class="tcv_inp_value_roughness tcv_clip_input"></input>
                            </div>
                        </div>
                        <div class="tcv_material_info">
                            This is not a full material renderer (e.g. the environment is black), so
                            not every combination creates expected or good results.
                        </div>
                    </div>
                </div>
            </div>
            <div class="tcv_cad_info_wrapper">
                <div class="tcv_toggle_info_wrapper">
                    <!-- <span class="tooltip" data-tooltip="Open/close info box"> -->
                        <!-- <input class='tcv_toggle_info tcv_btn tcv_small_info_btn' value="<" type="button" /> -->
                        <span class='tcv_toggle_info'></span><span class="tcv_info_label">Info</span>
                    <!-- </span> -->
                </div>
                <div class="tcv_cad_info tcv_round">
                    <div class="tcv_box_content tcv_mac-scrollbar tcv_scroller">
                        <div class="tcv_cad_info_container"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="tcv_cad_view">
            <div class="tcv_distance_measurement_panel tcv_panel tcv_round">
                <div class="tcv_measure_header">Distance</div>
            </div>

            <div class="tcv_properties_measurement_panel tcv_panel tcv_round">
                <div class="tcv_measure_header">Properties</div>
                <div class="tcv_measure_subheader">Shape</div>
            </div>

            <div class="tcv_cad_animation tcv_round">
                <span class="tcv_animation_label">E</span>
                <span><input type="range" min="0" max="1000" value="0"
                        class="tcv_animation_slider tcv_clip_slider"></span>
                <span class="tcv_tooltip" data-tooltip="Play animation"><input class='tcv_play tcv_btn'
                        type="button" /></span>
                <span class="tcv_tooltip" data-tooltip="Pause animation"><input class='tcv_pause tcv_btn'
                        type="button" /></span>
                <span class="tcv_tooltip" data-tooltip="Stop and reset animation"><input class='tcv_stop tcv_btn'
                        type="button" /></span>
            </div>
            
            <div class="tcv_cad_zscale tcv_round">
                <span class="tcv_animation_label">Z</span>
                <span><input type="range" min="1" max="32" value="0"
                        class="tcv_zscale_slider tcv_clip_slider"></span>
            </div>

            <div class="tcv_cad_help tcv_round">
                <table class="tcv_cad_help_layout">
                    <tr>
                        <td></td>
                        <td><b>Mouse Navigation</b></td>
                    </tr>
                    <tr>
                        <td>Rotate</td>
                        <td>&lt;left mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Rotate up / down</td>
                        <td>&lt;{{ctrl}}&gt; + &lt;left mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Rotate left / right</td>
                        <td>&lt;{{meta}}&gt; + &lt;left mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Pan</td>
                        <td>&lt;{{shift}}&gt; + &lt;left mouse button&gt; or &lt;right mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Zoom</td>
                        <td>&lt;mouse wheel&gt; or &lt;middle mouse button&gt;</td>
                    </tr>

                    <tr>
                        <td></td>
                        <td><b>Mouse Selection</b></td>
                    </tr>
                    <tr>
                        <td>Pick element</td>
                        <td>&lt;left mouse button&gt; double click</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>Click on navigation tree label</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>(Shows axis-aligned bounding box, AABB)</td>
                    </tr>
                    <tr>
                        <td>Isolate element</td>
                        <td>&lt;{{shift}}&gt; + &lt;left mouse button&gt; double click</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>&lt;{{shift}}&gt; + click on navigation tree label (nested)</td>
                    </tr>
                    <tr>
                        <td>Hide element</td>
                        <td>&lt;{{meta}}&gt; + &lt;left mouse button&gt; double click object</td>
                    </tr>
                    <tr>    
                        <td></td>                
                        <td>&lt;{{meta}}&gt; + &lt;left mouse button&gt; click tree label (nested)</td>
                    </tr>
                    <tr>
                        <td>Hide other elements</td>
                        <td>&lt;{{shift}}&gt; + &lt;{{meta}}&gt; + &lt;left mouse button&gt; click tree label (nested)</td>
                    </tr>
                    <tr>
                        <td>Set camera target</td>
                        <td>&lt;{{shift}}&gt + &lt;{{meta}}&gt; + &lt;left mouse button&gt; double click</td>
                    </tr>                    
                    <tr>
                        <td></td>
                        <td><b>CAD Object Tree</b></td>
                    </tr>
                    <tr>
                        <td>Collapse single leafs</td>
                        <td>Button '1' (all nodes with one leaf only)</td>
                    </tr>
                    <tr>
                        <td>Expand root only</td>
                        <td>Button 'R'</td>
                    </tr>
                    <tr>
                        <td>Collapse all nodes</td>
                        <td>Button 'C'</td>
                    </tr>
                    <tr>
                        <td>Expand all nodes</td>
                        <td>Button 'E'</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td><b>Measure Mode</b></td>
                    </tr>
                    <tr>
                        <td>Select 1. (and 2.) object</td>
                        <td>&lt;left mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Use center instead of min distance</td>
                        <td>&lt;{{shift}}&gt; + &lt;left mouse button&gt; for the second selection</td>
                    </tr>
                    <tr>
                        <td>Filter object types</td>
                        <td>Type menu or &lt;n&gt;one, &lt;s&gt;olid, &lt;f&gt;ace, &lt;e&gt;dge , &lt;v&gt;ertices</td>
                    </tr>
                    <tr>
                        <td>Unselect last object</td>
                        <td>&lt;right mouse button&gt;</td>
                    </tr>
                    <tr>
                        <td>Unselect all objects</td>
                        <td>&lt;ESC&gt;</td>
                    </tr>
                </table>
            </div>
            <div class="tcv_filter_menu">
                <div class="tcv_drop_down tcv_shape_filter">
                    <span class="tcv_round tcv_filter_content"><span class="tcv_filter_value">None</span>
                        <span class="tcv_filter_icon">⏶
                        </span></span>
                    <div class="tcv_filter_dropdown tcv_round">
                        <div class="tcv_filter_dropdown_value tvc_filter_none">None</div>
                        <div class="tcv_filter_dropdown_value tvc_filter_vertex">Vertex</div>
                        <div class="tcv_filter_dropdown_value tvc_filter_edge">Edge</div>
                        <div class="tcv_filter_dropdown_value tvc_filter_face">Face</div>
                        <div class="tcv_filter_dropdown_value tvc_filter_solid">Solid</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="tcv_tick_size">
        ⊢⊣<span class="tcv_tick_size_value">0</span>
    </div>
</div>`;
function OE(a) {
  const t = De.getshortcuts("shift"), e = De.getshortcuts("ctrl"), i = De.getshortcuts("meta"), n = De.getshortcuts("alt");
  var s = NE.replaceAll("{{id}}", a).replaceAll("{{shift}}", t).replaceAll("{{ctrl}}", e).replaceAll("{{meta}}", i).replaceAll("{{alt}}", n);
  return s;
}
function Li(a) {
  return `${a}px`;
}
const kE = ["plane", "play", "pause", "stop"], Nn = new TE();
class VE {
  /**
   * Create Display
   * @param {DOMElement} container - the DOM element, e.g. div, that should contain the Display
   * @param {} options - display options
   */
  constructor(t, e) {
    // handler (bound to Display instance)
    /**
     *
     * @function
     * @param {boolean} flag - to set or not
     */
    k(this, "setAxes", (t, e) => {
      this.viewer.setAxes(e);
    });
    /**
     * Check/uncheck the axes checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the axes checkbox
     */
    k(this, "setAxesCheck", (t) => {
      this.toolbarButtons.axes.set(t);
    });
    /**
     * Checkbox Handler for setting the grid parameter
     * @function
     * @param {boolean} flag - to set or not
     */
    k(this, "setGrid", (t, e) => {
      this.viewer.setGrid(t, e);
    });
    /**
     * Check/uncheck the main grid UI element
     * @function
     * @param {boolean} flag - whether to check or uncheck the main grid checkbox
     */
    k(this, "setGridCheck", (t) => {
      this.checkElement("tcv_grid", t);
    });
    /**
     * Checkbox Handler for setting the axes0 parameter
     * @function
     * @param {boolean} flag - to set or not
     */
    k(this, "setAxes0", (t, e) => {
      this.viewer.setAxes0(e);
    });
    /**
     * Check/uncheck the Axes0 checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the Axes0 checkbox
     */
    k(this, "setAxes0Check", (t) => {
      this.toolbarButtons.axes0.set(t);
    });
    /**
     * Checkbox Handler for setting the ortho parameter
     * @function
     * @param {boolean} flag - to set or not
     */
    k(this, "setOrtho", (t, e) => {
      this.viewer.switchCamera(!e);
    });
    /**
     * Check or uncheck the Ortho checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the ortho checkbox
     */
    k(this, "setOrthoCheck", (t) => {
      this.toolbarButtons.perspective.set(!t);
    });
    /**
     * Checkbox Handler for setting the transparent parameter
     * @function
     * @param {boolean} flag - to set or not
     */
    k(this, "setTransparent", (t, e) => {
      this.viewer.setTransparent(e);
    });
    /**
     * Check or uncheck the Transparent checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the Transparent checkbox
     */
    k(this, "setTransparentCheck", (t) => {
      this.toolbarButtons.transparent.set(t);
    });
    /**
     * Checkbox Handler for setting the black edges parameter
     * @function
     * @param {boolean} flag - to set or not
     */
    k(this, "setBlackEdges", (t, e) => {
      this.viewer.setBlackEdges(e);
    });
    /**
     * Check or uncheck the Black Edges checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the Black Edges checkbox
     */
    k(this, "setBlackEdgesCheck", (t) => {
      this.toolbarButtons.blackedges.set(t);
    });
    /**
     * Checkbox Handler for setting the explode mode
     * @function
     * @param {boolean} flag - to set or not
     */
    k(this, "setExplode", (t, e) => {
      e && this.explodeFlag || !e && !this.explodeFlag || (e ? (this.viewer.hasAnimation() && this.viewer.backupAnimation(), this.viewer.explode(), this.explodeFlag = !0) : (this.viewer.hasAnimation() && (this.controlAnimationByName("stop"), this.viewer.clearAnimation(), this.viewer.restoreAnimation()), this.explodeFlag = !1));
    });
    /**
     * Check or uncheck the Explode checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the Black Edges checkbox
     */
    k(this, "setExplodeCheck", (t) => {
      this.toolbarButtons.explode.set(t);
    });
    /**
     * Show or hide the Explode checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the Black Edges checkbox
     */
    k(this, "showExplode", (t) => {
      const e = this._getElement("tcv_explode_widget");
      e.style.display = t ? "inline-block" : "none";
    });
    /**
     * Checkbox Handler for setting the zscale mode
     * @function
     * @param {boolean} flag - to set or not
     */
    k(this, "setZScale", (t, e) => {
      this.showZScale(e), this.viewer.nestedGroup.setZScale(1), this.viewer.update(!0), this._getElement("tcv_zscale_slider").value = 1;
    });
    /**
     * Show or hide the ZScale slider
     * @function
     * @param {boolean} flag - whether to show the ZScale slider
     */
    k(this, "showZScale", (t) => {
      const e = this._getElement("tcv_cad_zscale");
      e.style.display = t ? "inline-block" : "none";
    });
    /**
     * Check or uncheck the ZScale checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the ZScale checkbox
     */
    k(this, "setZScaleCheck", (t) => {
      this.toolbarButtons.zscale.set(t);
    });
    /**
     * Checkbox Handler for setting the tools mode
     * @function
     * @param {boolean} flag - whether to start or stop measure context
     */
    k(this, "setTool", (t, e) => {
      this.viewer.toggleAnimationLoop(e), e ? (this.showAnimationControl(!1), this.viewer.hasAnimation() && this.viewer.backupAnimation(), ["distance", "properties", "angle", "select"].includes(t) && !["distance", "properties", "angle", "select"].includes(
        this.currentButton
      ) && (this.viewer.toggleGroup(!0), this.viewer.toggleTab(!0)), this.viewer.setRaycastMode(e), this.shapeFilterDropDownMenu.setRaycaster(this.viewer.raycaster), t == "distance" ? (this.viewer.cadTools.enable(Ue.DISTANCE), this.viewer.checkChanges({ activeTool: Ue.DISTANCE })) : t == "properties" ? (this.viewer.cadTools.enable(Ue.PROPERTIES), this.viewer.checkChanges({ activeTool: Ue.PROPERTIES })) : t == "select" && (this.viewer.cadTools.enable(Ue.SELECT), this.viewer.checkChanges({ activeTool: Ue.SELECT })), this.currentButton = t) : ((this.currentButton == t || t == "explode") && (this.viewer.toggleGroup(!1), this.viewer.toggleTab(!1), this.currentButton = null), t == "distance" ? this.viewer.cadTools.disable(Ue.DISTANCE) : t == "properties" ? this.viewer.cadTools.disable(Ue.PROPERTIES) : t == "select" && this.viewer.cadTools.disable(Ue.SELECT), this.viewer.checkChanges({ activeTool: Ue.NONE }), this.viewer.clearSelection(), this.viewer.hasAnimation() && (this.controlAnimationByName("stop"), this.viewer.clearAnimation(), this.viewer.restoreAnimation(), this.showAnimationControl(!0)), this.viewer.setRaycastMode(e)), this.viewer.setPickHandler(!e), this.shapeFilterDropDownMenu.show(e);
    });
    /**
     * Checkbox Handler for setting the clip planes parameter
     * @function
     * @param {Event} e - a DOM click event
     */
    k(this, "setClipPlaneHelpers", (t) => {
      const e = !!t.target.checked;
      this.setClipPlaneHelpersCheck(e), this.viewer.setClipPlaneHelpers(e);
    });
    /**
     * Check or uncheck the Plane Helpers checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the Plane Helpers checkbox
     */
    k(this, "setClipPlaneHelpersCheck", (t) => {
      this.checkElement("tcv_clip_plane_helpers", t), this.lastPlaneState = t;
    });
    /**
     * Show or hide the CAD tools
     * @function
     * @param {boolean} flag - whether to show or hide the CAD tools
     */
    k(this, "showTools", (t) => {
      this.tools = t, this.viewer && (this.viewer.tools = t);
      var e = this._getElement("tcv_cad_toolbar"), i = this._getElement("tcv_cad_navigation");
      t ? (e.style.height = "38px", e.style.display = "flex", i.style.height = "38px", i.style.display = "block") : (e.style.height = "0px", e.style.display = "none", i.style.height = "0px", i.style.display = "none");
    });
    /**
     * Show or hides measurement tools, measurement tools needs a backend to be used.
     * @param {boolean} flag
     */
    k(this, "showMeasureTools", (t) => {
      this.toolbarButtons.distance.show(t), this.toolbarButtons.properties.show(t);
    });
    /**
     * Show or hides measurement tools, measurement tools needs a backend to be used.
     * @param {boolean} flag
     */
    k(this, "showSelectTool", (t) => {
      this.toolbarButtons.select.show(t);
    });
    /**
     * Show or hides explode tool
     * @param {boolean} flag
     */
    k(this, "showExplodeTool", (t) => {
      this.toolbarButtons.explode.show(t);
    });
    /**
     * Show or hides ZScale tool
     * @param {boolean} flag
     */
    k(this, "showZScaleTool", (t) => {
      this.toolbarButtons.zscale.show(t), t || this.showZScale(!1);
    });
    /**
     * Checkbox Handler for setting the clip intersection parameter
     * @function
     * @param {*} e
     */
    k(this, "setClipIntersection", (t) => {
      const e = !!t.target.checked;
      this.viewer.setClipIntersection(e);
    });
    /**
     * Check or uncheck the Intersection checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the Intersection checkbox
     */
    k(this, "setClipIntersectionCheck", (t) => {
      const e = this._getElement("tcv_clip_intersection");
      e.checked = t;
    });
    /**
     * Checkbox Handler for toggling the clip caps
     * @function
     * @param {*} e
     */
    k(this, "setObjectColorCaps", (t) => {
      const e = !!t.target.checked;
      this.viewer.setClipObjectColorCaps(e);
    });
    /**
     * Check or uncheck the Intersection checkbox
     * @function
     * @param {boolean} flag - whether to check or uncheck the object colors checkbox
     */
    k(this, "setClipObjectColorsCheck", (t) => {
      const e = this._getElement("tcv_clip_caps");
      e.checked = t;
    });
    /**
     * Handler to reset position, zoom and up of the camera
     * @function
     */
    k(this, "reset", () => {
      this.viewer.reset(), this.clearHighlights();
    });
    /**
     * Handler to reset zoom of the camera
     * @function
     */
    k(this, "resize", () => {
      this.viewer.resize();
    });
    /**
     * Handler to set camera to a predefined position
     * @function
     * @param {Event} e - a DOM click event
     */
    k(this, "setView", (t, e = !1) => {
      this.viewer.presetCamera(t), e && this.viewer.centerVisibleObjects(), this.highlightButton(t), this.viewer.update(!0, !1);
    });
    /**
     * Pin screenshot of canvas as PNG
     * @function
     * @param {Event} e - a DOM click event
     */
    // eslint-disable-next-line no-unused-vars
    k(this, "pinAsPng", (t) => {
      this.viewer.pinAsPng();
    });
    /**
     * Handler to set the label of a clipping normal widget
     * @function
     * @param {number} index - index of the normal widget
     * @param {Vector3} normal - the normal
     */
    k(this, "setNormalLabel", (t, e) => {
      this.planeLabels[t].innerHTML = `N=(${e[0].toFixed(
        2
      )}, ${e[1].toFixed(2)}, ${e[2].toFixed(2)})`;
    });
    /**
     * Set the normal at index to the current viewing direction
     * @function
     * @param {Event} e - a DOM click event
     */
    k(this, "setClipNormalFromPosition", (t) => {
      const e = parseInt(t.target.classList[0].slice(-1));
      this.viewer.setClipNormalFromPosition(e - 1);
    });
    /**
     * Handler to activate a UI tab (tree / clipping)
     * @function
     * @param {Event} e - a DOM click event
     */
    k(this, "selectTab", (t) => {
      const e = t.target.className.split(" ")[0];
      this.selectTabByName(e.slice(8));
    });
    /**
     * Set the ambient light intensity in the UI
     * @function
     * @param {number} val - a float between 0 and 4
     */
    k(this, "setAmbientLight", (t) => {
      this.ambientlightSlider.setValue(t * 100);
    });
    /**
     * Set the direct light intensity in the UI
     * @function
     * @param {number} val - a float between 0 and 4
     */
    k(this, "setDirectLight", (t) => {
      this.directionallightSlider.setValue(t * 100);
    });
    /**
     * Set material metalness in the UI
     * @function
     * @param {number} val - a float between 0 and 1
     */
    k(this, "setMetalness", (t) => {
      this.metalnessSlider.setValue(t * 100);
    });
    /**
     * Set material roughness in the UI
     * @function
     * @param {number} val - a float between 0 and 1
     */
    k(this, "setRoughness", (t) => {
      this.roughnessSlider.setValue(t * 100);
    });
    /**
     * Reset material values to original values
     * @function
     * @param {Event} e - a DOM click event
     */
    // eslint-disable-next-line no-unused-vars
    k(this, "handleMaterialReset", (t) => {
      this.viewer.resetMaterial();
    });
    /**
     * Toggle visibility of the clipping tab
     * @function
     */
    k(this, "toggleClippingTab", (t) => {
      t ? this.tabClip.removeAttribute("disabled") : this.tabClip.setAttribute("disabled", "true"), this.tabClip.classList.toggle("tcv_tab-disabled", !t);
    });
    /**
     * Collapse nodes handler
     * @function
     * @param {Event} e - a DOM click event
     */
    k(this, "handleCollapseNodes", (t) => {
      this.collapseNodes(t.target.value);
    });
    /**
     * Show or hide the Animation control widget
     * @function
     * @param {boolean} flag - whether to show or hide the Animation control widget
     */
    k(this, "showAnimationControl", (t) => {
      this.cadAnim.style.display = t ? "block" : "none";
    });
    /**
     * Handler for the animation control
     * @function
     * @param {Event} e - a DOM click event
     */
    k(this, "controlAnimation", (t) => {
      const e = t.target.className.split(" ")[0].slice(4);
      this.controlAnimationByName(e);
    });
    /**
     * Handler for the animation slider
     * @function
     * @param {Event} e - a DOM click event
     */
    k(this, "animationChange", (t) => {
      this.viewer.animation.setRelativeTime(t.target.valueAsNumber / 1e3), this.viewer.lastBbox != null && (this.viewer.lastBbox.needsUpdate = !0);
    });
    /**
     * Show or hide help dialog
     * @function
     * @param {boolean} flag - whether to show or hide help dialog
     */
    k(this, "showHelp", (t) => {
      this.cadHelp.style.display = t ? "block" : "none", this.help_shown = t;
    });
    /**
     * Show or hide the distance measurement panel
     * @param {boolean} flag
     */
    k(this, "showDistancePanel", (t) => {
      this.distanceMeasurementPanel.style.display = t ? "block" : "none";
    });
    /**
     * Show or hide the properties measurement panel
     * @param {boolean} flag
     */
    k(this, "showPropertiesPanel", (t) => {
      this.propertiesMeasurementPanel.style.display = t ? "block" : "none";
    });
    /**
     * Show help dialog
     * @function
     */
    k(this, "toggleHelp", () => {
      this.showHelp(!this.help_shown);
    });
    /**
     * Show or hide info dialog
     * @function
     * @param {boolean} flag - whether to show or hide info dialog
     */
    k(this, "showInfo", (t) => {
      this.cadInfo.parentNode.parentNode.style.display = t ? "block" : "none", this._getElement("tcv_toggle_info").innerHTML = t ? "▾" : "▸", this.info_shown = t;
    });
    /**
     * Show info dialog
     * @function
     */
    k(this, "toggleInfo", () => {
      this.showInfo(!this.info_shown);
    });
    this.container = t, this.container.innerHTML = OE(this.container.id), this.cadBody = this._getElement("tcv_cad_body"), this.measureTools = e.measureTools, this.measurementDebug = e.measurementDebug, this.selectTool = e.selectTool, this.explodeTool = e.explodeTool, this.zscaleTool = e.zscaleTool, this.zScale = 1, this.cadTool = new CE(
      this._getElement("tcv_cad_toolbar"),
      t.id,
      this
    ), this.cadView = this._getElement("tcv_cad_view"), this.distanceMeasurementPanel = this._getElement(
      "tcv_distance_measurement_panel"
    ), this.propertiesMeasurementPanel = this._getElement(
      "tcv_properties_measurement_panel"
    ), this.cadTree = this._getElement("tcv_cad_tree_container"), this.cadTreeScrollContainer = this._getElement("tcv_box_content"), this.cadTreeToggles = this._getElement("tcv_cad_tree_toggles"), this.cadClip = this._getElement("tcv_cad_clip_container"), this.cadMaterial = this._getElement("tcv_cad_material_container"), this.tabTree = this._getElement("tcv_tab_tree"), this.tabClip = this._getElement("tcv_tab_clip"), this.tabMaterial = this._getElement("tcv_tab_material"), this.cadInfo = this._getElement("tcv_cad_info_container"), this.cadAnim = this._getElement("tcv_cad_animation"), this.cadTools = this._getElement("tcv_cad_tools"), this.cadHelp = this._getElement("tcv_cad_help"), Nn.add(this.cadHelp, "contextmenu", (r) => (r.preventDefault(), r.stopPropagation(), !1)), this.planeLabels = [];
    for (var i = 1; i < 4; i++)
      this.planeLabels.push(this._getElement(`tcv_lbl_norm_plane${i}`));
    this.viewer = null, this.glass = e.glass, this.tools = e.tools, this.cadWidth = e.cadWidth, this.height = e.height, this.treeWidth = e.treeWidth, this._events = [], this.setSizes(e), this.activeTab = "tree", this.cadTree.style.display = "block", this.cadClip.style.display = "none", this.cadMaterial.style.display = "none", this.clipSliders = null, this.explodeFlag = !1, this.currentButton = null, this.lastPlaneState = !1;
    const n = e.theme;
    if (this.theme = n, this.setButtonBackground(n), this.toolbarButtons = {}, this.toolbarButtons.axes = new Qi(
      n,
      "axes",
      "Show axes",
      this.setAxes
    ), this.cadTool.addButton(this.toolbarButtons.axes, -1), this.cadTool.addEllipsis(new Vl(0, this.cadTool.maximize)), this.toolbarButtons.axes0 = new Qi(
      n,
      "axes0",
      "Show axes at origin (0,0,0)",
      this.setAxes0
    ), this.cadTool.addButton(this.toolbarButtons.axes0, 0), this.toolbarButtons.grid = new Qi(
      n,
      "grid",
      "Show grid",
      this.setGrid,
      null,
      ["xy", "xz", "yz"]
    ), this.cadTool.addButton(this.toolbarButtons.grid, 0), this.cadTool.addSeparator(), this.toolbarButtons.perspective = new Qi(
      n,
      "perspective",
      "Use perspective camera",
      this.setOrtho
    ), this.cadTool.addButton(this.toolbarButtons.perspective, -1), this.cadTool.addEllipsis(new Vl(1, this.cadTool.maximize)), this.toolbarButtons.transparent = new Qi(
      n,
      "transparent",
      "Show transparent faces",
      this.setTransparent
    ), this.cadTool.addButton(this.toolbarButtons.transparent, 1), this.toolbarButtons.blackedges = new Qi(
      n,
      "blackedges",
      "Show black edges",
      this.setBlackEdges
    ), this.cadTool.addButton(this.toolbarButtons.blackedges, 1), this.cadTool.addSeparator(), this.toolbarButtons.reset = new Ki(
      n,
      "reset",
      "Reset view",
      this.reset
    ), this.cadTool.addButton(this.toolbarButtons.reset, -1), this.cadTool.addEllipsis(new Vl(2, this.cadTool.maximize)), this.toolbarButtons.resize = new Ki(
      n,
      "resize",
      "Resize object",
      this.resize
    ), this.cadTool.addButton(this.toolbarButtons.resize, 2), this.toolbarButtons.iso = new Ki(
      n,
      "iso",
      "Switch to iso view",
      this.setView
    ), this.cadTool.addButton(this.toolbarButtons.iso, 2), this.toolbarButtons.front = new Ki(
      n,
      "front",
      "Switch to front view",
      this.setView
    ), this.cadTool.addButton(this.toolbarButtons.front, 2), this.toolbarButtons.rear = new Ki(
      n,
      "rear",
      "Switch to back view",
      this.setView
    ), this.cadTool.addButton(this.toolbarButtons.rear, 2), this.toolbarButtons.top = new Ki(
      n,
      "top",
      "Switch to top view",
      this.setView
    ), this.cadTool.addButton(this.toolbarButtons.top, 2), this.toolbarButtons.bottom = new Ki(
      n,
      "bottom",
      "Switch to bottom view",
      this.setView
    ), this.cadTool.addButton(this.toolbarButtons.bottom, 2), this.toolbarButtons.left = new Ki(
      n,
      "left",
      "Switch to left view",
      this.setView
    ), this.cadTool.addButton(this.toolbarButtons.left, 2), this.toolbarButtons.right = new Ki(
      n,
      "right",
      "Switch to right view",
      this.setView
    ), this.cadTool.addButton(this.toolbarButtons.right, 2), this.cadTool.addSeparator(), this.toolbarButtons.explode = new Qi(
      n,
      "explode",
      "Explode tool",
      this.setExplode
    ), this.explodeTool && !this.zscaleTool && this.cadTool.addButton(this.toolbarButtons.explode, -1), this.toolbarButtons.zscale = new Qi(
      n,
      "zscale",
      "Scale along the Z-axis",
      this.setZScale
    ), this.zscaleTool && !this.explodeTool) {
      this.cadTool.addButton(this.toolbarButtons.zscale, -1), this.showZScale(!1);
      const r = this._getElement("tcv_zscale_slider");
      Nn.add(r, "change", (o) => {
        this.zScale = parseInt(o.target.value), this.viewer.setZscaleValue(o.target.value);
      });
    }
    this.toolbarButtons.distance = new Qi(
      n,
      "distance",
      "Measure distance between shapes",
      this.setTool
    ), this.cadTool.addButton(this.toolbarButtons.distance, 3), (this.measureTools ? 2 : 0) + (this.explodeTool ? 1 : 0) + (this.selectTool ? 1 : 0) + (this.zscaleTool ? 1 : 0) > 1 && this.cadTool.addEllipsis(new Vl(3, this.cadTool.maximize)), this.toolbarButtons.properties = new Qi(
      n,
      "properties",
      "Show shape properties",
      this.setTool
    ), this.cadTool.addButton(this.toolbarButtons.properties, 3), this.toolbarButtons.select = new Qi(
      n,
      "select",
      "Copy shape IDs to clipboard",
      this.setTool
    ), this.cadTool.addButton(this.toolbarButtons.select, 3), this.cadTool.defineGroup([
      this.toolbarButtons.explode,
      this.toolbarButtons.distance,
      this.toolbarButtons.properties,
      this.toolbarButtons.select
    ]), Nn.add(document, "keydown", (r) => {
      r.key === "Escape" && this.help_shown && (r.preventDefault(), this.showHelp(!1));
    }), this.cadTool.addSeparator(), this.toolbarButtons.pin = new Ki(
      n,
      "pin",
      "Pin viewer as png",
      this.pinAsPng
    ), this.toolbarButtons.pin.alignRight(), this.cadTool.addButton(this.toolbarButtons.pin, -1), this.shapeFilterDropDownMenu = new UE(this), this.showPinning(e.pinning), this.toolbarButtons.help = new Ki(
      n,
      "help",
      "Help",
      this.toggleHelp
    ), this.cadTool.addButton(this.toolbarButtons.help, -1);
  }
  setButtonBackground(t) {
    for (var e of kE)
      for (var i = this.container.getElementsByClassName(`tcv_${e}`), n = 0; n < i.length; n++) {
        var s = i[n];
        s.classList.add(`tcv_button_${e}`);
      }
  }
  widthThreshold() {
    var t = 770;
    return this.viewer.pinning || (t -= 30), this.viewer.selectTool || (t -= 30), !this.viewer.explodeTool && !this.zscaleTool && (t -= 30), t;
  }
  _setupCheckEvent(t, e, i) {
    const n = this._getElement(t);
    Nn.add(n, "change", e), i != null && (n.checked = i), this._events.push(["change", t, e]);
  }
  // eslint-disable-next-line no-unused-vars
  _setupClickEvent(t, e, i) {
    const n = this._getElement(t);
    Nn.add(n, "click", e), this._events.push(["click", t, e]);
  }
  /**
   *
   * @param {string} name Name of the DOM element
   * @returns {DOMElement}
   */
  _getElement(t) {
    return this.container.getElementsByClassName(t)[0];
  }
  dispose() {
    Nn.dispose(), this.viewer = void 0, this.cadTree.innerHTML = "", this.cadTree = void 0, this.cadView.removeChild(this.cadView.children[2]), this.container.innerHTML = "", this.container = null, this.cadTreeScrollContainer = null;
  }
  /**
   * Set the width and height of the different UI elements (tree, canvas and info box)
   * @param {DisplayOptions} options
   */
  setSizes(t, e = 2 / 3) {
    if (t.cadWidth && (this.cadWidth = t.cadWidth, this.cadView.style.width = Li(t.cadWidth)), t.height && (this.height = t.height, this.cadView.style.height = Li(t.height)), t.treeWidth && (this.treeWidth = t.treeWidth, this.cadTree.parentElement.parentElement.style.width = Li(
      t.treeWidth
    ), this.cadInfo.parentElement.parentElement.style.width = Li(
      t.treeWidth
    )), !t.glass) {
      const i = Math.round(t.height * e);
      this.cadTree.parentElement.parentElement.style.height = Li(i), this.cadInfo.parentElement.parentElement.style.height = Li(
        t.height - i - 4
      );
    }
    t.tools && !t.glass ? (this.cadTool.container.style.width = Li(
      t.treeWidth + t.cadWidth + 4
    ), this.cadBody.style.width = Li(t.treeWidth + t.cadWidth + 4)) : (this.cadTool.container.style.width = Li(t.cadWidth + 2), this.cadBody.style.width = Li(t.cadWidth + 2)), this.cadBody.style.height = Li(t.height + 4);
  }
  /**
   * Set up the UI
   * @param {Viewer} viewer - the viewer for this UI
   */
  setupUI(t) {
    this.viewer = t, this.theme === "browser" && (this.mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"), Nn.add(this.mediaQuery, "change", (n) => {
      n.matches ? this.setTheme("dark") : this.setTheme("light");
    })), this._setupClickEvent("tcv_expand_root", this.handleCollapseNodes), this._setupClickEvent("tcv_collapse_singles", this.handleCollapseNodes), this._setupClickEvent("tcv_collapse_all", this.handleCollapseNodes), this._setupClickEvent("tcv_expand", this.handleCollapseNodes), this._setupClickEvent("tcv_material_reset", this.handleMaterialReset), this._setupClickEvent("tcv_toggle_info", this.toggleInfo), this.help_shown = !0, this.info_shown = !this.glass, ["tcv_tab_tree", "tcv_tab_clip", "tcv_tab_material"].forEach((n) => {
      this._setupClickEvent(n, this.selectTab);
    }), this.clipSliders = [];
    for (var i = 1; i < 4; i++)
      this.clipSliders.push(new Ya(`plane${i}`, 0, 100, this));
    for (this.ambientlightSlider = new Ya("ambientlight", 0, 400, this), this.directionallightSlider = new Ya("pointlight", 0, 400, this), this.metalnessSlider = new Ya("metalness", 0, 100, this), this.roughnessSlider = new Ya("roughness", 0, 100, this), this._setupCheckEvent(
      "tcv_clip_plane_helpers",
      this.setClipPlaneHelpers,
      !1
    ), this._setupCheckEvent(
      "tcv_clip_intersection",
      this.setClipIntersection,
      !1
    ), this._setupCheckEvent("tcv_clip_caps", this.setObjectColorCaps, !1), i = 1; i < 4; i++)
      this._setupClickEvent(
        `tcv_btn_norm_plane${i}`,
        this.setClipNormalFromPosition,
        !1
      );
    this._setupClickEvent("tcv_play", this.controlAnimation, !1), this._setupClickEvent("tcv_pause", this.controlAnimation, !1), this._setupClickEvent("tcv_stop", this.controlAnimation, !1), this.animationSlider = this.container.getElementsByClassName(
      "tcv_animation_slider"
    )[0], this.animationSlider.value = 0, Nn.add(this.animationSlider, "input", this.animationChange), this.showAnimationControl(!1), this.showHelp(!1), this.showDistancePanel(!1), this.showPropertiesPanel(!1), this.showMeasureTools(this.measureTools), this.showSelectTool(this.selectTool), this.showExplodeTool(this.explodeTool), this.showZScaleTool(this.zscaleTool);
  }
  /**
   * Check or uncheck a checkbox
   * @property {boolean} [axes = false] - show X-, Y-, Z-axes.
   * @property {boolean} [axes0 = false] - show axes at [0,0,0] ot at object center (target).
   * @property {boolean} [ortho = true] - use an orthographic (true) or perspective camera (false)
   * @property {boolean} [transparent = false] - show CAD object transparent.
   * @property {boolean} [blackEdges = false] - show edges in black and not in edgeColor.
   * @property {boolean} [tools = true] - show CAD tools.
   * @property {boolean} [glass = false] - use glass mode, i.e. CAD navigation as overlay.
   */
  updateUI(t, e, i, n, s, r, o) {
    this.toolbarButtons.axes.set(t), this.toolbarButtons.axes0.set(e), this.toolbarButtons.perspective.set(!i), this.toolbarButtons.transparent.set(n), this.toolbarButtons.blackedges.set(s), this.showTools(r), this.glassMode(o), (this.glass ? this.cadWidth : this.cadWidth + this.treeWidth) < this.widthThreshold() && this.cadTool.minimize();
  }
  // setup functions
  /**
   * Check or uncheck a checkbox
   * @param {string} name - name of the check box, see getElement
   * @param {boolean} flag - whether to check or uncheck
   */
  checkElement(t, e) {
    this._getElement(t).checked = e;
  }
  /**
   * Add the Cad View (the canvas for threejs)
   * @param {DOMElement} cadView - the DOM element that contains the cadView
   */
  addCadView(t) {
    var e = this.cadView.querySelector("canvas");
    e ? this.cadView.replaceChild(t, e) : (this.cadView.appendChild(t), e = this.cadView.querySelector("canvas")), Nn.add(e, "click", (i) => {
      this.help_shown && this.showHelp(!1);
    });
  }
  /**
   * Get the DOM canvas element
   */
  getCanvas() {
    return this.cadView.children[this.cadView.children.length - 1];
  }
  /**
   * Clear the Cad tree
   */
  clearCadTree() {
    this.cadTree.innerHTML = "";
  }
  /**
   * Add the Cad tree and other UI elements like Clipping
   * @param {DOMElement} cadTree - the DOM element that contains the cadTree
   */
  addCadTree(t) {
    this.cadTree.appendChild(t);
  }
  /**
   * Clear all highlights of navigation tree entries
   */
  clearHighlights() {
    ["front", "rear", "top", "bottom", "left", "right", "iso"].forEach((e) => {
      var i = this.toolbarButtons[e];
      i.highlight(!1);
    });
  }
  /**
   * Highlight the selected button
   * @param {string} name - A CAD object id (path)
   */
  highlightButton(t) {
    this.clearHighlights();
    var e = this.toolbarButtons[t];
    e.highlight(!0), this.viewer.keepHighlight = !0;
  }
  /**
   * Show/hide pinning button
   * @function
   * @param {boolean} flag - Whether to show/hide the pinning button
   */
  showPinning(t) {
    this.toolbarButtons.pin.show(t);
  }
  /**
   * Activate the UI tab given the name of the tab
   * @param {string} tab - name of the tab "tree" or "clip"
   */
  selectTabByName(t) {
    if (["clip", "tree", "material"].includes(t)) {
      if (t === "tree" && this.activeTab !== "tree") {
        this.cadTree.style.display = "block", this.cadTreeToggles.style.display = "block", this.cadClip.style.display = "none", this.cadMaterial.style.display = "none", this.viewer.nestedGroup.setBackVisible(!1), this.viewer.setLocalClipping(!1), this.viewer.clipping.setVisible(!1);
        var e = this.viewer.getClipPlaneHelpers();
        this.viewer.setClipPlaneHelpers(!1), this.lastPlaneState = e;
      } else t === "clip" && this.activeTab !== "clip" ? (this.cadTree.style.display = "none", this.cadTreeToggles.style.display = "none", this.cadClip.style.display = "block", this.cadMaterial.style.display = "none", this.viewer.nestedGroup.setBackVisible(!0), this.viewer.setLocalClipping(!0), this.viewer.setClipIntersection(this.viewer.clipIntersection), this.viewer.setClipPlaneHelpers(this.lastPlaneState), this.viewer.clipping.setVisible(!0), this.viewer.update(!0, !1)) : t === "material" && this.activeTab !== "material" && (this.cadTree.style.display = "none", this.cadTreeToggles.style.display = "none", this.cadClip.style.display = "none", this.cadMaterial.style.display = "block", this.viewer.nestedGroup.setBackVisible(!1), this.viewer.setLocalClipping(!1), this.viewer.setClipPlaneHelpers(!1), this.viewer.clipping.setVisible(!1));
      this.activeTab = t, this.viewer.checkChanges({ tab: t }), t == "tree" ? (this.tabTree.classList.add("tcv_tab-selected"), this.tabTree.classList.remove("tcv_tab-unselected"), this.tabClip.classList.remove("tcv_tab-selected"), this.tabClip.classList.add("tcv_tab-unselected"), this.tabMaterial.classList.remove("tcv_tab-selected"), this.tabMaterial.classList.add("tcv_tab-unselected")) : t == "clip" ? (this.tabTree.classList.remove("tcv_tab-selected"), this.tabTree.classList.add("tcv_tab-unselected"), this.tabClip.classList.add("tcv_tab-selected"), this.tabClip.classList.remove("tcv_tab-unselected"), this.tabMaterial.classList.remove("tcv_tab-selected"), this.tabMaterial.classList.add("tcv_tab-unselected")) : (this.tabTree.classList.add("tcv_tab-unselected"), this.tabTree.classList.remove("tcv_tab-selected"), this.tabClip.classList.add("tcv_tab-unselected"), this.tabClip.classList.remove("tcv_tab-selected"), this.tabMaterial.classList.add("tcv_tab-selected"), this.tabMaterial.classList.remove("tcv_tab-unselected"));
    }
  }
  /**
   * Collapse nodes handler
   * @param {string} value - 1: collapse all leaf nodes, "R": expand root level only, "C": collapse all nodes, "E": expand all nodes
   */
  collapseNodes(t) {
    t === "1" ? this.viewer.treeview.openLevel(-1) : t === "R" ? this.viewer.treeview.openLevel(1) : t === "C" ? this.viewer.treeview.collapseAll() : t === "E" && this.viewer.treeview.expandAll();
  }
  /**
   * Set minimum and maximum of the sliders
   * @param {number} index - index of the plane: 0,1,2
   * @param {number} limit - the value for both minimum and maximum value of the slider
   */
  setSliderLimits(t) {
    for (var e = 0; e < 3; e++)
      this.clipSliders[e].setSlider(t);
  }
  /**
   * Refresh clipping plane
   * @function
   * @param {number} index - index of the plane: 0,1,2
   * @param {number} value - distance on the clipping normal from the center
   */
  refreshPlane(t, e) {
    this.viewer.refreshPlane(t - 1, parseFloat(e));
  }
  /**
   * Handle animation control
   * @function
   * @param {string} btn - animation control button name
   */
  controlAnimationByName(t) {
    this.viewer.controlAnimation(t);
    var e = this.viewer.animation.getRelativeTime();
    this.animationSlider.value = 1e3 * e, t == "play" ? this.viewer.bboxNeedsUpdate = !0 : t == "stop" ? (this.viewer.bboxNeedsUpdate = !1, this.viewer.lastBbox != null && (this.viewer.lastBbox.needsUpdate = !0)) : this.viewer.bboxNeedsUpdate = !this.viewer.bboxNeedsUpdate;
  }
  /**
   * Set label text of animation control
   * @param {string} label - "A" for animation and "E" for Explode control
   */
  setAnimationLabel(t) {
    var e = this._getElement("tcv_animation_label");
    e.innerHTML = t;
  }
  /**
   * Reset animation slider to 0
   */
  resetAnimationSlider() {
    this.animationSlider.value = 0;
  }
  /**
   * Auto collapse tree nodes, when cad width < 600
   * @function
   * @param {boolean} flag - whether to enable/disable glass mode
   */
  autoCollapse() {
    this.cadWidth < 600 && this.glass && (console.info("Small view, collapsing tree"), this.collapseNodes("C"));
  }
  /**
   * Enable/disable glass mode
   * @function
   * @param {boolean} flag - whether to enable/disable glass mode
   */
  glassMode(t) {
    t ? (this._getElement("tcv_cad_tree").classList.add("tcv_cad_tree_glass"), this._getElement("tcv_cad_tree").style.height = null, this._getElement("tcv_cad_tree").style["max-height"] = Li(
      Math.round(this.height * 2 / 3) - 18
    ), this._getElement("tcv_cad_info").classList.add("tcv_cad_info_glass"), this._getElement("tcv_cad_view").classList.add("tcv_cad_view_glass"), this._getElement("tcv_toggle_info_wrapper").style.display = "block", this.showInfo(!1), this.glass = !0, this.autoCollapse()) : (this._getElement("tcv_cad_tree").classList.remove("tcv_cad_tree_glass"), this._getElement("tcv_cad_tree").style["max-height"] = null, this._getElement("tcv_cad_tree").style.height = Li(
      Math.round(this.height * 2 / 3)
    ), this._getElement("tcv_cad_info").classList.remove("tcv_cad_info_glass"), this._getElement("tcv_cad_view").classList.remove("tcv_cad_view_glass"), this._getElement("tcv_toggle_info_wrapper").style.display = "none", this.showInfo(!0), this.glass = !1), this.viewer && (this.viewer.glass = !1);
    const e = {
      cadWidth: this.cadWidth,
      glass: this.glass,
      height: this.height,
      tools: this.tools,
      treeWidth: t ? 0 : this.treeWidth
    };
    this.setSizes(e);
  }
  updateHelp(t, e) {
    const i = this._getElement("tcv_cad_help_layout");
    for (var n in t)
      t[n] && e[n] && (i.innerHTML = i.innerHTML.replaceAll(
        "&lt;" + t[n].slice(0, -3) + "&gt;",
        "&lt;_" + e[n].slice(0, -3) + "&gt;"
      ));
    i.innerHTML = i.innerHTML.replaceAll("_shift", "shift"), i.innerHTML = i.innerHTML.replaceAll("_ctrl", "ctrl"), i.innerHTML = i.innerHTML.replaceAll("_alt", "alt"), i.innerHTML = i.innerHTML.replaceAll("_meta", "meta");
  }
  setTheme(t) {
    return t === "dark" || t == "browser" && window.matchMedia("(prefers-color-scheme: dark)").matches ? (this.container.setAttribute("data-theme", "dark"), document.body.setAttribute("data-theme", "dark"), this.viewer.orientationMarker && this.viewer.orientationMarker.changeTheme("dark"), this.viewer.gridHelper && (this.viewer.gridHelper.clearCache(), this.viewer.gridHelper.update(
      this.viewer.getCameraZoom(),
      !0,
      "dark"
    )), this.viewer.update(!0), "dark") : (this.container.setAttribute("data-theme", "light"), document.body.setAttribute("data-theme", "light"), this.viewer.orientationMarker && this.viewer.orientationMarker.changeTheme("light"), this.viewer.gridHelper && (this.viewer.gridHelper.clearCache(), this.viewer.gridHelper.update(
      this.viewer.getCameraZoom(),
      !0,
      "light"
    )), this.viewer.update(!0), "light");
  }
}
let B_ = class extends ff {
  toJSON() {
    return ou.prototype.toJSON.call(this);
  }
};
const Za = new E(), ja = new E(), pg = new Xt();
class HE extends oi {
  /**
   * Constructs a new vertex normals helper.
   *
   * @param {Object3D} object - The object for which to visualize vertex normals.
   * @param {number} [size=1] - The helper's size.
   * @param {number|Color|string} [color=0xff0000] - The helper's color.
   */
  constructor(t, e = 1, i = 16711680) {
    const n = new Ht(), s = t.geometry.attributes.normal.count, r = new wt(s * 2 * 3, 3);
    n.setAttribute("position", r), super(n, new Pe({ color: i, toneMapped: !1 })), this.object = t, this.size = e, this.type = "VertexNormalsHelper", this.matrixAutoUpdate = !1, this.isVertexNormalsHelper = !0, this.update();
  }
  /**
   * Updates the vertex normals preview based on the object's world transform.
   */
  update() {
    this.object.updateMatrixWorld(!0), pg.getNormalMatrix(this.object.matrixWorld);
    const t = this.object.matrixWorld, e = this.geometry.attributes.position, i = this.object.geometry;
    if (i) {
      const n = i.attributes.position, s = i.attributes.normal;
      let r = 0;
      for (let o = 0, l = n.count; o < l; o++)
        Za.fromBufferAttribute(n, o).applyMatrix4(t), ja.fromBufferAttribute(s, o), ja.applyMatrix3(pg).normalize().multiplyScalar(this.size).add(Za), e.setXYZ(r, Za.x, Za.y, Za.z), r = r + 1, e.setXYZ(r, ja.x, ja.y, ja.z), r = r + 1;
    }
    e.needsUpdate = !0;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose(), this.material.dispose();
  }
}
class or extends we {
  expandByObject(t, e = !1) {
    if (t.updateWorldMatrix(!1, !1), t.constructor.name == "ObjectGroup")
      return this.expandByObject(t.children[0], e), this;
    const i = t.geometry;
    if (i !== void 0)
      if (e && i.attributes != null && i.attributes.position !== void 0)
        if (t.type.startsWith("LineSegment")) {
          var n = i.clone();
          n.applyMatrix4(t.matrixWorld), n.boundingBox = null, n.computeBoundingBox(), Ja.copy(n.boundingBox), this.union(Ja);
        } else {
          const r = i.attributes.position;
          for (let o = 0, l = r.count; o < l; o++)
            ql.fromBufferAttribute(r, o).applyMatrix4(t.matrixWorld), this.expandByPoint(ql);
        }
      else
        i.boundingBox === null && i.computeBoundingBox(), Ja.copy(i.boundingBox), Ja.applyMatrix4(t.matrixWorld), this.union(Ja);
    const s = t.children;
    for (let r = 0, o = s.length; r < o; r++)
      s[r].name == "PlaneMeshes" && s[r].children && s[r].children.length > 0 && s[r].children[0].type.startsWith("StencilPlane") || this.expandByObject(s[r], e);
    return this;
  }
  max_dist_from_center() {
    return Math.max(
      ...this.min.toArray().concat(this.max.toArray()).map((t) => Math.abs(t))
    );
  }
  boundingSphere() {
    return this.getBoundingSphere(fg), fg;
  }
  center() {
    return this.getCenter(ql), ql.toArray();
  }
}
class GE extends oi {
  constructor(t, e = 16776960) {
    const i = new Uint16Array([
      0,
      1,
      1,
      2,
      2,
      3,
      3,
      0,
      4,
      5,
      5,
      6,
      6,
      7,
      7,
      4,
      0,
      4,
      1,
      5,
      2,
      6,
      3,
      7
    ]), n = new Float32Array(8 * 3), s = new Ht();
    s.setIndex(new ie(i, 1)), s.setAttribute("position", new ie(n, 3)), super(
      s,
      new Pe({ color: e, toneMapped: !1 })
    ), this.object = t, this.type = "BoxHelper", this.matrixAutoUpdate = !1, this.update();
  }
  update() {
    if (this.object !== void 0 && $l.setFromObject(this.object, !0), $l.isEmpty()) return;
    const t = $l.min, e = $l.max, i = this.geometry.attributes.position, n = i.array;
    n[0] = e.x, n[1] = e.y, n[2] = e.z, n[3] = t.x, n[4] = e.y, n[5] = e.z, n[6] = t.x, n[7] = t.y, n[8] = e.z, n[9] = e.x, n[10] = t.y, n[11] = e.z, n[12] = e.x, n[13] = e.y, n[14] = t.z, n[15] = t.x, n[16] = e.y, n[17] = t.z, n[18] = t.x, n[19] = t.y, n[20] = t.z, n[21] = e.x, n[22] = t.y, n[23] = t.z, i.needsUpdate = !0, this.geometry.computeBoundingSphere();
  }
  setFromObject(t) {
    return this.object = t, this.update(), this;
  }
}
const ql = new E(), Ja = new or(), $l = new or(), fg = new Re();
let ln = class extends yi {
  /**
   *
   * @param {*} opacity
   * @param {*} alpha
   * @param {*} edge_color
   * @param {object} shapeInfo A dictionary of shape information with a "topo" field and "geomtype" field.
   * @param {*} renderback
   */
  constructor(t, e, i, n, s, r) {
    super(), this.opacity = t, this.alpha = e ?? 1, this.edge_color = i, this.shapeInfo = n, this.subtype = s, this.renderback = r, this.types = { front: null, back: null, edges: null, vertices: null }, this.isSelected = !1, this.originalColor = null, this.originalBackColor = null, this.originalWidth = null, this.vertexFocusSize = 8, this.edgeFocusWidth = 5;
  }
  dispose() {
    this.shapeGeometry && (P_(this.shapeGeometry), this.shapeGeometry = null), me(Object.values(this.types)), this.children && (me(this.children), this.clear());
  }
  addType(t, e) {
    this.add(t), this.types[e] = t, this.types.vertices ? (this.originalColor = this.types.vertices.material.color.clone(), this.originalWidth = this.types.vertices.material.size) : this.types.edges && !this.types.front ? (this.originalColor = this.types.edges.material.color.clone(), this.originalWidth = this.types.edges.material.linewidth) : this.types.front ? this.originalColor = this.types.front.material.color.clone() : this.types.back && (this.originalBackColor = this.types.back.material.color.clone());
  }
  widen(t) {
    this.types.vertices ? this.types.vertices.material.size = t ? this.vertexFocusSize : this.isSelected ? this.vertexFocusSize - 2 : this.originalWidth : this.types.edges && (this.types.edges.material.linewidth = t ? this.edgeFocusWidth : this.isSelected ? this.edgeFocusWidth - 2 : this.originalWidth);
  }
  toggleSelection() {
    const t = !this.isSelected;
    this.isSelected = t, this.highlight(t), this.widen(!1);
  }
  unhighlight(t) {
    (!t || !this.isSelected) && (this.isSelected = !1, this.highlight(!1)), this.widen(!1);
  }
  highlight(t) {
    var e = null, i = null, n = null;
    this.types.front ? (e = this.types.front, i = this.isSelected ? new ct(5480675) : new ct(9026019), n = this.originalColor) : this.types.vertices ? (e = this.types.vertices, i = this.isSelected ? new ct(5480675) : new ct(9026019), n = this.originalColor) : this.types.edges && (e = this.types.edges, i = this.isSelected ? new ct(5480675) : new ct(9026019), n = this.originalColor), e != null && (this.widen(t), e.material.color = t ? i : n, e.material.needsUpdate = !0), this.types.back && (e = this.types.back, i = this.isSelected ? new ct(5480675) : new ct(9026019), n = this.originalBackColor), e != null && (e.material.color = t ? i : n, e.material.needsUpdate = !0);
  }
  clearHighlights() {
    this.highlight(!1), this.isSelected = !1, this.widen(!1);
  }
  metrics() {
    if (this.types.front)
      return { name: "face", value: 0 };
    if (this.types.vertices)
      return { name: "vertex", value: 0 };
    if (this.types.edges)
      return { name: "edge", value: 0 };
  }
  setMetalness(t) {
    for (var e of this.children)
      e.name.startsWith("clipping") || (e.material.metalness = t, e.material.needsUpdate = !0);
  }
  setRoughness(t) {
    for (var e of this.children)
      e.name.startsWith("clipping") || (e.material.roughness = t, e.material.needsUpdate = !0);
  }
  setTransparent(t) {
    this.types.back && (this.types.back.material.opacity = t ? this.opacity * this.alpha : this.alpha, this.types.front.material.opacity = t ? this.opacity * this.alpha : this.alpha);
    for (var e of this.children)
      e.name.startsWith("clipping") || (e.material.depthWrite = this.alpha < 1 ? !1 : !t, e.material.depthTest = !0, e.material.needsUpdate = !0);
  }
  setBlackEdges(t) {
    if (this.types.edges) {
      const e = t ? 0 : this.edge_color;
      this.originalColor = new ct(e), this.types.edges.material.color = new ct(e), this.types.edges.material.needsUpdate = !0;
    }
  }
  setEdgeColor(t) {
    this.types.edges && (this.edge_color = t, this.types.edges.material.color = new ct(t), this.types.edges.material.needsUpdate = !0);
  }
  setOpacity(t) {
    (this.types.front || this.types.back) && (this.opacity = t, this.types.back.material.opacity = this.opacity, this.types.front.material.opacity = this.opacity, this.types.back.material.needsUpdate = !0, this.types.front.material.needsUpdate = !0);
  }
  setShapeVisible(t) {
    this.types.front && (this.types.front.material.visible = t);
    for (var e of ["clipping-0", "clipping-1", "clipping-2"])
      this.types[e] && (this.types[e].children[0].material.visible = t, this.types[e].children[1].material.visible = t);
    this.types.back && this.renderback && (this.types.back.material.visible = t);
  }
  setEdgesVisible(t) {
    this.types.edges && (this.types.edges.material.visible = t), this.types.vertices && (this.types.vertices.material.visible = t);
  }
  setBackVisible(t) {
    this.types.back && this.types.front.material.visible && (this.types.back.material.visible = this.renderback || t);
  }
  getVisibility() {
    return this.types.front ? this.types.edges ? this.types.front.material.visible || this.types.edges.material.visible : this.types.front.material.visible : this.types.edges ? this.types.edges.material.visible : this.types.vertices ? this.types.vertices.material.visible : !1;
  }
  setClipIntersection(t) {
    for (var e of this.children)
      e.name.startsWith("clipping") || (e.material.clipIntersection = t, e.material.clipIntersection = t, e.material.clipIntersection = t);
  }
  setClipPlanes(t) {
    this.types.back && (this.types.back.material.clippingPlanes = t), this.types.front && (this.types.front.material.clippingPlanes = t), this.types.edges && (this.types.edges.material.clippingPlanes = t), this.types.vertices && (this.types.vertices.material.clippingPlanes = t), this.updateMaterials(!0);
  }
  setPolygonOffset(t) {
    this.types.back && (this.types.back.material.polygonOffsetUnits = t);
  }
  setZScale(t) {
    function e(i, n, s, r = !0) {
      for (var o of i.children)
        o.isMesh || o.isLine ? (o.scale.z = t, r && (o.parent.position.z = n * t)) : o.isGroup && e(o, n, s, !o.name.startsWith("clipping"));
    }
    (this.types.front || this.types.back || this.types.edges) && e(this, this.minZ, this.height);
  }
  updateMaterials(t) {
    this.types.back && (this.types.back.material.needsUpdate = t), this.types.front && (this.types.front.material.needsUpdate = t), this.types.edges && (this.types.edges.material.needsUpdate = t), this.types.vertices && (this.types.vertices.material.needsUpdate = t);
  }
};
class WE {
  constructor(t, e, i, n, s, r, o, l, h, c) {
    this.shapes = t, this.width = e, this.height = i, this.edgeColor = n, this.transparent = s, this.metalness = o, this.roughness = l, this.defaultOpacity = r, this.normalLen = h, this.blackEdges = !1, this.backVisible = !1, this.bb_max = c, this.delim = "|", this.rootGroup = null, this.instances = null, this.bbox = null, this.bsphere = null, this.groups = {}, this.clipPlanes = null;
  }
  dispose() {
    this.groups && (me(Object.values(this.groups)), this.groups = null), this.rootGroup && (me(this.rootGroup), this.rootGroup = null), this.shapes && (me(this.shapes), this.shapes = null);
  }
  _dump(t) {
    if (t == null && (t = ""), this.parts)
      for (var e of this.parts)
        this._dump(e, t + "  ");
  }
  _renderEdges(t, e, i, n) {
    var s = t instanceof Float32Array ? t : new Float32Array(xs(t, 3));
    const r = new B_();
    r.setPositions(s);
    const o = new hu({
      linewidth: e,
      transparent: !0,
      depthWrite: !this.transparent,
      depthTest: !this.transparent,
      clipIntersection: !1
    });
    if (Array.isArray(i)) {
      var l = i.map((c) => [
        new ct(c).toArray(),
        new ct(c).toArray()
      ]).flat(2);
      r.setColors(l), o.vertexColors = "VertexColors";
    } else
      o.color = new ct(
        i ?? this.edgeColor
      );
    o.visible = n == 1, o.resolution.set(this.width, this.height);
    var h = new mf(r, o);
    return h.renderOrder = 999, h;
  }
  renderEdges(t, e, i, n, s, r, o = null) {
    var l = new ln(
      this.defaultOpacity,
      1,
      i ?? this.edgeColor,
      o,
      "edges"
    ), h = this._renderEdges(
      t.edges ? t.edges : xs(t),
      // protocol version 1
      e,
      i,
      r
    );
    return s && (h.name = s), l.addType(h, "edges"), this.groups[n] = l, l.name = n.replaceAll("/", this.delim), l;
  }
  renderVertices(t, e, i, n, s, r, o = null) {
    var l = new ln(
      this.defaultOpacity,
      1,
      i ?? this.edgeColor,
      o,
      "vertices"
    );
    const h = i ?? this.edgeColor;
    let c;
    t.obj_vertices ? c = t.obj_vertices instanceof Float32Array ? t.obj_vertices : new Float32Array(t.obj_vertices) : c = t instanceof Float32Array ? t : new Float32Array(xs(t));
    const u = new Ht();
    u.setAttribute(
      "position",
      new wt(c, 3)
    );
    const d = new Xc({
      color: h,
      sizeAttenuation: !1,
      size: e,
      transparent: !0,
      clipIntersection: !1,
      visible: r == 1
    });
    var p = new kp(u, d);
    return s && (p.name = s), l.addType(p, "vertices"), this.groups[n] = l, l.name = n.replaceAll("/", this.delim), l;
  }
  renderShape(t, e, i, n, s, r, o, l, h = null, c = null, u = null, d = null, p = null) {
    const f = t.vertices instanceof Float32Array ? t.vertices : new Float32Array(xs(t.vertices)), y = t.normals instanceof Float32Array ? t.normals : new Float32Array(xs(t.normals)), g = t.triangles instanceof Uint32Array ? t.triangles : new Uint32Array(xs(t.triangles));
    var m = new ln(
      this.defaultOpacity,
      i,
      this.edgeColor,
      h,
      c,
      n
    );
    this.groups[r] = m, m.name = r.replaceAll("/", this.delim), i == null ? i = 1 : i < 1 && (this.transparent = !0);
    var v, x = null, _ = null;
    if (u != null) {
      const U = `data:image/${u.format};base64,${u.data}`;
      var S = new Image();
      S.setAttribute("src", U), v = new Ds(d, p), x = new Ne(S), x.needsUpdate = !0, x.colorSpace = ri, _ = new li({
        color: "#ffffff",
        map: x,
        side: Mi
      }), n = !1;
    } else
      v = new Ht(), v.setAttribute(
        "position",
        new ie(f, 3)
      ), v.setAttribute(
        "normal",
        new ie(y, 3)
      ), v.setIndex(new ie(g, 1)), m.shapeGeometry = v, _ = new hr({
        color: e,
        metalness: this.metalness,
        roughness: this.roughness,
        // envMap: texture,
        polygonOffset: !0,
        polygonOffsetFactor: 1,
        polygonOffsetUnits: 1,
        transparent: !0,
        opacity: this.transparent ? this.defaultOpacity * i : i,
        // turn depth write off for transparent objects
        depthWrite: !this.transparent,
        // but keep depth test
        depthTest: !0,
        clipIntersection: !1,
        side: $i,
        visible: l[0] == 1,
        map: x,
        name: "frontMaterial"
      });
    const w = m.subtype === "solid" && !s ? e : new ct(this.edgeColor).lerp(new ct(1, 1, 1), 0.15), T = new li({
      color: w,
      side: He,
      polygonOffset: !0,
      polygonOffsetFactor: 1,
      polygonOffsetUnits: 1,
      transparent: !0,
      opacity: this.transparent ? this.defaultOpacity * i : i,
      // turn depth write off for transparent objects
      depthWrite: !this.transparent,
      // but keep depth test
      depthTest: !0,
      clipIntersection: !1,
      visible: l[0] == 1 && (n || this.backVisible),
      name: "backMaterial"
    }), R = new re(v, T);
    R.name = o;
    const b = new re(v, _);
    if (b.name = o, i < 1 && (R.renderOrder = 999, b.renderOrder = 999), b.geometry.boundingBox == null && b.geometry.computeBoundingBox(), m.addType(R, "back"), m.addType(b, "front"), this.normalLen > 0) {
      const U = new HE(
        b,
        this.normalLen,
        16711935
      );
      m.add(U);
    }
    const M = t.edges;
    if (M.length > 0) {
      var L = this._renderEdges(M, 1, null, l[1]);
      L.name = o, m.addType(L, "edges");
    }
    return m;
  }
  renderPolygons(t, e, i, n, s, r, o, l, h, c = null, u = null) {
    const d = (V, W) => {
      const G = [], et = [];
      let H = 0;
      for (let pt = 0; pt < V.length; pt++) {
        const Lt = V[pt].getPoints(), jt = Lt.map((Y) => new E(Y.x, Y.y, 0)), ne = Lt.map((Y) => new E(Y.x, Y.y, W)), Jt = (Y) => {
          for (let st = 0; st < Y.length; st++) {
            const Et = (st + 1) % Y.length;
            et.push(H + st, H + Et);
          }
          G.push(...Y), H += Y.length;
        };
        Jt(jt), Jt(ne);
        for (let Y = 0; Y < Lt.length; Y++)
          et.push(
            H - 2 * Lt.length + Y,
            // Bottom point index
            H - Lt.length + Y
            // Top point index
          );
      }
      const at = new Ht();
      return at.setFromPoints(G), at.setIndex(et), at;
    };
    var p = new ln(
      this.defaultOpacity,
      1,
      this.edgeColor,
      c,
      u,
      s
    );
    p.name = o.replaceAll("/", this.delim), p.minZ = e, p.height = t.height, this.groups[o] = p;
    var f = [], y;
    t.matrices && t.matrices.length > 0 ? y = t.matrices : y = [1, 0, 0, 0, 1, 0];
    for (var g of t.refs) {
      var m = this.instances[g];
      const V = m.length / 2;
      for (var v = new Array(V), x = 0; x < y.length / 6; x++) {
        const W = y[6 * x], G = y[6 * x + 1], et = y[6 * x + 2], H = y[6 * x + 3], at = y[6 * x + 4], pt = y[6 * x + 5];
        for (let Lt = 0; Lt < V; Lt++)
          v[Lt] = new J(
            W * m[2 * Lt] + G * m[2 * Lt + 1] + et,
            H * m[2 * Lt] + at * m[2 * Lt + 1] + pt
          );
        const Mt = new As(v);
        f.push(Mt);
      }
    }
    const _ = {
      depth: t.height,
      bevelEnabled: !1
    };
    let S;
    S = new Vo(f, _);
    const w = {
      color: i,
      metalness: this.metalness,
      roughness: this.roughness,
      // envMap: texture,
      polygonOffset: !0,
      polygonOffsetFactor: 1,
      polygonOffsetUnits: 1,
      transparent: !0,
      opacity: this.transparent ? this.defaultOpacity * n : n,
      // turn depth write off for transparent objects
      depthWrite: !this.transparent,
      // but keep depth test
      depthTest: !0,
      clipIntersection: !1
    };
    var T = new hr({
      side: $i,
      name: "frontMaterial",
      visible: h[0] == 1,
      ...w
    }), R = new hr({
      side: He,
      visible: h[0] == 1 && (s || this.backVisible),
      name: "backMaterial",
      ...w
    });
    const b = new re(S, R);
    b.name = l;
    const M = new re(S, T);
    M.name = l;
    const L = d(f, t.height);
    var U = new Pe({
      color: this.edgeColor,
      depthWrite: !this.transparent,
      depthTest: !this.transparent,
      clipIntersection: !1
    }), O = new oi(L, U);
    return p.shapeGeometry = S, p.addType(M, "front"), p.addType(b, "back"), p.addType(O, "edges"), p;
  }
  renderLoop(t) {
    const e = (l, h, c, u) => {
      var d;
      switch (l.type) {
        case "edges":
          d = this.renderEdges(
            l.shape,
            l.width,
            l.color,
            l.id,
            l.name,
            l.state[1],
            { topo: "edge", geomtype: l.geomtype }
          );
          break;
        case "vertices":
          d = this.renderVertices(
            l.shape,
            l.size,
            l.color,
            l.id,
            l.name,
            l.state[1],
            { topo: "vertex", geomtype: null }
          );
          break;
        case "polygon":
          d = this.renderPolygons(
            l.shape,
            l.loc[0][2],
            l.color,
            1,
            l.renderback == null ? !1 : l.renderback,
            !1,
            //exploded
            l.id,
            l.name,
            l.state,
            { topo: "face", geomtype: l.geomtype },
            l.subtype
          );
          break;
        default:
          d = this.renderShape(
            l.shape,
            l.color,
            l.alpha,
            l.renderback == null ? !1 : l.renderback,
            l.exploded,
            l.id,
            l.name,
            l.state,
            { topo: "face", geomtype: l.geomtype },
            l.subtype,
            h,
            c,
            u
          );
      }
      return l.loc != null && (d.position.set(...l.loc[0]), d.quaternion.set(...l.loc[1])), d;
    };
    var i = new yi();
    t.loc == null && (t.loc = [
      [0, 0, 0],
      [0, 0, 0, 1]
    ]), i.position.set(...t.loc[0]), i.quaternion.set(...t.loc[1]), this.groups[t.id] = i, i.name = t.id.replaceAll("/", "|");
    for (var n of t.parts)
      if (n.parts)
        i.add(this.renderLoop(n));
      else {
        const l = n.texture != null;
        var s = l ? n.texture.image : null, r = l ? n.texture.width : null, o = l ? n.texture.height : null;
        const h = e(n, s, r, o);
        this.groups[n.id] = h, i.add(h);
      }
    return i;
  }
  render() {
    return this.shapes.format == "GDS" && (this.instances = this.shapes.instances), this.rootGroup = this.renderLoop(this.shapes), this.rootGroup;
  }
  boundingBox() {
    return this.bbox == null && (this.bbox = new or(), this.bbox.setFromObject(this.rootGroup, !1)), this.bbox;
  }
  _traverse(t, e) {
    for (var i in this.groups) {
      var n = this.groups[i];
      n instanceof ln && n[t](e);
    }
  }
  selection() {
    var t = [];
    for (var e in this.groups)
      for (var i of this.groups[e].children)
        i instanceof ln && i.isSelected && t.push(i);
    return t;
  }
  clearSelection() {
    for (var t of this.selection())
      t.clearHighlights();
  }
  setMetalness(t) {
    this.metalness = t, this._traverse("setMetalness", t);
  }
  setRoughness(t) {
    this.roughness = t, this._traverse("setRoughness", t);
  }
  setTransparent(t) {
    this.transparent = t, this._traverse("setTransparent", t);
  }
  setBlackEdges(t) {
    this.blackEdges = t, this._traverse("setBlackEdges", t);
  }
  setBackVisible(t) {
    this.backVisible = t, this._traverse("setBackVisible", t);
  }
  setEdgeColor(t) {
    this.edge_color = t, this._traverse("setEdgeColor", t);
  }
  setOpacity(t) {
    this.opacity = t, this._traverse("setOpacity", t);
  }
  setClipIntersection(t) {
    this._traverse("setClipIntersection", t);
  }
  setClipPlanes(t) {
    this.clipPlanes = t, this._traverse("setClipPlanes", t);
  }
  setPolygonOffset(t) {
    this._traverse("setPolygonOffset", t);
  }
  setZScale(t) {
    this._traverse("setZScale", t);
  }
  setMinZ() {
    this._traverse("setMinZ");
  }
  updateMaterials() {
    this._traverse("updateMaterials", !0);
  }
}
function qE(a, t, e, i, n) {
  const s = (i - t) / (e - a);
  return n < a ? t : n > e ? i : s * (n - a) + t;
}
function mg(a) {
  var t = a.replace(/(\.\d*[1-9])0+$/, "$1").replace(/\.0+$/, "");
  return t === "-0" && (t = "0"), t.indexOf(".") < 0 && (t = `${t}.0`), t;
}
class $E extends le {
  constructor(t, e, i, n, s) {
    super();
    const r = t / e, o = t / 2, l = [], h = [], c = [];
    var u = !1;
    for (let S = 0; S <= e; S++) {
      const w = -o + S * r;
      Math.abs(w) > 1e-10 ? l.push(-o, 0, w, o, 0, w) : (c.push(-o, 0, w, o, 0, w), u = !0), u || c.push(-o, 0, 0, o, 0, 0), u = !1, Math.abs(w) > 1e-10 ? l.push(w, 0, -o, w, 0, o) : h.push(w, 0, -o, w, 0, o), u || h.push(0, 0, -o, 0, 0, o);
    }
    const d = new Ht();
    d.setAttribute(
      "position",
      new wt(l, 3)
    );
    const p = d.getAttribute("position"), f = new Float32Array(p.count);
    for (let S = 0; S < p.count; S += 2) {
      const w = p.getX(S), T = p.getY(S), R = p.getZ(S), b = p.getX(S + 1), M = p.getY(S + 1), L = p.getZ(S + 1);
      f[S] = 0, f[S + 1] = Math.sqrt(
        (b - w) ** 2 + (M - T) ** 2 + (L - R) ** 2
      );
    }
    d.setAttribute(
      "lineDistance",
      new ie(f, 1)
    );
    const y = new Kp({
      color: s,
      dashSize: r / 20,
      gapSize: r / 20,
      opacity: 1,
      transparent: !1,
      vertexColors: !1
    }), g = new oi(d, y);
    this.add(g);
    const m = new Ht();
    m.setAttribute(
      "position",
      new wt(h, 3)
    );
    const v = new Pe({ color: i });
    this.add(new oi(m, v));
    const x = new Ht();
    x.setAttribute(
      "position",
      new wt(c, 3)
    );
    const _ = new Pe({ color: n });
    this.add(new oi(x, _));
  }
}
class XE extends yi {
  constructor(t, e, i, n, s, r, o, l, h) {
    super(), i === void 0 && (i = 5), this.ticks = i, this.gridFontSize = n, this.viewer = t, this.bbox = e, this.centerGrid = s, this.axes0 = r, this.grid = o, this.allGrid = o[0] | o[1] | o[2], this.theme = h, this.flipY = l, this.lastZoomIndex = 0, this.lastFontIndex = 50, this.tickValue = this.viewer.display._getElement("tcv_tick_size_value"), this.info = this.viewer.display._getElement("tcv_tick_size");
    const c = e.max_dist_from_center(), u = Math.min(this.viewer.cadWidth, this.viewer.height), d = Math.max(1, 6 - Math.log2(u / 100));
    this.minFontIndex = Math.round(
      (c < 2 ? 6 : c < 1e3 ? 5 : 3) * d
    ), this.minZoomIndex = -4, this.zoomMaxIndex = 5, this.canvasHeight = 128, this.geomCache = {}, this.textureAspectRatios = {}, this.labelCache = {}, this.materialCache = {}, this.colors = {
      dark: [
        "#ff4500",
        // x
        "#32cd32",
        // y
        "#3b9eff"
        // z
      ],
      light: [
        "#ff4500",
        // x
        "#32cd32",
        // y
        "#3b9eff"
        // z
      ]
    }, this.create();
  }
  calculateTextScale(t) {
    const e = this.viewer.camera.getCamera(), i = this.viewer.height, n = qE(300, 0.8, 800, 1, i) * t;
    if (this.viewer.ortho) {
      const s = (e.top - e.bottom) / e.zoom, r = i / s;
      return n / r * 1.6;
    } else
      return n / i * 0.6;
  }
  scaleLabels() {
    for (var t in this.children)
      for (var e = this.children[t], i = 1; i < e.children.length; i++) {
        const s = e.children[i];
        var n = this.calculateTextScale(this.gridFontSize);
        const r = s.userData.aspectRatio || 4;
        s.scale.set(n * r, n, 1);
      }
  }
  showLabels(t) {
    for (var e in this.children)
      for (var i = this.children[e], n = 1; n < i.children.length; n++) {
        const s = i.children[n];
        s.visible = t;
      }
  }
  async update(t, e = !1, i = null) {
    if (!this.getVisible()) return;
    i && (this.theme = i);
    var n = Math.round(Math.log2(0.4 * t));
    if (Math.abs(n) < 1e-6 && (n = 0), e || n != this.lastZoomIndex && n < this.zoomMaxIndex && n > this.minZoomIndex) {
      me(this.children), this.children = [];
      const r = this.ticks0 / 2 * 2 ** n;
      this.ticks = Math.round(2 * r), await this.create(!1), this.lastZoomIndex = n, e = !0;
    }
    const s = Math.round(t * 50);
    (e || s != this.lastFontIndex) && (s < this.minFontIndex ? this.showLabels(!1) : (this.viewer.ortho && this.scaleLabels(), this.showLabels(!0)), this.lastFontIndex = s);
  }
  async create(t = !0) {
    if (t) {
      const c = Math.max(
        Math.abs(this.bbox.max.x),
        Math.abs(this.bbox.max.y),
        Math.abs(this.bbox.max.z),
        Math.abs(this.bbox.min.x),
        Math.abs(this.bbox.min.y),
        Math.abs(this.bbox.min.z)
      );
      var [e, i, n] = this.niceBounds(
        -c * 1.05,
        c * 1.05,
        this.ticks
      );
      this.size = i - e, this.ticks = this.size / n, this.ticks0 = this.ticks, this.delta = n;
    } else
      this.delta = this.size / this.ticks;
    this.setTickInfo(this.delta / 2);
    for (var s = 0; s < 3; s++) {
      var r = new yi();
      r.name = `GridHelper-${s}`, r.add(
        new $E(
          this.size,
          2 * this.ticks,
          this.colors[this.theme][s === 0 ? 1 : s === 1 ? 0 : 2],
          this.colors[this.theme][s === 0 ? 0 : s === 1 ? 2 : 1],
          this.theme == "dark" ? 125269879 : 12303291
        )
      );
      for (var o, l = -this.size / 2; l <= this.size / 2; l += this.delta / 2)
        if (!(Math.abs(l) < 1e-6)) {
          var h = mg(l.toFixed(4));
          l > 0 && (h = "+" + h), o = this.createLabel(h, l, s, !0), r.add(o), o = this.createLabel(h, l, s, !1), r.add(o);
        }
      this.add(r);
    }
    this.children[0].rotateX(Math.PI / 2), this.children[1].rotateY(Math.PI / 2), this.children[2].rotateZ(Math.PI / 2), this.setCenter(this.axes0, this.flipY), this.scaleLabels(), this.setCenter(this.viewer.axes0, this.flipY), this.setVisible();
  }
  createTextTexture(t) {
    if (this.geomCache[t])
      return this.geomCache[t];
    const e = document.createElement("canvas"), i = e.getContext("2d", {
      alpha: !0,
      desynchronized: !1,
      willReadFrequently: !1
    }), n = 80, s = 12, o = `${this.theme === "dark" ? "500" : "560"} ${n}px Verdana, Arial, sans-serif`;
    i.font = o;
    const h = i.measureText(t).width, u = Math.round(h + 20 * 2), d = this.canvasHeight;
    e.width = u, e.height = d, i.textRendering = "optimizeLegibility", i.font = o, i.textAlign = "center", i.textBaseline = "middle", i.clearRect(0, 0, e.width, e.height);
    const p = e.width / 2, f = e.height / 2;
    i.lineWidth = s, i.lineJoin = "round", i.miterLimit = 2, i.strokeStyle = this.theme === "dark" ? "#444444" : "#ffffff", i.strokeText(t, p, f), i.fillStyle = this.theme === "dark" ? "#aaaaaa" : "#333333", i.fillText(t, p, f);
    const y = new Uy(e);
    return y.needsUpdate = !0, y.colorSpace = this.theme === "dark" ? ri : Cs, y.minFilter = Ce, y.magFilter = Ce, y.generateMipmaps = !1, y.anisotropy = this.viewer.renderer.capabilities.getMaxAnisotropy(), y.premultiplyAlpha = !1, y.wrapS = Si, y.wrapT = Si, this.geomCache[t] = y, this.textureAspectRatios[t] = u / d, y;
  }
  createLabel(t, e, i, n) {
    const s = `${t}_${i}_${n}`;
    if (this.labelCache[s]) {
      const p = this.labelCache[s], f = new mc(p.material);
      return f.position.copy(p.position), f.scale.copy(p.scale), f.userData.aspectRatio = p.userData.aspectRatio, f;
    }
    const r = this.createTextTexture(t);
    let o = 0;
    i === 0 ? o = 0 : i === 1 ? o = n ? Math.PI / 2 : 0 : o = n ? 0 : Math.PI / 2;
    const l = `${t}_${i}_${n}`;
    let h = this.materialCache[l];
    h || (h = new Wc({
      map: r,
      transparent: !0,
      depthTest: !0,
      depthWrite: !1,
      blending: ws,
      rotation: o,
      sizeAttenuation: !1
      // Disable distance scaling - maintain constant screen size
    }), this.materialCache[l] = h);
    const c = new mc(h);
    let u;
    i === 0 ? u = n ? 1 : -1 : i === 1 ? u = n ? -1 : 1 : u = 1, n ? c.position.set(u * e, 0, 0) : c.position.set(0, 0, u * e);
    const d = this.textureAspectRatios[t] || 4;
    return c.scale.set(d, 1, 1), c.userData.aspectRatio = d, this.labelCache[s] = c, c;
  }
  // Calculate nice symmetric grid bounds centered at zero
  // numTicks: desired number of ticks in one direction (from 0 to max)
  niceBounds(t, e, i) {
    i || (i = 8);
    const n = Math.max(Math.abs(t), Math.abs(e));
    if (n === 0)
      return [0, 0, 0];
    const s = n / i, r = Math.floor(Math.log10(s)), o = Math.pow(10, r), l = s / o;
    let h;
    l <= 1 ? h = 1 : l <= 2 ? h = 2 : l <= 2.5 ? h = 2.5 : l <= 5 ? h = 5 : h = 10;
    const c = h * o, u = Math.ceil(n / c), d = c * u;
    return [-d, d, c];
  }
  computeGrid() {
    this.allGrid = this.grid[0] | this.grid[1] | this.grid[2], this.viewer.display.toolbarButtons.grid.set(this.allGrid), this.viewer.display.checkElement("tcv_grid-xy", this.grid[0]), this.viewer.display.checkElement("tcv_grid-xz", this.grid[1]), this.viewer.display.checkElement("tcv_grid-yz", this.grid[2]), this.setVisible();
  }
  setGrid(t, e = null) {
    switch (t) {
      case "grid":
        this.allGrid = e ?? !this.allGrid, this.grid[0] = this.allGrid, this.grid[1] = this.allGrid, this.grid[2] = this.allGrid;
        break;
      case "grid-xy":
        this.grid[0] = !this.grid[0];
        break;
      case "grid-xz":
        this.grid[1] = !this.grid[1];
        break;
      case "grid-yz":
        this.grid[2] = !this.grid[2];
        break;
    }
    this.computeGrid();
  }
  setGrids(t, e, i) {
    this.grid[0] = t, this.grid[1] = e, this.grid[2] = i, this.computeGrid();
  }
  setCenter(t, e) {
    const i = t ? [0, 0, 0] : this.bbox.center();
    this.children.forEach((n) => n.position.set(...i)), this.centerGrid || (this.children[0].position.z -= this.size / 2, this.children[1].position.y -= (e ? -1 : 1) * this.size / 2, this.children[2].position.x -= this.size / 2);
  }
  setVisible() {
    this.children.forEach((t, e) => {
      t.visible = this.grid[e];
    }), this.allGrid ? this.info.style.display = "block" : this.info.style.display = "none";
  }
  setTickInfo() {
    this.tickValue.innerText = mg((this.delta / 2).toFixed(4));
  }
  getVisible() {
    return this.allGrid;
  }
  clearCache() {
    if (Object.keys(this.geomCache).length > 0) {
      for (var t of Object.keys(this.geomCache))
        this.geomCache[t].dispose();
      this.geomCache = {};
    }
    if (this.textureAspectRatios = {}, this.materialCache && Object.keys(this.materialCache).length > 0) {
      for (var t of Object.keys(this.materialCache))
        this.materialCache[t].dispose();
      this.materialCache = {};
    }
    Object.keys(this.labelCache).length > 0 && (this.labelCache = {});
  }
  dispose() {
    this.clearCache();
  }
}
class z_ extends mf {
  constructor(t, e, i, n, s, r, o, l) {
    const h = new Float32Array([
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      0,
      0,
      0,
      e
    ]), c = new B_();
    c.setPositions(h);
    const u = new hu({
      vertexColors: !0,
      toneMapped: !1,
      linewidth: i,
      transparent: !0
    });
    u.resolution.set(n, s), super(c, u), this.colors = {
      dark: [
        1,
        69 / 255,
        0,
        1,
        69 / 255,
        0,
        // x
        50 / 255,
        205 / 255,
        50 / 255,
        50 / 255,
        205 / 255,
        50 / 255,
        // y
        59 / 255,
        158 / 255,
        1,
        59 / 255,
        158 / 255,
        1
        // z
      ],
      light: [
        1,
        0,
        0,
        1,
        0,
        0,
        // x
        0,
        0.7,
        0,
        0,
        0.7,
        0,
        // y
        0,
        0,
        1,
        0,
        0,
        1
        // z
      ]
    }, c.setColors(new Float32Array(this.colors[l])), this.geometry = c, this.center = t, this.type = "AxesHelper", this.name = "AxesHelper", this.visible = o, this.setCenter(r);
  }
  setCenter(t) {
    t ? this.position.set(0, 0, 0) : this.position.set(...this.center);
  }
  setVisible(t) {
    this.visible = t;
  }
  changeTheme(t) {
    this.geometry.setColors(new Float32Array(this.colors[t]));
  }
}
class YE {
  /**
   * Constructs a new font.
   *
   * @param {Object} data - The font data as JSON.
   */
  constructor(t) {
    this.isFont = !0, this.type = "Font", this.data = t;
  }
  /**
   * Generates geometry shapes from the given text and size. The result of this method
   * should be used with {@link ShapeGeometry} to generate the actual geometry data.
   *
   * @param {string} text - The text.
   * @param {number} [size=100] - The text size.
   * @return {Array<Shape>} An array of shapes representing the text.
   */
  generateShapes(t, e = 100) {
    const i = [], n = ZE(t, e, this.data);
    for (let s = 0, r = n.length; s < r; s++)
      i.push(...n[s].toShapes());
    return i;
  }
}
function ZE(a, t, e) {
  const i = Array.from(a), n = t / e.resolution, s = (e.boundingBox.yMax - e.boundingBox.yMin + e.underlineThickness) * n, r = [];
  let o = 0, l = 0;
  for (let h = 0; h < i.length; h++) {
    const c = i[h];
    if (c === `
`)
      o = 0, l -= s;
    else {
      const u = jE(c, n, o, l, e);
      o += u.offsetX, r.push(u.path);
    }
  }
  return r;
}
function jE(a, t, e, i, n) {
  const s = n.glyphs[a] || n.glyphs["?"];
  if (!s) {
    console.error('THREE.Font: character "' + a + '" does not exists in font family ' + n.familyName + ".");
    return;
  }
  const r = new b_();
  let o, l, h, c, u, d, p, f;
  if (s.o) {
    const y = s._cachedOutline || (s._cachedOutline = s.o.split(" "));
    for (let g = 0, m = y.length; g < m; )
      switch (y[g++]) {
        case "m":
          o = y[g++] * t + e, l = y[g++] * t + i, r.moveTo(o, l);
          break;
        case "l":
          o = y[g++] * t + e, l = y[g++] * t + i, r.lineTo(o, l);
          break;
        case "q":
          h = y[g++] * t + e, c = y[g++] * t + i, u = y[g++] * t + e, d = y[g++] * t + i, r.quadraticCurveTo(u, d, h, c);
          break;
        case "b":
          h = y[g++] * t + e, c = y[g++] * t + i, u = y[g++] * t + e, d = y[g++] * t + i, p = y[g++] * t + e, f = y[g++] * t + i, r.bezierCurveTo(u, d, p, f, h, c);
          break;
      }
  }
  return { offsetX: s.ha * t, path: r };
}
const JE = {
  glyphs: {
    X: {
      x_min: -0.015625,
      x_max: 854.15625,
      ha: 940,
      o: "m 854 0 l 683 0 l 423 409 l 166 0 l 0 0 l 347 519 l 18 1013 l 186 1013 l 428 637 l 675 1013 l 836 1013 l 504 520 l 854 0 "
    },
    Y: {
      x_min: 0,
      x_max: 820,
      ha: 886,
      o: "m 820 1013 l 482 416 l 482 0 l 342 0 l 342 416 l 0 1013 l 140 1013 l 411 534 l 679 1012 l 820 1013 "
    },
    Z: {
      x_min: 0,
      x_max: 779,
      ha: 849,
      o: "m 779 0 l 0 0 l 0 113 l 621 896 l 40 896 l 40 1013 l 779 1013 l 778 887 l 171 124 l 779 124 l 779 0 "
    },
    e: {
      x_min: 0,
      x_max: 714,
      ha: 813,
      o: "m 714 326 l 140 326 q 200 157 140 227 q 359 87 260 87 q 488 130 431 87 q 561 245 545 174 l 697 245 q 577 48 670 123 q 358 -26 484 -26 q 97 85 195 -26 q 0 363 0 197 q 94 642 0 529 q 358 765 195 765 q 626 627 529 765 q 714 326 714 503 m 576 429 q 507 583 564 522 q 355 650 445 650 q 206 583 266 650 q 140 429 152 522 l 576 429 "
    },
    0: {
      x_min: 73,
      x_max: 715,
      ha: 792,
      o: "m 394 -29 q 153 129 242 -29 q 73 479 73 272 q 152 829 73 687 q 394 989 241 989 q 634 829 545 989 q 715 479 715 684 q 635 129 715 270 q 394 -29 546 -29 m 394 89 q 546 211 489 89 q 598 479 598 322 q 548 748 598 640 q 394 871 491 871 q 241 748 298 871 q 190 479 190 637 q 239 211 190 319 q 394 89 296 89 "
    },
    1: {
      x_min: 215.671875,
      x_max: 574,
      ha: 792,
      o: "m 574 0 l 442 0 l 442 697 l 215 697 l 215 796 q 386 833 330 796 q 475 986 447 875 l 574 986 l 574 0 "
    },
    2: {
      x_min: 59,
      x_max: 731,
      ha: 792,
      o: "m 731 0 l 59 0 q 197 314 59 188 q 457 487 199 315 q 598 691 598 580 q 543 819 598 772 q 411 867 488 867 q 272 811 328 867 q 209 630 209 747 l 81 630 q 182 901 81 805 q 408 986 271 986 q 629 909 536 986 q 731 694 731 826 q 613 449 731 541 q 378 316 495 383 q 201 122 235 234 l 731 122 l 731 0 "
    },
    3: {
      x_min: 54,
      x_max: 737,
      ha: 792,
      o: "m 737 284 q 635 55 737 141 q 399 -25 541 -25 q 156 52 248 -25 q 54 308 54 140 l 185 308 q 245 147 185 202 q 395 96 302 96 q 539 140 484 96 q 602 280 602 190 q 510 429 602 390 q 324 454 451 454 l 324 565 q 487 584 441 565 q 565 719 565 617 q 515 835 565 791 q 395 879 466 879 q 255 824 307 879 q 203 661 203 769 l 78 661 q 166 909 78 822 q 387 992 250 992 q 603 921 513 992 q 701 723 701 844 q 669 607 701 656 q 578 524 637 558 q 696 434 655 499 q 737 284 737 369 "
    },
    4: {
      x_min: 48,
      x_max: 742.453125,
      ha: 792,
      o: "m 742 243 l 602 243 l 602 0 l 476 0 l 476 243 l 48 243 l 48 368 l 476 958 l 602 958 l 602 354 l 742 354 l 742 243 m 476 354 l 476 792 l 162 354 l 476 354 "
    },
    5: {
      x_min: 54.171875,
      x_max: 738,
      ha: 792,
      o: "m 738 314 q 626 60 738 153 q 382 -23 526 -23 q 155 47 248 -23 q 54 256 54 125 l 183 256 q 259 132 204 174 q 382 91 314 91 q 533 149 471 91 q 602 314 602 213 q 538 469 602 411 q 386 528 475 528 q 284 506 332 528 q 197 439 237 484 l 81 439 l 159 958 l 684 958 l 684 840 l 254 840 l 214 579 q 306 627 258 612 q 407 643 354 643 q 636 552 540 643 q 738 314 738 457 "
    },
    6: {
      x_min: 53,
      x_max: 739,
      ha: 792,
      o: "m 739 312 q 633 62 739 162 q 400 -31 534 -31 q 162 78 257 -31 q 53 439 53 206 q 178 859 53 712 q 441 986 284 986 q 643 912 559 986 q 732 713 732 833 l 601 713 q 544 830 594 786 q 426 875 494 875 q 268 793 331 875 q 193 517 193 697 q 301 597 240 570 q 427 624 362 624 q 643 540 552 624 q 739 312 739 451 m 603 298 q 540 461 603 400 q 404 516 484 516 q 268 461 323 516 q 207 300 207 401 q 269 137 207 198 q 405 83 325 83 q 541 137 486 83 q 603 298 603 197 "
    },
    7: {
      x_min: 58.71875,
      x_max: 730.953125,
      ha: 792,
      o: "m 730 839 q 469 448 560 641 q 335 0 378 255 l 192 0 q 328 441 235 252 q 593 830 421 630 l 58 830 l 58 958 l 730 958 l 730 839 "
    },
    8: {
      x_min: 55,
      x_max: 736,
      ha: 792,
      o: "m 571 527 q 694 424 652 491 q 736 280 736 358 q 648 71 736 158 q 395 -26 551 -26 q 142 69 238 -26 q 55 279 55 157 q 96 425 55 359 q 220 527 138 491 q 120 615 153 562 q 88 726 88 668 q 171 904 88 827 q 395 986 261 986 q 618 905 529 986 q 702 727 702 830 q 670 616 702 667 q 571 527 638 565 m 394 565 q 519 610 475 565 q 563 717 563 655 q 521 823 563 781 q 392 872 474 872 q 265 824 312 872 q 224 720 224 783 q 265 613 224 656 q 394 565 312 565 m 395 91 q 545 150 488 91 q 597 280 597 204 q 546 408 597 355 q 395 465 492 465 q 244 408 299 465 q 194 280 194 356 q 244 150 194 203 q 395 91 299 91 "
    },
    9: {
      x_min: 53,
      x_max: 739,
      ha: 792,
      o: "m 739 524 q 619 94 739 241 q 362 -32 516 -32 q 150 47 242 -32 q 59 244 59 126 l 191 244 q 246 129 191 176 q 373 82 301 82 q 526 161 466 82 q 597 440 597 255 q 363 334 501 334 q 130 432 216 334 q 53 650 53 521 q 134 880 53 786 q 383 986 226 986 q 659 841 566 986 q 739 524 739 719 m 388 449 q 535 514 480 449 q 585 658 585 573 q 535 805 585 744 q 388 873 480 873 q 242 809 294 873 q 191 658 191 745 q 239 514 191 572 q 388 449 292 449 "
    },
    "+": {
      x_min: 23,
      x_max: 768,
      ha: 792,
      o: "m 768 372 l 444 372 l 444 0 l 347 0 l 347 372 l 23 372 l 23 468 l 347 468 l 347 840 l 444 840 l 444 468 l 768 468 l 768 372 "
    },
    "-": {
      x_min: 8.71875,
      x_max: 350.390625,
      ha: 478,
      o: "m 350 317 l 8 317 l 8 428 l 350 428 l 350 317 "
    },
    ".": {
      x_min: 0,
      x_max: 142,
      ha: 239,
      o: "m 142 0 l 0 0 l 0 151 l 142 151 l 142 0 "
    }
  },
  cssFontWeight: "normal",
  ascender: 1189,
  underlinePosition: -100,
  cssFontStyle: "normal",
  boundingBox: { yMin: -334, xMin: -111, yMax: 1189, xMax: 1672 },
  resolution: 1e3,
  original_font_information: "see https://github.com/mrdoob/three.js/blob/dev/examples/fonts/helvetiker_regular.typeface.json",
  descender: -334,
  familyName: "Helvetiker",
  lineHeight: 1522,
  underlineThickness: 50
}, ao = 54, cd = ao + 18;
class KE {
  constructor(t, e, i, n) {
    this.width = t, this.height = e, this.cad_camera = i, this.theme = n, this.camera = null, this.scene = null, this.renderer = null, this.labels = [], this.ready = !1;
  }
  create() {
    const t = new YE(JE), e = 2.5;
    this.scene = new ko(), this.camera = new Ia(
      -this.width,
      this.width,
      this.height,
      -this.height,
      1,
      1e3
    ), this.camera.up = this.cad_camera.up, this.camera.lookAt(new E(0, 0, 0)), this.axes = new z_(
      [0, 0, 0],
      ao,
      e,
      this.width,
      this.height,
      !0,
      !0,
      this.theme
    ), this.scene.add(this.axes), this.colors = {
      dark: [
        [1, 69 / 255, 0],
        [50 / 255, 205 / 255, 50 / 255],
        [59 / 255, 158 / 255, 1]
      ],
      light: [
        [1, 0, 0],
        [0, 0.5, 0],
        [0, 0, 1]
      ]
    }, this.cones = [];
    for (var i = 0; i < 3; i++) {
      var n = new Ta(
        0,
        2.5 * e,
        5 * e,
        20,
        1
      );
      const h = new li({
        color: new ct(...this.colors[this.theme][i]),
        toneMapped: !1
      }), c = new re(n, h);
      c.matrixAutoUpdate = !1, this.cones.push(c);
    }
    this.cones[0].geometry.rotateZ(-Math.PI / 2), this.cones[0].geometry.translate(ao, 0, 0), this.cones[1].geometry.translate(0, ao, 0), this.cones[2].geometry.rotateX(Math.PI / 2), this.cones[2].geometry.translate(0, 0, ao), this.scene.add(...this.cones);
    const s = ["X", "Y", "Z"];
    for (i = 0; i < 3; i++) {
      const h = new Pe({
        // color: new THREE.Color(...this.colors[this.theme][i]),
        color: this.theme === "dark" ? new ct(0.9, 0.9, 0.9) : new ct(0, 0, 0),
        side: Mi
      }), c = t.generateShapes(s[i], 16), u = new Go(c);
      u.computeBoundingBox();
      const d = -0.5 * (u.boundingBox.max.x - u.boundingBox.min.x), p = -0.5 * (u.boundingBox.max.y - u.boundingBox.min.y);
      u.translate(d, p, 0);
      const f = new re(u, h);
      this.scene.add(f), this.labels.push(f);
    }
    const r = new Ra(3 * e, 20, 20), o = new li({ color: 10526880 }), l = new re(r, o);
    this.scene.add(l), this.scene.background = null, this.ready = !0;
  }
  setVisible(t) {
    for (var e of this.scene.children)
      e.visible = t;
  }
  dispose() {
    R_(this.scene, (t) => {
      var e, i;
      (e = t.geometry) == null || e.dispose(), (i = t.material) == null || i.dispose();
    }), this.scene = null, this.camera = null, this.cad_camera = null, this.cones = null, this.labels = null;
  }
  render(t) {
    this.ready && (t.setViewport(0, 0, this.width, this.height), t.render(this.scene, this.camera));
  }
  // handler (bound to OrientationMarker instance)
  update(t, e) {
    if (this.ready) {
      let n = new ve().setFromUnitVectors(
        new E(0, 0, 1),
        t.normalize()
      );
      this.camera.position.set(0, 0, 1).applyQuaternion(n).multiplyScalar(300), this.camera.quaternion.copy(e);
      for (var i = 0; i < 3; i++)
        this.labels[i].position.set(
          i == 0 ? cd : 0,
          i == 1 ? cd : 0,
          i == 2 ? cd : 0
        ), this.labels[i].quaternion.copy(e);
    }
  }
  changeTheme(t) {
    for (const e in this.cones) {
      const i = this.cones[e];
      i.material.color = new ct(...this.colors[t][e]);
    }
    this.axes.changeTheme(t);
    for (const e in this.labels) {
      const i = this.labels[e];
      i.material.color = t === "dark" ? new ct(0.9, 0.9, 0.9) : new ct(0, 0, 0);
    }
  }
}
const xe = {
  unselected: 0,
  selected: 1,
  mixed: 2,
  disabled: 3
};
var gg = 0;
class QE {
  /**
   * Constructs a TreeView object.
   *
   * @param {HTMLElement} container - The container element for the tree view.
   * @param {Object} tree - The tree structure data.
   * @param {boolean} [debug=false] - Indicates whether to enable debug mode.
   */
  constructor(t, e, i, n, s, r, o, l, h, c = !1) {
    /************************************************************************************
     *  Handlers
     ************************************************************************************/
    /**
     * Handles the scroll event.
     */
    k(this, "handleScroll", () => {
      this.scrollContainer && (this.lastScrollTop = this.scrollContainer.scrollTop, this.debug && console.log("update => scroll"), this.update());
    });
    /**
     * Handles the click event on a navigation node.
     *
     * @param {Object} node - The node associated with the navigation marker.
     * @returns {Function} - The event handler function.
     */
    k(this, "handleNavigationClick", (t) => (e) => {
      e.stopPropagation(), t.expanded = !t.expanded, this.showChildContainer(t), this.debug && console.log("update => navClick"), this.update();
    });
    /**
     * Handles the click event on an icon.
     *
     * @param {Node} node - The node associated with the icon.
     * @param {string} s - The icon number 's'.
     * @returns {Function} - The event handler function.
     */
    k(this, "handleIconClick", (t, e) => (i) => {
      i.stopPropagation(), this.toggleIcon(t, e);
    });
    /**
     * Updates the tree view with the given prefix.
     *
     * @param {string|null} prefix - The prefix to filter the visible elements.
     *                               If null, all elements are considered.
     */
    k(this, "update", (t = null) => {
      const e = this.getVisibleElements().filter(
        (s) => t == null || s.dataset.path.startsWith(t)
      );
      for (var i of e) {
        const s = i.dataset.path, r = this.findNodeByPath(s);
        if (r != null) {
          if (r.rendered || (this.renderNode(r, i), r.rendered = !0), r.expanded) {
            const o = i.querySelector(".tv-children");
            if (o != null && o.children != null && o.children.length === 0) {
              for (var n in r.children) {
                const l = r.children[n];
                this.renderPlaceholder(l, o);
              }
              this.showChildContainer(r), this.update(s);
            }
          }
          for (let o in [0, 1]) {
            const l = i.dataset[`state${o}`], h = r.state[o];
            l != h && this.updateIconInDOM(r, o);
          }
          this.showChildContainer(r);
        } else
          console.error(`Node not found: ${s}`);
      }
    });
    /************************************************************************************
     *  DOM functions
     ************************************************************************************/
    /**
     * Retrieves the DOM node with the specified path.
     *
     * @param {string} path - The path of the DOM node to retrieve.
     * @returns {Element|null} - The DOM node with the specified path, or null if not found.
     */
    k(this, "getDomNode", (t) => this.container.querySelector(`[data-path="${t}"]`));
    /**
     * Updates the object based on the provided node.
     * @param {Object} node - The node to update the object with.
     */
    k(this, "updateObject", (t, e) => {
      var i = e == 0 && this.linkIcons ? [0, 1] : [e];
      for (var n of i)
        this.objectHandler(this.getNodePath(t), t.state[n], n, !0, !1);
    });
    this.viewIcons = [
      ["shape_no", "shape", "shape_mix", "shape_empty"],
      ["mesh_no", "mesh", "mesh_mix", "mesh_empty"]
    ], this.navIcons = {
      right: "▾",
      down: "▸"
    }, this.tree = t, this.offset = 12, this.scrollContainer = e, this.objectHandler = i, this.pickHandler = n, this.updateHandler = s, this.notificationHandler = r, this.colorGetter = o, this.theme = l, this.linkIcons = h, this.debug = c;
  }
  create() {
    return this.maxLevel = 0, this.root = this.buildTreeStructure(this.tree), this.container = document.createElement("ul"), this.container.classList.add("tcv_toplevel"), this.scrollContainer.addEventListener("scroll", this.handleScroll), this.lastLabel = null, this.container;
  }
  /************************************************************************************
   *  Tree creation and synching
   ************************************************************************************/
  /**
   * Builds a tree structure based on the provided data.
   *
   * @param {Object} data - The data used to build the tree structure.
   * @returns {Object} - The root node of the tree structure.
   */
  buildTreeStructure(t) {
    const e = (n, s, r) => {
      var o = [-1, -1];
      const l = (p) => {
        for (let f of [0, 1])
          p[xe.mixed][f] || p[xe.selected][f] && p[xe.unselected][f] ? o[f] = xe.mixed : p[xe.selected][f] ? o[f] = xe.selected : p[xe.unselected][f] ? o[f] = xe.unselected : p[xe.disabled][f] && (o[f] = xe.disabled);
        return o;
      }, h = {};
      this.maxLevel < r && (this.maxLevel = r);
      var c = [
        [!1, !1],
        [!1, !1],
        [!1, !1],
        [!1, !1]
      ];
      for (const p in n) {
        var u = "";
        s == null ? u = p : u = `${s}/${p}`;
        let f;
        const y = n[p];
        if (Array.isArray(y))
          f = y, c[y[0]][0] = !0, c[y[1]][1] = !0, h[p] = {
            name: p,
            state: f,
            path: u,
            rendered: !1,
            level: r
          };
        else {
          let g;
          [g, f] = e(y, u, r + 1), c[f[0]][0] = !0, c[f[1]][1] = !0, h[p] = {
            name: p,
            state: f,
            path: u,
            rendered: !1,
            level: r,
            children: g,
            expanded: !1
          };
        }
      }
      const d = l(c);
      return [h, d];
    }, i = e(t, null, 0)[0];
    return i[Object.keys(i)[0]];
  }
  /************************************************************************************
   * Visble elements handling
   ************************************************************************************/
  /**
   * Retrieves the visible elements within the container.
   * @returns {Element[]} An array of visible elements.
   */
  getVisibleElements() {
    const t = (s, r) => {
      const o = s.getBoundingClientRect();
      return o.height > 0 && o.top >= -this.offset && o.top <= r.bottom + this.offset;
    }, e = this.container.querySelectorAll(".tv-tree-node"), i = this.scrollContainer.getBoundingClientRect(), n = Array.from(e).filter(
      (s) => t(s, i)
    );
    if (this.debug) {
      gg++, console.log(
        `
${gg}> visible elements (${n.length}):`
      );
      for (let s in n) {
        const r = n[s], o = this.findNodeByPath(r.dataset.path);
        console.log(
          o.path,
          o.state[0],
          o.state[1],
          " => ",
          r.dataset.state0,
          r.dataset.state1
        );
      }
    }
    return n;
  }
  /**
   * Handles the click event on a label.
   *
   * @param {Node} node - The node that was clicked.
   * @returns {void}
   */
  handleLabelClick(t, e) {
    this.pickHandler(
      this.getNodePath(this.getParent(t)),
      t.name,
      De.get(e, "meta"),
      De.get(e, "shift"),
      De.get(e, "alt"),
      null,
      this.isLeaf(t) ? "leaf" : "node",
      !0
    ), console.log(`Label clicked: ${this.getNodePath(t)}`);
  }
  /************************************************************************************
   *  Rendering routines
   ************************************************************************************/
  /**
   * Renders the tree view by clearing the container, rendering the placeholder,
   * and updating the tree.
   */
  render() {
    this.container.innerHTML = "", this.renderPlaceholder(this.root, this.container), this.debug && console.log("update => render"), this.update();
  }
  /**
   * Renders a placeholder node in the tree view.
   *
   * @param {Object} node - The node object to render.
   * @param {HTMLElement} container - The container element to append the rendered node to.
   * @param {string|null} openPath - The path of the node to be opened, or null if no node should be opened.
   */
  renderPlaceholder(t, e, i = null) {
    this.debug && console.log("renderPlaceholder", t.path, t.level);
    const n = document.createElement("div");
    n.className = "tv-tree-node", n.dataset.path = this.getNodePath(t), n.dataset.openPath = i, n.dataset.state0 = t.state[0], n.dataset.state1 = t.state[1];
    const s = document.createElement("div");
    s.className = "tv-node-content", this.debug && (s.innerText = t.path), n.appendChild(s), e.appendChild(n);
  }
  /**
   * Renders a node in the tree view to replace the placeholder.
   *
   * @param {Object} node - The node object to render.
   * @param {HTMLElement} parentElement - The parent element to append the rendered node to.
   * @returns {HTMLElement} - The container element for the node's children, if any.
   */
  renderNode(t, e) {
    this.debug && console.log("renderNode", t.path, t.level);
    const i = document.createElement("div");
    i.className = "tv-node-content", e.removeChild(e.firstChild), e.appendChild(i);
    const n = document.createElement("span");
    n.className = "tv-nav-marker", n.innerHTML = t.children ? t.expanded ? "▾" : "▸" : "", n.onclick = this.handleNavigationClick(t), i.dataset.state0 = t.state[0], i.dataset.state1 = t.state[1], i.appendChild(n);
    for (var s of [0, 1]) {
      const c = document.createElement("span"), u = t.state[s];
      var r = `tv-icon tv-icon${s}`;
      u !== xe.disabled && (r += " tv-pointer"), c.className = r, c.classList.add("tcv_tree_button"), c.classList.add(`tcv_button_${this.viewIcons[s][u]}`), u !== xe.disabled && (c.onmousedown = (d) => {
        d.preventDefault();
      }, c.onclick = this.handleIconClick(t, s)), i.appendChild(c);
    }
    const o = document.createElement("span");
    o.className = "tv-node-label", o.innerHTML = t.name;
    const l = this.colorGetter(t.path);
    l != null && (o.innerHTML += `<span style="color:${l}"> ⚈</span>`), o.onmousedown = (c) => {
      c.preventDefault();
    }, o.oncontextmenu = (c) => {
      c.preventDefault(), c.stopPropagation(), this.handleLabelClick(t, c);
    }, o.onclick = (c) => {
      c.stopPropagation(), this.handleLabelClick(t, c);
    }, i.appendChild(o);
    let h = null;
    return t.children && (h = document.createElement("div"), h.className = "tv-children", h.style.display = "none", e.appendChild(h)), h;
  }
  /**
   * Shows or hides the child container of a node based on the expanded parameter.
   *
   * @param {object} node - The node object.
   */
  showChildContainer(t) {
    if (t.expanded == null) return;
    const e = this.getNodePath(t), i = this.getDomNode(e);
    if (i) {
      const n = i.querySelector(".tv-children");
      n && n.style.display !== "none" !== t.expanded && (n.style.display = t.expanded ? "block" : "none", i.querySelector(".tv-nav-marker").innerHTML = t.expanded ? this.navIcons.right : this.navIcons.down, t.expanded || (this.debug && console.log("update => showChildContainer"), this.update()));
    } else
      console.error(`Element not found: ${e}`);
  }
  /**
   * Updates the icon in the DOM for a given node.
   *
   * @param {Node} node - The node to update the icon for.
   * @param {number} iconNumber - The icon number to update.
   */
  updateIconInDOM(t, e) {
    const i = this.getNodePath(t), n = this.container.querySelector(
      `[data-path="${i}"]`
    );
    if (n) {
      const r = n.querySelector(`.tv-icon${e}`);
      if (r) {
        for (var s of this.viewIcons[e])
          r.classList.remove(`tcv_button_${s}`);
        r.classList.add(
          `tcv_button_${this.viewIcons[e][t.state[e]]}`
        );
      }
      n.dataset[`state${e}`] = t.state[e];
    }
  }
  /**
   * Toggles the color of the label for a given node.
   * @param {Node} node - The node for which to toggle the label color.
   * @param {str} path - If node is null, the path for which to toggle the label color.
   */
  toggleLabelColor(t, e = null) {
    const i = e ?? this.getNodePath(t), n = this.container.querySelector(
      `[data-path="${i}"]`
    );
    if (this.lastLabel && this.lastLabel.classList.remove("tv-node-label-highlight"), n) {
      const s = n.querySelector(".tv-node-label");
      s && (this.lastLabel === s ? this.lastLabel = null : (s.classList.toggle("tv-node-label-highlight"), this.lastLabel = s));
    }
  }
  /************************************************************************************
   *  Tree handling functions
   ************************************************************************************/
  /**
   * Traverses a tree-like structure and applies a callback function to each node.
   * @param {Object} node - The root node of the tree.
   * @param {Function} callback - The callback function to be applied to each node.
   */
  traverse(t, e) {
    if (e(t), t.children)
      for (let i of Object.keys(t.children))
        this.traverse(t.children[i], e);
  }
  /**
   * Checks if a given node is a leaf node.
   *
   * @param {Object} node - The node to check.
   * @returns {boolean} - Returns true if the node is a leaf node, false otherwise.
   */
  isLeaf(t) {
    return t.children == null;
  }
  /**
   * Returns the path of a given node.
   *
   * @param {Node} node - The node object.
   * @returns {string} The path of the node.
   */
  getNodePath(t) {
    return t == null ? "" : "/" + t.path;
  }
  /**
   * Finds a node in the tree by its path.
   *
   * @param {string|string[]} path - The path of the node to find. Can be either a string or an array of strings.
   * @returns {object|null} - The found node or null if the node is not found.
   */
  findNodeByPath(t) {
    var e = Array.isArray(t) ? t : t.split("/").filter(Boolean);
    let i = this.root;
    for (let n = 1; n < e.length; n++) {
      const s = e[n];
      if (i.children[s])
        i = i.children[s];
      else
        return null;
    }
    return i;
  }
  /**
   * Retrieves the parent node of the given node.
   *
   * @param {Object} node - The node for which to find the parent.
   * @returns {Object|null} - The parent node if found, or null if the given node is the root node.
   */
  getParent(t) {
    const e = t.path.substring(0, t.path.lastIndexOf("/"));
    return e.length === 0 ? null : this.findNodeByPath(e);
  }
  /**
   * Toggles the state of an icon for a given node.
   *
   * @param {Node} node - The node for which to toggle the icon state.
   * @param {number} iconNumber - The index of the icon to toggle.
   * @returns {void}
   */
  toggleIcon(t, e, i = null) {
    const n = t.state[e];
    if (n !== xe.disabled) {
      var s = e == 0 ? this.linkIcons ? [0, 1] : [0] : [1];
      for (var r of s)
        t.state[r] != 3 && (i != null ? t.state[r] = i ? 1 : 0 : t.state[r] = n === xe.selected ? xe.unselected : xe.selected), this.updateObject(t, e), this.updateParentStates(t, r), this.updateChildrenStates(t, r), this.update(null, r);
      this.updateHandler(!0), this.notificationHandler();
    }
  }
  /**
   * Hides all nodes in the tree.
   */
  hideAll() {
    this.toggleIcon(this.root, 0, !1), (!this.linkIcons || this.root.state[0] === 3) && this.toggleIcon(this.root, 1, !1);
  }
  /**
   * Shows all nodes in the tree.
   */
  showAll() {
    this.toggleIcon(this.root, 0, !0), this.linkIcons || this.toggleIcon(this.root, 1, !0);
  }
  /**
   * Shows the node specified by the given path.
   *
   * @param {string} path - The path of the node to be shown.
   */
  show(t) {
    const e = this.findNodeByPath(t);
    e && this.toggleIcon(e, 0, !0);
  }
  /**
   * Retrieves the states of a node specified by the given path.
   *
   * @param {string} path - The path of the node.
   * @returns {object|null} - The states of the node, or null if the node is not found.
   */
  getState(t) {
    const e = this.findNodeByPath(t);
    return e ? e.state : null;
  }
  /**
   * Retrieves the states of all leaf nodes in the tree.
   * @returns {Object} An object containing the states of all leaf nodes.
   */
  getStates() {
    const t = {}, e = (i) => {
      this.isLeaf(i) && (t[this.getNodePath(i)] = i.state);
    };
    return this.traverse(this.root, e), t;
  }
  /**
   * Sets the state of a node identified by the given path.
   *
   * @param {string} path - The path of the node.
   * @param {Array} state - The new state of the node.
   */
  setState(t, e) {
    const i = this.findNodeByPath(t);
    i && (this.toggleIcon(i, 0, e[0]), this.toggleIcon(i, 1, e[1]));
  }
  /**
   * Sets the states of the nodes based on the provided states object.
   *
   * @param {Object} states - The states object containing the node paths and their corresponding states.
   */
  setStates(t) {
    for (var e in t)
      this.setState(e, t[e]);
    this.update();
  }
  /**
   * Hides the node specified by the given path.
   *
   * @param {string} path - The path of the node to hide.
   */
  hide(t) {
    const e = this.findNodeByPath(t);
    e && this.toggleIcon(e, 0, !1);
  }
  /**
   * Updates the state of parent nodes based on the state of their children.
   *
   * @param {Node} node - The node whose parent states need to be updated.
   * @param {number} iconNumber - The icon number representing the state.
   */
  updateParentStates(t, e) {
    let i = this.getParent(t);
    for (; i; ) {
      const n = Object.values(i.children), s = n.every(
        (l) => l.state[e] === xe.selected || l.state[e] === xe.disabled
      ), r = n.every(
        (l) => l.state[e] === xe.unselected || l.state[e] === xe.disabled
      ), o = s ? xe.selected : r ? xe.unselected : xe.mixed;
      i.state[e] !== o && i.state[e] !== xe.disabled && (i.state[e] = o, this.updateObject(i, e)), i = this.getParent(i);
    }
  }
  /**
   * Updates the states of the children nodes based on the given icon number.
   *
   * @param {Object} node - The node whose children states need to be updated.
   * @param {number} iconNumber - The icon number to determine the new state of the children nodes.
   */
  updateChildrenStates(t, e) {
    const i = t.state[e], n = (s) => {
      if (s.state[e] !== i && s.state[e] !== xe.disabled && (s.state[e] = i, this.updateObject(s, e)), s.children)
        for (var r in s.children)
          n(s.children[r]);
    };
    n(t);
  }
  /************************************************************************************
   *  Tree handling high level API
   ************************************************************************************/
  /**
   * Scrolls the parent container to center the specified element within the visible area.
   * Ensures the scrolling does not exceed the scrollable bounds of the parent container.
   *
   * @param {HTMLElement} element - The DOM element to center within the scroll container.
   */
  scrollCentered(t) {
    if (t != null) {
      let e = this.scrollContainer;
      const i = t.offsetHeight, n = e.clientHeight, r = t.offsetTop - e.offsetTop - n / 2 + i / 2, o = e.scrollHeight - n, l = Math.max(0, Math.min(r, o));
      e.scrollTo({ top: l, behavior: "smooth" });
    }
  }
  /**
   * Opens the specified path in the tree view.
   *
   * @param {string} path - The path to open in the tree view.
   */
  openPath(t) {
    const e = t.split("/").filter(Boolean);
    var i = "", n;
    let s;
    for (var r of e)
      if (i += "/" + r, n = this.findNodeByPath(i), s = this.getDomNode(i), n)
        n.expanded = !0, this.showChildContainer(n), this.debug && console.log("update => openPath"), this.update();
      else {
        console.error(`Path not found: ${i}`);
        break;
      }
    this.scrollCentered(s), this.toggleLabelColor(n);
  }
  /**
   * Closes the specified path in the tree view.
   *
   * @param {string} path - The path to be closed.
   */
  closePath(t) {
    const e = this.findNodeByPath(t);
    if (e) {
      e.expanded = !1, this.showChildContainer(e);
      const i = this.getDomNode(t);
      if (i != null) {
        const n = this.scrollContainer;
        n.scrollTop = i.offsetTop - n.offsetTop;
      }
      this.debug && console.log("update => collapsePath"), this.update();
    } else
      console.error(`Path not found: ${t}`);
  }
  /**
   * Opens the specified level in the tree view.
   * @param {number} level - The level to open.
   */
  openLevel(t) {
    const e = (s) => {
      this.isLeaf(s) || (t == -1 ? s.expanded = s.children != null && !(Object.keys(s.children).length == 1 && this.isLeaf(Object.values(s.children)[0])) : s.expanded = s.level < t);
    };
    this.traverse(this.root, e);
    const i = this.getDomNode(this.getNodePath(this.root));
    if (i != null) {
      const s = this.scrollContainer;
      s.scrollTop = i.offsetTop - s.offsetTop;
    }
    for (var n = 0; n <= (t == -1 ? this.maxLevel : t); n++)
      this.debug && console.log("update => openLevel"), this.update();
  }
  /**
   * Collapses all nodes in the tree view.
   */
  collapseAll() {
    this.openLevel(0);
  }
  /**
   * Expands all nodes in the treeview.
   */
  expandAll() {
    this.openLevel(this.maxLevel);
  }
  dispose() {
    this.root = null, this.tree = null, this.scrollContainer.removeEventListener("scroll", this.handleScroll);
  }
}
class ud {
  constructor(t, e) {
    this.prefix = t, this.timeit = e, this.start = performance.now(), this.last = this.start, e && console.info(`three-cad-viewer: ${t}:timer start`);
  }
  split(t) {
    if (this.timeit) {
      const e = performance.now();
      console.info(
        `three-cad-viewer: ${this.prefix}:${t}:timer split ${(e - this.last).toFixed(1)} ms`
      ), this.last = e;
    }
  }
  stop() {
    if (this.timeit) {
      const t = performance.now();
      console.info(
        `three-cad-viewer: ${this.prefix}:timer stop ${(t - this.start).toFixed(
          1
        )} ms:`
      );
    }
  }
}
const dd = [
  new E(-1, 0, 0),
  new E(0, -1, 0),
  new E(0, 0, -1)
], Xl = {
  light: [16711680, 65280, 255],
  dark: [16729344, 3329330, 3907327]
}, tT = new li({
  opacity: 0.1,
  transparent: !0,
  depthWrite: !1,
  toneMapped: !1,
  side: Mi
}), eT = new li({
  depthWrite: !1,
  depthTest: !1,
  colorWrite: !1,
  side: He,
  stencilWrite: !0,
  stencilFunc: To,
  stencilFail: Sh,
  stencilZFail: Sh,
  stencilZPass: Sh
}), iT = new li({
  depthWrite: !1,
  depthTest: !1,
  colorWrite: !1,
  side: $i,
  stencilWrite: !0,
  stencilFunc: To,
  stencilFail: wh,
  stencilZFail: wh,
  stencilZPass: wh
}), nT = new hr({
  metalness: 0.3,
  roughness: 0.65,
  opacity: 1,
  transparent: !1,
  side: Mi,
  polygonOffset: !0,
  polygonOffsetFactor: 1,
  polygonOffsetUnits: 1,
  stencilWrite: !0,
  stencilRef: 0,
  stencilFunc: ry,
  stencilFail: Mh,
  stencilZFail: Mh,
  stencilZPass: Mh
});
class yg extends qn {
  constructor(t, e, i) {
    super(t, e), this.center = i, this.setConstant(e);
  }
  setConstant(t) {
    this.centeredConstant = t;
    const e = this.distanceToPoint(new E(...this.center)), i = this.distanceToPoint(new E(0, 0, 0));
    this.constant = i - e + t;
  }
}
const xo = class xo extends re {
  constructor(e, i, n, s, r, o, l) {
    const h = new Ds(2, 2);
    h.computeBoundingSphere(), r.color.set(new ct(o));
    super(h, r);
    k(this, "onAfterRender", (e) => {
      this.type.startsWith("StencilPlane") && e.clearStencil();
    });
    this.type = l, this.index = e, this.plane = i, this.size = s, this.center = n;
  }
  // https://discourse.threejs.org/t/center-threejs-planehelper-on-geometry/48516/4
  updateMatrixWorld(e) {
    this.position.set(0, 0, 0), this.scale.set(0.5 * this.size, 0.5 * this.size, 1), xo.matrix.lookAt(this.position, this.plane.normal, this.up), this.quaternion.setFromRotationMatrix(xo.matrix), this.translateZ(this.plane.constant), super.updateMatrixWorld(this, e);
  }
};
k(xo, "matrix", new Vt());
let Mc = xo;
function _g(a, t, e, i) {
  t.clippingPlanes = [i];
  const n = new re(e, t);
  return n.name = a, n;
}
class sT extends yi {
  constructor(e, i, n, s, r) {
    super();
    k(this, "setNormal", (e, i) => {
      var n = i.clone();
      this.clipPlanes[e].normal = n, this.reverseClipPlanes[e].normal = n.clone().negate(), this.setConstant(e, this.distance), this.display.setNormalLabel(e, n.toArray());
    });
    k(this, "getObjectColorCaps", () => this.objectColorCaps);
    k(this, "setObjectColorCaps", (e) => {
      var i;
      for (i of this.nestedGroup.rootGroup.children)
        if (i.name === "PlaneMeshes")
          break;
      var n = 0, s = -1;
      const r = Object.keys(i.children).length / 3;
      for (var o of i.children)
        n % r === 0 && s++, e ? o.material.color.set(new ct(this.objectColors[n])) : o.material.color.set(new ct(Xl[this.theme][s])), n++;
      this.objectColorCaps = e;
    });
    k(this, "setVisible", (e) => {
      var i;
      for (i of this.nestedGroup.rootGroup.children)
        if (i.name === "PlaneMeshes")
          break;
      for (var n of i.children)
        n.material.visible = e;
    });
    this.center = e, this.distance = i / 2, this.display = s, this.theme = r, this.nestedGroup = n, this.planeHelpers = new yi(), this.planeHelpers.name = "PlaneHelpers", this.clipPlanes = [], this.reverseClipPlanes = [], this.add(this.planeHelpers), this.name = "PlaneHelpers", this.objectColors = [], this.objectColorCaps = !1;
    var o;
    for (o = 0; o < 3; o++) {
      const f = new yg(dd[o], this.distance, e);
      this.clipPlanes.push(f);
      const y = new yg(
        dd[o].clone().negate(),
        -this.distance,
        e
      );
      this.reverseClipPlanes.push(y), this.display.setNormalLabel(o, dd[o].toArray());
      const g = tT.clone();
      g.opacity = r === "dark" ? 0.2 : 0.1, this.planeHelpers.add(
        new Mc(
          o,
          f,
          e,
          i,
          g,
          Xl[r][o],
          "PlaneHelper"
        )
      );
    }
    for (this.planeHelpers.visible = !1, o = 0; o < 3; o++) {
      const f = this.clipPlanes.filter((y, g) => g !== o);
      this.planeHelpers.children[o].material.clippingPlanes = f;
    }
    var l = new yi();
    for (l.name = "PlaneMeshes", o = 0; o < 3; o++) {
      const f = this.clipPlanes[o], y = this.clipPlanes.filter((g, m) => m !== o);
      var h = 0;
      for (var c in n.groups) {
        var u = new yi();
        u.name = `clipping-${o}`;
        var d = n.groups[c];
        if (d instanceof ln && d.subtype === "solid") {
          this.objectColors.push(d.children[0].material.color.getHex()), u.add(
            _g(
              `frontStencil-${o}-${h}`,
              iT.clone(),
              d.shapeGeometry,
              f
            )
          ), u.add(
            _g(
              `backStencil-${o}-${h}`,
              eT.clone(),
              d.shapeGeometry,
              f
            )
          ), d.addType(u, `clipping-${o}`);
          var p = nT.clone();
          p.color.set(new ct(Xl[r][o])), p.clippingPlanes = y, l.add(
            new Mc(
              o,
              f,
              e,
              i,
              p,
              Xl[r][o],
              `StencilPlane-${o}-${h}`
            )
          ), h++;
        }
      }
    }
    n.rootGroup.add(l);
  }
  setConstant(e, i) {
    this.clipPlanes[e].setConstant(i), this.reverseClipPlanes[e].setConstant(-i);
  }
  dispose() {
    me(this.clipPlanes), me(this.reverseClipPlanes), this.nestedGroup = null, this.clipPlanes = null, this.reverseClipPlanes = null, this.objectColors = null, this.display = null, this.center = null;
  }
}
const xg = ["t", "tx", "ty", "tz", "q", "rx", "ry", "rz"];
function rT(a, t) {
  switch (a) {
    case "x":
      a = new E(1, 0, 0);
      break;
    case "y":
      a = new E(0, 1, 0);
      break;
    case "z":
      a = new E(0, 0, 1);
      break;
  }
  var e = new ve();
  return e.setFromAxisAngle(a, t / 180 * Math.PI), e;
}
class aT {
  constructor(t) {
    this.delim = t, this.tracks = [], this.mixer = null, this.clip = null, this.clipAction = null, this.clock = new lf(), this.duration = 0, this._backup = [], this.root = null, this.duration = null, this.speed = null, this.repeat = null;
  }
  addTrack(t, e, i, n, s) {
    if (t = t.replaceAll("/", this.delim), xg.indexOf(i) === -1) {
      console.error(`Unknown action: "${i}" not in ${xg}`);
      return;
    }
    if (n.length != s.length) {
      console.error("times and values arrays need have the same lenght");
      return;
    }
    var r;
    if (i.startsWith("t")) {
      const o = e.position;
      switch (i) {
        case "t":
          r = s.map(
            (l) => o.clone().add(new E(...l)).toArray()
          );
          break;
        case "tx":
          r = s.map(
            (l) => o.add(new E(l, 0, 0)).toArray()
          );
          break;
        case "ty":
          r = s.map(
            (l) => o.add(new E(0, l, 0)).toArray()
          );
          break;
        case "tz":
          r = s.map(
            (l) => o.add(new E(0, 0, l)).toArray()
          );
          break;
        default:
          console.error(`action ${i} is not supported`);
          return;
      }
      this.tracks.push(
        new ba(
          t + ".position",
          n,
          r.flat()
        )
      );
    } else {
      const o = e.quaternion;
      if (i.startsWith("r"))
        r = s.map(
          (h) => rT(i.slice(1), h)
        ).map(
          (h) => o.clone().multiply(h).toArray()
        );
      else if (i == "q")
        r = s.map((l) => o.clone().multiply(l).toArray());
      else {
        console.error(`action ${i} is not supported`);
        return;
      }
      this.tracks.push(
        new Pa(
          t + ".quaternion",
          n,
          r.flat()
        )
      );
    }
  }
  backup() {
    this._backup = {
      tracks: this.tracks,
      root: this.root,
      duration: this.duration,
      speed: this.speed,
      repeat: this.repeat
    };
  }
  restore() {
    return this.tracks = this._backup.tracks, {
      duration: this._backup.duration,
      speed: this._backup.speed,
      repeat: this._backup.repeat
    };
  }
  cleanBackup() {
    this._backup = [];
  }
  hasTracks() {
    return this.tracks != null && this.tracks.length > 0;
  }
  hasBackup() {
    return this._backup != null && Object.keys(this._backup).length > 0;
  }
  animate(t, e, i, n = !0) {
    return this.root = t, this.duration = e, this.speed = i, this.repeat = n, this.clip = new Ma("track", e, this.tracks), this.mixer = new y_(t), this.mixer.timeScale = i, this.clipAction = this.mixer.clipAction(this.clip), this.clipAction.setLoop(n ? Ip : Lp), this.clipAction;
  }
  setRelativeTime(t) {
    this.clipAction.play(), this.clipAction.paused = !0;
    var e = this.duration * t;
    this.clipAction.time = e;
  }
  getRelativeTime() {
    return this.clipAction.time / this.duration;
  }
  dispose() {
    this.mixer = null, this.clipAction = null, this.clip = null, this.tracks = [], this.root = null;
  }
  update() {
    this.mixer && this.mixer.update(this.clock.getDelta());
  }
}
class oT {
  constructor(t, e) {
    this.html = t, this.clear();
  }
  clear() {
    this.html.value = "", this.number = 0, this.chunks = [];
  }
  dispose() {
    this.clear(), this.html.innerHTML = "";
  }
  addText(t) {
    this.addHtml(`<pre style="white-space: nowrap;">${t}</pre>`);
  }
  addHtml(t) {
    this.chunks.unshift([this.number, t]), this.number += 1, this.render();
  }
  render() {
    var t = "<table class='tcv_info_table'>";
    for (var e of this.chunks)
      t += "<tr class='tcv_info_row'>", t += `<td><pre class="tcv_info_num">[${e[0]}]</pre></td>`, t += `<td>${e[1]}</td>`, t += "</tr>";
    t += "</table>", this.html.innerHTML = t;
  }
  versionMsg(t, e) {
    this.addHtml(
      `<b>Versions</b>
          <table>
            <tr class="tcv_small_table"><td>CadQuery:</td>        <td>${t}</td> </tr>
            <tr class="tcv_small_table"><td>Jupyter CadQuery:</td><td>${e}</td> </tr>
          </table>`
    );
  }
  readyMsg(t, e) {
    var i = `<div class="tcv_info_header">Ready</div>
            <table class="small_table">
              <tr class="tcv_small_table_row" ><td>Version</td><td>${t}</td> </tr>
              <tr class="tcv_small_table_row" ><td>Control</td><td>${e}</td></tr>
              <tr class="tcv_small_table_row" ><td>Axes</td>
                <td>
                  <span class="tcv_info_red"><b>X</b></span>,
                  <span class="tcv_info_green"><b>Y</b></span>,
                  <span class="tcv_info_blue"><b>Z</b></span>
                </td> 
              </tr>
            </table>`;
    this.addHtml(i);
  }
  bbInfo(t, e, i) {
    var n = `
            <table class="tcv_small_table">
                <tr class="tcv_small_table_row">
                    <td><b>Path:</b></td>
                    <td>${t}</td>
                </tr>
                <tr class="tcv_small_table_row">
                    <td><b>Name:</b></td>
                    <td>${e}</td>
                </tr>
            </table>
            `;
    n += `
            <div class="tcv_info_header">Bounding box:</div>
            <table class="tcv_small_table">
                <tr class="tcv_small_table_row">
                    <th></th>
                    <th>min</th>
                    <th>max</th>
                    <th>center</th>
                </tr>
            `;
    var s = new E();
    i.getCenter(s), ["x", "y", "z"].forEach((r) => {
      n += `
                <tr class="tcv_small_table_row">
                    <th>${r}</th>
                    <td align='right'>${i.min[r].toFixed(3)}</td>
                    <td align='right'>${i.max[r].toFixed(3)}</td>
                    <td align='right'>${s[r].toFixed(3)}</td>
                </tr>
            `;
    }), n += "</table>", this.addHtml(n);
  }
  centerInfo(t) {
    var e = `<div>Camera target set to AABB center:</div><div class='tcv_info_line'>{ x: ${t[0].toFixed(2)}, y: ${t[1].toFixed(2)}, z: ${t[2].toFixed(2)} }</div>`;
    this.addHtml(e);
  }
}
var Ps = function(a, t) {
  t === void 0 && console.warn('THREE.CameraControls: The second parameter "domElement" is now mandatory.'), t === document && console.error('THREE.CameraControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.'), this.object = a, this.domElement = t, this.enabled = !0, this.target = new E(), this.trackball = !1, this.holroyd = !0, this.radius = 0.9, this.minDistance = 0, this.maxDistance = 1 / 0, this.minZoom = 0, this.maxZoom = 1 / 0, this.minPolarAngle = 0, this.maxPolarAngle = Math.PI, this.minAzimuthAngle = -1 / 0, this.maxAzimuthAngle = 1 / 0, this.enableDamping = !1, this.dampingFactor = 0.05, this.enableZoom = !0, this.zoomSpeed = 1, this.enableRotate = !0, this.rotateSpeed = 1, this.enablePan = !0, this.panSpeed = 1, this.screenSpacePanning = !1, this.keyPanSpeed = 7, this.autoRotate = !1, this.autoRotateSpeed = 2, this.enableKeys = !0, this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 }, this.mouseButtons = { LEFT: Ze.ROTATE, MIDDLE: Ze.DOLLY, RIGHT: Ze.PAN }, this.touches = { ONE: zi.ROTATE, TWO: zi.DOLLY_PAN }, this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.quaternion0 = this.object.quaternion.clone(), this.zoom0 = this.object.zoom, this.getPolarAngle = function() {
    return u.phi;
  }, this.getAzimuthalAngle = function() {
    return u.theta;
  }, this.saveState = function() {
    n.target0.copy(n.target), n.position0.copy(n.object.position), n.quaternion0.copy(n.object.quaternion), n.zoom0 = n.object.zoom;
  }, this.reset = function() {
    n.target.copy(n.target0), n.object.position.copy(n.position0), n.object.quaternion.copy(n.quaternion0), n.object.zoom = n.zoom0, n.object.updateProjectionMatrix(), n.dispatchEvent(s), n.update(), h = l.NONE;
  }, this.update = function() {
    var I = new E(), lt = new ve().setFromUnitVectors(a.up, new E(0, 1, 0)), gt = lt.clone().invert(), j = new E(), mt = new ve(), At = new ve(), Tt = new E();
    const vt = new E();
    return function() {
      var F = n.object.position, ht;
      if (I.copy(F).sub(n.target), n.trackball && !n.holroyd)
        d.theta && (Tt.set(0, 1, 0).applyQuaternion(n.object.quaternion), ht = n.enableDamping ? n.dampingFactor : 1, At.setFromAxisAngle(Tt, d.theta * ht), n.object.quaternion.premultiply(At), I.applyQuaternion(At)), d.phi && (Tt.set(1, 0, 0).applyQuaternion(n.object.quaternion), ht = n.enableDamping ? n.dampingFactor : 1, At.setFromAxisAngle(Tt, d.phi * ht), n.object.quaternion.premultiply(At), I.applyQuaternion(At)), I.multiplyScalar(p), I.clampLength(n.minDistance, n.maxDistance);
      else if (n.trackball && n.holroyd) {
        vt.crossVectors(x, _);
        var _t = Math.atan(vt.length() / x.dot(_));
        _t && (vt.normalize(), vt.applyQuaternion(n.object.quaternion), ht = n.enableDamping ? n.dampingFactor : 1, _t *= -2 * ht, At.setFromAxisAngle(vt, _t), n.object.quaternion.premultiply(At), I.applyQuaternion(At)), I.multiplyScalar(p), I.clampLength(n.minDistance, n.maxDistance), x.set(0, 0, 0), _.set(0, 0, 0);
      } else
        I.applyQuaternion(lt), n.autoRotate && h === l.NONE && W(O()), u.setFromVector3(I), n.enableDamping ? (u.theta += d.theta * n.dampingFactor, u.phi += d.phi * n.dampingFactor) : (u.theta += d.theta, u.phi += d.phi), u.theta = Math.max(n.minAzimuthAngle, Math.min(n.maxAzimuthAngle, u.theta)), u.phi = Math.max(n.minPolarAngle, Math.min(n.maxPolarAngle, u.phi)), u.makeSafe(), u.radius *= p, u.radius = Math.max(n.minDistance, Math.min(n.maxDistance, u.radius)), I.setFromSpherical(u), I.applyQuaternion(gt);
      return n.enableDamping === !0 ? n.target.addScaledVector(f, n.dampingFactor) : n.target.add(f), F.copy(n.target).add(I), n.trackball === !1 && n.object.lookAt(n.target), n.enableDamping === !0 ? (d.theta *= 1 - n.dampingFactor, d.phi *= 1 - n.dampingFactor, f.multiplyScalar(1 - n.dampingFactor)) : (d.set(0, 0, 0), f.set(0, 0, 0)), p = 1, y || j.distanceToSquared(n.object.position) > c || 8 * (1 - mt.dot(n.object.quaternion)) > c ? (n.dispatchEvent(s), j.copy(n.object.position), mt.copy(n.object.quaternion), y = !1, !0) : !1;
    };
  }();
  const e = {
    x: new E(1, 0, 0),
    y: new E(0, 1, 0),
    z: new E(0, 0, 1)
  };
  function i(I, lt) {
    if (n.trackball) {
      const gt = e[I], j = new ve().setFromAxisAngle(gt, lt);
      n.object.quaternion.premultiply(j), n.object.position.sub(n.target).applyQuaternion(j).add(n.target);
    } else
      console.log("not supported for orbit controls");
  }
  this.rotateX = function(I) {
    i("x", I);
  }, this.rotateY = function(I) {
    i("y", I);
  }, this.rotateZ = function(I) {
    i("z", I);
  }, this.rotateLeft = function(I) {
    this.trackball ? console.log("not supported for trackball controls") : W(I);
  }, this.rotateUp = function(I) {
    this.trackball ? console.log("not supported for trackball controls") : G(I);
  }, this.dispose = function() {
    n.domElement.removeEventListener("contextmenu", It, !1), n.domElement.removeEventListener("mousedown", Wt, !1), n.domElement.removeEventListener("wheel", A, !1), n.domElement.removeEventListener("touchstart", X, !1), n.domElement.removeEventListener("touchend", Z, !1), n.domElement.removeEventListener("touchmove", rt, !1), document.removeEventListener("mousemove", Nt, !1), document.removeEventListener("mouseup", P, !1), n.domElement.removeEventListener("keydown", N, !1);
  };
  var n = this, s = { type: "change" }, r = { type: "start" }, o = { type: "end" }, l = {
    NONE: -1,
    ROTATE: 0,
    DOLLY: 1,
    PAN: 2,
    TOUCH_ROTATE: 3,
    TOUCH_PAN: 4,
    TOUCH_DOLLY_PAN: 5,
    TOUCH_DOLLY_ROTATE: 6
  }, h = l.NONE, c = 1e-6, u = new op(), d = new op(), p = 1, f = new E(), y = !1, g = new J(), m = new J(), v = new J(), x = new E(), _ = new E(), S = new J(), w = new J(), T = new J(), R = new J(), b = new J(), M = new J(), L = !0, U = !0;
  function O() {
    return 2 * Math.PI / 60 / 60 * n.autoRotateSpeed;
  }
  function V() {
    return Math.pow(0.95, n.zoomSpeed);
  }
  function W(I) {
    L && (d.theta -= I);
  }
  function G(I) {
    U && (d.phi -= I);
  }
  var et = function() {
    var I = new E();
    return function(gt, j) {
      I.setFromMatrixColumn(j, 0), I.multiplyScalar(-gt), f.add(I);
    };
  }(), H = function() {
    var I = new E();
    return function(gt, j) {
      n.screenSpacePanning === !0 ? I.setFromMatrixColumn(j, 1) : (I.setFromMatrixColumn(j, 0), I.crossVectors(n.object.up, I)), I.multiplyScalar(gt), f.add(I);
    };
  }(), at = function() {
    var I = new E();
    return function(gt, j) {
      var mt = n.domElement;
      if (n.object.isPerspectiveCamera) {
        var At = n.object.position;
        I.copy(At).sub(n.target);
        var Tt = I.length();
        Tt *= Math.tan(n.object.fov / 2 * Math.PI / 180), et(2 * gt * Tt / mt.clientHeight, n.object.matrix), H(2 * j * Tt / mt.clientHeight, n.object.matrix);
      } else n.object.isOrthographicCamera ? (et(gt * (n.object.right - n.object.left) / n.object.zoom / mt.clientWidth, n.object.matrix), H(j * (n.object.top - n.object.bottom) / n.object.zoom / mt.clientHeight, n.object.matrix)) : (console.warn("WARNING: CameraControls.js encountered an unknown camera type - pan disabled."), n.enablePan = !1);
    };
  }();
  function pt(I) {
    n.object.isPerspectiveCamera ? p /= I : n.object.isOrthographicCamera ? (n.object.zoom = Math.max(n.minZoom, Math.min(n.maxZoom, n.object.zoom * I)), n.object.updateProjectionMatrix(), y = !0) : (console.warn("WARNING: CameraControls.js encountered an unknown camera type - dolly/zoom disabled."), n.enableZoom = !1);
  }
  function Mt(I) {
    n.object.isPerspectiveCamera ? p *= I : n.object.isOrthographicCamera ? (n.object.zoom = Math.max(n.minZoom, Math.min(n.maxZoom, n.object.zoom / I)), n.object.updateProjectionMatrix(), y = !0) : (console.warn("WARNING: CameraControls.js encountered an unknown camera type - dolly/zoom disabled."), n.enableZoom = !1);
  }
  const Lt = function() {
    const I = new E(), lt = n.radius * n.radius;
    function gt(j, mt) {
      j *= n.rotateSpeed, mt *= n.rotateSpeed;
      var At = j * j + mt * mt;
      At <= lt / 2 ? I.set(j, mt, Math.sqrt(lt - At)) : I.set(j, mt, lt / (2 * Math.sqrt(At)));
    }
    return function(mt) {
      const At = n.domElement.getBoundingClientRect(), Tt = (mt.x - At.x) / (At.width / 2) - 1, vt = 1 - (mt.y - At.y) / (At.height / 2);
      return gt(
        L ? Tt : 0,
        U ? vt : 0
      ), I;
    };
  }();
  function jt(I) {
    g.set(I.clientX, I.clientY);
  }
  function ne(I) {
    R.set(I.clientX, I.clientY);
  }
  function Jt(I) {
    S.set(I.clientX, I.clientY);
  }
  function Y(I) {
    if (m.set(I.clientX, I.clientY), n.trackball && n.holroyd)
      x = Lt(g).clone(), _ = Lt(m).clone();
    else {
      var lt = n.domElement;
      v.subVectors(m, g).multiplyScalar(n.rotateSpeed), W(2 * Math.PI * v.x / lt.clientHeight), G(2 * Math.PI * v.y / lt.clientHeight);
    }
    g.copy(m), n.update();
  }
  function st(I) {
    b.set(I.clientX, I.clientY), M.subVectors(b, R), M.y > 0 ? pt(V()) : M.y < 0 && Mt(V()), R.copy(b), n.update();
  }
  function Et(I) {
    w.set(I.clientX, I.clientY), T.subVectors(w, S).multiplyScalar(n.panSpeed), at(T.x, T.y), S.copy(w), n.update();
  }
  function Ut(I) {
    I.deltaY < 0 ? Mt(V()) : I.deltaY > 0 && pt(V()), n.update();
  }
  function Pt(I) {
    var lt = !1;
    switch (I.keyCode) {
      case n.keys.UP:
        at(0, n.keyPanSpeed), lt = !0;
        break;
      case n.keys.BOTTOM:
        at(0, -n.keyPanSpeed), lt = !0;
        break;
      case n.keys.LEFT:
        at(n.keyPanSpeed, 0), lt = !0;
        break;
      case n.keys.RIGHT:
        at(-n.keyPanSpeed, 0), lt = !0;
        break;
    }
    lt && (I.preventDefault(), n.update());
  }
  function Kt(I) {
    if (I.touches.length == 1)
      g.set(I.touches[0].pageX, I.touches[0].pageY);
    else {
      var lt = 0.5 * (I.touches[0].pageX + I.touches[1].pageX), gt = 0.5 * (I.touches[0].pageY + I.touches[1].pageY);
      g.set(lt, gt);
    }
  }
  function he(I) {
    if (I.touches.length == 1)
      S.set(I.touches[0].pageX, I.touches[0].pageY);
    else {
      var lt = 0.5 * (I.touches[0].pageX + I.touches[1].pageX), gt = 0.5 * (I.touches[0].pageY + I.touches[1].pageY);
      S.set(lt, gt);
    }
  }
  function D(I) {
    var lt = I.touches[0].pageX - I.touches[1].pageX, gt = I.touches[0].pageY - I.touches[1].pageY, j = Math.sqrt(lt * lt + gt * gt);
    R.set(0, j);
  }
  function ot(I) {
    n.enableZoom && D(I), n.enablePan && he(I);
  }
  function it(I) {
    n.enableZoom && D(I), n.enableRotate && Kt(I);
  }
  function Q(I) {
    if (I.touches.length == 1)
      m.set(I.touches[0].pageX, I.touches[0].pageY);
    else {
      var lt = 0.5 * (I.touches[0].pageX + I.touches[1].pageX), gt = 0.5 * (I.touches[0].pageY + I.touches[1].pageY);
      m.set(lt, gt);
    }
    if (n.trackball && n.holroyd)
      x = Lt(g).clone(), _ = Lt(m).clone();
    else {
      v.subVectors(m, g).multiplyScalar(n.rotateSpeed);
      var j = n.domElement;
      W(2 * Math.PI * v.x / j.clientHeight), G(2 * Math.PI * v.y / j.clientHeight);
    }
    g.copy(m);
  }
  function K(I) {
    if (I.touches.length == 1)
      w.set(I.touches[0].pageX, I.touches[0].pageY);
    else {
      var lt = 0.5 * (I.touches[0].pageX + I.touches[1].pageX), gt = 0.5 * (I.touches[0].pageY + I.touches[1].pageY);
      w.set(lt, gt);
    }
    T.subVectors(w, S).multiplyScalar(n.panSpeed), at(T.x, T.y), S.copy(w);
  }
  function yt(I) {
    var lt = I.touches[0].pageX - I.touches[1].pageX, gt = I.touches[0].pageY - I.touches[1].pageY, j = Math.sqrt(lt * lt + gt * gt);
    b.set(0, j), M.set(0, Math.pow(b.y / R.y, n.zoomSpeed)), pt(M.y), R.copy(b);
  }
  function ut(I) {
    n.enableZoom && yt(I), n.enablePan && K(I);
  }
  function xt(I) {
    n.enableZoom && yt(I), n.enableRotate && Q(I);
  }
  function Wt(I) {
    if (n.enabled !== !1) {
      I.preventDefault(), I.stopPropagation(), n.domElement.focus ? n.domElement.focus() : window.focus();
      var lt;
      switch (I.button) {
        case 0:
          lt = n.mouseButtons.LEFT;
          break;
        case 1:
          lt = n.mouseButtons.MIDDLE;
          break;
        case 2:
          lt = n.mouseButtons.RIGHT;
          break;
        default:
          lt = -1;
      }
      switch (lt) {
        case Ze.DOLLY:
          if (n.enableZoom === !1) return;
          ne(I), h = l.DOLLY;
          break;
        case Ze.ROTATE:
          if (De.get(I, "shift")) {
            if (n.enablePan === !1) return;
            Jt(I), h = l.PAN;
          } else {
            if (n.enableRotate === !1) return;
            De.get(I, "ctrl") && (L = !1), De.get(I, "meta") && (U = !1), jt(I), h = l.ROTATE;
          }
          break;
        case Ze.PAN:
          if (De.get(I, "ctrl") || De.get(I, "meta") || De.get(I, "shift")) {
            if (n.enableRotate === !1) return;
            jt(I), h = l.ROTATE;
          } else {
            if (n.enablePan === !1) return;
            Jt(I), h = l.PAN;
          }
          break;
        default:
          h = l.NONE;
      }
      h !== l.NONE && (document.addEventListener("mousemove", Nt, !1), document.addEventListener("mouseup", P, !1), n.dispatchEvent(r));
    }
  }
  function Nt(I) {
    if (n.enabled !== !1)
      switch (I.preventDefault(), I.stopPropagation(), h) {
        case l.ROTATE:
          if (n.enableRotate === !1) return;
          Y(I);
          break;
        case l.DOLLY:
          if (n.enableZoom === !1) return;
          st(I);
          break;
        case l.PAN:
          if (n.enablePan === !1) return;
          Et(I);
          break;
      }
  }
  function P(I) {
    n.enabled !== !1 && (document.removeEventListener("mousemove", Nt, !1), document.removeEventListener("mouseup", P, !1), L = !0, U = !0, n.dispatchEvent(o), h = l.NONE);
  }
  function A(I) {
    n.enabled === !1 || n.enableZoom === !1 || h !== l.NONE && h !== l.ROTATE || (I.preventDefault(), I.stopPropagation(), n.dispatchEvent(r), Ut(I), n.dispatchEvent(o));
  }
  function N(I) {
    n.enabled === !1 || n.enableKeys === !1 || n.enablePan === !1 || Pt(I);
  }
  function X(I) {
    if (n.enabled !== !1) {
      switch (I.preventDefault(), I.touches.length) {
        case 1:
          switch (n.touches.ONE) {
            case zi.ROTATE:
              if (n.enableRotate === !1) return;
              Kt(I), h = l.TOUCH_ROTATE;
              break;
            case zi.PAN:
              if (n.enablePan === !1) return;
              he(I), h = l.TOUCH_PAN;
              break;
            default:
              h = l.NONE;
          }
          break;
        case 2:
          switch (n.touches.TWO) {
            case zi.DOLLY_PAN:
              if (n.enableZoom === !1 && n.enablePan === !1) return;
              ot(I), h = l.TOUCH_DOLLY_PAN;
              break;
            case zi.DOLLY_ROTATE:
              if (n.enableZoom === !1 && n.enableRotate === !1) return;
              it(I), h = l.TOUCH_DOLLY_ROTATE;
              break;
            default:
              h = l.NONE;
          }
          break;
        default:
          h = l.NONE;
      }
      h !== l.NONE && n.dispatchEvent(r);
    }
  }
  function rt(I) {
    if (n.enabled !== !1)
      switch (I.preventDefault(), I.stopPropagation(), h) {
        case l.TOUCH_ROTATE:
          if (n.enableRotate === !1) return;
          Q(I), n.update();
          break;
        case l.TOUCH_PAN:
          if (n.enablePan === !1) return;
          K(I), n.update();
          break;
        case l.TOUCH_DOLLY_PAN:
          if (n.enableZoom === !1 && n.enablePan === !1) return;
          ut(I), n.update();
          break;
        case l.TOUCH_DOLLY_ROTATE:
          if (n.enableZoom === !1 && n.enableRotate === !1) return;
          xt(I), n.update();
          break;
        default:
          h = l.NONE;
      }
  }
  function Z(I) {
    n.enabled !== !1 && (n.dispatchEvent(o), h = l.NONE);
  }
  function It(I) {
    n.enabled !== !1 && I.preventDefault();
  }
  n.domElement.addEventListener("contextmenu", It, !1), n.domElement.addEventListener("mousedown", Wt, !1), n.domElement.addEventListener("wheel", A, !1), n.domElement.addEventListener("touchstart", X, !1), n.domElement.addEventListener("touchend", Z, !1), n.domElement.addEventListener("touchmove", rt, !1), n.domElement.addEventListener("keydown", N, !1), n.domElement.tabIndex === -1 && (n.domElement.tabIndex = 0), this.object.lookAt(n.target), this.update(), this.saveState();
};
Ps.prototype = Object.create(Ei.prototype);
Ps.prototype.constructor = Ps;
var mp = function(a, t) {
  Ps.call(this, a, t), this.mouseButtons.LEFT = Ze.ROTATE, this.mouseButtons.RIGHT = Ze.PAN, this.touches.ONE = zi.ROTATE, this.touches.TWO = zi.DOLLY_PAN;
};
mp.prototype = Object.create(Ei.prototype);
mp.prototype.constructor = mp;
var gp = function(a, t) {
  Ps.call(this, a, t), this.mouseButtons.LEFT = Ze.PAN, this.mouseButtons.RIGHT = Ze.ROTATE, this.touches.ONE = zi.PAN, this.touches.TWO = zi.DOLLY_ROTATE;
};
gp.prototype = Object.create(Ei.prototype);
gp.prototype.constructor = gp;
var yp = function(a, t) {
  Ps.call(this, a, t), this.trackball = !0, this.screenSpacePanning = !0, this.autoRotate = !1, this.mouseButtons.LEFT = Ze.ROTATE, this.mouseButtons.RIGHT = Ze.PAN, this.touches.ONE = zi.ROTATE, this.touches.TWO = zi.DOLLY_PAN;
};
yp.prototype = Object.create(Ei.prototype);
yp.prototype.constructor = yp;
class lT {
  /**
   * Create Camera Controls.
   * @param {string} type - Type of controls: "orbit", "trackball".
   * @param {THREE.Camera} camera - The camera object.
   * @param {THREE.Vector3} target - The lookAt target for the camera.
   * @param {canvas} domElement - The dom element of the rendering canvas.
   * @param {number} [rotateSpeed=1.0] - Speed for rotating.
   * @param {number} [zoomSpeed=1.0] - Speed for zooming.
   * @param {number} [panSpeed=1.0] - Speed for panning.
   */
  constructor(t, e, i, n, s = 1, r = 1, o = 1) {
    /**
     * Get reset location value.
     * @function
     * @returns {object} - target, position, quaternion, zoom as object.
     */
    k(this, "getResetLocation", () => ({
      target0: this.controls.target0.clone(),
      position0: this.controls.position0.clone(),
      quaternion0: this.controls.quaternion0.clone(),
      zoom0: this.controls.zoom0
    }));
    /**
     * Set reset location value.
     * @function
     * @param {number[]} target - camera target as THREE.Vector3.
     * @param {number[]} position - camera position as THREE.Vector3.
     * @returns {number[]} camera rotation as THREE.Quaternion.
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setResetLocation", (t, e, i, n) => {
      this.controls.target0.copy(t), this.controls.position0.copy(e), this.controls.quaternion0.copy(i), this.controls.zoom0 = n;
    });
    switch (this.type = t, this.camera = e, this.target = i, this.target0 = i.slice(), this.domElement = n, this.rotateSpeed = s, this.zoomSpeed = r, this.panSpeed = o, t) {
      case "orbit":
        this.initOrbitControls();
        break;
      case "trackball":
        this.initTrackballControls();
        break;
    }
    this.controls.target = new E(...this.target), this.controls.rotateSpeed = this.rotateSpeed, this.controls.zoomSpeed = this.zoomSpeed, this.controls.panSpeed = this.panSpeed, this.currentUpdateCallback = null, this.saveState(), this.update();
  }
  /**
   * Remove assets and event handlers.
   */
  dispose() {
    this.controls && (this.controls.dispose(), this.controls = null);
  }
  /**
   * Save state for reset.
   */
  saveState() {
    this.controls.saveState();
  }
  /**
   * Initialize Trackball Controls.
   * @param {boolean} [holroyd=true] - enable holroyd (non tumbling) mode.
   **/
  initTrackballControls(t = !0) {
    this.controls = new Ps(this.camera, this.domElement), this.controls.trackball = !0, this.setHolroydTrackball(t);
  }
  /**
   * Initialize Orbit Controls.
   **/
  initOrbitControls() {
    this.controls = new Ps(this.camera, this.domElement);
  }
  /**
   * Add an event listener callback for the "change" event.
   * @param {callback} domEventCallback - the callback function.
   **/
  addChangeListener(t) {
    this.currentUpdateCallback == null && (this.currentUpdateCallback = t, this.controls.addEventListener("change", t));
  }
  /**
   * Remove the event listener callback for the "change" event.
   **/
  removeChangeListener() {
    this.currentUpdateCallback != null && (this.controls.removeEventListener("change", this.currentUpdateCallback), this.currentUpdateCallback = null);
  }
  /**
   * Update controls after camera position, zoom or quaternion changes.
   **/
  update() {
    this.controls.update();
  }
  /**
   * Reset camera to initial (automatically saved) state of position, up, quaternion and zoom.
   **/
  reset() {
    this.controls.reset();
  }
  /**
   * Set the camera to be controlled.
   * @param {THREE.Camera} camera - a threejs Camera object.
   **/
  setCamera(t) {
    this.controls.object = t;
  }
  /**
   * Change the trackball holroyd (non tumbling) flag.
   * @param {boolean} flag - a threejs Camera object.
   **/
  setHolroydTrackball(t) {
    this.controls.holroyd = t;
  }
  /**
   * Get the lookAt target of the camera.
   * @returns {THREE.Vector3} The lookAt target
   **/
  getTarget() {
    return this.controls.target;
  }
  /**
   * Get the initial zoom value of the camera.
   **/
  getZoom0() {
    return this.controls.zoom0;
  }
  /**
   * Get the lookAt target of the camera.
   * @param {number[]} target - camera target as THREE.Vector3.
   **/
  setTarget(t) {
    this.controls.target.copy(t);
  }
  /**
   * Set the zoom speed.
   * @param {number} val - the speed value.
   **/
  setZoomSpeed(t) {
    this.controls.zoomSpeed = t;
  }
  /**
   * Set the pan speed.
   * @param {number} val - the speed value.
   **/
  setPanSpeed(t) {
    this.controls.panSpeed = t;
  }
  /**
   * Set the rotate speed.
   * @param {number} val - the speed value.
   **/
  setRotateSpeed(t) {
    this.controls.rotateSpeed = t;
  }
  // Rotations for OrbitControls
  /**
   * Rotate camera up (OrbitControls only)
   * @param {number} angle - the angle to rotate.
   **/
  rotateUp(t) {
    this.controls.rotateUp(-t / 180 * Math.PI), this.update();
  }
  /**
   * Rotate camera left (OrbitControls only)
   * @param {number} angle - the angle to rotate.
   **/
  rotateLeft(t) {
    this.controls.rotateLeft(t / 180 * Math.PI), this.update();
  }
  // Rotations for TrackballControls
  /**
   * Rotate camera around x-axis (TrackballControls only)
   * @param {number} angle - the angle to rotate.
   **/
  rotateX(t) {
    this.controls.rotateX(t / 180 * Math.PI), this.update();
  }
  /**
   * Rotate camera around y-axis (TrackballControls only)
   * @param {number} angle - the angle to rotate.
   **/
  rotateY(t) {
    this.controls.rotateY(t / 180 * Math.PI), this.update();
  }
  /**
   * Rotate camera around z-axis (TrackballControls only)
   * @param {number} angle - the angle to rotate.
   **/
  rotateZ(t) {
    this.controls.rotateZ(t / 180 * Math.PI), this.update();
  }
}
const pd = {
  y_up: {
    // compatible to fusion 360
    iso: { pos: new E(1, 1, 1), quat: null },
    front: { pos: new E(0, 0, 1), quat: null },
    rear: { pos: new E(0, 0, -1), quat: null },
    left: { pos: new E(-1, 0, 0), quat: null },
    right: { pos: new E(1, 0, 0), quat: null },
    top: { pos: new E(0, 1, 0), quat: null },
    bottom: { pos: new E(0, -1, 0), quat: null }
  },
  z_up: {
    // compatible to FreeCAD, OnShape
    iso: { pos: new E(1, -1, 1), quat: null },
    front: { pos: new E(0, -1, 0), quat: null },
    rear: { pos: new E(0, 1, 0), quat: null },
    left: { pos: new E(-1, 0, 0), quat: null },
    right: { pos: new E(1, 0, 0), quat: null },
    top: { pos: new E(0, 0, 1), quat: [0, 0, 0, 1] },
    bottom: { pos: new E(0, 0, -1), quat: [1, 0, 0, 0] }
  },
  legacy: {
    // legacy Z up
    iso: { pos: new E(1, 1, 1), quat: null },
    front: { pos: new E(1, 0, 0), quat: null },
    rear: { pos: new E(-1, 0, 0), quat: null },
    left: { pos: new E(0, 1, 0), quat: null },
    right: { pos: new E(0, -1, 0), quat: null },
    top: { pos: new E(0, 0, 1), quat: null },
    bottom: { pos: new E(0, 0, -1), quat: null }
  }
}, fd = {
  y_up: [0, 1, 0],
  z_up: [0, 0, 1],
  legacy: [0, 0, 1]
};
class hT {
  /**
   * Create a combined camera (orthographic and persepctive).
   * @param {number} width - canvas width.
   * @param {number} height - canvas height.
   * @param {number} distance - distance from the lookAt point.
   * @param {THREE.Vector3} target - target (Vector3) to look at.
   * @param {boolean} ortho - flag whether the initial camera should be orthographic.
   * @param {string} up - Z or Y to define whether Z or Y direction is camera up.
   **/
  constructor(t, e, i, n, s, r) {
    const o = {
      Y: "y_up",
      Z: "z_up",
      L: "legacy"
    };
    this.target = new E(...n), this.ortho = s, this.up = o[r], this.yaxis = new E(0, 1, 0), this.zaxis = new E(0, 0, 1);
    const l = t / e;
    var h = 22;
    const c = 5;
    this.camera_distance = c * i, this.pCamera = new Ve(
      h,
      l,
      0.1,
      100 * i
    ), this.pCamera.up.set(...fd[this.up]), this.pCamera.lookAt(this.target);
    const u = this.projectSize(i, l);
    this.oCamera = new Ia(
      -u[0],
      u[0],
      u[1],
      -u[1],
      0.1,
      100 * i
    ), this.oCamera.up.set(...fd[this.up]), this.oCamera.lookAt(this.target), this.camera = s ? this.oCamera : this.pCamera, this.camera.up.set(...fd[this.up]);
  }
  /**
   * Remove assets.
   */
  dispose() {
    this.oCamera = null, this.pCamera = null;
  }
  /**
   * Get the current camera.
   * @returns {THREE.Camera} Camera object.
   **/
  getCamera() {
    return this.camera;
  }
  /**
   * Set the lookAt point for the camera to the provided target.
   **/
  lookAtTarget() {
    this.camera.lookAt(this.target);
  }
  /**
   * Update current camera's projection matrix.
   **/
  updateProjectionMatrix() {
    this.camera.updateProjectionMatrix();
  }
  /**
   * Switch between orthographic and perspective camera.
   * @param {boolean} ortho_flag - true for orthographic camera, else persepctive camera.
   **/
  switchCamera(t) {
    var e = this.getPosition().clone();
    const i = this.getZoom(), n = this.getQuaternion().clone();
    t ? (this.camera = this.oCamera, this.ortho = !0) : (this.camera = this.pCamera, this.ortho = !1), this.setPosition(e, !1), this.setZoom(i), this.setQuaternion(n), this.updateProjectionMatrix();
  }
  /**
   * Calculate projected size for orthographic ca,era
   * @param {number} frustum - view frustum.
   * @param {number} aspect - viewer aspect (width / height).
   **/
  projectSize(t, e) {
    var i, n;
    return e < 1 ? (i = t, n = i / e) : (n = t, i = n * e), [i, n];
  }
  /**
   * Setup the current camera.
   * @param {boolean} relative - flag whether the position is a relative (e.g. [1,1,1] for iso) or absolute point.
   * @param {THREE.Vector3} position - the camera position (relative or absolute).
   * @param {THREE.Quaternion} quaternion - the camera rotation expressed by a quaternion.
   * @param {number} zoom - zoom value.
   **/
  setupCamera(t, e = null, i = null, n = null) {
    if (e != null) {
      var s = t ? e.clone().normalize().multiplyScalar(this.camera_distance).add(this.target) : e;
      this.camera.position.set(...s.toArray());
    }
    i != null && this.camera.quaternion.set(...i.toArray()), n != null && this.setZoom(n), this.updateProjectionMatrix();
  }
  /**
   * Move the camera to a given preset.
   * @param {string} dir - can be "iso", "top", "bottom", "front", "rear", "left", "right"
   **/
  presetCamera(t, e = null) {
    if (e == null && (e = this.camera.zoom), this.setupCamera(!0, pd[this.up][t].pos, null, e), this.lookAtTarget(), pd[this.up][t].quat != null) {
      var i = pd[this.up][t].quat;
      this.setQuaternion(i);
    }
  }
  /**
   * Return current zoom value.
   * @returns {number} zoom value.
   **/
  getZoom() {
    if (this.ortho)
      return this.camera.zoom;
    var t = this.camera.position.clone().sub(this.target);
    return this.camera_distance / t.length();
  }
  /**
   * Set zoom value.
   * @param {number} val - float zoom value.
   **/
  setZoom(t) {
    this.ortho ? this.camera.zoom = t : this.camera.position.sub(this.target).setLength(this.camera_distance / t).add(this.target), this.updateProjectionMatrix();
  }
  /**
   * Get the current camera position.
   * @returns {THREE.Vector3} camera position.
   **/
  getPosition() {
    return this.camera.position;
  }
  /**
   * Set camera position.
   * @param {boolean} relative - flag whether the position is a relative (e.g. [1,1,1] for iso) or absolute point.
   * @param {(Array(3) | THREE.Vector3)} position - position as 3 dim Array [x,y,z] or as Vector3.
   **/
  setPosition(t, e) {
    const i = this;
    Array.isArray(t) && t.length === 3 ? i.setupCamera(e, new E(...t)) : t instanceof E ? i.setupCamera(e, t) : console.error("wrong type for position", t);
  }
  /**
   * Get the current camera quaternion.
   * @returns {THREE.Quaternion} camera quaternion.
   **/
  getQuaternion() {
    return this.camera.quaternion;
  }
  /**
   * Set camera quaternion.
   * @param {(Array(4)|THREE.Quaternion)} quaternion - quaternion as 4 dim Array or as Quaternion.
   **/
  setQuaternion(t) {
    const e = this;
    Array.isArray(t) && t.length === 4 ? e.setupCamera(null, null, new ve(...t)) : t instanceof ve ? e.setupCamera(null, null, t) : console.error("wrong type for quaternion", t), this.updateProjectionMatrix();
  }
  /**
   * Get the current camera rotation.
   * @returns {THREE.Euler} camera rotation.
   **/
  getRotation() {
    return this.camera.rotation;
  }
  getVisibleArea() {
    if (this.ortho) {
      const t = this.getCamera(), e = (t.top - t.bottom) / t.zoom;
      return { width: (t.right - t.left) / t.zoom, height: e };
    } else {
      const t = this.getCamera(), e = t.position.distanceTo(this.target), i = t.fov * Math.PI / 180, n = 2 * Math.tan(i / 2) * e;
      return { width: n * t.aspect, height: n };
    }
  }
  changeDimensions(t, e, i) {
    const n = e / i, s = this.projectSize(t, n);
    this.oCamera && (this.oCamera.left = -s[0], this.oCamera.right = s[0], this.oCamera.top = s[1], this.oCamera.bottom = -s[1]), this.pCamera && (this.pCamera.aspect = n), this.camera && this.camera.updateProjectionMatrix();
  }
}
const vg = "3.6.3";
class cT {
  /**
   * Create Viewer.
   * @param {Display} display - The Display object.
   * @param {DisplayOptions} options - configuration parameters.
   * @param {NotificationCallback} notifyCallback - The callback to receive changes of viewer parameters.
   * @param {boolean} updateMarker - enforce to redraw orientation marker after evry ui activity
   */
  constructor(t, e, i, n = null, s = !0) {
    // - - - - - - - - - - - - - - - - - - - - - - - -
    // Update handling of the renderer
    // - - - - - - - - - - - - - - - - - - - - - - - -
    /**
     * Creates ChangeNotification object if new value != old value and sends change notifications via viewer.notifyCallback.
     * @function
     * @param {ChangeInfos} changes - change information.
     * @param {boolean} notify - whether to send notification or not.
     */
    k(this, "checkChanges", (t, e = !0) => {
      var i = {};
      Object.keys(t).forEach((n) => {
        if (!up(this.lastNotification[n], t[n])) {
          var s = bc(t[n]);
          i[n] = {
            new: s,
            // map undefined in lastNotification to null to enable JSON exchange
            old: this.lastNotification[n] == null ? null : bc(this.lastNotification[n])
          }, this.lastNotification[n] = s;
        }
      }), Object.keys(i).includes("position") && (this.keepHighlight ? this.keepHighlight = !1 : this.display.clearHighlights()), e && this.notifyCallback && Object.keys(i).length && this.notifyCallback(i);
    });
    /**
     * Notifies the states by checking for changes and passing the states to the checkChanges method.
     */
    k(this, "notifyStates", () => {
      this.checkChanges({ states: this.getStates() }, !0);
    });
    /**
     * Render scene and update orientation marker
     * If no animation loop exists, this needs to be called manually after every camera/scene change
     * @function
     * @param {boolean} updateMarker - whether to update the orientation marker
     * @param {boolean} fromAnimationLoop - whether a animation loop is running in the background. Update will skipped for this case
     * @param {boolean} notify - whether to send notification or not.
     */
    k(this, "update", (t, e = !0) => {
      this.ready && (this.renderer.clear(), this.raycaster && this.raycaster.raycastMode && this.handleRaycast(), this.gridHelper.update(this.camera.getZoom()), this.renderer.setViewport(0, 0, this.cadWidth, this.height), this.renderer.render(this.scene, this.camera.getCamera()), this.cadTools.update(), this.directLight.position.copy(this.camera.getCamera().position), this.lastBbox != null && (this.lastBbox.needsUpdate || this.bboxNeedsUpdate) && (console.debug("updated bbox"), this.lastBbox.bbox.update(), this.lastBbox.needsUpdate = !1), t && (this.renderer.clearDepth(), this.orientationMarker.update(
        this.camera.getPosition().clone().sub(this.controls.getTarget()),
        this.camera.getQuaternion()
      ), this.orientationMarker.render(this.renderer)), this.animation && this.animation.update(), this.checkChanges(
        {
          zoom: this.camera.getZoom(),
          position: this.camera.getPosition().toArray(),
          quaternion: this.camera.getQuaternion().toArray(),
          target: this.controls.getTarget().toArray()
        },
        e
      ));
    });
    /**
     * Start the animation loop
     * @function
     */
    k(this, "animate", () => {
      this.continueAnimation ? (requestAnimationFrame(this.animate), this.controls.update(), this.update(!0, !0)) : console.debug("three-cad-viewer: Animation loop stopped");
    });
    // - - - - - - - - - - - - - - - - - - - - - - - -
    // Rendering
    // - - - - - - - - - - - - - - - - - - - - - - - -
    /**
     * Synchronizes the states of two tree structures recursively.
     *
     * @param {Array|Object} compactTree - The compact tree structure.
     * @param {Array|Object} expandedTree - The expanded tree structure.
     * @param {string} path - The current path in the tree structure.
     */
    k(this, "syncTreeStates", (t, e, i, n) => {
      if (Array.isArray(t))
        if (i)
          for (var s in e)
            for (var r in e[s]) {
              const u = `${n}/${s}/${r}`, d = this.expandedNestedGroup.groups[u];
              for (var o of [0, 1])
                o == 0 ? d.setShapeVisible(t[0] == 1) : d.setEdgesVisible(t[1] == 1), e[s][r][o] != 3 && (e[s][r][o] = t[o]);
            }
        else {
          const u = this.compactNestedGroup.groups[n];
          for (var o of [0, 1]) {
            var l = !1;
            for (var s in e)
              for (var r in e[s])
                e[s][r][o] == 1 && (l = !0);
            o == 0 ? u.setShapeVisible(l) : u.setEdgesVisible(l), t[o] != 3 && (t[o] = l ? 1 : 0);
          }
        }
      else
        for (var h in t) {
          var c = `${n}/${h}`;
          this.syncTreeStates(t[h], e[h], i, c);
        }
    });
    /**
     * Get the color of a node from its path
     * @param path - path of the CAD object
     */
    k(this, "getNodeColor", (t) => {
      var e = this.nestedGroup.groups["/" + t];
      if (e instanceof ln) {
        let i = "";
        return e.children[0].type !== "Mesh" || e.children[0].material.name == "frontMaterial" ? i = e.children[0].material.color : i = e.children[1].material.color, "#" + i.getHexString();
      }
      return null;
    });
    // - - - - - - - - - - - - - - - - - - - - - - - -
    // Event handlers
    // - - - - - - - - - - - - - - - - - - - - - - - -
    /**
     * Move the camera to a given locations
     * @function
     * @param {relative} [relative=false] - flag whether the position is a relative (e.g. [1,1,1] for iso) or absolute point.
     * @param {number[]} position - the camera position as 3 dim array [x,y,z]
     * @param {number[]} [quaternion=null] - the camera rotation expressed by a quaternion array [x,y,z,w].
     * @param {number} [zoom=null] - zoom value.
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setCamera", (t, e, i = null, n = null, s = !0) => {
      this.camera.setupCamera(
        t,
        new E(...e),
        i != null ? new ve(...i) : null,
        n,
        s
      ), this.update(!0, s);
    });
    /**
     * Move the camera to one of the preset locations
     * @function
     * @param {string} dir - can be "iso", "top", "bottom", "front", "rear", "left", "right"
     * @param {number} [zoom=null] - zoom value
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "presetCamera", (t, e = null, i = !0) => {
      this.camera.target = new E(...this.bbox.center()), this.camera.presetCamera(t, e, i), this.controls.setTarget(this.camera.target), this.update(!0, i);
    });
    /**
     * Reset zoom to 1.0
     * @function
     */
    k(this, "resize", () => {
      this.camera.setZoom(1), this.camera.updateProjectionMatrix(), this.update(!0);
    });
    /**
     * Reset the view to the initial camera and controls settings
     * @function
     */
    k(this, "reset", () => {
      this.controls.reset(), this.update(!0);
    });
    /**
     * Sets the visibility state of an object in the viewer.
     *
     * @param {string} path - The path of the object.
     * @param {number} state - The visibility state (0 or 1).
     * @param {number} iconNumber - The icon number.
     * @param {boolean} [notify=true] - Whether to notify the changes.
     */
    k(this, "setObject", (t, e, i, n = !0, s = !0) => {
      var r = this.nestedGroup.groups[t];
      r != null && r instanceof ln && (i == 0 ? r.setShapeVisible(e === 1) : r.setEdgesVisible(e === 1), n && this.getState(t), s && this.update(this.updateMarker));
    });
    /**
     * Sets the bounding box for a given ID.
     * @param {string} id - The ID of the group.
     */
    k(this, "setBoundingBox", (t) => {
      var e = this.nestedGroup.groups[t];
      e != null && (this.lastBbox != null && this.scene.remove(this.lastBbox.bbox), this.lastBbox == null || this.lastBbox != null && t != this.lastBbox.id ? (this.lastBbox = {
        id: t,
        bbox: new GE(e, 16711935),
        needsUpdate: !1
      }, this.scene.add(this.lastBbox.bbox)) : this.lastBbox = null, this.update(!1, !1, !1));
    });
    /**
     * Refresh clipping plane
     * @function
     * @param {number} index - index of the plane: 0,1,2
     * @param {number} value - distance on the clipping normal from the center
     */
    k(this, "refreshPlane", (t, e) => {
      this.clipping.setConstant(t, e), this.update(this.updateMarker);
    });
    /**
     * Handler for the animation control
     * @function
     * @param {string} btn - the pressed button as string: "play", "pause", "stop"
     */
    k(this, "controlAnimation", (t) => {
      switch (t) {
        case "play":
          this.clipAction.paused && (this.clipAction.paused = !1), this.clipAction.play();
          break;
        case "pause":
          this.clipAction.paused = !this.clipAction.paused;
          break;
        case "stop":
          this.clipAction.stop();
          break;
      }
    });
    /**
     * Set state of one entry of a treeview leaf given by an id
     * @function
     * @param {string} id - object id
     * @param {number[]} state - 2 dim array [mesh, edges] = [0/1, 0/1]
     * @p^aram {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setState", (t, e, i = "leaf", n = !0) => {
      this.treeview.setState(t, e), this.update(this.updateMarker, n);
    });
    /**
     * Handle bounding box and notifications for picked elements
     * @function
     * @param {string} - path of object
     * @param {string} - name of object (id = path/name)
     * @param {boolean} - meta key pressed
     * @param {boolean} shift - whether to send notification or not.
     */
    k(this, "handlePick", (t, e, i, n, s, r, o = "leaf", l) => {
      var p;
      const h = `${t}/${e}`, c = this.nestedGroup.groups[h];
      if (c != null) {
        var u;
        if (c.parent != null)
          u = new or().setFromObject(c, !0);
        else {
          u = new or();
          for (var d = 0; d < c.children.length - 1; d++)
            u = u.expandByObject(c.children[d]);
        }
        if (this.lastBbox != null && this.lastBbox.id === h && !i && !n)
          this.removeLastBbox(), this.treeview.toggleLabelColor(null, h);
        else if (this.checkChanges({
          lastPick: {
            path: t,
            name: e,
            boundingBox: u,
            boundingSphere: u.boundingSphere()
          }
        }), (p = this.animation.clipAction) != null && p.isRunning() && (this.bboxNeedsUpdate = !0), n && i)
          if (this.removeLastBbox(), l)
            this.treeview.hideAll(), this.setState(h, [1, 1], o);
          else {
            const f = u.center();
            this.setCameraTarget(r), this.info.centerInfo(f);
          }
        else if (n) {
          this.removeLastBbox(), this.treeview.hideAll(), this.setState(h, [1, 1], o);
          const f = u.center();
          this.setCameraTarget(new E(...f)), this.info.centerInfo(f);
        } else i ? this.setState(h, [0, 0], o) : (this.info.bbInfo(t, e, u), this.setBoundingBox(h), this.treeview.openPath(h));
        this.update(!0);
      }
    });
    /**
     * Find the shape that was double clicked and send notification
     * @function
     * @param {MouseEvent} e - a DOM MouseEvent
     */
    k(this, "pick", (t) => {
      const e = new ug(
        this.camera,
        this.renderer.domElement,
        this.cadWidth,
        this.height,
        this.bb_max / 30,
        this.scene.children.slice(0, 1),
        // eslint-disable-next-line no-unused-vars
        (l) => {
        }
      );
      e.init(), e.onPointerMove(t);
      const i = e.getIntersectedObjs(t);
      if (i.length == 0)
        return;
      let n = null;
      for (var s in i)
        if (i[s].object instanceof re) {
          n = i[s];
          break;
        }
      if (n == null)
        return;
      const r = n.point, o = {
        path: n.object.parent.parent.name.replaceAll("|", "/"),
        name: n.object.name,
        boundingBox: this.shapes.format == "GDS" ? new we(
          r.clone().subScalar(10),
          r.clone().addScalar(10)
        ) : n.object.geometry.boundingBox,
        boundingSphere: this.shapes.format == "GDS" ? new Re(r, 1) : n.object.geometry.boundingSphere,
        objectGroup: n.object.parent
      };
      o != null && this.handlePick(
        o.path,
        o.name,
        De.get(t, "meta"),
        De.get(t, "shift"),
        De.get(t, "alt"),
        n.point,
        null,
        !1
      ), e.dispose();
    });
    //
    // Handle CAD Tools
    //
    k(this, "clearSelection", () => {
      this.nestedGroup.clearSelection(), this.cadTools.handleResetSelection();
    });
    k(this, "_releaseLastSelected", () => {
      if (this.lastObject != null) {
        let t = this.lastObject.objs();
        for (let e of t)
          e.unhighlight(!0);
      }
    });
    k(this, "_removeLastSelected", () => {
      if (this.lastSelection != null) {
        let t = this.lastSelection.objs();
        for (let e of t)
          e.unhighlight(!1), this.treeview.toggleLabelColor(
            null,
            e.name.replaceAll(this.nestedGroup.delim, "/")
          );
        this.lastSelection = null, this.lastObject = null;
      }
      this.cadTools.handleRemoveLastSelection(!0);
    });
    k(this, "handleRaycast", () => {
      const t = this.raycaster.getValidIntersectedObjs();
      if (t.length > 0)
        for (var e of t) {
          const s = e.object.parent;
          var i = s ? s.name : null, n = this.lastObject ? this.lastObject.obj.name : null;
          if (i != null && i !== n) {
            this._releaseLastSelected();
            const r = this.raycaster.filters.topoFilter.includes(
              la.solid
            ), o = new LE(s, r);
            for (let l of o.objs())
              l.highlight(!0);
            this.lastObject = o;
          }
          break;
        }
      else
        this.lastObject != null && (this._releaseLastSelected(), this.lastObject = null);
    });
    k(this, "handleRaycastEvent", (t) => {
      var e;
      if (t.key)
        switch (t.key) {
          case "Escape":
            this.clearSelection();
            break;
          case "Backspace":
            this._removeLastSelected();
            break;
        }
      else
        switch (t.mouse) {
          case "left":
            if (this.lastObject != null) {
              const i = this.lastObject.objs();
              for (let n of i)
                n.toggleSelection();
              this.cadTools.handleSelectedObj(
                this.lastObject,
                ((e = this.lastSelection) == null ? void 0 : e.obj.name) != this.lastObject.obj.name,
                t.shift
              ), this.lastSelection = this.lastObject;
            }
            break;
          case "right":
            this._removeLastSelected();
            break;
        }
    });
    /**
     * Handle a backend response sent by the backend
     * The response is a JSON object sent by the Python backend through VSCode
     * @param {object} response
     */
    k(this, "handleBackendResponse", (t) => {
      t.subtype === "tool_response" && this.cadTools.handleResponse(t);
    });
    /**
     * Show/hide axes helper
     * @function
     * @param {boolean} flag - whether to show the axes
     * @param {boolean} notify - whether to send notification or not.
     */
    k(this, "setAxes", (t, e = !0) => {
      this.axes = t, this.axesHelper.setVisible(t), this.display.setAxesCheck(t), this.checkChanges({ axes: t }, e), this.update(this.updateMarker);
    });
    /**
     * Show/hide grids
     * @function
     * @param {string} action -  one of "grid" (all grids), "grid-xy","grid-xz", "grid-yz"
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setGrid", (t, e, i = !0) => {
      this.gridHelper.setGrid(t, e), this.checkChanges({ grid: this.gridHelper.grid }, i), this.update(this.updateMarker);
    });
    /**
     * Toggle grid visibility
     * @function
     * @param {boolean[]} grids - 3 dim grid visibility (xy, xz, yz)
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setGrids", (t, e = !0) => {
      this.gridHelper.setGrids(...t), this.grid = this.gridHelper.grid, this.checkChanges({ grid: this.gridHelper.grid }, e), this.update(this.updateMarker);
    });
    /**
     * Set grid center
     * @function
     * @param {boolean[]} center - true for centering grid at (0,0,0)
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setGridCenter", (t, e = !0) => {
      this.gridHelper.centerGrid = t, this.gridHelper.setCenter(this.axes0, this.up == "Z"), this.checkChanges({ center_grid: this.gridHelper.centerGrid }, e), this.update(this.updateMarker);
    });
    /**
     * Set whether grids and axes center at the origin or the object's boundary box center
     * @function
     * @param {boolean} flag - whether grids and axes center at the origin (0,0,0)
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setAxes0", (t, e = !0) => {
      this.axes0 = t, this.gridHelper.setCenter(t, this.up == "Z"), this.display.setAxes0Check(t), this.axesHelper.setCenter(t), this.checkChanges({ axes0: t }, e), this.update(this.updateMarker);
    });
    /**
     * Set the intensity of ambient light
     * @function
     * @param {number} val - the new ambient light intensity
     * @param {boolean} [ui=false] - if true, set the UI slider value
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setAmbientLight", (t, e = !1, i = !0) => {
      this.ambientIntensity = t, this.ambientLight.intensity = kl(t), this.checkChanges({ ambient_intensity: t }, i), this.update(this.updateMarker, i), e && this.display.setAmbientLight(t);
    });
    /**
     * Set the intensity of directional light
     * @function
     * @param {number} val - the new direct light intensity
     * @param {boolean} [ui=false] - if true, set the UI slider value
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setDirectLight", (t, e = !1, i = !0) => {
      this.directIntensity = t, this.directLight.intensity = kl(t), this.checkChanges({ direct_intensity: t }, i), this.update(this.updateMarker, i), e && this.display.setDirectLight(t);
    });
    /**
     * Retrieves the metalness value.
     *
     * @returns {number} The current metalness value.
     */
    k(this, "getMetalness", () => this.metalness);
    /**
     * Sets the metalness value for the viewer and updates related properties.
     *
     * @param {number} value - The metalness value to set.
     * @param {boolean} [ui=false] - Whether to update the UI with the new metalness value.
     * @param {boolean} [notify=true] - Whether to notify about the changes.
     */
    k(this, "setMetalness", (t, e = !1, i = !0) => {
      this.metalness = t, this.nestedGroup.setMetalness(t), this.checkChanges({ metalness: t }, i), this.update(this.updateMarker), e && this.display.setMetalness(t);
    });
    /**
     * Retrieves the roughness value.
     *
     * @returns {number} The current roughness value.
     */
    k(this, "getRoughness", () => this.roughness);
    /**
     * Sets the roughness value for the viewer and updates related components.
     *
     * @param {number} value - The roughness value to set.
     * @param {boolean} [ui=false] - Whether to update the UI directly.
     * @param {boolean} [notify=true] - Whether to notify about the changes.
     * @returns {void}
     */
    k(this, "setRoughness", (t, e = !1, i = !0) => {
      this.roughness = t, this.nestedGroup.setRoughness(t), this.checkChanges({ roughness: t }, i), this.update(this.updateMarker), e && this.display.setRoughness(t);
    });
    /**
     * Resets the material settings of the viewer to their default values.
     * Updates the metalness, roughness, ambient light intensity, and direct light intensity
     * based on the current material settings.
     *
     * @returns {void}
     */
    k(this, "resetMaterial", () => {
      this.setMetalness(this.materialSettings.metalness, !0, !0), this.setRoughness(this.materialSettings.roughness, !0, !0), this.setAmbientLight(this.materialSettings.ambientIntensity, !0, !0), this.setDirectLight(this.materialSettings.directIntensity, !0, !0);
    });
    /**
     * Set CAD objects transparency
     * @function
     * @param {boolean} flag - whether to show the CAD object in transparent mode
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setTransparent", (t, e = !0) => {
      this.transparent = t, this.nestedGroup.setTransparent(t), this.display.setTransparentCheck(t), this.checkChanges({ transparent: t }, e), this.update(this.updateMarker);
    });
    /**
     * Show edges in black or the default edge color
     * @function
     * @param {boolean} flag - whether to show edges in black
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setBlackEdges", (t, e = !0) => {
      this.blackEdges = t, this.nestedGroup.setBlackEdges(t), this.display.setBlackEdgesCheck(t), this.checkChanges({ black_edges: t }, e), this.update(this.updateMarker);
    });
    /**
     * Set the default edge color
     * @function
     * @param {number} edge color (0xrrggbb)
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setEdgeColor", (t, e = !0) => {
      this.edgeColor = t, this.nestedGroup.setEdgeColor(t), this.update(this.updateMarker, e);
    });
    /**
     * Set the default opacity
     * @function
     * @param {number} opacity (between 0.0 and 1.0)
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setOpacity", (t, e = !0) => {
      this.defaultOpacity = t, this.nestedGroup.setOpacity(t), this.update(this.updateMarker, e);
    });
    /**
     * Show/hide the CAD tools
     * @function
     * @param {boolean} flag
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "showTools", (t, e = !0) => {
      this.tools = t, this.display.showTools(t), this.update(this.updateMarker, e);
    });
    /**
     * Set states of a treeview leafs
     * @function
     * @param {dict} - states
     */
    k(this, "setStates", (t) => {
      this.treeview.setStates(t);
    });
    /**
     * Set zoom speed.
     * @function
     * @param {number} val - the new zoom speed
     * @param {boolean} notify - whether to send notification or not.
     */
    k(this, "setZoomSpeed", (t, e = !0) => {
      this.zoomSpeed = t, this.controls.setZoomSpeed(t), this.checkChanges({ grid: this.gridHelper.grid }, e);
    });
    /**
     * Set pan speed.
     * @function
     * @param {number} val - the new pan speed
     * @param {boolean} notify - whether to send notification or not.
     */
    k(this, "setPanSpeed", (t, e = !0) => {
      this.panSpeed = t, this.controls.setPanSpeed(t), this.checkChanges({ grid: this.gridHelper.grid }, e);
    });
    /**
     * Set rotation speed.
     * @function
     * @param {number} val - the new rotation speed.
     * @param {boolean} notify - whether to send notification or not.
     */
    k(this, "setRotateSpeed", (t, e = !0) => {
      this.rotateSpeed = t, this.controls.setRotateSpeed(t), this.checkChanges({ grid: this.gridHelper.grid }, e);
    });
    /**
     * Set the clipping mode to intersection mode
     * @function
     * @param {boolean} flag - whether to use intersection mode
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setClipIntersection", (t, e = !0) => {
      if (t != null) {
        this.clipIntersection = t, this.nestedGroup.setClipIntersection(t), this.display.setClipIntersectionCheck(t);
        for (var i of this.nestedGroup.rootGroup.children)
          if (i.name == "PlaneMeshes")
            for (var n of i.children)
              t ? n.material.clippingPlanes = this.clipping.reverseClipPlanes.filter(
                (r, o) => o !== n.index
              ) : n.material.clippingPlanes = this.clipping.clipPlanes.filter(
                (r, o) => o !== n.index
              );
        for (i of this.scene.children)
          if (i.name == "PlaneHelpers")
            for (var s of i.children[0].children)
              t ? s.material.clippingPlanes = this.clipping.reverseClipPlanes.filter(
                (r, o) => o !== s.index
              ) : s.material.clippingPlanes = this.clipping.clipPlanes.filter(
                (r, o) => o !== s.index
              );
        this.checkChanges({ clip_intersection: t }, e), this.update(this.updateMarker);
      }
    });
    /**
     * Get whether the clipping caps color status
     * @returns {boolean} color caps value (object color (true) or RGB (false)).
     */
    k(this, "getObjectColorCaps", () => this.clipping.getObjectColorCaps());
    /**
     * Toggle the clipping caps color between object color and RGB
     * @function
     * @param {boolean} flag - whether to use intersection mode
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setClipObjectColorCaps", (t, e = !0) => {
      t != null && (this.clipping.setObjectColorCaps(t), this.display.setClipObjectColorsCheck(t), this.checkChanges({ clip_object_colors: t }, e), this.update(this.updateMarker));
    });
    /**
     * Show/hide clip plane helpers
     * @function
     * @param {boolean} flag - whether to show clip plane helpers
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setClipPlaneHelpers", (t, e = !0) => {
      t != null && (this.clipPlaneHelpers = t, this.clipping.planeHelpers.visible = t, this.display.setClipPlaneHelpersCheck(t), this.checkChanges({ clip_planes: t }, e), this.update(this.updateMarker));
    });
    /**
     * Set the normal at index to the current viewing direction
     * @function
     * @param {number} index - index of the normal: 0, 1 ,2
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setClipNormalFromPosition", (t, e = !0) => {
      const n = this.camera.getPosition().clone().sub(this.controls.getTarget()).normalize().negate().toArray();
      this.setClipNormal(t, n, null, e);
      var s = {};
      s[`clip_normal_${t}`] = n, this.checkChanges(s, e);
    });
    /**
     * Get clipping slider value.
     * @function
     * @param {number} index - index of the normal: 0, 1 ,2
     * @returns {boolean} clip plane visibility value.
     **/
    k(this, "getClipSlider", (t) => this.display.clipSliders[t].getValue());
    /**
     * Set clipping slider value.
     * @function
     * @param {number} index - index of the normal: 0, 1 ,2
     * @param {number} value - value for the clipping slide. will be trimmed to slide min/max limits
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setClipSlider", (t, e, i = !0) => {
      e == -1 || e == null || this.display.clipSliders[t].setValue(e, i);
    });
    /**
     * Get reset location value.
     * @function
     * @returns {object} - target, position, quaternion, zoom as object.
     */
    k(this, "getResetLocation", () => {
      const t = this.controls.getResetLocation();
      return {
        target0: t.target0.toArray(),
        position0: t.position0.toArray(),
        quaternion0: t.quaternion0.toArray(),
        zoom0: t.zoom0
      };
    });
    /**
     * Set reset location value.
     * @function
     * @param {number[]} target - camera target as 3 dim Array [x,y,z].
     * @param {number[]} position - camera position as 3 dim Array [x,y,z].
     * @param {number[]} quaternion - camera rotation as 4 dim quaternion array [x,y,z,w].
     * @param {number} zoom - camera zoom value.
     * @param {boolean} [notify=true] - whether to send notification or not.
     */
    k(this, "setResetLocation", (t, e, i, n, s = !0) => {
      var r = this.getResetLocation();
      this.controls.setResetLocation(
        new E(...t),
        new E(...e),
        new Qt(...i),
        n
      ), s && this.notifyCallback && this.notifyCallback({
        target0: { old: r.target0, new: t },
        position0: { old: r.position0, new: e },
        quaternion0: { old: r.quaternion0, new: i },
        zoom0: { old: r.zoom0, new: n }
      });
    });
    /**
     * Replace CadView with an inline png image of the canvas.
     *
     * Note: Only the canvas will be shown, no tools and orientation marker
     */
    k(this, "pinAsPng", () => {
      this.getImage("screenshot").then((e) => {
        var i = document.createElement("img");
        if (i.width = this.cadWidth, i.height = this.height, i.src = e.dataUrl, this.pinAsPngCallback == null) {
          for (var n of this.display.container.children)
            this.display.container.removeChild(n);
          this.display.container.appendChild(i);
        }
      });
    });
    /**
     * Get the current canvas as png data.
     * @function
     * @param {string} taksId - and id to identify the screenshot
     * Note: Only the canvas will be shown, no tools and orientation marker
     */
    k(this, "getImage", (t) => {
      const e = this.hasAnimationLoop;
      return e || this.toggleAnimationLoop(!0), this.orientationMarker.setVisible(!1), this.update(!0), new Promise((n, s) => {
        const r = this.display.getCanvas();
        this.renderer.setViewport(0, 0, this.cadWidth, this.height), this.renderer.render(this.scene, this.camera.getCamera()), r.toBlob((o) => {
          let l = new FileReader();
          l.addEventListener(
            "load",
            () => {
              n({ task: t, dataUrl: l.result }), e || this.toggleAnimationLoop(!1), this.orientationMarker.setVisible(!0), this.update(!0);
            },
            { once: !0 }
          ), l.readAsDataURL(o);
        });
      });
    });
    this.notifyCallback = i, this.pinAsPngCallback = n, this.updateMarker = s, this.hasAnimationLoop = !1, this.setDisplayDefaults(e), this.display = t, e.keymap && this.setKeyMap(e.keymap), window.THREE = wE, this.nestedGroup = null, this.mapping = null, this.tree = null, this.bbox = null, this.bb_max = 0, this.scene = null, this.camera = null, this.gridHelper = null, this.axesHelper = null, this.controls = null, this.orientationMarker = null, this.treeview = null, this.cadTools = new zE(this, e.measurementDebug), this.newTreeBehavior = e.newTreeBehavior, this.ready = !1, this.mixer = null, this.animation = new aT("|"), this.continueAnimation = !0, this.clipNormals = [
      [-1, 0, 0],
      [0, -1, 0],
      [0, 0, -1]
    ], this.camera_distance = 0, this.mouse = new J(), this.renderer = new C_({
      alpha: !0,
      antialias: !0,
      stencil: !0
    }), this.renderer.setPixelRatio(window.devicePixelRatio), this.renderer.setSize(this.cadWidth, this.height), this.renderer.setClearColor(16777215, 0), this.renderer.autoClear = !1, this.lastNotification = {}, this.lastBbox = null, this.expandedTree = null, this.compactTree = null, this.expandedNestedGroup = null, this.compactNestedGroup = null, this.lastObject = null, this.lastSelection = null, this.lastPosition = null, this.bboxNeedsUpdate = !1, this.keepHighlight = !1, this.setPickHandler(!0), this.renderer.domElement.addEventListener(
      "contextmenu",
      (r) => r.stopPropagation()
    ), this.display.setupUI(this), this.display.addCadView(this.renderer.domElement), console.debug("three-cad-viewer: WebGL Renderer created"), window.viewer = this;
  }
  /**
   * Return three-cad-viewer version as semver string
   * @returns semver version
   */
  version() {
    return vg;
  }
  /**
   * Enhance the given options for viewer creation by default values.
   * @param {DisplayOptions} options - The provided options object for the viewer.
   */
  setDisplayDefaults(t) {
    this.theme = "light", this.cadWidth = 800, this.treeWidth = 250, this.height = 600, this.pinning = !1, this.glass = !1, this.tools = !0, this.keymap = { shift: "shiftKey", ctrl: "ctrlKey", meta: "metaKey" }, this.newTreeBehavior = !0, this.measureTools = !0, this.selectTool = !0, this.explodeTool = !0, this.zscaleTool = !1, this.measurementDebug = !0;
    for (var e in t)
      this[e] == null ? console.warn(`Unknown option "${e}" to create a viewer - ignored`) : this[e] = t[e];
    t.theme === "dark" || t.theme == "browser" && window.matchMedia("(prefers-color-scheme: dark)").matches ? this.theme = "dark" : this.theme = "light";
  }
  /**
   * Enhance the given options for rendering by default values.
   * @param {RenderOptions} options - The provided options object for the viewer.
   */
  setRenderDefaults(t) {
    this.ambientIntensity = 0.5, this.directIntensity = 0.6, this.metalness = 0.7, this.roughness = 0.7, this.defaultOpacity = 0.5, this.edgeColor = 7368816, this.normalLen = 0;
    for (var e in t)
      this[e] === void 0 ? console.warn(`Unknown option "${e}" to create a viewer - ignored`) : this[e] = t[e];
    this.materialSettings = {
      ambientIntensity: this.ambientIntensity,
      directIntensity: this.directIntensity,
      metalness: this.metalness,
      roughness: this.roughness
    };
  }
  /**
   * Enhance the given options for the view by default values.
   * @param {ViewOptions} options - The provided options object for the viewer.
   */
  setViewerDefaults(t) {
    this.axes = !1, this.axes0 = !1, this.grid = [!1, !1, !1], this.ortho = !0, this.transparent = !1, this.blackEdges = !1, this.collapse = 0, this.clipIntersection = !1, this.clipPlaneHelpers = !1, this.clipObjectColors = !1, this.clipNormal0 = [-1, 0, 0], this.clipNormal1 = [0, -1, 0], this.clipNormal2 = [0, 0, -1], this.clipSlider0 = -1, this.clipSlider1 = -1, this.clipSlider2 = -1, this.control = "orbit", this.up = "Z", this.ticks = 10, this.gridFontSize = 10, this.centerGrid = !1, this.position = null, this.quaternion = null, this.target = null, this.zoom = 1, this.panSpeed = 0.5, this.rotateSpeed = 1, this.zoomSpeed = 0.5, this.timeit = !1;
    for (var e in t)
      this[e] === void 0 ? console.warn(`Unknown option ${e} to add shapes - ignored`) : this[e] = t[e];
  }
  dumpOptions() {
    console.log("Display:"), console.log("- cadWidth", this.cadWidth), console.log("- control", this.control), console.log("- height", this.height), console.log("- pinning", this.pinning), console.log("- theme", this.theme), console.log("- treeHeight", this.treeHeight), console.log("- treeWidth", this.treeWidth), console.log("Render:"), console.log("- ambientIntensity", this.ambientIntensity), console.log("- defaultOpacity", this.defaultOpacity), console.log("- directIntensity", this.directIntensity), console.log("- edgeColor", this.edgeColor), console.log("- normalLen", this.normalLen), console.log("View:"), console.log("- axes", this.axes), console.log("- axes0", this.axes0), console.log("- blackEdges", this.blackEdges), console.log("- clipIntersection", this.clipIntersection), console.log("- clipPlaneHelpers", this.clipPlaneHelpers), console.log("- clipObjectColors", this.clipObjectColors), console.log("- clipNormal0", this.clipNormal0), console.log("- clipNormal1", this.clipNormal1), console.log("- clipNormal2", this.clipNormal2), console.log("- clipSlider0", this.clipSlider0), console.log("- clipSlider1", this.clipSlider1), console.log("- clipSlider2", this.clipSlider2), console.log("- grid", this.grid), console.log("- ortho", this.ortho), console.log("- panSpeed", this.panSpeed), console.log("- position", this.position), console.log("- quaternion", this.quaternion), console.log("- rotateSpeed", this.rotateSpeed), console.log("- ticks", this.ticks), console.log("- timeit", this.timeit), console.log("- tools", this.tools), console.log("- glass", this.glass), console.log("- transparent", this.transparent), console.log("- zoom", this.zoom), console.log("- zoom0", this.controls.getZoom0()), console.log("- zoomSpeed", this.zoomSpeed);
  }
  // - - - - - - - - - - - - - - - - - - - - - - - -
  // Load Tesselated Shapes
  // - - - - - - - - - - - - - - - - - - - - - - - -
  /**
   * Render tessellated shapes of a CAD object.
   * @param {Shapes} shapes - The Shapes object representing the tessellated CAD object.
   * @returns {THREE.Group} A nested THREE.Group object.
   */
  _renderTessellatedShapes(t) {
    const e = new WE(
      t,
      this.cadWidth,
      this.height,
      this.edgeColor,
      this.transparent,
      this.defaultOpacity,
      this.metalness,
      this.roughness,
      this.normalLen
    );
    return t.bb && (this.bbox = new or(
      new E(t.bb.xmin, t.bb.ymin, t.bb.zmin),
      new E(t.bb.xmax, t.bb.ymax, t.bb.zmax)
    )), e.render(), e;
  }
  /**
   * Retrieve the navigation tree from a Shapes object.
   * @param {Shapes} shapes - The Shapes object.
   * @returns {NavTree} The navigation tree object.
   */
  _getTree(t) {
    const e = (n) => {
      var s = {};
      for (var r of n)
        r.parts != null ? s[r.name] = e(r.parts) : s[r.name] = r.state;
      return s;
    };
    var i = {};
    return i[t.name] = e(t.parts), i;
  }
  /**
   * Decompose a CAD object into faces, edges and vertices.
   * @param {Shapes} shapes - The Shapes object.
   * @returns {Shapes} A decomposed Shapes object.
   */
  _decompose(t) {
    const e = t.shape;
    var i;
    if (t.parts = [], t.type == "shapes") {
      var n = {
        parts: [],
        loc: [
          [0, 0, 0],
          [0, 0, 0, 1]
        ],
        name: "faces",
        id: `${t.id}/faces`
      }, s;
      const y = e.vertices, g = e.normals, m = e.triangles_per_face ? e.triangles_per_face.length : e.triangles.length;
      var r = 0;
      for (i = 0; i < m; i++) {
        e.triangles_per_face ? (s = e.triangles.subarray(
          r,
          r + 3 * e.triangles_per_face[i]
        ), r += 3 * e.triangles_per_face[i]) : s = e.triangles[i];
        for (var o = new Float32Array(s.length * 3), l = new Float32Array(s.length * 3), h = 0; h < s.length; h++) {
          var c = s[h];
          o[3 * h] = y[3 * c], o[3 * h + 1] = y[3 * c + 1], o[3 * h + 2] = y[3 * c + 2], l[3 * h] = g[3 * c], l[3 * h + 1] = g[3 * c + 1], l[3 * h + 2] = g[3 * c + 2];
        }
        var u = {
          loc: [
            [0, 0, 0],
            [0, 0, 0, 1]
          ],
          name: `faces_${i}`,
          id: `${t.id}/faces/faces_${i}`,
          type: "shapes",
          color: t.color,
          alpha: t.alpha,
          renderback: !0,
          state: [1, 3],
          accuracy: t.accuracy,
          bb: {},
          geomtype: e.face_types[i],
          subtype: t.subtype,
          exploded: !0,
          shape: {
            triangles: [...Array(s.length).keys()],
            vertices: o,
            normals: l,
            edges: []
          }
        };
        t.texture && (u.texture = t.texture), n.parts.push(u);
      }
      t.parts.push(n);
    }
    if (t.type == "shapes" || t.type == "edges") {
      n = {
        parts: [],
        loc: [
          [0, 0, 0],
          [0, 0, 0, 1]
        ],
        name: "edges",
        id: `${t.id}/edges`
      };
      const y = Array.isArray(t.color) && t.color.length == e.edges.length;
      var d;
      const g = e.segments_per_edge ? e.segments_per_edge.length : e.edges.length;
      r = 0;
      var p;
      for (i = 0; i < g; i++)
        e.segments_per_edge ? (p = e.edges.subarray(
          r,
          r + 6 * e.segments_per_edge[i]
        ), r += 6 * e.segments_per_edge[i]) : p = e.edges[i], d = y ? t.color[i] : t.color, u = {
          loc: [
            [0, 0, 0],
            [0, 0, 0, 1]
          ],
          name: `edges_${i}`,
          id: `${t.id}/edges/edges_${i}`,
          type: "edges",
          color: t.type == "shapes" ? this.edgeColor : d,
          state: [3, 1],
          width: t.type == "shapes" ? 1 : t.width,
          bb: {},
          geomtype: e.edge_types[i],
          shape: { edges: p }
        }, n.parts.push(u);
      n.parts.length > 0 && t.parts.push(n);
    }
    n = {
      parts: [],
      loc: [
        [0, 0, 0],
        [0, 0, 0, 1]
      ],
      name: "vertices",
      id: `${t.id}/vertices`
    };
    var f = e.obj_vertices;
    for (i = 0; i < f.length / 3; i++)
      u = {
        loc: [
          [0, 0, 0],
          [0, 0, 0, 1]
        ],
        name: `vertices_${i}`,
        id: `${t.id}/vertices/vertices_${i}`,
        type: "vertices",
        color: t.type == "shapes" || t.type == "edges" ? this.edgeColor : t.color,
        state: [3, 1],
        size: t.type == "shapes" || t.type == "edges" ? 4 : t.size,
        bb: {},
        shape: {
          obj_vertices: [
            f[3 * i],
            f[3 * i + 1],
            f[3 * i + 2]
          ]
        }
      }, n.parts.push(u);
    return n.parts.length > 0 && t.parts.push(n), delete t.shape, delete t.color, delete t.alpha, delete t.accuracy, delete t.renderBack, t;
  }
  /**
   * Render the shapes of the CAD object.
   * @param {boolean} exploded - Whether to render the compact or exploded version
   * @param {Shapes} shapes - The Shapes object.
   * @returns {THREE.Group} A nested THREE.Group object.
   */
  renderTessellatedShapes(t, e) {
    const i = (l) => {
      l.triangles != null && !(l.triangles instanceof Uint32Array) && (l.triangles = new Uint32Array(l.triangles)), l.edges != null && !(l.edges instanceof Float32Array) && (l.edges = new Float32Array(xs(l.edges, 3))), l.vertices != null && !(l.vertices instanceof Float32Array) && (l.vertices = new Float32Array(l.vertices)), l.normals != null && !(l.normals instanceof Float32Array) && (l.normals = new Float32Array(xs(l.normals, 2))), l.obj_vertices != null && !(l.obj_vertices instanceof Float32Array) && (l.obj_vertices = new Float32Array(l.obj_vertices)), l.face_types != null && !(l.face_types instanceof Uint32Array) && (l.face_types = new Uint32Array(l.face_types)), l.edge_types != null && !(l.edge_types instanceof Uint32Array) && (l.edge_types = new Uint32Array(l.edge_types)), l.triangles_per_face != null && !(l.triangles_per_face instanceof Uint32Array) && (l.triangles_per_face = new Uint32Array(l.triangles_per_face)), l.segments_per_edge != null && !(l.segments_per_edge instanceof Uint32Array) && (l.segments_per_edge = new Uint32Array(l.segments_per_edge));
    }, n = (l) => {
      var h;
      if (l.version == 2 || l.version == 3) {
        var c, u;
        let d = [];
        for (c = 0; c < l.parts.length; c++)
          h = l.parts[c], h.shape != null && i(h.shape), h.parts != null ? (u = n(h), d.push(u)) : d.push(this._decompose(h));
        l.parts = d;
      }
      return l;
    };
    var s;
    t ? s = n(structuredClone(e)) : s = structuredClone(e);
    var r = this._renderTessellatedShapes(s), o = this._getTree(s);
    return {
      group: r,
      tree: o
    };
  }
  // - - - - - - - - - - - - - - - - - - - - - - - -
  // Animation
  // - - - - - - - - - - - - - - - - - - - - - - - -
  /**
   * Add an animation track for a THREE.Group
   * @param {string} selector - path/id of group to be animated.
   * @param {string} action - one of "rx", "ry", "rz" for rotations around axes, "q" for quaternions or "t", "tx", "ty", "tz" for translations.
   * @param {number[]} time - array of times.
   * @param {number[]} values - array of values, the type depends on the action.
   */
  addAnimationTrack(t, e, i, n) {
    this.animation.addTrack(
      t,
      this.nestedGroup.groups[t],
      e,
      i,
      n
    );
  }
  /**
   * Initialize the animation.
   * @param {number} duration - overall duration of the anmiation.
   * @param {number} speed - speed of the animation.
   */
  initAnimation(t, e, i = "A", n = !0) {
    if (this.animation == null || this.animation.tracks.lenght == 0) {
      console.error("Animation does not have tracks");
      return;
    }
    console.debug("three-cad-viewer: Animation initialized"), this.hasAnimationLoop || this.toggleAnimationLoop(!0), this.display.showAnimationControl(!0), this.clipAction = this.animation.animate(
      this.nestedGroup.rootGroup,
      t,
      e,
      n
    ), this.display.setAnimationLabel(i), this.display.resetAnimationSlider();
  }
  /**
   * Check whether animation object exists
   */
  hasAnimation() {
    return !!this.animation.clipAction;
  }
  /**
   * Clear the animation obect and dispose dependent objects
   */
  clearAnimation() {
    this.animation && me(this.animation), this.display.showAnimationControl(!1), this.toggleAnimationLoop(!1);
  }
  toggleAnimationLoop(t) {
    t ? (this.continueAnimation = !0, this.hasAnimationLoop = !0, this.controls.removeChangeListener(), console.debug("three-cad-viewer: Change listener removed"), this.animate(), console.debug("three-cad-viewer: Animation loop started")) : (this.hasAnimationLoop && console.debug("three-cad-viewer: Turning animation loop off"), this.continueAnimation = !1, this.hasAnimationLoop = !1, this.controls.addChangeListener(() => this.update(!0, !0)), console.debug("three-cad-viewer: Change listener registered"), setTimeout(() => this.update(!0, !0), 50));
  }
  // - - - - - - - - - - - - - - - - - - - - - - - -
  // Clean up
  // - - - - - - - - - - - - - - - - - - - - - - - -
  /**
   * Remove assets and event handlers.
   */
  dispose() {
    this.clear(), me(this.gridHelper), this.gridHelper = null, this.orientationMarker != null && this.orientationMarker.dispose(), this.renderer != null && (this.renderer.renderLists.dispose(), this.renderer.getContext("webgl2").getExtension("WEBGL_lose_context").loseContext(), console.debug("three-cad-viewer: WebGL context disposed"), this.renderer = null), this.ambientLight.dispose(), this.ambientLight = null, this.directLight.dispose(), this.directLight = null, this.materialSettings = null, this.clipping = null, this.camera = null, this.gridHelper = null, this.axesHelper = null, this.controls = null, this.orientationMarker = null, this.compactTree = null, me(this.cadTools), this.cadTools = null, this.clipAction = null, this.treeview.dispose(), this.treeview = null, this.animation = null, this.clipNormals = null, this.lastNotification = null, this.clipNormal0 = null, this.clipNormal1 = null, this.clipNormal2 = null, this.display = null, this.renderOptions = null, this.mouse = null, this.tree = null, this.info = null, this.bbox = null, this.keymap = null, this.raycaster && (this.raycaster.dispose(), this.raycaster = null);
  }
  /**
   * Clear CAD view and remove event handler.
   */
  clear() {
    this.scene != null && (this.hasAnimationLoop = !1, this.continueAnimation = !1, this.hasAnimationLoop || (this.controls.removeChangeListener(), console.debug("three-cad-viewer: Change listener removed")), this.hasAnimationLoop = !1, this.display.showAnimationControl(!1), this.animation != null && me(this.animation), this.display.setExplodeCheck(!1), this.display.setExplode("", !1), this.shapes.format == "GDS" && (this.display.setZScaleCheck(!1), this.display.setZScale("", !1)), this.renderer.clear(), this.cadTools && (this.cadTools.disable(), this.display.currentButton != null && (this.display.toolbarButtons[this.display.currentButton].set(!1), this.display.setTool(this.display.currentButton, !1))), me(this.scene), me(this.gridHelper), me(this.clipping), this.clipping = null, this.display.clearCadTree(), me(this.info), me(this.camera), me(this.controls), this.scene = null, this.ready = !1), this.shapes != null && (me(this.shapes), this.shapes = null), this.expandedNestedGroup != null && (me(this.expandedNestedGroup), this.expandedNestedGroup = null), this.compactNestedGroup != null && (me(this.compactNestedGroup), this.compactNestedGroup = null), this.nestedGroup != null && (me(this.nestedGroup), this.nestedGroup = null);
  }
  /**
   * Toggle the two version of the NestedGroup
   * @param expanded - whether to render the exploded or compact version
   */
  toggleGroup(t) {
    var e = new ud("toggleGroup", this.timeit), i = () => {
      this.nestedGroup.setTransparent(this.transparent), this.nestedGroup.setBlackEdges(this.blackEdges), this.nestedGroup.setMetalness(this.metalness), this.nestedGroup.setRoughness(this.roughness), this.nestedGroup.setPolygonOffset(2);
    };
    if (this.compactNestedGroup == null && !t || this.expandedNestedGroup == null && t) {
      this.setRenderDefaults(this.renderOptions);
      var n;
      t ? this.expandedNestedGroup == null && (n = this.renderTessellatedShapes(t, this.shapes), this.nestedGroup = n.group, this.expandedNestedGroup = n.group, i(), this.expandedTree = n.tree) : this.compactNestedGroup == null && (n = this.renderTessellatedShapes(t, this.shapes), this.nestedGroup = n.group, this.compactNestedGroup = n.group, i(), this.compactTree = n.tree), e.split(`rendered${t ? " exploded" : " compact"} shapes`);
    } else
      this.nestedGroup = t ? this.expandedNestedGroup : this.compactNestedGroup, i();
    this.expandedTree && this.syncTreeStates(this.compactTree, this.expandedTree, t, ""), e.split("synched tree states"), this.tree = t ? this.expandedTree : this.compactTree, this.scene.children[0] = this.nestedGroup.rootGroup, e.split("added shapes to scene"), me(this.treeview), this.treeview = new QE(
      this.tree,
      this.display.cadTreeScrollContainer,
      this.setObject,
      this.handlePick,
      this.update,
      this.notifyStates,
      this.getNodeColor,
      this.theme,
      this.newTreeBehavior,
      !1
    ), this.display.clearCadTree();
    const s = this.treeview.create();
    e.split("created tree"), this.display.addCadTree(s), this.treeview.render(), e.split("rendered tree"), e.stop();
  }
  /**
   * Toggle tab and ensure collaps is treated correctly
   * Needs to be called in sync with toggleGroup!
   * @param boolean disable - true to disable clipping tab
   */
  toggleTab(t) {
    var e = new ud("toggleTab", this.timeit);
    switch (this.display.selectTabByName("tree"), e.split("collapse tree"), this.collapse) {
      case 0:
        this.treeview.expandAll();
        break;
      case 1:
        this.treeview.openLevel(-1);
        break;
      case 2:
        this.treeview.collapseAll();
        break;
      case 3:
        this.treeview.openLevel(1);
        break;
    }
    this.checkChanges({ states: this.getStates() }, !0), e.split("notify state changes"), e.stop(), this.display.toggleClippingTab(!t);
  }
  /**
   * Render a CAD object and build the navigation tree
   * @param {Shapes} shapes - the Shapes object representing the tessellated CAD object
   * @param {RenderOptions} renderOptions - the render options
   * @param {ViewerOptions} viewerOptions - the viewer options
   */
  render(t, e, i) {
    this.shapes = t, this.renderOptions = e, this.setViewerDefaults(i), this.animation.cleanBackup();
    const n = new ud("viewer", this.timeit);
    this.scene = new ko(), this.toggleGroup(!1), n.split("scene and tree done"), this.bbox || (this.bbox = this.nestedGroup.boundingBox());
    const s = new E();
    this.bbox.getCenter(s), this.bb_max = this.bbox.max_dist_from_center(), this.bb_radius = Math.max(
      this.bbox.boundingSphere().radius,
      s.length()
    ), n.split("bounding box"), this.info = new oT(this.display.cadInfo, this.theme), this.camera = new hT(
      this.cadWidth,
      this.height,
      this.bb_radius,
      i.target == null ? this.bbox.center() : i.target,
      this.ortho,
      i.up
    ), this.controls = new lT(
      this.control,
      this.camera.getCamera(),
      i.target == null ? this.bbox.center() : i.target,
      this.renderer.domElement,
      this.rotateSpeed,
      this.zoomSpeed,
      this.panSpeed
    ), this.controls.enableKeys = !1, this.controls.controls.screenSpacePanning = !0, i.position == null && i.quaternion == null ? (this.presetCamera("iso", this.zoom), this.display.highlightButton("iso")) : i.position != null ? (this.setCamera(
      !1,
      i.position,
      i.quaternion,
      this.zoom
    ), i.quaternion == null && this.camera.lookAtTarget()) : (this.info.addHtml(
      "<b>quaternion needs position to be provided, falling back to ISO view</b>"
    ), this.presetCamera("iso", this.zoom)), this.controls.update(), this.controls.saveState(), this.ambientLight = new af(
      16777215,
      kl(this.ambientIntensity)
    ), this.scene.add(this.ambientLight), this.directLight = new rf(
      16777215,
      kl(this.directIntensity)
    ), this.scene.add(this.directLight), this.setAmbientLight(this.ambientIntensity), this.setDirectLight(this.directIntensity), this.gridHelper = new XE(
      this,
      this.bbox,
      this.ticks,
      this.gridFontSize,
      this.centerGrid,
      this.axes0,
      this.grid,
      i.up == "Z",
      this.theme
    ), this.gridHelper.computeGrid(), this.scene.add(this.gridHelper), this.gridSize = this.gridHelper.size, this.axesHelper = new z_(
      this.bbox.center(),
      this.gridSize / 2,
      2,
      this.cadWidth,
      this.height,
      this.axes0,
      this.axes,
      this.theme
    ), this.scene.add(this.axesHelper);
    const r = 1.1 * Math.max(
      Math.abs(this.bbox.min.length()),
      Math.abs(this.bbox.max.length())
    );
    this.clipping = new sT(
      this.bbox.center(),
      2 * r,
      this.nestedGroup,
      this.display,
      this.theme
    ), this.display.setSliderLimits(this.gridSize / 2, this.bbox.center()), this.setClipNormal(0, i.clipNormal0, null, !0), this.setClipNormal(1, i.clipNormal1, null, !0), this.setClipNormal(2, i.clipNormal2, null, !0), this.clipSlider0 = i.clipSlider0 != null ? i.clipSlider0 : this.gridSize / 2, this.clipSlider1 = i.clipSlider1 != null ? i.clipSlider1 : this.gridSize / 2, this.clipSlider2 = i.clipSlider2 != null ? i.clipSlider2 : this.gridSize / 2, this.setClipSlider(0, this.clipSlider0, !0), this.setClipSlider(1, this.clipSlider1, !0), this.setClipSlider(2, this.clipSlider2, !0), this.setClipIntersection(i.clipIntersection, !0), this.setClipObjectColorCaps(i.clipObjectColors, !0), this.setClipPlaneHelpersCheck(i.clipPlaneHelpers, !0), this.scene.add(this.clipping), this.nestedGroup.setClipPlanes(this.clipping.clipPlanes), this.setLocalClipping(!1), this.clipping.setVisible(!1), this.toggleTab(!1), this.display.metalnessSlider.setValue(this.metalness * 100), this.display.roughnessSlider.setValue(this.roughness * 100), this.display.ambientlightSlider.setValue(this.ambientIntensity * 100), this.display.directionallightSlider.setValue(this.directIntensity * 100);
    const o = this.theme === "dark" || this.theme === "browser" && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
    this.orientationMarker = new KE(
      80,
      80,
      this.camera.getCamera(),
      o
    ), this.orientationMarker.create(), this.display.updateUI(
      this.axes,
      this.axes0,
      this.ortho,
      this.transparent,
      this.blackEdges,
      this.tools,
      this.glass
    ), n.split("ui updated"), this.display.autoCollapse(), n.split("stencil done"), this.toggleAnimationLoop(this.hasAnimationLoop), this.ready = !0, this.info.readyMsg(vg, this.control), n.split("show done"), this.notifyCallback && this.notifyCallback({
      tab: { old: null, new: this.display.activeTab },
      target: { old: null, new: this.controls.target },
      target0: { old: null, new: this.controls.target0 },
      clip_normal_0: { old: null, new: this.clipNormal0 },
      clip_normal_1: { old: null, new: this.clipNormal1 },
      clip_normal_2: { old: null, new: this.clipNormal2 }
    }), n.split("notification done"), this.update(!0, !1), this.treeview.update(), this.display.setTheme(this.theme), n.split("update done"), n.stop();
  }
  /**
   * Get camera type.
   * @returns {string} "ortho" or "perspective".
   **/
  getCameraType() {
    return this.camera.ortho ? "ortho" : "perspective";
  }
  /**
   * Set camera mode to OrthographicCamera or PersepctiveCamera (see also setOrtho)
   * @param {boolean} flag - whether the camery should be orthographic or persepctive
   * @param {boolean} [notify=true] - whether to send notification or not.
   */
  switchCamera(t, e = !0) {
    this.ortho = t, this.camera.switchCamera(t, e), this.controls.setCamera(this.camera.getCamera()), this.display.setOrthoCheck(t), this.checkChanges({ ortho: t }, e), this.gridHelper.scaleLabels(), this.gridHelper.update(this.camera.getZoom(), !0), this.update(!0, e);
  }
  /**
   * TODO: Doesn't work as expected. Needs to be fixed.
   *
   * Set camera mode to OrthographicCamera or PersepctiveCamera (see also setOrtho)
   * @param {number} distance - if provided, new camera distance
   * @param {boolean} [notify=true] - whether to send notification or not.
   */
  recenterCamera(t = !0) {
    const e = this.camera.getCamera(), i = new E(), n = this.bbox.center();
    i.fromArray(n);
    const s = new E(), r = this.controls.target;
    s.fromArray(r), this.camera.camera_distance = 5 * this.bb_radius, e.position.sub(s).add(i), this.controls.controls.target = i;
    let o = new E();
    e.getWorldDirection(o);
    let l = i.clone().add(o.normalize().multiplyScalar(-this.camera.camera_distance));
    e.position.set(l.x, l.y, l.z), this.update(!0, t);
  }
  /**
   * Centers the camera view on all visible objects in the scene.
   * Calculates a bounding box that encompasses all visible ObjectGroup instances
   * and sets the camera target to the center of that bounding box.
   *
   * @param {boolean} [notify=true] - Whether to notify listeners of the camera update
   */
  centerVisibleObjects(t = !0) {
    const e = this.nestedGroup.groups;
    var i = new or();
    for (var n in e) {
      var s = e[n];
      s instanceof ln && s.getVisibility() && (console.log(n), i.expandByObject(s));
    }
    const r = new E(...i.center());
    this.setCameraTarget(r), this.update(!0, t);
  }
  /**
   * Enbable/disable local clipping
   * @param {boolean} flag - whether to enable local clipping
   */
  setLocalClipping(t) {
    this.renderer.localClippingEnabled = t, this.update(this.updateMarker);
  }
  /**
   * Backup animation (for switch to explode animation)
   */
  backupAnimation() {
    this.animation.hasTracks() && (this.backupTracks = this.animation.backup());
  }
  /**
   * Restore animation (for switch back from explode animation)
   */
  restoreAnimation() {
    if (this.animation.hasBackup()) {
      var t = this.animation.restore();
      this.initAnimation(t.duration, t.speed, "A", t.repeat);
    }
  }
  removeLastBbox() {
    this.lastBbox != null && (this.scene.remove(this.lastBbox.bbox), this.lastBbox = null);
  }
  setPickHandler(t) {
    t ? this.renderer.domElement.addEventListener("dblclick", this.pick, !1) : this.renderer.domElement.removeEventListener(
      "dblclick",
      this.pick,
      !1
    );
  }
  /**
   * Set raycast mode
   * @function
   * @param {boolean} flag - turn raycast mode on or off
   */
  setRaycastMode(t) {
    t ? (this.raycaster = new ug(
      this.camera,
      this.renderer.domElement,
      this.cadWidth,
      this.height,
      this.bb_max / 30,
      this.scene.children.slice(0, 1),
      this.handleRaycastEvent
    ), this.raycaster.init()) : (this.raycaster && this.raycaster.dispose(), this.raycaster = null);
  }
  //
  // Getters and Setters
  //
  /**
   * Get whether axes helpers are shon/hidden.
   * @returns {boolean} axes value.
   **/
  getAxes() {
    return this.axes;
  }
  /**
   * Get visibility of grids.
   * @returns {number[]} grids value.
   **/
  getGrids() {
    return this.grid;
  }
  /**
   * Get location of axes.
   * @returns {boolean} axes0 value, true means at origin (0,0,0)
   **/
  getAxes0() {
    return this.axes0;
  }
  /**
   * Get intensity of ambient light.
   * @returns {number} ambientLight value.
   **/
  getAmbientLight() {
    return this.ambientIntensity;
  }
  /**
   * Get intensity of direct light.
   * @returns {number} directLight value.
   **/
  getDirectLight() {
    return this.directIntensity;
  }
  /**
   * Get transparency state of CAD objects.
   * @returns {boolean} transparent value.
   **/
  getTransparent() {
    return this.transparent;
  }
  /**
   * Get blackEdges value.
   * @returns {boolean} blackEdges value.
   **/
  getBlackEdges() {
    return this.blackEdges;
  }
  /**
   * Get ortho value.
   * @returns {number} ortho value.
   **/
  getOrtho() {
    return this.camera.ortho;
  }
  /**
   * Set/unset camera's orthographic mode.
   * @param {boolean} whether to set orthographic mode or not.
   **/
  setOrtho(t, e = !0) {
    this.switchCamera(t, e);
  }
  /**
   * Set zscaling value.
   * @param {number} scale factor.
   **/
  setZscaleValue(t) {
    this.nestedGroup.setZScale(t), this.zScale = t, this.update(!0);
  }
  /**
   * Get zoom value.
   * @returns {number} zoom value.
   **/
  getCameraZoom() {
    return this.camera.getZoom();
  }
  /**
   * Set zoom value.
   * @param {number} val - float zoom value.
   * @param {boolean} [notify=true] - whether to send notification or not.
   **/
  setCameraZoom(t, e = !0) {
    this.camera.setZoom(t), this.controls.update(), this.update(!0, e);
  }
  /**
   * Get the current camera position.
   * @returns {number[]} camera position as 3 dim array [x,y,z].
   **/
  getCameraPosition() {
    return this.camera.getPosition().toArray();
  }
  /**
   * Set camera position.
   * @param {number[]} position - camera position as 3 dim Array [x,y,z].
   * @param {relative} [relative=false] - flag whether the position is a relative (e.g. [1,1,1] for iso) or absolute point.
   * @param {boolean} [notify=true] - whether to send notification or not.
   **/
  setCameraPosition(t, e = !1, i = !0) {
    this.camera.setPosition(t, e), this.controls.update(), this.update(!0, i);
  }
  /**
   * Get the current camera rotation as quaternion.
   * @returns {number[]} camera rotation as 4 dim quaternion array [x,y,z,w].
   **/
  getCameraQuaternion() {
    return this.camera.getQuaternion().toArray();
  }
  /**
   * Set camera rotation via quaternion.
   * @param {number[]} quaternion - camera rotation as 4 dim quaternion array [x,y,z,w].
   * @param {boolean} [notify=true] - whether to send notification or not.
   **/
  setCameraQuaternion(t, e = !0) {
    this.camera.setQuaternion(t), this.controls.update(), this.update(!0, e);
  }
  /**
   * Get the current camera target.
   * @returns {number[]} camera target as 3 dim array array [x,y,z].
   **/
  getCameraTarget() {
    return this.controls.getTarget().toArray();
  }
  /**
   * Set camera target.
   * @param {number[]} target - camera target as 3 dim quaternion array [x,y,z].
   * @param {boolean} [notify=true] - whether to send notification or not.
   **/
  setCameraTarget(t, e = !0) {
    const i = this.camera.getCamera(), n = i.zoom, s = i.position.clone().sub(this.controls.getTarget());
    i.position.copy(t.clone().add(s)), i.updateWorldMatrix(!0, !1), this.controls.getTarget().copy(t), i.type === "OrthographicCamera" && (i.zoom = n, i.updateProjectionMatrix()), this.controls.update(), this.update(!0, e);
  }
  getCameraLocationSettings() {
    return {
      position: this.getCameraPosition(),
      quaternion: this.getCameraQuaternion(),
      target: this.getCameraTarget(),
      zoom: this.getCameraZoom()
    };
  }
  setCameraLocationSettings(t = null, e = null, i = null, n = null, s = !0) {
    t != null && this.camera.setPosition(t, !1), e != null && this.control === "trackball" && this.camera.setQuaternion(e), i != null && this.controls.setTarget(new E(...i)), n != null && this.camera.setZoom(n), this.controls.update(), this.update(!0, s);
  }
  /**
   * Get default color of the edges.
   * @returns {number} edgeColor value.
   **/
  getEdgeColor() {
    return this.edgeColor;
  }
  /**
   * Get default opacity.
   * @returns {number} opacity value.
   **/
  getOpacity() {
    return this.defaultOpacity;
  }
  /**
   * Get whether tools are shown/hidden.
   * @returns {boolean} tools value.
   **/
  getTools() {
    return this.tools;
  }
  /**
   * Get states of a treeview leafs.
   **/
  getStates() {
    return this.treeview.getStates();
  }
  /**
   * Get state of a treeview leafs for a path.
   * separator can be / or |
   * @param {string} path - path of the object
   * @returns {number[]} state value in the form of [mesh, edges] = [0/1, 0/1]
   **/
  getState(t) {
    var e = t.replaceAll("|", "/");
    return this.treeview.getState(e);
  }
  /**
   * Get zoom speed.
   * @returns {number} zoomSpeed value.
   **/
  getZoomSpeed() {
    return this.zoomSpeed;
  }
  /**
   * Get panning speed.
   * @returns {number} pan speed value.
   **/
  getPanSpeed() {
    return this.panSpeed;
  }
  /**
   * Get rotation speed.
   * @returns {number} rotation speed value.
   **/
  getRotateSpeed() {
    return this.rotateSpeed;
  }
  /**
   * Get intersection mode.
   * @returns {boolean} clip intersection value.
   **/
  getClipIntersection() {
    return this.clipIntersection;
  }
  /**
   * Get clipping plane state.
   * @returns {boolean} clip plane visibility value.
   **/
  getClipPlaneHelpers() {
    return this.clipPlaneHelpers;
  }
  /**
   * Set clip plane helpers check box
   * @function
   * @param {boolean} flag - whether to show clip plane helpers
   */
  setClipPlaneHelpersCheck(t) {
    t != null && this.display.setClipPlaneHelpersCheck(t);
  }
  /**
   * Get clipping plane state.
   * @param {boolean} index - index of the normal: 0, 1 ,2
   * @returns {boolean} clip plane visibility value.
   **/
  getClipNormal(t) {
    return this.clipNormals[t];
  }
  /**
   * Set the normal at index to a given normal
   * @function
   * @param {number} index - index of the normal: 0, 1 ,2
   * @param {number[]} normal - 3 dim array representing the normal
   * @param {number} [value=null] - value of the slider, if given
   * @param {boolean} [notify=true] - whether to send notification or not.
   */
  setClipNormal(t, e, i = null, n = !0) {
    if (e == null) return;
    const s = new E(...e).normalize().toArray();
    this.clipNormals[t] = s, this.clipping.setNormal(t, new E(...s)), this.clipping.setConstant(t, this.gridSize / 2), i == null && (i = this.gridSize / 2), this.setClipSlider(t, i);
    var r = {};
    r[`clip_normal_${t}`] = s, r[`clip_slider_${t}`] = i, this.checkChanges(r, n), this.nestedGroup.setClipPlanes(this.clipping.clipPlanes), this.update(this.updateMarker);
  }
  /**
   * Calculate explode trajectories and initiate the animation
   *
   * @param {number} [duration=2] - duration of animation.
   * @param {number} [speed=1] - speed of animation.
   * @param {number} [multiplier=2.5] - multiplier for length of trajectories.
   */
  explode(t = 2, e = 1, i = 2.5) {
    this.clearAnimation();
    const n = this.getAxes0();
    var s = new E(), r = new E(), o = null, l = null, h = null;
    if (!n) {
      var c = new we().setFromObject(this.nestedGroup.rootGroup);
      c.getCenter(s);
    }
    for (var u in this.nestedGroup.groups) {
      var d = this.nestedGroup.groups[u], p = new we();
      d instanceof ln && p.expandByObject(d), !p.isEmpty() && (p.getCenter(r), o = r.sub(s), l = d.parent.worldToLocal(o.clone()), h = d.parent.worldToLocal(
        o.clone().multiplyScalar(i)
      ), h.sub(l), this.addAnimationTrack(
        u,
        "t",
        [0, t],
        [[0, 0, 0], h.toArray()]
      ));
    }
    this.initAnimation(t, e, "E", !1);
  }
  /**
   * Set modifiers for keymap
   *
   * @param {config} keymap - e.g. {"shift": "shiftKey", "ctrl": "ctrlKey", "meta": "altKey"}
   */
  setKeyMap(t) {
    const e = De.get_config();
    De.set(t), this.display.updateHelp(e, t);
  }
  /**
   * Resize UI and renderer
   *
   * @param {number} cadWidth - new width of CAD View
   * @param {number} treeWidth - new width of navigation tree
   * @param {number} height - new height of CAD View
   * @param {boolean} [glass=false] - Whether to use glass mode or not
   */
  resizeCadView(t, e, i, n = !1) {
    this.cadWidth = t, this.height = i, this.renderer.setSize(t, i), this.display.setSizes({
      treeWidth: e,
      cadWidth: t,
      height: i
    }), this.display.glassMode(n), t + (n ? 0 : e) >= this.display.widthThreshold() ? this.display.cadTool.maximize() : this.display.cadTool.minimize(), this.camera.changeDimensions(this.bb_radius, t, i), this.update(!0), this.raycaster && (this.raycaster.width = t, this.raycaster.height = i);
  }
  vector3(t = 0, e = 0, i = 0) {
    return new E(t, e, i);
  }
  quaternion(t = 0, e = 0, i = 0, n = 1) {
    return new ve(t, e, i, n);
  }
}
/**
 * @license
 * Copyright 2010-2024 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
const N_ = "170", Bo = 0, gf = 1, bg = 1, Mg = 100, Sg = 204, wg = 205, Ag = 3, uT = 0, O_ = 300, Eg = 1e3, Yl = 1001, Tg = 1002, dT = 1006, pT = 1008, fT = 1009, mT = 1015, gT = 1023, yT = 0, k_ = "", an = "srgb", V_ = "srgb-linear", H_ = "linear", _p = "srgb", Vr = 7680, md = 34055, gd = 34056, Sc = 519, xp = 35044, Zl = 2e3, Cg = 2001;
let cu = class {
  addEventListener(t, e) {
    this._listeners === void 0 && (this._listeners = {});
    const i = this._listeners;
    i[t] === void 0 && (i[t] = []), i[t].indexOf(e) === -1 && i[t].push(e);
  }
  hasEventListener(t, e) {
    if (this._listeners === void 0) return !1;
    const i = this._listeners;
    return i[t] !== void 0 && i[t].indexOf(e) !== -1;
  }
  removeEventListener(t, e) {
    if (this._listeners === void 0) return;
    const n = this._listeners[t];
    if (n !== void 0) {
      const s = n.indexOf(e);
      s !== -1 && n.splice(s, 1);
    }
  }
  dispatchEvent(t) {
    if (this._listeners === void 0) return;
    const i = this._listeners[t.type];
    if (i !== void 0) {
      t.target = this;
      const n = i.slice(0);
      for (let s = 0, r = n.length; s < r; s++)
        n[s].call(this, t);
      t.target = null;
    }
  }
};
const ti = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"];
let Rg = 1234567;
const G_ = Math.PI / 180, W_ = 180 / Math.PI;
function Jn() {
  const a = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, e = Math.random() * 4294967295 | 0, i = Math.random() * 4294967295 | 0;
  return (ti[a & 255] + ti[a >> 8 & 255] + ti[a >> 16 & 255] + ti[a >> 24 & 255] + "-" + ti[t & 255] + ti[t >> 8 & 255] + "-" + ti[t >> 16 & 15 | 64] + ti[t >> 24 & 255] + "-" + ti[e & 63 | 128] + ti[e >> 8 & 255] + "-" + ti[e >> 16 & 255] + ti[e >> 24 & 255] + ti[i & 255] + ti[i >> 8 & 255] + ti[i >> 16 & 255] + ti[i >> 24 & 255]).toLowerCase();
}
function ai(a, t, e) {
  return Math.max(t, Math.min(e, a));
}
function yf(a, t) {
  return (a % t + t) % t;
}
function _T(a, t, e, i, n) {
  return i + (a - t) * (n - i) / (e - t);
}
function xT(a, t, e) {
  return a !== t ? (e - a) / (t - a) : 0;
}
function yo(a, t, e) {
  return (1 - e) * a + e * t;
}
function vT(a, t, e, i) {
  return yo(a, t, 1 - Math.exp(-e * i));
}
function bT(a, t = 1) {
  return t - Math.abs(yf(a, t * 2) - t);
}
function MT(a, t, e) {
  return a <= t ? 0 : a >= e ? 1 : (a = (a - t) / (e - t), a * a * (3 - 2 * a));
}
function ST(a, t, e) {
  return a <= t ? 0 : a >= e ? 1 : (a = (a - t) / (e - t), a * a * a * (a * (a * 6 - 15) + 10));
}
function wT(a, t) {
  return a + Math.floor(Math.random() * (t - a + 1));
}
function AT(a, t) {
  return a + Math.random() * (t - a);
}
function ET(a) {
  return a * (0.5 - Math.random());
}
function TT(a) {
  a !== void 0 && (Rg = a);
  let t = Rg += 1831565813;
  return t = Math.imul(t ^ t >>> 15, t | 1), t ^= t + Math.imul(t ^ t >>> 7, t | 61), ((t ^ t >>> 14) >>> 0) / 4294967296;
}
function CT(a) {
  return a * G_;
}
function RT(a) {
  return a * W_;
}
function PT(a) {
  return (a & a - 1) === 0 && a !== 0;
}
function IT(a) {
  return Math.pow(2, Math.ceil(Math.log(a) / Math.LN2));
}
function LT(a) {
  return Math.pow(2, Math.floor(Math.log(a) / Math.LN2));
}
function DT(a, t, e, i, n) {
  const s = Math.cos, r = Math.sin, o = s(e / 2), l = r(e / 2), h = s((t + i) / 2), c = r((t + i) / 2), u = s((t - i) / 2), d = r((t - i) / 2), p = s((i - t) / 2), f = r((i - t) / 2);
  switch (n) {
    case "XYX":
      a.set(o * c, l * u, l * d, o * h);
      break;
    case "YZY":
      a.set(l * d, o * c, l * u, o * h);
      break;
    case "ZXZ":
      a.set(l * u, l * d, o * c, o * h);
      break;
    case "XZX":
      a.set(o * c, l * f, l * p, o * h);
      break;
    case "YXY":
      a.set(l * p, o * c, l * f, o * h);
      break;
    case "ZYZ":
      a.set(l * f, l * p, o * c, o * h);
      break;
    default:
      console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + n);
  }
}
function hn(a, t) {
  switch (t.constructor) {
    case Float32Array:
      return a;
    case Uint32Array:
      return a / 4294967295;
    case Uint16Array:
      return a / 65535;
    case Uint8Array:
      return a / 255;
    case Int32Array:
      return Math.max(a / 2147483647, -1);
    case Int16Array:
      return Math.max(a / 32767, -1);
    case Int8Array:
      return Math.max(a / 127, -1);
    default:
      throw new Error("Invalid component type.");
  }
}
function ue(a, t) {
  switch (t.constructor) {
    case Float32Array:
      return a;
    case Uint32Array:
      return Math.round(a * 4294967295);
    case Uint16Array:
      return Math.round(a * 65535);
    case Uint8Array:
      return Math.round(a * 255);
    case Int32Array:
      return Math.round(a * 2147483647);
    case Int16Array:
      return Math.round(a * 32767);
    case Int8Array:
      return Math.round(a * 127);
    default:
      throw new Error("Invalid component type.");
  }
}
const FT = {
  DEG2RAD: G_,
  RAD2DEG: W_,
  generateUUID: Jn,
  clamp: ai,
  euclideanModulo: yf,
  mapLinear: _T,
  inverseLerp: xT,
  lerp: yo,
  damp: vT,
  pingpong: bT,
  smoothstep: MT,
  smootherstep: ST,
  randInt: wT,
  randFloat: AT,
  randFloatSpread: ET,
  seededRandom: TT,
  degToRad: CT,
  radToDeg: RT,
  isPowerOfTwo: PT,
  ceilPowerOfTwo: IT,
  floorPowerOfTwo: LT,
  setQuaternionFromProperEuler: DT,
  normalize: ue,
  denormalize: hn
};
let _i = class q_ {
  constructor(t = 0, e = 0) {
    q_.prototype.isVector2 = !0, this.x = t, this.y = e;
  }
  get width() {
    return this.x;
  }
  set width(t) {
    this.x = t;
  }
  get height() {
    return this.y;
  }
  set height(t) {
    this.y = t;
  }
  set(t, e) {
    return this.x = t, this.y = e, this;
  }
  setScalar(t) {
    return this.x = t, this.y = t, this;
  }
  setX(t) {
    return this.x = t, this;
  }
  setY(t) {
    return this.y = t, this;
  }
  setComponent(t, e) {
    switch (t) {
      case 0:
        this.x = e;
        break;
      case 1:
        this.y = e;
        break;
      default:
        throw new Error("index is out of range: " + t);
    }
    return this;
  }
  getComponent(t) {
    switch (t) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      default:
        throw new Error("index is out of range: " + t);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y);
  }
  copy(t) {
    return this.x = t.x, this.y = t.y, this;
  }
  add(t) {
    return this.x += t.x, this.y += t.y, this;
  }
  addScalar(t) {
    return this.x += t, this.y += t, this;
  }
  addVectors(t, e) {
    return this.x = t.x + e.x, this.y = t.y + e.y, this;
  }
  addScaledVector(t, e) {
    return this.x += t.x * e, this.y += t.y * e, this;
  }
  sub(t) {
    return this.x -= t.x, this.y -= t.y, this;
  }
  subScalar(t) {
    return this.x -= t, this.y -= t, this;
  }
  subVectors(t, e) {
    return this.x = t.x - e.x, this.y = t.y - e.y, this;
  }
  multiply(t) {
    return this.x *= t.x, this.y *= t.y, this;
  }
  multiplyScalar(t) {
    return this.x *= t, this.y *= t, this;
  }
  divide(t) {
    return this.x /= t.x, this.y /= t.y, this;
  }
  divideScalar(t) {
    return this.multiplyScalar(1 / t);
  }
  applyMatrix3(t) {
    const e = this.x, i = this.y, n = t.elements;
    return this.x = n[0] * e + n[3] * i + n[6], this.y = n[1] * e + n[4] * i + n[7], this;
  }
  min(t) {
    return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this;
  }
  max(t) {
    return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this;
  }
  clamp(t, e) {
    return this.x = Math.max(t.x, Math.min(e.x, this.x)), this.y = Math.max(t.y, Math.min(e.y, this.y)), this;
  }
  clampScalar(t, e) {
    return this.x = Math.max(t, Math.min(e, this.x)), this.y = Math.max(t, Math.min(e, this.y)), this;
  }
  clampLength(t, e) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(Math.max(t, Math.min(e, i)));
  }
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this;
  }
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this;
  }
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this;
  }
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this;
  }
  negate() {
    return this.x = -this.x, this.y = -this.y, this;
  }
  dot(t) {
    return this.x * t.x + this.y * t.y;
  }
  cross(t) {
    return this.x * t.y - this.y * t.x;
  }
  lengthSq() {
    return this.x * this.x + this.y * this.y;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  angle() {
    return Math.atan2(-this.y, -this.x) + Math.PI;
  }
  angleTo(t) {
    const e = Math.sqrt(this.lengthSq() * t.lengthSq());
    if (e === 0) return Math.PI / 2;
    const i = this.dot(t) / e;
    return Math.acos(ai(i, -1, 1));
  }
  distanceTo(t) {
    return Math.sqrt(this.distanceToSquared(t));
  }
  distanceToSquared(t) {
    const e = this.x - t.x, i = this.y - t.y;
    return e * e + i * i;
  }
  manhattanDistanceTo(t) {
    return Math.abs(this.x - t.x) + Math.abs(this.y - t.y);
  }
  setLength(t) {
    return this.normalize().multiplyScalar(t);
  }
  lerp(t, e) {
    return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this;
  }
  lerpVectors(t, e, i) {
    return this.x = t.x + (e.x - t.x) * i, this.y = t.y + (e.y - t.y) * i, this;
  }
  equals(t) {
    return t.x === this.x && t.y === this.y;
  }
  fromArray(t, e = 0) {
    return this.x = t[e], this.y = t[e + 1], this;
  }
  toArray(t = [], e = 0) {
    return t[e] = this.x, t[e + 1] = this.y, t;
  }
  fromBufferAttribute(t, e) {
    return this.x = t.getX(e), this.y = t.getY(e), this;
  }
  rotateAround(t, e) {
    const i = Math.cos(e), n = Math.sin(e), s = this.x - t.x, r = this.y - t.y;
    return this.x = s * i - r * n + t.x, this.y = s * n + r * i + t.y, this;
  }
  random() {
    return this.x = Math.random(), this.y = Math.random(), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y;
  }
}, de = class $_ {
  constructor(t, e, i, n, s, r, o, l, h) {
    $_.prototype.isMatrix3 = !0, this.elements = [
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ], t !== void 0 && this.set(t, e, i, n, s, r, o, l, h);
  }
  set(t, e, i, n, s, r, o, l, h) {
    const c = this.elements;
    return c[0] = t, c[1] = n, c[2] = o, c[3] = e, c[4] = s, c[5] = l, c[6] = i, c[7] = r, c[8] = h, this;
  }
  identity() {
    return this.set(
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ), this;
  }
  copy(t) {
    const e = this.elements, i = t.elements;
    return e[0] = i[0], e[1] = i[1], e[2] = i[2], e[3] = i[3], e[4] = i[4], e[5] = i[5], e[6] = i[6], e[7] = i[7], e[8] = i[8], this;
  }
  extractBasis(t, e, i) {
    return t.setFromMatrix3Column(this, 0), e.setFromMatrix3Column(this, 1), i.setFromMatrix3Column(this, 2), this;
  }
  setFromMatrix4(t) {
    const e = t.elements;
    return this.set(
      e[0],
      e[4],
      e[8],
      e[1],
      e[5],
      e[9],
      e[2],
      e[6],
      e[10]
    ), this;
  }
  multiply(t) {
    return this.multiplyMatrices(this, t);
  }
  premultiply(t) {
    return this.multiplyMatrices(t, this);
  }
  multiplyMatrices(t, e) {
    const i = t.elements, n = e.elements, s = this.elements, r = i[0], o = i[3], l = i[6], h = i[1], c = i[4], u = i[7], d = i[2], p = i[5], f = i[8], y = n[0], g = n[3], m = n[6], v = n[1], x = n[4], _ = n[7], S = n[2], w = n[5], T = n[8];
    return s[0] = r * y + o * v + l * S, s[3] = r * g + o * x + l * w, s[6] = r * m + o * _ + l * T, s[1] = h * y + c * v + u * S, s[4] = h * g + c * x + u * w, s[7] = h * m + c * _ + u * T, s[2] = d * y + p * v + f * S, s[5] = d * g + p * x + f * w, s[8] = d * m + p * _ + f * T, this;
  }
  multiplyScalar(t) {
    const e = this.elements;
    return e[0] *= t, e[3] *= t, e[6] *= t, e[1] *= t, e[4] *= t, e[7] *= t, e[2] *= t, e[5] *= t, e[8] *= t, this;
  }
  determinant() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8];
    return e * r * c - e * o * h - i * s * c + i * o * l + n * s * h - n * r * l;
  }
  invert() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8], u = c * r - o * h, d = o * l - c * s, p = h * s - r * l, f = e * u + i * d + n * p;
    if (f === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
    const y = 1 / f;
    return t[0] = u * y, t[1] = (n * h - c * i) * y, t[2] = (o * i - n * r) * y, t[3] = d * y, t[4] = (c * e - n * l) * y, t[5] = (n * s - o * e) * y, t[6] = p * y, t[7] = (i * l - h * e) * y, t[8] = (r * e - i * s) * y, this;
  }
  transpose() {
    let t;
    const e = this.elements;
    return t = e[1], e[1] = e[3], e[3] = t, t = e[2], e[2] = e[6], e[6] = t, t = e[5], e[5] = e[7], e[7] = t, this;
  }
  getNormalMatrix(t) {
    return this.setFromMatrix4(t).invert().transpose();
  }
  transposeIntoArray(t) {
    const e = this.elements;
    return t[0] = e[0], t[1] = e[3], t[2] = e[6], t[3] = e[1], t[4] = e[4], t[5] = e[7], t[6] = e[2], t[7] = e[5], t[8] = e[8], this;
  }
  setUvTransform(t, e, i, n, s, r, o) {
    const l = Math.cos(s), h = Math.sin(s);
    return this.set(
      i * l,
      i * h,
      -i * (l * r + h * o) + r + t,
      -n * h,
      n * l,
      -n * (-h * r + l * o) + o + e,
      0,
      0,
      1
    ), this;
  }
  //
  scale(t, e) {
    return this.premultiply(yd.makeScale(t, e)), this;
  }
  rotate(t) {
    return this.premultiply(yd.makeRotation(-t)), this;
  }
  translate(t, e) {
    return this.premultiply(yd.makeTranslation(t, e)), this;
  }
  // for 2D Transforms
  makeTranslation(t, e) {
    return t.isVector2 ? this.set(
      1,
      0,
      t.x,
      0,
      1,
      t.y,
      0,
      0,
      1
    ) : this.set(
      1,
      0,
      t,
      0,
      1,
      e,
      0,
      0,
      1
    ), this;
  }
  makeRotation(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      -i,
      0,
      i,
      e,
      0,
      0,
      0,
      1
    ), this;
  }
  makeScale(t, e) {
    return this.set(
      t,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      1
    ), this;
  }
  //
  equals(t) {
    const e = this.elements, i = t.elements;
    for (let n = 0; n < 9; n++)
      if (e[n] !== i[n]) return !1;
    return !0;
  }
  fromArray(t, e = 0) {
    for (let i = 0; i < 9; i++)
      this.elements[i] = t[i + e];
    return this;
  }
  toArray(t = [], e = 0) {
    const i = this.elements;
    return t[e] = i[0], t[e + 1] = i[1], t[e + 2] = i[2], t[e + 3] = i[3], t[e + 4] = i[4], t[e + 5] = i[5], t[e + 6] = i[6], t[e + 7] = i[7], t[e + 8] = i[8], t;
  }
  clone() {
    return new this.constructor().fromArray(this.elements);
  }
};
const yd = /* @__PURE__ */ new de();
function UT(a) {
  for (let t = a.length - 1; t >= 0; --t)
    if (a[t] >= 65535) return !0;
  return !1;
}
function Pg(a) {
  return document.createElementNS("http://www.w3.org/1999/xhtml", a);
}
const Wi = {
  enabled: !0,
  workingColorSpace: V_,
  /**
   * Implementations of supported color spaces.
   *
   * Required:
   *	- primaries: chromaticity coordinates [ rx ry gx gy bx by ]
   *	- whitePoint: reference white [ x y ]
   *	- transfer: transfer function (pre-defined)
   *	- toXYZ: Matrix3 RGB to XYZ transform
   *	- fromXYZ: Matrix3 XYZ to RGB transform
   *	- luminanceCoefficients: RGB luminance coefficients
   *
   * Optional:
   *  - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
   *  - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
   *
   * Reference:
   * - https://www.russellcottrell.com/photo/matrixCalculator.htm
   */
  spaces: {},
  convert: function(a, t, e) {
    return this.enabled === !1 || t === e || !t || !e || (this.spaces[t].transfer === _p && (a.r = Kn(a.r), a.g = Kn(a.g), a.b = Kn(a.b)), this.spaces[t].primaries !== this.spaces[e].primaries && (a.applyMatrix3(this.spaces[t].toXYZ), a.applyMatrix3(this.spaces[e].fromXYZ)), this.spaces[e].transfer === _p && (a.r = ha(a.r), a.g = ha(a.g), a.b = ha(a.b))), a;
  },
  fromWorkingColorSpace: function(a, t) {
    return this.convert(a, this.workingColorSpace, t);
  },
  toWorkingColorSpace: function(a, t) {
    return this.convert(a, t, this.workingColorSpace);
  },
  getPrimaries: function(a) {
    return this.spaces[a].primaries;
  },
  getTransfer: function(a) {
    return a === k_ ? H_ : this.spaces[a].transfer;
  },
  getLuminanceCoefficients: function(a, t = this.workingColorSpace) {
    return a.fromArray(this.spaces[t].luminanceCoefficients);
  },
  define: function(a) {
    Object.assign(this.spaces, a);
  },
  // Internal APIs
  _getMatrix: function(a, t, e) {
    return a.copy(this.spaces[t].toXYZ).multiply(this.spaces[e].fromXYZ);
  },
  _getDrawingBufferColorSpace: function(a) {
    return this.spaces[a].outputColorSpaceConfig.drawingBufferColorSpace;
  },
  _getUnpackColorSpace: function(a = this.workingColorSpace) {
    return this.spaces[a].workingColorSpaceConfig.unpackColorSpace;
  }
};
function Kn(a) {
  return a < 0.04045 ? a * 0.0773993808 : Math.pow(a * 0.9478672986 + 0.0521327014, 2.4);
}
function ha(a) {
  return a < 31308e-7 ? a * 12.92 : 1.055 * Math.pow(a, 0.41666) - 0.055;
}
const Ig = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], Lg = [0.2126, 0.7152, 0.0722], Dg = [0.3127, 0.329], Fg = /* @__PURE__ */ new de().set(
  0.4123908,
  0.3575843,
  0.1804808,
  0.212639,
  0.7151687,
  0.0721923,
  0.0193308,
  0.1191948,
  0.9505322
), Ug = /* @__PURE__ */ new de().set(
  3.2409699,
  -1.5373832,
  -0.4986108,
  -0.9692436,
  1.8759675,
  0.0415551,
  0.0556301,
  -0.203977,
  1.0569715
);
Wi.define({
  [V_]: {
    primaries: Ig,
    whitePoint: Dg,
    transfer: H_,
    toXYZ: Fg,
    fromXYZ: Ug,
    luminanceCoefficients: Lg,
    workingColorSpaceConfig: { unpackColorSpace: an },
    outputColorSpaceConfig: { drawingBufferColorSpace: an }
  },
  [an]: {
    primaries: Ig,
    whitePoint: Dg,
    transfer: _p,
    toXYZ: Fg,
    fromXYZ: Ug,
    luminanceCoefficients: Lg,
    outputColorSpaceConfig: { drawingBufferColorSpace: an }
  }
});
let Hr, BT = class {
  static getDataURL(t) {
    if (/^data:/i.test(t.src) || typeof HTMLCanvasElement > "u")
      return t.src;
    let e;
    if (t instanceof HTMLCanvasElement)
      e = t;
    else {
      Hr === void 0 && (Hr = Pg("canvas")), Hr.width = t.width, Hr.height = t.height;
      const i = Hr.getContext("2d");
      t instanceof ImageData ? i.putImageData(t, 0, 0) : i.drawImage(t, 0, 0, t.width, t.height), e = Hr;
    }
    return e.width > 2048 || e.height > 2048 ? (console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons", t), e.toDataURL("image/jpeg", 0.6)) : e.toDataURL("image/png");
  }
  static sRGBToLinear(t) {
    if (typeof HTMLImageElement < "u" && t instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && t instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && t instanceof ImageBitmap) {
      const e = Pg("canvas");
      e.width = t.width, e.height = t.height;
      const i = e.getContext("2d");
      i.drawImage(t, 0, 0, t.width, t.height);
      const n = i.getImageData(0, 0, t.width, t.height), s = n.data;
      for (let r = 0; r < s.length; r++)
        s[r] = Kn(s[r] / 255) * 255;
      return i.putImageData(n, 0, 0), e;
    } else if (t.data) {
      const e = t.data.slice(0);
      for (let i = 0; i < e.length; i++)
        e instanceof Uint8Array || e instanceof Uint8ClampedArray ? e[i] = Math.floor(Kn(e[i] / 255) * 255) : e[i] = Kn(e[i]);
      return {
        data: e,
        width: t.width,
        height: t.height
      };
    } else
      return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), t;
  }
}, zT = 0, NT = class {
  constructor(t = null) {
    this.isSource = !0, Object.defineProperty(this, "id", { value: zT++ }), this.uuid = Jn(), this.data = t, this.dataReady = !0, this.version = 0;
  }
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  toJSON(t) {
    const e = t === void 0 || typeof t == "string";
    if (!e && t.images[this.uuid] !== void 0)
      return t.images[this.uuid];
    const i = {
      uuid: this.uuid,
      url: ""
    }, n = this.data;
    if (n !== null) {
      let s;
      if (Array.isArray(n)) {
        s = [];
        for (let r = 0, o = n.length; r < o; r++)
          n[r].isDataTexture ? s.push(_d(n[r].image)) : s.push(_d(n[r]));
      } else
        s = _d(n);
      i.url = s;
    }
    return e || (t.images[this.uuid] = i), i;
  }
};
function _d(a) {
  return typeof HTMLImageElement < "u" && a instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && a instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && a instanceof ImageBitmap ? BT.getDataURL(a) : a.data ? {
    data: Array.from(a.data),
    width: a.width,
    height: a.height,
    type: a.data.constructor.name
  } : (console.warn("THREE.Texture: Unable to serialize Texture."), {});
}
let OT = 0, _f = class Rh extends cu {
  constructor(t = Rh.DEFAULT_IMAGE, e = Rh.DEFAULT_MAPPING, i = Yl, n = Yl, s = dT, r = pT, o = gT, l = fT, h = Rh.DEFAULT_ANISOTROPY, c = k_) {
    super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: OT++ }), this.uuid = Jn(), this.name = "", this.source = new NT(t), this.mipmaps = [], this.mapping = e, this.channel = 0, this.wrapS = i, this.wrapT = n, this.magFilter = s, this.minFilter = r, this.anisotropy = h, this.format = o, this.internalFormat = null, this.type = l, this.offset = new _i(0, 0), this.repeat = new _i(1, 1), this.center = new _i(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new de(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = c, this.userData = {}, this.version = 0, this.onUpdate = null, this.isRenderTargetTexture = !1, this.pmremVersion = 0;
  }
  get image() {
    return this.source.data;
  }
  set image(t = null) {
    this.source.data = t;
  }
  updateMatrix() {
    this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(t) {
    return this.name = t.name, this.source = t.source, this.mipmaps = t.mipmaps.slice(0), this.mapping = t.mapping, this.channel = t.channel, this.wrapS = t.wrapS, this.wrapT = t.wrapT, this.magFilter = t.magFilter, this.minFilter = t.minFilter, this.anisotropy = t.anisotropy, this.format = t.format, this.internalFormat = t.internalFormat, this.type = t.type, this.offset.copy(t.offset), this.repeat.copy(t.repeat), this.center.copy(t.center), this.rotation = t.rotation, this.matrixAutoUpdate = t.matrixAutoUpdate, this.matrix.copy(t.matrix), this.generateMipmaps = t.generateMipmaps, this.premultiplyAlpha = t.premultiplyAlpha, this.flipY = t.flipY, this.unpackAlignment = t.unpackAlignment, this.colorSpace = t.colorSpace, this.userData = JSON.parse(JSON.stringify(t.userData)), this.needsUpdate = !0, this;
  }
  toJSON(t) {
    const e = t === void 0 || typeof t == "string";
    if (!e && t.textures[this.uuid] !== void 0)
      return t.textures[this.uuid];
    const i = {
      metadata: {
        version: 4.6,
        type: "Texture",
        generator: "Texture.toJSON"
      },
      uuid: this.uuid,
      name: this.name,
      image: this.source.toJSON(t).uuid,
      mapping: this.mapping,
      channel: this.channel,
      repeat: [this.repeat.x, this.repeat.y],
      offset: [this.offset.x, this.offset.y],
      center: [this.center.x, this.center.y],
      rotation: this.rotation,
      wrap: [this.wrapS, this.wrapT],
      format: this.format,
      internalFormat: this.internalFormat,
      type: this.type,
      colorSpace: this.colorSpace,
      minFilter: this.minFilter,
      magFilter: this.magFilter,
      anisotropy: this.anisotropy,
      flipY: this.flipY,
      generateMipmaps: this.generateMipmaps,
      premultiplyAlpha: this.premultiplyAlpha,
      unpackAlignment: this.unpackAlignment
    };
    return Object.keys(this.userData).length > 0 && (i.userData = this.userData), e || (t.textures[this.uuid] = i), i;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  transformUv(t) {
    if (this.mapping !== O_) return t;
    if (t.applyMatrix3(this.matrix), t.x < 0 || t.x > 1)
      switch (this.wrapS) {
        case Eg:
          t.x = t.x - Math.floor(t.x);
          break;
        case Yl:
          t.x = t.x < 0 ? 0 : 1;
          break;
        case Tg:
          Math.abs(Math.floor(t.x) % 2) === 1 ? t.x = Math.ceil(t.x) - t.x : t.x = t.x - Math.floor(t.x);
          break;
      }
    if (t.y < 0 || t.y > 1)
      switch (this.wrapT) {
        case Eg:
          t.y = t.y - Math.floor(t.y);
          break;
        case Yl:
          t.y = t.y < 0 ? 0 : 1;
          break;
        case Tg:
          Math.abs(Math.floor(t.y) % 2) === 1 ? t.y = Math.ceil(t.y) - t.y : t.y = t.y - Math.floor(t.y);
          break;
      }
    return this.flipY && (t.y = 1 - t.y), t;
  }
  set needsUpdate(t) {
    t === !0 && (this.version++, this.source.needsUpdate = !0);
  }
  set needsPMREMUpdate(t) {
    t === !0 && this.pmremVersion++;
  }
};
_f.DEFAULT_IMAGE = null;
_f.DEFAULT_MAPPING = O_;
_f.DEFAULT_ANISOTROPY = 1;
class Pn {
  constructor(t = 0, e = 0, i = 0, n = 1) {
    Pn.prototype.isVector4 = !0, this.x = t, this.y = e, this.z = i, this.w = n;
  }
  get width() {
    return this.z;
  }
  set width(t) {
    this.z = t;
  }
  get height() {
    return this.w;
  }
  set height(t) {
    this.w = t;
  }
  set(t, e, i, n) {
    return this.x = t, this.y = e, this.z = i, this.w = n, this;
  }
  setScalar(t) {
    return this.x = t, this.y = t, this.z = t, this.w = t, this;
  }
  setX(t) {
    return this.x = t, this;
  }
  setY(t) {
    return this.y = t, this;
  }
  setZ(t) {
    return this.z = t, this;
  }
  setW(t) {
    return this.w = t, this;
  }
  setComponent(t, e) {
    switch (t) {
      case 0:
        this.x = e;
        break;
      case 1:
        this.y = e;
        break;
      case 2:
        this.z = e;
        break;
      case 3:
        this.w = e;
        break;
      default:
        throw new Error("index is out of range: " + t);
    }
    return this;
  }
  getComponent(t) {
    switch (t) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      case 3:
        return this.w;
      default:
        throw new Error("index is out of range: " + t);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y, this.z, this.w);
  }
  copy(t) {
    return this.x = t.x, this.y = t.y, this.z = t.z, this.w = t.w !== void 0 ? t.w : 1, this;
  }
  add(t) {
    return this.x += t.x, this.y += t.y, this.z += t.z, this.w += t.w, this;
  }
  addScalar(t) {
    return this.x += t, this.y += t, this.z += t, this.w += t, this;
  }
  addVectors(t, e) {
    return this.x = t.x + e.x, this.y = t.y + e.y, this.z = t.z + e.z, this.w = t.w + e.w, this;
  }
  addScaledVector(t, e) {
    return this.x += t.x * e, this.y += t.y * e, this.z += t.z * e, this.w += t.w * e, this;
  }
  sub(t) {
    return this.x -= t.x, this.y -= t.y, this.z -= t.z, this.w -= t.w, this;
  }
  subScalar(t) {
    return this.x -= t, this.y -= t, this.z -= t, this.w -= t, this;
  }
  subVectors(t, e) {
    return this.x = t.x - e.x, this.y = t.y - e.y, this.z = t.z - e.z, this.w = t.w - e.w, this;
  }
  multiply(t) {
    return this.x *= t.x, this.y *= t.y, this.z *= t.z, this.w *= t.w, this;
  }
  multiplyScalar(t) {
    return this.x *= t, this.y *= t, this.z *= t, this.w *= t, this;
  }
  applyMatrix4(t) {
    const e = this.x, i = this.y, n = this.z, s = this.w, r = t.elements;
    return this.x = r[0] * e + r[4] * i + r[8] * n + r[12] * s, this.y = r[1] * e + r[5] * i + r[9] * n + r[13] * s, this.z = r[2] * e + r[6] * i + r[10] * n + r[14] * s, this.w = r[3] * e + r[7] * i + r[11] * n + r[15] * s, this;
  }
  divide(t) {
    return this.x /= t.x, this.y /= t.y, this.z /= t.z, this.w /= t.w, this;
  }
  divideScalar(t) {
    return this.multiplyScalar(1 / t);
  }
  setAxisAngleFromQuaternion(t) {
    this.w = 2 * Math.acos(t.w);
    const e = Math.sqrt(1 - t.w * t.w);
    return e < 1e-4 ? (this.x = 1, this.y = 0, this.z = 0) : (this.x = t.x / e, this.y = t.y / e, this.z = t.z / e), this;
  }
  setAxisAngleFromRotationMatrix(t) {
    let e, i, n, s;
    const l = t.elements, h = l[0], c = l[4], u = l[8], d = l[1], p = l[5], f = l[9], y = l[2], g = l[6], m = l[10];
    if (Math.abs(c - d) < 0.01 && Math.abs(u - y) < 0.01 && Math.abs(f - g) < 0.01) {
      if (Math.abs(c + d) < 0.1 && Math.abs(u + y) < 0.1 && Math.abs(f + g) < 0.1 && Math.abs(h + p + m - 3) < 0.1)
        return this.set(1, 0, 0, 0), this;
      e = Math.PI;
      const x = (h + 1) / 2, _ = (p + 1) / 2, S = (m + 1) / 2, w = (c + d) / 4, T = (u + y) / 4, R = (f + g) / 4;
      return x > _ && x > S ? x < 0.01 ? (i = 0, n = 0.707106781, s = 0.707106781) : (i = Math.sqrt(x), n = w / i, s = T / i) : _ > S ? _ < 0.01 ? (i = 0.707106781, n = 0, s = 0.707106781) : (n = Math.sqrt(_), i = w / n, s = R / n) : S < 0.01 ? (i = 0.707106781, n = 0.707106781, s = 0) : (s = Math.sqrt(S), i = T / s, n = R / s), this.set(i, n, s, e), this;
    }
    let v = Math.sqrt((g - f) * (g - f) + (u - y) * (u - y) + (d - c) * (d - c));
    return Math.abs(v) < 1e-3 && (v = 1), this.x = (g - f) / v, this.y = (u - y) / v, this.z = (d - c) / v, this.w = Math.acos((h + p + m - 1) / 2), this;
  }
  setFromMatrixPosition(t) {
    const e = t.elements;
    return this.x = e[12], this.y = e[13], this.z = e[14], this.w = e[15], this;
  }
  min(t) {
    return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this.z = Math.min(this.z, t.z), this.w = Math.min(this.w, t.w), this;
  }
  max(t) {
    return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this.z = Math.max(this.z, t.z), this.w = Math.max(this.w, t.w), this;
  }
  clamp(t, e) {
    return this.x = Math.max(t.x, Math.min(e.x, this.x)), this.y = Math.max(t.y, Math.min(e.y, this.y)), this.z = Math.max(t.z, Math.min(e.z, this.z)), this.w = Math.max(t.w, Math.min(e.w, this.w)), this;
  }
  clampScalar(t, e) {
    return this.x = Math.max(t, Math.min(e, this.x)), this.y = Math.max(t, Math.min(e, this.y)), this.z = Math.max(t, Math.min(e, this.z)), this.w = Math.max(t, Math.min(e, this.w)), this;
  }
  clampLength(t, e) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(Math.max(t, Math.min(e, i)));
  }
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this.w = Math.floor(this.w), this;
  }
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this.w = Math.ceil(this.w), this;
  }
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this.w = Math.round(this.w), this;
  }
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this.w = Math.trunc(this.w), this;
  }
  negate() {
    return this.x = -this.x, this.y = -this.y, this.z = -this.z, this.w = -this.w, this;
  }
  dot(t) {
    return this.x * t.x + this.y * t.y + this.z * t.z + this.w * t.w;
  }
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  setLength(t) {
    return this.normalize().multiplyScalar(t);
  }
  lerp(t, e) {
    return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this.z += (t.z - this.z) * e, this.w += (t.w - this.w) * e, this;
  }
  lerpVectors(t, e, i) {
    return this.x = t.x + (e.x - t.x) * i, this.y = t.y + (e.y - t.y) * i, this.z = t.z + (e.z - t.z) * i, this.w = t.w + (e.w - t.w) * i, this;
  }
  equals(t) {
    return t.x === this.x && t.y === this.y && t.z === this.z && t.w === this.w;
  }
  fromArray(t, e = 0) {
    return this.x = t[e], this.y = t[e + 1], this.z = t[e + 2], this.w = t[e + 3], this;
  }
  toArray(t = [], e = 0) {
    return t[e] = this.x, t[e + 1] = this.y, t[e + 2] = this.z, t[e + 3] = this.w, t;
  }
  fromBufferAttribute(t, e) {
    return this.x = t.getX(e), this.y = t.getY(e), this.z = t.getZ(e), this.w = t.getW(e), this;
  }
  random() {
    return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this.w = Math.random(), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y, yield this.z, yield this.w;
  }
}
let qo = class {
  constructor(t = 0, e = 0, i = 0, n = 1) {
    this.isQuaternion = !0, this._x = t, this._y = e, this._z = i, this._w = n;
  }
  static slerpFlat(t, e, i, n, s, r, o) {
    let l = i[n + 0], h = i[n + 1], c = i[n + 2], u = i[n + 3];
    const d = s[r + 0], p = s[r + 1], f = s[r + 2], y = s[r + 3];
    if (o === 0) {
      t[e + 0] = l, t[e + 1] = h, t[e + 2] = c, t[e + 3] = u;
      return;
    }
    if (o === 1) {
      t[e + 0] = d, t[e + 1] = p, t[e + 2] = f, t[e + 3] = y;
      return;
    }
    if (u !== y || l !== d || h !== p || c !== f) {
      let g = 1 - o;
      const m = l * d + h * p + c * f + u * y, v = m >= 0 ? 1 : -1, x = 1 - m * m;
      if (x > Number.EPSILON) {
        const S = Math.sqrt(x), w = Math.atan2(S, m * v);
        g = Math.sin(g * w) / S, o = Math.sin(o * w) / S;
      }
      const _ = o * v;
      if (l = l * g + d * _, h = h * g + p * _, c = c * g + f * _, u = u * g + y * _, g === 1 - o) {
        const S = 1 / Math.sqrt(l * l + h * h + c * c + u * u);
        l *= S, h *= S, c *= S, u *= S;
      }
    }
    t[e] = l, t[e + 1] = h, t[e + 2] = c, t[e + 3] = u;
  }
  static multiplyQuaternionsFlat(t, e, i, n, s, r) {
    const o = i[n], l = i[n + 1], h = i[n + 2], c = i[n + 3], u = s[r], d = s[r + 1], p = s[r + 2], f = s[r + 3];
    return t[e] = o * f + c * u + l * p - h * d, t[e + 1] = l * f + c * d + h * u - o * p, t[e + 2] = h * f + c * p + o * d - l * u, t[e + 3] = c * f - o * u - l * d - h * p, t;
  }
  get x() {
    return this._x;
  }
  set x(t) {
    this._x = t, this._onChangeCallback();
  }
  get y() {
    return this._y;
  }
  set y(t) {
    this._y = t, this._onChangeCallback();
  }
  get z() {
    return this._z;
  }
  set z(t) {
    this._z = t, this._onChangeCallback();
  }
  get w() {
    return this._w;
  }
  set w(t) {
    this._w = t, this._onChangeCallback();
  }
  set(t, e, i, n) {
    return this._x = t, this._y = e, this._z = i, this._w = n, this._onChangeCallback(), this;
  }
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._w);
  }
  copy(t) {
    return this._x = t.x, this._y = t.y, this._z = t.z, this._w = t.w, this._onChangeCallback(), this;
  }
  setFromEuler(t, e = !0) {
    const i = t._x, n = t._y, s = t._z, r = t._order, o = Math.cos, l = Math.sin, h = o(i / 2), c = o(n / 2), u = o(s / 2), d = l(i / 2), p = l(n / 2), f = l(s / 2);
    switch (r) {
      case "XYZ":
        this._x = d * c * u + h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "YXZ":
        this._x = d * c * u + h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u + d * p * f;
        break;
      case "ZXY":
        this._x = d * c * u - h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "ZYX":
        this._x = d * c * u - h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u + d * p * f;
        break;
      case "YZX":
        this._x = d * c * u + h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "XZY":
        this._x = d * c * u - h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u + d * p * f;
        break;
      default:
        console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + r);
    }
    return e === !0 && this._onChangeCallback(), this;
  }
  setFromAxisAngle(t, e) {
    const i = e / 2, n = Math.sin(i);
    return this._x = t.x * n, this._y = t.y * n, this._z = t.z * n, this._w = Math.cos(i), this._onChangeCallback(), this;
  }
  setFromRotationMatrix(t) {
    const e = t.elements, i = e[0], n = e[4], s = e[8], r = e[1], o = e[5], l = e[9], h = e[2], c = e[6], u = e[10], d = i + o + u;
    if (d > 0) {
      const p = 0.5 / Math.sqrt(d + 1);
      this._w = 0.25 / p, this._x = (c - l) * p, this._y = (s - h) * p, this._z = (r - n) * p;
    } else if (i > o && i > u) {
      const p = 2 * Math.sqrt(1 + i - o - u);
      this._w = (c - l) / p, this._x = 0.25 * p, this._y = (n + r) / p, this._z = (s + h) / p;
    } else if (o > u) {
      const p = 2 * Math.sqrt(1 + o - i - u);
      this._w = (s - h) / p, this._x = (n + r) / p, this._y = 0.25 * p, this._z = (l + c) / p;
    } else {
      const p = 2 * Math.sqrt(1 + u - i - o);
      this._w = (r - n) / p, this._x = (s + h) / p, this._y = (l + c) / p, this._z = 0.25 * p;
    }
    return this._onChangeCallback(), this;
  }
  setFromUnitVectors(t, e) {
    let i = t.dot(e) + 1;
    return i < Number.EPSILON ? (i = 0, Math.abs(t.x) > Math.abs(t.z) ? (this._x = -t.y, this._y = t.x, this._z = 0, this._w = i) : (this._x = 0, this._y = -t.z, this._z = t.y, this._w = i)) : (this._x = t.y * e.z - t.z * e.y, this._y = t.z * e.x - t.x * e.z, this._z = t.x * e.y - t.y * e.x, this._w = i), this.normalize();
  }
  angleTo(t) {
    return 2 * Math.acos(Math.abs(ai(this.dot(t), -1, 1)));
  }
  rotateTowards(t, e) {
    const i = this.angleTo(t);
    if (i === 0) return this;
    const n = Math.min(1, e / i);
    return this.slerp(t, n), this;
  }
  identity() {
    return this.set(0, 0, 0, 1);
  }
  invert() {
    return this.conjugate();
  }
  conjugate() {
    return this._x *= -1, this._y *= -1, this._z *= -1, this._onChangeCallback(), this;
  }
  dot(t) {
    return this._x * t._x + this._y * t._y + this._z * t._z + this._w * t._w;
  }
  lengthSq() {
    return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  }
  length() {
    return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  }
  normalize() {
    let t = this.length();
    return t === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (t = 1 / t, this._x = this._x * t, this._y = this._y * t, this._z = this._z * t, this._w = this._w * t), this._onChangeCallback(), this;
  }
  multiply(t) {
    return this.multiplyQuaternions(this, t);
  }
  premultiply(t) {
    return this.multiplyQuaternions(t, this);
  }
  multiplyQuaternions(t, e) {
    const i = t._x, n = t._y, s = t._z, r = t._w, o = e._x, l = e._y, h = e._z, c = e._w;
    return this._x = i * c + r * o + n * h - s * l, this._y = n * c + r * l + s * o - i * h, this._z = s * c + r * h + i * l - n * o, this._w = r * c - i * o - n * l - s * h, this._onChangeCallback(), this;
  }
  slerp(t, e) {
    if (e === 0) return this;
    if (e === 1) return this.copy(t);
    const i = this._x, n = this._y, s = this._z, r = this._w;
    let o = r * t._w + i * t._x + n * t._y + s * t._z;
    if (o < 0 ? (this._w = -t._w, this._x = -t._x, this._y = -t._y, this._z = -t._z, o = -o) : this.copy(t), o >= 1)
      return this._w = r, this._x = i, this._y = n, this._z = s, this;
    const l = 1 - o * o;
    if (l <= Number.EPSILON) {
      const p = 1 - e;
      return this._w = p * r + e * this._w, this._x = p * i + e * this._x, this._y = p * n + e * this._y, this._z = p * s + e * this._z, this.normalize(), this;
    }
    const h = Math.sqrt(l), c = Math.atan2(h, o), u = Math.sin((1 - e) * c) / h, d = Math.sin(e * c) / h;
    return this._w = r * u + this._w * d, this._x = i * u + this._x * d, this._y = n * u + this._y * d, this._z = s * u + this._z * d, this._onChangeCallback(), this;
  }
  slerpQuaternions(t, e, i) {
    return this.copy(t).slerp(e, i);
  }
  random() {
    const t = 2 * Math.PI * Math.random(), e = 2 * Math.PI * Math.random(), i = Math.random(), n = Math.sqrt(1 - i), s = Math.sqrt(i);
    return this.set(
      n * Math.sin(t),
      n * Math.cos(t),
      s * Math.sin(e),
      s * Math.cos(e)
    );
  }
  equals(t) {
    return t._x === this._x && t._y === this._y && t._z === this._z && t._w === this._w;
  }
  fromArray(t, e = 0) {
    return this._x = t[e], this._y = t[e + 1], this._z = t[e + 2], this._w = t[e + 3], this._onChangeCallback(), this;
  }
  toArray(t = [], e = 0) {
    return t[e] = this._x, t[e + 1] = this._y, t[e + 2] = this._z, t[e + 3] = this._w, t;
  }
  fromBufferAttribute(t, e) {
    return this._x = t.getX(e), this._y = t.getY(e), this._z = t.getZ(e), this._w = t.getW(e), this._onChangeCallback(), this;
  }
  toJSON() {
    return this.toArray();
  }
  _onChange(t) {
    return this._onChangeCallback = t, this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x, yield this._y, yield this._z, yield this._w;
  }
}, tt = class X_ {
  constructor(t = 0, e = 0, i = 0) {
    X_.prototype.isVector3 = !0, this.x = t, this.y = e, this.z = i;
  }
  set(t, e, i) {
    return i === void 0 && (i = this.z), this.x = t, this.y = e, this.z = i, this;
  }
  setScalar(t) {
    return this.x = t, this.y = t, this.z = t, this;
  }
  setX(t) {
    return this.x = t, this;
  }
  setY(t) {
    return this.y = t, this;
  }
  setZ(t) {
    return this.z = t, this;
  }
  setComponent(t, e) {
    switch (t) {
      case 0:
        this.x = e;
        break;
      case 1:
        this.y = e;
        break;
      case 2:
        this.z = e;
        break;
      default:
        throw new Error("index is out of range: " + t);
    }
    return this;
  }
  getComponent(t) {
    switch (t) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      default:
        throw new Error("index is out of range: " + t);
    }
  }
  clone() {
    return new this.constructor(this.x, this.y, this.z);
  }
  copy(t) {
    return this.x = t.x, this.y = t.y, this.z = t.z, this;
  }
  add(t) {
    return this.x += t.x, this.y += t.y, this.z += t.z, this;
  }
  addScalar(t) {
    return this.x += t, this.y += t, this.z += t, this;
  }
  addVectors(t, e) {
    return this.x = t.x + e.x, this.y = t.y + e.y, this.z = t.z + e.z, this;
  }
  addScaledVector(t, e) {
    return this.x += t.x * e, this.y += t.y * e, this.z += t.z * e, this;
  }
  sub(t) {
    return this.x -= t.x, this.y -= t.y, this.z -= t.z, this;
  }
  subScalar(t) {
    return this.x -= t, this.y -= t, this.z -= t, this;
  }
  subVectors(t, e) {
    return this.x = t.x - e.x, this.y = t.y - e.y, this.z = t.z - e.z, this;
  }
  multiply(t) {
    return this.x *= t.x, this.y *= t.y, this.z *= t.z, this;
  }
  multiplyScalar(t) {
    return this.x *= t, this.y *= t, this.z *= t, this;
  }
  multiplyVectors(t, e) {
    return this.x = t.x * e.x, this.y = t.y * e.y, this.z = t.z * e.z, this;
  }
  applyEuler(t) {
    return this.applyQuaternion(Bg.setFromEuler(t));
  }
  applyAxisAngle(t, e) {
    return this.applyQuaternion(Bg.setFromAxisAngle(t, e));
  }
  applyMatrix3(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements;
    return this.x = s[0] * e + s[3] * i + s[6] * n, this.y = s[1] * e + s[4] * i + s[7] * n, this.z = s[2] * e + s[5] * i + s[8] * n, this;
  }
  applyNormalMatrix(t) {
    return this.applyMatrix3(t).normalize();
  }
  applyMatrix4(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements, r = 1 / (s[3] * e + s[7] * i + s[11] * n + s[15]);
    return this.x = (s[0] * e + s[4] * i + s[8] * n + s[12]) * r, this.y = (s[1] * e + s[5] * i + s[9] * n + s[13]) * r, this.z = (s[2] * e + s[6] * i + s[10] * n + s[14]) * r, this;
  }
  applyQuaternion(t) {
    const e = this.x, i = this.y, n = this.z, s = t.x, r = t.y, o = t.z, l = t.w, h = 2 * (r * n - o * i), c = 2 * (o * e - s * n), u = 2 * (s * i - r * e);
    return this.x = e + l * h + r * u - o * c, this.y = i + l * c + o * h - s * u, this.z = n + l * u + s * c - r * h, this;
  }
  project(t) {
    return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix);
  }
  unproject(t) {
    return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld);
  }
  transformDirection(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements;
    return this.x = s[0] * e + s[4] * i + s[8] * n, this.y = s[1] * e + s[5] * i + s[9] * n, this.z = s[2] * e + s[6] * i + s[10] * n, this.normalize();
  }
  divide(t) {
    return this.x /= t.x, this.y /= t.y, this.z /= t.z, this;
  }
  divideScalar(t) {
    return this.multiplyScalar(1 / t);
  }
  min(t) {
    return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this.z = Math.min(this.z, t.z), this;
  }
  max(t) {
    return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this.z = Math.max(this.z, t.z), this;
  }
  clamp(t, e) {
    return this.x = Math.max(t.x, Math.min(e.x, this.x)), this.y = Math.max(t.y, Math.min(e.y, this.y)), this.z = Math.max(t.z, Math.min(e.z, this.z)), this;
  }
  clampScalar(t, e) {
    return this.x = Math.max(t, Math.min(e, this.x)), this.y = Math.max(t, Math.min(e, this.y)), this.z = Math.max(t, Math.min(e, this.z)), this;
  }
  clampLength(t, e) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(Math.max(t, Math.min(e, i)));
  }
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this;
  }
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this;
  }
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this;
  }
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this;
  }
  negate() {
    return this.x = -this.x, this.y = -this.y, this.z = -this.z, this;
  }
  dot(t) {
    return this.x * t.x + this.y * t.y + this.z * t.z;
  }
  // TODO lengthSquared?
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z;
  }
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  }
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  }
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  setLength(t) {
    return this.normalize().multiplyScalar(t);
  }
  lerp(t, e) {
    return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this.z += (t.z - this.z) * e, this;
  }
  lerpVectors(t, e, i) {
    return this.x = t.x + (e.x - t.x) * i, this.y = t.y + (e.y - t.y) * i, this.z = t.z + (e.z - t.z) * i, this;
  }
  cross(t) {
    return this.crossVectors(this, t);
  }
  crossVectors(t, e) {
    const i = t.x, n = t.y, s = t.z, r = e.x, o = e.y, l = e.z;
    return this.x = n * l - s * o, this.y = s * r - i * l, this.z = i * o - n * r, this;
  }
  projectOnVector(t) {
    const e = t.lengthSq();
    if (e === 0) return this.set(0, 0, 0);
    const i = t.dot(this) / e;
    return this.copy(t).multiplyScalar(i);
  }
  projectOnPlane(t) {
    return xd.copy(this).projectOnVector(t), this.sub(xd);
  }
  reflect(t) {
    return this.sub(xd.copy(t).multiplyScalar(2 * this.dot(t)));
  }
  angleTo(t) {
    const e = Math.sqrt(this.lengthSq() * t.lengthSq());
    if (e === 0) return Math.PI / 2;
    const i = this.dot(t) / e;
    return Math.acos(ai(i, -1, 1));
  }
  distanceTo(t) {
    return Math.sqrt(this.distanceToSquared(t));
  }
  distanceToSquared(t) {
    const e = this.x - t.x, i = this.y - t.y, n = this.z - t.z;
    return e * e + i * i + n * n;
  }
  manhattanDistanceTo(t) {
    return Math.abs(this.x - t.x) + Math.abs(this.y - t.y) + Math.abs(this.z - t.z);
  }
  setFromSpherical(t) {
    return this.setFromSphericalCoords(t.radius, t.phi, t.theta);
  }
  setFromSphericalCoords(t, e, i) {
    const n = Math.sin(e) * t;
    return this.x = n * Math.sin(i), this.y = Math.cos(e) * t, this.z = n * Math.cos(i), this;
  }
  setFromCylindrical(t) {
    return this.setFromCylindricalCoords(t.radius, t.theta, t.y);
  }
  setFromCylindricalCoords(t, e, i) {
    return this.x = t * Math.sin(e), this.y = i, this.z = t * Math.cos(e), this;
  }
  setFromMatrixPosition(t) {
    const e = t.elements;
    return this.x = e[12], this.y = e[13], this.z = e[14], this;
  }
  setFromMatrixScale(t) {
    const e = this.setFromMatrixColumn(t, 0).length(), i = this.setFromMatrixColumn(t, 1).length(), n = this.setFromMatrixColumn(t, 2).length();
    return this.x = e, this.y = i, this.z = n, this;
  }
  setFromMatrixColumn(t, e) {
    return this.fromArray(t.elements, e * 4);
  }
  setFromMatrix3Column(t, e) {
    return this.fromArray(t.elements, e * 3);
  }
  setFromEuler(t) {
    return this.x = t._x, this.y = t._y, this.z = t._z, this;
  }
  setFromColor(t) {
    return this.x = t.r, this.y = t.g, this.z = t.b, this;
  }
  equals(t) {
    return t.x === this.x && t.y === this.y && t.z === this.z;
  }
  fromArray(t, e = 0) {
    return this.x = t[e], this.y = t[e + 1], this.z = t[e + 2], this;
  }
  toArray(t = [], e = 0) {
    return t[e] = this.x, t[e + 1] = this.y, t[e + 2] = this.z, t;
  }
  fromBufferAttribute(t, e) {
    return this.x = t.getX(e), this.y = t.getY(e), this.z = t.getZ(e), this;
  }
  random() {
    return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this;
  }
  randomDirection() {
    const t = Math.random() * Math.PI * 2, e = Math.random() * 2 - 1, i = Math.sqrt(1 - e * e);
    return this.x = i * Math.cos(t), this.y = e, this.z = i * Math.sin(t), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y, yield this.z;
  }
};
const xd = /* @__PURE__ */ new tt(), Bg = /* @__PURE__ */ new qo();
class Us {
  constructor(t = new tt(1 / 0, 1 / 0, 1 / 0), e = new tt(-1 / 0, -1 / 0, -1 / 0)) {
    this.isBox3 = !0, this.min = t, this.max = e;
  }
  set(t, e) {
    return this.min.copy(t), this.max.copy(e), this;
  }
  setFromArray(t) {
    this.makeEmpty();
    for (let e = 0, i = t.length; e < i; e += 3)
      this.expandByPoint(tn.fromArray(t, e));
    return this;
  }
  setFromBufferAttribute(t) {
    this.makeEmpty();
    for (let e = 0, i = t.count; e < i; e++)
      this.expandByPoint(tn.fromBufferAttribute(t, e));
    return this;
  }
  setFromPoints(t) {
    this.makeEmpty();
    for (let e = 0, i = t.length; e < i; e++)
      this.expandByPoint(t[e]);
    return this;
  }
  setFromCenterAndSize(t, e) {
    const i = tn.copy(e).multiplyScalar(0.5);
    return this.min.copy(t).sub(i), this.max.copy(t).add(i), this;
  }
  setFromObject(t, e = !1) {
    return this.makeEmpty(), this.expandByObject(t, e);
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(t) {
    return this.min.copy(t.min), this.max.copy(t.max), this;
  }
  makeEmpty() {
    return this.min.x = this.min.y = this.min.z = 1 / 0, this.max.x = this.max.y = this.max.z = -1 / 0, this;
  }
  isEmpty() {
    return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  }
  getCenter(t) {
    return this.isEmpty() ? t.set(0, 0, 0) : t.addVectors(this.min, this.max).multiplyScalar(0.5);
  }
  getSize(t) {
    return this.isEmpty() ? t.set(0, 0, 0) : t.subVectors(this.max, this.min);
  }
  expandByPoint(t) {
    return this.min.min(t), this.max.max(t), this;
  }
  expandByVector(t) {
    return this.min.sub(t), this.max.add(t), this;
  }
  expandByScalar(t) {
    return this.min.addScalar(-t), this.max.addScalar(t), this;
  }
  expandByObject(t, e = !1) {
    t.updateWorldMatrix(!1, !1);
    const i = t.geometry;
    if (i !== void 0) {
      const s = i.getAttribute("position");
      if (e === !0 && s !== void 0 && t.isInstancedMesh !== !0)
        for (let r = 0, o = s.count; r < o; r++)
          t.isMesh === !0 ? t.getVertexPosition(r, tn) : tn.fromBufferAttribute(s, r), tn.applyMatrix4(t.matrixWorld), this.expandByPoint(tn);
      else
        t.boundingBox !== void 0 ? (t.boundingBox === null && t.computeBoundingBox(), jl.copy(t.boundingBox)) : (i.boundingBox === null && i.computeBoundingBox(), jl.copy(i.boundingBox)), jl.applyMatrix4(t.matrixWorld), this.union(jl);
    }
    const n = t.children;
    for (let s = 0, r = n.length; s < r; s++)
      this.expandByObject(n[s], e);
    return this;
  }
  containsPoint(t) {
    return t.x >= this.min.x && t.x <= this.max.x && t.y >= this.min.y && t.y <= this.max.y && t.z >= this.min.z && t.z <= this.max.z;
  }
  containsBox(t) {
    return this.min.x <= t.min.x && t.max.x <= this.max.x && this.min.y <= t.min.y && t.max.y <= this.max.y && this.min.z <= t.min.z && t.max.z <= this.max.z;
  }
  getParameter(t, e) {
    return e.set(
      (t.x - this.min.x) / (this.max.x - this.min.x),
      (t.y - this.min.y) / (this.max.y - this.min.y),
      (t.z - this.min.z) / (this.max.z - this.min.z)
    );
  }
  intersectsBox(t) {
    return t.max.x >= this.min.x && t.min.x <= this.max.x && t.max.y >= this.min.y && t.min.y <= this.max.y && t.max.z >= this.min.z && t.min.z <= this.max.z;
  }
  intersectsSphere(t) {
    return this.clampPoint(t.center, tn), tn.distanceToSquared(t.center) <= t.radius * t.radius;
  }
  intersectsPlane(t) {
    let e, i;
    return t.normal.x > 0 ? (e = t.normal.x * this.min.x, i = t.normal.x * this.max.x) : (e = t.normal.x * this.max.x, i = t.normal.x * this.min.x), t.normal.y > 0 ? (e += t.normal.y * this.min.y, i += t.normal.y * this.max.y) : (e += t.normal.y * this.max.y, i += t.normal.y * this.min.y), t.normal.z > 0 ? (e += t.normal.z * this.min.z, i += t.normal.z * this.max.z) : (e += t.normal.z * this.max.z, i += t.normal.z * this.min.z), e <= -t.constant && i >= -t.constant;
  }
  intersectsTriangle(t) {
    if (this.isEmpty())
      return !1;
    this.getCenter(Ka), Jl.subVectors(this.max, Ka), Gr.subVectors(t.a, Ka), Wr.subVectors(t.b, Ka), qr.subVectors(t.c, Ka), ds.subVectors(Wr, Gr), ps.subVectors(qr, Wr), Ks.subVectors(Gr, qr);
    let e = [
      0,
      -ds.z,
      ds.y,
      0,
      -ps.z,
      ps.y,
      0,
      -Ks.z,
      Ks.y,
      ds.z,
      0,
      -ds.x,
      ps.z,
      0,
      -ps.x,
      Ks.z,
      0,
      -Ks.x,
      -ds.y,
      ds.x,
      0,
      -ps.y,
      ps.x,
      0,
      -Ks.y,
      Ks.x,
      0
    ];
    return !vd(e, Gr, Wr, qr, Jl) || (e = [1, 0, 0, 0, 1, 0, 0, 0, 1], !vd(e, Gr, Wr, qr, Jl)) ? !1 : (Kl.crossVectors(ds, ps), e = [Kl.x, Kl.y, Kl.z], vd(e, Gr, Wr, qr, Jl));
  }
  clampPoint(t, e) {
    return e.copy(t).clamp(this.min, this.max);
  }
  distanceToPoint(t) {
    return this.clampPoint(t, tn).distanceTo(t);
  }
  getBoundingSphere(t) {
    return this.isEmpty() ? t.makeEmpty() : (this.getCenter(t.center), t.radius = this.getSize(tn).length() * 0.5), t;
  }
  intersect(t) {
    return this.min.max(t.min), this.max.min(t.max), this.isEmpty() && this.makeEmpty(), this;
  }
  union(t) {
    return this.min.min(t.min), this.max.max(t.max), this;
  }
  applyMatrix4(t) {
    return this.isEmpty() ? this : (On[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(t), On[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(t), On[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(t), On[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(t), On[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(t), On[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(t), On[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(t), On[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(t), this.setFromPoints(On), this);
  }
  translate(t) {
    return this.min.add(t), this.max.add(t), this;
  }
  equals(t) {
    return t.min.equals(this.min) && t.max.equals(this.max);
  }
}
const On = [
  /* @__PURE__ */ new tt(),
  /* @__PURE__ */ new tt(),
  /* @__PURE__ */ new tt(),
  /* @__PURE__ */ new tt(),
  /* @__PURE__ */ new tt(),
  /* @__PURE__ */ new tt(),
  /* @__PURE__ */ new tt(),
  /* @__PURE__ */ new tt()
], tn = /* @__PURE__ */ new tt(), jl = /* @__PURE__ */ new Us(), Gr = /* @__PURE__ */ new tt(), Wr = /* @__PURE__ */ new tt(), qr = /* @__PURE__ */ new tt(), ds = /* @__PURE__ */ new tt(), ps = /* @__PURE__ */ new tt(), Ks = /* @__PURE__ */ new tt(), Ka = /* @__PURE__ */ new tt(), Jl = /* @__PURE__ */ new tt(), Kl = /* @__PURE__ */ new tt(), Qs = /* @__PURE__ */ new tt();
function vd(a, t, e, i, n) {
  for (let s = 0, r = a.length - 3; s <= r; s += 3) {
    Qs.fromArray(a, s);
    const o = n.x * Math.abs(Qs.x) + n.y * Math.abs(Qs.y) + n.z * Math.abs(Qs.z), l = t.dot(Qs), h = e.dot(Qs), c = i.dot(Qs);
    if (Math.max(-Math.max(l, h, c), Math.min(l, h, c)) > o)
      return !1;
  }
  return !0;
}
const kT = /* @__PURE__ */ new Us(), Qa = /* @__PURE__ */ new tt(), bd = /* @__PURE__ */ new tt();
class uu {
  constructor(t = new tt(), e = -1) {
    this.isSphere = !0, this.center = t, this.radius = e;
  }
  set(t, e) {
    return this.center.copy(t), this.radius = e, this;
  }
  setFromPoints(t, e) {
    const i = this.center;
    e !== void 0 ? i.copy(e) : kT.setFromPoints(t).getCenter(i);
    let n = 0;
    for (let s = 0, r = t.length; s < r; s++)
      n = Math.max(n, i.distanceToSquared(t[s]));
    return this.radius = Math.sqrt(n), this;
  }
  copy(t) {
    return this.center.copy(t.center), this.radius = t.radius, this;
  }
  isEmpty() {
    return this.radius < 0;
  }
  makeEmpty() {
    return this.center.set(0, 0, 0), this.radius = -1, this;
  }
  containsPoint(t) {
    return t.distanceToSquared(this.center) <= this.radius * this.radius;
  }
  distanceToPoint(t) {
    return t.distanceTo(this.center) - this.radius;
  }
  intersectsSphere(t) {
    const e = this.radius + t.radius;
    return t.center.distanceToSquared(this.center) <= e * e;
  }
  intersectsBox(t) {
    return t.intersectsSphere(this);
  }
  intersectsPlane(t) {
    return Math.abs(t.distanceToPoint(this.center)) <= this.radius;
  }
  clampPoint(t, e) {
    const i = this.center.distanceToSquared(t);
    return e.copy(t), i > this.radius * this.radius && (e.sub(this.center).normalize(), e.multiplyScalar(this.radius).add(this.center)), e;
  }
  getBoundingBox(t) {
    return this.isEmpty() ? (t.makeEmpty(), t) : (t.set(this.center, this.center), t.expandByScalar(this.radius), t);
  }
  applyMatrix4(t) {
    return this.center.applyMatrix4(t), this.radius = this.radius * t.getMaxScaleOnAxis(), this;
  }
  translate(t) {
    return this.center.add(t), this;
  }
  expandByPoint(t) {
    if (this.isEmpty())
      return this.center.copy(t), this.radius = 0, this;
    Qa.subVectors(t, this.center);
    const e = Qa.lengthSq();
    if (e > this.radius * this.radius) {
      const i = Math.sqrt(e), n = (i - this.radius) * 0.5;
      this.center.addScaledVector(Qa, n / i), this.radius += n;
    }
    return this;
  }
  union(t) {
    return t.isEmpty() ? this : this.isEmpty() ? (this.copy(t), this) : (this.center.equals(t.center) === !0 ? this.radius = Math.max(this.radius, t.radius) : (bd.subVectors(t.center, this.center).setLength(t.radius), this.expandByPoint(Qa.copy(t.center).add(bd)), this.expandByPoint(Qa.copy(t.center).sub(bd))), this);
  }
  equals(t) {
    return t.center.equals(this.center) && t.radius === this.radius;
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
const kn = /* @__PURE__ */ new tt(), Md = /* @__PURE__ */ new tt(), Ql = /* @__PURE__ */ new tt(), fs = /* @__PURE__ */ new tt(), Sd = /* @__PURE__ */ new tt(), th = /* @__PURE__ */ new tt(), wd = /* @__PURE__ */ new tt();
class VT {
  constructor(t = new tt(), e = new tt(0, 0, -1)) {
    this.origin = t, this.direction = e;
  }
  set(t, e) {
    return this.origin.copy(t), this.direction.copy(e), this;
  }
  copy(t) {
    return this.origin.copy(t.origin), this.direction.copy(t.direction), this;
  }
  at(t, e) {
    return e.copy(this.origin).addScaledVector(this.direction, t);
  }
  lookAt(t) {
    return this.direction.copy(t).sub(this.origin).normalize(), this;
  }
  recast(t) {
    return this.origin.copy(this.at(t, kn)), this;
  }
  closestPointToPoint(t, e) {
    e.subVectors(t, this.origin);
    const i = e.dot(this.direction);
    return i < 0 ? e.copy(this.origin) : e.copy(this.origin).addScaledVector(this.direction, i);
  }
  distanceToPoint(t) {
    return Math.sqrt(this.distanceSqToPoint(t));
  }
  distanceSqToPoint(t) {
    const e = kn.subVectors(t, this.origin).dot(this.direction);
    return e < 0 ? this.origin.distanceToSquared(t) : (kn.copy(this.origin).addScaledVector(this.direction, e), kn.distanceToSquared(t));
  }
  distanceSqToSegment(t, e, i, n) {
    Md.copy(t).add(e).multiplyScalar(0.5), Ql.copy(e).sub(t).normalize(), fs.copy(this.origin).sub(Md);
    const s = t.distanceTo(e) * 0.5, r = -this.direction.dot(Ql), o = fs.dot(this.direction), l = -fs.dot(Ql), h = fs.lengthSq(), c = Math.abs(1 - r * r);
    let u, d, p, f;
    if (c > 0)
      if (u = r * l - o, d = r * o - l, f = s * c, u >= 0)
        if (d >= -f)
          if (d <= f) {
            const y = 1 / c;
            u *= y, d *= y, p = u * (u + r * d + 2 * o) + d * (r * u + d + 2 * l) + h;
          } else
            d = s, u = Math.max(0, -(r * d + o)), p = -u * u + d * (d + 2 * l) + h;
        else
          d = -s, u = Math.max(0, -(r * d + o)), p = -u * u + d * (d + 2 * l) + h;
      else
        d <= -f ? (u = Math.max(0, -(-r * s + o)), d = u > 0 ? -s : Math.min(Math.max(-s, -l), s), p = -u * u + d * (d + 2 * l) + h) : d <= f ? (u = 0, d = Math.min(Math.max(-s, -l), s), p = d * (d + 2 * l) + h) : (u = Math.max(0, -(r * s + o)), d = u > 0 ? s : Math.min(Math.max(-s, -l), s), p = -u * u + d * (d + 2 * l) + h);
    else
      d = r > 0 ? -s : s, u = Math.max(0, -(r * d + o)), p = -u * u + d * (d + 2 * l) + h;
    return i && i.copy(this.origin).addScaledVector(this.direction, u), n && n.copy(Md).addScaledVector(Ql, d), p;
  }
  intersectSphere(t, e) {
    kn.subVectors(t.center, this.origin);
    const i = kn.dot(this.direction), n = kn.dot(kn) - i * i, s = t.radius * t.radius;
    if (n > s) return null;
    const r = Math.sqrt(s - n), o = i - r, l = i + r;
    return l < 0 ? null : o < 0 ? this.at(l, e) : this.at(o, e);
  }
  intersectsSphere(t) {
    return this.distanceSqToPoint(t.center) <= t.radius * t.radius;
  }
  distanceToPlane(t) {
    const e = t.normal.dot(this.direction);
    if (e === 0)
      return t.distanceToPoint(this.origin) === 0 ? 0 : null;
    const i = -(this.origin.dot(t.normal) + t.constant) / e;
    return i >= 0 ? i : null;
  }
  intersectPlane(t, e) {
    const i = this.distanceToPlane(t);
    return i === null ? null : this.at(i, e);
  }
  intersectsPlane(t) {
    const e = t.distanceToPoint(this.origin);
    return e === 0 || t.normal.dot(this.direction) * e < 0;
  }
  intersectBox(t, e) {
    let i, n, s, r, o, l;
    const h = 1 / this.direction.x, c = 1 / this.direction.y, u = 1 / this.direction.z, d = this.origin;
    return h >= 0 ? (i = (t.min.x - d.x) * h, n = (t.max.x - d.x) * h) : (i = (t.max.x - d.x) * h, n = (t.min.x - d.x) * h), c >= 0 ? (s = (t.min.y - d.y) * c, r = (t.max.y - d.y) * c) : (s = (t.max.y - d.y) * c, r = (t.min.y - d.y) * c), i > r || s > n || ((s > i || isNaN(i)) && (i = s), (r < n || isNaN(n)) && (n = r), u >= 0 ? (o = (t.min.z - d.z) * u, l = (t.max.z - d.z) * u) : (o = (t.max.z - d.z) * u, l = (t.min.z - d.z) * u), i > l || o > n) || ((o > i || i !== i) && (i = o), (l < n || n !== n) && (n = l), n < 0) ? null : this.at(i >= 0 ? i : n, e);
  }
  intersectsBox(t) {
    return this.intersectBox(t, kn) !== null;
  }
  intersectTriangle(t, e, i, n, s) {
    Sd.subVectors(e, t), th.subVectors(i, t), wd.crossVectors(Sd, th);
    let r = this.direction.dot(wd), o;
    if (r > 0) {
      if (n) return null;
      o = 1;
    } else if (r < 0)
      o = -1, r = -r;
    else
      return null;
    fs.subVectors(this.origin, t);
    const l = o * this.direction.dot(th.crossVectors(fs, th));
    if (l < 0)
      return null;
    const h = o * this.direction.dot(Sd.cross(fs));
    if (h < 0 || l + h > r)
      return null;
    const c = -o * fs.dot(wd);
    return c < 0 ? null : this.at(c / r, s);
  }
  applyMatrix4(t) {
    return this.origin.applyMatrix4(t), this.direction.transformDirection(t), this;
  }
  equals(t) {
    return t.origin.equals(this.origin) && t.direction.equals(this.direction);
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
let Qn = class vp {
  constructor(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g) {
    vp.prototype.isMatrix4 = !0, this.elements = [
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ], t !== void 0 && this.set(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g);
  }
  set(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g) {
    const m = this.elements;
    return m[0] = t, m[4] = e, m[8] = i, m[12] = n, m[1] = s, m[5] = r, m[9] = o, m[13] = l, m[2] = h, m[6] = c, m[10] = u, m[14] = d, m[3] = p, m[7] = f, m[11] = y, m[15] = g, this;
  }
  identity() {
    return this.set(
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  clone() {
    return new vp().fromArray(this.elements);
  }
  copy(t) {
    const e = this.elements, i = t.elements;
    return e[0] = i[0], e[1] = i[1], e[2] = i[2], e[3] = i[3], e[4] = i[4], e[5] = i[5], e[6] = i[6], e[7] = i[7], e[8] = i[8], e[9] = i[9], e[10] = i[10], e[11] = i[11], e[12] = i[12], e[13] = i[13], e[14] = i[14], e[15] = i[15], this;
  }
  copyPosition(t) {
    const e = this.elements, i = t.elements;
    return e[12] = i[12], e[13] = i[13], e[14] = i[14], this;
  }
  setFromMatrix3(t) {
    const e = t.elements;
    return this.set(
      e[0],
      e[3],
      e[6],
      0,
      e[1],
      e[4],
      e[7],
      0,
      e[2],
      e[5],
      e[8],
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  extractBasis(t, e, i) {
    return t.setFromMatrixColumn(this, 0), e.setFromMatrixColumn(this, 1), i.setFromMatrixColumn(this, 2), this;
  }
  makeBasis(t, e, i) {
    return this.set(
      t.x,
      e.x,
      i.x,
      0,
      t.y,
      e.y,
      i.y,
      0,
      t.z,
      e.z,
      i.z,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  extractRotation(t) {
    const e = this.elements, i = t.elements, n = 1 / $r.setFromMatrixColumn(t, 0).length(), s = 1 / $r.setFromMatrixColumn(t, 1).length(), r = 1 / $r.setFromMatrixColumn(t, 2).length();
    return e[0] = i[0] * n, e[1] = i[1] * n, e[2] = i[2] * n, e[3] = 0, e[4] = i[4] * s, e[5] = i[5] * s, e[6] = i[6] * s, e[7] = 0, e[8] = i[8] * r, e[9] = i[9] * r, e[10] = i[10] * r, e[11] = 0, e[12] = 0, e[13] = 0, e[14] = 0, e[15] = 1, this;
  }
  makeRotationFromEuler(t) {
    const e = this.elements, i = t.x, n = t.y, s = t.z, r = Math.cos(i), o = Math.sin(i), l = Math.cos(n), h = Math.sin(n), c = Math.cos(s), u = Math.sin(s);
    if (t.order === "XYZ") {
      const d = r * c, p = r * u, f = o * c, y = o * u;
      e[0] = l * c, e[4] = -l * u, e[8] = h, e[1] = p + f * h, e[5] = d - y * h, e[9] = -o * l, e[2] = y - d * h, e[6] = f + p * h, e[10] = r * l;
    } else if (t.order === "YXZ") {
      const d = l * c, p = l * u, f = h * c, y = h * u;
      e[0] = d + y * o, e[4] = f * o - p, e[8] = r * h, e[1] = r * u, e[5] = r * c, e[9] = -o, e[2] = p * o - f, e[6] = y + d * o, e[10] = r * l;
    } else if (t.order === "ZXY") {
      const d = l * c, p = l * u, f = h * c, y = h * u;
      e[0] = d - y * o, e[4] = -r * u, e[8] = f + p * o, e[1] = p + f * o, e[5] = r * c, e[9] = y - d * o, e[2] = -r * h, e[6] = o, e[10] = r * l;
    } else if (t.order === "ZYX") {
      const d = r * c, p = r * u, f = o * c, y = o * u;
      e[0] = l * c, e[4] = f * h - p, e[8] = d * h + y, e[1] = l * u, e[5] = y * h + d, e[9] = p * h - f, e[2] = -h, e[6] = o * l, e[10] = r * l;
    } else if (t.order === "YZX") {
      const d = r * l, p = r * h, f = o * l, y = o * h;
      e[0] = l * c, e[4] = y - d * u, e[8] = f * u + p, e[1] = u, e[5] = r * c, e[9] = -o * c, e[2] = -h * c, e[6] = p * u + f, e[10] = d - y * u;
    } else if (t.order === "XZY") {
      const d = r * l, p = r * h, f = o * l, y = o * h;
      e[0] = l * c, e[4] = -u, e[8] = h * c, e[1] = d * u + y, e[5] = r * c, e[9] = p * u - f, e[2] = f * u - p, e[6] = o * c, e[10] = y * u + d;
    }
    return e[3] = 0, e[7] = 0, e[11] = 0, e[12] = 0, e[13] = 0, e[14] = 0, e[15] = 1, this;
  }
  makeRotationFromQuaternion(t) {
    return this.compose(HT, t, GT);
  }
  lookAt(t, e, i) {
    const n = this.elements;
    return Di.subVectors(t, e), Di.lengthSq() === 0 && (Di.z = 1), Di.normalize(), ms.crossVectors(i, Di), ms.lengthSq() === 0 && (Math.abs(i.z) === 1 ? Di.x += 1e-4 : Di.z += 1e-4, Di.normalize(), ms.crossVectors(i, Di)), ms.normalize(), eh.crossVectors(Di, ms), n[0] = ms.x, n[4] = eh.x, n[8] = Di.x, n[1] = ms.y, n[5] = eh.y, n[9] = Di.y, n[2] = ms.z, n[6] = eh.z, n[10] = Di.z, this;
  }
  multiply(t) {
    return this.multiplyMatrices(this, t);
  }
  premultiply(t) {
    return this.multiplyMatrices(t, this);
  }
  multiplyMatrices(t, e) {
    const i = t.elements, n = e.elements, s = this.elements, r = i[0], o = i[4], l = i[8], h = i[12], c = i[1], u = i[5], d = i[9], p = i[13], f = i[2], y = i[6], g = i[10], m = i[14], v = i[3], x = i[7], _ = i[11], S = i[15], w = n[0], T = n[4], R = n[8], b = n[12], M = n[1], L = n[5], U = n[9], O = n[13], V = n[2], W = n[6], G = n[10], et = n[14], H = n[3], at = n[7], pt = n[11], Mt = n[15];
    return s[0] = r * w + o * M + l * V + h * H, s[4] = r * T + o * L + l * W + h * at, s[8] = r * R + o * U + l * G + h * pt, s[12] = r * b + o * O + l * et + h * Mt, s[1] = c * w + u * M + d * V + p * H, s[5] = c * T + u * L + d * W + p * at, s[9] = c * R + u * U + d * G + p * pt, s[13] = c * b + u * O + d * et + p * Mt, s[2] = f * w + y * M + g * V + m * H, s[6] = f * T + y * L + g * W + m * at, s[10] = f * R + y * U + g * G + m * pt, s[14] = f * b + y * O + g * et + m * Mt, s[3] = v * w + x * M + _ * V + S * H, s[7] = v * T + x * L + _ * W + S * at, s[11] = v * R + x * U + _ * G + S * pt, s[15] = v * b + x * O + _ * et + S * Mt, this;
  }
  multiplyScalar(t) {
    const e = this.elements;
    return e[0] *= t, e[4] *= t, e[8] *= t, e[12] *= t, e[1] *= t, e[5] *= t, e[9] *= t, e[13] *= t, e[2] *= t, e[6] *= t, e[10] *= t, e[14] *= t, e[3] *= t, e[7] *= t, e[11] *= t, e[15] *= t, this;
  }
  determinant() {
    const t = this.elements, e = t[0], i = t[4], n = t[8], s = t[12], r = t[1], o = t[5], l = t[9], h = t[13], c = t[2], u = t[6], d = t[10], p = t[14], f = t[3], y = t[7], g = t[11], m = t[15];
    return f * (+s * l * u - n * h * u - s * o * d + i * h * d + n * o * p - i * l * p) + y * (+e * l * p - e * h * d + s * r * d - n * r * p + n * h * c - s * l * c) + g * (+e * h * u - e * o * p - s * r * u + i * r * p + s * o * c - i * h * c) + m * (-n * o * c - e * l * u + e * o * d + n * r * u - i * r * d + i * l * c);
  }
  transpose() {
    const t = this.elements;
    let e;
    return e = t[1], t[1] = t[4], t[4] = e, e = t[2], t[2] = t[8], t[8] = e, e = t[6], t[6] = t[9], t[9] = e, e = t[3], t[3] = t[12], t[12] = e, e = t[7], t[7] = t[13], t[13] = e, e = t[11], t[11] = t[14], t[14] = e, this;
  }
  setPosition(t, e, i) {
    const n = this.elements;
    return t.isVector3 ? (n[12] = t.x, n[13] = t.y, n[14] = t.z) : (n[12] = t, n[13] = e, n[14] = i), this;
  }
  invert() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8], u = t[9], d = t[10], p = t[11], f = t[12], y = t[13], g = t[14], m = t[15], v = u * g * h - y * d * h + y * l * p - o * g * p - u * l * m + o * d * m, x = f * d * h - c * g * h - f * l * p + r * g * p + c * l * m - r * d * m, _ = c * y * h - f * u * h + f * o * p - r * y * p - c * o * m + r * u * m, S = f * u * l - c * y * l - f * o * d + r * y * d + c * o * g - r * u * g, w = e * v + i * x + n * _ + s * S;
    if (w === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    const T = 1 / w;
    return t[0] = v * T, t[1] = (y * d * s - u * g * s - y * n * p + i * g * p + u * n * m - i * d * m) * T, t[2] = (o * g * s - y * l * s + y * n * h - i * g * h - o * n * m + i * l * m) * T, t[3] = (u * l * s - o * d * s - u * n * h + i * d * h + o * n * p - i * l * p) * T, t[4] = x * T, t[5] = (c * g * s - f * d * s + f * n * p - e * g * p - c * n * m + e * d * m) * T, t[6] = (f * l * s - r * g * s - f * n * h + e * g * h + r * n * m - e * l * m) * T, t[7] = (r * d * s - c * l * s + c * n * h - e * d * h - r * n * p + e * l * p) * T, t[8] = _ * T, t[9] = (f * u * s - c * y * s - f * i * p + e * y * p + c * i * m - e * u * m) * T, t[10] = (r * y * s - f * o * s + f * i * h - e * y * h - r * i * m + e * o * m) * T, t[11] = (c * o * s - r * u * s - c * i * h + e * u * h + r * i * p - e * o * p) * T, t[12] = S * T, t[13] = (c * y * n - f * u * n + f * i * d - e * y * d - c * i * g + e * u * g) * T, t[14] = (f * o * n - r * y * n - f * i * l + e * y * l + r * i * g - e * o * g) * T, t[15] = (r * u * n - c * o * n + c * i * l - e * u * l - r * i * d + e * o * d) * T, this;
  }
  scale(t) {
    const e = this.elements, i = t.x, n = t.y, s = t.z;
    return e[0] *= i, e[4] *= n, e[8] *= s, e[1] *= i, e[5] *= n, e[9] *= s, e[2] *= i, e[6] *= n, e[10] *= s, e[3] *= i, e[7] *= n, e[11] *= s, this;
  }
  getMaxScaleOnAxis() {
    const t = this.elements, e = t[0] * t[0] + t[1] * t[1] + t[2] * t[2], i = t[4] * t[4] + t[5] * t[5] + t[6] * t[6], n = t[8] * t[8] + t[9] * t[9] + t[10] * t[10];
    return Math.sqrt(Math.max(e, i, n));
  }
  makeTranslation(t, e, i) {
    return t.isVector3 ? this.set(
      1,
      0,
      0,
      t.x,
      0,
      1,
      0,
      t.y,
      0,
      0,
      1,
      t.z,
      0,
      0,
      0,
      1
    ) : this.set(
      1,
      0,
      0,
      t,
      0,
      1,
      0,
      e,
      0,
      0,
      1,
      i,
      0,
      0,
      0,
      1
    ), this;
  }
  makeRotationX(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      1,
      0,
      0,
      0,
      0,
      e,
      -i,
      0,
      0,
      i,
      e,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  makeRotationY(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      0,
      i,
      0,
      0,
      1,
      0,
      0,
      -i,
      0,
      e,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  makeRotationZ(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      -i,
      0,
      0,
      i,
      e,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  makeRotationAxis(t, e) {
    const i = Math.cos(e), n = Math.sin(e), s = 1 - i, r = t.x, o = t.y, l = t.z, h = s * r, c = s * o;
    return this.set(
      h * r + i,
      h * o - n * l,
      h * l + n * o,
      0,
      h * o + n * l,
      c * o + i,
      c * l - n * r,
      0,
      h * l - n * o,
      c * l + n * r,
      s * l * l + i,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  makeScale(t, e, i) {
    return this.set(
      t,
      0,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      0,
      i,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  makeShear(t, e, i, n, s, r) {
    return this.set(
      1,
      i,
      s,
      0,
      t,
      1,
      r,
      0,
      e,
      n,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  compose(t, e, i) {
    const n = this.elements, s = e._x, r = e._y, o = e._z, l = e._w, h = s + s, c = r + r, u = o + o, d = s * h, p = s * c, f = s * u, y = r * c, g = r * u, m = o * u, v = l * h, x = l * c, _ = l * u, S = i.x, w = i.y, T = i.z;
    return n[0] = (1 - (y + m)) * S, n[1] = (p + _) * S, n[2] = (f - x) * S, n[3] = 0, n[4] = (p - _) * w, n[5] = (1 - (d + m)) * w, n[6] = (g + v) * w, n[7] = 0, n[8] = (f + x) * T, n[9] = (g - v) * T, n[10] = (1 - (d + y)) * T, n[11] = 0, n[12] = t.x, n[13] = t.y, n[14] = t.z, n[15] = 1, this;
  }
  decompose(t, e, i) {
    const n = this.elements;
    let s = $r.set(n[0], n[1], n[2]).length();
    const r = $r.set(n[4], n[5], n[6]).length(), o = $r.set(n[8], n[9], n[10]).length();
    this.determinant() < 0 && (s = -s), t.x = n[12], t.y = n[13], t.z = n[14], en.copy(this);
    const h = 1 / s, c = 1 / r, u = 1 / o;
    return en.elements[0] *= h, en.elements[1] *= h, en.elements[2] *= h, en.elements[4] *= c, en.elements[5] *= c, en.elements[6] *= c, en.elements[8] *= u, en.elements[9] *= u, en.elements[10] *= u, e.setFromRotationMatrix(en), i.x = s, i.y = r, i.z = o, this;
  }
  makePerspective(t, e, i, n, s, r, o = Zl) {
    const l = this.elements, h = 2 * s / (e - t), c = 2 * s / (i - n), u = (e + t) / (e - t), d = (i + n) / (i - n);
    let p, f;
    if (o === Zl)
      p = -(r + s) / (r - s), f = -2 * r * s / (r - s);
    else if (o === Cg)
      p = -r / (r - s), f = -r * s / (r - s);
    else
      throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + o);
    return l[0] = h, l[4] = 0, l[8] = u, l[12] = 0, l[1] = 0, l[5] = c, l[9] = d, l[13] = 0, l[2] = 0, l[6] = 0, l[10] = p, l[14] = f, l[3] = 0, l[7] = 0, l[11] = -1, l[15] = 0, this;
  }
  makeOrthographic(t, e, i, n, s, r, o = Zl) {
    const l = this.elements, h = 1 / (e - t), c = 1 / (i - n), u = 1 / (r - s), d = (e + t) * h, p = (i + n) * c;
    let f, y;
    if (o === Zl)
      f = (r + s) * u, y = -2 * u;
    else if (o === Cg)
      f = s * u, y = -1 * u;
    else
      throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + o);
    return l[0] = 2 * h, l[4] = 0, l[8] = 0, l[12] = -d, l[1] = 0, l[5] = 2 * c, l[9] = 0, l[13] = -p, l[2] = 0, l[6] = 0, l[10] = y, l[14] = -f, l[3] = 0, l[7] = 0, l[11] = 0, l[15] = 1, this;
  }
  equals(t) {
    const e = this.elements, i = t.elements;
    for (let n = 0; n < 16; n++)
      if (e[n] !== i[n]) return !1;
    return !0;
  }
  fromArray(t, e = 0) {
    for (let i = 0; i < 16; i++)
      this.elements[i] = t[i + e];
    return this;
  }
  toArray(t = [], e = 0) {
    const i = this.elements;
    return t[e] = i[0], t[e + 1] = i[1], t[e + 2] = i[2], t[e + 3] = i[3], t[e + 4] = i[4], t[e + 5] = i[5], t[e + 6] = i[6], t[e + 7] = i[7], t[e + 8] = i[8], t[e + 9] = i[9], t[e + 10] = i[10], t[e + 11] = i[11], t[e + 12] = i[12], t[e + 13] = i[13], t[e + 14] = i[14], t[e + 15] = i[15], t;
  }
};
const $r = /* @__PURE__ */ new tt(), en = /* @__PURE__ */ new Qn(), HT = /* @__PURE__ */ new tt(0, 0, 0), GT = /* @__PURE__ */ new tt(1, 1, 1), ms = /* @__PURE__ */ new tt(), eh = /* @__PURE__ */ new tt(), Di = /* @__PURE__ */ new tt(), zg = /* @__PURE__ */ new Qn(), Ng = /* @__PURE__ */ new qo();
let du = class Y_ {
  constructor(t = 0, e = 0, i = 0, n = Y_.DEFAULT_ORDER) {
    this.isEuler = !0, this._x = t, this._y = e, this._z = i, this._order = n;
  }
  get x() {
    return this._x;
  }
  set x(t) {
    this._x = t, this._onChangeCallback();
  }
  get y() {
    return this._y;
  }
  set y(t) {
    this._y = t, this._onChangeCallback();
  }
  get z() {
    return this._z;
  }
  set z(t) {
    this._z = t, this._onChangeCallback();
  }
  get order() {
    return this._order;
  }
  set order(t) {
    this._order = t, this._onChangeCallback();
  }
  set(t, e, i, n = this._order) {
    return this._x = t, this._y = e, this._z = i, this._order = n, this._onChangeCallback(), this;
  }
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._order);
  }
  copy(t) {
    return this._x = t._x, this._y = t._y, this._z = t._z, this._order = t._order, this._onChangeCallback(), this;
  }
  setFromRotationMatrix(t, e = this._order, i = !0) {
    const n = t.elements, s = n[0], r = n[4], o = n[8], l = n[1], h = n[5], c = n[9], u = n[2], d = n[6], p = n[10];
    switch (e) {
      case "XYZ":
        this._y = Math.asin(ai(o, -1, 1)), Math.abs(o) < 0.9999999 ? (this._x = Math.atan2(-c, p), this._z = Math.atan2(-r, s)) : (this._x = Math.atan2(d, h), this._z = 0);
        break;
      case "YXZ":
        this._x = Math.asin(-ai(c, -1, 1)), Math.abs(c) < 0.9999999 ? (this._y = Math.atan2(o, p), this._z = Math.atan2(l, h)) : (this._y = Math.atan2(-u, s), this._z = 0);
        break;
      case "ZXY":
        this._x = Math.asin(ai(d, -1, 1)), Math.abs(d) < 0.9999999 ? (this._y = Math.atan2(-u, p), this._z = Math.atan2(-r, h)) : (this._y = 0, this._z = Math.atan2(l, s));
        break;
      case "ZYX":
        this._y = Math.asin(-ai(u, -1, 1)), Math.abs(u) < 0.9999999 ? (this._x = Math.atan2(d, p), this._z = Math.atan2(l, s)) : (this._x = 0, this._z = Math.atan2(-r, h));
        break;
      case "YZX":
        this._z = Math.asin(ai(l, -1, 1)), Math.abs(l) < 0.9999999 ? (this._x = Math.atan2(-c, h), this._y = Math.atan2(-u, s)) : (this._x = 0, this._y = Math.atan2(o, p));
        break;
      case "XZY":
        this._z = Math.asin(-ai(r, -1, 1)), Math.abs(r) < 0.9999999 ? (this._x = Math.atan2(d, h), this._y = Math.atan2(o, s)) : (this._x = Math.atan2(-c, p), this._y = 0);
        break;
      default:
        console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + e);
    }
    return this._order = e, i === !0 && this._onChangeCallback(), this;
  }
  setFromQuaternion(t, e, i) {
    return zg.makeRotationFromQuaternion(t), this.setFromRotationMatrix(zg, e, i);
  }
  setFromVector3(t, e = this._order) {
    return this.set(t.x, t.y, t.z, e);
  }
  reorder(t) {
    return Ng.setFromEuler(this), this.setFromQuaternion(Ng, t);
  }
  equals(t) {
    return t._x === this._x && t._y === this._y && t._z === this._z && t._order === this._order;
  }
  fromArray(t) {
    return this._x = t[0], this._y = t[1], this._z = t[2], t[3] !== void 0 && (this._order = t[3]), this._onChangeCallback(), this;
  }
  toArray(t = [], e = 0) {
    return t[e] = this._x, t[e + 1] = this._y, t[e + 2] = this._z, t[e + 3] = this._order, t;
  }
  _onChange(t) {
    return this._onChangeCallback = t, this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x, yield this._y, yield this._z, yield this._order;
  }
};
du.DEFAULT_ORDER = "XYZ";
let WT = class {
  constructor() {
    this.mask = 1;
  }
  set(t) {
    this.mask = (1 << t | 0) >>> 0;
  }
  enable(t) {
    this.mask |= 1 << t | 0;
  }
  enableAll() {
    this.mask = -1;
  }
  toggle(t) {
    this.mask ^= 1 << t | 0;
  }
  disable(t) {
    this.mask &= ~(1 << t | 0);
  }
  disableAll() {
    this.mask = 0;
  }
  test(t) {
    return (this.mask & t.mask) !== 0;
  }
  isEnabled(t) {
    return (this.mask & (1 << t | 0)) !== 0;
  }
}, qT = 0;
const Og = /* @__PURE__ */ new tt(), Xr = /* @__PURE__ */ new qo(), Vn = /* @__PURE__ */ new Qn(), ih = /* @__PURE__ */ new tt(), to = /* @__PURE__ */ new tt(), $T = /* @__PURE__ */ new tt(), XT = /* @__PURE__ */ new qo(), kg = /* @__PURE__ */ new tt(1, 0, 0), Vg = /* @__PURE__ */ new tt(0, 1, 0), Hg = /* @__PURE__ */ new tt(0, 0, 1), Gg = { type: "added" }, YT = { type: "removed" }, Yr = { type: "childadded", child: null }, Ad = { type: "childremoved", child: null };
let Da = class Ph extends cu {
  constructor() {
    super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: qT++ }), this.uuid = Jn(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = Ph.DEFAULT_UP.clone();
    const t = new tt(), e = new du(), i = new qo(), n = new tt(1, 1, 1);
    function s() {
      i.setFromEuler(e, !1);
    }
    function r() {
      e.setFromQuaternion(i, void 0, !1);
    }
    e._onChange(s), i._onChange(r), Object.defineProperties(this, {
      position: {
        configurable: !0,
        enumerable: !0,
        value: t
      },
      rotation: {
        configurable: !0,
        enumerable: !0,
        value: e
      },
      quaternion: {
        configurable: !0,
        enumerable: !0,
        value: i
      },
      scale: {
        configurable: !0,
        enumerable: !0,
        value: n
      },
      modelViewMatrix: {
        value: new Qn()
      },
      normalMatrix: {
        value: new de()
      }
    }), this.matrix = new Qn(), this.matrixWorld = new Qn(), this.matrixAutoUpdate = Ph.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = Ph.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new WT(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.userData = {};
  }
  onBeforeShadow() {
  }
  onAfterShadow() {
  }
  onBeforeRender() {
  }
  onAfterRender() {
  }
  applyMatrix4(t) {
    this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(t), this.matrix.decompose(this.position, this.quaternion, this.scale);
  }
  applyQuaternion(t) {
    return this.quaternion.premultiply(t), this;
  }
  setRotationFromAxisAngle(t, e) {
    this.quaternion.setFromAxisAngle(t, e);
  }
  setRotationFromEuler(t) {
    this.quaternion.setFromEuler(t, !0);
  }
  setRotationFromMatrix(t) {
    this.quaternion.setFromRotationMatrix(t);
  }
  setRotationFromQuaternion(t) {
    this.quaternion.copy(t);
  }
  rotateOnAxis(t, e) {
    return Xr.setFromAxisAngle(t, e), this.quaternion.multiply(Xr), this;
  }
  rotateOnWorldAxis(t, e) {
    return Xr.setFromAxisAngle(t, e), this.quaternion.premultiply(Xr), this;
  }
  rotateX(t) {
    return this.rotateOnAxis(kg, t);
  }
  rotateY(t) {
    return this.rotateOnAxis(Vg, t);
  }
  rotateZ(t) {
    return this.rotateOnAxis(Hg, t);
  }
  translateOnAxis(t, e) {
    return Og.copy(t).applyQuaternion(this.quaternion), this.position.add(Og.multiplyScalar(e)), this;
  }
  translateX(t) {
    return this.translateOnAxis(kg, t);
  }
  translateY(t) {
    return this.translateOnAxis(Vg, t);
  }
  translateZ(t) {
    return this.translateOnAxis(Hg, t);
  }
  localToWorld(t) {
    return this.updateWorldMatrix(!0, !1), t.applyMatrix4(this.matrixWorld);
  }
  worldToLocal(t) {
    return this.updateWorldMatrix(!0, !1), t.applyMatrix4(Vn.copy(this.matrixWorld).invert());
  }
  lookAt(t, e, i) {
    t.isVector3 ? ih.copy(t) : ih.set(t, e, i);
    const n = this.parent;
    this.updateWorldMatrix(!0, !1), to.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? Vn.lookAt(to, ih, this.up) : Vn.lookAt(ih, to, this.up), this.quaternion.setFromRotationMatrix(Vn), n && (Vn.extractRotation(n.matrixWorld), Xr.setFromRotationMatrix(Vn), this.quaternion.premultiply(Xr.invert()));
  }
  add(t) {
    if (arguments.length > 1) {
      for (let e = 0; e < arguments.length; e++)
        this.add(arguments[e]);
      return this;
    }
    return t === this ? (console.error("THREE.Object3D.add: object can't be added as a child of itself.", t), this) : (t && t.isObject3D ? (t.removeFromParent(), t.parent = this, this.children.push(t), t.dispatchEvent(Gg), Yr.child = t, this.dispatchEvent(Yr), Yr.child = null) : console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", t), this);
  }
  remove(t) {
    if (arguments.length > 1) {
      for (let i = 0; i < arguments.length; i++)
        this.remove(arguments[i]);
      return this;
    }
    const e = this.children.indexOf(t);
    return e !== -1 && (t.parent = null, this.children.splice(e, 1), t.dispatchEvent(YT), Ad.child = t, this.dispatchEvent(Ad), Ad.child = null), this;
  }
  removeFromParent() {
    const t = this.parent;
    return t !== null && t.remove(this), this;
  }
  clear() {
    return this.remove(...this.children);
  }
  attach(t) {
    return this.updateWorldMatrix(!0, !1), Vn.copy(this.matrixWorld).invert(), t.parent !== null && (t.parent.updateWorldMatrix(!0, !1), Vn.multiply(t.parent.matrixWorld)), t.applyMatrix4(Vn), t.removeFromParent(), t.parent = this, this.children.push(t), t.updateWorldMatrix(!1, !0), t.dispatchEvent(Gg), Yr.child = t, this.dispatchEvent(Yr), Yr.child = null, this;
  }
  getObjectById(t) {
    return this.getObjectByProperty("id", t);
  }
  getObjectByName(t) {
    return this.getObjectByProperty("name", t);
  }
  getObjectByProperty(t, e) {
    if (this[t] === e) return this;
    for (let i = 0, n = this.children.length; i < n; i++) {
      const r = this.children[i].getObjectByProperty(t, e);
      if (r !== void 0)
        return r;
    }
  }
  getObjectsByProperty(t, e, i = []) {
    this[t] === e && i.push(this);
    const n = this.children;
    for (let s = 0, r = n.length; s < r; s++)
      n[s].getObjectsByProperty(t, e, i);
    return i;
  }
  getWorldPosition(t) {
    return this.updateWorldMatrix(!0, !1), t.setFromMatrixPosition(this.matrixWorld);
  }
  getWorldQuaternion(t) {
    return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(to, t, $T), t;
  }
  getWorldScale(t) {
    return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(to, XT, t), t;
  }
  getWorldDirection(t) {
    this.updateWorldMatrix(!0, !1);
    const e = this.matrixWorld.elements;
    return t.set(e[8], e[9], e[10]).normalize();
  }
  raycast() {
  }
  traverse(t) {
    t(this);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].traverse(t);
  }
  traverseVisible(t) {
    if (this.visible === !1) return;
    t(this);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].traverseVisible(t);
  }
  traverseAncestors(t) {
    const e = this.parent;
    e !== null && (t(e), e.traverseAncestors(t));
  }
  updateMatrix() {
    this.matrix.compose(this.position, this.quaternion, this.scale), this.matrixWorldNeedsUpdate = !0;
  }
  updateMatrixWorld(t) {
    this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || t) && (this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = !1, t = !0);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].updateMatrixWorld(t);
  }
  updateWorldMatrix(t, e) {
    const i = this.parent;
    if (t === !0 && i !== null && i.updateWorldMatrix(!0, !1), this.matrixAutoUpdate && this.updateMatrix(), this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), e === !0) {
      const n = this.children;
      for (let s = 0, r = n.length; s < r; s++)
        n[s].updateWorldMatrix(!1, !0);
    }
  }
  toJSON(t) {
    const e = t === void 0 || typeof t == "string", i = {};
    e && (t = {
      geometries: {},
      materials: {},
      textures: {},
      images: {},
      shapes: {},
      skeletons: {},
      animations: {},
      nodes: {}
    }, i.metadata = {
      version: 4.6,
      type: "Object",
      generator: "Object3D.toJSON"
    });
    const n = {};
    n.uuid = this.uuid, n.type = this.type, this.name !== "" && (n.name = this.name), this.castShadow === !0 && (n.castShadow = !0), this.receiveShadow === !0 && (n.receiveShadow = !0), this.visible === !1 && (n.visible = !1), this.frustumCulled === !1 && (n.frustumCulled = !1), this.renderOrder !== 0 && (n.renderOrder = this.renderOrder), Object.keys(this.userData).length > 0 && (n.userData = this.userData), n.layers = this.layers.mask, n.matrix = this.matrix.toArray(), n.up = this.up.toArray(), this.matrixAutoUpdate === !1 && (n.matrixAutoUpdate = !1), this.isInstancedMesh && (n.type = "InstancedMesh", n.count = this.count, n.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (n.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (n.type = "BatchedMesh", n.perObjectFrustumCulled = this.perObjectFrustumCulled, n.sortObjects = this.sortObjects, n.drawRanges = this._drawRanges, n.reservedRanges = this._reservedRanges, n.visibility = this._visibility, n.active = this._active, n.bounds = this._bounds.map((o) => ({
      boxInitialized: o.boxInitialized,
      boxMin: o.box.min.toArray(),
      boxMax: o.box.max.toArray(),
      sphereInitialized: o.sphereInitialized,
      sphereRadius: o.sphere.radius,
      sphereCenter: o.sphere.center.toArray()
    })), n.maxInstanceCount = this._maxInstanceCount, n.maxVertexCount = this._maxVertexCount, n.maxIndexCount = this._maxIndexCount, n.geometryInitialized = this._geometryInitialized, n.geometryCount = this._geometryCount, n.matricesTexture = this._matricesTexture.toJSON(t), this._colorsTexture !== null && (n.colorsTexture = this._colorsTexture.toJSON(t)), this.boundingSphere !== null && (n.boundingSphere = {
      center: n.boundingSphere.center.toArray(),
      radius: n.boundingSphere.radius
    }), this.boundingBox !== null && (n.boundingBox = {
      min: n.boundingBox.min.toArray(),
      max: n.boundingBox.max.toArray()
    }));
    function s(o, l) {
      return o[l.uuid] === void 0 && (o[l.uuid] = l.toJSON(t)), l.uuid;
    }
    if (this.isScene)
      this.background && (this.background.isColor ? n.background = this.background.toJSON() : this.background.isTexture && (n.background = this.background.toJSON(t).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (n.environment = this.environment.toJSON(t).uuid);
    else if (this.isMesh || this.isLine || this.isPoints) {
      n.geometry = s(t.geometries, this.geometry);
      const o = this.geometry.parameters;
      if (o !== void 0 && o.shapes !== void 0) {
        const l = o.shapes;
        if (Array.isArray(l))
          for (let h = 0, c = l.length; h < c; h++) {
            const u = l[h];
            s(t.shapes, u);
          }
        else
          s(t.shapes, l);
      }
    }
    if (this.isSkinnedMesh && (n.bindMode = this.bindMode, n.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (s(t.skeletons, this.skeleton), n.skeleton = this.skeleton.uuid)), this.material !== void 0)
      if (Array.isArray(this.material)) {
        const o = [];
        for (let l = 0, h = this.material.length; l < h; l++)
          o.push(s(t.materials, this.material[l]));
        n.material = o;
      } else
        n.material = s(t.materials, this.material);
    if (this.children.length > 0) {
      n.children = [];
      for (let o = 0; o < this.children.length; o++)
        n.children.push(this.children[o].toJSON(t).object);
    }
    if (this.animations.length > 0) {
      n.animations = [];
      for (let o = 0; o < this.animations.length; o++) {
        const l = this.animations[o];
        n.animations.push(s(t.animations, l));
      }
    }
    if (e) {
      const o = r(t.geometries), l = r(t.materials), h = r(t.textures), c = r(t.images), u = r(t.shapes), d = r(t.skeletons), p = r(t.animations), f = r(t.nodes);
      o.length > 0 && (i.geometries = o), l.length > 0 && (i.materials = l), h.length > 0 && (i.textures = h), c.length > 0 && (i.images = c), u.length > 0 && (i.shapes = u), d.length > 0 && (i.skeletons = d), p.length > 0 && (i.animations = p), f.length > 0 && (i.nodes = f);
    }
    return i.object = n, i;
    function r(o) {
      const l = [];
      for (const h in o) {
        const c = o[h];
        delete c.metadata, l.push(c);
      }
      return l;
    }
  }
  clone(t) {
    return new this.constructor().copy(this, t);
  }
  copy(t, e = !0) {
    if (this.name = t.name, this.up.copy(t.up), this.position.copy(t.position), this.rotation.order = t.rotation.order, this.quaternion.copy(t.quaternion), this.scale.copy(t.scale), this.matrix.copy(t.matrix), this.matrixWorld.copy(t.matrixWorld), this.matrixAutoUpdate = t.matrixAutoUpdate, this.matrixWorldAutoUpdate = t.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = t.matrixWorldNeedsUpdate, this.layers.mask = t.layers.mask, this.visible = t.visible, this.castShadow = t.castShadow, this.receiveShadow = t.receiveShadow, this.frustumCulled = t.frustumCulled, this.renderOrder = t.renderOrder, this.animations = t.animations.slice(), this.userData = JSON.parse(JSON.stringify(t.userData)), e === !0)
      for (let i = 0; i < t.children.length; i++) {
        const n = t.children[i];
        this.add(n.clone());
      }
    return this;
  }
};
Da.DEFAULT_UP = /* @__PURE__ */ new tt(0, 1, 0);
Da.DEFAULT_MATRIX_AUTO_UPDATE = !0;
Da.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0;
const nn = /* @__PURE__ */ new tt(), Hn = /* @__PURE__ */ new tt(), Ed = /* @__PURE__ */ new tt(), Gn = /* @__PURE__ */ new tt(), Zr = /* @__PURE__ */ new tt(), jr = /* @__PURE__ */ new tt(), Wg = /* @__PURE__ */ new tt(), Td = /* @__PURE__ */ new tt(), Cd = /* @__PURE__ */ new tt(), Rd = /* @__PURE__ */ new tt(), Pd = /* @__PURE__ */ new Pn(), Id = /* @__PURE__ */ new Pn(), Ld = /* @__PURE__ */ new Pn();
class cn {
  constructor(t = new tt(), e = new tt(), i = new tt()) {
    this.a = t, this.b = e, this.c = i;
  }
  static getNormal(t, e, i, n) {
    n.subVectors(i, e), nn.subVectors(t, e), n.cross(nn);
    const s = n.lengthSq();
    return s > 0 ? n.multiplyScalar(1 / Math.sqrt(s)) : n.set(0, 0, 0);
  }
  // static/instance method to calculate barycentric coordinates
  // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  static getBarycoord(t, e, i, n, s) {
    nn.subVectors(n, e), Hn.subVectors(i, e), Ed.subVectors(t, e);
    const r = nn.dot(nn), o = nn.dot(Hn), l = nn.dot(Ed), h = Hn.dot(Hn), c = Hn.dot(Ed), u = r * h - o * o;
    if (u === 0)
      return s.set(0, 0, 0), null;
    const d = 1 / u, p = (h * l - o * c) * d, f = (r * c - o * l) * d;
    return s.set(1 - p - f, f, p);
  }
  static containsPoint(t, e, i, n) {
    return this.getBarycoord(t, e, i, n, Gn) === null ? !1 : Gn.x >= 0 && Gn.y >= 0 && Gn.x + Gn.y <= 1;
  }
  static getInterpolation(t, e, i, n, s, r, o, l) {
    return this.getBarycoord(t, e, i, n, Gn) === null ? (l.x = 0, l.y = 0, "z" in l && (l.z = 0), "w" in l && (l.w = 0), null) : (l.setScalar(0), l.addScaledVector(s, Gn.x), l.addScaledVector(r, Gn.y), l.addScaledVector(o, Gn.z), l);
  }
  static getInterpolatedAttribute(t, e, i, n, s, r) {
    return Pd.setScalar(0), Id.setScalar(0), Ld.setScalar(0), Pd.fromBufferAttribute(t, e), Id.fromBufferAttribute(t, i), Ld.fromBufferAttribute(t, n), r.setScalar(0), r.addScaledVector(Pd, s.x), r.addScaledVector(Id, s.y), r.addScaledVector(Ld, s.z), r;
  }
  static isFrontFacing(t, e, i, n) {
    return nn.subVectors(i, e), Hn.subVectors(t, e), nn.cross(Hn).dot(n) < 0;
  }
  set(t, e, i) {
    return this.a.copy(t), this.b.copy(e), this.c.copy(i), this;
  }
  setFromPointsAndIndices(t, e, i, n) {
    return this.a.copy(t[e]), this.b.copy(t[i]), this.c.copy(t[n]), this;
  }
  setFromAttributeAndIndices(t, e, i, n) {
    return this.a.fromBufferAttribute(t, e), this.b.fromBufferAttribute(t, i), this.c.fromBufferAttribute(t, n), this;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(t) {
    return this.a.copy(t.a), this.b.copy(t.b), this.c.copy(t.c), this;
  }
  getArea() {
    return nn.subVectors(this.c, this.b), Hn.subVectors(this.a, this.b), nn.cross(Hn).length() * 0.5;
  }
  getMidpoint(t) {
    return t.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  }
  getNormal(t) {
    return cn.getNormal(this.a, this.b, this.c, t);
  }
  getPlane(t) {
    return t.setFromCoplanarPoints(this.a, this.b, this.c);
  }
  getBarycoord(t, e) {
    return cn.getBarycoord(t, this.a, this.b, this.c, e);
  }
  getInterpolation(t, e, i, n, s) {
    return cn.getInterpolation(t, this.a, this.b, this.c, e, i, n, s);
  }
  containsPoint(t) {
    return cn.containsPoint(t, this.a, this.b, this.c);
  }
  isFrontFacing(t) {
    return cn.isFrontFacing(this.a, this.b, this.c, t);
  }
  intersectsBox(t) {
    return t.intersectsTriangle(this);
  }
  closestPointToPoint(t, e) {
    const i = this.a, n = this.b, s = this.c;
    let r, o;
    Zr.subVectors(n, i), jr.subVectors(s, i), Td.subVectors(t, i);
    const l = Zr.dot(Td), h = jr.dot(Td);
    if (l <= 0 && h <= 0)
      return e.copy(i);
    Cd.subVectors(t, n);
    const c = Zr.dot(Cd), u = jr.dot(Cd);
    if (c >= 0 && u <= c)
      return e.copy(n);
    const d = l * u - c * h;
    if (d <= 0 && l >= 0 && c <= 0)
      return r = l / (l - c), e.copy(i).addScaledVector(Zr, r);
    Rd.subVectors(t, s);
    const p = Zr.dot(Rd), f = jr.dot(Rd);
    if (f >= 0 && p <= f)
      return e.copy(s);
    const y = p * h - l * f;
    if (y <= 0 && h >= 0 && f <= 0)
      return o = h / (h - f), e.copy(i).addScaledVector(jr, o);
    const g = c * f - p * u;
    if (g <= 0 && u - c >= 0 && p - f >= 0)
      return Wg.subVectors(s, n), o = (u - c) / (u - c + (p - f)), e.copy(n).addScaledVector(Wg, o);
    const m = 1 / (g + y + d);
    return r = y * m, o = d * m, e.copy(i).addScaledVector(Zr, r).addScaledVector(jr, o);
  }
  equals(t) {
    return t.a.equals(this.a) && t.b.equals(this.b) && t.c.equals(this.c);
  }
}
const Z_ = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
}, gs = { h: 0, s: 0, l: 0 }, nh = { h: 0, s: 0, l: 0 };
function Dd(a, t, e) {
  return e < 0 && (e += 1), e > 1 && (e -= 1), e < 1 / 6 ? a + (t - a) * 6 * e : e < 1 / 2 ? t : e < 2 / 3 ? a + (t - a) * 6 * (2 / 3 - e) : a;
}
let Ai = class {
  constructor(t, e, i) {
    return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(t, e, i);
  }
  set(t, e, i) {
    if (e === void 0 && i === void 0) {
      const n = t;
      n && n.isColor ? this.copy(n) : typeof n == "number" ? this.setHex(n) : typeof n == "string" && this.setStyle(n);
    } else
      this.setRGB(t, e, i);
    return this;
  }
  setScalar(t) {
    return this.r = t, this.g = t, this.b = t, this;
  }
  setHex(t, e = an) {
    return t = Math.floor(t), this.r = (t >> 16 & 255) / 255, this.g = (t >> 8 & 255) / 255, this.b = (t & 255) / 255, Wi.toWorkingColorSpace(this, e), this;
  }
  setRGB(t, e, i, n = Wi.workingColorSpace) {
    return this.r = t, this.g = e, this.b = i, Wi.toWorkingColorSpace(this, n), this;
  }
  setHSL(t, e, i, n = Wi.workingColorSpace) {
    if (t = yf(t, 1), e = ai(e, 0, 1), i = ai(i, 0, 1), e === 0)
      this.r = this.g = this.b = i;
    else {
      const s = i <= 0.5 ? i * (1 + e) : i + e - i * e, r = 2 * i - s;
      this.r = Dd(r, s, t + 1 / 3), this.g = Dd(r, s, t), this.b = Dd(r, s, t - 1 / 3);
    }
    return Wi.toWorkingColorSpace(this, n), this;
  }
  setStyle(t, e = an) {
    function i(s) {
      s !== void 0 && parseFloat(s) < 1 && console.warn("THREE.Color: Alpha component of " + t + " will be ignored.");
    }
    let n;
    if (n = /^(\w+)\(([^\)]*)\)/.exec(t)) {
      let s;
      const r = n[1], o = n[2];
      switch (r) {
        case "rgb":
        case "rgba":
          if (s = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setRGB(
              Math.min(255, parseInt(s[1], 10)) / 255,
              Math.min(255, parseInt(s[2], 10)) / 255,
              Math.min(255, parseInt(s[3], 10)) / 255,
              e
            );
          if (s = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setRGB(
              Math.min(100, parseInt(s[1], 10)) / 100,
              Math.min(100, parseInt(s[2], 10)) / 100,
              Math.min(100, parseInt(s[3], 10)) / 100,
              e
            );
          break;
        case "hsl":
        case "hsla":
          if (s = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setHSL(
              parseFloat(s[1]) / 360,
              parseFloat(s[2]) / 100,
              parseFloat(s[3]) / 100,
              e
            );
          break;
        default:
          console.warn("THREE.Color: Unknown color model " + t);
      }
    } else if (n = /^\#([A-Fa-f\d]+)$/.exec(t)) {
      const s = n[1], r = s.length;
      if (r === 3)
        return this.setRGB(
          parseInt(s.charAt(0), 16) / 15,
          parseInt(s.charAt(1), 16) / 15,
          parseInt(s.charAt(2), 16) / 15,
          e
        );
      if (r === 6)
        return this.setHex(parseInt(s, 16), e);
      console.warn("THREE.Color: Invalid hex color " + t);
    } else if (t && t.length > 0)
      return this.setColorName(t, e);
    return this;
  }
  setColorName(t, e = an) {
    const i = Z_[t.toLowerCase()];
    return i !== void 0 ? this.setHex(i, e) : console.warn("THREE.Color: Unknown color " + t), this;
  }
  clone() {
    return new this.constructor(this.r, this.g, this.b);
  }
  copy(t) {
    return this.r = t.r, this.g = t.g, this.b = t.b, this;
  }
  copySRGBToLinear(t) {
    return this.r = Kn(t.r), this.g = Kn(t.g), this.b = Kn(t.b), this;
  }
  copyLinearToSRGB(t) {
    return this.r = ha(t.r), this.g = ha(t.g), this.b = ha(t.b), this;
  }
  convertSRGBToLinear() {
    return this.copySRGBToLinear(this), this;
  }
  convertLinearToSRGB() {
    return this.copyLinearToSRGB(this), this;
  }
  getHex(t = an) {
    return Wi.fromWorkingColorSpace(ei.copy(this), t), Math.round(ai(ei.r * 255, 0, 255)) * 65536 + Math.round(ai(ei.g * 255, 0, 255)) * 256 + Math.round(ai(ei.b * 255, 0, 255));
  }
  getHexString(t = an) {
    return ("000000" + this.getHex(t).toString(16)).slice(-6);
  }
  getHSL(t, e = Wi.workingColorSpace) {
    Wi.fromWorkingColorSpace(ei.copy(this), e);
    const i = ei.r, n = ei.g, s = ei.b, r = Math.max(i, n, s), o = Math.min(i, n, s);
    let l, h;
    const c = (o + r) / 2;
    if (o === r)
      l = 0, h = 0;
    else {
      const u = r - o;
      switch (h = c <= 0.5 ? u / (r + o) : u / (2 - r - o), r) {
        case i:
          l = (n - s) / u + (n < s ? 6 : 0);
          break;
        case n:
          l = (s - i) / u + 2;
          break;
        case s:
          l = (i - n) / u + 4;
          break;
      }
      l /= 6;
    }
    return t.h = l, t.s = h, t.l = c, t;
  }
  getRGB(t, e = Wi.workingColorSpace) {
    return Wi.fromWorkingColorSpace(ei.copy(this), e), t.r = ei.r, t.g = ei.g, t.b = ei.b, t;
  }
  getStyle(t = an) {
    Wi.fromWorkingColorSpace(ei.copy(this), t);
    const e = ei.r, i = ei.g, n = ei.b;
    return t !== an ? `color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})` : `rgb(${Math.round(e * 255)},${Math.round(i * 255)},${Math.round(n * 255)})`;
  }
  offsetHSL(t, e, i) {
    return this.getHSL(gs), this.setHSL(gs.h + t, gs.s + e, gs.l + i);
  }
  add(t) {
    return this.r += t.r, this.g += t.g, this.b += t.b, this;
  }
  addColors(t, e) {
    return this.r = t.r + e.r, this.g = t.g + e.g, this.b = t.b + e.b, this;
  }
  addScalar(t) {
    return this.r += t, this.g += t, this.b += t, this;
  }
  sub(t) {
    return this.r = Math.max(0, this.r - t.r), this.g = Math.max(0, this.g - t.g), this.b = Math.max(0, this.b - t.b), this;
  }
  multiply(t) {
    return this.r *= t.r, this.g *= t.g, this.b *= t.b, this;
  }
  multiplyScalar(t) {
    return this.r *= t, this.g *= t, this.b *= t, this;
  }
  lerp(t, e) {
    return this.r += (t.r - this.r) * e, this.g += (t.g - this.g) * e, this.b += (t.b - this.b) * e, this;
  }
  lerpColors(t, e, i) {
    return this.r = t.r + (e.r - t.r) * i, this.g = t.g + (e.g - t.g) * i, this.b = t.b + (e.b - t.b) * i, this;
  }
  lerpHSL(t, e) {
    this.getHSL(gs), t.getHSL(nh);
    const i = yo(gs.h, nh.h, e), n = yo(gs.s, nh.s, e), s = yo(gs.l, nh.l, e);
    return this.setHSL(i, n, s), this;
  }
  setFromVector3(t) {
    return this.r = t.x, this.g = t.y, this.b = t.z, this;
  }
  applyMatrix3(t) {
    const e = this.r, i = this.g, n = this.b, s = t.elements;
    return this.r = s[0] * e + s[3] * i + s[6] * n, this.g = s[1] * e + s[4] * i + s[7] * n, this.b = s[2] * e + s[5] * i + s[8] * n, this;
  }
  equals(t) {
    return t.r === this.r && t.g === this.g && t.b === this.b;
  }
  fromArray(t, e = 0) {
    return this.r = t[e], this.g = t[e + 1], this.b = t[e + 2], this;
  }
  toArray(t = [], e = 0) {
    return t[e] = this.r, t[e + 1] = this.g, t[e + 2] = this.b, t;
  }
  fromBufferAttribute(t, e) {
    return this.r = t.getX(e), this.g = t.getY(e), this.b = t.getZ(e), this;
  }
  toJSON() {
    return this.getHex();
  }
  *[Symbol.iterator]() {
    yield this.r, yield this.g, yield this.b;
  }
};
const ei = /* @__PURE__ */ new Ai();
Ai.NAMES = Z_;
let ZT = 0;
class xf extends cu {
  static get type() {
    return "Material";
  }
  get type() {
    return this.constructor.type;
  }
  set type(t) {
  }
  constructor() {
    super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: ZT++ }), this.uuid = Jn(), this.name = "", this.blending = bg, this.side = Bo, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = Sg, this.blendDst = wg, this.blendEquation = Mg, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new Ai(0, 0, 0), this.blendAlpha = 0, this.depthFunc = Ag, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = Sc, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = Vr, this.stencilZFail = Vr, this.stencilZPass = Vr, this.stencilWrite = !1, this.clippingPlanes = null, this.clipIntersection = !1, this.clipShadows = !1, this.shadowSide = null, this.colorWrite = !0, this.precision = null, this.polygonOffset = !1, this.polygonOffsetFactor = 0, this.polygonOffsetUnits = 0, this.dithering = !1, this.alphaToCoverage = !1, this.premultipliedAlpha = !1, this.forceSinglePass = !1, this.visible = !0, this.toneMapped = !0, this.userData = {}, this.version = 0, this._alphaTest = 0;
  }
  get alphaTest() {
    return this._alphaTest;
  }
  set alphaTest(t) {
    this._alphaTest > 0 != t > 0 && this.version++, this._alphaTest = t;
  }
  // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  onBeforeRender() {
  }
  onBeforeCompile() {
  }
  customProgramCacheKey() {
    return this.onBeforeCompile.toString();
  }
  setValues(t) {
    if (t !== void 0)
      for (const e in t) {
        const i = t[e];
        if (i === void 0) {
          console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);
          continue;
        }
        const n = this[e];
        if (n === void 0) {
          console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`);
          continue;
        }
        n && n.isColor ? n.set(i) : n && n.isVector3 && i && i.isVector3 ? n.copy(i) : this[e] = i;
      }
  }
  toJSON(t) {
    const e = t === void 0 || typeof t == "string";
    e && (t = {
      textures: {},
      images: {}
    });
    const i = {
      metadata: {
        version: 4.6,
        type: "Material",
        generator: "Material.toJSON"
      }
    };
    i.uuid = this.uuid, i.type = this.type, this.name !== "" && (i.name = this.name), this.color && this.color.isColor && (i.color = this.color.getHex()), this.roughness !== void 0 && (i.roughness = this.roughness), this.metalness !== void 0 && (i.metalness = this.metalness), this.sheen !== void 0 && (i.sheen = this.sheen), this.sheenColor && this.sheenColor.isColor && (i.sheenColor = this.sheenColor.getHex()), this.sheenRoughness !== void 0 && (i.sheenRoughness = this.sheenRoughness), this.emissive && this.emissive.isColor && (i.emissive = this.emissive.getHex()), this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1 && (i.emissiveIntensity = this.emissiveIntensity), this.specular && this.specular.isColor && (i.specular = this.specular.getHex()), this.specularIntensity !== void 0 && (i.specularIntensity = this.specularIntensity), this.specularColor && this.specularColor.isColor && (i.specularColor = this.specularColor.getHex()), this.shininess !== void 0 && (i.shininess = this.shininess), this.clearcoat !== void 0 && (i.clearcoat = this.clearcoat), this.clearcoatRoughness !== void 0 && (i.clearcoatRoughness = this.clearcoatRoughness), this.clearcoatMap && this.clearcoatMap.isTexture && (i.clearcoatMap = this.clearcoatMap.toJSON(t).uuid), this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture && (i.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(t).uuid), this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture && (i.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(t).uuid, i.clearcoatNormalScale = this.clearcoatNormalScale.toArray()), this.dispersion !== void 0 && (i.dispersion = this.dispersion), this.iridescence !== void 0 && (i.iridescence = this.iridescence), this.iridescenceIOR !== void 0 && (i.iridescenceIOR = this.iridescenceIOR), this.iridescenceThicknessRange !== void 0 && (i.iridescenceThicknessRange = this.iridescenceThicknessRange), this.iridescenceMap && this.iridescenceMap.isTexture && (i.iridescenceMap = this.iridescenceMap.toJSON(t).uuid), this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture && (i.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(t).uuid), this.anisotropy !== void 0 && (i.anisotropy = this.anisotropy), this.anisotropyRotation !== void 0 && (i.anisotropyRotation = this.anisotropyRotation), this.anisotropyMap && this.anisotropyMap.isTexture && (i.anisotropyMap = this.anisotropyMap.toJSON(t).uuid), this.map && this.map.isTexture && (i.map = this.map.toJSON(t).uuid), this.matcap && this.matcap.isTexture && (i.matcap = this.matcap.toJSON(t).uuid), this.alphaMap && this.alphaMap.isTexture && (i.alphaMap = this.alphaMap.toJSON(t).uuid), this.lightMap && this.lightMap.isTexture && (i.lightMap = this.lightMap.toJSON(t).uuid, i.lightMapIntensity = this.lightMapIntensity), this.aoMap && this.aoMap.isTexture && (i.aoMap = this.aoMap.toJSON(t).uuid, i.aoMapIntensity = this.aoMapIntensity), this.bumpMap && this.bumpMap.isTexture && (i.bumpMap = this.bumpMap.toJSON(t).uuid, i.bumpScale = this.bumpScale), this.normalMap && this.normalMap.isTexture && (i.normalMap = this.normalMap.toJSON(t).uuid, i.normalMapType = this.normalMapType, i.normalScale = this.normalScale.toArray()), this.displacementMap && this.displacementMap.isTexture && (i.displacementMap = this.displacementMap.toJSON(t).uuid, i.displacementScale = this.displacementScale, i.displacementBias = this.displacementBias), this.roughnessMap && this.roughnessMap.isTexture && (i.roughnessMap = this.roughnessMap.toJSON(t).uuid), this.metalnessMap && this.metalnessMap.isTexture && (i.metalnessMap = this.metalnessMap.toJSON(t).uuid), this.emissiveMap && this.emissiveMap.isTexture && (i.emissiveMap = this.emissiveMap.toJSON(t).uuid), this.specularMap && this.specularMap.isTexture && (i.specularMap = this.specularMap.toJSON(t).uuid), this.specularIntensityMap && this.specularIntensityMap.isTexture && (i.specularIntensityMap = this.specularIntensityMap.toJSON(t).uuid), this.specularColorMap && this.specularColorMap.isTexture && (i.specularColorMap = this.specularColorMap.toJSON(t).uuid), this.envMap && this.envMap.isTexture && (i.envMap = this.envMap.toJSON(t).uuid, this.combine !== void 0 && (i.combine = this.combine)), this.envMapRotation !== void 0 && (i.envMapRotation = this.envMapRotation.toArray()), this.envMapIntensity !== void 0 && (i.envMapIntensity = this.envMapIntensity), this.reflectivity !== void 0 && (i.reflectivity = this.reflectivity), this.refractionRatio !== void 0 && (i.refractionRatio = this.refractionRatio), this.gradientMap && this.gradientMap.isTexture && (i.gradientMap = this.gradientMap.toJSON(t).uuid), this.transmission !== void 0 && (i.transmission = this.transmission), this.transmissionMap && this.transmissionMap.isTexture && (i.transmissionMap = this.transmissionMap.toJSON(t).uuid), this.thickness !== void 0 && (i.thickness = this.thickness), this.thicknessMap && this.thicknessMap.isTexture && (i.thicknessMap = this.thicknessMap.toJSON(t).uuid), this.attenuationDistance !== void 0 && this.attenuationDistance !== 1 / 0 && (i.attenuationDistance = this.attenuationDistance), this.attenuationColor !== void 0 && (i.attenuationColor = this.attenuationColor.getHex()), this.size !== void 0 && (i.size = this.size), this.shadowSide !== null && (i.shadowSide = this.shadowSide), this.sizeAttenuation !== void 0 && (i.sizeAttenuation = this.sizeAttenuation), this.blending !== bg && (i.blending = this.blending), this.side !== Bo && (i.side = this.side), this.vertexColors === !0 && (i.vertexColors = !0), this.opacity < 1 && (i.opacity = this.opacity), this.transparent === !0 && (i.transparent = !0), this.blendSrc !== Sg && (i.blendSrc = this.blendSrc), this.blendDst !== wg && (i.blendDst = this.blendDst), this.blendEquation !== Mg && (i.blendEquation = this.blendEquation), this.blendSrcAlpha !== null && (i.blendSrcAlpha = this.blendSrcAlpha), this.blendDstAlpha !== null && (i.blendDstAlpha = this.blendDstAlpha), this.blendEquationAlpha !== null && (i.blendEquationAlpha = this.blendEquationAlpha), this.blendColor && this.blendColor.isColor && (i.blendColor = this.blendColor.getHex()), this.blendAlpha !== 0 && (i.blendAlpha = this.blendAlpha), this.depthFunc !== Ag && (i.depthFunc = this.depthFunc), this.depthTest === !1 && (i.depthTest = this.depthTest), this.depthWrite === !1 && (i.depthWrite = this.depthWrite), this.colorWrite === !1 && (i.colorWrite = this.colorWrite), this.stencilWriteMask !== 255 && (i.stencilWriteMask = this.stencilWriteMask), this.stencilFunc !== Sc && (i.stencilFunc = this.stencilFunc), this.stencilRef !== 0 && (i.stencilRef = this.stencilRef), this.stencilFuncMask !== 255 && (i.stencilFuncMask = this.stencilFuncMask), this.stencilFail !== Vr && (i.stencilFail = this.stencilFail), this.stencilZFail !== Vr && (i.stencilZFail = this.stencilZFail), this.stencilZPass !== Vr && (i.stencilZPass = this.stencilZPass), this.stencilWrite === !0 && (i.stencilWrite = this.stencilWrite), this.rotation !== void 0 && this.rotation !== 0 && (i.rotation = this.rotation), this.polygonOffset === !0 && (i.polygonOffset = !0), this.polygonOffsetFactor !== 0 && (i.polygonOffsetFactor = this.polygonOffsetFactor), this.polygonOffsetUnits !== 0 && (i.polygonOffsetUnits = this.polygonOffsetUnits), this.linewidth !== void 0 && this.linewidth !== 1 && (i.linewidth = this.linewidth), this.dashSize !== void 0 && (i.dashSize = this.dashSize), this.gapSize !== void 0 && (i.gapSize = this.gapSize), this.scale !== void 0 && (i.scale = this.scale), this.dithering === !0 && (i.dithering = !0), this.alphaTest > 0 && (i.alphaTest = this.alphaTest), this.alphaHash === !0 && (i.alphaHash = !0), this.alphaToCoverage === !0 && (i.alphaToCoverage = !0), this.premultipliedAlpha === !0 && (i.premultipliedAlpha = !0), this.forceSinglePass === !0 && (i.forceSinglePass = !0), this.wireframe === !0 && (i.wireframe = !0), this.wireframeLinewidth > 1 && (i.wireframeLinewidth = this.wireframeLinewidth), this.wireframeLinecap !== "round" && (i.wireframeLinecap = this.wireframeLinecap), this.wireframeLinejoin !== "round" && (i.wireframeLinejoin = this.wireframeLinejoin), this.flatShading === !0 && (i.flatShading = !0), this.visible === !1 && (i.visible = !1), this.toneMapped === !1 && (i.toneMapped = !1), this.fog === !1 && (i.fog = !1), Object.keys(this.userData).length > 0 && (i.userData = this.userData);
    function n(s) {
      const r = [];
      for (const o in s) {
        const l = s[o];
        delete l.metadata, r.push(l);
      }
      return r;
    }
    if (e) {
      const s = n(t.textures), r = n(t.images);
      s.length > 0 && (i.textures = s), r.length > 0 && (i.images = r);
    }
    return i;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(t) {
    this.name = t.name, this.blending = t.blending, this.side = t.side, this.vertexColors = t.vertexColors, this.opacity = t.opacity, this.transparent = t.transparent, this.blendSrc = t.blendSrc, this.blendDst = t.blendDst, this.blendEquation = t.blendEquation, this.blendSrcAlpha = t.blendSrcAlpha, this.blendDstAlpha = t.blendDstAlpha, this.blendEquationAlpha = t.blendEquationAlpha, this.blendColor.copy(t.blendColor), this.blendAlpha = t.blendAlpha, this.depthFunc = t.depthFunc, this.depthTest = t.depthTest, this.depthWrite = t.depthWrite, this.stencilWriteMask = t.stencilWriteMask, this.stencilFunc = t.stencilFunc, this.stencilRef = t.stencilRef, this.stencilFuncMask = t.stencilFuncMask, this.stencilFail = t.stencilFail, this.stencilZFail = t.stencilZFail, this.stencilZPass = t.stencilZPass, this.stencilWrite = t.stencilWrite;
    const e = t.clippingPlanes;
    let i = null;
    if (e !== null) {
      const n = e.length;
      i = new Array(n);
      for (let s = 0; s !== n; ++s)
        i[s] = e[s].clone();
    }
    return this.clippingPlanes = i, this.clipIntersection = t.clipIntersection, this.clipShadows = t.clipShadows, this.shadowSide = t.shadowSide, this.colorWrite = t.colorWrite, this.precision = t.precision, this.polygonOffset = t.polygonOffset, this.polygonOffsetFactor = t.polygonOffsetFactor, this.polygonOffsetUnits = t.polygonOffsetUnits, this.dithering = t.dithering, this.alphaTest = t.alphaTest, this.alphaHash = t.alphaHash, this.alphaToCoverage = t.alphaToCoverage, this.premultipliedAlpha = t.premultipliedAlpha, this.forceSinglePass = t.forceSinglePass, this.visible = t.visible, this.toneMapped = t.toneMapped, this.userData = JSON.parse(JSON.stringify(t.userData)), this;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  onBuild() {
    console.warn("Material: onBuild() has been removed.");
  }
}
class pu extends xf {
  static get type() {
    return "MeshBasicMaterial";
  }
  constructor(t) {
    super(), this.isMeshBasicMaterial = !0, this.color = new Ai(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new du(), this.combine = uT, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.color.copy(t.color), this.map = t.map, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.specularMap = t.specularMap, this.alphaMap = t.alphaMap, this.envMap = t.envMap, this.envMapRotation.copy(t.envMapRotation), this.combine = t.combine, this.reflectivity = t.reflectivity, this.refractionRatio = t.refractionRatio, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.fog = t.fog, this;
  }
}
const Le = /* @__PURE__ */ new tt(), sh = /* @__PURE__ */ new _i();
class qi {
  constructor(t, e, i = !1) {
    if (Array.isArray(t))
      throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
    this.isBufferAttribute = !0, this.name = "", this.array = t, this.itemSize = e, this.count = t !== void 0 ? t.length / e : 0, this.normalized = i, this.usage = xp, this.updateRanges = [], this.gpuType = mT, this.version = 0;
  }
  onUploadCallback() {
  }
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  setUsage(t) {
    return this.usage = t, this;
  }
  addUpdateRange(t, e) {
    this.updateRanges.push({ start: t, count: e });
  }
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  copy(t) {
    return this.name = t.name, this.array = new t.array.constructor(t.array), this.itemSize = t.itemSize, this.count = t.count, this.normalized = t.normalized, this.usage = t.usage, this.gpuType = t.gpuType, this;
  }
  copyAt(t, e, i) {
    t *= this.itemSize, i *= e.itemSize;
    for (let n = 0, s = this.itemSize; n < s; n++)
      this.array[t + n] = e.array[i + n];
    return this;
  }
  copyArray(t) {
    return this.array.set(t), this;
  }
  applyMatrix3(t) {
    if (this.itemSize === 2)
      for (let e = 0, i = this.count; e < i; e++)
        sh.fromBufferAttribute(this, e), sh.applyMatrix3(t), this.setXY(e, sh.x, sh.y);
    else if (this.itemSize === 3)
      for (let e = 0, i = this.count; e < i; e++)
        Le.fromBufferAttribute(this, e), Le.applyMatrix3(t), this.setXYZ(e, Le.x, Le.y, Le.z);
    return this;
  }
  applyMatrix4(t) {
    for (let e = 0, i = this.count; e < i; e++)
      Le.fromBufferAttribute(this, e), Le.applyMatrix4(t), this.setXYZ(e, Le.x, Le.y, Le.z);
    return this;
  }
  applyNormalMatrix(t) {
    for (let e = 0, i = this.count; e < i; e++)
      Le.fromBufferAttribute(this, e), Le.applyNormalMatrix(t), this.setXYZ(e, Le.x, Le.y, Le.z);
    return this;
  }
  transformDirection(t) {
    for (let e = 0, i = this.count; e < i; e++)
      Le.fromBufferAttribute(this, e), Le.transformDirection(t), this.setXYZ(e, Le.x, Le.y, Le.z);
    return this;
  }
  set(t, e = 0) {
    return this.array.set(t, e), this;
  }
  getComponent(t, e) {
    let i = this.array[t * this.itemSize + e];
    return this.normalized && (i = hn(i, this.array)), i;
  }
  setComponent(t, e, i) {
    return this.normalized && (i = ue(i, this.array)), this.array[t * this.itemSize + e] = i, this;
  }
  getX(t) {
    let e = this.array[t * this.itemSize];
    return this.normalized && (e = hn(e, this.array)), e;
  }
  setX(t, e) {
    return this.normalized && (e = ue(e, this.array)), this.array[t * this.itemSize] = e, this;
  }
  getY(t) {
    let e = this.array[t * this.itemSize + 1];
    return this.normalized && (e = hn(e, this.array)), e;
  }
  setY(t, e) {
    return this.normalized && (e = ue(e, this.array)), this.array[t * this.itemSize + 1] = e, this;
  }
  getZ(t) {
    let e = this.array[t * this.itemSize + 2];
    return this.normalized && (e = hn(e, this.array)), e;
  }
  setZ(t, e) {
    return this.normalized && (e = ue(e, this.array)), this.array[t * this.itemSize + 2] = e, this;
  }
  getW(t) {
    let e = this.array[t * this.itemSize + 3];
    return this.normalized && (e = hn(e, this.array)), e;
  }
  setW(t, e) {
    return this.normalized && (e = ue(e, this.array)), this.array[t * this.itemSize + 3] = e, this;
  }
  setXY(t, e, i) {
    return t *= this.itemSize, this.normalized && (e = ue(e, this.array), i = ue(i, this.array)), this.array[t + 0] = e, this.array[t + 1] = i, this;
  }
  setXYZ(t, e, i, n) {
    return t *= this.itemSize, this.normalized && (e = ue(e, this.array), i = ue(i, this.array), n = ue(n, this.array)), this.array[t + 0] = e, this.array[t + 1] = i, this.array[t + 2] = n, this;
  }
  setXYZW(t, e, i, n, s) {
    return t *= this.itemSize, this.normalized && (e = ue(e, this.array), i = ue(i, this.array), n = ue(n, this.array), s = ue(s, this.array)), this.array[t + 0] = e, this.array[t + 1] = i, this.array[t + 2] = n, this.array[t + 3] = s, this;
  }
  onUpload(t) {
    return this.onUploadCallback = t, this;
  }
  clone() {
    return new this.constructor(this.array, this.itemSize).copy(this);
  }
  toJSON() {
    const t = {
      itemSize: this.itemSize,
      type: this.array.constructor.name,
      array: Array.from(this.array),
      normalized: this.normalized
    };
    return this.name !== "" && (t.name = this.name), this.usage !== xp && (t.usage = this.usage), t;
  }
}
class jT extends qi {
  constructor(t, e, i) {
    super(new Uint16Array(t), e, i);
  }
}
class JT extends qi {
  constructor(t, e, i) {
    super(new Uint32Array(t), e, i);
  }
}
class wc extends qi {
  constructor(t, e, i) {
    super(new Float32Array(t), e, i);
  }
}
let KT = 0;
const Gi = /* @__PURE__ */ new Qn(), Fd = /* @__PURE__ */ new Da(), Jr = /* @__PURE__ */ new tt(), Fi = /* @__PURE__ */ new Us(), eo = /* @__PURE__ */ new Us(), ke = /* @__PURE__ */ new tt();
class Fa extends cu {
  constructor() {
    super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: KT++ }), this.uuid = Jn(), this.name = "", this.type = "BufferGeometry", this.index = null, this.indirect = null, this.attributes = {}, this.morphAttributes = {}, this.morphTargetsRelative = !1, this.groups = [], this.boundingBox = null, this.boundingSphere = null, this.drawRange = { start: 0, count: 1 / 0 }, this.userData = {};
  }
  getIndex() {
    return this.index;
  }
  setIndex(t) {
    return Array.isArray(t) ? this.index = new (UT(t) ? JT : jT)(t, 1) : this.index = t, this;
  }
  setIndirect(t) {
    return this.indirect = t, this;
  }
  getIndirect() {
    return this.indirect;
  }
  getAttribute(t) {
    return this.attributes[t];
  }
  setAttribute(t, e) {
    return this.attributes[t] = e, this;
  }
  deleteAttribute(t) {
    return delete this.attributes[t], this;
  }
  hasAttribute(t) {
    return this.attributes[t] !== void 0;
  }
  addGroup(t, e, i = 0) {
    this.groups.push({
      start: t,
      count: e,
      materialIndex: i
    });
  }
  clearGroups() {
    this.groups = [];
  }
  setDrawRange(t, e) {
    this.drawRange.start = t, this.drawRange.count = e;
  }
  applyMatrix4(t) {
    const e = this.attributes.position;
    e !== void 0 && (e.applyMatrix4(t), e.needsUpdate = !0);
    const i = this.attributes.normal;
    if (i !== void 0) {
      const s = new de().getNormalMatrix(t);
      i.applyNormalMatrix(s), i.needsUpdate = !0;
    }
    const n = this.attributes.tangent;
    return n !== void 0 && (n.transformDirection(t), n.needsUpdate = !0), this.boundingBox !== null && this.computeBoundingBox(), this.boundingSphere !== null && this.computeBoundingSphere(), this;
  }
  applyQuaternion(t) {
    return Gi.makeRotationFromQuaternion(t), this.applyMatrix4(Gi), this;
  }
  rotateX(t) {
    return Gi.makeRotationX(t), this.applyMatrix4(Gi), this;
  }
  rotateY(t) {
    return Gi.makeRotationY(t), this.applyMatrix4(Gi), this;
  }
  rotateZ(t) {
    return Gi.makeRotationZ(t), this.applyMatrix4(Gi), this;
  }
  translate(t, e, i) {
    return Gi.makeTranslation(t, e, i), this.applyMatrix4(Gi), this;
  }
  scale(t, e, i) {
    return Gi.makeScale(t, e, i), this.applyMatrix4(Gi), this;
  }
  lookAt(t) {
    return Fd.lookAt(t), Fd.updateMatrix(), this.applyMatrix4(Fd.matrix), this;
  }
  center() {
    return this.computeBoundingBox(), this.boundingBox.getCenter(Jr).negate(), this.translate(Jr.x, Jr.y, Jr.z), this;
  }
  setFromPoints(t) {
    const e = this.getAttribute("position");
    if (e === void 0) {
      const i = [];
      for (let n = 0, s = t.length; n < s; n++) {
        const r = t[n];
        i.push(r.x, r.y, r.z || 0);
      }
      this.setAttribute("position", new wc(i, 3));
    } else {
      for (let i = 0, n = e.count; i < n; i++) {
        const s = t[i];
        e.setXYZ(i, s.x, s.y, s.z || 0);
      }
      t.length > e.count && console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."), e.needsUpdate = !0;
    }
    return this;
  }
  computeBoundingBox() {
    this.boundingBox === null && (this.boundingBox = new Us());
    const t = this.attributes.position, e = this.morphAttributes.position;
    if (t && t.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this), this.boundingBox.set(
        new tt(-1 / 0, -1 / 0, -1 / 0),
        new tt(1 / 0, 1 / 0, 1 / 0)
      );
      return;
    }
    if (t !== void 0) {
      if (this.boundingBox.setFromBufferAttribute(t), e)
        for (let i = 0, n = e.length; i < n; i++) {
          const s = e[i];
          Fi.setFromBufferAttribute(s), this.morphTargetsRelative ? (ke.addVectors(this.boundingBox.min, Fi.min), this.boundingBox.expandByPoint(ke), ke.addVectors(this.boundingBox.max, Fi.max), this.boundingBox.expandByPoint(ke)) : (this.boundingBox.expandByPoint(Fi.min), this.boundingBox.expandByPoint(Fi.max));
        }
    } else
      this.boundingBox.makeEmpty();
    (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) && console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  }
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new uu());
    const t = this.attributes.position, e = this.morphAttributes.position;
    if (t && t.isGLBufferAttribute) {
      console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this), this.boundingSphere.set(new tt(), 1 / 0);
      return;
    }
    if (t) {
      const i = this.boundingSphere.center;
      if (Fi.setFromBufferAttribute(t), e)
        for (let s = 0, r = e.length; s < r; s++) {
          const o = e[s];
          eo.setFromBufferAttribute(o), this.morphTargetsRelative ? (ke.addVectors(Fi.min, eo.min), Fi.expandByPoint(ke), ke.addVectors(Fi.max, eo.max), Fi.expandByPoint(ke)) : (Fi.expandByPoint(eo.min), Fi.expandByPoint(eo.max));
        }
      Fi.getCenter(i);
      let n = 0;
      for (let s = 0, r = t.count; s < r; s++)
        ke.fromBufferAttribute(t, s), n = Math.max(n, i.distanceToSquared(ke));
      if (e)
        for (let s = 0, r = e.length; s < r; s++) {
          const o = e[s], l = this.morphTargetsRelative;
          for (let h = 0, c = o.count; h < c; h++)
            ke.fromBufferAttribute(o, h), l && (Jr.fromBufferAttribute(t, h), ke.add(Jr)), n = Math.max(n, i.distanceToSquared(ke));
        }
      this.boundingSphere.radius = Math.sqrt(n), isNaN(this.boundingSphere.radius) && console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
    }
  }
  computeTangents() {
    const t = this.index, e = this.attributes;
    if (t === null || e.position === void 0 || e.normal === void 0 || e.uv === void 0) {
      console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");
      return;
    }
    const i = e.position, n = e.normal, s = e.uv;
    this.hasAttribute("tangent") === !1 && this.setAttribute("tangent", new qi(new Float32Array(4 * i.count), 4));
    const r = this.getAttribute("tangent"), o = [], l = [];
    for (let R = 0; R < i.count; R++)
      o[R] = new tt(), l[R] = new tt();
    const h = new tt(), c = new tt(), u = new tt(), d = new _i(), p = new _i(), f = new _i(), y = new tt(), g = new tt();
    function m(R, b, M) {
      h.fromBufferAttribute(i, R), c.fromBufferAttribute(i, b), u.fromBufferAttribute(i, M), d.fromBufferAttribute(s, R), p.fromBufferAttribute(s, b), f.fromBufferAttribute(s, M), c.sub(h), u.sub(h), p.sub(d), f.sub(d);
      const L = 1 / (p.x * f.y - f.x * p.y);
      isFinite(L) && (y.copy(c).multiplyScalar(f.y).addScaledVector(u, -p.y).multiplyScalar(L), g.copy(u).multiplyScalar(p.x).addScaledVector(c, -f.x).multiplyScalar(L), o[R].add(y), o[b].add(y), o[M].add(y), l[R].add(g), l[b].add(g), l[M].add(g));
    }
    let v = this.groups;
    v.length === 0 && (v = [{
      start: 0,
      count: t.count
    }]);
    for (let R = 0, b = v.length; R < b; ++R) {
      const M = v[R], L = M.start, U = M.count;
      for (let O = L, V = L + U; O < V; O += 3)
        m(
          t.getX(O + 0),
          t.getX(O + 1),
          t.getX(O + 2)
        );
    }
    const x = new tt(), _ = new tt(), S = new tt(), w = new tt();
    function T(R) {
      S.fromBufferAttribute(n, R), w.copy(S);
      const b = o[R];
      x.copy(b), x.sub(S.multiplyScalar(S.dot(b))).normalize(), _.crossVectors(w, b);
      const L = _.dot(l[R]) < 0 ? -1 : 1;
      r.setXYZW(R, x.x, x.y, x.z, L);
    }
    for (let R = 0, b = v.length; R < b; ++R) {
      const M = v[R], L = M.start, U = M.count;
      for (let O = L, V = L + U; O < V; O += 3)
        T(t.getX(O + 0)), T(t.getX(O + 1)), T(t.getX(O + 2));
    }
  }
  computeVertexNormals() {
    const t = this.index, e = this.getAttribute("position");
    if (e !== void 0) {
      let i = this.getAttribute("normal");
      if (i === void 0)
        i = new qi(new Float32Array(e.count * 3), 3), this.setAttribute("normal", i);
      else
        for (let d = 0, p = i.count; d < p; d++)
          i.setXYZ(d, 0, 0, 0);
      const n = new tt(), s = new tt(), r = new tt(), o = new tt(), l = new tt(), h = new tt(), c = new tt(), u = new tt();
      if (t)
        for (let d = 0, p = t.count; d < p; d += 3) {
          const f = t.getX(d + 0), y = t.getX(d + 1), g = t.getX(d + 2);
          n.fromBufferAttribute(e, f), s.fromBufferAttribute(e, y), r.fromBufferAttribute(e, g), c.subVectors(r, s), u.subVectors(n, s), c.cross(u), o.fromBufferAttribute(i, f), l.fromBufferAttribute(i, y), h.fromBufferAttribute(i, g), o.add(c), l.add(c), h.add(c), i.setXYZ(f, o.x, o.y, o.z), i.setXYZ(y, l.x, l.y, l.z), i.setXYZ(g, h.x, h.y, h.z);
        }
      else
        for (let d = 0, p = e.count; d < p; d += 3)
          n.fromBufferAttribute(e, d + 0), s.fromBufferAttribute(e, d + 1), r.fromBufferAttribute(e, d + 2), c.subVectors(r, s), u.subVectors(n, s), c.cross(u), i.setXYZ(d + 0, c.x, c.y, c.z), i.setXYZ(d + 1, c.x, c.y, c.z), i.setXYZ(d + 2, c.x, c.y, c.z);
      this.normalizeNormals(), i.needsUpdate = !0;
    }
  }
  normalizeNormals() {
    const t = this.attributes.normal;
    for (let e = 0, i = t.count; e < i; e++)
      ke.fromBufferAttribute(t, e), ke.normalize(), t.setXYZ(e, ke.x, ke.y, ke.z);
  }
  toNonIndexed() {
    function t(o, l) {
      const h = o.array, c = o.itemSize, u = o.normalized, d = new h.constructor(l.length * c);
      let p = 0, f = 0;
      for (let y = 0, g = l.length; y < g; y++) {
        o.isInterleavedBufferAttribute ? p = l[y] * o.data.stride + o.offset : p = l[y] * c;
        for (let m = 0; m < c; m++)
          d[f++] = h[p++];
      }
      return new qi(d, c, u);
    }
    if (this.index === null)
      return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."), this;
    const e = new Fa(), i = this.index.array, n = this.attributes;
    for (const o in n) {
      const l = n[o], h = t(l, i);
      e.setAttribute(o, h);
    }
    const s = this.morphAttributes;
    for (const o in s) {
      const l = [], h = s[o];
      for (let c = 0, u = h.length; c < u; c++) {
        const d = h[c], p = t(d, i);
        l.push(p);
      }
      e.morphAttributes[o] = l;
    }
    e.morphTargetsRelative = this.morphTargetsRelative;
    const r = this.groups;
    for (let o = 0, l = r.length; o < l; o++) {
      const h = r[o];
      e.addGroup(h.start, h.count, h.materialIndex);
    }
    return e;
  }
  toJSON() {
    const t = {
      metadata: {
        version: 4.6,
        type: "BufferGeometry",
        generator: "BufferGeometry.toJSON"
      }
    };
    if (t.uuid = this.uuid, t.type = this.type, this.name !== "" && (t.name = this.name), Object.keys(this.userData).length > 0 && (t.userData = this.userData), this.parameters !== void 0) {
      const l = this.parameters;
      for (const h in l)
        l[h] !== void 0 && (t[h] = l[h]);
      return t;
    }
    t.data = { attributes: {} };
    const e = this.index;
    e !== null && (t.data.index = {
      type: e.array.constructor.name,
      array: Array.prototype.slice.call(e.array)
    });
    const i = this.attributes;
    for (const l in i) {
      const h = i[l];
      t.data.attributes[l] = h.toJSON(t.data);
    }
    const n = {};
    let s = !1;
    for (const l in this.morphAttributes) {
      const h = this.morphAttributes[l], c = [];
      for (let u = 0, d = h.length; u < d; u++) {
        const p = h[u];
        c.push(p.toJSON(t.data));
      }
      c.length > 0 && (n[l] = c, s = !0);
    }
    s && (t.data.morphAttributes = n, t.data.morphTargetsRelative = this.morphTargetsRelative);
    const r = this.groups;
    r.length > 0 && (t.data.groups = JSON.parse(JSON.stringify(r)));
    const o = this.boundingSphere;
    return o !== null && (t.data.boundingSphere = {
      center: o.center.toArray(),
      radius: o.radius
    }), t;
  }
  clone() {
    return new this.constructor().copy(this);
  }
  copy(t) {
    this.index = null, this.attributes = {}, this.morphAttributes = {}, this.groups = [], this.boundingBox = null, this.boundingSphere = null;
    const e = {};
    this.name = t.name;
    const i = t.index;
    i !== null && this.setIndex(i.clone(e));
    const n = t.attributes;
    for (const h in n) {
      const c = n[h];
      this.setAttribute(h, c.clone(e));
    }
    const s = t.morphAttributes;
    for (const h in s) {
      const c = [], u = s[h];
      for (let d = 0, p = u.length; d < p; d++)
        c.push(u[d].clone(e));
      this.morphAttributes[h] = c;
    }
    this.morphTargetsRelative = t.morphTargetsRelative;
    const r = t.groups;
    for (let h = 0, c = r.length; h < c; h++) {
      const u = r[h];
      this.addGroup(u.start, u.count, u.materialIndex);
    }
    const o = t.boundingBox;
    o !== null && (this.boundingBox = o.clone());
    const l = t.boundingSphere;
    return l !== null && (this.boundingSphere = l.clone()), this.drawRange.start = t.drawRange.start, this.drawRange.count = t.drawRange.count, this.userData = t.userData, this;
  }
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
}
const qg = /* @__PURE__ */ new Qn(), tr = /* @__PURE__ */ new VT(), rh = /* @__PURE__ */ new uu(), $g = /* @__PURE__ */ new tt(), ah = /* @__PURE__ */ new tt(), oh = /* @__PURE__ */ new tt(), lh = /* @__PURE__ */ new tt(), Ud = /* @__PURE__ */ new tt(), hh = /* @__PURE__ */ new tt(), Xg = /* @__PURE__ */ new tt(), ch = /* @__PURE__ */ new tt();
class Ac extends Da {
  constructor(t = new Fa(), e = new pu()) {
    super(), this.isMesh = !0, this.type = "Mesh", this.geometry = t, this.material = e, this.updateMorphTargets();
  }
  copy(t, e) {
    return super.copy(t, e), t.morphTargetInfluences !== void 0 && (this.morphTargetInfluences = t.morphTargetInfluences.slice()), t.morphTargetDictionary !== void 0 && (this.morphTargetDictionary = Object.assign({}, t.morphTargetDictionary)), this.material = Array.isArray(t.material) ? t.material.slice() : t.material, this.geometry = t.geometry, this;
  }
  updateMorphTargets() {
    const e = this.geometry.morphAttributes, i = Object.keys(e);
    if (i.length > 0) {
      const n = e[i[0]];
      if (n !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let s = 0, r = n.length; s < r; s++) {
          const o = n[s].name || String(s);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[o] = s;
        }
      }
    }
  }
  getVertexPosition(t, e) {
    const i = this.geometry, n = i.attributes.position, s = i.morphAttributes.position, r = i.morphTargetsRelative;
    e.fromBufferAttribute(n, t);
    const o = this.morphTargetInfluences;
    if (s && o) {
      hh.set(0, 0, 0);
      for (let l = 0, h = s.length; l < h; l++) {
        const c = o[l], u = s[l];
        c !== 0 && (Ud.fromBufferAttribute(u, t), r ? hh.addScaledVector(Ud, c) : hh.addScaledVector(Ud.sub(e), c));
      }
      e.add(hh);
    }
    return e;
  }
  raycast(t, e) {
    const i = this.geometry, n = this.material, s = this.matrixWorld;
    n !== void 0 && (i.boundingSphere === null && i.computeBoundingSphere(), rh.copy(i.boundingSphere), rh.applyMatrix4(s), tr.copy(t.ray).recast(t.near), !(rh.containsPoint(tr.origin) === !1 && (tr.intersectSphere(rh, $g) === null || tr.origin.distanceToSquared($g) > (t.far - t.near) ** 2)) && (qg.copy(s).invert(), tr.copy(t.ray).applyMatrix4(qg), !(i.boundingBox !== null && tr.intersectsBox(i.boundingBox) === !1) && this._computeIntersections(t, e, tr)));
  }
  _computeIntersections(t, e, i) {
    let n;
    const s = this.geometry, r = this.material, o = s.index, l = s.attributes.position, h = s.attributes.uv, c = s.attributes.uv1, u = s.attributes.normal, d = s.groups, p = s.drawRange;
    if (o !== null)
      if (Array.isArray(r))
        for (let f = 0, y = d.length; f < y; f++) {
          const g = d[f], m = r[g.materialIndex], v = Math.max(g.start, p.start), x = Math.min(o.count, Math.min(g.start + g.count, p.start + p.count));
          for (let _ = v, S = x; _ < S; _ += 3) {
            const w = o.getX(_), T = o.getX(_ + 1), R = o.getX(_ + 2);
            n = uh(this, m, t, i, h, c, u, w, T, R), n && (n.faceIndex = Math.floor(_ / 3), n.face.materialIndex = g.materialIndex, e.push(n));
          }
        }
      else {
        const f = Math.max(0, p.start), y = Math.min(o.count, p.start + p.count);
        for (let g = f, m = y; g < m; g += 3) {
          const v = o.getX(g), x = o.getX(g + 1), _ = o.getX(g + 2);
          n = uh(this, r, t, i, h, c, u, v, x, _), n && (n.faceIndex = Math.floor(g / 3), e.push(n));
        }
      }
    else if (l !== void 0)
      if (Array.isArray(r))
        for (let f = 0, y = d.length; f < y; f++) {
          const g = d[f], m = r[g.materialIndex], v = Math.max(g.start, p.start), x = Math.min(l.count, Math.min(g.start + g.count, p.start + p.count));
          for (let _ = v, S = x; _ < S; _ += 3) {
            const w = _, T = _ + 1, R = _ + 2;
            n = uh(this, m, t, i, h, c, u, w, T, R), n && (n.faceIndex = Math.floor(_ / 3), n.face.materialIndex = g.materialIndex, e.push(n));
          }
        }
      else {
        const f = Math.max(0, p.start), y = Math.min(l.count, p.start + p.count);
        for (let g = f, m = y; g < m; g += 3) {
          const v = g, x = g + 1, _ = g + 2;
          n = uh(this, r, t, i, h, c, u, v, x, _), n && (n.faceIndex = Math.floor(g / 3), e.push(n));
        }
      }
  }
}
function QT(a, t, e, i, n, s, r, o) {
  let l;
  if (t.side === gf ? l = i.intersectTriangle(r, s, n, !0, o) : l = i.intersectTriangle(n, s, r, t.side === Bo, o), l === null) return null;
  ch.copy(o), ch.applyMatrix4(a.matrixWorld);
  const h = e.ray.origin.distanceTo(ch);
  return h < e.near || h > e.far ? null : {
    distance: h,
    point: ch.clone(),
    object: a
  };
}
function uh(a, t, e, i, n, s, r, o, l, h) {
  a.getVertexPosition(o, ah), a.getVertexPosition(l, oh), a.getVertexPosition(h, lh);
  const c = QT(a, t, e, i, ah, oh, lh, Xg);
  if (c) {
    const u = new tt();
    cn.getBarycoord(Xg, ah, oh, lh, u), n && (c.uv = cn.getInterpolatedAttribute(n, o, l, h, u, new _i())), s && (c.uv1 = cn.getInterpolatedAttribute(s, o, l, h, u, new _i())), r && (c.normal = cn.getInterpolatedAttribute(r, o, l, h, u, new tt()), c.normal.dot(i.direction) > 0 && c.normal.multiplyScalar(-1));
    const d = {
      a: o,
      b: l,
      c: h,
      normal: new tt(),
      materialIndex: 0
    };
    cn.getNormal(ah, oh, lh, d.normal), c.face = d, c.barycoord = u;
  }
  return c;
}
function vf(a) {
  const t = {};
  for (const e in a) {
    t[e] = {};
    for (const i in a[e]) {
      const n = a[e][i];
      n && (n.isColor || n.isMatrix3 || n.isMatrix4 || n.isVector2 || n.isVector3 || n.isVector4 || n.isTexture || n.isQuaternion) ? n.isRenderTargetTexture ? (console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), t[e][i] = null) : t[e][i] = n.clone() : Array.isArray(n) ? t[e][i] = n.slice() : t[e][i] = n;
    }
  }
  return t;
}
function bf(a) {
  const t = {};
  for (let e = 0; e < a.length; e++) {
    const i = vf(a[e]);
    for (const n in i)
      t[n] = i[n];
  }
  return t;
}
function tC(a) {
  const t = [];
  for (let e = 0; e < a.length; e++)
    t.push(a[e].clone());
  return t;
}
const j_ = { clone: vf, merge: bf };
var eC = `void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`, iC = `void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;
class nC extends xf {
  static get type() {
    return "ShaderMaterial";
  }
  constructor(t) {
    super(), this.isShaderMaterial = !0, this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = eC, this.fragmentShader = iC, this.linewidth = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.fog = !1, this.lights = !1, this.clipping = !1, this.forceSinglePass = !0, this.extensions = {
      clipCullDistance: !1,
      // set to use vertex shader clipping
      multiDraw: !1
      // set to use vertex shader multi_draw / enable gl_DrawID
    }, this.defaultAttributeValues = {
      color: [1, 1, 1],
      uv: [0, 0],
      uv1: [0, 0]
    }, this.index0AttributeName = void 0, this.uniformsNeedUpdate = !1, this.glslVersion = null, t !== void 0 && this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.fragmentShader = t.fragmentShader, this.vertexShader = t.vertexShader, this.uniforms = vf(t.uniforms), this.uniformsGroups = tC(t.uniformsGroups), this.defines = Object.assign({}, t.defines), this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.fog = t.fog, this.lights = t.lights, this.clipping = t.clipping, this.extensions = Object.assign({}, t.extensions), this.glslVersion = t.glslVersion, this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    e.glslVersion = this.glslVersion, e.uniforms = {};
    for (const n in this.uniforms) {
      const r = this.uniforms[n].value;
      r && r.isTexture ? e.uniforms[n] = {
        type: "t",
        value: r.toJSON(t).uuid
      } : r && r.isColor ? e.uniforms[n] = {
        type: "c",
        value: r.getHex()
      } : r && r.isVector2 ? e.uniforms[n] = {
        type: "v2",
        value: r.toArray()
      } : r && r.isVector3 ? e.uniforms[n] = {
        type: "v3",
        value: r.toArray()
      } : r && r.isVector4 ? e.uniforms[n] = {
        type: "v4",
        value: r.toArray()
      } : r && r.isMatrix3 ? e.uniforms[n] = {
        type: "m3",
        value: r.toArray()
      } : r && r.isMatrix4 ? e.uniforms[n] = {
        type: "m4",
        value: r.toArray()
      } : e.uniforms[n] = {
        value: r
      };
    }
    Object.keys(this.defines).length > 0 && (e.defines = this.defines), e.vertexShader = this.vertexShader, e.fragmentShader = this.fragmentShader, e.lights = this.lights, e.clipping = this.clipping;
    const i = {};
    for (const n in this.extensions)
      this.extensions[n] === !0 && (i[n] = !0);
    return Object.keys(i).length > 0 && (e.extensions = i), e;
  }
}
const sC = `#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
	varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
#ifdef USE_TRANSMISSION
	vWorldPosition = worldPosition.xyz;
#endif
}`, rC = `#define STANDARD
#ifdef PHYSICAL
	#define IOR
	#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
	uniform float ior;
#endif
#ifdef USE_SPECULAR
	uniform float specularIntensity;
	uniform vec3 specularColor;
	#ifdef USE_SPECULAR_COLORMAP
		uniform sampler2D specularColorMap;
	#endif
	#ifdef USE_SPECULAR_INTENSITYMAP
		uniform sampler2D specularIntensityMap;
	#endif
#endif
#ifdef USE_CLEARCOAT
	uniform float clearcoat;
	uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
	uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
	uniform float iridescence;
	uniform float iridescenceIOR;
	uniform float iridescenceThicknessMinimum;
	uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
	uniform vec3 sheenColor;
	uniform float sheenRoughness;
	#ifdef USE_SHEEN_COLORMAP
		uniform sampler2D sheenColorMap;
	#endif
	#ifdef USE_SHEEN_ROUGHNESSMAP
		uniform sampler2D sheenRoughnessMap;
	#endif
#endif
#ifdef USE_ANISOTROPY
	uniform vec2 anisotropyVector;
	#ifdef USE_ANISOTROPYMAP
		uniform sampler2D anisotropyMap;
	#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <roughnessmap_fragment>
	#include <metalnessmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <clearcoat_normal_fragment_begin>
	#include <clearcoat_normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_physical_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
	#include <transmission_fragment>
	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
	#ifdef USE_SHEEN
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
	#endif
	#ifdef USE_CLEARCOAT
		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
	#endif
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`, Yg = {
  meshphysical_vert: sC,
  meshphysical_frag: rC
}, si = {
  common: {
    diffuse: { value: /* @__PURE__ */ new Ai(16777215) },
    opacity: { value: 1 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new de() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new de() },
    alphaTest: { value: 0 }
  },
  envmap: {
    envMap: { value: null },
    envMapRotation: { value: /* @__PURE__ */ new de() },
    flipEnvMap: { value: -1 },
    reflectivity: { value: 1 },
    // basic, lambert, phong
    ior: { value: 1.5 },
    // physical
    refractionRatio: { value: 0.98 }
    // basic, lambert, phong
  },
  aomap: {
    aoMap: { value: null },
    aoMapIntensity: { value: 1 },
    aoMapTransform: { value: /* @__PURE__ */ new de() }
  },
  lightmap: {
    lightMap: { value: null },
    lightMapIntensity: { value: 1 },
    lightMapTransform: { value: /* @__PURE__ */ new de() }
  },
  bumpmap: {
    bumpMap: { value: null },
    bumpMapTransform: { value: /* @__PURE__ */ new de() },
    bumpScale: { value: 1 }
  },
  normalmap: {
    normalMap: { value: null },
    normalMapTransform: { value: /* @__PURE__ */ new de() },
    normalScale: { value: /* @__PURE__ */ new _i(1, 1) }
  },
  displacementmap: {
    displacementMap: { value: null },
    displacementMapTransform: { value: /* @__PURE__ */ new de() },
    displacementScale: { value: 1 },
    displacementBias: { value: 0 }
  },
  emissivemap: {
    emissiveMap: { value: null },
    emissiveMapTransform: { value: /* @__PURE__ */ new de() }
  },
  metalnessmap: {
    metalnessMap: { value: null },
    metalnessMapTransform: { value: /* @__PURE__ */ new de() }
  },
  roughnessmap: {
    roughnessMap: { value: null },
    roughnessMapTransform: { value: /* @__PURE__ */ new de() }
  },
  fog: {
    fogDensity: { value: 25e-5 },
    fogNear: { value: 1 },
    fogFar: { value: 2e3 },
    fogColor: { value: /* @__PURE__ */ new Ai(16777215) }
  },
  lights: {
    ambientLightColor: { value: [] },
    lightProbe: { value: [] },
    directionalLights: { value: [], properties: {
      direction: {},
      color: {}
    } },
    directionalLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    directionalShadowMap: { value: [] },
    directionalShadowMatrix: { value: [] },
    spotLights: { value: [], properties: {
      color: {},
      position: {},
      direction: {},
      distance: {},
      coneCos: {},
      penumbraCos: {},
      decay: {}
    } },
    spotLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    spotLightMap: { value: [] },
    spotShadowMap: { value: [] },
    spotLightMatrix: { value: [] },
    pointLights: { value: [], properties: {
      color: {},
      position: {},
      decay: {},
      distance: {}
    } },
    pointLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {},
      shadowCameraNear: {},
      shadowCameraFar: {}
    } },
    pointShadowMap: { value: [] },
    pointShadowMatrix: { value: [] },
    hemisphereLights: { value: [], properties: {
      direction: {},
      skyColor: {},
      groundColor: {}
    } },
    // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
    rectAreaLights: { value: [], properties: {
      color: {},
      position: {},
      width: {},
      height: {}
    } },
    ltc_1: { value: null },
    ltc_2: { value: null }
  }
}, ca = {
  standard: {
    uniforms: /* @__PURE__ */ bf([
      si.common,
      si.envmap,
      si.aomap,
      si.lightmap,
      si.emissivemap,
      si.bumpmap,
      si.normalmap,
      si.displacementmap,
      si.roughnessmap,
      si.metalnessmap,
      si.fog,
      si.lights,
      {
        emissive: { value: /* @__PURE__ */ new Ai(0) },
        roughness: { value: 1 },
        metalness: { value: 0 },
        envMapIntensity: { value: 1 }
      }
    ])
  }
};
ca.physical = {
  uniforms: /* @__PURE__ */ bf([
    ca.standard.uniforms,
    {
      clearcoat: { value: 0 },
      clearcoatMap: { value: null },
      clearcoatMapTransform: { value: /* @__PURE__ */ new de() },
      clearcoatNormalMap: { value: null },
      clearcoatNormalMapTransform: { value: /* @__PURE__ */ new de() },
      clearcoatNormalScale: { value: /* @__PURE__ */ new _i(1, 1) },
      clearcoatRoughness: { value: 0 },
      clearcoatRoughnessMap: { value: null },
      clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new de() },
      dispersion: { value: 0 },
      iridescence: { value: 0 },
      iridescenceMap: { value: null },
      iridescenceMapTransform: { value: /* @__PURE__ */ new de() },
      iridescenceIOR: { value: 1.3 },
      iridescenceThicknessMinimum: { value: 100 },
      iridescenceThicknessMaximum: { value: 400 },
      iridescenceThicknessMap: { value: null },
      iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new de() },
      sheen: { value: 0 },
      sheenColor: { value: /* @__PURE__ */ new Ai(0) },
      sheenColorMap: { value: null },
      sheenColorMapTransform: { value: /* @__PURE__ */ new de() },
      sheenRoughness: { value: 1 },
      sheenRoughnessMap: { value: null },
      sheenRoughnessMapTransform: { value: /* @__PURE__ */ new de() },
      transmission: { value: 0 },
      transmissionMap: { value: null },
      transmissionMapTransform: { value: /* @__PURE__ */ new de() },
      transmissionSamplerSize: { value: /* @__PURE__ */ new _i() },
      transmissionSamplerMap: { value: null },
      thickness: { value: 0 },
      thicknessMap: { value: null },
      thicknessMapTransform: { value: /* @__PURE__ */ new de() },
      attenuationDistance: { value: 0 },
      attenuationColor: { value: /* @__PURE__ */ new Ai(0) },
      specularColor: { value: /* @__PURE__ */ new Ai(1, 1, 1) },
      specularColorMap: { value: null },
      specularColorMapTransform: { value: /* @__PURE__ */ new de() },
      specularIntensity: { value: 1 },
      specularIntensityMap: { value: null },
      specularIntensityMapTransform: { value: /* @__PURE__ */ new de() },
      anisotropyVector: { value: /* @__PURE__ */ new _i() },
      anisotropyMap: { value: null },
      anisotropyMapTransform: { value: /* @__PURE__ */ new de() }
    }
  ]),
  vertexShader: Yg.meshphysical_vert,
  fragmentShader: Yg.meshphysical_frag
};
let aC = class extends Da {
  constructor() {
    super(), this.isGroup = !0, this.type = "Group";
  }
};
class oC {
  constructor(t, e) {
    this.isInterleavedBuffer = !0, this.array = t, this.stride = e, this.count = t !== void 0 ? t.length / e : 0, this.usage = xp, this.updateRanges = [], this.version = 0, this.uuid = Jn();
  }
  onUploadCallback() {
  }
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  setUsage(t) {
    return this.usage = t, this;
  }
  addUpdateRange(t, e) {
    this.updateRanges.push({ start: t, count: e });
  }
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  copy(t) {
    return this.array = new t.array.constructor(t.array), this.count = t.count, this.stride = t.stride, this.usage = t.usage, this;
  }
  copyAt(t, e, i) {
    t *= this.stride, i *= e.stride;
    for (let n = 0, s = this.stride; n < s; n++)
      this.array[t + n] = e.array[i + n];
    return this;
  }
  set(t, e = 0) {
    return this.array.set(t, e), this;
  }
  clone(t) {
    t.arrayBuffers === void 0 && (t.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = Jn()), t.arrayBuffers[this.array.buffer._uuid] === void 0 && (t.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer);
    const e = new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]), i = new this.constructor(e, this.stride);
    return i.setUsage(this.usage), i;
  }
  onUpload(t) {
    return this.onUploadCallback = t, this;
  }
  toJSON(t) {
    return t.arrayBuffers === void 0 && (t.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = Jn()), t.arrayBuffers[this.array.buffer._uuid] === void 0 && (t.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer))), {
      uuid: this.uuid,
      buffer: this.array.buffer._uuid,
      type: this.array.constructor.name,
      stride: this.stride
    };
  }
}
const di = /* @__PURE__ */ new tt();
class Ss {
  constructor(t, e, i, n = !1) {
    this.isInterleavedBufferAttribute = !0, this.name = "", this.data = t, this.itemSize = e, this.offset = i, this.normalized = n;
  }
  get count() {
    return this.data.count;
  }
  get array() {
    return this.data.array;
  }
  set needsUpdate(t) {
    this.data.needsUpdate = t;
  }
  applyMatrix4(t) {
    for (let e = 0, i = this.data.count; e < i; e++)
      di.fromBufferAttribute(this, e), di.applyMatrix4(t), this.setXYZ(e, di.x, di.y, di.z);
    return this;
  }
  applyNormalMatrix(t) {
    for (let e = 0, i = this.count; e < i; e++)
      di.fromBufferAttribute(this, e), di.applyNormalMatrix(t), this.setXYZ(e, di.x, di.y, di.z);
    return this;
  }
  transformDirection(t) {
    for (let e = 0, i = this.count; e < i; e++)
      di.fromBufferAttribute(this, e), di.transformDirection(t), this.setXYZ(e, di.x, di.y, di.z);
    return this;
  }
  getComponent(t, e) {
    let i = this.array[t * this.data.stride + this.offset + e];
    return this.normalized && (i = hn(i, this.array)), i;
  }
  setComponent(t, e, i) {
    return this.normalized && (i = ue(i, this.array)), this.data.array[t * this.data.stride + this.offset + e] = i, this;
  }
  setX(t, e) {
    return this.normalized && (e = ue(e, this.array)), this.data.array[t * this.data.stride + this.offset] = e, this;
  }
  setY(t, e) {
    return this.normalized && (e = ue(e, this.array)), this.data.array[t * this.data.stride + this.offset + 1] = e, this;
  }
  setZ(t, e) {
    return this.normalized && (e = ue(e, this.array)), this.data.array[t * this.data.stride + this.offset + 2] = e, this;
  }
  setW(t, e) {
    return this.normalized && (e = ue(e, this.array)), this.data.array[t * this.data.stride + this.offset + 3] = e, this;
  }
  getX(t) {
    let e = this.data.array[t * this.data.stride + this.offset];
    return this.normalized && (e = hn(e, this.array)), e;
  }
  getY(t) {
    let e = this.data.array[t * this.data.stride + this.offset + 1];
    return this.normalized && (e = hn(e, this.array)), e;
  }
  getZ(t) {
    let e = this.data.array[t * this.data.stride + this.offset + 2];
    return this.normalized && (e = hn(e, this.array)), e;
  }
  getW(t) {
    let e = this.data.array[t * this.data.stride + this.offset + 3];
    return this.normalized && (e = hn(e, this.array)), e;
  }
  setXY(t, e, i) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = ue(e, this.array), i = ue(i, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = i, this;
  }
  setXYZ(t, e, i, n) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = ue(e, this.array), i = ue(i, this.array), n = ue(n, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = i, this.data.array[t + 2] = n, this;
  }
  setXYZW(t, e, i, n, s) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = ue(e, this.array), i = ue(i, this.array), n = ue(n, this.array), s = ue(s, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = i, this.data.array[t + 2] = n, this.data.array[t + 3] = s, this;
  }
  clone(t) {
    if (t === void 0) {
      console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");
      const e = [];
      for (let i = 0; i < this.count; i++) {
        const n = i * this.data.stride + this.offset;
        for (let s = 0; s < this.itemSize; s++)
          e.push(this.data.array[n + s]);
      }
      return new qi(new this.array.constructor(e), this.itemSize, this.normalized);
    } else
      return t.interleavedBuffers === void 0 && (t.interleavedBuffers = {}), t.interleavedBuffers[this.data.uuid] === void 0 && (t.interleavedBuffers[this.data.uuid] = this.data.clone(t)), new Ss(t.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  }
  toJSON(t) {
    if (t === void 0) {
      console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");
      const e = [];
      for (let i = 0; i < this.count; i++) {
        const n = i * this.data.stride + this.offset;
        for (let s = 0; s < this.itemSize; s++)
          e.push(this.data.array[n + s]);
      }
      return {
        itemSize: this.itemSize,
        type: this.array.constructor.name,
        array: e,
        normalized: this.normalized
      };
    } else
      return t.interleavedBuffers === void 0 && (t.interleavedBuffers = {}), t.interleavedBuffers[this.data.uuid] === void 0 && (t.interleavedBuffers[this.data.uuid] = this.data.toJSON(t)), {
        isInterleavedBufferAttribute: !0,
        itemSize: this.itemSize,
        data: this.data.uuid,
        offset: this.offset,
        normalized: this.normalized
      };
  }
}
class lC extends Fa {
  constructor(t = null) {
    if (super(), this.type = "WireframeGeometry", this.parameters = {
      geometry: t
    }, t !== null) {
      const e = [], i = /* @__PURE__ */ new Set(), n = new tt(), s = new tt();
      if (t.index !== null) {
        const r = t.attributes.position, o = t.index;
        let l = t.groups;
        l.length === 0 && (l = [{ start: 0, count: o.count, materialIndex: 0 }]);
        for (let h = 0, c = l.length; h < c; ++h) {
          const u = l[h], d = u.start, p = u.count;
          for (let f = d, y = d + p; f < y; f += 3)
            for (let g = 0; g < 3; g++) {
              const m = o.getX(f + g), v = o.getX(f + (g + 1) % 3);
              n.fromBufferAttribute(r, m), s.fromBufferAttribute(r, v), Zg(n, s, i) === !0 && (e.push(n.x, n.y, n.z), e.push(s.x, s.y, s.z));
            }
        }
      } else {
        const r = t.attributes.position;
        for (let o = 0, l = r.count / 3; o < l; o++)
          for (let h = 0; h < 3; h++) {
            const c = 3 * o + h, u = 3 * o + (h + 1) % 3;
            n.fromBufferAttribute(r, c), s.fromBufferAttribute(r, u), Zg(n, s, i) === !0 && (e.push(n.x, n.y, n.z), e.push(s.x, s.y, s.z));
          }
      }
      this.setAttribute("position", new wc(e, 3));
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
}
function Zg(a, t, e) {
  const i = `${a.x},${a.y},${a.z}-${t.x},${t.y},${t.z}`, n = `${t.x},${t.y},${t.z}-${a.x},${a.y},${a.z}`;
  return e.has(i) === !0 || e.has(n) === !0 ? !1 : (e.add(i), e.add(n), !0);
}
class hC extends xf {
  static get type() {
    return "MeshStandardMaterial";
  }
  constructor(t) {
    super(), this.isMeshStandardMaterial = !0, this.defines = { STANDARD: "" }, this.color = new Ai(16777215), this.roughness = 1, this.metalness = 0, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new Ai(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = yT, this.normalScale = new _i(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.roughnessMap = null, this.metalnessMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new du(), this.envMapIntensity = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(t);
  }
  copy(t) {
    return super.copy(t), this.defines = { STANDARD: "" }, this.color.copy(t.color), this.roughness = t.roughness, this.metalness = t.metalness, this.map = t.map, this.lightMap = t.lightMap, this.lightMapIntensity = t.lightMapIntensity, this.aoMap = t.aoMap, this.aoMapIntensity = t.aoMapIntensity, this.emissive.copy(t.emissive), this.emissiveMap = t.emissiveMap, this.emissiveIntensity = t.emissiveIntensity, this.bumpMap = t.bumpMap, this.bumpScale = t.bumpScale, this.normalMap = t.normalMap, this.normalMapType = t.normalMapType, this.normalScale.copy(t.normalScale), this.displacementMap = t.displacementMap, this.displacementScale = t.displacementScale, this.displacementBias = t.displacementBias, this.roughnessMap = t.roughnessMap, this.metalnessMap = t.metalnessMap, this.alphaMap = t.alphaMap, this.envMap = t.envMap, this.envMapRotation.copy(t.envMapRotation), this.envMapIntensity = t.envMapIntensity, this.wireframe = t.wireframe, this.wireframeLinewidth = t.wireframeLinewidth, this.wireframeLinecap = t.wireframeLinecap, this.wireframeLinejoin = t.wireframeLinejoin, this.flatShading = t.flatShading, this.fog = t.fog, this;
  }
}
class cC extends Fa {
  constructor() {
    super(), this.isInstancedBufferGeometry = !0, this.type = "InstancedBufferGeometry", this.instanceCount = 1 / 0;
  }
  copy(t) {
    return super.copy(t), this.instanceCount = t.instanceCount, this;
  }
  toJSON() {
    const t = super.toJSON();
    return t.instanceCount = this.instanceCount, t.isInstancedBufferGeometry = !0, t;
  }
}
class bp extends oC {
  constructor(t, e, i = 1) {
    super(t, e), this.isInstancedInterleavedBuffer = !0, this.meshPerAttribute = i;
  }
  copy(t) {
    return super.copy(t), this.meshPerAttribute = t.meshPerAttribute, this;
  }
  clone(t) {
    const e = super.clone(t);
    return e.meshPerAttribute = this.meshPerAttribute, e;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.isInstancedInterleavedBuffer = !0, e.meshPerAttribute = this.meshPerAttribute, e;
  }
}
const jg = /* @__PURE__ */ new tt(), dh = /* @__PURE__ */ new tt();
class uC {
  constructor(t = new tt(), e = new tt()) {
    this.start = t, this.end = e;
  }
  set(t, e) {
    return this.start.copy(t), this.end.copy(e), this;
  }
  copy(t) {
    return this.start.copy(t.start), this.end.copy(t.end), this;
  }
  getCenter(t) {
    return t.addVectors(this.start, this.end).multiplyScalar(0.5);
  }
  delta(t) {
    return t.subVectors(this.end, this.start);
  }
  distanceSq() {
    return this.start.distanceToSquared(this.end);
  }
  distance() {
    return this.start.distanceTo(this.end);
  }
  at(t, e) {
    return this.delta(e).multiplyScalar(t).add(this.start);
  }
  closestPointToPointParameter(t, e) {
    jg.subVectors(t, this.start), dh.subVectors(this.end, this.start);
    const i = dh.dot(dh);
    let s = dh.dot(jg) / i;
    return e && (s = ai(s, 0, 1)), s;
  }
  closestPointToPoint(t, e, i) {
    const n = this.closestPointToPointParameter(t, e);
    return this.delta(i).multiplyScalar(n).add(this.start);
  }
  applyMatrix4(t) {
    return this.start.applyMatrix4(t), this.end.applyMatrix4(t), this;
  }
  equals(t) {
    return t.start.equals(this.start) && t.end.equals(this.end);
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: {
  revision: N_
} }));
typeof window < "u" && (window.__THREE__ ? console.warn("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = N_);
/**
 * @license
 * Copyright 2010-2025 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
const J_ = "180", K_ = 300, Jg = 1e3, ph = 1001, Kg = 1002, dC = 1006, pC = 1008, fC = 1009, mC = 1023, Q_ = "", on = "srgb", Qg = "srgb-linear", t0 = "linear", Bd = "srgb", fh = 2e3, e0 = 2001;
class tx {
  /**
   * Adds the given event listener to the given event type.
   *
   * @param {string} type - The type of event to listen to.
   * @param {Function} listener - The function that gets called when the event is fired.
   */
  addEventListener(t, e) {
    this._listeners === void 0 && (this._listeners = {});
    const i = this._listeners;
    i[t] === void 0 && (i[t] = []), i[t].indexOf(e) === -1 && i[t].push(e);
  }
  /**
   * Returns `true` if the given event listener has been added to the given event type.
   *
   * @param {string} type - The type of event.
   * @param {Function} listener - The listener to check.
   * @return {boolean} Whether the given event listener has been added to the given event type.
   */
  hasEventListener(t, e) {
    const i = this._listeners;
    return i === void 0 ? !1 : i[t] !== void 0 && i[t].indexOf(e) !== -1;
  }
  /**
   * Removes the given event listener from the given event type.
   *
   * @param {string} type - The type of event.
   * @param {Function} listener - The listener to remove.
   */
  removeEventListener(t, e) {
    const i = this._listeners;
    if (i === void 0) return;
    const n = i[t];
    if (n !== void 0) {
      const s = n.indexOf(e);
      s !== -1 && n.splice(s, 1);
    }
  }
  /**
   * Dispatches an event object.
   *
   * @param {Object} event - The event that gets fired.
   */
  dispatchEvent(t) {
    const e = this._listeners;
    if (e === void 0) return;
    const i = e[t.type];
    if (i !== void 0) {
      t.target = this;
      const n = i.slice(0);
      for (let s = 0, r = n.length; s < r; s++)
        n[s].call(this, t);
      t.target = null;
    }
  }
}
const ii = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"];
function Mf() {
  const a = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, e = Math.random() * 4294967295 | 0, i = Math.random() * 4294967295 | 0;
  return (ii[a & 255] + ii[a >> 8 & 255] + ii[a >> 16 & 255] + ii[a >> 24 & 255] + "-" + ii[t & 255] + ii[t >> 8 & 255] + "-" + ii[t >> 16 & 15 | 64] + ii[t >> 24 & 255] + "-" + ii[e & 63 | 128] + ii[e >> 8 & 255] + "-" + ii[e >> 16 & 255] + ii[e >> 24 & 255] + ii[i & 255] + ii[i >> 8 & 255] + ii[i >> 16 & 255] + ii[i >> 24 & 255]).toLowerCase();
}
function ye(a, t, e) {
  return Math.max(t, Math.min(e, a));
}
function gC(a, t) {
  return (a % t + t) % t;
}
function zd(a, t, e) {
  return (1 - e) * a + e * t;
}
class _o {
  /**
   * Constructs a new 2D vector.
   *
   * @param {number} [x=0] - The x value of this vector.
   * @param {number} [y=0] - The y value of this vector.
   */
  constructor(t = 0, e = 0) {
    _o.prototype.isVector2 = !0, this.x = t, this.y = e;
  }
  /**
   * Alias for {@link Vector2#x}.
   *
   * @type {number}
   */
  get width() {
    return this.x;
  }
  set width(t) {
    this.x = t;
  }
  /**
   * Alias for {@link Vector2#y}.
   *
   * @type {number}
   */
  get height() {
    return this.y;
  }
  set height(t) {
    this.y = t;
  }
  /**
   * Sets the vector components.
   *
   * @param {number} x - The value of the x component.
   * @param {number} y - The value of the y component.
   * @return {Vector2} A reference to this vector.
   */
  set(t, e) {
    return this.x = t, this.y = e, this;
  }
  /**
   * Sets the vector components to the same value.
   *
   * @param {number} scalar - The value to set for all vector components.
   * @return {Vector2} A reference to this vector.
   */
  setScalar(t) {
    return this.x = t, this.y = t, this;
  }
  /**
   * Sets the vector's x component to the given value
   *
   * @param {number} x - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setX(t) {
    return this.x = t, this;
  }
  /**
   * Sets the vector's y component to the given value
   *
   * @param {number} y - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setY(t) {
    return this.y = t, this;
  }
  /**
   * Allows to set a vector component with an index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y.
   * @param {number} value - The value to set.
   * @return {Vector2} A reference to this vector.
   */
  setComponent(t, e) {
    switch (t) {
      case 0:
        this.x = e;
        break;
      case 1:
        this.y = e;
        break;
      default:
        throw new Error("index is out of range: " + t);
    }
    return this;
  }
  /**
   * Returns the value of the vector component which matches the given index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y.
   * @return {number} A vector component value.
   */
  getComponent(t) {
    switch (t) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      default:
        throw new Error("index is out of range: " + t);
    }
  }
  /**
   * Returns a new vector with copied values from this instance.
   *
   * @return {Vector2} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.x, this.y);
  }
  /**
   * Copies the values of the given vector to this instance.
   *
   * @param {Vector2} v - The vector to copy.
   * @return {Vector2} A reference to this vector.
   */
  copy(t) {
    return this.x = t.x, this.y = t.y, this;
  }
  /**
   * Adds the given vector to this instance.
   *
   * @param {Vector2} v - The vector to add.
   * @return {Vector2} A reference to this vector.
   */
  add(t) {
    return this.x += t.x, this.y += t.y, this;
  }
  /**
   * Adds the given scalar value to all components of this instance.
   *
   * @param {number} s - The scalar to add.
   * @return {Vector2} A reference to this vector.
   */
  addScalar(t) {
    return this.x += t, this.y += t, this;
  }
  /**
   * Adds the given vectors and stores the result in this instance.
   *
   * @param {Vector2} a - The first vector.
   * @param {Vector2} b - The second vector.
   * @return {Vector2} A reference to this vector.
   */
  addVectors(t, e) {
    return this.x = t.x + e.x, this.y = t.y + e.y, this;
  }
  /**
   * Adds the given vector scaled by the given factor to this instance.
   *
   * @param {Vector2} v - The vector.
   * @param {number} s - The factor that scales `v`.
   * @return {Vector2} A reference to this vector.
   */
  addScaledVector(t, e) {
    return this.x += t.x * e, this.y += t.y * e, this;
  }
  /**
   * Subtracts the given vector from this instance.
   *
   * @param {Vector2} v - The vector to subtract.
   * @return {Vector2} A reference to this vector.
   */
  sub(t) {
    return this.x -= t.x, this.y -= t.y, this;
  }
  /**
   * Subtracts the given scalar value from all components of this instance.
   *
   * @param {number} s - The scalar to subtract.
   * @return {Vector2} A reference to this vector.
   */
  subScalar(t) {
    return this.x -= t, this.y -= t, this;
  }
  /**
   * Subtracts the given vectors and stores the result in this instance.
   *
   * @param {Vector2} a - The first vector.
   * @param {Vector2} b - The second vector.
   * @return {Vector2} A reference to this vector.
   */
  subVectors(t, e) {
    return this.x = t.x - e.x, this.y = t.y - e.y, this;
  }
  /**
   * Multiplies the given vector with this instance.
   *
   * @param {Vector2} v - The vector to multiply.
   * @return {Vector2} A reference to this vector.
   */
  multiply(t) {
    return this.x *= t.x, this.y *= t.y, this;
  }
  /**
   * Multiplies the given scalar value with all components of this instance.
   *
   * @param {number} scalar - The scalar to multiply.
   * @return {Vector2} A reference to this vector.
   */
  multiplyScalar(t) {
    return this.x *= t, this.y *= t, this;
  }
  /**
   * Divides this instance by the given vector.
   *
   * @param {Vector2} v - The vector to divide.
   * @return {Vector2} A reference to this vector.
   */
  divide(t) {
    return this.x /= t.x, this.y /= t.y, this;
  }
  /**
   * Divides this vector by the given scalar.
   *
   * @param {number} scalar - The scalar to divide.
   * @return {Vector2} A reference to this vector.
   */
  divideScalar(t) {
    return this.multiplyScalar(1 / t);
  }
  /**
   * Multiplies this vector (with an implicit 1 as the 3rd component) by
   * the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to apply.
   * @return {Vector2} A reference to this vector.
   */
  applyMatrix3(t) {
    const e = this.x, i = this.y, n = t.elements;
    return this.x = n[0] * e + n[3] * i + n[6], this.y = n[1] * e + n[4] * i + n[7], this;
  }
  /**
   * If this vector's x or y value is greater than the given vector's x or y
   * value, replace that value with the corresponding min value.
   *
   * @param {Vector2} v - The vector.
   * @return {Vector2} A reference to this vector.
   */
  min(t) {
    return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this;
  }
  /**
   * If this vector's x or y value is less than the given vector's x or y
   * value, replace that value with the corresponding max value.
   *
   * @param {Vector2} v - The vector.
   * @return {Vector2} A reference to this vector.
   */
  max(t) {
    return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this;
  }
  /**
   * If this vector's x or y value is greater than the max vector's x or y
   * value, it is replaced by the corresponding value.
   * If this vector's x or y value is less than the min vector's x or y value,
   * it is replaced by the corresponding value.
   *
   * @param {Vector2} min - The minimum x and y values.
   * @param {Vector2} max - The maximum x and y values in the desired range.
   * @return {Vector2} A reference to this vector.
   */
  clamp(t, e) {
    return this.x = ye(this.x, t.x, e.x), this.y = ye(this.y, t.y, e.y), this;
  }
  /**
   * If this vector's x or y values are greater than the max value, they are
   * replaced by the max value.
   * If this vector's x or y values are less than the min value, they are
   * replaced by the min value.
   *
   * @param {number} minVal - The minimum value the components will be clamped to.
   * @param {number} maxVal - The maximum value the components will be clamped to.
   * @return {Vector2} A reference to this vector.
   */
  clampScalar(t, e) {
    return this.x = ye(this.x, t, e), this.y = ye(this.y, t, e), this;
  }
  /**
   * If this vector's length is greater than the max value, it is replaced by
   * the max value.
   * If this vector's length is less than the min value, it is replaced by the
   * min value.
   *
   * @param {number} min - The minimum value the vector length will be clamped to.
   * @param {number} max - The maximum value the vector length will be clamped to.
   * @return {Vector2} A reference to this vector.
   */
  clampLength(t, e) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(ye(i, t, e));
  }
  /**
   * The components of this vector are rounded down to the nearest integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this;
  }
  /**
   * The components of this vector are rounded up to the nearest integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this;
  }
  /**
   * The components of this vector are rounded to the nearest integer value
   *
   * @return {Vector2} A reference to this vector.
   */
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this;
  }
  /**
   * The components of this vector are rounded towards zero (up if negative,
   * down if positive) to an integer value.
   *
   * @return {Vector2} A reference to this vector.
   */
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this;
  }
  /**
   * Inverts this vector - i.e. sets x = -x and y = -y.
   *
   * @return {Vector2} A reference to this vector.
   */
  negate() {
    return this.x = -this.x, this.y = -this.y, this;
  }
  /**
   * Calculates the dot product of the given vector with this instance.
   *
   * @param {Vector2} v - The vector to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(t) {
    return this.x * t.x + this.y * t.y;
  }
  /**
   * Calculates the cross product of the given vector with this instance.
   *
   * @param {Vector2} v - The vector to compute the cross product with.
   * @return {number} The result of the cross product.
   */
  cross(t) {
    return this.x * t.y - this.y * t.x;
  }
  /**
   * Computes the square of the Euclidean length (straight-line length) from
   * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
   * compare the length squared instead as it is slightly more efficient to calculate.
   *
   * @return {number} The square length of this vector.
   */
  lengthSq() {
    return this.x * this.x + this.y * this.y;
  }
  /**
   * Computes the  Euclidean length (straight-line length) from (0, 0) to (x, y).
   *
   * @return {number} The length of this vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
  /**
   * Computes the Manhattan length of this vector.
   *
   * @return {number} The length of this vector.
   */
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y);
  }
  /**
   * Converts this vector to a unit vector - that is, sets it equal to a vector
   * with the same direction as this one, but with a vector length of `1`.
   *
   * @return {Vector2} A reference to this vector.
   */
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  /**
   * Computes the angle in radians of this vector with respect to the positive x-axis.
   *
   * @return {number} The angle in radians.
   */
  angle() {
    return Math.atan2(-this.y, -this.x) + Math.PI;
  }
  /**
   * Returns the angle between the given vector and this instance in radians.
   *
   * @param {Vector2} v - The vector to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(t) {
    const e = Math.sqrt(this.lengthSq() * t.lengthSq());
    if (e === 0) return Math.PI / 2;
    const i = this.dot(t) / e;
    return Math.acos(ye(i, -1, 1));
  }
  /**
   * Computes the distance from the given vector to this instance.
   *
   * @param {Vector2} v - The vector to compute the distance to.
   * @return {number} The distance.
   */
  distanceTo(t) {
    return Math.sqrt(this.distanceToSquared(t));
  }
  /**
   * Computes the squared distance from the given vector to this instance.
   * If you are just comparing the distance with another distance, you should compare
   * the distance squared instead as it is slightly more efficient to calculate.
   *
   * @param {Vector2} v - The vector to compute the squared distance to.
   * @return {number} The squared distance.
   */
  distanceToSquared(t) {
    const e = this.x - t.x, i = this.y - t.y;
    return e * e + i * i;
  }
  /**
   * Computes the Manhattan distance from the given vector to this instance.
   *
   * @param {Vector2} v - The vector to compute the Manhattan distance to.
   * @return {number} The Manhattan distance.
   */
  manhattanDistanceTo(t) {
    return Math.abs(this.x - t.x) + Math.abs(this.y - t.y);
  }
  /**
   * Sets this vector to a vector with the same direction as this one, but
   * with the specified length.
   *
   * @param {number} length - The new length of this vector.
   * @return {Vector2} A reference to this vector.
   */
  setLength(t) {
    return this.normalize().multiplyScalar(t);
  }
  /**
   * Linearly interpolates between the given vector and this instance, where
   * alpha is the percent distance along the line - alpha = 0 will be this
   * vector, and alpha = 1 will be the given one.
   *
   * @param {Vector2} v - The vector to interpolate towards.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector2} A reference to this vector.
   */
  lerp(t, e) {
    return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this;
  }
  /**
   * Linearly interpolates between the given vectors, where alpha is the percent
   * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
   * be the second one. The result is stored in this instance.
   *
   * @param {Vector2} v1 - The first vector.
   * @param {Vector2} v2 - The second vector.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector2} A reference to this vector.
   */
  lerpVectors(t, e, i) {
    return this.x = t.x + (e.x - t.x) * i, this.y = t.y + (e.y - t.y) * i, this;
  }
  /**
   * Returns `true` if this vector is equal with the given one.
   *
   * @param {Vector2} v - The vector to test for equality.
   * @return {boolean} Whether this vector is equal with the given one.
   */
  equals(t) {
    return t.x === this.x && t.y === this.y;
  }
  /**
   * Sets this vector's x value to be `array[ offset ]` and y
   * value to be `array[ offset + 1 ]`.
   *
   * @param {Array<number>} array - An array holding the vector component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Vector2} A reference to this vector.
   */
  fromArray(t, e = 0) {
    return this.x = t[e], this.y = t[e + 1], this;
  }
  /**
   * Writes the components of this vector to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the vector components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The vector components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this.x, t[e + 1] = this.y, t;
  }
  /**
   * Sets the components of this vector from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
   * @param {number} index - The index into the attribute.
   * @return {Vector2} A reference to this vector.
   */
  fromBufferAttribute(t, e) {
    return this.x = t.getX(e), this.y = t.getY(e), this;
  }
  /**
   * Rotates this vector around the given center by the given angle.
   *
   * @param {Vector2} center - The point around which to rotate.
   * @param {number} angle - The angle to rotate, in radians.
   * @return {Vector2} A reference to this vector.
   */
  rotateAround(t, e) {
    const i = Math.cos(e), n = Math.sin(e), s = this.x - t.x, r = this.y - t.y;
    return this.x = s * i - r * n + t.x, this.y = s * n + r * i + t.y, this;
  }
  /**
   * Sets each component of this vector to a pseudo-random value between `0` and
   * `1`, excluding `1`.
   *
   * @return {Vector2} A reference to this vector.
   */
  random() {
    return this.x = Math.random(), this.y = Math.random(), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y;
  }
}
class $o {
  /**
   * Constructs a new quaternion.
   *
   * @param {number} [x=0] - The x value of this quaternion.
   * @param {number} [y=0] - The y value of this quaternion.
   * @param {number} [z=0] - The z value of this quaternion.
   * @param {number} [w=1] - The w value of this quaternion.
   */
  constructor(t = 0, e = 0, i = 0, n = 1) {
    this.isQuaternion = !0, this._x = t, this._y = e, this._z = i, this._w = n;
  }
  /**
   * Interpolates between two quaternions via SLERP. This implementation assumes the
   * quaternion data are managed  in flat arrays.
   *
   * @param {Array<number>} dst - The destination array.
   * @param {number} dstOffset - An offset into the destination array.
   * @param {Array<number>} src0 - The source array of the first quaternion.
   * @param {number} srcOffset0 - An offset into the first source array.
   * @param {Array<number>} src1 -  The source array of the second quaternion.
   * @param {number} srcOffset1 - An offset into the second source array.
   * @param {number} t - The interpolation factor in the range `[0,1]`.
   * @see {@link Quaternion#slerp}
   */
  static slerpFlat(t, e, i, n, s, r, o) {
    let l = i[n + 0], h = i[n + 1], c = i[n + 2], u = i[n + 3];
    const d = s[r + 0], p = s[r + 1], f = s[r + 2], y = s[r + 3];
    if (o === 0) {
      t[e + 0] = l, t[e + 1] = h, t[e + 2] = c, t[e + 3] = u;
      return;
    }
    if (o === 1) {
      t[e + 0] = d, t[e + 1] = p, t[e + 2] = f, t[e + 3] = y;
      return;
    }
    if (u !== y || l !== d || h !== p || c !== f) {
      let g = 1 - o;
      const m = l * d + h * p + c * f + u * y, v = m >= 0 ? 1 : -1, x = 1 - m * m;
      if (x > Number.EPSILON) {
        const S = Math.sqrt(x), w = Math.atan2(S, m * v);
        g = Math.sin(g * w) / S, o = Math.sin(o * w) / S;
      }
      const _ = o * v;
      if (l = l * g + d * _, h = h * g + p * _, c = c * g + f * _, u = u * g + y * _, g === 1 - o) {
        const S = 1 / Math.sqrt(l * l + h * h + c * c + u * u);
        l *= S, h *= S, c *= S, u *= S;
      }
    }
    t[e] = l, t[e + 1] = h, t[e + 2] = c, t[e + 3] = u;
  }
  /**
   * Multiplies two quaternions. This implementation assumes the quaternion data are managed
   * in flat arrays.
   *
   * @param {Array<number>} dst - The destination array.
   * @param {number} dstOffset - An offset into the destination array.
   * @param {Array<number>} src0 - The source array of the first quaternion.
   * @param {number} srcOffset0 - An offset into the first source array.
   * @param {Array<number>} src1 -  The source array of the second quaternion.
   * @param {number} srcOffset1 - An offset into the second source array.
   * @return {Array<number>} The destination array.
   * @see {@link Quaternion#multiplyQuaternions}.
   */
  static multiplyQuaternionsFlat(t, e, i, n, s, r) {
    const o = i[n], l = i[n + 1], h = i[n + 2], c = i[n + 3], u = s[r], d = s[r + 1], p = s[r + 2], f = s[r + 3];
    return t[e] = o * f + c * u + l * p - h * d, t[e + 1] = l * f + c * d + h * u - o * p, t[e + 2] = h * f + c * p + o * d - l * u, t[e + 3] = c * f - o * u - l * d - h * p, t;
  }
  /**
   * The x value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get x() {
    return this._x;
  }
  set x(t) {
    this._x = t, this._onChangeCallback();
  }
  /**
   * The y value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get y() {
    return this._y;
  }
  set y(t) {
    this._y = t, this._onChangeCallback();
  }
  /**
   * The z value of this quaternion.
   *
   * @type {number}
   * @default 0
   */
  get z() {
    return this._z;
  }
  set z(t) {
    this._z = t, this._onChangeCallback();
  }
  /**
   * The w value of this quaternion.
   *
   * @type {number}
   * @default 1
   */
  get w() {
    return this._w;
  }
  set w(t) {
    this._w = t, this._onChangeCallback();
  }
  /**
   * Sets the quaternion components.
   *
   * @param {number} x - The x value of this quaternion.
   * @param {number} y - The y value of this quaternion.
   * @param {number} z - The z value of this quaternion.
   * @param {number} w - The w value of this quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  set(t, e, i, n) {
    return this._x = t, this._y = e, this._z = i, this._w = n, this._onChangeCallback(), this;
  }
  /**
   * Returns a new quaternion with copied values from this instance.
   *
   * @return {Quaternion} A clone of this instance.
   */
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._w);
  }
  /**
   * Copies the values of the given quaternion to this instance.
   *
   * @param {Quaternion} quaternion - The quaternion to copy.
   * @return {Quaternion} A reference to this quaternion.
   */
  copy(t) {
    return this._x = t.x, this._y = t.y, this._z = t.z, this._w = t.w, this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the rotation specified by the given
   * Euler angles.
   *
   * @param {Euler} euler - The Euler angles.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromEuler(t, e = !0) {
    const i = t._x, n = t._y, s = t._z, r = t._order, o = Math.cos, l = Math.sin, h = o(i / 2), c = o(n / 2), u = o(s / 2), d = l(i / 2), p = l(n / 2), f = l(s / 2);
    switch (r) {
      case "XYZ":
        this._x = d * c * u + h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "YXZ":
        this._x = d * c * u + h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u + d * p * f;
        break;
      case "ZXY":
        this._x = d * c * u - h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "ZYX":
        this._x = d * c * u - h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u + d * p * f;
        break;
      case "YZX":
        this._x = d * c * u + h * p * f, this._y = h * p * u + d * c * f, this._z = h * c * f - d * p * u, this._w = h * c * u - d * p * f;
        break;
      case "XZY":
        this._x = d * c * u - h * p * f, this._y = h * p * u - d * c * f, this._z = h * c * f + d * p * u, this._w = h * c * u + d * p * f;
        break;
      default:
        console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + r);
    }
    return e === !0 && this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the given axis and angle.
   *
   * @param {Vector3} axis - The normalized axis.
   * @param {number} angle - The angle in radians.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromAxisAngle(t, e) {
    const i = e / 2, n = Math.sin(i);
    return this._x = t.x * n, this._y = t.y * n, this._z = t.z * n, this._w = Math.cos(i), this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion from the given rotation matrix.
   *
   * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromRotationMatrix(t) {
    const e = t.elements, i = e[0], n = e[4], s = e[8], r = e[1], o = e[5], l = e[9], h = e[2], c = e[6], u = e[10], d = i + o + u;
    if (d > 0) {
      const p = 0.5 / Math.sqrt(d + 1);
      this._w = 0.25 / p, this._x = (c - l) * p, this._y = (s - h) * p, this._z = (r - n) * p;
    } else if (i > o && i > u) {
      const p = 2 * Math.sqrt(1 + i - o - u);
      this._w = (c - l) / p, this._x = 0.25 * p, this._y = (n + r) / p, this._z = (s + h) / p;
    } else if (o > u) {
      const p = 2 * Math.sqrt(1 + o - i - u);
      this._w = (s - h) / p, this._x = (n + r) / p, this._y = 0.25 * p, this._z = (l + c) / p;
    } else {
      const p = 2 * Math.sqrt(1 + u - i - o);
      this._w = (r - n) / p, this._x = (s + h) / p, this._y = (l + c) / p, this._z = 0.25 * p;
    }
    return this._onChangeCallback(), this;
  }
  /**
   * Sets this quaternion to the rotation required to rotate the direction vector
   * `vFrom` to the direction vector `vTo`.
   *
   * @param {Vector3} vFrom - The first (normalized) direction vector.
   * @param {Vector3} vTo - The second (normalized) direction vector.
   * @return {Quaternion} A reference to this quaternion.
   */
  setFromUnitVectors(t, e) {
    let i = t.dot(e) + 1;
    return i < 1e-8 ? (i = 0, Math.abs(t.x) > Math.abs(t.z) ? (this._x = -t.y, this._y = t.x, this._z = 0, this._w = i) : (this._x = 0, this._y = -t.z, this._z = t.y, this._w = i)) : (this._x = t.y * e.z - t.z * e.y, this._y = t.z * e.x - t.x * e.z, this._z = t.x * e.y - t.y * e.x, this._w = i), this.normalize();
  }
  /**
   * Returns the angle between this quaternion and the given one in radians.
   *
   * @param {Quaternion} q - The quaternion to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(t) {
    return 2 * Math.acos(Math.abs(ye(this.dot(t), -1, 1)));
  }
  /**
   * Rotates this quaternion by a given angular step to the given quaternion.
   * The method ensures that the final quaternion will not overshoot `q`.
   *
   * @param {Quaternion} q - The target quaternion.
   * @param {number} step - The angular step in radians.
   * @return {Quaternion} A reference to this quaternion.
   */
  rotateTowards(t, e) {
    const i = this.angleTo(t);
    if (i === 0) return this;
    const n = Math.min(1, e / i);
    return this.slerp(t, n), this;
  }
  /**
   * Sets this quaternion to the identity quaternion; that is, to the
   * quaternion that represents "no rotation".
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  identity() {
    return this.set(0, 0, 0, 1);
  }
  /**
   * Inverts this quaternion via {@link Quaternion#conjugate}. The
   * quaternion is assumed to have unit length.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  invert() {
    return this.conjugate();
  }
  /**
   * Returns the rotational conjugate of this quaternion. The conjugate of a
   * quaternion represents the same rotation in the opposite direction about
   * the rotational axis.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  conjugate() {
    return this._x *= -1, this._y *= -1, this._z *= -1, this._onChangeCallback(), this;
  }
  /**
   * Calculates the dot product of this quaternion and the given one.
   *
   * @param {Quaternion} v - The quaternion to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(t) {
    return this._x * t._x + this._y * t._y + this._z * t._z + this._w * t._w;
  }
  /**
   * Computes the squared Euclidean length (straight-line length) of this quaternion,
   * considered as a 4 dimensional vector. This can be useful if you are comparing the
   * lengths of two quaternions, as this is a slightly more efficient calculation than
   * {@link Quaternion#length}.
   *
   * @return {number} The squared Euclidean length.
   */
  lengthSq() {
    return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  }
  /**
   * Computes the Euclidean length (straight-line length) of this quaternion,
   * considered as a 4 dimensional vector.
   *
   * @return {number} The Euclidean length.
   */
  length() {
    return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  }
  /**
   * Normalizes this quaternion - that is, calculated the quaternion that performs
   * the same rotation as this one, but has a length equal to `1`.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  normalize() {
    let t = this.length();
    return t === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (t = 1 / t, this._x = this._x * t, this._y = this._y * t, this._z = this._z * t, this._w = this._w * t), this._onChangeCallback(), this;
  }
  /**
   * Multiplies this quaternion by the given one.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  multiply(t) {
    return this.multiplyQuaternions(this, t);
  }
  /**
   * Pre-multiplies this quaternion by the given one.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  premultiply(t) {
    return this.multiplyQuaternions(t, this);
  }
  /**
   * Multiplies the given quaternions and stores the result in this instance.
   *
   * @param {Quaternion} a - The first quaternion.
   * @param {Quaternion} b - The second quaternion.
   * @return {Quaternion} A reference to this quaternion.
   */
  multiplyQuaternions(t, e) {
    const i = t._x, n = t._y, s = t._z, r = t._w, o = e._x, l = e._y, h = e._z, c = e._w;
    return this._x = i * c + r * o + n * h - s * l, this._y = n * c + r * l + s * o - i * h, this._z = s * c + r * h + i * l - n * o, this._w = r * c - i * o - n * l - s * h, this._onChangeCallback(), this;
  }
  /**
   * Performs a spherical linear interpolation between quaternions.
   *
   * @param {Quaternion} qb - The target quaternion.
   * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
   * @return {Quaternion} A reference to this quaternion.
   */
  slerp(t, e) {
    if (e === 0) return this;
    if (e === 1) return this.copy(t);
    const i = this._x, n = this._y, s = this._z, r = this._w;
    let o = r * t._w + i * t._x + n * t._y + s * t._z;
    if (o < 0 ? (this._w = -t._w, this._x = -t._x, this._y = -t._y, this._z = -t._z, o = -o) : this.copy(t), o >= 1)
      return this._w = r, this._x = i, this._y = n, this._z = s, this;
    const l = 1 - o * o;
    if (l <= Number.EPSILON) {
      const p = 1 - e;
      return this._w = p * r + e * this._w, this._x = p * i + e * this._x, this._y = p * n + e * this._y, this._z = p * s + e * this._z, this.normalize(), this;
    }
    const h = Math.sqrt(l), c = Math.atan2(h, o), u = Math.sin((1 - e) * c) / h, d = Math.sin(e * c) / h;
    return this._w = r * u + this._w * d, this._x = i * u + this._x * d, this._y = n * u + this._y * d, this._z = s * u + this._z * d, this._onChangeCallback(), this;
  }
  /**
   * Performs a spherical linear interpolation between the given quaternions
   * and stores the result in this quaternion.
   *
   * @param {Quaternion} qa - The source quaternion.
   * @param {Quaternion} qb - The target quaternion.
   * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
   * @return {Quaternion} A reference to this quaternion.
   */
  slerpQuaternions(t, e, i) {
    return this.copy(t).slerp(e, i);
  }
  /**
   * Sets this quaternion to a uniformly random, normalized quaternion.
   *
   * @return {Quaternion} A reference to this quaternion.
   */
  random() {
    const t = 2 * Math.PI * Math.random(), e = 2 * Math.PI * Math.random(), i = Math.random(), n = Math.sqrt(1 - i), s = Math.sqrt(i);
    return this.set(
      n * Math.sin(t),
      n * Math.cos(t),
      s * Math.sin(e),
      s * Math.cos(e)
    );
  }
  /**
   * Returns `true` if this quaternion is equal with the given one.
   *
   * @param {Quaternion} quaternion - The quaternion to test for equality.
   * @return {boolean} Whether this quaternion is equal with the given one.
   */
  equals(t) {
    return t._x === this._x && t._y === this._y && t._z === this._z && t._w === this._w;
  }
  /**
   * Sets this quaternion's components from the given array.
   *
   * @param {Array<number>} array - An array holding the quaternion component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Quaternion} A reference to this quaternion.
   */
  fromArray(t, e = 0) {
    return this._x = t[e], this._y = t[e + 1], this._z = t[e + 2], this._w = t[e + 3], this._onChangeCallback(), this;
  }
  /**
   * Writes the components of this quaternion to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The quaternion components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this._x, t[e + 1] = this._y, t[e + 2] = this._z, t[e + 3] = this._w, t;
  }
  /**
   * Sets the components of this quaternion from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
   * @param {number} index - The index into the attribute.
   * @return {Quaternion} A reference to this quaternion.
   */
  fromBufferAttribute(t, e) {
    return this._x = t.getX(e), this._y = t.getY(e), this._z = t.getZ(e), this._w = t.getW(e), this._onChangeCallback(), this;
  }
  /**
   * This methods defines the serialization result of this class. Returns the
   * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
   *
   * @return {Array<number>} The serialized quaternion.
   */
  toJSON() {
    return this.toArray();
  }
  _onChange(t) {
    return this._onChangeCallback = t, this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x, yield this._y, yield this._z, yield this._w;
  }
}
class Fe {
  /**
   * Constructs a new 3D vector.
   *
   * @param {number} [x=0] - The x value of this vector.
   * @param {number} [y=0] - The y value of this vector.
   * @param {number} [z=0] - The z value of this vector.
   */
  constructor(t = 0, e = 0, i = 0) {
    Fe.prototype.isVector3 = !0, this.x = t, this.y = e, this.z = i;
  }
  /**
   * Sets the vector components.
   *
   * @param {number} x - The value of the x component.
   * @param {number} y - The value of the y component.
   * @param {number} z - The value of the z component.
   * @return {Vector3} A reference to this vector.
   */
  set(t, e, i) {
    return i === void 0 && (i = this.z), this.x = t, this.y = e, this.z = i, this;
  }
  /**
   * Sets the vector components to the same value.
   *
   * @param {number} scalar - The value to set for all vector components.
   * @return {Vector3} A reference to this vector.
   */
  setScalar(t) {
    return this.x = t, this.y = t, this.z = t, this;
  }
  /**
   * Sets the vector's x component to the given value
   *
   * @param {number} x - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setX(t) {
    return this.x = t, this;
  }
  /**
   * Sets the vector's y component to the given value
   *
   * @param {number} y - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setY(t) {
    return this.y = t, this;
  }
  /**
   * Sets the vector's z component to the given value
   *
   * @param {number} z - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setZ(t) {
    return this.z = t, this;
  }
  /**
   * Allows to set a vector component with an index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
   * @param {number} value - The value to set.
   * @return {Vector3} A reference to this vector.
   */
  setComponent(t, e) {
    switch (t) {
      case 0:
        this.x = e;
        break;
      case 1:
        this.y = e;
        break;
      case 2:
        this.z = e;
        break;
      default:
        throw new Error("index is out of range: " + t);
    }
    return this;
  }
  /**
   * Returns the value of the vector component which matches the given index.
   *
   * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
   * @return {number} A vector component value.
   */
  getComponent(t) {
    switch (t) {
      case 0:
        return this.x;
      case 1:
        return this.y;
      case 2:
        return this.z;
      default:
        throw new Error("index is out of range: " + t);
    }
  }
  /**
   * Returns a new vector with copied values from this instance.
   *
   * @return {Vector3} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.x, this.y, this.z);
  }
  /**
   * Copies the values of the given vector to this instance.
   *
   * @param {Vector3} v - The vector to copy.
   * @return {Vector3} A reference to this vector.
   */
  copy(t) {
    return this.x = t.x, this.y = t.y, this.z = t.z, this;
  }
  /**
   * Adds the given vector to this instance.
   *
   * @param {Vector3} v - The vector to add.
   * @return {Vector3} A reference to this vector.
   */
  add(t) {
    return this.x += t.x, this.y += t.y, this.z += t.z, this;
  }
  /**
   * Adds the given scalar value to all components of this instance.
   *
   * @param {number} s - The scalar to add.
   * @return {Vector3} A reference to this vector.
   */
  addScalar(t) {
    return this.x += t, this.y += t, this.z += t, this;
  }
  /**
   * Adds the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  addVectors(t, e) {
    return this.x = t.x + e.x, this.y = t.y + e.y, this.z = t.z + e.z, this;
  }
  /**
   * Adds the given vector scaled by the given factor to this instance.
   *
   * @param {Vector3|Vector4} v - The vector.
   * @param {number} s - The factor that scales `v`.
   * @return {Vector3} A reference to this vector.
   */
  addScaledVector(t, e) {
    return this.x += t.x * e, this.y += t.y * e, this.z += t.z * e, this;
  }
  /**
   * Subtracts the given vector from this instance.
   *
   * @param {Vector3} v - The vector to subtract.
   * @return {Vector3} A reference to this vector.
   */
  sub(t) {
    return this.x -= t.x, this.y -= t.y, this.z -= t.z, this;
  }
  /**
   * Subtracts the given scalar value from all components of this instance.
   *
   * @param {number} s - The scalar to subtract.
   * @return {Vector3} A reference to this vector.
   */
  subScalar(t) {
    return this.x -= t, this.y -= t, this.z -= t, this;
  }
  /**
   * Subtracts the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  subVectors(t, e) {
    return this.x = t.x - e.x, this.y = t.y - e.y, this.z = t.z - e.z, this;
  }
  /**
   * Multiplies the given vector with this instance.
   *
   * @param {Vector3} v - The vector to multiply.
   * @return {Vector3} A reference to this vector.
   */
  multiply(t) {
    return this.x *= t.x, this.y *= t.y, this.z *= t.z, this;
  }
  /**
   * Multiplies the given scalar value with all components of this instance.
   *
   * @param {number} scalar - The scalar to multiply.
   * @return {Vector3} A reference to this vector.
   */
  multiplyScalar(t) {
    return this.x *= t, this.y *= t, this.z *= t, this;
  }
  /**
   * Multiplies the given vectors and stores the result in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  multiplyVectors(t, e) {
    return this.x = t.x * e.x, this.y = t.y * e.y, this.z = t.z * e.z, this;
  }
  /**
   * Applies the given Euler rotation to this vector.
   *
   * @param {Euler} euler - The Euler angles.
   * @return {Vector3} A reference to this vector.
   */
  applyEuler(t) {
    return this.applyQuaternion(i0.setFromEuler(t));
  }
  /**
   * Applies a rotation specified by an axis and an angle to this vector.
   *
   * @param {Vector3} axis - A normalized vector representing the rotation axis.
   * @param {number} angle - The angle in radians.
   * @return {Vector3} A reference to this vector.
   */
  applyAxisAngle(t, e) {
    return this.applyQuaternion(i0.setFromAxisAngle(t, e));
  }
  /**
   * Multiplies this vector with the given 3x3 matrix.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @return {Vector3} A reference to this vector.
   */
  applyMatrix3(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements;
    return this.x = s[0] * e + s[3] * i + s[6] * n, this.y = s[1] * e + s[4] * i + s[7] * n, this.z = s[2] * e + s[5] * i + s[8] * n, this;
  }
  /**
   * Multiplies this vector by the given normal matrix and normalizes
   * the result.
   *
   * @param {Matrix3} m - The normal matrix.
   * @return {Vector3} A reference to this vector.
   */
  applyNormalMatrix(t) {
    return this.applyMatrix3(t).normalize();
  }
  /**
   * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
   * divides by perspective.
   *
   * @param {Matrix4} m - The matrix to apply.
   * @return {Vector3} A reference to this vector.
   */
  applyMatrix4(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements, r = 1 / (s[3] * e + s[7] * i + s[11] * n + s[15]);
    return this.x = (s[0] * e + s[4] * i + s[8] * n + s[12]) * r, this.y = (s[1] * e + s[5] * i + s[9] * n + s[13]) * r, this.z = (s[2] * e + s[6] * i + s[10] * n + s[14]) * r, this;
  }
  /**
   * Applies the given Quaternion to this vector.
   *
   * @param {Quaternion} q - The Quaternion.
   * @return {Vector3} A reference to this vector.
   */
  applyQuaternion(t) {
    const e = this.x, i = this.y, n = this.z, s = t.x, r = t.y, o = t.z, l = t.w, h = 2 * (r * n - o * i), c = 2 * (o * e - s * n), u = 2 * (s * i - r * e);
    return this.x = e + l * h + r * u - o * c, this.y = i + l * c + o * h - s * u, this.z = n + l * u + s * c - r * h, this;
  }
  /**
   * Projects this vector from world space into the camera's normalized
   * device coordinate (NDC) space.
   *
   * @param {Camera} camera - The camera.
   * @return {Vector3} A reference to this vector.
   */
  project(t) {
    return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix);
  }
  /**
   * Unprojects this vector from the camera's normalized device coordinate (NDC)
   * space into world space.
   *
   * @param {Camera} camera - The camera.
   * @return {Vector3} A reference to this vector.
   */
  unproject(t) {
    return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld);
  }
  /**
   * Transforms the direction of this vector by a matrix (the upper left 3 x 3
   * subset of the given 4x4 matrix and then normalizes the result.
   *
   * @param {Matrix4} m - The matrix.
   * @return {Vector3} A reference to this vector.
   */
  transformDirection(t) {
    const e = this.x, i = this.y, n = this.z, s = t.elements;
    return this.x = s[0] * e + s[4] * i + s[8] * n, this.y = s[1] * e + s[5] * i + s[9] * n, this.z = s[2] * e + s[6] * i + s[10] * n, this.normalize();
  }
  /**
   * Divides this instance by the given vector.
   *
   * @param {Vector3} v - The vector to divide.
   * @return {Vector3} A reference to this vector.
   */
  divide(t) {
    return this.x /= t.x, this.y /= t.y, this.z /= t.z, this;
  }
  /**
   * Divides this vector by the given scalar.
   *
   * @param {number} scalar - The scalar to divide.
   * @return {Vector3} A reference to this vector.
   */
  divideScalar(t) {
    return this.multiplyScalar(1 / t);
  }
  /**
   * If this vector's x, y or z value is greater than the given vector's x, y or z
   * value, replace that value with the corresponding min value.
   *
   * @param {Vector3} v - The vector.
   * @return {Vector3} A reference to this vector.
   */
  min(t) {
    return this.x = Math.min(this.x, t.x), this.y = Math.min(this.y, t.y), this.z = Math.min(this.z, t.z), this;
  }
  /**
   * If this vector's x, y or z value is less than the given vector's x, y or z
   * value, replace that value with the corresponding max value.
   *
   * @param {Vector3} v - The vector.
   * @return {Vector3} A reference to this vector.
   */
  max(t) {
    return this.x = Math.max(this.x, t.x), this.y = Math.max(this.y, t.y), this.z = Math.max(this.z, t.z), this;
  }
  /**
   * If this vector's x, y or z value is greater than the max vector's x, y or z
   * value, it is replaced by the corresponding value.
   * If this vector's x, y or z value is less than the min vector's x, y or z value,
   * it is replaced by the corresponding value.
   *
   * @param {Vector3} min - The minimum x, y and z values.
   * @param {Vector3} max - The maximum x, y and z values in the desired range.
   * @return {Vector3} A reference to this vector.
   */
  clamp(t, e) {
    return this.x = ye(this.x, t.x, e.x), this.y = ye(this.y, t.y, e.y), this.z = ye(this.z, t.z, e.z), this;
  }
  /**
   * If this vector's x, y or z values are greater than the max value, they are
   * replaced by the max value.
   * If this vector's x, y or z values are less than the min value, they are
   * replaced by the min value.
   *
   * @param {number} minVal - The minimum value the components will be clamped to.
   * @param {number} maxVal - The maximum value the components will be clamped to.
   * @return {Vector3} A reference to this vector.
   */
  clampScalar(t, e) {
    return this.x = ye(this.x, t, e), this.y = ye(this.y, t, e), this.z = ye(this.z, t, e), this;
  }
  /**
   * If this vector's length is greater than the max value, it is replaced by
   * the max value.
   * If this vector's length is less than the min value, it is replaced by the
   * min value.
   *
   * @param {number} min - The minimum value the vector length will be clamped to.
   * @param {number} max - The maximum value the vector length will be clamped to.
   * @return {Vector3} A reference to this vector.
   */
  clampLength(t, e) {
    const i = this.length();
    return this.divideScalar(i || 1).multiplyScalar(ye(i, t, e));
  }
  /**
   * The components of this vector are rounded down to the nearest integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  floor() {
    return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this;
  }
  /**
   * The components of this vector are rounded up to the nearest integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  ceil() {
    return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this;
  }
  /**
   * The components of this vector are rounded to the nearest integer value
   *
   * @return {Vector3} A reference to this vector.
   */
  round() {
    return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this;
  }
  /**
   * The components of this vector are rounded towards zero (up if negative,
   * down if positive) to an integer value.
   *
   * @return {Vector3} A reference to this vector.
   */
  roundToZero() {
    return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this;
  }
  /**
   * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
   *
   * @return {Vector3} A reference to this vector.
   */
  negate() {
    return this.x = -this.x, this.y = -this.y, this.z = -this.z, this;
  }
  /**
   * Calculates the dot product of the given vector with this instance.
   *
   * @param {Vector3} v - The vector to compute the dot product with.
   * @return {number} The result of the dot product.
   */
  dot(t) {
    return this.x * t.x + this.y * t.y + this.z * t.z;
  }
  // TODO lengthSquared?
  /**
   * Computes the square of the Euclidean length (straight-line length) from
   * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
   * compare the length squared instead as it is slightly more efficient to calculate.
   *
   * @return {number} The square length of this vector.
   */
  lengthSq() {
    return this.x * this.x + this.y * this.y + this.z * this.z;
  }
  /**
   * Computes the  Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
   *
   * @return {number} The length of this vector.
   */
  length() {
    return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  }
  /**
   * Computes the Manhattan length of this vector.
   *
   * @return {number} The length of this vector.
   */
  manhattanLength() {
    return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  }
  /**
   * Converts this vector to a unit vector - that is, sets it equal to a vector
   * with the same direction as this one, but with a vector length of `1`.
   *
   * @return {Vector3} A reference to this vector.
   */
  normalize() {
    return this.divideScalar(this.length() || 1);
  }
  /**
   * Sets this vector to a vector with the same direction as this one, but
   * with the specified length.
   *
   * @param {number} length - The new length of this vector.
   * @return {Vector3} A reference to this vector.
   */
  setLength(t) {
    return this.normalize().multiplyScalar(t);
  }
  /**
   * Linearly interpolates between the given vector and this instance, where
   * alpha is the percent distance along the line - alpha = 0 will be this
   * vector, and alpha = 1 will be the given one.
   *
   * @param {Vector3} v - The vector to interpolate towards.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector3} A reference to this vector.
   */
  lerp(t, e) {
    return this.x += (t.x - this.x) * e, this.y += (t.y - this.y) * e, this.z += (t.z - this.z) * e, this;
  }
  /**
   * Linearly interpolates between the given vectors, where alpha is the percent
   * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
   * be the second one. The result is stored in this instance.
   *
   * @param {Vector3} v1 - The first vector.
   * @param {Vector3} v2 - The second vector.
   * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
   * @return {Vector3} A reference to this vector.
   */
  lerpVectors(t, e, i) {
    return this.x = t.x + (e.x - t.x) * i, this.y = t.y + (e.y - t.y) * i, this.z = t.z + (e.z - t.z) * i, this;
  }
  /**
   * Calculates the cross product of the given vector with this instance.
   *
   * @param {Vector3} v - The vector to compute the cross product with.
   * @return {Vector3} The result of the cross product.
   */
  cross(t) {
    return this.crossVectors(this, t);
  }
  /**
   * Calculates the cross product of the given vectors and stores the result
   * in this instance.
   *
   * @param {Vector3} a - The first vector.
   * @param {Vector3} b - The second vector.
   * @return {Vector3} A reference to this vector.
   */
  crossVectors(t, e) {
    const i = t.x, n = t.y, s = t.z, r = e.x, o = e.y, l = e.z;
    return this.x = n * l - s * o, this.y = s * r - i * l, this.z = i * o - n * r, this;
  }
  /**
   * Projects this vector onto the given one.
   *
   * @param {Vector3} v - The vector to project to.
   * @return {Vector3} A reference to this vector.
   */
  projectOnVector(t) {
    const e = t.lengthSq();
    if (e === 0) return this.set(0, 0, 0);
    const i = t.dot(this) / e;
    return this.copy(t).multiplyScalar(i);
  }
  /**
   * Projects this vector onto a plane by subtracting this
   * vector projected onto the plane's normal from this vector.
   *
   * @param {Vector3} planeNormal - The plane normal.
   * @return {Vector3} A reference to this vector.
   */
  projectOnPlane(t) {
    return Nd.copy(this).projectOnVector(t), this.sub(Nd);
  }
  /**
   * Reflects this vector off a plane orthogonal to the given normal vector.
   *
   * @param {Vector3} normal - The (normalized) normal vector.
   * @return {Vector3} A reference to this vector.
   */
  reflect(t) {
    return this.sub(Nd.copy(t).multiplyScalar(2 * this.dot(t)));
  }
  /**
   * Returns the angle between the given vector and this instance in radians.
   *
   * @param {Vector3} v - The vector to compute the angle with.
   * @return {number} The angle in radians.
   */
  angleTo(t) {
    const e = Math.sqrt(this.lengthSq() * t.lengthSq());
    if (e === 0) return Math.PI / 2;
    const i = this.dot(t) / e;
    return Math.acos(ye(i, -1, 1));
  }
  /**
   * Computes the distance from the given vector to this instance.
   *
   * @param {Vector3} v - The vector to compute the distance to.
   * @return {number} The distance.
   */
  distanceTo(t) {
    return Math.sqrt(this.distanceToSquared(t));
  }
  /**
   * Computes the squared distance from the given vector to this instance.
   * If you are just comparing the distance with another distance, you should compare
   * the distance squared instead as it is slightly more efficient to calculate.
   *
   * @param {Vector3} v - The vector to compute the squared distance to.
   * @return {number} The squared distance.
   */
  distanceToSquared(t) {
    const e = this.x - t.x, i = this.y - t.y, n = this.z - t.z;
    return e * e + i * i + n * n;
  }
  /**
   * Computes the Manhattan distance from the given vector to this instance.
   *
   * @param {Vector3} v - The vector to compute the Manhattan distance to.
   * @return {number} The Manhattan distance.
   */
  manhattanDistanceTo(t) {
    return Math.abs(this.x - t.x) + Math.abs(this.y - t.y) + Math.abs(this.z - t.z);
  }
  /**
   * Sets the vector components from the given spherical coordinates.
   *
   * @param {Spherical} s - The spherical coordinates.
   * @return {Vector3} A reference to this vector.
   */
  setFromSpherical(t) {
    return this.setFromSphericalCoords(t.radius, t.phi, t.theta);
  }
  /**
   * Sets the vector components from the given spherical coordinates.
   *
   * @param {number} radius - The radius.
   * @param {number} phi - The phi angle in radians.
   * @param {number} theta - The theta angle in radians.
   * @return {Vector3} A reference to this vector.
   */
  setFromSphericalCoords(t, e, i) {
    const n = Math.sin(e) * t;
    return this.x = n * Math.sin(i), this.y = Math.cos(e) * t, this.z = n * Math.cos(i), this;
  }
  /**
   * Sets the vector components from the given cylindrical coordinates.
   *
   * @param {Cylindrical} c - The cylindrical coordinates.
   * @return {Vector3} A reference to this vector.
   */
  setFromCylindrical(t) {
    return this.setFromCylindricalCoords(t.radius, t.theta, t.y);
  }
  /**
   * Sets the vector components from the given cylindrical coordinates.
   *
   * @param {number} radius - The radius.
   * @param {number} theta - The theta angle in radians.
   * @param {number} y - The y value.
   * @return {Vector3} A reference to this vector.
   */
  setFromCylindricalCoords(t, e, i) {
    return this.x = t * Math.sin(e), this.y = i, this.z = t * Math.cos(e), this;
  }
  /**
   * Sets the vector components to the position elements of the
   * given transformation matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixPosition(t) {
    const e = t.elements;
    return this.x = e[12], this.y = e[13], this.z = e[14], this;
  }
  /**
   * Sets the vector components to the scale elements of the
   * given transformation matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixScale(t) {
    const e = this.setFromMatrixColumn(t, 0).length(), i = this.setFromMatrixColumn(t, 1).length(), n = this.setFromMatrixColumn(t, 2).length();
    return this.x = e, this.y = i, this.z = n, this;
  }
  /**
   * Sets the vector components from the specified matrix column.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @param {number} index - The column index.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrixColumn(t, e) {
    return this.fromArray(t.elements, e * 4);
  }
  /**
   * Sets the vector components from the specified matrix column.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @param {number} index - The column index.
   * @return {Vector3} A reference to this vector.
   */
  setFromMatrix3Column(t, e) {
    return this.fromArray(t.elements, e * 3);
  }
  /**
   * Sets the vector components from the given Euler angles.
   *
   * @param {Euler} e - The Euler angles to set.
   * @return {Vector3} A reference to this vector.
   */
  setFromEuler(t) {
    return this.x = t._x, this.y = t._y, this.z = t._z, this;
  }
  /**
   * Sets the vector components from the RGB components of the
   * given color.
   *
   * @param {Color} c - The color to set.
   * @return {Vector3} A reference to this vector.
   */
  setFromColor(t) {
    return this.x = t.r, this.y = t.g, this.z = t.b, this;
  }
  /**
   * Returns `true` if this vector is equal with the given one.
   *
   * @param {Vector3} v - The vector to test for equality.
   * @return {boolean} Whether this vector is equal with the given one.
   */
  equals(t) {
    return t.x === this.x && t.y === this.y && t.z === this.z;
  }
  /**
   * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
   * and z value to be `array[ offset + 2 ]`.
   *
   * @param {Array<number>} array - An array holding the vector component values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Vector3} A reference to this vector.
   */
  fromArray(t, e = 0) {
    return this.x = t[e], this.y = t[e + 1], this.z = t[e + 2], this;
  }
  /**
   * Writes the components of this vector to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the vector components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The vector components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this.x, t[e + 1] = this.y, t[e + 2] = this.z, t;
  }
  /**
   * Sets the components of this vector from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
   * @param {number} index - The index into the attribute.
   * @return {Vector3} A reference to this vector.
   */
  fromBufferAttribute(t, e) {
    return this.x = t.getX(e), this.y = t.getY(e), this.z = t.getZ(e), this;
  }
  /**
   * Sets each component of this vector to a pseudo-random value between `0` and
   * `1`, excluding `1`.
   *
   * @return {Vector3} A reference to this vector.
   */
  random() {
    return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this;
  }
  /**
   * Sets this vector to a uniformly random point on a unit sphere.
   *
   * @return {Vector3} A reference to this vector.
   */
  randomDirection() {
    const t = Math.random() * Math.PI * 2, e = Math.random() * 2 - 1, i = Math.sqrt(1 - e * e);
    return this.x = i * Math.cos(t), this.y = e, this.z = i * Math.sin(t), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y, yield this.z;
  }
}
const Nd = /* @__PURE__ */ new Fe(), i0 = /* @__PURE__ */ new $o();
class _r {
  /**
   * Constructs a new 3x3 matrix. The arguments are supposed to be
   * in row-major order. If no arguments are provided, the constructor
   * initializes the matrix as an identity matrix.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   */
  constructor(t, e, i, n, s, r, o, l, h) {
    _r.prototype.isMatrix3 = !0, this.elements = [
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ], t !== void 0 && this.set(t, e, i, n, s, r, o, l, h);
  }
  /**
   * Sets the elements of the matrix.The arguments are supposed to be
   * in row-major order.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @return {Matrix3} A reference to this matrix.
   */
  set(t, e, i, n, s, r, o, l, h) {
    const c = this.elements;
    return c[0] = t, c[1] = n, c[2] = o, c[3] = e, c[4] = s, c[5] = l, c[6] = i, c[7] = r, c[8] = h, this;
  }
  /**
   * Sets this matrix to the 3x3 identity matrix.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  identity() {
    return this.set(
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Copies the values of the given matrix to this instance.
   *
   * @param {Matrix3} m - The matrix to copy.
   * @return {Matrix3} A reference to this matrix.
   */
  copy(t) {
    const e = this.elements, i = t.elements;
    return e[0] = i[0], e[1] = i[1], e[2] = i[2], e[3] = i[3], e[4] = i[4], e[5] = i[5], e[6] = i[6], e[7] = i[7], e[8] = i[8], this;
  }
  /**
   * Extracts the basis of this matrix into the three axis vectors provided.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix3} A reference to this matrix.
   */
  extractBasis(t, e, i) {
    return t.setFromMatrix3Column(this, 0), e.setFromMatrix3Column(this, 1), i.setFromMatrix3Column(this, 2), this;
  }
  /**
   * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
   *
   * @param {Matrix4} m - The 4x4 matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  setFromMatrix4(t) {
    const e = t.elements;
    return this.set(
      e[0],
      e[4],
      e[8],
      e[1],
      e[5],
      e[9],
      e[2],
      e[6],
      e[10]
    ), this;
  }
  /**
   * Post-multiplies this matrix by the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to multiply with.
   * @return {Matrix3} A reference to this matrix.
   */
  multiply(t) {
    return this.multiplyMatrices(this, t);
  }
  /**
   * Pre-multiplies this matrix by the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix to multiply with.
   * @return {Matrix3} A reference to this matrix.
   */
  premultiply(t) {
    return this.multiplyMatrices(t, this);
  }
  /**
   * Multiples the given 3x3 matrices and stores the result
   * in this matrix.
   *
   * @param {Matrix3} a - The first matrix.
   * @param {Matrix3} b - The second matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  multiplyMatrices(t, e) {
    const i = t.elements, n = e.elements, s = this.elements, r = i[0], o = i[3], l = i[6], h = i[1], c = i[4], u = i[7], d = i[2], p = i[5], f = i[8], y = n[0], g = n[3], m = n[6], v = n[1], x = n[4], _ = n[7], S = n[2], w = n[5], T = n[8];
    return s[0] = r * y + o * v + l * S, s[3] = r * g + o * x + l * w, s[6] = r * m + o * _ + l * T, s[1] = h * y + c * v + u * S, s[4] = h * g + c * x + u * w, s[7] = h * m + c * _ + u * T, s[2] = d * y + p * v + f * S, s[5] = d * g + p * x + f * w, s[8] = d * m + p * _ + f * T, this;
  }
  /**
   * Multiplies every component of the matrix by the given scalar.
   *
   * @param {number} s - The scalar.
   * @return {Matrix3} A reference to this matrix.
   */
  multiplyScalar(t) {
    const e = this.elements;
    return e[0] *= t, e[3] *= t, e[6] *= t, e[1] *= t, e[4] *= t, e[7] *= t, e[2] *= t, e[5] *= t, e[8] *= t, this;
  }
  /**
   * Computes and returns the determinant of this matrix.
   *
   * @return {number} The determinant.
   */
  determinant() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8];
    return e * r * c - e * o * h - i * s * c + i * o * l + n * s * h - n * r * l;
  }
  /**
   * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
   * You can not invert with a determinant of zero. If you attempt this, the method produces
   * a zero matrix instead.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  invert() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8], u = c * r - o * h, d = o * l - c * s, p = h * s - r * l, f = e * u + i * d + n * p;
    if (f === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
    const y = 1 / f;
    return t[0] = u * y, t[1] = (n * h - c * i) * y, t[2] = (o * i - n * r) * y, t[3] = d * y, t[4] = (c * e - n * l) * y, t[5] = (n * s - o * e) * y, t[6] = p * y, t[7] = (i * l - h * e) * y, t[8] = (r * e - i * s) * y, this;
  }
  /**
   * Transposes this matrix in place.
   *
   * @return {Matrix3} A reference to this matrix.
   */
  transpose() {
    let t;
    const e = this.elements;
    return t = e[1], e[1] = e[3], e[3] = t, t = e[2], e[2] = e[6], e[6] = t, t = e[5], e[5] = e[7], e[7] = t, this;
  }
  /**
   * Computes the normal matrix which is the inverse transpose of the upper
   * left 3x3 portion of the given 4x4 matrix.
   *
   * @param {Matrix4} matrix4 - The 4x4 matrix.
   * @return {Matrix3} A reference to this matrix.
   */
  getNormalMatrix(t) {
    return this.setFromMatrix4(t).invert().transpose();
  }
  /**
   * Transposes this matrix into the supplied array, and returns itself unchanged.
   *
   * @param {Array<number>} r - An array to store the transposed matrix elements.
   * @return {Matrix3} A reference to this matrix.
   */
  transposeIntoArray(t) {
    const e = this.elements;
    return t[0] = e[0], t[1] = e[3], t[2] = e[6], t[3] = e[1], t[4] = e[4], t[5] = e[7], t[6] = e[2], t[7] = e[5], t[8] = e[8], this;
  }
  /**
   * Sets the UV transform matrix from offset, repeat, rotation, and center.
   *
   * @param {number} tx - Offset x.
   * @param {number} ty - Offset y.
   * @param {number} sx - Repeat x.
   * @param {number} sy - Repeat y.
   * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
   * @param {number} cx - Center x of rotation.
   * @param {number} cy - Center y of rotation
   * @return {Matrix3} A reference to this matrix.
   */
  setUvTransform(t, e, i, n, s, r, o) {
    const l = Math.cos(s), h = Math.sin(s);
    return this.set(
      i * l,
      i * h,
      -i * (l * r + h * o) + r + t,
      -n * h,
      n * l,
      -n * (-h * r + l * o) + o + e,
      0,
      0,
      1
    ), this;
  }
  /**
   * Scales this matrix with the given scalar values.
   *
   * @param {number} sx - The amount to scale in the X axis.
   * @param {number} sy - The amount to scale in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  scale(t, e) {
    return this.premultiply(Od.makeScale(t, e)), this;
  }
  /**
   * Rotates this matrix by the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix3} A reference to this matrix.
   */
  rotate(t) {
    return this.premultiply(Od.makeRotation(-t)), this;
  }
  /**
   * Translates this matrix by the given scalar values.
   *
   * @param {number} tx - The amount to translate in the X axis.
   * @param {number} ty - The amount to translate in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  translate(t, e) {
    return this.premultiply(Od.makeTranslation(t, e)), this;
  }
  // for 2D Transforms
  /**
   * Sets this matrix as a 2D translation transform.
   *
   * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
   * @param {number} y - The amount to translate in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  makeTranslation(t, e) {
    return t.isVector2 ? this.set(
      1,
      0,
      t.x,
      0,
      1,
      t.y,
      0,
      0,
      1
    ) : this.set(
      1,
      0,
      t,
      0,
      1,
      e,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a 2D rotational transformation.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix3} A reference to this matrix.
   */
  makeRotation(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      -i,
      0,
      i,
      e,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a 2D scale transform.
   *
   * @param {number} x - The amount to scale in the X axis.
   * @param {number} y - The amount to scale in the Y axis.
   * @return {Matrix3} A reference to this matrix.
   */
  makeScale(t, e) {
    return this.set(
      t,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Returns `true` if this matrix is equal with the given one.
   *
   * @param {Matrix3} matrix - The matrix to test for equality.
   * @return {boolean} Whether this matrix is equal with the given one.
   */
  equals(t) {
    const e = this.elements, i = t.elements;
    for (let n = 0; n < 9; n++)
      if (e[n] !== i[n]) return !1;
    return !0;
  }
  /**
   * Sets the elements of the matrix from the given array.
   *
   * @param {Array<number>} array - The matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Matrix3} A reference to this matrix.
   */
  fromArray(t, e = 0) {
    for (let i = 0; i < 9; i++)
      this.elements[i] = t[i + e];
    return this;
  }
  /**
   * Writes the elements of this matrix to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The matrix elements in column-major order.
   */
  toArray(t = [], e = 0) {
    const i = this.elements;
    return t[e] = i[0], t[e + 1] = i[1], t[e + 2] = i[2], t[e + 3] = i[3], t[e + 4] = i[4], t[e + 5] = i[5], t[e + 6] = i[6], t[e + 7] = i[7], t[e + 8] = i[8], t;
  }
  /**
   * Returns a matrix with copied values from this instance.
   *
   * @return {Matrix3} A clone of this instance.
   */
  clone() {
    return new this.constructor().fromArray(this.elements);
  }
}
const Od = /* @__PURE__ */ new _r();
function n0(a) {
  return document.createElementNS("http://www.w3.org/1999/xhtml", a);
}
const s0 = {};
function r0(a) {
  a in s0 || (s0[a] = !0, console.warn(a));
}
const a0 = /* @__PURE__ */ new _r().set(
  0.4123908,
  0.3575843,
  0.1804808,
  0.212639,
  0.7151687,
  0.0721923,
  0.0193308,
  0.1191948,
  0.9505322
), o0 = /* @__PURE__ */ new _r().set(
  3.2409699,
  -1.5373832,
  -0.4986108,
  -0.9692436,
  1.8759675,
  0.0415551,
  0.0556301,
  -0.203977,
  1.0569715
);
function yC() {
  const a = {
    enabled: !0,
    workingColorSpace: Qg,
    /**
     * Implementations of supported color spaces.
     *
     * Required:
     *	- primaries: chromaticity coordinates [ rx ry gx gy bx by ]
     *	- whitePoint: reference white [ x y ]
     *	- transfer: transfer function (pre-defined)
     *	- toXYZ: Matrix3 RGB to XYZ transform
     *	- fromXYZ: Matrix3 XYZ to RGB transform
     *	- luminanceCoefficients: RGB luminance coefficients
     *
     * Optional:
     *  - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
     *  - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
     *
     * Reference:
     * - https://www.russellcottrell.com/photo/matrixCalculator.htm
     */
    spaces: {},
    convert: function(n, s, r) {
      return this.enabled === !1 || s === r || !s || !r || (this.spaces[s].transfer === Bd && (n.r = ts(n.r), n.g = ts(n.g), n.b = ts(n.b)), this.spaces[s].primaries !== this.spaces[r].primaries && (n.applyMatrix3(this.spaces[s].toXYZ), n.applyMatrix3(this.spaces[r].fromXYZ)), this.spaces[r].transfer === Bd && (n.r = ua(n.r), n.g = ua(n.g), n.b = ua(n.b))), n;
    },
    workingToColorSpace: function(n, s) {
      return this.convert(n, this.workingColorSpace, s);
    },
    colorSpaceToWorking: function(n, s) {
      return this.convert(n, s, this.workingColorSpace);
    },
    getPrimaries: function(n) {
      return this.spaces[n].primaries;
    },
    getTransfer: function(n) {
      return n === Q_ ? t0 : this.spaces[n].transfer;
    },
    getToneMappingMode: function(n) {
      return this.spaces[n].outputColorSpaceConfig.toneMappingMode || "standard";
    },
    getLuminanceCoefficients: function(n, s = this.workingColorSpace) {
      return n.fromArray(this.spaces[s].luminanceCoefficients);
    },
    define: function(n) {
      Object.assign(this.spaces, n);
    },
    // Internal APIs
    _getMatrix: function(n, s, r) {
      return n.copy(this.spaces[s].toXYZ).multiply(this.spaces[r].fromXYZ);
    },
    _getDrawingBufferColorSpace: function(n) {
      return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace;
    },
    _getUnpackColorSpace: function(n = this.workingColorSpace) {
      return this.spaces[n].workingColorSpaceConfig.unpackColorSpace;
    },
    // Deprecated
    fromWorkingColorSpace: function(n, s) {
      return r0("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."), a.workingToColorSpace(n, s);
    },
    toWorkingColorSpace: function(n, s) {
      return r0("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."), a.colorSpaceToWorking(n, s);
    }
  }, t = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], e = [0.2126, 0.7152, 0.0722], i = [0.3127, 0.329];
  return a.define({
    [Qg]: {
      primaries: t,
      whitePoint: i,
      transfer: t0,
      toXYZ: a0,
      fromXYZ: o0,
      luminanceCoefficients: e,
      workingColorSpaceConfig: { unpackColorSpace: on },
      outputColorSpaceConfig: { drawingBufferColorSpace: on }
    },
    [on]: {
      primaries: t,
      whitePoint: i,
      transfer: Bd,
      toXYZ: a0,
      fromXYZ: o0,
      luminanceCoefficients: e,
      outputColorSpaceConfig: { drawingBufferColorSpace: on }
    }
  }), a;
}
const sn = /* @__PURE__ */ yC();
function ts(a) {
  return a < 0.04045 ? a * 0.0773993808 : Math.pow(a * 0.9478672986 + 0.0521327014, 2.4);
}
function ua(a) {
  return a < 31308e-7 ? a * 12.92 : 1.055 * Math.pow(a, 0.41666) - 0.055;
}
let Kr;
class _C {
  /**
   * Returns a data URI containing a representation of the given image.
   *
   * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
   * @param {string} [type='image/png'] - Indicates the image format.
   * @return {string} The data URI.
   */
  static getDataURL(t, e = "image/png") {
    if (/^data:/i.test(t.src) || typeof HTMLCanvasElement > "u")
      return t.src;
    let i;
    if (t instanceof HTMLCanvasElement)
      i = t;
    else {
      Kr === void 0 && (Kr = n0("canvas")), Kr.width = t.width, Kr.height = t.height;
      const n = Kr.getContext("2d");
      t instanceof ImageData ? n.putImageData(t, 0, 0) : n.drawImage(t, 0, 0, t.width, t.height), i = Kr;
    }
    return i.toDataURL(e);
  }
  /**
   * Converts the given sRGB image data to linear color space.
   *
   * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
   * @return {HTMLCanvasElement|Object} The converted image.
   */
  static sRGBToLinear(t) {
    if (typeof HTMLImageElement < "u" && t instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && t instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && t instanceof ImageBitmap) {
      const e = n0("canvas");
      e.width = t.width, e.height = t.height;
      const i = e.getContext("2d");
      i.drawImage(t, 0, 0, t.width, t.height);
      const n = i.getImageData(0, 0, t.width, t.height), s = n.data;
      for (let r = 0; r < s.length; r++)
        s[r] = ts(s[r] / 255) * 255;
      return i.putImageData(n, 0, 0), e;
    } else if (t.data) {
      const e = t.data.slice(0);
      for (let i = 0; i < e.length; i++)
        e instanceof Uint8Array || e instanceof Uint8ClampedArray ? e[i] = Math.floor(ts(e[i] / 255) * 255) : e[i] = ts(e[i]);
      return {
        data: e,
        width: t.width,
        height: t.height
      };
    } else
      return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), t;
  }
}
let xC = 0;
class vC {
  /**
   * Constructs a new video texture.
   *
   * @param {any} [data=null] - The data definition of a texture.
   */
  constructor(t = null) {
    this.isSource = !0, Object.defineProperty(this, "id", { value: xC++ }), this.uuid = Mf(), this.data = t, this.dataReady = !0, this.version = 0;
  }
  /**
   * Returns the dimensions of the source into the given target vector.
   *
   * @param {(Vector2|Vector3)} target - The target object the result is written into.
   * @return {(Vector2|Vector3)} The dimensions of the source.
   */
  getSize(t) {
    const e = this.data;
    return typeof HTMLVideoElement < "u" && e instanceof HTMLVideoElement ? t.set(e.videoWidth, e.videoHeight, 0) : e instanceof VideoFrame ? t.set(e.displayHeight, e.displayWidth, 0) : e !== null ? t.set(e.width, e.height, e.depth || 0) : t.set(0, 0, 0), t;
  }
  /**
   * When the property is set to `true`, the engine allocates the memory
   * for the texture (if necessary) and triggers the actual texture upload
   * to the GPU next time the source is used.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    t === !0 && this.version++;
  }
  /**
   * Serializes the source into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized source.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(t) {
    const e = t === void 0 || typeof t == "string";
    if (!e && t.images[this.uuid] !== void 0)
      return t.images[this.uuid];
    const i = {
      uuid: this.uuid,
      url: ""
    }, n = this.data;
    if (n !== null) {
      let s;
      if (Array.isArray(n)) {
        s = [];
        for (let r = 0, o = n.length; r < o; r++)
          n[r].isDataTexture ? s.push(kd(n[r].image)) : s.push(kd(n[r]));
      } else
        s = kd(n);
      i.url = s;
    }
    return e || (t.images[this.uuid] = i), i;
  }
}
function kd(a) {
  return typeof HTMLImageElement < "u" && a instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && a instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && a instanceof ImageBitmap ? _C.getDataURL(a) : a.data ? {
    data: Array.from(a.data),
    width: a.width,
    height: a.height,
    type: a.data.constructor.name
  } : (console.warn("THREE.Texture: Unable to serialize Texture."), {});
}
let bC = 0;
const Vd = /* @__PURE__ */ new Fe();
class ur extends tx {
  /**
   * Constructs a new texture.
   *
   * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
   * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
   * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
   * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
   * @param {number} [magFilter=LinearFilter] - The mag filter value.
   * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
   * @param {number} [format=RGBAFormat] - The texture format.
   * @param {number} [type=UnsignedByteType] - The texture type.
   * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
   * @param {string} [colorSpace=NoColorSpace] - The color space.
   */
  constructor(t = ur.DEFAULT_IMAGE, e = ur.DEFAULT_MAPPING, i = ph, n = ph, s = dC, r = pC, o = mC, l = fC, h = ur.DEFAULT_ANISOTROPY, c = Q_) {
    super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: bC++ }), this.uuid = Mf(), this.name = "", this.source = new vC(t), this.mipmaps = [], this.mapping = e, this.channel = 0, this.wrapS = i, this.wrapT = n, this.magFilter = s, this.minFilter = r, this.anisotropy = h, this.format = o, this.internalFormat = null, this.type = l, this.offset = new _o(0, 0), this.repeat = new _o(1, 1), this.center = new _o(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new _r(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = c, this.userData = {}, this.updateRanges = [], this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isArrayTexture = !!(t && t.depth && t.depth > 1), this.pmremVersion = 0;
  }
  /**
   * The width of the texture in pixels.
   */
  get width() {
    return this.source.getSize(Vd).x;
  }
  /**
   * The height of the texture in pixels.
   */
  get height() {
    return this.source.getSize(Vd).y;
  }
  /**
   * The depth of the texture in pixels.
   */
  get depth() {
    return this.source.getSize(Vd).z;
  }
  /**
   * The image object holding the texture data.
   *
   * @type {?Object}
   */
  get image() {
    return this.source.data;
  }
  set image(t = null) {
    this.source.data = t;
  }
  /**
   * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
   * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
   */
  updateMatrix() {
    this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  }
  /**
   * Adds a range of data in the data texture to be updated on the GPU.
   *
   * @param {number} start - Position at which to start update.
   * @param {number} count - The number of components to update.
   */
  addUpdateRange(t, e) {
    this.updateRanges.push({ start: t, count: e });
  }
  /**
   * Clears the update ranges.
   */
  clearUpdateRanges() {
    this.updateRanges.length = 0;
  }
  /**
   * Returns a new texture with copied values from this instance.
   *
   * @return {Texture} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Copies the values of the given texture to this instance.
   *
   * @param {Texture} source - The texture to copy.
   * @return {Texture} A reference to this instance.
   */
  copy(t) {
    return this.name = t.name, this.source = t.source, this.mipmaps = t.mipmaps.slice(0), this.mapping = t.mapping, this.channel = t.channel, this.wrapS = t.wrapS, this.wrapT = t.wrapT, this.magFilter = t.magFilter, this.minFilter = t.minFilter, this.anisotropy = t.anisotropy, this.format = t.format, this.internalFormat = t.internalFormat, this.type = t.type, this.offset.copy(t.offset), this.repeat.copy(t.repeat), this.center.copy(t.center), this.rotation = t.rotation, this.matrixAutoUpdate = t.matrixAutoUpdate, this.matrix.copy(t.matrix), this.generateMipmaps = t.generateMipmaps, this.premultiplyAlpha = t.premultiplyAlpha, this.flipY = t.flipY, this.unpackAlignment = t.unpackAlignment, this.colorSpace = t.colorSpace, this.renderTarget = t.renderTarget, this.isRenderTargetTexture = t.isRenderTargetTexture, this.isArrayTexture = t.isArrayTexture, this.userData = JSON.parse(JSON.stringify(t.userData)), this.needsUpdate = !0, this;
  }
  /**
   * Sets this texture's properties based on `values`.
   * @param {Object} values - A container with texture parameters.
   */
  setValues(t) {
    for (const e in t) {
      const i = t[e];
      if (i === void 0) {
        console.warn(`THREE.Texture.setValues(): parameter '${e}' has value of undefined.`);
        continue;
      }
      const n = this[e];
      if (n === void 0) {
        console.warn(`THREE.Texture.setValues(): property '${e}' does not exist.`);
        continue;
      }
      n && i && n.isVector2 && i.isVector2 || n && i && n.isVector3 && i.isVector3 || n && i && n.isMatrix3 && i.isMatrix3 ? n.copy(i) : this[e] = i;
    }
  }
  /**
   * Serializes the texture into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized texture.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(t) {
    const e = t === void 0 || typeof t == "string";
    if (!e && t.textures[this.uuid] !== void 0)
      return t.textures[this.uuid];
    const i = {
      metadata: {
        version: 4.7,
        type: "Texture",
        generator: "Texture.toJSON"
      },
      uuid: this.uuid,
      name: this.name,
      image: this.source.toJSON(t).uuid,
      mapping: this.mapping,
      channel: this.channel,
      repeat: [this.repeat.x, this.repeat.y],
      offset: [this.offset.x, this.offset.y],
      center: [this.center.x, this.center.y],
      rotation: this.rotation,
      wrap: [this.wrapS, this.wrapT],
      format: this.format,
      internalFormat: this.internalFormat,
      type: this.type,
      colorSpace: this.colorSpace,
      minFilter: this.minFilter,
      magFilter: this.magFilter,
      anisotropy: this.anisotropy,
      flipY: this.flipY,
      generateMipmaps: this.generateMipmaps,
      premultiplyAlpha: this.premultiplyAlpha,
      unpackAlignment: this.unpackAlignment
    };
    return Object.keys(this.userData).length > 0 && (i.userData = this.userData), e || (t.textures[this.uuid] = i), i;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   *
   * @fires Texture#dispose
   */
  dispose() {
    this.dispatchEvent({ type: "dispose" });
  }
  /**
   * Transforms the given uv vector with the textures uv transformation matrix.
   *
   * @param {Vector2} uv - The uv vector.
   * @return {Vector2} The transformed uv vector.
   */
  transformUv(t) {
    if (this.mapping !== K_) return t;
    if (t.applyMatrix3(this.matrix), t.x < 0 || t.x > 1)
      switch (this.wrapS) {
        case Jg:
          t.x = t.x - Math.floor(t.x);
          break;
        case ph:
          t.x = t.x < 0 ? 0 : 1;
          break;
        case Kg:
          Math.abs(Math.floor(t.x) % 2) === 1 ? t.x = Math.ceil(t.x) - t.x : t.x = t.x - Math.floor(t.x);
          break;
      }
    if (t.y < 0 || t.y > 1)
      switch (this.wrapT) {
        case Jg:
          t.y = t.y - Math.floor(t.y);
          break;
        case ph:
          t.y = t.y < 0 ? 0 : 1;
          break;
        case Kg:
          Math.abs(Math.floor(t.y) % 2) === 1 ? t.y = Math.ceil(t.y) - t.y : t.y = t.y - Math.floor(t.y);
          break;
      }
    return this.flipY && (t.y = 1 - t.y), t;
  }
  /**
   * Setting this property to `true` indicates the engine the texture
   * must be updated in the next render. This triggers a texture upload
   * to the GPU and ensures correct texture parameter configuration.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsUpdate(t) {
    t === !0 && (this.version++, this.source.needsUpdate = !0);
  }
  /**
   * Setting this property to `true` indicates the engine the PMREM
   * must be regenerated.
   *
   * @type {boolean}
   * @default false
   * @param {boolean} value
   */
  set needsPMREMUpdate(t) {
    t === !0 && this.pmremVersion++;
  }
}
ur.DEFAULT_IMAGE = null;
ur.DEFAULT_MAPPING = K_;
ur.DEFAULT_ANISOTROPY = 1;
class es {
  /**
   * Constructs a new 4x4 matrix. The arguments are supposed to be
   * in row-major order. If no arguments are provided, the constructor
   * initializes the matrix as an identity matrix.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n14] - 1-4 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n24] - 2-4 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @param {number} [n34] - 3-4 matrix element.
   * @param {number} [n41] - 4-1 matrix element.
   * @param {number} [n42] - 4-2 matrix element.
   * @param {number} [n43] - 4-3 matrix element.
   * @param {number} [n44] - 4-4 matrix element.
   */
  constructor(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g) {
    es.prototype.isMatrix4 = !0, this.elements = [
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ], t !== void 0 && this.set(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g);
  }
  /**
   * Sets the elements of the matrix.The arguments are supposed to be
   * in row-major order.
   *
   * @param {number} [n11] - 1-1 matrix element.
   * @param {number} [n12] - 1-2 matrix element.
   * @param {number} [n13] - 1-3 matrix element.
   * @param {number} [n14] - 1-4 matrix element.
   * @param {number} [n21] - 2-1 matrix element.
   * @param {number} [n22] - 2-2 matrix element.
   * @param {number} [n23] - 2-3 matrix element.
   * @param {number} [n24] - 2-4 matrix element.
   * @param {number} [n31] - 3-1 matrix element.
   * @param {number} [n32] - 3-2 matrix element.
   * @param {number} [n33] - 3-3 matrix element.
   * @param {number} [n34] - 3-4 matrix element.
   * @param {number} [n41] - 4-1 matrix element.
   * @param {number} [n42] - 4-2 matrix element.
   * @param {number} [n43] - 4-3 matrix element.
   * @param {number} [n44] - 4-4 matrix element.
   * @return {Matrix4} A reference to this matrix.
   */
  set(t, e, i, n, s, r, o, l, h, c, u, d, p, f, y, g) {
    const m = this.elements;
    return m[0] = t, m[4] = e, m[8] = i, m[12] = n, m[1] = s, m[5] = r, m[9] = o, m[13] = l, m[2] = h, m[6] = c, m[10] = u, m[14] = d, m[3] = p, m[7] = f, m[11] = y, m[15] = g, this;
  }
  /**
   * Sets this matrix to the 4x4 identity matrix.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  identity() {
    return this.set(
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Returns a matrix with copied values from this instance.
   *
   * @return {Matrix4} A clone of this instance.
   */
  clone() {
    return new es().fromArray(this.elements);
  }
  /**
   * Copies the values of the given matrix to this instance.
   *
   * @param {Matrix4} m - The matrix to copy.
   * @return {Matrix4} A reference to this matrix.
   */
  copy(t) {
    const e = this.elements, i = t.elements;
    return e[0] = i[0], e[1] = i[1], e[2] = i[2], e[3] = i[3], e[4] = i[4], e[5] = i[5], e[6] = i[6], e[7] = i[7], e[8] = i[8], e[9] = i[9], e[10] = i[10], e[11] = i[11], e[12] = i[12], e[13] = i[13], e[14] = i[14], e[15] = i[15], this;
  }
  /**
   * Copies the translation component of the given matrix
   * into this matrix's translation component.
   *
   * @param {Matrix4} m - The matrix to copy the translation component.
   * @return {Matrix4} A reference to this matrix.
   */
  copyPosition(t) {
    const e = this.elements, i = t.elements;
    return e[12] = i[12], e[13] = i[13], e[14] = i[14], this;
  }
  /**
   * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
   *
   * @param {Matrix3} m - The 3x3 matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  setFromMatrix3(t) {
    const e = t.elements;
    return this.set(
      e[0],
      e[3],
      e[6],
      0,
      e[1],
      e[4],
      e[7],
      0,
      e[2],
      e[5],
      e[8],
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Extracts the basis of this matrix into the three axis vectors provided.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  extractBasis(t, e, i) {
    return t.setFromMatrixColumn(this, 0), e.setFromMatrixColumn(this, 1), i.setFromMatrixColumn(this, 2), this;
  }
  /**
   * Sets the given basis vectors to this matrix.
   *
   * @param {Vector3} xAxis - The basis's x axis.
   * @param {Vector3} yAxis - The basis's y axis.
   * @param {Vector3} zAxis - The basis's z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeBasis(t, e, i) {
    return this.set(
      t.x,
      e.x,
      i.x,
      0,
      t.y,
      e.y,
      i.y,
      0,
      t.z,
      e.z,
      i.z,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Extracts the rotation component of the given matrix
   * into this matrix's rotation component.
   *
   * Note: This method does not support reflection matrices.
   *
   * @param {Matrix4} m - The matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  extractRotation(t) {
    const e = this.elements, i = t.elements, n = 1 / Qr.setFromMatrixColumn(t, 0).length(), s = 1 / Qr.setFromMatrixColumn(t, 1).length(), r = 1 / Qr.setFromMatrixColumn(t, 2).length();
    return e[0] = i[0] * n, e[1] = i[1] * n, e[2] = i[2] * n, e[3] = 0, e[4] = i[4] * s, e[5] = i[5] * s, e[6] = i[6] * s, e[7] = 0, e[8] = i[8] * r, e[9] = i[9] * r, e[10] = i[10] * r, e[11] = 0, e[12] = 0, e[13] = 0, e[14] = 0, e[15] = 1, this;
  }
  /**
   * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
   * the rotation specified by the given Euler angles. The rest of
   * the matrix is set to the identity. Depending on the {@link Euler#order},
   * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
   * for a complete list.
   *
   * @param {Euler} euler - The Euler angles.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationFromEuler(t) {
    const e = this.elements, i = t.x, n = t.y, s = t.z, r = Math.cos(i), o = Math.sin(i), l = Math.cos(n), h = Math.sin(n), c = Math.cos(s), u = Math.sin(s);
    if (t.order === "XYZ") {
      const d = r * c, p = r * u, f = o * c, y = o * u;
      e[0] = l * c, e[4] = -l * u, e[8] = h, e[1] = p + f * h, e[5] = d - y * h, e[9] = -o * l, e[2] = y - d * h, e[6] = f + p * h, e[10] = r * l;
    } else if (t.order === "YXZ") {
      const d = l * c, p = l * u, f = h * c, y = h * u;
      e[0] = d + y * o, e[4] = f * o - p, e[8] = r * h, e[1] = r * u, e[5] = r * c, e[9] = -o, e[2] = p * o - f, e[6] = y + d * o, e[10] = r * l;
    } else if (t.order === "ZXY") {
      const d = l * c, p = l * u, f = h * c, y = h * u;
      e[0] = d - y * o, e[4] = -r * u, e[8] = f + p * o, e[1] = p + f * o, e[5] = r * c, e[9] = y - d * o, e[2] = -r * h, e[6] = o, e[10] = r * l;
    } else if (t.order === "ZYX") {
      const d = r * c, p = r * u, f = o * c, y = o * u;
      e[0] = l * c, e[4] = f * h - p, e[8] = d * h + y, e[1] = l * u, e[5] = y * h + d, e[9] = p * h - f, e[2] = -h, e[6] = o * l, e[10] = r * l;
    } else if (t.order === "YZX") {
      const d = r * l, p = r * h, f = o * l, y = o * h;
      e[0] = l * c, e[4] = y - d * u, e[8] = f * u + p, e[1] = u, e[5] = r * c, e[9] = -o * c, e[2] = -h * c, e[6] = p * u + f, e[10] = d - y * u;
    } else if (t.order === "XZY") {
      const d = r * l, p = r * h, f = o * l, y = o * h;
      e[0] = l * c, e[4] = -u, e[8] = h * c, e[1] = d * u + y, e[5] = r * c, e[9] = p * u - f, e[2] = f * u - p, e[6] = o * c, e[10] = y * u + d;
    }
    return e[3] = 0, e[7] = 0, e[11] = 0, e[12] = 0, e[13] = 0, e[14] = 0, e[15] = 1, this;
  }
  /**
   * Sets the rotation component of this matrix to the rotation specified by
   * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
   * The rest of the matrix is set to the identity.
   *
   * @param {Quaternion} q - The Quaternion.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationFromQuaternion(t) {
    return this.compose(MC, t, SC);
  }
  /**
   * Sets the rotation component of the transformation matrix, looking from `eye` towards
   * `target`, and oriented by the up-direction.
   *
   * @param {Vector3} eye - The eye vector.
   * @param {Vector3} target - The target vector.
   * @param {Vector3} up - The up vector.
   * @return {Matrix4} A reference to this matrix.
   */
  lookAt(t, e, i) {
    const n = this.elements;
    return Ui.subVectors(t, e), Ui.lengthSq() === 0 && (Ui.z = 1), Ui.normalize(), ys.crossVectors(i, Ui), ys.lengthSq() === 0 && (Math.abs(i.z) === 1 ? Ui.x += 1e-4 : Ui.z += 1e-4, Ui.normalize(), ys.crossVectors(i, Ui)), ys.normalize(), mh.crossVectors(Ui, ys), n[0] = ys.x, n[4] = mh.x, n[8] = Ui.x, n[1] = ys.y, n[5] = mh.y, n[9] = Ui.y, n[2] = ys.z, n[6] = mh.z, n[10] = Ui.z, this;
  }
  /**
   * Post-multiplies this matrix by the given 4x4 matrix.
   *
   * @param {Matrix4} m - The matrix to multiply with.
   * @return {Matrix4} A reference to this matrix.
   */
  multiply(t) {
    return this.multiplyMatrices(this, t);
  }
  /**
   * Pre-multiplies this matrix by the given 4x4 matrix.
   *
   * @param {Matrix4} m - The matrix to multiply with.
   * @return {Matrix4} A reference to this matrix.
   */
  premultiply(t) {
    return this.multiplyMatrices(t, this);
  }
  /**
   * Multiples the given 4x4 matrices and stores the result
   * in this matrix.
   *
   * @param {Matrix4} a - The first matrix.
   * @param {Matrix4} b - The second matrix.
   * @return {Matrix4} A reference to this matrix.
   */
  multiplyMatrices(t, e) {
    const i = t.elements, n = e.elements, s = this.elements, r = i[0], o = i[4], l = i[8], h = i[12], c = i[1], u = i[5], d = i[9], p = i[13], f = i[2], y = i[6], g = i[10], m = i[14], v = i[3], x = i[7], _ = i[11], S = i[15], w = n[0], T = n[4], R = n[8], b = n[12], M = n[1], L = n[5], U = n[9], O = n[13], V = n[2], W = n[6], G = n[10], et = n[14], H = n[3], at = n[7], pt = n[11], Mt = n[15];
    return s[0] = r * w + o * M + l * V + h * H, s[4] = r * T + o * L + l * W + h * at, s[8] = r * R + o * U + l * G + h * pt, s[12] = r * b + o * O + l * et + h * Mt, s[1] = c * w + u * M + d * V + p * H, s[5] = c * T + u * L + d * W + p * at, s[9] = c * R + u * U + d * G + p * pt, s[13] = c * b + u * O + d * et + p * Mt, s[2] = f * w + y * M + g * V + m * H, s[6] = f * T + y * L + g * W + m * at, s[10] = f * R + y * U + g * G + m * pt, s[14] = f * b + y * O + g * et + m * Mt, s[3] = v * w + x * M + _ * V + S * H, s[7] = v * T + x * L + _ * W + S * at, s[11] = v * R + x * U + _ * G + S * pt, s[15] = v * b + x * O + _ * et + S * Mt, this;
  }
  /**
   * Multiplies every component of the matrix by the given scalar.
   *
   * @param {number} s - The scalar.
   * @return {Matrix4} A reference to this matrix.
   */
  multiplyScalar(t) {
    const e = this.elements;
    return e[0] *= t, e[4] *= t, e[8] *= t, e[12] *= t, e[1] *= t, e[5] *= t, e[9] *= t, e[13] *= t, e[2] *= t, e[6] *= t, e[10] *= t, e[14] *= t, e[3] *= t, e[7] *= t, e[11] *= t, e[15] *= t, this;
  }
  /**
   * Computes and returns the determinant of this matrix.
   *
   * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
   *
   * @return {number} The determinant.
   */
  determinant() {
    const t = this.elements, e = t[0], i = t[4], n = t[8], s = t[12], r = t[1], o = t[5], l = t[9], h = t[13], c = t[2], u = t[6], d = t[10], p = t[14], f = t[3], y = t[7], g = t[11], m = t[15];
    return f * (+s * l * u - n * h * u - s * o * d + i * h * d + n * o * p - i * l * p) + y * (+e * l * p - e * h * d + s * r * d - n * r * p + n * h * c - s * l * c) + g * (+e * h * u - e * o * p - s * r * u + i * r * p + s * o * c - i * h * c) + m * (-n * o * c - e * l * u + e * o * d + n * r * u - i * r * d + i * l * c);
  }
  /**
   * Transposes this matrix in place.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  transpose() {
    const t = this.elements;
    let e;
    return e = t[1], t[1] = t[4], t[4] = e, e = t[2], t[2] = t[8], t[8] = e, e = t[6], t[6] = t[9], t[9] = e, e = t[3], t[3] = t[12], t[12] = e, e = t[7], t[7] = t[13], t[13] = e, e = t[11], t[11] = t[14], t[14] = e, this;
  }
  /**
   * Sets the position component for this matrix from the given vector,
   * without affecting the rest of the matrix.
   *
   * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
   * @param {number} y - The y component of the vector.
   * @param {number} z - The z component of the vector.
   * @return {Matrix4} A reference to this matrix.
   */
  setPosition(t, e, i) {
    const n = this.elements;
    return t.isVector3 ? (n[12] = t.x, n[13] = t.y, n[14] = t.z) : (n[12] = t, n[13] = e, n[14] = i), this;
  }
  /**
   * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
   * You can not invert with a determinant of zero. If you attempt this, the method produces
   * a zero matrix instead.
   *
   * @return {Matrix4} A reference to this matrix.
   */
  invert() {
    const t = this.elements, e = t[0], i = t[1], n = t[2], s = t[3], r = t[4], o = t[5], l = t[6], h = t[7], c = t[8], u = t[9], d = t[10], p = t[11], f = t[12], y = t[13], g = t[14], m = t[15], v = u * g * h - y * d * h + y * l * p - o * g * p - u * l * m + o * d * m, x = f * d * h - c * g * h - f * l * p + r * g * p + c * l * m - r * d * m, _ = c * y * h - f * u * h + f * o * p - r * y * p - c * o * m + r * u * m, S = f * u * l - c * y * l - f * o * d + r * y * d + c * o * g - r * u * g, w = e * v + i * x + n * _ + s * S;
    if (w === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    const T = 1 / w;
    return t[0] = v * T, t[1] = (y * d * s - u * g * s - y * n * p + i * g * p + u * n * m - i * d * m) * T, t[2] = (o * g * s - y * l * s + y * n * h - i * g * h - o * n * m + i * l * m) * T, t[3] = (u * l * s - o * d * s - u * n * h + i * d * h + o * n * p - i * l * p) * T, t[4] = x * T, t[5] = (c * g * s - f * d * s + f * n * p - e * g * p - c * n * m + e * d * m) * T, t[6] = (f * l * s - r * g * s - f * n * h + e * g * h + r * n * m - e * l * m) * T, t[7] = (r * d * s - c * l * s + c * n * h - e * d * h - r * n * p + e * l * p) * T, t[8] = _ * T, t[9] = (f * u * s - c * y * s - f * i * p + e * y * p + c * i * m - e * u * m) * T, t[10] = (r * y * s - f * o * s + f * i * h - e * y * h - r * i * m + e * o * m) * T, t[11] = (c * o * s - r * u * s - c * i * h + e * u * h + r * i * p - e * o * p) * T, t[12] = S * T, t[13] = (c * y * n - f * u * n + f * i * d - e * y * d - c * i * g + e * u * g) * T, t[14] = (f * o * n - r * y * n - f * i * l + e * y * l + r * i * g - e * o * g) * T, t[15] = (r * u * n - c * o * n + c * i * l - e * u * l - r * i * d + e * o * d) * T, this;
  }
  /**
   * Multiplies the columns of this matrix by the given vector.
   *
   * @param {Vector3} v - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  scale(t) {
    const e = this.elements, i = t.x, n = t.y, s = t.z;
    return e[0] *= i, e[4] *= n, e[8] *= s, e[1] *= i, e[5] *= n, e[9] *= s, e[2] *= i, e[6] *= n, e[10] *= s, e[3] *= i, e[7] *= n, e[11] *= s, this;
  }
  /**
   * Gets the maximum scale value of the three axes.
   *
   * @return {number} The maximum scale.
   */
  getMaxScaleOnAxis() {
    const t = this.elements, e = t[0] * t[0] + t[1] * t[1] + t[2] * t[2], i = t[4] * t[4] + t[5] * t[5] + t[6] * t[6], n = t[8] * t[8] + t[9] * t[9] + t[10] * t[10];
    return Math.sqrt(Math.max(e, i, n));
  }
  /**
   * Sets this matrix as a translation transform from the given vector.
   *
   * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
   * @param {number} y - The amount to translate in the Y axis.
   * @param {number} z - The amount to translate in the z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeTranslation(t, e, i) {
    return t.isVector3 ? this.set(
      1,
      0,
      0,
      t.x,
      0,
      1,
      0,
      t.y,
      0,
      0,
      1,
      t.z,
      0,
      0,
      0,
      1
    ) : this.set(
      1,
      0,
      0,
      t,
      0,
      1,
      0,
      e,
      0,
      0,
      1,
      i,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the X axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationX(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      1,
      0,
      0,
      0,
      0,
      e,
      -i,
      0,
      0,
      i,
      e,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the Y axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationY(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      0,
      i,
      0,
      0,
      1,
      0,
      0,
      -i,
      0,
      e,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the Z axis by
   * the given angle.
   *
   * @param {number} theta - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationZ(t) {
    const e = Math.cos(t), i = Math.sin(t);
    return this.set(
      e,
      -i,
      0,
      0,
      i,
      e,
      0,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a rotational transformation around the given axis by
   * the given angle.
   *
   * This is a somewhat controversial but mathematically sound alternative to
   * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
   *
   * @param {Vector3} axis - The normalized rotation axis.
   * @param {number} angle - The rotation in radians.
   * @return {Matrix4} A reference to this matrix.
   */
  makeRotationAxis(t, e) {
    const i = Math.cos(e), n = Math.sin(e), s = 1 - i, r = t.x, o = t.y, l = t.z, h = s * r, c = s * o;
    return this.set(
      h * r + i,
      h * o - n * l,
      h * l + n * o,
      0,
      h * o + n * l,
      c * o + i,
      c * l - n * r,
      0,
      h * l - n * o,
      c * l + n * r,
      s * l * l + i,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a scale transformation.
   *
   * @param {number} x - The amount to scale in the X axis.
   * @param {number} y - The amount to scale in the Y axis.
   * @param {number} z - The amount to scale in the Z axis.
   * @return {Matrix4} A reference to this matrix.
   */
  makeScale(t, e, i) {
    return this.set(
      t,
      0,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      0,
      i,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix as a shear transformation.
   *
   * @param {number} xy - The amount to shear X by Y.
   * @param {number} xz - The amount to shear X by Z.
   * @param {number} yx - The amount to shear Y by X.
   * @param {number} yz - The amount to shear Y by Z.
   * @param {number} zx - The amount to shear Z by X.
   * @param {number} zy - The amount to shear Z by Y.
   * @return {Matrix4} A reference to this matrix.
   */
  makeShear(t, e, i, n, s, r) {
    return this.set(
      1,
      i,
      s,
      0,
      t,
      1,
      r,
      0,
      e,
      n,
      1,
      0,
      0,
      0,
      0,
      1
    ), this;
  }
  /**
   * Sets this matrix to the transformation composed of the given position,
   * rotation (Quaternion) and scale.
   *
   * @param {Vector3} position - The position vector.
   * @param {Quaternion} quaternion - The rotation as a Quaternion.
   * @param {Vector3} scale - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  compose(t, e, i) {
    const n = this.elements, s = e._x, r = e._y, o = e._z, l = e._w, h = s + s, c = r + r, u = o + o, d = s * h, p = s * c, f = s * u, y = r * c, g = r * u, m = o * u, v = l * h, x = l * c, _ = l * u, S = i.x, w = i.y, T = i.z;
    return n[0] = (1 - (y + m)) * S, n[1] = (p + _) * S, n[2] = (f - x) * S, n[3] = 0, n[4] = (p - _) * w, n[5] = (1 - (d + m)) * w, n[6] = (g + v) * w, n[7] = 0, n[8] = (f + x) * T, n[9] = (g - v) * T, n[10] = (1 - (d + y)) * T, n[11] = 0, n[12] = t.x, n[13] = t.y, n[14] = t.z, n[15] = 1, this;
  }
  /**
   * Decomposes this matrix into its position, rotation and scale components
   * and provides the result in the given objects.
   *
   * Note: Not all matrices are decomposable in this way. For example, if an
   * object has a non-uniformly scaled parent, then the object's world matrix
   * may not be decomposable, and this method may not be appropriate.
   *
   * @param {Vector3} position - The position vector.
   * @param {Quaternion} quaternion - The rotation as a Quaternion.
   * @param {Vector3} scale - The scale vector.
   * @return {Matrix4} A reference to this matrix.
   */
  decompose(t, e, i) {
    const n = this.elements;
    let s = Qr.set(n[0], n[1], n[2]).length();
    const r = Qr.set(n[4], n[5], n[6]).length(), o = Qr.set(n[8], n[9], n[10]).length();
    this.determinant() < 0 && (s = -s), t.x = n[12], t.y = n[13], t.z = n[14], rn.copy(this);
    const h = 1 / s, c = 1 / r, u = 1 / o;
    return rn.elements[0] *= h, rn.elements[1] *= h, rn.elements[2] *= h, rn.elements[4] *= c, rn.elements[5] *= c, rn.elements[6] *= c, rn.elements[8] *= u, rn.elements[9] *= u, rn.elements[10] *= u, e.setFromRotationMatrix(rn), i.x = s, i.y = r, i.z = o, this;
  }
  /**
  	 * Creates a perspective projection matrix. This is used internally by
  	 * {@link PerspectiveCamera#updateProjectionMatrix}.
  
  	 * @param {number} left - Left boundary of the viewing frustum at the near plane.
  	 * @param {number} right - Right boundary of the viewing frustum at the near plane.
  	 * @param {number} top - Top boundary of the viewing frustum at the near plane.
  	 * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  	 * @param {number} near - The distance from the camera to the near plane.
  	 * @param {number} far - The distance from the camera to the far plane.
  	 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  	 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  	 * @return {Matrix4} A reference to this matrix.
  	 */
  makePerspective(t, e, i, n, s, r, o = fh, l = !1) {
    const h = this.elements, c = 2 * s / (e - t), u = 2 * s / (i - n), d = (e + t) / (e - t), p = (i + n) / (i - n);
    let f, y;
    if (l)
      f = s / (r - s), y = r * s / (r - s);
    else if (o === fh)
      f = -(r + s) / (r - s), y = -2 * r * s / (r - s);
    else if (o === e0)
      f = -r / (r - s), y = -r * s / (r - s);
    else
      throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + o);
    return h[0] = c, h[4] = 0, h[8] = d, h[12] = 0, h[1] = 0, h[5] = u, h[9] = p, h[13] = 0, h[2] = 0, h[6] = 0, h[10] = f, h[14] = y, h[3] = 0, h[7] = 0, h[11] = -1, h[15] = 0, this;
  }
  /**
  	 * Creates a orthographic projection matrix. This is used internally by
  	 * {@link OrthographicCamera#updateProjectionMatrix}.
  
  	 * @param {number} left - Left boundary of the viewing frustum at the near plane.
  	 * @param {number} right - Right boundary of the viewing frustum at the near plane.
  	 * @param {number} top - Top boundary of the viewing frustum at the near plane.
  	 * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  	 * @param {number} near - The distance from the camera to the near plane.
  	 * @param {number} far - The distance from the camera to the far plane.
  	 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  	 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  	 * @return {Matrix4} A reference to this matrix.
  	 */
  makeOrthographic(t, e, i, n, s, r, o = fh, l = !1) {
    const h = this.elements, c = 2 / (e - t), u = 2 / (i - n), d = -(e + t) / (e - t), p = -(i + n) / (i - n);
    let f, y;
    if (l)
      f = 1 / (r - s), y = r / (r - s);
    else if (o === fh)
      f = -2 / (r - s), y = -(r + s) / (r - s);
    else if (o === e0)
      f = -1 / (r - s), y = -s / (r - s);
    else
      throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + o);
    return h[0] = c, h[4] = 0, h[8] = 0, h[12] = d, h[1] = 0, h[5] = u, h[9] = 0, h[13] = p, h[2] = 0, h[6] = 0, h[10] = f, h[14] = y, h[3] = 0, h[7] = 0, h[11] = 0, h[15] = 1, this;
  }
  /**
   * Returns `true` if this matrix is equal with the given one.
   *
   * @param {Matrix4} matrix - The matrix to test for equality.
   * @return {boolean} Whether this matrix is equal with the given one.
   */
  equals(t) {
    const e = this.elements, i = t.elements;
    for (let n = 0; n < 16; n++)
      if (e[n] !== i[n]) return !1;
    return !0;
  }
  /**
   * Sets the elements of the matrix from the given array.
   *
   * @param {Array<number>} array - The matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Matrix4} A reference to this matrix.
   */
  fromArray(t, e = 0) {
    for (let i = 0; i < 16; i++)
      this.elements[i] = t[i + e];
    return this;
  }
  /**
   * Writes the elements of this matrix to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The matrix elements in column-major order.
   */
  toArray(t = [], e = 0) {
    const i = this.elements;
    return t[e] = i[0], t[e + 1] = i[1], t[e + 2] = i[2], t[e + 3] = i[3], t[e + 4] = i[4], t[e + 5] = i[5], t[e + 6] = i[6], t[e + 7] = i[7], t[e + 8] = i[8], t[e + 9] = i[9], t[e + 10] = i[10], t[e + 11] = i[11], t[e + 12] = i[12], t[e + 13] = i[13], t[e + 14] = i[14], t[e + 15] = i[15], t;
  }
}
const Qr = /* @__PURE__ */ new Fe(), rn = /* @__PURE__ */ new es(), MC = /* @__PURE__ */ new Fe(0, 0, 0), SC = /* @__PURE__ */ new Fe(1, 1, 1), ys = /* @__PURE__ */ new Fe(), mh = /* @__PURE__ */ new Fe(), Ui = /* @__PURE__ */ new Fe(), l0 = /* @__PURE__ */ new es(), h0 = /* @__PURE__ */ new $o();
class fu {
  /**
   * Constructs a new euler instance.
   *
   * @param {number} [x=0] - The angle of the x axis in radians.
   * @param {number} [y=0] - The angle of the y axis in radians.
   * @param {number} [z=0] - The angle of the z axis in radians.
   * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
   */
  constructor(t = 0, e = 0, i = 0, n = fu.DEFAULT_ORDER) {
    this.isEuler = !0, this._x = t, this._y = e, this._z = i, this._order = n;
  }
  /**
   * The angle of the x axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get x() {
    return this._x;
  }
  set x(t) {
    this._x = t, this._onChangeCallback();
  }
  /**
   * The angle of the y axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get y() {
    return this._y;
  }
  set y(t) {
    this._y = t, this._onChangeCallback();
  }
  /**
   * The angle of the z axis in radians.
   *
   * @type {number}
   * @default 0
   */
  get z() {
    return this._z;
  }
  set z(t) {
    this._z = t, this._onChangeCallback();
  }
  /**
   * A string representing the order that the rotations are applied.
   *
   * @type {string}
   * @default 'XYZ'
   */
  get order() {
    return this._order;
  }
  set order(t) {
    this._order = t, this._onChangeCallback();
  }
  /**
   * Sets the Euler components.
   *
   * @param {number} x - The angle of the x axis in radians.
   * @param {number} y - The angle of the y axis in radians.
   * @param {number} z - The angle of the z axis in radians.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  set(t, e, i, n = this._order) {
    return this._x = t, this._y = e, this._z = i, this._order = n, this._onChangeCallback(), this;
  }
  /**
   * Returns a new Euler instance with copied values from this instance.
   *
   * @return {Euler} A clone of this instance.
   */
  clone() {
    return new this.constructor(this._x, this._y, this._z, this._order);
  }
  /**
   * Copies the values of the given Euler instance to this instance.
   *
   * @param {Euler} euler - The Euler instance to copy.
   * @return {Euler} A reference to this Euler instance.
   */
  copy(t) {
    return this._x = t._x, this._y = t._y, this._z = t._z, this._order = t._order, this._onChangeCallback(), this;
  }
  /**
   * Sets the angles of this Euler instance from a pure rotation matrix.
   *
   * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromRotationMatrix(t, e = this._order, i = !0) {
    const n = t.elements, s = n[0], r = n[4], o = n[8], l = n[1], h = n[5], c = n[9], u = n[2], d = n[6], p = n[10];
    switch (e) {
      case "XYZ":
        this._y = Math.asin(ye(o, -1, 1)), Math.abs(o) < 0.9999999 ? (this._x = Math.atan2(-c, p), this._z = Math.atan2(-r, s)) : (this._x = Math.atan2(d, h), this._z = 0);
        break;
      case "YXZ":
        this._x = Math.asin(-ye(c, -1, 1)), Math.abs(c) < 0.9999999 ? (this._y = Math.atan2(o, p), this._z = Math.atan2(l, h)) : (this._y = Math.atan2(-u, s), this._z = 0);
        break;
      case "ZXY":
        this._x = Math.asin(ye(d, -1, 1)), Math.abs(d) < 0.9999999 ? (this._y = Math.atan2(-u, p), this._z = Math.atan2(-r, h)) : (this._y = 0, this._z = Math.atan2(l, s));
        break;
      case "ZYX":
        this._y = Math.asin(-ye(u, -1, 1)), Math.abs(u) < 0.9999999 ? (this._x = Math.atan2(d, p), this._z = Math.atan2(l, s)) : (this._x = 0, this._z = Math.atan2(-r, h));
        break;
      case "YZX":
        this._z = Math.asin(ye(l, -1, 1)), Math.abs(l) < 0.9999999 ? (this._x = Math.atan2(-c, h), this._y = Math.atan2(-u, s)) : (this._x = 0, this._y = Math.atan2(o, p));
        break;
      case "XZY":
        this._z = Math.asin(-ye(r, -1, 1)), Math.abs(r) < 0.9999999 ? (this._x = Math.atan2(d, h), this._y = Math.atan2(o, s)) : (this._x = Math.atan2(-c, p), this._y = 0);
        break;
      default:
        console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + e);
    }
    return this._order = e, i === !0 && this._onChangeCallback(), this;
  }
  /**
   * Sets the angles of this Euler instance from a normalized quaternion.
   *
   * @param {Quaternion} q - A normalized Quaternion.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromQuaternion(t, e, i) {
    return l0.makeRotationFromQuaternion(t), this.setFromRotationMatrix(l0, e, i);
  }
  /**
   * Sets the angles of this Euler instance from the given vector.
   *
   * @param {Vector3} v - The vector.
   * @param {string} [order] - A string representing the order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  setFromVector3(t, e = this._order) {
    return this.set(t.x, t.y, t.z, e);
  }
  /**
   * Resets the euler angle with a new order by creating a quaternion from this
   * euler angle and then setting this euler angle with the quaternion and the
   * new order.
   *
   * Warning: This discards revolution information.
   *
   * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
   * @return {Euler} A reference to this Euler instance.
   */
  reorder(t) {
    return h0.setFromEuler(this), this.setFromQuaternion(h0, t);
  }
  /**
   * Returns `true` if this Euler instance is equal with the given one.
   *
   * @param {Euler} euler - The Euler instance to test for equality.
   * @return {boolean} Whether this Euler instance is equal with the given one.
   */
  equals(t) {
    return t._x === this._x && t._y === this._y && t._z === this._z && t._order === this._order;
  }
  /**
   * Sets this Euler instance's components to values from the given array. The first three
   * entries of the array are assign to the x,y and z components. An optional fourth entry
   * defines the Euler order.
   *
   * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
   * @return {Euler} A reference to this Euler instance.
   */
  fromArray(t) {
    return this._x = t[0], this._y = t[1], this._z = t[2], t[3] !== void 0 && (this._order = t[3]), this._onChangeCallback(), this;
  }
  /**
   * Writes the components of this Euler instance to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number,number,number,string>} The Euler components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this._x, t[e + 1] = this._y, t[e + 2] = this._z, t[e + 3] = this._order, t;
  }
  _onChange(t) {
    return this._onChangeCallback = t, this;
  }
  _onChangeCallback() {
  }
  *[Symbol.iterator]() {
    yield this._x, yield this._y, yield this._z, yield this._order;
  }
}
fu.DEFAULT_ORDER = "XYZ";
class wC {
  /**
   * Constructs a new layers instance, with membership
   * initially set to layer `0`.
   */
  constructor() {
    this.mask = 1;
  }
  /**
   * Sets membership to the given layer, and remove membership all other layers.
   *
   * @param {number} layer - The layer to set.
   */
  set(t) {
    this.mask = (1 << t | 0) >>> 0;
  }
  /**
   * Adds membership of the given layer.
   *
   * @param {number} layer - The layer to enable.
   */
  enable(t) {
    this.mask |= 1 << t | 0;
  }
  /**
   * Adds membership to all layers.
   */
  enableAll() {
    this.mask = -1;
  }
  /**
   * Toggles the membership of the given layer.
   *
   * @param {number} layer - The layer to toggle.
   */
  toggle(t) {
    this.mask ^= 1 << t | 0;
  }
  /**
   * Removes membership of the given layer.
   *
   * @param {number} layer - The layer to enable.
   */
  disable(t) {
    this.mask &= ~(1 << t | 0);
  }
  /**
   * Removes the membership from all layers.
   */
  disableAll() {
    this.mask = 0;
  }
  /**
   * Returns `true` if this and the given layers object have at least one
   * layer in common.
   *
   * @param {Layers} layers - The layers to test.
   * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
   */
  test(t) {
    return (this.mask & t.mask) !== 0;
  }
  /**
   * Returns `true` if the given layer is enabled.
   *
   * @param {number} layer - The layer to test.
   * @return {boolean } Whether the given layer is enabled or not.
   */
  isEnabled(t) {
    return (this.mask & (1 << t | 0)) !== 0;
  }
}
let AC = 0;
const c0 = /* @__PURE__ */ new Fe(), ta = /* @__PURE__ */ new $o(), Wn = /* @__PURE__ */ new es(), gh = /* @__PURE__ */ new Fe(), io = /* @__PURE__ */ new Fe(), EC = /* @__PURE__ */ new Fe(), TC = /* @__PURE__ */ new $o(), u0 = /* @__PURE__ */ new Fe(1, 0, 0), d0 = /* @__PURE__ */ new Fe(0, 1, 0), p0 = /* @__PURE__ */ new Fe(0, 0, 1), f0 = { type: "added" }, CC = { type: "removed" }, ea = { type: "childadded", child: null }, Hd = { type: "childremoved", child: null };
class Es extends tx {
  /**
   * Constructs a new 3D object.
   */
  constructor() {
    super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: AC++ }), this.uuid = Mf(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = Es.DEFAULT_UP.clone();
    const t = new Fe(), e = new fu(), i = new $o(), n = new Fe(1, 1, 1);
    function s() {
      i.setFromEuler(e, !1);
    }
    function r() {
      e.setFromQuaternion(i, void 0, !1);
    }
    e._onChange(s), i._onChange(r), Object.defineProperties(this, {
      /**
       * Represents the object's local position.
       *
       * @name Object3D#position
       * @type {Vector3}
       * @default (0,0,0)
       */
      position: {
        configurable: !0,
        enumerable: !0,
        value: t
      },
      /**
       * Represents the object's local rotation as Euler angles, in radians.
       *
       * @name Object3D#rotation
       * @type {Euler}
       * @default (0,0,0)
       */
      rotation: {
        configurable: !0,
        enumerable: !0,
        value: e
      },
      /**
       * Represents the object's local rotation as Quaternions.
       *
       * @name Object3D#quaternion
       * @type {Quaternion}
       */
      quaternion: {
        configurable: !0,
        enumerable: !0,
        value: i
      },
      /**
       * Represents the object's local scale.
       *
       * @name Object3D#scale
       * @type {Vector3}
       * @default (1,1,1)
       */
      scale: {
        configurable: !0,
        enumerable: !0,
        value: n
      },
      /**
       * Represents the object's model-view matrix.
       *
       * @name Object3D#modelViewMatrix
       * @type {Matrix4}
       */
      modelViewMatrix: {
        value: new es()
      },
      /**
       * Represents the object's normal matrix.
       *
       * @name Object3D#normalMatrix
       * @type {Matrix3}
       */
      normalMatrix: {
        value: new _r()
      }
    }), this.matrix = new es(), this.matrixWorld = new es(), this.matrixAutoUpdate = Es.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = Es.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new wC(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.userData = {};
  }
  /**
   * A callback that is executed immediately before a 3D object is rendered to a shadow map.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {Camera} shadowCamera - The shadow camera.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} depthMaterial - The depth material.
   * @param {Object} group - The geometry group data.
   */
  onBeforeShadow() {
  }
  /**
   * A callback that is executed immediately after a 3D object is rendered to a shadow map.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {Camera} shadowCamera - The shadow camera.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} depthMaterial - The depth material.
   * @param {Object} group - The geometry group data.
   */
  onAfterShadow() {
  }
  /**
   * A callback that is executed immediately before a 3D object is rendered.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} material - The 3D object's material.
   * @param {Object} group - The geometry group data.
   */
  onBeforeRender() {
  }
  /**
   * A callback that is executed immediately after a 3D object is rendered.
   *
   * @param {Renderer|WebGLRenderer} renderer - The renderer.
   * @param {Object3D} object - The 3D object.
   * @param {Camera} camera - The camera that is used to render the scene.
   * @param {BufferGeometry} geometry - The 3D object's geometry.
   * @param {Material} material - The 3D object's material.
   * @param {Object} group - The geometry group data.
   */
  onAfterRender() {
  }
  /**
   * Applies the given transformation matrix to the object and updates the object's position,
   * rotation and scale.
   *
   * @param {Matrix4} matrix - The transformation matrix.
   */
  applyMatrix4(t) {
    this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(t), this.matrix.decompose(this.position, this.quaternion, this.scale);
  }
  /**
   * Applies a rotation represented by given the quaternion to the 3D object.
   *
   * @param {Quaternion} q - The quaternion.
   * @return {Object3D} A reference to this instance.
   */
  applyQuaternion(t) {
    return this.quaternion.premultiply(t), this;
  }
  /**
   * Sets the given rotation represented as an axis/angle couple to the 3D object.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   */
  setRotationFromAxisAngle(t, e) {
    this.quaternion.setFromAxisAngle(t, e);
  }
  /**
   * Sets the given rotation represented as Euler angles to the 3D object.
   *
   * @param {Euler} euler - The Euler angles.
   */
  setRotationFromEuler(t) {
    this.quaternion.setFromEuler(t, !0);
  }
  /**
   * Sets the given rotation represented as rotation matrix to the 3D object.
   *
   * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
   * a pure rotation matrix (i.e, unscaled).
   */
  setRotationFromMatrix(t) {
    this.quaternion.setFromRotationMatrix(t);
  }
  /**
   * Sets the given rotation represented as a Quaternion to the 3D object.
   *
   * @param {Quaternion} q - The Quaternion
   */
  setRotationFromQuaternion(t) {
    this.quaternion.copy(t);
  }
  /**
   * Rotates the 3D object along an axis in local space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateOnAxis(t, e) {
    return ta.setFromAxisAngle(t, e), this.quaternion.multiply(ta), this;
  }
  /**
   * Rotates the 3D object along an axis in world space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateOnWorldAxis(t, e) {
    return ta.setFromAxisAngle(t, e), this.quaternion.premultiply(ta), this;
  }
  /**
   * Rotates the 3D object around its X axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateX(t) {
    return this.rotateOnAxis(u0, t);
  }
  /**
   * Rotates the 3D object around its Y axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateY(t) {
    return this.rotateOnAxis(d0, t);
  }
  /**
   * Rotates the 3D object around its Z axis in local space.
   *
   * @param {number} angle - The angle in radians.
   * @return {Object3D} A reference to this instance.
   */
  rotateZ(t) {
    return this.rotateOnAxis(p0, t);
  }
  /**
   * Translate the 3D object by a distance along the given axis in local space.
   *
   * @param {Vector3} axis - The (normalized) axis vector.
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateOnAxis(t, e) {
    return c0.copy(t).applyQuaternion(this.quaternion), this.position.add(c0.multiplyScalar(e)), this;
  }
  /**
   * Translate the 3D object by a distance along its X-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateX(t) {
    return this.translateOnAxis(u0, t);
  }
  /**
   * Translate the 3D object by a distance along its Y-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateY(t) {
    return this.translateOnAxis(d0, t);
  }
  /**
   * Translate the 3D object by a distance along its Z-axis in local space.
   *
   * @param {number} distance - The distance in world units.
   * @return {Object3D} A reference to this instance.
   */
  translateZ(t) {
    return this.translateOnAxis(p0, t);
  }
  /**
   * Converts the given vector from this 3D object's local space to world space.
   *
   * @param {Vector3} vector - The vector to convert.
   * @return {Vector3} The converted vector.
   */
  localToWorld(t) {
    return this.updateWorldMatrix(!0, !1), t.applyMatrix4(this.matrixWorld);
  }
  /**
   * Converts the given vector from this 3D object's word space to local space.
   *
   * @param {Vector3} vector - The vector to convert.
   * @return {Vector3} The converted vector.
   */
  worldToLocal(t) {
    return this.updateWorldMatrix(!0, !1), t.applyMatrix4(Wn.copy(this.matrixWorld).invert());
  }
  /**
   * Rotates the object to face a point in world space.
   *
   * This method does not support objects having non-uniformly-scaled parent(s).
   *
   * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
   * @param {number} [y] - The y coordinate in world space.
   * @param {number} [z] - The z coordinate in world space.
   */
  lookAt(t, e, i) {
    t.isVector3 ? gh.copy(t) : gh.set(t, e, i);
    const n = this.parent;
    this.updateWorldMatrix(!0, !1), io.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? Wn.lookAt(io, gh, this.up) : Wn.lookAt(gh, io, this.up), this.quaternion.setFromRotationMatrix(Wn), n && (Wn.extractRotation(n.matrixWorld), ta.setFromRotationMatrix(Wn), this.quaternion.premultiply(ta.invert()));
  }
  /**
   * Adds the given 3D object as a child to this 3D object. An arbitrary number of
   * objects may be added. Any current parent on an object passed in here will be
   * removed, since an object can have at most one parent.
   *
   * @fires Object3D#added
   * @fires Object3D#childadded
   * @param {Object3D} object - The 3D object to add.
   * @return {Object3D} A reference to this instance.
   */
  add(t) {
    if (arguments.length > 1) {
      for (let e = 0; e < arguments.length; e++)
        this.add(arguments[e]);
      return this;
    }
    return t === this ? (console.error("THREE.Object3D.add: object can't be added as a child of itself.", t), this) : (t && t.isObject3D ? (t.removeFromParent(), t.parent = this, this.children.push(t), t.dispatchEvent(f0), ea.child = t, this.dispatchEvent(ea), ea.child = null) : console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", t), this);
  }
  /**
   * Removes the given 3D object as child from this 3D object.
   * An arbitrary number of objects may be removed.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @param {Object3D} object - The 3D object to remove.
   * @return {Object3D} A reference to this instance.
   */
  remove(t) {
    if (arguments.length > 1) {
      for (let i = 0; i < arguments.length; i++)
        this.remove(arguments[i]);
      return this;
    }
    const e = this.children.indexOf(t);
    return e !== -1 && (t.parent = null, this.children.splice(e, 1), t.dispatchEvent(CC), Hd.child = t, this.dispatchEvent(Hd), Hd.child = null), this;
  }
  /**
   * Removes this 3D object from its current parent.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @return {Object3D} A reference to this instance.
   */
  removeFromParent() {
    const t = this.parent;
    return t !== null && t.remove(this), this;
  }
  /**
   * Removes all child objects.
   *
   * @fires Object3D#removed
   * @fires Object3D#childremoved
   * @return {Object3D} A reference to this instance.
   */
  clear() {
    return this.remove(...this.children);
  }
  /**
   * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
   * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
   *
   * @fires Object3D#added
   * @fires Object3D#childadded
   * @param {Object3D} object - The 3D object to attach.
   * @return {Object3D} A reference to this instance.
   */
  attach(t) {
    return this.updateWorldMatrix(!0, !1), Wn.copy(this.matrixWorld).invert(), t.parent !== null && (t.parent.updateWorldMatrix(!0, !1), Wn.multiply(t.parent.matrixWorld)), t.applyMatrix4(Wn), t.removeFromParent(), t.parent = this, this.children.push(t), t.updateWorldMatrix(!1, !0), t.dispatchEvent(f0), ea.child = t, this.dispatchEvent(ea), ea.child = null, this;
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching ID.
   *
   * @param {number} id - The id.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectById(t) {
    return this.getObjectByProperty("id", t);
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching name.
   *
   * @param {string} name - The name.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectByName(t) {
    return this.getObjectByProperty("name", t);
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns the first with a matching property value.
   *
   * @param {string} name - The name of the property.
   * @param {any} value - The value.
   * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
   */
  getObjectByProperty(t, e) {
    if (this[t] === e) return this;
    for (let i = 0, n = this.children.length; i < n; i++) {
      const r = this.children[i].getObjectByProperty(t, e);
      if (r !== void 0)
        return r;
    }
  }
  /**
   * Searches through the 3D object and its children, starting with the 3D object
   * itself, and returns all 3D objects with a matching property value.
   *
   * @param {string} name - The name of the property.
   * @param {any} value - The value.
   * @param {Array<Object3D>} result - The method stores the result in this array.
   * @return {Array<Object3D>} The found 3D objects.
   */
  getObjectsByProperty(t, e, i = []) {
    this[t] === e && i.push(this);
    const n = this.children;
    for (let s = 0, r = n.length; s < r; s++)
      n[s].getObjectsByProperty(t, e, i);
    return i;
  }
  /**
   * Returns a vector representing the position of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's position in world space.
   */
  getWorldPosition(t) {
    return this.updateWorldMatrix(!0, !1), t.setFromMatrixPosition(this.matrixWorld);
  }
  /**
   * Returns a Quaternion representing the position of the 3D object in world space.
   *
   * @param {Quaternion} target - The target Quaternion the result is stored to.
   * @return {Quaternion} The 3D object's rotation in world space.
   */
  getWorldQuaternion(t) {
    return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(io, t, EC), t;
  }
  /**
   * Returns a vector representing the scale of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's scale in world space.
   */
  getWorldScale(t) {
    return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(io, TC, t), t;
  }
  /**
   * Returns a vector representing the ("look") direction of the 3D object in world space.
   *
   * @param {Vector3} target - The target vector the result is stored to.
   * @return {Vector3} The 3D object's direction in world space.
   */
  getWorldDirection(t) {
    this.updateWorldMatrix(!0, !1);
    const e = this.matrixWorld.elements;
    return t.set(e[8], e[9], e[10]).normalize();
  }
  /**
   * Abstract method to get intersections between a casted ray and this
   * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
   * implement this method in order to use raycasting.
   *
   * @abstract
   * @param {Raycaster} raycaster - The raycaster.
   * @param {Array<Object>} intersects - An array holding the result of the method.
   */
  raycast() {
  }
  /**
   * Executes the callback on this 3D object and all descendants.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverse(t) {
    t(this);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].traverse(t);
  }
  /**
   * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
   * Descendants of invisible 3D objects are not traversed.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverseVisible(t) {
    if (this.visible === !1) return;
    t(this);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].traverseVisible(t);
  }
  /**
   * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
   *
   * Note: Modifying the scene graph inside the callback is discouraged.
   *
   * @param {Function} callback - A callback function that allows to process the current 3D object.
   */
  traverseAncestors(t) {
    const e = this.parent;
    e !== null && (t(e), e.traverseAncestors(t));
  }
  /**
   * Updates the transformation matrix in local space by computing it from the current
   * position, rotation and scale values.
   */
  updateMatrix() {
    this.matrix.compose(this.position, this.quaternion, this.scale), this.matrixWorldNeedsUpdate = !0;
  }
  /**
   * Updates the transformation matrix in world space of this 3D objects and its descendants.
   *
   * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
   * local space. The computation of the local and world matrix can be controlled with the
   * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
   * `true` by default.  Set these flags to `false` if you need more control over the update matrix process.
   *
   * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
   * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
   */
  updateMatrixWorld(t) {
    this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || t) && (this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = !1, t = !0);
    const e = this.children;
    for (let i = 0, n = e.length; i < n; i++)
      e[i].updateMatrixWorld(t);
  }
  /**
   * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
   * update of ancestor and descendant nodes.
   *
   * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
   * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
   */
  updateWorldMatrix(t, e) {
    const i = this.parent;
    if (t === !0 && i !== null && i.updateWorldMatrix(!0, !1), this.matrixAutoUpdate && this.updateMatrix(), this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), e === !0) {
      const n = this.children;
      for (let s = 0, r = n.length; s < r; s++)
        n[s].updateWorldMatrix(!1, !0);
    }
  }
  /**
   * Serializes the 3D object into JSON.
   *
   * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
   * @return {Object} A JSON object representing the serialized 3D object.
   * @see {@link ObjectLoader#parse}
   */
  toJSON(t) {
    const e = t === void 0 || typeof t == "string", i = {};
    e && (t = {
      geometries: {},
      materials: {},
      textures: {},
      images: {},
      shapes: {},
      skeletons: {},
      animations: {},
      nodes: {}
    }, i.metadata = {
      version: 4.7,
      type: "Object",
      generator: "Object3D.toJSON"
    });
    const n = {};
    n.uuid = this.uuid, n.type = this.type, this.name !== "" && (n.name = this.name), this.castShadow === !0 && (n.castShadow = !0), this.receiveShadow === !0 && (n.receiveShadow = !0), this.visible === !1 && (n.visible = !1), this.frustumCulled === !1 && (n.frustumCulled = !1), this.renderOrder !== 0 && (n.renderOrder = this.renderOrder), Object.keys(this.userData).length > 0 && (n.userData = this.userData), n.layers = this.layers.mask, n.matrix = this.matrix.toArray(), n.up = this.up.toArray(), this.matrixAutoUpdate === !1 && (n.matrixAutoUpdate = !1), this.isInstancedMesh && (n.type = "InstancedMesh", n.count = this.count, n.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (n.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (n.type = "BatchedMesh", n.perObjectFrustumCulled = this.perObjectFrustumCulled, n.sortObjects = this.sortObjects, n.drawRanges = this._drawRanges, n.reservedRanges = this._reservedRanges, n.geometryInfo = this._geometryInfo.map((o) => ({
      ...o,
      boundingBox: o.boundingBox ? o.boundingBox.toJSON() : void 0,
      boundingSphere: o.boundingSphere ? o.boundingSphere.toJSON() : void 0
    })), n.instanceInfo = this._instanceInfo.map((o) => ({ ...o })), n.availableInstanceIds = this._availableInstanceIds.slice(), n.availableGeometryIds = this._availableGeometryIds.slice(), n.nextIndexStart = this._nextIndexStart, n.nextVertexStart = this._nextVertexStart, n.geometryCount = this._geometryCount, n.maxInstanceCount = this._maxInstanceCount, n.maxVertexCount = this._maxVertexCount, n.maxIndexCount = this._maxIndexCount, n.geometryInitialized = this._geometryInitialized, n.matricesTexture = this._matricesTexture.toJSON(t), n.indirectTexture = this._indirectTexture.toJSON(t), this._colorsTexture !== null && (n.colorsTexture = this._colorsTexture.toJSON(t)), this.boundingSphere !== null && (n.boundingSphere = this.boundingSphere.toJSON()), this.boundingBox !== null && (n.boundingBox = this.boundingBox.toJSON()));
    function s(o, l) {
      return o[l.uuid] === void 0 && (o[l.uuid] = l.toJSON(t)), l.uuid;
    }
    if (this.isScene)
      this.background && (this.background.isColor ? n.background = this.background.toJSON() : this.background.isTexture && (n.background = this.background.toJSON(t).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (n.environment = this.environment.toJSON(t).uuid);
    else if (this.isMesh || this.isLine || this.isPoints) {
      n.geometry = s(t.geometries, this.geometry);
      const o = this.geometry.parameters;
      if (o !== void 0 && o.shapes !== void 0) {
        const l = o.shapes;
        if (Array.isArray(l))
          for (let h = 0, c = l.length; h < c; h++) {
            const u = l[h];
            s(t.shapes, u);
          }
        else
          s(t.shapes, l);
      }
    }
    if (this.isSkinnedMesh && (n.bindMode = this.bindMode, n.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (s(t.skeletons, this.skeleton), n.skeleton = this.skeleton.uuid)), this.material !== void 0)
      if (Array.isArray(this.material)) {
        const o = [];
        for (let l = 0, h = this.material.length; l < h; l++)
          o.push(s(t.materials, this.material[l]));
        n.material = o;
      } else
        n.material = s(t.materials, this.material);
    if (this.children.length > 0) {
      n.children = [];
      for (let o = 0; o < this.children.length; o++)
        n.children.push(this.children[o].toJSON(t).object);
    }
    if (this.animations.length > 0) {
      n.animations = [];
      for (let o = 0; o < this.animations.length; o++) {
        const l = this.animations[o];
        n.animations.push(s(t.animations, l));
      }
    }
    if (e) {
      const o = r(t.geometries), l = r(t.materials), h = r(t.textures), c = r(t.images), u = r(t.shapes), d = r(t.skeletons), p = r(t.animations), f = r(t.nodes);
      o.length > 0 && (i.geometries = o), l.length > 0 && (i.materials = l), h.length > 0 && (i.textures = h), c.length > 0 && (i.images = c), u.length > 0 && (i.shapes = u), d.length > 0 && (i.skeletons = d), p.length > 0 && (i.animations = p), f.length > 0 && (i.nodes = f);
    }
    return i.object = n, i;
    function r(o) {
      const l = [];
      for (const h in o) {
        const c = o[h];
        delete c.metadata, l.push(c);
      }
      return l;
    }
  }
  /**
   * Returns a new 3D object with copied values from this instance.
   *
   * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
   * @return {Object3D} A clone of this instance.
   */
  clone(t) {
    return new this.constructor().copy(this, t);
  }
  /**
   * Copies the values of the given 3D object to this instance.
   *
   * @param {Object3D} source - The 3D object to copy.
   * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
   * @return {Object3D} A reference to this instance.
   */
  copy(t, e = !0) {
    if (this.name = t.name, this.up.copy(t.up), this.position.copy(t.position), this.rotation.order = t.rotation.order, this.quaternion.copy(t.quaternion), this.scale.copy(t.scale), this.matrix.copy(t.matrix), this.matrixWorld.copy(t.matrixWorld), this.matrixAutoUpdate = t.matrixAutoUpdate, this.matrixWorldAutoUpdate = t.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = t.matrixWorldNeedsUpdate, this.layers.mask = t.layers.mask, this.visible = t.visible, this.castShadow = t.castShadow, this.receiveShadow = t.receiveShadow, this.frustumCulled = t.frustumCulled, this.renderOrder = t.renderOrder, this.animations = t.animations.slice(), this.userData = JSON.parse(JSON.stringify(t.userData)), e === !0)
      for (let i = 0; i < t.children.length; i++) {
        const n = t.children[i];
        this.add(n.clone());
      }
    return this;
  }
}
Es.DEFAULT_UP = /* @__PURE__ */ new Fe(0, 1, 0);
Es.DEFAULT_MATRIX_AUTO_UPDATE = !0;
Es.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0;
const ex = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
}, _s = { h: 0, s: 0, l: 0 }, yh = { h: 0, s: 0, l: 0 };
function Gd(a, t, e) {
  return e < 0 && (e += 1), e > 1 && (e -= 1), e < 1 / 6 ? a + (t - a) * 6 * e : e < 1 / 2 ? t : e < 2 / 3 ? a + (t - a) * 6 * (2 / 3 - e) : a;
}
class Bi {
  /**
   * Constructs a new color.
   *
   * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
   * and that method is used throughout the rest of the documentation.
   *
   * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
   * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
   * @param {number} [g] - The green component.
   * @param {number} [b] - The blue component.
   */
  constructor(t, e, i) {
    return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(t, e, i);
  }
  /**
   * Sets the colors's components from the given values.
   *
   * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
   * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
   * @param {number} [g] - The green component.
   * @param {number} [b] - The blue component.
   * @return {Color} A reference to this color.
   */
  set(t, e, i) {
    if (e === void 0 && i === void 0) {
      const n = t;
      n && n.isColor ? this.copy(n) : typeof n == "number" ? this.setHex(n) : typeof n == "string" && this.setStyle(n);
    } else
      this.setRGB(t, e, i);
    return this;
  }
  /**
   * Sets the colors's components to the given scalar value.
   *
   * @param {number} scalar - The scalar value.
   * @return {Color} A reference to this color.
   */
  setScalar(t) {
    return this.r = t, this.g = t, this.b = t, this;
  }
  /**
   * Sets this color from a hexadecimal value.
   *
   * @param {number} hex - The hexadecimal value.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setHex(t, e = on) {
    return t = Math.floor(t), this.r = (t >> 16 & 255) / 255, this.g = (t >> 8 & 255) / 255, this.b = (t & 255) / 255, sn.colorSpaceToWorking(this, e), this;
  }
  /**
   * Sets this color from RGB values.
   *
   * @param {number} r - Red channel value between `0.0` and `1.0`.
   * @param {number} g - Green channel value between `0.0` and `1.0`.
   * @param {number} b - Blue channel value between `0.0` and `1.0`.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setRGB(t, e, i, n = sn.workingColorSpace) {
    return this.r = t, this.g = e, this.b = i, sn.colorSpaceToWorking(this, n), this;
  }
  /**
   * Sets this color from RGB values.
   *
   * @param {number} h - Hue value between `0.0` and `1.0`.
   * @param {number} s - Saturation value between `0.0` and `1.0`.
   * @param {number} l - Lightness value between `0.0` and `1.0`.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setHSL(t, e, i, n = sn.workingColorSpace) {
    if (t = gC(t, 1), e = ye(e, 0, 1), i = ye(i, 0, 1), e === 0)
      this.r = this.g = this.b = i;
    else {
      const s = i <= 0.5 ? i * (1 + e) : i + e - i * e, r = 2 * i - s;
      this.r = Gd(r, s, t + 1 / 3), this.g = Gd(r, s, t), this.b = Gd(r, s, t - 1 / 3);
    }
    return sn.colorSpaceToWorking(this, n), this;
  }
  /**
   * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
   * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
   * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
   * all 140 color names are supported).
   *
   * @param {string} style - Color as a CSS-style string.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setStyle(t, e = on) {
    function i(s) {
      s !== void 0 && parseFloat(s) < 1 && console.warn("THREE.Color: Alpha component of " + t + " will be ignored.");
    }
    let n;
    if (n = /^(\w+)\(([^\)]*)\)/.exec(t)) {
      let s;
      const r = n[1], o = n[2];
      switch (r) {
        case "rgb":
        case "rgba":
          if (s = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setRGB(
              Math.min(255, parseInt(s[1], 10)) / 255,
              Math.min(255, parseInt(s[2], 10)) / 255,
              Math.min(255, parseInt(s[3], 10)) / 255,
              e
            );
          if (s = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setRGB(
              Math.min(100, parseInt(s[1], 10)) / 100,
              Math.min(100, parseInt(s[2], 10)) / 100,
              Math.min(100, parseInt(s[3], 10)) / 100,
              e
            );
          break;
        case "hsl":
        case "hsla":
          if (s = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))
            return i(s[4]), this.setHSL(
              parseFloat(s[1]) / 360,
              parseFloat(s[2]) / 100,
              parseFloat(s[3]) / 100,
              e
            );
          break;
        default:
          console.warn("THREE.Color: Unknown color model " + t);
      }
    } else if (n = /^\#([A-Fa-f\d]+)$/.exec(t)) {
      const s = n[1], r = s.length;
      if (r === 3)
        return this.setRGB(
          parseInt(s.charAt(0), 16) / 15,
          parseInt(s.charAt(1), 16) / 15,
          parseInt(s.charAt(2), 16) / 15,
          e
        );
      if (r === 6)
        return this.setHex(parseInt(s, 16), e);
      console.warn("THREE.Color: Invalid hex color " + t);
    } else if (t && t.length > 0)
      return this.setColorName(t, e);
    return this;
  }
  /**
   * Sets this color from a color name. Faster than {@link Color#setStyle} if
   * you don't need the other CSS-style formats.
   *
   * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
   * ```js
   * Color.NAMES.aliceblue // returns 0xF0F8FF
   * ```
   *
   * @param {string} style - The color name.
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {Color} A reference to this color.
   */
  setColorName(t, e = on) {
    const i = ex[t.toLowerCase()];
    return i !== void 0 ? this.setHex(i, e) : console.warn("THREE.Color: Unknown color " + t), this;
  }
  /**
   * Returns a new color with copied values from this instance.
   *
   * @return {Color} A clone of this instance.
   */
  clone() {
    return new this.constructor(this.r, this.g, this.b);
  }
  /**
   * Copies the values of the given color to this instance.
   *
   * @param {Color} color - The color to copy.
   * @return {Color} A reference to this color.
   */
  copy(t) {
    return this.r = t.r, this.g = t.g, this.b = t.b, this;
  }
  /**
   * Copies the given color into this color, and then converts this color from
   * `SRGBColorSpace` to `LinearSRGBColorSpace`.
   *
   * @param {Color} color - The color to copy/convert.
   * @return {Color} A reference to this color.
   */
  copySRGBToLinear(t) {
    return this.r = ts(t.r), this.g = ts(t.g), this.b = ts(t.b), this;
  }
  /**
   * Copies the given color into this color, and then converts this color from
   * `LinearSRGBColorSpace` to `SRGBColorSpace`.
   *
   * @param {Color} color - The color to copy/convert.
   * @return {Color} A reference to this color.
   */
  copyLinearToSRGB(t) {
    return this.r = ua(t.r), this.g = ua(t.g), this.b = ua(t.b), this;
  }
  /**
   * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
   *
   * @return {Color} A reference to this color.
   */
  convertSRGBToLinear() {
    return this.copySRGBToLinear(this), this;
  }
  /**
   * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
   *
   * @return {Color} A reference to this color.
   */
  convertLinearToSRGB() {
    return this.copyLinearToSRGB(this), this;
  }
  /**
   * Returns the hexadecimal value of this color.
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {number} The hexadecimal value.
   */
  getHex(t = on) {
    return sn.workingToColorSpace(ni.copy(this), t), Math.round(ye(ni.r * 255, 0, 255)) * 65536 + Math.round(ye(ni.g * 255, 0, 255)) * 256 + Math.round(ye(ni.b * 255, 0, 255));
  }
  /**
   * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {string} The hexadecimal value as a string.
   */
  getHexString(t = on) {
    return ("000000" + this.getHex(t).toString(16)).slice(-6);
  }
  /**
   * Converts the colors RGB values into the HSL format and stores them into the
   * given target object.
   *
   * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {{h:number,s:number,l:number}} The HSL representation of this color.
   */
  getHSL(t, e = sn.workingColorSpace) {
    sn.workingToColorSpace(ni.copy(this), e);
    const i = ni.r, n = ni.g, s = ni.b, r = Math.max(i, n, s), o = Math.min(i, n, s);
    let l, h;
    const c = (o + r) / 2;
    if (o === r)
      l = 0, h = 0;
    else {
      const u = r - o;
      switch (h = c <= 0.5 ? u / (r + o) : u / (2 - r - o), r) {
        case i:
          l = (n - s) / u + (n < s ? 6 : 0);
          break;
        case n:
          l = (s - i) / u + 2;
          break;
        case s:
          l = (i - n) / u + 4;
          break;
      }
      l /= 6;
    }
    return t.h = l, t.s = h, t.l = c, t;
  }
  /**
   * Returns the RGB values of this color and stores them into the given target object.
   *
   * @param {Color} target - The target color that is used to store the method's result.
   * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
   * @return {Color} The RGB representation of this color.
   */
  getRGB(t, e = sn.workingColorSpace) {
    return sn.workingToColorSpace(ni.copy(this), e), t.r = ni.r, t.g = ni.g, t.b = ni.b, t;
  }
  /**
   * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
   *
   * @param {string} [colorSpace=SRGBColorSpace] - The color space.
   * @return {string} The CSS representation of this color.
   */
  getStyle(t = on) {
    sn.workingToColorSpace(ni.copy(this), t);
    const e = ni.r, i = ni.g, n = ni.b;
    return t !== on ? `color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})` : `rgb(${Math.round(e * 255)},${Math.round(i * 255)},${Math.round(n * 255)})`;
  }
  /**
   * Adds the given HSL values to this color's values.
   * Internally, this converts the color's RGB values to HSL, adds HSL
   * and then converts the color back to RGB.
   *
   * @param {number} h - Hue value between `0.0` and `1.0`.
   * @param {number} s - Saturation value between `0.0` and `1.0`.
   * @param {number} l - Lightness value between `0.0` and `1.0`.
   * @return {Color} A reference to this color.
   */
  offsetHSL(t, e, i) {
    return this.getHSL(_s), this.setHSL(_s.h + t, _s.s + e, _s.l + i);
  }
  /**
   * Adds the RGB values of the given color to the RGB values of this color.
   *
   * @param {Color} color - The color to add.
   * @return {Color} A reference to this color.
   */
  add(t) {
    return this.r += t.r, this.g += t.g, this.b += t.b, this;
  }
  /**
   * Adds the RGB values of the given colors and stores the result in this instance.
   *
   * @param {Color} color1 - The first color.
   * @param {Color} color2 - The second color.
   * @return {Color} A reference to this color.
   */
  addColors(t, e) {
    return this.r = t.r + e.r, this.g = t.g + e.g, this.b = t.b + e.b, this;
  }
  /**
   * Adds the given scalar value to the RGB values of this color.
   *
   * @param {number} s - The scalar to add.
   * @return {Color} A reference to this color.
   */
  addScalar(t) {
    return this.r += t, this.g += t, this.b += t, this;
  }
  /**
   * Subtracts the RGB values of the given color from the RGB values of this color.
   *
   * @param {Color} color - The color to subtract.
   * @return {Color} A reference to this color.
   */
  sub(t) {
    return this.r = Math.max(0, this.r - t.r), this.g = Math.max(0, this.g - t.g), this.b = Math.max(0, this.b - t.b), this;
  }
  /**
   * Multiplies the RGB values of the given color with the RGB values of this color.
   *
   * @param {Color} color - The color to multiply.
   * @return {Color} A reference to this color.
   */
  multiply(t) {
    return this.r *= t.r, this.g *= t.g, this.b *= t.b, this;
  }
  /**
   * Multiplies the given scalar value with the RGB values of this color.
   *
   * @param {number} s - The scalar to multiply.
   * @return {Color} A reference to this color.
   */
  multiplyScalar(t) {
    return this.r *= t, this.g *= t, this.b *= t, this;
  }
  /**
   * Linearly interpolates this color's RGB values toward the RGB values of the
   * given color. The alpha argument can be thought of as the ratio between
   * the two colors, where `0.0` is this color and `1.0` is the first argument.
   *
   * @param {Color} color - The color to converge on.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerp(t, e) {
    return this.r += (t.r - this.r) * e, this.g += (t.g - this.g) * e, this.b += (t.b - this.b) * e, this;
  }
  /**
   * Linearly interpolates between the given colors and stores the result in this instance.
   * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
   * is the first and `1.0` is the second color.
   *
   * @param {Color} color1 - The first color.
   * @param {Color} color2 - The second color.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerpColors(t, e, i) {
    return this.r = t.r + (e.r - t.r) * i, this.g = t.g + (e.g - t.g) * i, this.b = t.b + (e.b - t.b) * i, this;
  }
  /**
   * Linearly interpolates this color's HSL values toward the HSL values of the
   * given color. It differs from {@link Color#lerp} by not interpolating straight
   * from one color to the other, but instead going through all the hues in between
   * those two colors. The alpha argument can be thought of as the ratio between
   * the two colors, where 0.0 is this color and 1.0 is the first argument.
   *
   * @param {Color} color - The color to converge on.
   * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
   * @return {Color} A reference to this color.
   */
  lerpHSL(t, e) {
    this.getHSL(_s), t.getHSL(yh);
    const i = zd(_s.h, yh.h, e), n = zd(_s.s, yh.s, e), s = zd(_s.l, yh.l, e);
    return this.setHSL(i, n, s), this;
  }
  /**
   * Sets the color's RGB components from the given 3D vector.
   *
   * @param {Vector3} v - The vector to set.
   * @return {Color} A reference to this color.
   */
  setFromVector3(t) {
    return this.r = t.x, this.g = t.y, this.b = t.z, this;
  }
  /**
   * Transforms this color with the given 3x3 matrix.
   *
   * @param {Matrix3} m - The matrix.
   * @return {Color} A reference to this color.
   */
  applyMatrix3(t) {
    const e = this.r, i = this.g, n = this.b, s = t.elements;
    return this.r = s[0] * e + s[3] * i + s[6] * n, this.g = s[1] * e + s[4] * i + s[7] * n, this.b = s[2] * e + s[5] * i + s[8] * n, this;
  }
  /**
   * Returns `true` if this color is equal with the given one.
   *
   * @param {Color} c - The color to test for equality.
   * @return {boolean} Whether this bounding color is equal with the given one.
   */
  equals(t) {
    return t.r === this.r && t.g === this.g && t.b === this.b;
  }
  /**
   * Sets this color's RGB components from the given array.
   *
   * @param {Array<number>} array - An array holding the RGB values.
   * @param {number} [offset=0] - The offset into the array.
   * @return {Color} A reference to this color.
   */
  fromArray(t, e = 0) {
    return this.r = t[e], this.g = t[e + 1], this.b = t[e + 2], this;
  }
  /**
   * Writes the RGB components of this color to the given array. If no array is provided,
   * the method returns a new instance.
   *
   * @param {Array<number>} [array=[]] - The target array holding the color components.
   * @param {number} [offset=0] - Index of the first element in the array.
   * @return {Array<number>} The color components.
   */
  toArray(t = [], e = 0) {
    return t[e] = this.r, t[e + 1] = this.g, t[e + 2] = this.b, t;
  }
  /**
   * Sets the components of this color from the given buffer attribute.
   *
   * @param {BufferAttribute} attribute - The buffer attribute holding color data.
   * @param {number} index - The index into the attribute.
   * @return {Color} A reference to this color.
   */
  fromBufferAttribute(t, e) {
    return this.r = t.getX(e), this.g = t.getY(e), this.b = t.getZ(e), this;
  }
  /**
   * This methods defines the serialization result of this class. Returns the color
   * as a hexadecimal value.
   *
   * @return {number} The hexadecimal value.
   */
  toJSON() {
    return this.getHex();
  }
  *[Symbol.iterator]() {
    yield this.r, yield this.g, yield this.b;
  }
}
const ni = /* @__PURE__ */ new Bi();
Bi.NAMES = ex;
class RC extends Es {
  constructor() {
    super(), this.isGroup = !0, this.type = "Group";
  }
}
typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: {
  revision: J_
} }));
typeof window < "u" && (window.__THREE__ ? console.warn("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = J_);
function ix(a) {
  var t;
  if (a) {
    a.dispose();
    for (const e of Object.values(a.attributes))
      (t = e == null ? void 0 : e.dispose) == null || t.call(e);
  }
}
function PC(a) {
  a.geometry && ix(a.geometry), a.material && (Array.isArray(a.material) ? a.material.forEach((t) => t.dispose()) : a.material.dispose());
}
function Ec(a) {
  a && (Array.isArray(a.children) && a.children.forEach(Ec), a.dispose ? a.dispose() : Array.isArray(a) ? a.forEach(Ec) : (a.isMesh || a.isLine) && PC(a));
}
class IC extends RC {
  /**
   *
   * @param {*} opacity
   * @param {*} alpha
   * @param {*} edge_color
   * @param {object} shapeInfo A dictionary of shape information with a "topo" field and "geomtype" field.
   * @param {*} renderback
   */
  constructor(t, e, i, n, s, r) {
    super(), this.opacity = t, this.alpha = e ?? 1, this.edge_color = i, this.shapeInfo = n, this.subtype = s, this.renderback = r, this.types = { front: null, back: null, edges: null, vertices: null }, this.isSelected = !1, this.originalColor = null, this.originalBackColor = null, this.originalWidth = null, this.vertexFocusSize = 8, this.edgeFocusWidth = 5;
  }
  dispose() {
    this.shapeGeometry && (ix(this.shapeGeometry), this.shapeGeometry = null), Ec(Object.values(this.types)), this.children && (Ec(this.children), this.clear());
  }
  addType(t, e) {
    this.add(t), this.types[e] = t, this.types.vertices ? (this.originalColor = this.types.vertices.material.color.clone(), this.originalWidth = this.types.vertices.material.size) : this.types.edges && !this.types.front ? (this.originalColor = this.types.edges.material.color.clone(), this.originalWidth = this.types.edges.material.linewidth) : this.types.front ? this.originalColor = this.types.front.material.color.clone() : this.types.back && (this.originalBackColor = this.types.back.material.color.clone());
  }
  widen(t) {
    this.types.vertices ? this.types.vertices.material.size = t ? this.vertexFocusSize : this.isSelected ? this.vertexFocusSize - 2 : this.originalWidth : this.types.edges && (this.types.edges.material.linewidth = t ? this.edgeFocusWidth : this.isSelected ? this.edgeFocusWidth - 2 : this.originalWidth);
  }
  toggleSelection() {
    const t = !this.isSelected;
    this.isSelected = t, this.highlight(t), this.widen(!1);
  }
  unhighlight(t) {
    (!t || !this.isSelected) && (this.isSelected = !1, this.highlight(!1)), this.widen(!1);
  }
  highlight(t) {
    var e = null, i = null, n = null;
    this.types.front ? (e = this.types.front, i = this.isSelected ? new Bi(5480675) : new Bi(9026019), n = this.originalColor) : this.types.vertices ? (e = this.types.vertices, i = this.isSelected ? new Bi(5480675) : new Bi(9026019), n = this.originalColor) : this.types.edges && (e = this.types.edges, i = this.isSelected ? new Bi(5480675) : new Bi(9026019), n = this.originalColor), e != null && (this.widen(t), e.material.color = t ? i : n, e.material.needsUpdate = !0), this.types.back && (e = this.types.back, i = this.isSelected ? new Bi(5480675) : new Bi(9026019), n = this.originalBackColor), e != null && (e.material.color = t ? i : n, e.material.needsUpdate = !0);
  }
  clearHighlights() {
    this.highlight(!1), this.isSelected = !1, this.widen(!1);
  }
  metrics() {
    if (this.types.front)
      return { name: "face", value: 0 };
    if (this.types.vertices)
      return { name: "vertex", value: 0 };
    if (this.types.edges)
      return { name: "edge", value: 0 };
  }
  setMetalness(t) {
    for (var e of this.children)
      e.name.startsWith("clipping") || (e.material.metalness = t, e.material.needsUpdate = !0);
  }
  setRoughness(t) {
    for (var e of this.children)
      e.name.startsWith("clipping") || (e.material.roughness = t, e.material.needsUpdate = !0);
  }
  setTransparent(t) {
    this.types.back && (this.types.back.material.opacity = t ? this.opacity * this.alpha : this.alpha, this.types.front.material.opacity = t ? this.opacity * this.alpha : this.alpha);
    for (var e of this.children)
      e.name.startsWith("clipping") || (e.material.depthWrite = this.alpha < 1 ? !1 : !t, e.material.depthTest = !0, e.material.needsUpdate = !0);
  }
  setBlackEdges(t) {
    if (this.types.edges) {
      const e = t ? 0 : this.edge_color;
      this.originalColor = new Bi(e), this.types.edges.material.color = new Bi(e), this.types.edges.material.needsUpdate = !0;
    }
  }
  setEdgeColor(t) {
    this.types.edges && (this.edge_color = t, this.types.edges.material.color = new Bi(t), this.types.edges.material.needsUpdate = !0);
  }
  setOpacity(t) {
    (this.types.front || this.types.back) && (this.opacity = t, this.types.back.material.opacity = this.opacity, this.types.front.material.opacity = this.opacity, this.types.back.material.needsUpdate = !0, this.types.front.material.needsUpdate = !0);
  }
  setShapeVisible(t) {
    this.types.front && (this.types.front.material.visible = t);
    for (var e of ["clipping-0", "clipping-1", "clipping-2"])
      this.types[e] && (this.types[e].children[0].material.visible = t, this.types[e].children[1].material.visible = t);
    this.types.back && this.renderback && (this.types.back.material.visible = t);
  }
  setEdgesVisible(t) {
    this.types.edges && (this.types.edges.material.visible = t), this.types.vertices && (this.types.vertices.material.visible = t);
  }
  setBackVisible(t) {
    this.types.back && this.types.front.material.visible && (this.types.back.material.visible = this.renderback || t);
  }
  getVisibility() {
    return this.types.front ? this.types.edges ? this.types.front.material.visible || this.types.edges.material.visible : this.types.front.material.visible : this.types.edges ? this.types.edges.material.visible : this.types.vertices ? this.types.vertices.material.visible : !1;
  }
  setClipIntersection(t) {
    for (var e of this.children)
      e.name.startsWith("clipping") || (e.material.clipIntersection = t, e.material.clipIntersection = t, e.material.clipIntersection = t);
  }
  setClipPlanes(t) {
    this.types.back && (this.types.back.material.clippingPlanes = t), this.types.front && (this.types.front.material.clippingPlanes = t), this.types.edges && (this.types.edges.material.clippingPlanes = t), this.types.vertices && (this.types.vertices.material.clippingPlanes = t), this.updateMaterials(!0);
  }
  setPolygonOffset(t) {
    this.types.back && (this.types.back.material.polygonOffsetUnits = t);
  }
  setZScale(t) {
    function e(i, n, s, r = !0) {
      for (var o of i.children)
        o.isMesh || o.isLine ? (o.scale.z = t, r && (o.parent.position.z = n * t)) : o.isGroup && e(o, n, s, !o.name.startsWith("clipping"));
    }
    (this.types.front || this.types.back || this.types.edges) && e(this, this.minZ, this.height);
  }
  updateMaterials(t) {
    this.types.back && (this.types.back.material.needsUpdate = t), this.types.front && (this.types.front.material.needsUpdate = t), this.types.edges && (this.types.edges.material.needsUpdate = t), this.types.vertices && (this.types.vertices.material.needsUpdate = t);
  }
}
const m0 = new Us(), _h = new tt();
class nx extends cC {
  constructor() {
    super(), this.isLineSegmentsGeometry = !0, this.type = "LineSegmentsGeometry";
    const t = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0], e = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2], i = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5];
    this.setIndex(i), this.setAttribute("position", new wc(t, 3)), this.setAttribute("uv", new wc(e, 2));
  }
  applyMatrix4(t) {
    const e = this.attributes.instanceStart, i = this.attributes.instanceEnd;
    return e !== void 0 && (e.applyMatrix4(t), i.applyMatrix4(t), e.needsUpdate = !0), this.boundingBox !== null && this.computeBoundingBox(), this.boundingSphere !== null && this.computeBoundingSphere(), this;
  }
  setPositions(t) {
    let e;
    t instanceof Float32Array ? e = t : Array.isArray(t) && (e = new Float32Array(t));
    const i = new bp(e, 6, 1);
    return this.setAttribute("instanceStart", new Ss(i, 3, 0)), this.setAttribute("instanceEnd", new Ss(i, 3, 3)), this.instanceCount = this.attributes.instanceStart.count, this.computeBoundingBox(), this.computeBoundingSphere(), this;
  }
  setColors(t) {
    let e;
    t instanceof Float32Array ? e = t : Array.isArray(t) && (e = new Float32Array(t));
    const i = new bp(e, 6, 1);
    return this.setAttribute("instanceColorStart", new Ss(i, 3, 0)), this.setAttribute("instanceColorEnd", new Ss(i, 3, 3)), this;
  }
  fromWireframeGeometry(t) {
    return this.setPositions(t.attributes.position.array), this;
  }
  fromEdgesGeometry(t) {
    return this.setPositions(t.attributes.position.array), this;
  }
  fromMesh(t) {
    return this.fromWireframeGeometry(new lC(t.geometry)), this;
  }
  fromLineSegments(t) {
    const e = t.geometry;
    return this.setPositions(e.attributes.position.array), this;
  }
  computeBoundingBox() {
    this.boundingBox === null && (this.boundingBox = new Us());
    const t = this.attributes.instanceStart, e = this.attributes.instanceEnd;
    t !== void 0 && e !== void 0 && (this.boundingBox.setFromBufferAttribute(t), m0.setFromBufferAttribute(e), this.boundingBox.union(m0));
  }
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new uu()), this.boundingBox === null && this.computeBoundingBox();
    const t = this.attributes.instanceStart, e = this.attributes.instanceEnd;
    if (t !== void 0 && e !== void 0) {
      const i = this.boundingSphere.center;
      this.boundingBox.getCenter(i);
      let n = 0;
      for (let s = 0, r = t.count; s < r; s++)
        _h.fromBufferAttribute(t, s), n = Math.max(n, i.distanceToSquared(_h)), _h.fromBufferAttribute(e, s), n = Math.max(n, i.distanceToSquared(_h));
      this.boundingSphere.radius = Math.sqrt(n), isNaN(this.boundingSphere.radius) && console.error("THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.", this);
    }
  }
  toJSON() {
  }
  applyMatrix(t) {
    return console.warn("THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4()."), this.applyMatrix4(t);
  }
}
si.line = {
  worldUnits: { value: 1 },
  linewidth: { value: 1 },
  resolution: { value: new _i(1, 1) },
  dashOffset: { value: 0 },
  dashScale: { value: 1 },
  dashSize: { value: 1 },
  gapSize: { value: 1 }
  // todo FIX - maybe change to totalSize
};
ca.line = {
  uniforms: j_.merge([
    si.common,
    si.fog,
    si.line
  ]),
  vertexShader: (
    /* glsl */
    `
		#include <common>
		#include <color_pars_vertex>
		#include <fog_pars_vertex>
		#include <logdepthbuf_pars_vertex>
		#include <clipping_planes_pars_vertex>

		uniform float linewidth;
		uniform vec2 resolution;

		attribute vec3 instanceStart;
		attribute vec3 instanceEnd;

		attribute vec3 instanceColorStart;
		attribute vec3 instanceColorEnd;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#ifdef USE_DASH

			uniform float dashScale;
			attribute float instanceDistanceStart;
			attribute float instanceDistanceEnd;
			varying float vLineDistance;

		#endif

		void trimSegment( const in vec4 start, inout vec4 end ) {

			// trim end segment so it terminates between the camera plane and the near plane

			// conservative estimate of the near plane
			float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
			float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
			float nearEstimate = - 0.5 * b / a;

			float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );

			end.xyz = mix( start.xyz, end.xyz, alpha );

		}

		void main() {

			#ifdef USE_COLOR

				vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;

			#endif

			#ifdef USE_DASH

				vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
				vUv = uv;

			#endif

			float aspect = resolution.x / resolution.y;

			// camera space
			vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
			vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );

			#ifdef WORLD_UNITS

				worldStart = start.xyz;
				worldEnd = end.xyz;

			#else

				vUv = uv;

			#endif

			// special case for perspective projection, and segments that terminate either in, or behind, the camera plane
			// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
			// but we need to perform ndc-space calculations in the shader, so we must address this issue directly
			// perhaps there is a more elegant solution -- WestLangley

			bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column

			if ( perspective ) {

				if ( start.z < 0.0 && end.z >= 0.0 ) {

					trimSegment( start, end );

				} else if ( end.z < 0.0 && start.z >= 0.0 ) {

					trimSegment( end, start );

				}

			}

			// clip space
			vec4 clipStart = projectionMatrix * start;
			vec4 clipEnd = projectionMatrix * end;

			// ndc space
			vec3 ndcStart = clipStart.xyz / clipStart.w;
			vec3 ndcEnd = clipEnd.xyz / clipEnd.w;

			// direction
			vec2 dir = ndcEnd.xy - ndcStart.xy;

			// account for clip-space aspect ratio
			dir.x *= aspect;
			dir = normalize( dir );

			#ifdef WORLD_UNITS

				vec3 worldDir = normalize( end.xyz - start.xyz );
				vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) );
				vec3 worldUp = normalize( cross( worldDir, tmpFwd ) );
				vec3 worldFwd = cross( worldDir, worldUp );
				worldPos = position.y < 0.5 ? start: end;

				// height offset
				float hw = linewidth * 0.5;
				worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp;

				// don't extend the line if we're rendering dashes because we
				// won't be rendering the endcaps
				#ifndef USE_DASH

					// cap extension
					worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir;

					// add width to the box
					worldPos.xyz += worldFwd * hw;

					// endcaps
					if ( position.y > 1.0 || position.y < 0.0 ) {

						worldPos.xyz -= worldFwd * 2.0 * hw;

					}

				#endif

				// project the worldpos
				vec4 clip = projectionMatrix * worldPos;

				// shift the depth of the projected points so the line
				// segments overlap neatly
				vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
				clip.z = clipPose.z * clip.w;

			#else

				vec2 offset = vec2( dir.y, - dir.x );
				// undo aspect ratio adjustment
				dir.x /= aspect;
				offset.x /= aspect;

				// sign flip
				if ( position.x < 0.0 ) offset *= - 1.0;

				// endcaps
				if ( position.y < 0.0 ) {

					offset += - dir;

				} else if ( position.y > 1.0 ) {

					offset += dir;

				}

				// adjust for linewidth
				offset *= linewidth;

				// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
				offset /= resolution.y;

				// select end
				vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;

				// back to clip space
				offset *= clip.w;

				clip.xy += offset;

			#endif

			gl_Position = clip;

			vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation

			#include <logdepthbuf_vertex>
			#include <clipping_planes_vertex>
			#include <fog_vertex>

		}
		`
  ),
  fragmentShader: (
    /* glsl */
    `
		uniform vec3 diffuse;
		uniform float opacity;
		uniform float linewidth;

		#ifdef USE_DASH

			uniform float dashOffset;
			uniform float dashSize;
			uniform float gapSize;

		#endif

		varying float vLineDistance;

		#ifdef WORLD_UNITS

			varying vec4 worldPos;
			varying vec3 worldStart;
			varying vec3 worldEnd;

			#ifdef USE_DASH

				varying vec2 vUv;

			#endif

		#else

			varying vec2 vUv;

		#endif

		#include <common>
		#include <color_pars_fragment>
		#include <fog_pars_fragment>
		#include <logdepthbuf_pars_fragment>
		#include <clipping_planes_pars_fragment>

		vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {

			float mua;
			float mub;

			vec3 p13 = p1 - p3;
			vec3 p43 = p4 - p3;

			vec3 p21 = p2 - p1;

			float d1343 = dot( p13, p43 );
			float d4321 = dot( p43, p21 );
			float d1321 = dot( p13, p21 );
			float d4343 = dot( p43, p43 );
			float d2121 = dot( p21, p21 );

			float denom = d2121 * d4343 - d4321 * d4321;

			float numer = d1343 * d4321 - d1321 * d4343;

			mua = numer / denom;
			mua = clamp( mua, 0.0, 1.0 );
			mub = ( d1343 + d4321 * ( mua ) ) / d4343;
			mub = clamp( mub, 0.0, 1.0 );

			return vec2( mua, mub );

		}

		void main() {

			#include <clipping_planes_fragment>

			#ifdef USE_DASH

				if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps

				if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX

			#endif

			float alpha = opacity;

			#ifdef WORLD_UNITS

				// Find the closest points on the view ray and the line segment
				vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
				vec3 lineDir = worldEnd - worldStart;
				vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );

				vec3 p1 = worldStart + lineDir * params.x;
				vec3 p2 = rayEnd * params.y;
				vec3 delta = p1 - p2;
				float len = length( delta );
				float norm = len / linewidth;

				#ifndef USE_DASH

					#ifdef USE_ALPHA_TO_COVERAGE

						float dnorm = fwidth( norm );
						alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );

					#else

						if ( norm > 0.5 ) {

							discard;

						}

					#endif

				#endif

			#else

				#ifdef USE_ALPHA_TO_COVERAGE

					// artifacts appear on some hardware if a derivative is taken within a conditional
					float a = vUv.x;
					float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
					float len2 = a * a + b * b;
					float dlen = fwidth( len2 );

					if ( abs( vUv.y ) > 1.0 ) {

						alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );

					}

				#else

					if ( abs( vUv.y ) > 1.0 ) {

						float a = vUv.x;
						float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
						float len2 = a * a + b * b;

						if ( len2 > 1.0 ) discard;

					}

				#endif

			#endif

			vec4 diffuseColor = vec4( diffuse, alpha );

			#include <logdepthbuf_fragment>
			#include <color_fragment>

			gl_FragColor = vec4( diffuseColor.rgb, alpha );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>
			#include <fog_fragment>
			#include <premultiplied_alpha_fragment>

		}
		`
  )
};
class sx extends nC {
  static get type() {
    return "LineMaterial";
  }
  constructor(t) {
    super({
      uniforms: j_.clone(ca.line.uniforms),
      vertexShader: ca.line.vertexShader,
      fragmentShader: ca.line.fragmentShader,
      clipping: !0
      // required for clipping support
    }), this.isLineMaterial = !0, this.setValues(t);
  }
  get color() {
    return this.uniforms.diffuse.value;
  }
  set color(t) {
    this.uniforms.diffuse.value = t;
  }
  get worldUnits() {
    return "WORLD_UNITS" in this.defines;
  }
  set worldUnits(t) {
    t === !0 ? this.defines.WORLD_UNITS = "" : delete this.defines.WORLD_UNITS;
  }
  get linewidth() {
    return this.uniforms.linewidth.value;
  }
  set linewidth(t) {
    this.uniforms.linewidth && (this.uniforms.linewidth.value = t);
  }
  get dashed() {
    return "USE_DASH" in this.defines;
  }
  set dashed(t) {
    t === !0 !== this.dashed && (this.needsUpdate = !0), t === !0 ? this.defines.USE_DASH = "" : delete this.defines.USE_DASH;
  }
  get dashScale() {
    return this.uniforms.dashScale.value;
  }
  set dashScale(t) {
    this.uniforms.dashScale.value = t;
  }
  get dashSize() {
    return this.uniforms.dashSize.value;
  }
  set dashSize(t) {
    this.uniforms.dashSize.value = t;
  }
  get dashOffset() {
    return this.uniforms.dashOffset.value;
  }
  set dashOffset(t) {
    this.uniforms.dashOffset.value = t;
  }
  get gapSize() {
    return this.uniforms.gapSize.value;
  }
  set gapSize(t) {
    this.uniforms.gapSize.value = t;
  }
  get opacity() {
    return this.uniforms.opacity.value;
  }
  set opacity(t) {
    this.uniforms && (this.uniforms.opacity.value = t);
  }
  get resolution() {
    return this.uniforms.resolution.value;
  }
  set resolution(t) {
    this.uniforms.resolution.value.copy(t);
  }
  get alphaToCoverage() {
    return "USE_ALPHA_TO_COVERAGE" in this.defines;
  }
  set alphaToCoverage(t) {
    this.defines && (t === !0 !== this.alphaToCoverage && (this.needsUpdate = !0), t === !0 ? this.defines.USE_ALPHA_TO_COVERAGE = "" : delete this.defines.USE_ALPHA_TO_COVERAGE);
  }
}
const Wd = new Pn(), g0 = new tt(), y0 = new tt(), qe = new Pn(), $e = new Pn(), bn = new Pn(), qd = new tt(), $d = new Qn(), Ye = new uC(), _0 = new tt(), xh = new Us(), vh = new uu(), Mn = new Pn();
let An, dr;
function x0(a, t, e) {
  return Mn.set(0, 0, -t, 1).applyMatrix4(a.projectionMatrix), Mn.multiplyScalar(1 / Mn.w), Mn.x = dr / e.width, Mn.y = dr / e.height, Mn.applyMatrix4(a.projectionMatrixInverse), Mn.multiplyScalar(1 / Mn.w), Math.abs(Math.max(Mn.x, Mn.y));
}
function LC(a, t) {
  const e = a.matrixWorld, i = a.geometry, n = i.attributes.instanceStart, s = i.attributes.instanceEnd, r = Math.min(i.instanceCount, n.count);
  for (let o = 0, l = r; o < l; o++) {
    Ye.start.fromBufferAttribute(n, o), Ye.end.fromBufferAttribute(s, o), Ye.applyMatrix4(e);
    const h = new tt(), c = new tt();
    An.distanceSqToSegment(Ye.start, Ye.end, c, h), c.distanceTo(h) < dr * 0.5 && t.push({
      point: c,
      pointOnLine: h,
      distance: An.origin.distanceTo(c),
      object: a,
      face: null,
      faceIndex: o,
      uv: null,
      uv1: null
    });
  }
}
function DC(a, t, e) {
  const i = t.projectionMatrix, s = a.material.resolution, r = a.matrixWorld, o = a.geometry, l = o.attributes.instanceStart, h = o.attributes.instanceEnd, c = Math.min(o.instanceCount, l.count), u = -t.near;
  An.at(1, bn), bn.w = 1, bn.applyMatrix4(t.matrixWorldInverse), bn.applyMatrix4(i), bn.multiplyScalar(1 / bn.w), bn.x *= s.x / 2, bn.y *= s.y / 2, bn.z = 0, qd.copy(bn), $d.multiplyMatrices(t.matrixWorldInverse, r);
  for (let d = 0, p = c; d < p; d++) {
    if (qe.fromBufferAttribute(l, d), $e.fromBufferAttribute(h, d), qe.w = 1, $e.w = 1, qe.applyMatrix4($d), $e.applyMatrix4($d), qe.z > u && $e.z > u)
      continue;
    if (qe.z > u) {
      const x = qe.z - $e.z, _ = (qe.z - u) / x;
      qe.lerp($e, _);
    } else if ($e.z > u) {
      const x = $e.z - qe.z, _ = ($e.z - u) / x;
      $e.lerp(qe, _);
    }
    qe.applyMatrix4(i), $e.applyMatrix4(i), qe.multiplyScalar(1 / qe.w), $e.multiplyScalar(1 / $e.w), qe.x *= s.x / 2, qe.y *= s.y / 2, $e.x *= s.x / 2, $e.y *= s.y / 2, Ye.start.copy(qe), Ye.start.z = 0, Ye.end.copy($e), Ye.end.z = 0;
    const y = Ye.closestPointToPointParameter(qd, !0);
    Ye.at(y, _0);
    const g = FT.lerp(qe.z, $e.z, y), m = g >= -1 && g <= 1, v = qd.distanceTo(_0) < dr * 0.5;
    if (m && v) {
      Ye.start.fromBufferAttribute(l, d), Ye.end.fromBufferAttribute(h, d), Ye.start.applyMatrix4(r), Ye.end.applyMatrix4(r);
      const x = new tt(), _ = new tt();
      An.distanceSqToSegment(Ye.start, Ye.end, _, x), e.push({
        point: _,
        pointOnLine: x,
        distance: An.origin.distanceTo(_),
        object: a,
        face: null,
        faceIndex: d,
        uv: null,
        uv1: null
      });
    }
  }
}
class FC extends Ac {
  constructor(t = new nx(), e = new sx({ color: Math.random() * 16777215 })) {
    super(t, e), this.isLineSegments2 = !0, this.type = "LineSegments2";
  }
  // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  computeLineDistances() {
    const t = this.geometry, e = t.attributes.instanceStart, i = t.attributes.instanceEnd, n = new Float32Array(2 * e.count);
    for (let r = 0, o = 0, l = e.count; r < l; r++, o += 2)
      g0.fromBufferAttribute(e, r), y0.fromBufferAttribute(i, r), n[o] = o === 0 ? 0 : n[o - 1], n[o + 1] = n[o] + g0.distanceTo(y0);
    const s = new bp(n, 2, 1);
    return t.setAttribute("instanceDistanceStart", new Ss(s, 1, 0)), t.setAttribute("instanceDistanceEnd", new Ss(s, 1, 1)), this;
  }
  raycast(t, e) {
    const i = this.material.worldUnits, n = t.camera;
    n === null && !i && console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');
    const s = t.params.Line2 !== void 0 && t.params.Line2.threshold || 0;
    An = t.ray;
    const r = this.matrixWorld, o = this.geometry, l = this.material;
    dr = l.linewidth + s, o.boundingSphere === null && o.computeBoundingSphere(), vh.copy(o.boundingSphere).applyMatrix4(r);
    let h;
    if (i)
      h = dr * 0.5;
    else {
      const u = Math.max(n.near, vh.distanceToPoint(An.origin));
      h = x0(n, u, l.resolution);
    }
    if (vh.radius += h, An.intersectsSphere(vh) === !1)
      return;
    o.boundingBox === null && o.computeBoundingBox(), xh.copy(o.boundingBox).applyMatrix4(r);
    let c;
    if (i)
      c = dr * 0.5;
    else {
      const u = Math.max(n.near, xh.distanceToPoint(An.origin));
      c = x0(n, u, l.resolution);
    }
    xh.expandByScalar(c), An.intersectsBox(xh) !== !1 && (i ? LC(this, e) : DC(this, n, e));
  }
  onBeforeRender(t) {
    const e = this.material.uniforms;
    e && e.resolution && (t.getViewport(Wd), this.material.uniforms.resolution.value.set(Wd.z, Wd.w));
  }
}
const ia = 200, v0 = 12, b0 = 400, Sf = 800, UC = 100, BC = "#e8b024", rx = 3355443, ax = {
  ambientIntensity: 1,
  directIntensity: 1.1,
  metalness: 0.3,
  roughness: 0.65,
  edgeColor: rx,
  defaultOpacity: 0.5,
  normalLen: 0
}, oo = {
  EXPAND_ALL: 0,
  // Show all nodes expanded
  ROOT_ONLY: 1,
  // Collapse to root level only
  COLLAPSE_ALL: 2,
  // All nodes collapsed
  FIRST_LEVEL: 3
  // Expand first level only
}, M0 = {
  up: "Z",
  axes: !0,
  axes0: !0,
  grid: [!0, !1, !1],
  ortho: !0,
  transparent: !1,
  blackEdges: !0,
  collapse: oo.ROOT_ONLY
}, zC = [1, 1], NC = 1, OC = {
  theme: "browser",
  pinning: !1
}, ox = 600;
function kC(a, t, e) {
  const i = a instanceof Float32Array ? a : new Float32Array(a), n = new nx();
  n.setPositions(i);
  const s = t.edgeColor ?? rx, r = new sx({
    color: new Ai(s),
    linewidth: 1,
    transparent: !0,
    depthWrite: !t.transparent,
    depthTest: !t.transparent,
    clipIntersection: !1
  });
  r.visible = e[1] === 1, r.resolution.set(t.width || Sf, t.height || ox);
  const o = new FC(n, r);
  return o.renderOrder = 999, o;
}
function VC(a, t = {}) {
  var T;
  const e = { ...ax, width: Sf, height: ox, ...t }, { id: i, name: n, shape: s, color: r, alpha: o, state: l } = a, h = new Ai(r || BC), c = o ?? NC, u = l || zC, d = !0, p = new IC(
    e.defaultOpacity,
    // opacity
    c,
    // alpha
    e.edgeColor,
    // edge_color
    { topo: "face" },
    // shapeInfo (geomtype)
    "solid",
    // subtype - CRITICAL for clipping check
    d
    // renderback
  );
  p.name = i.replaceAll("/", "|");
  const f = s.vertices instanceof Float32Array ? s.vertices : new Float32Array(s.vertices), y = s.normals instanceof Float32Array ? s.normals : new Float32Array(s.normals), g = s.triangles instanceof Uint32Array ? s.triangles : new Uint32Array(s.triangles), m = new Fa();
  m.setAttribute("position", new qi(f, 3)), m.setAttribute("normal", new qi(y, 3)), m.setIndex(new qi(g, 1)), m.computeBoundingBox(), m.computeBoundingSphere(), p.shapeGeometry = m;
  const v = e.transparent || c < 1, x = new hC({
    color: h,
    metalness: e.metalness,
    roughness: e.roughness,
    polygonOffset: !0,
    polygonOffsetFactor: 1,
    polygonOffsetUnits: 1,
    transparent: !0,
    opacity: v ? e.defaultOpacity * c : c,
    depthWrite: !v,
    depthTest: !0,
    clipIntersection: !1,
    side: Bo,
    visible: u[0] === 1,
    name: "frontMaterial"
  }), _ = new pu({
    color: h,
    side: gf,
    polygonOffset: !0,
    polygonOffsetFactor: 1,
    polygonOffsetUnits: 1,
    transparent: !0,
    opacity: v ? e.defaultOpacity * c : c,
    depthWrite: !v,
    depthTest: !0,
    clipIntersection: !1,
    visible: u[0] === 1 && d,
    name: "backMaterial"
  }), S = new Ac(m, _);
  S.name = n || i;
  const w = new Ac(m, x);
  if (w.name = n || i, c < 1 && (S.renderOrder = 999, w.renderOrder = 999), p.addType(S, "back"), p.addType(w, "front"), ((T = s.edges) == null ? void 0 : T.length) > 0) {
    const R = kC(s.edges, e, u);
    R.name = n || i, p.addType(R, "edges");
  }
  return p;
}
function HC(a, t) {
  return t ? {
    ...a,
    width: t.cadWidth || a.width,
    height: t.height || a.height
  } : a;
}
const GC = new pu({
  depthWrite: !1,
  depthTest: !1,
  colorWrite: !1,
  side: gf,
  stencilWrite: !0,
  stencilFunc: Sc,
  stencilFail: md,
  stencilZFail: md,
  stencilZPass: md
}), WC = new pu({
  depthWrite: !1,
  depthTest: !1,
  colorWrite: !1,
  side: Bo,
  stencilWrite: !0,
  stencilFunc: Sc,
  stencilFail: gd,
  stencilZFail: gd,
  stencilZPass: gd
});
function S0(a, t, e, i) {
  const n = t.clone();
  n.clippingPlanes = [i];
  const s = new Ac(e, n);
  return s.name = a, s;
}
class qC {
  /**
   * @param {Object} viewer - LiveViewer instance
   */
  constructor(t) {
    this._viewer = t;
  }
  /**
   * Check if clipping is available (viewer has been rendered)
   * @returns {boolean}
   */
  get isReady() {
    var t, e;
    return !!((e = (t = this._viewer) == null ? void 0 : t.clipping) != null && e.clipPlanes);
  }
  /**
   * Get the clipping planes from the viewer
   * @returns {Array<THREE.Plane>|null}
   */
  get clipPlanes() {
    var t, e;
    return ((e = (t = this._viewer) == null ? void 0 : t.clipping) == null ? void 0 : e.clipPlanes) || null;
  }
  /**
   * Setup clipping stencils for a newly added ObjectGroup.
   * Must be called AFTER viewer.clipping exists (after first render).
   * 
   * This replicates what the Clipping constructor does for each ObjectGroup:
   * 1. Creates front/back stencil meshes for each clipping plane (X, Y, Z)
   * 2. Adds them to the group via addType() so setShapeVisible() controls them
   * 3. Sets clip planes on the group's materials
   * 
   * @param {ObjectGroup} group - ObjectGroup instance to setup clipping for
   * @returns {boolean} - true if clipping was set up, false if not possible
   */
  setupClipping(t) {
    var n;
    if (!this.isReady || !(t != null && t.shapeGeometry) || t.subtype !== "solid" || (n = t.types) != null && n["clipping-0"])
      return !1;
    const e = this.clipPlanes, i = t.shapeGeometry;
    for (let s = 0; s < 3; s++) {
      const r = e[s], o = new aC();
      o.name = `clipping-${s}`;
      const l = S0(
        `frontStencil-${s}`,
        WC,
        i,
        r
      );
      o.add(l);
      const h = S0(
        `backStencil-${s}`,
        GC,
        i,
        r
      );
      o.add(h), t.addType(o, `clipping-${s}`);
    }
    return t.setClipPlanes(e), !0;
  }
  /**
   * Remove clipping from a group (for cleanup)
   * @param {ObjectGroup} group - ObjectGroup instance
   */
  removeClipping(t) {
    if (t != null && t.types) {
      for (let e = 0; e < 3; e++) {
        const i = `clipping-${e}`, n = t.types[i];
        if (n) {
          for (const s of n.children)
            s.material && s.material.dispose();
          t.remove(n), delete t.types[i];
        }
      }
      typeof t.setClipPlanes == "function" && t.setClipPlanes(null);
    }
  }
  /**
   * Setup clipping for all groups that don't have it yet.
   * Useful after batch adding parts.
   * @param {Object} groups - Map of path -> ObjectGroup
   * @returns {number} - Number of groups that got clipping setup
   */
  setupClippingForAll(t) {
    if (!t || !this.isReady) return 0;
    let e = 0;
    for (const i of Object.values(t))
      this.setupClipping(i) && e++;
    return e;
  }
}
class Xd {
  /**
   * @param {string} id - Part ID (path like "/Group/PartName")
   * @param {ObjectGroup} group - ObjectGroup instance
   */
  constructor(t, e) {
    this.id = t, this._group = e, this._disposed = !1;
  }
  /** Check if this handle is still valid */
  get isValid() {
    return !this._disposed && this._group && this._group.parent;
  }
  /** Get the ObjectGroup for this part */
  get group() {
    return this._group;
  }
  /** Get the geometry */
  get geometry() {
    var t;
    return (t = this._group) == null ? void 0 : t.shapeGeometry;
  }
  /** Set part position */
  setPosition(t, e, i) {
    this.isValid && this._group.position.set(t, e, i);
  }
  /** Set part rotation as quaternion */
  setQuaternion(t, e, i, n) {
    this.isValid && this._group.quaternion.set(t, e, i, n);
  }
  /** Set position and quaternion from loc array [[x,y,z], [qx,qy,qz,qw]] */
  setTransform(t) {
    if (!this.isValid || !t) return;
    const [e, i] = t;
    e && this.setPosition(e[0], e[1], e[2]), i && this.setQuaternion(i[0], i[1], i[2], i[3]);
  }
  /** Update geometry buffers */
  updateGeometry(t, e, i) {
    if (!this.isValid) return;
    const n = this._group.shapeGeometry;
    if (!n) return;
    const s = t instanceof Float32Array ? t : new Float32Array(t), r = e instanceof Float32Array ? e : new Float32Array(e), o = i instanceof Uint32Array ? i : new Uint32Array(i);
    this._updateBufferAttribute(n, "position", s, 3), this._updateBufferAttribute(n, "normal", r, 3), this._updateIndex(n, o), n.computeBoundingBox(), n.computeBoundingSphere();
  }
  /** Update edge geometry */
  updateEdges(t) {
    var n, s;
    if (!this.isValid) return;
    const e = (n = this._group.types) == null ? void 0 : n.edges;
    if (!((s = e == null ? void 0 : e.geometry) != null && s.setPositions)) return;
    const i = t instanceof Float32Array ? t : new Float32Array(t);
    e.geometry.setPositions(i);
  }
  /** Dispose of this part's resources */
  dispose() {
    this._disposed || (this._group && (this._group.parent && this._group.parent.remove(this._group), typeof this._group.dispose == "function" && this._group.dispose()), this._disposed = !0);
  }
  /** @private Update a buffer attribute, reusing if size matches */
  _updateBufferAttribute(t, e, i, n) {
    const s = t.attributes[e];
    s && s.array.length === i.length ? (s.array.set(i), s.needsUpdate = !0) : t.setAttribute(e, new qi(i, n));
  }
  /** @private Update geometry index */
  _updateIndex(t, e) {
    const i = t.index;
    i && i.array.length === e.length ? (i.array.set(e), i.needsUpdate = !0) : t.setIndex(new qi(e, 1));
  }
}
class $C {
  /**
   * @param {Object} viewer - LiveViewer instance
   */
  constructor(t) {
    this._viewer = t, this._parts = /* @__PURE__ */ new Map(), this._renderOptions = null, this._clippingExt = new qC(t);
  }
  /** Get the ClippingExtension */
  get clipping() {
    return this._clippingExt;
  }
  /** Set render options for new parts */
  setRenderOptions(t) {
    this._renderOptions = t;
  }
  /** Get render options with display dimensions */
  _getOptions() {
    var t;
    return HC(
      this._renderOptions || {},
      (t = this._viewer) == null ? void 0 : t.display
    );
  }
  /** Get a part by ID */
  get(t) {
    return this._parts.get(t) || null;
  }
  /** Check if a part exists */
  has(t) {
    return this._parts.has(t);
  }
  /** Get all part IDs */
  ids() {
    return Array.from(this._parts.keys());
  }
  /** Get all parts */
  all() {
    return Array.from(this._parts.values());
  }
  /** 
   * Build part map from viewer's current state (after initial render).
   * Maps three-cad-viewer's ObjectGroups to PartHandles.
   */
  buildFromViewer() {
    var e, i;
    this._parts.clear();
    const t = (i = (e = this._viewer) == null ? void 0 : e.nestedGroup) == null ? void 0 : i.groups;
    if (t)
      for (const [n, s] of Object.entries(t)) {
        if (!n) continue;
        const r = new Xd(n, s);
        this._parts.set(n, r);
      }
  }
  /**
   * Add a new part to the scene using a real ObjectGroup.
   * @param {Object} partData - Part data with shape, color, etc.
   * @returns {PartHandle|null}
   */
  add(t) {
    var r, o, l;
    const { id: e, loc: i } = t;
    if (!((r = t.shape) != null && r.vertices) || !((l = (o = this._viewer) == null ? void 0 : o.nestedGroup) != null && l.rootGroup))
      return null;
    const n = VC(t, this._getOptions());
    this._viewer.nestedGroup.rootGroup.add(n), this._viewer.nestedGroup.groups[e] = n, this._clippingExt.setupClipping(n);
    const s = new Xd(e, n);
    return this._parts.set(e, s), i && s.setTransform(i), s;
  }
  /**
   * Remove a part from the scene.
   * @param {string} id - Part ID to remove
   */
  remove(t) {
    var i, n, s;
    const e = this._parts.get(t);
    e && (this._clippingExt.removeClipping(e.group), e.dispose(), this._parts.delete(t)), (s = (n = (i = this._viewer) == null ? void 0 : i.nestedGroup) == null ? void 0 : n.groups) != null && s[t] && delete this._viewer.nestedGroup.groups[t];
  }
  /**
   * Update an existing part's geometry and transform.
   * @param {string} id - Part ID
   * @param {Object} partData - New part data
   */
  update(t, e) {
    var r, o, l;
    let i = this._parts.get(t);
    if (!i) {
      const h = (l = (o = (r = this._viewer) == null ? void 0 : r.nestedGroup) == null ? void 0 : o.groups) == null ? void 0 : l[t];
      h && (i = new Xd(t, h), this._parts.set(t, i));
    }
    if (!i || !i.isValid) return;
    const { shape: n, loc: s } = e;
    n != null && n.vertices && (i.updateGeometry(n.vertices, n.normals, n.triangles), n.edges && i.updateEdges(n.edges)), s && i.setTransform(s);
  }
  /**
   * Sync parts with new data - intelligently add, remove, update.
   * @param {Array} partsData - Array of part data objects
   * @returns {Object} - { added, updated, removed } counts
   */
  sync(t) {
    const e = new Set(t.map((r) => r.id)), i = new Set(this._parts.keys()), n = this._getViewerPartIds();
    for (const r of n)
      i.add(r);
    const s = { added: 0, updated: 0, removed: 0 };
    for (const r of i)
      e.has(r) || (this.remove(r), s.removed++);
    for (const r of t)
      i.has(r.id) ? (this.update(r.id, r), s.updated++) : (this.add(r), s.added++);
    return s;
  }
  /** @private Get all part IDs (paths) from viewer's groups */
  _getViewerPartIds() {
    var i, n;
    const t = /* @__PURE__ */ new Set(), e = (n = (i = this._viewer) == null ? void 0 : i.nestedGroup) == null ? void 0 : n.groups;
    if (!e) return t;
    for (const s of Object.keys(e))
      s && t.add(s);
    return t;
  }
  /** Clear all parts */
  clear() {
    for (const t of this._parts.values())
      this._clippingExt.removeClipping(t.group), t.dispose();
    this._parts.clear();
  }
}
class XC {
  constructor() {
    this._states = /* @__PURE__ */ new Map();
  }
  /**
   * Get state for a path, returns default [1, 1] if not found
   * @param {string} path - Part path (e.g., "/Group/PartName")
   * @returns {[number, number]} - [shapeVisible, edgesVisible]
   */
  get(t) {
    return this._states.get(t) || [1, 1];
  }
  /**
   * Set state for a path
   * @param {string} path - Part path
   * @param {[number, number]} state - [shapeVisible, edgesVisible]
   */
  set(t, e) {
    this._states.set(t, e);
  }
  /**
   * Remove state for a path
   * @param {string} path - Part path
   */
  remove(t) {
    this._states.delete(t);
  }
  /**
   * Check if a path has saved state
   * @param {string} path - Part path
   * @returns {boolean}
   */
  has(t) {
    return this._states.has(t);
  }
  /**
   * Get all states as an object
   * @returns {Object.<string, [number, number]>}
   */
  all() {
    return Object.fromEntries(this._states);
  }
  /**
   * Get number of saved states
   * @returns {number}
   */
  get size() {
    return this._states.size;
  }
  /**
   * Clear all states
   */
  clear() {
    this._states.clear();
  }
  /**
   * Save current states from tree view before rebuild.
   * @param {Object} treeview - TreeView instance with getStates() method
   */
  saveFromTree(t) {
    if (t != null && t.getStates)
      try {
        const e = t.getStates();
        for (const [i, n] of Object.entries(e))
          i && Array.isArray(n) && this._states.set(i, n);
      } catch (e) {
        console.warn("[StateManager] Could not save states from tree:", e.message);
      }
  }
  /**
   * Apply saved states to ObjectGroups.
   * Called after tree rebuild to restore visibility.
   * @param {Object} groups - Map of path -> ObjectGroup
   */
  applyToGroups(t) {
    if (t)
      for (const [e, i] of this._states) {
        const n = t[e];
        n && (typeof n.setShapeVisible == "function" && n.setShapeVisible(i[0] === 1), typeof n.setEdgesVisible == "function" && n.setEdgesVisible(i[1] === 1));
      }
  }
  /**
   * Apply state to a single group
   * @param {string} path - Part path
   * @param {Object} group - ObjectGroup instance
   */
  applyToGroup(t, e) {
    const i = this.get(t);
    typeof e.setShapeVisible == "function" && e.setShapeVisible(i[0] === 1), typeof e.setEdgesVisible == "function" && e.setEdgesVisible(i[1] === 1);
  }
  /**
   * Remove states for paths not in the current set.
   * Called after sync to clean up removed parts.
   * @param {Set<string>} currentPaths - Set of current part paths
   */
  cleanupRemoved(t) {
    for (const e of this._states.keys())
      t.has(e) || this._states.delete(e);
  }
  /**
   * Initialize states from parts data (for new parts).
   * Only sets state if not already saved.
   * @param {Array} partsData - Array of part data objects
   */
  initFromParts(t) {
    for (const e of t)
      if (e.id && !this._states.has(e.id)) {
        const i = e.state || [1, 1];
        this._states.set(e.id, i);
      }
  }
}
class YC extends cT {
  constructor(e, i, n) {
    super(e, i, n);
    /**
     * Fixed getNodeColor that uses duck typing instead of instanceof ObjectGroup.
     * The original relies on instanceof which fails for our dynamically created groups.
     * @param {string} path - Node path without leading slash
     * @returns {string|null} - Hex color string or null
     */
    k(this, "_getNodeColorFixed", (e) => {
      var r, o, l, h, c;
      const i = (o = (r = this.nestedGroup) == null ? void 0 : r.groups) == null ? void 0 : o["/" + e];
      if (!i || !i.children || i.children.length === 0) return null;
      let n = null;
      const s = i.children[0];
      return (l = s == null ? void 0 : s.material) != null && l.color && (s.type !== "Mesh" || s.material.name === "frontMaterial" ? n = s.material.color : (c = (h = i.children[1]) == null ? void 0 : h.material) != null && c.color && (n = i.children[1].material.color)), n ? "#" + n.getHexString() : null;
    });
    /**
     * Fixed setObject that uses duck typing instead of instanceof ObjectGroup.
     * The original relies on instanceof which fails for our dynamically created groups.
     * @param {string} path - Node path (with leading slash)
     * @param {number} state - 0 or 1 for visibility
     * @param {number} iconNumber - 0 for shape, 1 for edges
     * @param {boolean} notify - Whether to notify state change
     * @param {boolean} update - Whether to trigger render update
     */
    k(this, "_setObjectFixed", (e, i, n, s = !0, r = !0) => {
      var l, h;
      const o = (h = (l = this.nestedGroup) == null ? void 0 : l.groups) == null ? void 0 : h[e];
      o && (typeof o.setShapeVisible != "function" || typeof o.setEdgesVisible != "function" || (n === 0 ? o.setShapeVisible(i === 1) : o.setEdgesVisible(i === 1), r && this.update(this.updateMarker)));
    });
    this._parts = new $C(this), this._stateManager = new XC(), this._renderOptions = null, this._viewerOptions = null, this._lastPartsData = null, this.getNodeColor = this._getNodeColorFixed, this.setObject = this._setObjectFixed;
  }
  /**
   * Get the PartManager for direct part manipulation.
   * @returns {PartManager}
   */
  get parts() {
    return this._parts;
  }
  /**
   * Get the StateManager for visibility state management.
   * @returns {StateManager}
   */
  get stateManager() {
    return this._stateManager;
  }
  /**
   * Override render to initialize PartManager after scene is built.
   */
  render(e, i, n) {
    this._renderOptions = i, this._viewerOptions = n, this._parts.setRenderOptions(i), this._lastPartsData = (e == null ? void 0 : e.parts) || [];
    const s = super.render(e, i, n);
    return this._parts.buildFromViewer(), this._stateManager.initFromParts(this._lastPartsData), s;
  }
  /**
   * Sync parts with new data - intelligently add, remove, or update.
   * Preserves camera position and visibility states.
   * 
   * @param {Object} shapesData - Shape data with parts array
   * @param {Object} options - Sync options
   * @param {boolean} options.updateTree - Whether to update the tree view (default: true)
   * @returns {boolean} true if sync succeeded
   */
  syncParts(e, i = {}) {
    var o;
    const { updateTree: n = !0 } = i;
    if (!this.ready || !((o = this.nestedGroup) != null && o.groups) || !(e != null && e.parts))
      return !1;
    this._stateManager.saveFromTree(this.treeview);
    const s = this._parts.sync(e.parts), r = new Set(e.parts.map((l) => l.id));
    return this._stateManager.cleanupRemoved(r), this._stateManager.initFromParts(e.parts), n && (s.added > 0 || s.removed > 0) && this._rebuildTreeView(e.parts), this._stateManager.applyToGroups(this.nestedGroup.groups), this._lastPartsData = e.parts, this.update(this.updateMarker), !0;
  }
  /**
   * Rebuild the tree view to reflect current parts.
   * Uses StateManager for visibility state preservation.
   * @private
   */
  _rebuildTreeView(e) {
    if (!this.treeview || !this.display)
      return;
    const i = this._buildTreeFromParts(e);
    this.tree = i, this.expandedTree = i, this.compactTree = i, this.treeview.dispose && this.treeview.dispose(), this.display.clearCadTree();
    try {
      const n = this.treeview.constructor;
      this.treeview = new n(
        this.tree,
        this.display.cadTreeScrollContainer,
        this.setObject,
        this.handlePick,
        this.update,
        this.notifyStates,
        this.getNodeColor,
        this.theme,
        this.newTreeBehavior,
        !1
        // debug
      );
      const s = this.treeview.create();
      switch (this.display.addCadTree(s), this.treeview.render(), this.collapse) {
        case oo.EXPAND_ALL:
          this.treeview.expandAll();
          break;
        case oo.ROOT_ONLY:
          this.treeview.openLevel(-1);
          break;
        case oo.COLLAPSE_ALL:
          this.treeview.collapseAll();
          break;
        case oo.FIRST_LEVEL:
          this.treeview.openLevel(1);
          break;
      }
    } catch (n) {
      console.warn("[LiveViewer] Could not rebuild tree view:", n.message);
    }
  }
  /**
   * Build a tree structure from parts data.
   * Tree structure must match part IDs so paths align.
   * Part ID "/Group/MyBox" -> tree { Group: { MyBox: [1,1] } }
   * @param {Array} partsData - Parts data
   * @private
   */
  _buildTreeFromParts(e) {
    const i = {};
    for (const n of e) {
      const s = n.id || "", r = s.split("/").filter((c) => c);
      if (r.length === 0) continue;
      const o = this._stateManager.get(s);
      let l = i;
      for (let c = 0; c < r.length - 1; c++) {
        const u = r[c];
        l[u] || (l[u] = {}), l = l[u];
      }
      const h = r[r.length - 1];
      l[h] = o;
    }
    return i;
  }
  /**
   * Get a part handle by ID for direct manipulation.
   * @param {string} id - Part ID
   * @returns {PartHandle|null}
   */
  getPart(e) {
    return this._parts.get(e);
  }
  /**
   * Update a single part's geometry and transform.
   * @param {string} id - Part ID
   * @param {Object} partData - Part data with shape and/or loc
   */
  updatePart(e, i) {
    this._parts.update(e, i), this.update(this.updateMarker);
  }
  /**
   * Add a new part to the scene.
   * @param {Object} partData - Part data
   * @returns {PartHandle|null}
   */
  addPart(e) {
    const i = this._parts.add(e);
    return i && (this._stateManager.initFromParts([e]), this.update(this.updateMarker)), i;
  }
  /**
   * Remove a part from the scene.
   * @param {string} id - Part ID
   */
  removePart(e) {
    this._parts.remove(e), this._stateManager.remove(e), this.update(this.updateMarker);
  }
}
function ZC({ model: a, el: t }) {
  const e = a.get("width") || "100%", i = a.get("height") || 600, n = typeof e == "number" ? `${e}px` : e, s = document.createElement("div");
  s.className = "marimo-cad-container", s.style.width = n, s.style.height = i + "px", t.appendChild(s);
  let r = null, o = null, l = null, h = !1;
  function c() {
    if (h) return;
    const f = s.getBoundingClientRect().width, y = f > 0 ? Math.floor(f) : Sf, g = Math.max(y - ia - v0, b0), m = {
      ...OC,
      cadWidth: g,
      height: i,
      treeWidth: ia
    };
    r = new VE(s, m), o = new YC(r, M0, (v) => {
      v.type === "select" && (a.set("selected", v.data), a.save_changes());
    }), h = !0, a.send({ type: "ready" }), u(), requestAnimationFrame(() => {
      if (o.ready)
        try {
          o.resizeCadView(g, ia, i, !1);
        } catch (v) {
          console.warn("[marimo-cad] Initial resize failed:", v.message);
        }
    });
  }
  function u() {
    if (!o) return;
    const f = a.get("shapes_data");
    if (!(!f || !f.parts || f.parts.length === 0) && !(o.ready && o.syncParts && o.syncParts(f))) {
      if (o.nestedGroup)
        try {
          o.clear();
        } catch (y) {
          console.warn("[marimo-cad] Failed to clear viewer:", y.message);
        }
      o.render(f, ax, M0);
    }
  }
  a.on("change:shapes_data", u);
  function d(f) {
    if (!r || !o || !o.ready) return;
    const y = Math.max(Math.floor(f) - ia - v0, b0);
    try {
      r.setSizes({
        cadWidth: y,
        height: i,
        treeWidth: ia
      }), o.resizeCadView(y, ia, i, !1);
    } catch (g) {
      console.warn("[marimo-cad] Resize failed:", g.message);
    }
  }
  const p = new ResizeObserver((f) => {
    const y = f[0].contentRect.width;
    y > 0 && (h ? (l && clearTimeout(l), l = setTimeout(() => {
      d(y);
    }, UC)) : c());
  });
  return p.observe(s), requestAnimationFrame(() => {
    h || c();
  }), () => {
    if (p.disconnect(), l && clearTimeout(l), o)
      try {
        o.dispose();
      } catch (f) {
        console.warn("[marimo-cad] Dispose failed:", f.message);
      }
    s.innerHTML = "";
  };
}
const k2 = { render: ZC };
export {
  k2 as default,
  ZC as render
};
