var e2 = Object.defineProperty;
var n2 = (n, t, e) => t in n ? e2(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
var At = (n, t, e) => n2(n, typeof t != "symbol" ? t + "" : t, e);
function lM(n) {
  return n && n.__esModule && Object.prototype.hasOwnProperty.call(n, "default") ? n.default : n;
}
var pm = { exports: {} }, me = {};
/**
 * @license React
 * react.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var rS;
function i2() {
  if (rS) return me;
  rS = 1;
  var n = Symbol.for("react.transitional.element"), t = Symbol.for("react.portal"), e = Symbol.for("react.fragment"), s = Symbol.for("react.strict_mode"), a = Symbol.for("react.profiler"), o = Symbol.for("react.consumer"), c = Symbol.for("react.context"), u = Symbol.for("react.forward_ref"), d = Symbol.for("react.suspense"), h = Symbol.for("react.memo"), m = Symbol.for("react.lazy"), p = Symbol.for("react.activity"), g = Symbol.iterator;
  function _(F) {
    return F === null || typeof F != "object" ? null : (F = g && F[g] || F["@@iterator"], typeof F == "function" ? F : null);
  }
  var x = {
    isMounted: function() {
      return !1;
    },
    enqueueForceUpdate: function() {
    },
    enqueueReplaceState: function() {
    },
    enqueueSetState: function() {
    }
  }, A = Object.assign, b = {};
  function y(F, W, et) {
    this.props = F, this.context = W, this.refs = b, this.updater = et || x;
  }
  y.prototype.isReactComponent = {}, y.prototype.setState = function(F, W) {
    if (typeof F != "object" && typeof F != "function" && F != null)
      throw Error(
        "takes an object of state variables to update or a function which returns an object of state variables."
      );
    this.updater.enqueueSetState(this, F, W, "setState");
  }, y.prototype.forceUpdate = function(F) {
    this.updater.enqueueForceUpdate(this, F, "forceUpdate");
  };
  function E() {
  }
  E.prototype = y.prototype;
  function w(F, W, et) {
    this.props = F, this.context = W, this.refs = b, this.updater = et || x;
  }
  var M = w.prototype = new E();
  M.constructor = w, A(M, y.prototype), M.isPureReactComponent = !0;
  var O = Array.isArray;
  function C() {
  }
  var D = { H: null, A: null, T: null, S: null }, T = Object.prototype.hasOwnProperty;
  function L(F, W, et) {
    var $ = et.ref;
    return {
      $$typeof: n,
      type: F,
      key: W,
      ref: $ !== void 0 ? $ : null,
      props: et
    };
  }
  function z(F, W) {
    return L(F.type, W, F.props);
  }
  function R(F) {
    return typeof F == "object" && F !== null && F.$$typeof === n;
  }
  function B(F) {
    var W = { "=": "=0", ":": "=2" };
    return "$" + F.replace(/[=:]/g, function(et) {
      return W[et];
    });
  }
  var H = /\/+/g;
  function U(F, W) {
    return typeof F == "object" && F !== null && F.key != null ? B("" + F.key) : W.toString(36);
  }
  function V(F) {
    switch (F.status) {
      case "fulfilled":
        return F.value;
      case "rejected":
        throw F.reason;
      default:
        switch (typeof F.status == "string" ? F.then(C, C) : (F.status = "pending", F.then(
          function(W) {
            F.status === "pending" && (F.status = "fulfilled", F.value = W);
          },
          function(W) {
            F.status === "pending" && (F.status = "rejected", F.reason = W);
          }
        )), F.status) {
          case "fulfilled":
            return F.value;
          case "rejected":
            throw F.reason;
        }
    }
    throw F;
  }
  function N(F, W, et, $, j) {
    var Y = typeof F;
    (Y === "undefined" || Y === "boolean") && (F = null);
    var K = !1;
    if (F === null) K = !0;
    else
      switch (Y) {
        case "bigint":
        case "string":
        case "number":
          K = !0;
          break;
        case "object":
          switch (F.$$typeof) {
            case n:
            case t:
              K = !0;
              break;
            case m:
              return K = F._init, N(
                K(F._payload),
                W,
                et,
                $,
                j
              );
          }
      }
    if (K)
      return j = j(F), K = $ === "" ? "." + U(F, 0) : $, O(j) ? (et = "", K != null && (et = K.replace(H, "$&/") + "/"), N(j, W, et, "", function(dt) {
        return dt;
      })) : j != null && (R(j) && (j = z(
        j,
        et + (j.key == null || F && F.key === j.key ? "" : ("" + j.key).replace(
          H,
          "$&/"
        ) + "/") + K
      )), W.push(j)), 1;
    K = 0;
    var J = $ === "" ? "." : $ + ":";
    if (O(F))
      for (var rt = 0; rt < F.length; rt++)
        $ = F[rt], Y = J + U($, rt), K += N(
          $,
          W,
          et,
          Y,
          j
        );
    else if (rt = _(F), typeof rt == "function")
      for (F = rt.call(F), rt = 0; !($ = F.next()).done; )
        $ = $.value, Y = J + U($, rt++), K += N(
          $,
          W,
          et,
          Y,
          j
        );
    else if (Y === "object") {
      if (typeof F.then == "function")
        return N(
          V(F),
          W,
          et,
          $,
          j
        );
      throw W = String(F), Error(
        "Objects are not valid as a React child (found: " + (W === "[object Object]" ? "object with keys {" + Object.keys(F).join(", ") + "}" : W) + "). If you meant to render a collection of children, use an array instead."
      );
    }
    return K;
  }
  function I(F, W, et) {
    if (F == null) return F;
    var $ = [], j = 0;
    return N(F, $, "", "", function(Y) {
      return W.call(et, Y, j++);
    }), $;
  }
  function k(F) {
    if (F._status === -1) {
      var W = F._result;
      W = W(), W.then(
        function(et) {
          (F._status === 0 || F._status === -1) && (F._status = 1, F._result = et);
        },
        function(et) {
          (F._status === 0 || F._status === -1) && (F._status = 2, F._result = et);
        }
      ), F._status === -1 && (F._status = 0, F._result = W);
    }
    if (F._status === 1) return F._result.default;
    throw F._result;
  }
  var X = typeof reportError == "function" ? reportError : function(F) {
    if (typeof window == "object" && typeof window.ErrorEvent == "function") {
      var W = new window.ErrorEvent("error", {
        bubbles: !0,
        cancelable: !0,
        message: typeof F == "object" && F !== null && typeof F.message == "string" ? String(F.message) : String(F),
        error: F
      });
      if (!window.dispatchEvent(W)) return;
    } else if (typeof process == "object" && typeof process.emit == "function") {
      process.emit("uncaughtException", F);
      return;
    }
    console.error(F);
  }, Q = {
    map: I,
    forEach: function(F, W, et) {
      I(
        F,
        function() {
          W.apply(this, arguments);
        },
        et
      );
    },
    count: function(F) {
      var W = 0;
      return I(F, function() {
        W++;
      }), W;
    },
    toArray: function(F) {
      return I(F, function(W) {
        return W;
      }) || [];
    },
    only: function(F) {
      if (!R(F))
        throw Error(
          "React.Children.only expected to receive a single React element child."
        );
      return F;
    }
  };
  return me.Activity = p, me.Children = Q, me.Component = y, me.Fragment = e, me.Profiler = a, me.PureComponent = w, me.StrictMode = s, me.Suspense = d, me.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = D, me.__COMPILER_RUNTIME = {
    __proto__: null,
    c: function(F) {
      return D.H.useMemoCache(F);
    }
  }, me.cache = function(F) {
    return function() {
      return F.apply(null, arguments);
    };
  }, me.cacheSignal = function() {
    return null;
  }, me.cloneElement = function(F, W, et) {
    if (F == null)
      throw Error(
        "The argument must be a React element, but you passed " + F + "."
      );
    var $ = A({}, F.props), j = F.key;
    if (W != null)
      for (Y in W.key !== void 0 && (j = "" + W.key), W)
        !T.call(W, Y) || Y === "key" || Y === "__self" || Y === "__source" || Y === "ref" && W.ref === void 0 || ($[Y] = W[Y]);
    var Y = arguments.length - 2;
    if (Y === 1) $.children = et;
    else if (1 < Y) {
      for (var K = Array(Y), J = 0; J < Y; J++)
        K[J] = arguments[J + 2];
      $.children = K;
    }
    return L(F.type, j, $);
  }, me.createContext = function(F) {
    return F = {
      $$typeof: c,
      _currentValue: F,
      _currentValue2: F,
      _threadCount: 0,
      Provider: null,
      Consumer: null
    }, F.Provider = F, F.Consumer = {
      $$typeof: o,
      _context: F
    }, F;
  }, me.createElement = function(F, W, et) {
    var $, j = {}, Y = null;
    if (W != null)
      for ($ in W.key !== void 0 && (Y = "" + W.key), W)
        T.call(W, $) && $ !== "key" && $ !== "__self" && $ !== "__source" && (j[$] = W[$]);
    var K = arguments.length - 2;
    if (K === 1) j.children = et;
    else if (1 < K) {
      for (var J = Array(K), rt = 0; rt < K; rt++)
        J[rt] = arguments[rt + 2];
      j.children = J;
    }
    if (F && F.defaultProps)
      for ($ in K = F.defaultProps, K)
        j[$] === void 0 && (j[$] = K[$]);
    return L(F, Y, j);
  }, me.createRef = function() {
    return { current: null };
  }, me.forwardRef = function(F) {
    return { $$typeof: u, render: F };
  }, me.isValidElement = R, me.lazy = function(F) {
    return {
      $$typeof: m,
      _payload: { _status: -1, _result: F },
      _init: k
    };
  }, me.memo = function(F, W) {
    return {
      $$typeof: h,
      type: F,
      compare: W === void 0 ? null : W
    };
  }, me.startTransition = function(F) {
    var W = D.T, et = {};
    D.T = et;
    try {
      var $ = F(), j = D.S;
      j !== null && j(et, $), typeof $ == "object" && $ !== null && typeof $.then == "function" && $.then(C, X);
    } catch (Y) {
      X(Y);
    } finally {
      W !== null && et.types !== null && (W.types = et.types), D.T = W;
    }
  }, me.unstable_useCacheRefresh = function() {
    return D.H.useCacheRefresh();
  }, me.use = function(F) {
    return D.H.use(F);
  }, me.useActionState = function(F, W, et) {
    return D.H.useActionState(F, W, et);
  }, me.useCallback = function(F, W) {
    return D.H.useCallback(F, W);
  }, me.useContext = function(F) {
    return D.H.useContext(F);
  }, me.useDebugValue = function() {
  }, me.useDeferredValue = function(F, W) {
    return D.H.useDeferredValue(F, W);
  }, me.useEffect = function(F, W) {
    return D.H.useEffect(F, W);
  }, me.useEffectEvent = function(F) {
    return D.H.useEffectEvent(F);
  }, me.useId = function() {
    return D.H.useId();
  }, me.useImperativeHandle = function(F, W, et) {
    return D.H.useImperativeHandle(F, W, et);
  }, me.useInsertionEffect = function(F, W) {
    return D.H.useInsertionEffect(F, W);
  }, me.useLayoutEffect = function(F, W) {
    return D.H.useLayoutEffect(F, W);
  }, me.useMemo = function(F, W) {
    return D.H.useMemo(F, W);
  }, me.useOptimistic = function(F, W) {
    return D.H.useOptimistic(F, W);
  }, me.useReducer = function(F, W, et) {
    return D.H.useReducer(F, W, et);
  }, me.useRef = function(F) {
    return D.H.useRef(F);
  }, me.useState = function(F) {
    return D.H.useState(F);
  }, me.useSyncExternalStore = function(F, W, et) {
    return D.H.useSyncExternalStore(
      F,
      W,
      et
    );
  }, me.useTransition = function() {
    return D.H.useTransition();
  }, me.version = "19.2.4", me;
}
var aS;
function eu() {
  return aS || (aS = 1, pm.exports = i2()), pm.exports;
}
var vt = eu();
const Rc = /* @__PURE__ */ lM(vt);
var mm = { exports: {} }, fc = {}, gm = { exports: {} }, vm = {};
/**
 * @license React
 * scheduler.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var oS;
function s2() {
  return oS || (oS = 1, (function(n) {
    function t(N, I) {
      var k = N.length;
      N.push(I);
      t: for (; 0 < k; ) {
        var X = k - 1 >>> 1, Q = N[X];
        if (0 < a(Q, I))
          N[X] = I, N[k] = Q, k = X;
        else break t;
      }
    }
    function e(N) {
      return N.length === 0 ? null : N[0];
    }
    function s(N) {
      if (N.length === 0) return null;
      var I = N[0], k = N.pop();
      if (k !== I) {
        N[0] = k;
        t: for (var X = 0, Q = N.length, F = Q >>> 1; X < F; ) {
          var W = 2 * (X + 1) - 1, et = N[W], $ = W + 1, j = N[$];
          if (0 > a(et, k))
            $ < Q && 0 > a(j, et) ? (N[X] = j, N[$] = k, X = $) : (N[X] = et, N[W] = k, X = W);
          else if ($ < Q && 0 > a(j, k))
            N[X] = j, N[$] = k, X = $;
          else break t;
        }
      }
      return I;
    }
    function a(N, I) {
      var k = N.sortIndex - I.sortIndex;
      return k !== 0 ? k : N.id - I.id;
    }
    if (n.unstable_now = void 0, typeof performance == "object" && typeof performance.now == "function") {
      var o = performance;
      n.unstable_now = function() {
        return o.now();
      };
    } else {
      var c = Date, u = c.now();
      n.unstable_now = function() {
        return c.now() - u;
      };
    }
    var d = [], h = [], m = 1, p = null, g = 3, _ = !1, x = !1, A = !1, b = !1, y = typeof setTimeout == "function" ? setTimeout : null, E = typeof clearTimeout == "function" ? clearTimeout : null, w = typeof setImmediate < "u" ? setImmediate : null;
    function M(N) {
      for (var I = e(h); I !== null; ) {
        if (I.callback === null) s(h);
        else if (I.startTime <= N)
          s(h), I.sortIndex = I.expirationTime, t(d, I);
        else break;
        I = e(h);
      }
    }
    function O(N) {
      if (A = !1, M(N), !x)
        if (e(d) !== null)
          x = !0, C || (C = !0, B());
        else {
          var I = e(h);
          I !== null && V(O, I.startTime - N);
        }
    }
    var C = !1, D = -1, T = 5, L = -1;
    function z() {
      return b ? !0 : !(n.unstable_now() - L < T);
    }
    function R() {
      if (b = !1, C) {
        var N = n.unstable_now();
        L = N;
        var I = !0;
        try {
          t: {
            x = !1, A && (A = !1, E(D), D = -1), _ = !0;
            var k = g;
            try {
              e: {
                for (M(N), p = e(d); p !== null && !(p.expirationTime > N && z()); ) {
                  var X = p.callback;
                  if (typeof X == "function") {
                    p.callback = null, g = p.priorityLevel;
                    var Q = X(
                      p.expirationTime <= N
                    );
                    if (N = n.unstable_now(), typeof Q == "function") {
                      p.callback = Q, M(N), I = !0;
                      break e;
                    }
                    p === e(d) && s(d), M(N);
                  } else s(d);
                  p = e(d);
                }
                if (p !== null) I = !0;
                else {
                  var F = e(h);
                  F !== null && V(
                    O,
                    F.startTime - N
                  ), I = !1;
                }
              }
              break t;
            } finally {
              p = null, g = k, _ = !1;
            }
            I = void 0;
          }
        } finally {
          I ? B() : C = !1;
        }
      }
    }
    var B;
    if (typeof w == "function")
      B = function() {
        w(R);
      };
    else if (typeof MessageChannel < "u") {
      var H = new MessageChannel(), U = H.port2;
      H.port1.onmessage = R, B = function() {
        U.postMessage(null);
      };
    } else
      B = function() {
        y(R, 0);
      };
    function V(N, I) {
      D = y(function() {
        N(n.unstable_now());
      }, I);
    }
    n.unstable_IdlePriority = 5, n.unstable_ImmediatePriority = 1, n.unstable_LowPriority = 4, n.unstable_NormalPriority = 3, n.unstable_Profiling = null, n.unstable_UserBlockingPriority = 2, n.unstable_cancelCallback = function(N) {
      N.callback = null;
    }, n.unstable_forceFrameRate = function(N) {
      0 > N || 125 < N ? console.error(
        "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
      ) : T = 0 < N ? Math.floor(1e3 / N) : 5;
    }, n.unstable_getCurrentPriorityLevel = function() {
      return g;
    }, n.unstable_next = function(N) {
      switch (g) {
        case 1:
        case 2:
        case 3:
          var I = 3;
          break;
        default:
          I = g;
      }
      var k = g;
      g = I;
      try {
        return N();
      } finally {
        g = k;
      }
    }, n.unstable_requestPaint = function() {
      b = !0;
    }, n.unstable_runWithPriority = function(N, I) {
      switch (N) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          break;
        default:
          N = 3;
      }
      var k = g;
      g = N;
      try {
        return I();
      } finally {
        g = k;
      }
    }, n.unstable_scheduleCallback = function(N, I, k) {
      var X = n.unstable_now();
      switch (typeof k == "object" && k !== null ? (k = k.delay, k = typeof k == "number" && 0 < k ? X + k : X) : k = X, N) {
        case 1:
          var Q = -1;
          break;
        case 2:
          Q = 250;
          break;
        case 5:
          Q = 1073741823;
          break;
        case 4:
          Q = 1e4;
          break;
        default:
          Q = 5e3;
      }
      return Q = k + Q, N = {
        id: m++,
        callback: I,
        priorityLevel: N,
        startTime: k,
        expirationTime: Q,
        sortIndex: -1
      }, k > X ? (N.sortIndex = k, t(h, N), e(d) === null && N === e(h) && (A ? (E(D), D = -1) : A = !0, V(O, k - X))) : (N.sortIndex = Q, t(d, N), x || _ || (x = !0, C || (C = !0, B()))), N;
    }, n.unstable_shouldYield = z, n.unstable_wrapCallback = function(N) {
      var I = g;
      return function() {
        var k = g;
        g = I;
        try {
          return N.apply(this, arguments);
        } finally {
          g = k;
        }
      };
    };
  })(vm)), vm;
}
var lS;
function r2() {
  return lS || (lS = 1, gm.exports = s2()), gm.exports;
}
var _m = { exports: {} }, Zn = {};
/**
 * @license React
 * react-dom.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var cS;
function a2() {
  if (cS) return Zn;
  cS = 1;
  var n = eu();
  function t(d) {
    var h = "https://react.dev/errors/" + d;
    if (1 < arguments.length) {
      h += "?args[]=" + encodeURIComponent(arguments[1]);
      for (var m = 2; m < arguments.length; m++)
        h += "&args[]=" + encodeURIComponent(arguments[m]);
    }
    return "Minified React error #" + d + "; visit " + h + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
  }
  function e() {
  }
  var s = {
    d: {
      f: e,
      r: function() {
        throw Error(t(522));
      },
      D: e,
      C: e,
      L: e,
      m: e,
      X: e,
      S: e,
      M: e
    },
    p: 0,
    findDOMNode: null
  }, a = Symbol.for("react.portal");
  function o(d, h, m) {
    var p = 3 < arguments.length && arguments[3] !== void 0 ? arguments[3] : null;
    return {
      $$typeof: a,
      key: p == null ? null : "" + p,
      children: d,
      containerInfo: h,
      implementation: m
    };
  }
  var c = n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
  function u(d, h) {
    if (d === "font") return "";
    if (typeof h == "string")
      return h === "use-credentials" ? h : "";
  }
  return Zn.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = s, Zn.createPortal = function(d, h) {
    var m = 2 < arguments.length && arguments[2] !== void 0 ? arguments[2] : null;
    if (!h || h.nodeType !== 1 && h.nodeType !== 9 && h.nodeType !== 11)
      throw Error(t(299));
    return o(d, h, null, m);
  }, Zn.flushSync = function(d) {
    var h = c.T, m = s.p;
    try {
      if (c.T = null, s.p = 2, d) return d();
    } finally {
      c.T = h, s.p = m, s.d.f();
    }
  }, Zn.preconnect = function(d, h) {
    typeof d == "string" && (h ? (h = h.crossOrigin, h = typeof h == "string" ? h === "use-credentials" ? h : "" : void 0) : h = null, s.d.C(d, h));
  }, Zn.prefetchDNS = function(d) {
    typeof d == "string" && s.d.D(d);
  }, Zn.preinit = function(d, h) {
    if (typeof d == "string" && h && typeof h.as == "string") {
      var m = h.as, p = u(m, h.crossOrigin), g = typeof h.integrity == "string" ? h.integrity : void 0, _ = typeof h.fetchPriority == "string" ? h.fetchPriority : void 0;
      m === "style" ? s.d.S(
        d,
        typeof h.precedence == "string" ? h.precedence : void 0,
        {
          crossOrigin: p,
          integrity: g,
          fetchPriority: _
        }
      ) : m === "script" && s.d.X(d, {
        crossOrigin: p,
        integrity: g,
        fetchPriority: _,
        nonce: typeof h.nonce == "string" ? h.nonce : void 0
      });
    }
  }, Zn.preinitModule = function(d, h) {
    if (typeof d == "string")
      if (typeof h == "object" && h !== null) {
        if (h.as == null || h.as === "script") {
          var m = u(
            h.as,
            h.crossOrigin
          );
          s.d.M(d, {
            crossOrigin: m,
            integrity: typeof h.integrity == "string" ? h.integrity : void 0,
            nonce: typeof h.nonce == "string" ? h.nonce : void 0
          });
        }
      } else h == null && s.d.M(d);
  }, Zn.preload = function(d, h) {
    if (typeof d == "string" && typeof h == "object" && h !== null && typeof h.as == "string") {
      var m = h.as, p = u(m, h.crossOrigin);
      s.d.L(d, m, {
        crossOrigin: p,
        integrity: typeof h.integrity == "string" ? h.integrity : void 0,
        nonce: typeof h.nonce == "string" ? h.nonce : void 0,
        type: typeof h.type == "string" ? h.type : void 0,
        fetchPriority: typeof h.fetchPriority == "string" ? h.fetchPriority : void 0,
        referrerPolicy: typeof h.referrerPolicy == "string" ? h.referrerPolicy : void 0,
        imageSrcSet: typeof h.imageSrcSet == "string" ? h.imageSrcSet : void 0,
        imageSizes: typeof h.imageSizes == "string" ? h.imageSizes : void 0,
        media: typeof h.media == "string" ? h.media : void 0
      });
    }
  }, Zn.preloadModule = function(d, h) {
    if (typeof d == "string")
      if (h) {
        var m = u(h.as, h.crossOrigin);
        s.d.m(d, {
          as: typeof h.as == "string" && h.as !== "script" ? h.as : void 0,
          crossOrigin: m,
          integrity: typeof h.integrity == "string" ? h.integrity : void 0
        });
      } else s.d.m(d);
  }, Zn.requestFormReset = function(d) {
    s.d.r(d);
  }, Zn.unstable_batchedUpdates = function(d, h) {
    return d(h);
  }, Zn.useFormState = function(d, h, m) {
    return c.H.useFormState(d, h, m);
  }, Zn.useFormStatus = function() {
    return c.H.useHostTransitionStatus();
  }, Zn.version = "19.2.4", Zn;
}
var uS;
function cM() {
  if (uS) return _m.exports;
  uS = 1;
  function n() {
    if (!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ > "u" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE != "function"))
      try {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n);
      } catch (t) {
        console.error(t);
      }
  }
  return n(), _m.exports = a2(), _m.exports;
}
/**
 * @license React
 * react-dom-client.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var fS;
function o2() {
  if (fS) return fc;
  fS = 1;
  var n = r2(), t = eu(), e = cM();
  function s(i) {
    var r = "https://react.dev/errors/" + i;
    if (1 < arguments.length) {
      r += "?args[]=" + encodeURIComponent(arguments[1]);
      for (var l = 2; l < arguments.length; l++)
        r += "&args[]=" + encodeURIComponent(arguments[l]);
    }
    return "Minified React error #" + i + "; visit " + r + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
  }
  function a(i) {
    return !(!i || i.nodeType !== 1 && i.nodeType !== 9 && i.nodeType !== 11);
  }
  function o(i) {
    var r = i, l = i;
    if (i.alternate) for (; r.return; ) r = r.return;
    else {
      i = r;
      do
        r = i, (r.flags & 4098) !== 0 && (l = r.return), i = r.return;
      while (i);
    }
    return r.tag === 3 ? l : null;
  }
  function c(i) {
    if (i.tag === 13) {
      var r = i.memoizedState;
      if (r === null && (i = i.alternate, i !== null && (r = i.memoizedState)), r !== null) return r.dehydrated;
    }
    return null;
  }
  function u(i) {
    if (i.tag === 31) {
      var r = i.memoizedState;
      if (r === null && (i = i.alternate, i !== null && (r = i.memoizedState)), r !== null) return r.dehydrated;
    }
    return null;
  }
  function d(i) {
    if (o(i) !== i)
      throw Error(s(188));
  }
  function h(i) {
    var r = i.alternate;
    if (!r) {
      if (r = o(i), r === null) throw Error(s(188));
      return r !== i ? null : i;
    }
    for (var l = i, f = r; ; ) {
      var v = l.return;
      if (v === null) break;
      var S = v.alternate;
      if (S === null) {
        if (f = v.return, f !== null) {
          l = f;
          continue;
        }
        break;
      }
      if (v.child === S.child) {
        for (S = v.child; S; ) {
          if (S === l) return d(v), i;
          if (S === f) return d(v), r;
          S = S.sibling;
        }
        throw Error(s(188));
      }
      if (l.return !== f.return) l = v, f = S;
      else {
        for (var P = !1, q = v.child; q; ) {
          if (q === l) {
            P = !0, l = v, f = S;
            break;
          }
          if (q === f) {
            P = !0, f = v, l = S;
            break;
          }
          q = q.sibling;
        }
        if (!P) {
          for (q = S.child; q; ) {
            if (q === l) {
              P = !0, l = S, f = v;
              break;
            }
            if (q === f) {
              P = !0, f = S, l = v;
              break;
            }
            q = q.sibling;
          }
          if (!P) throw Error(s(189));
        }
      }
      if (l.alternate !== f) throw Error(s(190));
    }
    if (l.tag !== 3) throw Error(s(188));
    return l.stateNode.current === l ? i : r;
  }
  function m(i) {
    var r = i.tag;
    if (r === 5 || r === 26 || r === 27 || r === 6) return i;
    for (i = i.child; i !== null; ) {
      if (r = m(i), r !== null) return r;
      i = i.sibling;
    }
    return null;
  }
  var p = Object.assign, g = Symbol.for("react.element"), _ = Symbol.for("react.transitional.element"), x = Symbol.for("react.portal"), A = Symbol.for("react.fragment"), b = Symbol.for("react.strict_mode"), y = Symbol.for("react.profiler"), E = Symbol.for("react.consumer"), w = Symbol.for("react.context"), M = Symbol.for("react.forward_ref"), O = Symbol.for("react.suspense"), C = Symbol.for("react.suspense_list"), D = Symbol.for("react.memo"), T = Symbol.for("react.lazy"), L = Symbol.for("react.activity"), z = Symbol.for("react.memo_cache_sentinel"), R = Symbol.iterator;
  function B(i) {
    return i === null || typeof i != "object" ? null : (i = R && i[R] || i["@@iterator"], typeof i == "function" ? i : null);
  }
  var H = Symbol.for("react.client.reference");
  function U(i) {
    if (i == null) return null;
    if (typeof i == "function")
      return i.$$typeof === H ? null : i.displayName || i.name || null;
    if (typeof i == "string") return i;
    switch (i) {
      case A:
        return "Fragment";
      case y:
        return "Profiler";
      case b:
        return "StrictMode";
      case O:
        return "Suspense";
      case C:
        return "SuspenseList";
      case L:
        return "Activity";
    }
    if (typeof i == "object")
      switch (i.$$typeof) {
        case x:
          return "Portal";
        case w:
          return i.displayName || "Context";
        case E:
          return (i._context.displayName || "Context") + ".Consumer";
        case M:
          var r = i.render;
          return i = i.displayName, i || (i = r.displayName || r.name || "", i = i !== "" ? "ForwardRef(" + i + ")" : "ForwardRef"), i;
        case D:
          return r = i.displayName || null, r !== null ? r : U(i.type) || "Memo";
        case T:
          r = i._payload, i = i._init;
          try {
            return U(i(r));
          } catch {
          }
      }
    return null;
  }
  var V = Array.isArray, N = t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, I = e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, k = {
    pending: !1,
    data: null,
    method: null,
    action: null
  }, X = [], Q = -1;
  function F(i) {
    return { current: i };
  }
  function W(i) {
    0 > Q || (i.current = X[Q], X[Q] = null, Q--);
  }
  function et(i, r) {
    Q++, X[Q] = i.current, i.current = r;
  }
  var $ = F(null), j = F(null), Y = F(null), K = F(null);
  function J(i, r) {
    switch (et(Y, r), et(j, i), et($, null), r.nodeType) {
      case 9:
      case 11:
        i = (i = r.documentElement) && (i = i.namespaceURI) ? Cx(i) : 0;
        break;
      default:
        if (i = r.tagName, r = r.namespaceURI)
          r = Cx(r), i = Rx(r, i);
        else
          switch (i) {
            case "svg":
              i = 1;
              break;
            case "math":
              i = 2;
              break;
            default:
              i = 0;
          }
    }
    W($), et($, i);
  }
  function rt() {
    W($), W(j), W(Y);
  }
  function dt(i) {
    i.memoizedState !== null && et(K, i);
    var r = $.current, l = Rx(r, i.type);
    r !== l && (et(j, i), et($, l));
  }
  function yt(i) {
    j.current === i && (W($), W(j)), K.current === i && (W(K), oc._currentValue = k);
  }
  var Pt, Lt;
  function zt(i) {
    if (Pt === void 0)
      try {
        throw Error();
      } catch (l) {
        var r = l.stack.trim().match(/\n( *(at )?)/);
        Pt = r && r[1] || "", Lt = -1 < l.stack.indexOf(`
    at`) ? " (<anonymous>)" : -1 < l.stack.indexOf("@") ? "@unknown:0:0" : "";
      }
    return `
` + Pt + i + Lt;
  }
  var Xt = !1;
  function Ft(i, r) {
    if (!i || Xt) return "";
    Xt = !0;
    var l = Error.prepareStackTrace;
    Error.prepareStackTrace = void 0;
    try {
      var f = {
        DetermineComponentFrameRoot: function() {
          try {
            if (r) {
              var Ct = function() {
                throw Error();
              };
              if (Object.defineProperty(Ct.prototype, "props", {
                set: function() {
                  throw Error();
                }
              }), typeof Reflect == "object" && Reflect.construct) {
                try {
                  Reflect.construct(Ct, []);
                } catch (St) {
                  var gt = St;
                }
                Reflect.construct(i, [], Ct);
              } else {
                try {
                  Ct.call();
                } catch (St) {
                  gt = St;
                }
                i.call(Ct.prototype);
              }
            } else {
              try {
                throw Error();
              } catch (St) {
                gt = St;
              }
              (Ct = i()) && typeof Ct.catch == "function" && Ct.catch(function() {
              });
            }
          } catch (St) {
            if (St && gt && typeof St.stack == "string")
              return [St.stack, gt.stack];
          }
          return [null, null];
        }
      };
      f.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
      var v = Object.getOwnPropertyDescriptor(
        f.DetermineComponentFrameRoot,
        "name"
      );
      v && v.configurable && Object.defineProperty(
        f.DetermineComponentFrameRoot,
        "name",
        { value: "DetermineComponentFrameRoot" }
      );
      var S = f.DetermineComponentFrameRoot(), P = S[0], q = S[1];
      if (P && q) {
        var nt = P.split(`
`), pt = q.split(`
`);
        for (v = f = 0; f < nt.length && !nt[f].includes("DetermineComponentFrameRoot"); )
          f++;
        for (; v < pt.length && !pt[v].includes(
          "DetermineComponentFrameRoot"
        ); )
          v++;
        if (f === nt.length || v === pt.length)
          for (f = nt.length - 1, v = pt.length - 1; 1 <= f && 0 <= v && nt[f] !== pt[v]; )
            v--;
        for (; 1 <= f && 0 <= v; f--, v--)
          if (nt[f] !== pt[v]) {
            if (f !== 1 || v !== 1)
              do
                if (f--, v--, 0 > v || nt[f] !== pt[v]) {
                  var wt = `
` + nt[f].replace(" at new ", " at ");
                  return i.displayName && wt.includes("<anonymous>") && (wt = wt.replace("<anonymous>", i.displayName)), wt;
                }
              while (1 <= f && 0 <= v);
            break;
          }
      }
    } finally {
      Xt = !1, Error.prepareStackTrace = l;
    }
    return (l = i ? i.displayName || i.name : "") ? zt(l) : "";
  }
  function ve(i, r) {
    switch (i.tag) {
      case 26:
      case 27:
      case 5:
        return zt(i.type);
      case 16:
        return zt("Lazy");
      case 13:
        return i.child !== r && r !== null ? zt("Suspense Fallback") : zt("Suspense");
      case 19:
        return zt("SuspenseList");
      case 0:
      case 15:
        return Ft(i.type, !1);
      case 11:
        return Ft(i.type.render, !1);
      case 1:
        return Ft(i.type, !0);
      case 31:
        return zt("Activity");
      default:
        return "";
    }
  }
  function it(i) {
    try {
      var r = "", l = null;
      do
        r += ve(i, l), l = i, i = i.return;
      while (i);
      return r;
    } catch (f) {
      return `
Error generating stack: ` + f.message + `
` + f.stack;
    }
  }
  var Ue = Object.prototype.hasOwnProperty, xe = n.unstable_scheduleCallback, Re = n.unstable_cancelCallback, Kt = n.unstable_shouldYield, tt = n.unstable_requestPaint, G = n.unstable_now, ct = n.unstable_getCurrentPriorityLevel, Et = n.unstable_ImmediatePriority, Rt = n.unstable_UserBlockingPriority, Mt = n.unstable_NormalPriority, Jt = n.unstable_LowPriority, It = n.unstable_IdlePriority, se = n.log, le = n.unstable_setDisableYieldValue, Ot = null, Dt = null;
  function Wt(i) {
    if (typeof se == "function" && le(i), Dt && typeof Dt.setStrictMode == "function")
      try {
        Dt.setStrictMode(Ot, i);
      } catch {
      }
  }
  var kt = Math.clz32 ? Math.clz32 : lt, Yt = Math.log, _e = Math.LN2;
  function lt(i) {
    return i >>>= 0, i === 0 ? 32 : 31 - (Yt(i) / _e | 0) | 0;
  }
  var Bt = 256, Ut = 262144, jt = 4194304;
  function Nt(i) {
    var r = i & 42;
    if (r !== 0) return r;
    switch (i & -i) {
      case 1:
        return 1;
      case 2:
        return 2;
      case 4:
        return 4;
      case 8:
        return 8;
      case 16:
        return 16;
      case 32:
        return 32;
      case 64:
        return 64;
      case 128:
        return 128;
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
      case 32768:
      case 65536:
      case 131072:
        return i & 261888;
      case 262144:
      case 524288:
      case 1048576:
      case 2097152:
        return i & 3932160;
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
        return i & 62914560;
      case 67108864:
        return 67108864;
      case 134217728:
        return 134217728;
      case 268435456:
        return 268435456;
      case 536870912:
        return 536870912;
      case 1073741824:
        return 0;
      default:
        return i;
    }
  }
  function bt(i, r, l) {
    var f = i.pendingLanes;
    if (f === 0) return 0;
    var v = 0, S = i.suspendedLanes, P = i.pingedLanes;
    i = i.warmLanes;
    var q = f & 134217727;
    return q !== 0 ? (f = q & ~S, f !== 0 ? v = Nt(f) : (P &= q, P !== 0 ? v = Nt(P) : l || (l = q & ~i, l !== 0 && (v = Nt(l))))) : (q = f & ~S, q !== 0 ? v = Nt(q) : P !== 0 ? v = Nt(P) : l || (l = f & ~i, l !== 0 && (v = Nt(l)))), v === 0 ? 0 : r !== 0 && r !== v && (r & S) === 0 && (S = v & -v, l = r & -r, S >= l || S === 32 && (l & 4194048) !== 0) ? r : v;
  }
  function Zt(i, r) {
    return (i.pendingLanes & ~(i.suspendedLanes & ~i.pingedLanes) & r) === 0;
  }
  function fe(i, r) {
    switch (i) {
      case 1:
      case 2:
      case 4:
      case 8:
      case 64:
        return r + 250;
      case 16:
      case 32:
      case 128:
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
      case 32768:
      case 65536:
      case 131072:
      case 262144:
      case 524288:
      case 1048576:
      case 2097152:
        return r + 5e3;
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
        return -1;
      case 67108864:
      case 134217728:
      case 268435456:
      case 536870912:
      case 1073741824:
        return -1;
      default:
        return -1;
    }
  }
  function He() {
    var i = jt;
    return jt <<= 1, (jt & 62914560) === 0 && (jt = 4194304), i;
  }
  function Oe(i) {
    for (var r = [], l = 0; 31 > l; l++) r.push(i);
    return r;
  }
  function Fn(i, r) {
    i.pendingLanes |= r, r !== 268435456 && (i.suspendedLanes = 0, i.pingedLanes = 0, i.warmLanes = 0);
  }
  function mi(i, r, l, f, v, S) {
    var P = i.pendingLanes;
    i.pendingLanes = l, i.suspendedLanes = 0, i.pingedLanes = 0, i.warmLanes = 0, i.expiredLanes &= l, i.entangledLanes &= l, i.errorRecoveryDisabledLanes &= l, i.shellSuspendCounter = 0;
    var q = i.entanglements, nt = i.expirationTimes, pt = i.hiddenUpdates;
    for (l = P & ~l; 0 < l; ) {
      var wt = 31 - kt(l), Ct = 1 << wt;
      q[wt] = 0, nt[wt] = -1;
      var gt = pt[wt];
      if (gt !== null)
        for (pt[wt] = null, wt = 0; wt < gt.length; wt++) {
          var St = gt[wt];
          St !== null && (St.lane &= -536870913);
        }
      l &= ~Ct;
    }
    f !== 0 && oa(i, f, 0), S !== 0 && v === 0 && i.tag !== 0 && (i.suspendedLanes |= S & ~(P & ~r));
  }
  function oa(i, r, l) {
    i.pendingLanes |= r, i.suspendedLanes &= ~r;
    var f = 31 - kt(r);
    i.entangledLanes |= r, i.entanglements[f] = i.entanglements[f] | 1073741824 | l & 261930;
  }
  function vr(i, r) {
    var l = i.entangledLanes |= r;
    for (i = i.entanglements; l; ) {
      var f = 31 - kt(l), v = 1 << f;
      v & r | i[f] & r && (i[f] |= r), l &= ~v;
    }
  }
  function $a(i, r) {
    var l = r & -r;
    return l = (l & 42) !== 0 ? 1 : _r(l), (l & (i.suspendedLanes | r)) !== 0 ? 0 : l;
  }
  function _r(i) {
    switch (i) {
      case 2:
        i = 1;
        break;
      case 8:
        i = 4;
        break;
      case 32:
        i = 16;
        break;
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
      case 32768:
      case 65536:
      case 131072:
      case 262144:
      case 524288:
      case 1048576:
      case 2097152:
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
        i = 128;
        break;
      case 268435456:
        i = 134217728;
        break;
      default:
        i = 0;
    }
    return i;
  }
  function yr(i) {
    return i &= -i, 2 < i ? 8 < i ? (i & 134217727) !== 0 ? 32 : 268435456 : 8 : 2;
  }
  function Li() {
    var i = I.p;
    return i !== 0 ? i : (i = window.event, i === void 0 ? 32 : Qx(i.type));
  }
  function xr(i, r) {
    var l = I.p;
    try {
      return I.p = i, r();
    } finally {
      I.p = l;
    }
  }
  var gi = Math.random().toString(36).slice(2), cn = "__reactFiber$" + gi, hn = "__reactProps$" + gi, Ui = "__reactContainer$" + gi, Yi = "__reactEvents$" + gi, la = "__reactListeners$" + gi, Ka = "__reactHandles$" + gi, Qa = "__reactResources$" + gi, Ls = "__reactMarker$" + gi;
  function ca(i) {
    delete i[cn], delete i[hn], delete i[Yi], delete i[la], delete i[Ka];
  }
  function cs(i) {
    var r = i[cn];
    if (r) return r;
    for (var l = i.parentNode; l; ) {
      if (r = l[Ui] || l[cn]) {
        if (l = r.alternate, r.child !== null || l !== null && l.child !== null)
          for (i = Ix(i); i !== null; ) {
            if (l = i[cn]) return l;
            i = Ix(i);
          }
        return r;
      }
      i = l, l = i.parentNode;
    }
    return null;
  }
  function us(i) {
    if (i = i[cn] || i[Ui]) {
      var r = i.tag;
      if (r === 5 || r === 6 || r === 13 || r === 31 || r === 26 || r === 27 || r === 3)
        return i;
    }
    return null;
  }
  function fs(i) {
    var r = i.tag;
    if (r === 5 || r === 26 || r === 27 || r === 6) return i.stateNode;
    throw Error(s(33));
  }
  function Z(i) {
    var r = i[Qa];
    return r || (r = i[Qa] = { hoistableStyles: /* @__PURE__ */ new Map(), hoistableScripts: /* @__PURE__ */ new Map() }), r;
  }
  function ot(i) {
    i[Ls] = !0;
  }
  var xt = /* @__PURE__ */ new Set(), mt = {};
  function ft(i, r) {
    Ht(i, r), Ht(i + "Capture", r);
  }
  function Ht(i, r) {
    for (mt[i] = r, i = 0; i < r.length; i++)
      xt.add(r[i]);
  }
  var qt = RegExp(
    "^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
  ), Vt = {}, te = {};
  function ne(i) {
    return Ue.call(te, i) ? !0 : Ue.call(Vt, i) ? !1 : qt.test(i) ? te[i] = !0 : (Vt[i] = !0, !1);
  }
  function ue(i, r, l) {
    if (ne(r))
      if (l === null) i.removeAttribute(r);
      else {
        switch (typeof l) {
          case "undefined":
          case "function":
          case "symbol":
            i.removeAttribute(r);
            return;
          case "boolean":
            var f = r.toLowerCase().slice(0, 5);
            if (f !== "data-" && f !== "aria-") {
              i.removeAttribute(r);
              return;
            }
        }
        i.setAttribute(r, "" + l);
      }
  }
  function pe(i, r, l) {
    if (l === null) i.removeAttribute(r);
    else {
      switch (typeof l) {
        case "undefined":
        case "function":
        case "symbol":
        case "boolean":
          i.removeAttribute(r);
          return;
      }
      i.setAttribute(r, "" + l);
    }
  }
  function $t(i, r, l, f) {
    if (f === null) i.removeAttribute(l);
    else {
      switch (typeof f) {
        case "undefined":
        case "function":
        case "symbol":
        case "boolean":
          i.removeAttribute(l);
          return;
      }
      i.setAttributeNS(r, l, "" + f);
    }
  }
  function ye(i) {
    switch (typeof i) {
      case "bigint":
      case "boolean":
      case "number":
      case "string":
      case "undefined":
        return i;
      case "object":
        return i;
      default:
        return "";
    }
  }
  function en(i) {
    var r = i.type;
    return (i = i.nodeName) && i.toLowerCase() === "input" && (r === "checkbox" || r === "radio");
  }
  function nn(i, r, l) {
    var f = Object.getOwnPropertyDescriptor(
      i.constructor.prototype,
      r
    );
    if (!i.hasOwnProperty(r) && typeof f < "u" && typeof f.get == "function" && typeof f.set == "function") {
      var v = f.get, S = f.set;
      return Object.defineProperty(i, r, {
        configurable: !0,
        get: function() {
          return v.call(this);
        },
        set: function(P) {
          l = "" + P, S.call(this, P);
        }
      }), Object.defineProperty(i, r, {
        enumerable: f.enumerable
      }), {
        getValue: function() {
          return l;
        },
        setValue: function(P) {
          l = "" + P;
        },
        stopTracking: function() {
          i._valueTracker = null, delete i[r];
        }
      };
    }
  }
  function Ae(i) {
    if (!i._valueTracker) {
      var r = en(i) ? "checked" : "value";
      i._valueTracker = nn(
        i,
        r,
        "" + i[r]
      );
    }
  }
  function pn(i) {
    if (!i) return !1;
    var r = i._valueTracker;
    if (!r) return !0;
    var l = r.getValue(), f = "";
    return i && (f = en(i) ? i.checked ? "true" : "false" : i.value), i = f, i !== l ? (r.setValue(i), !0) : !1;
  }
  function Qt(i) {
    if (i = i || (typeof document < "u" ? document : void 0), typeof i > "u") return null;
    try {
      return i.activeElement || i.body;
    } catch {
      return i.body;
    }
  }
  var Hn = /[\n"\\]/g;
  function he(i) {
    return i.replace(
      Hn,
      function(r) {
        return "\\" + r.charCodeAt(0).toString(16) + " ";
      }
    );
  }
  function Dn(i, r, l, f, v, S, P, q) {
    i.name = "", P != null && typeof P != "function" && typeof P != "symbol" && typeof P != "boolean" ? i.type = P : i.removeAttribute("type"), r != null ? P === "number" ? (r === 0 && i.value === "" || i.value != r) && (i.value = "" + ye(r)) : i.value !== "" + ye(r) && (i.value = "" + ye(r)) : P !== "submit" && P !== "reset" || i.removeAttribute("value"), r != null ? vi(i, P, ye(r)) : l != null ? vi(i, P, ye(l)) : f != null && i.removeAttribute("value"), v == null && S != null && (i.defaultChecked = !!S), v != null && (i.checked = v && typeof v != "function" && typeof v != "symbol"), q != null && typeof q != "function" && typeof q != "symbol" && typeof q != "boolean" ? i.name = "" + ye(q) : i.removeAttribute("name");
  }
  function ti(i, r, l, f, v, S, P, q) {
    if (S != null && typeof S != "function" && typeof S != "symbol" && typeof S != "boolean" && (i.type = S), r != null || l != null) {
      if (!(S !== "submit" && S !== "reset" || r != null)) {
        Ae(i);
        return;
      }
      l = l != null ? "" + ye(l) : "", r = r != null ? "" + ye(r) : l, q || r === i.value || (i.value = r), i.defaultValue = r;
    }
    f = f ?? v, f = typeof f != "function" && typeof f != "symbol" && !!f, i.checked = q ? i.checked : !!f, i.defaultChecked = !!f, P != null && typeof P != "function" && typeof P != "symbol" && typeof P != "boolean" && (i.name = P), Ae(i);
  }
  function vi(i, r, l) {
    r === "number" && Qt(i.ownerDocument) === i || i.defaultValue === "" + l || (i.defaultValue = "" + l);
  }
  function qn(i, r, l, f) {
    if (i = i.options, r) {
      r = {};
      for (var v = 0; v < l.length; v++)
        r["$" + l[v]] = !0;
      for (l = 0; l < i.length; l++)
        v = r.hasOwnProperty("$" + i[l].value), i[l].selected !== v && (i[l].selected = v), v && f && (i[l].defaultSelected = !0);
    } else {
      for (l = "" + ye(l), r = null, v = 0; v < i.length; v++) {
        if (i[v].value === l) {
          i[v].selected = !0, f && (i[v].defaultSelected = !0);
          return;
        }
        r !== null || i[v].disabled || (r = i[v]);
      }
      r !== null && (r.selected = !0);
    }
  }
  function Ge(i, r, l) {
    if (r != null && (r = "" + ye(r), r !== i.value && (i.value = r), l == null)) {
      i.defaultValue !== r && (i.defaultValue = r);
      return;
    }
    i.defaultValue = l != null ? "" + ye(l) : "";
  }
  function yn(i, r, l, f) {
    if (r == null) {
      if (f != null) {
        if (l != null) throw Error(s(92));
        if (V(f)) {
          if (1 < f.length) throw Error(s(93));
          f = f[0];
        }
        l = f;
      }
      l == null && (l = ""), r = l;
    }
    l = ye(r), i.defaultValue = l, f = i.textContent, f === l && f !== "" && f !== null && (i.value = f), Ae(i);
  }
  function ei(i, r) {
    if (r) {
      var l = i.firstChild;
      if (l && l === i.lastChild && l.nodeType === 3) {
        l.nodeValue = r;
        return;
      }
    }
    i.textContent = r;
  }
  var xn = new Set(
    "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
      " "
    )
  );
  function ji(i, r, l) {
    var f = r.indexOf("--") === 0;
    l == null || typeof l == "boolean" || l === "" ? f ? i.setProperty(r, "") : r === "float" ? i.cssFloat = "" : i[r] = "" : f ? i.setProperty(r, l) : typeof l != "number" || l === 0 || xn.has(r) ? r === "float" ? i.cssFloat = l : i[r] = ("" + l).trim() : i[r] = l + "px";
  }
  function Us(i, r, l) {
    if (r != null && typeof r != "object")
      throw Error(s(62));
    if (i = i.style, l != null) {
      for (var f in l)
        !l.hasOwnProperty(f) || r != null && r.hasOwnProperty(f) || (f.indexOf("--") === 0 ? i.setProperty(f, "") : f === "float" ? i.cssFloat = "" : i[f] = "");
      for (var v in r)
        f = r[v], r.hasOwnProperty(v) && l[v] !== f && ji(i, v, f);
    } else
      for (var S in r)
        r.hasOwnProperty(S) && ji(i, S, r[S]);
  }
  function Ja(i) {
    if (i.indexOf("-") === -1) return !1;
    switch (i) {
      case "annotation-xml":
      case "color-profile":
      case "font-face":
      case "font-face-src":
      case "font-face-uri":
      case "font-face-format":
      case "font-face-name":
      case "missing-glyph":
        return !1;
      default:
        return !0;
    }
  }
  var Kw = /* @__PURE__ */ new Map([
    ["acceptCharset", "accept-charset"],
    ["htmlFor", "for"],
    ["httpEquiv", "http-equiv"],
    ["crossOrigin", "crossorigin"],
    ["accentHeight", "accent-height"],
    ["alignmentBaseline", "alignment-baseline"],
    ["arabicForm", "arabic-form"],
    ["baselineShift", "baseline-shift"],
    ["capHeight", "cap-height"],
    ["clipPath", "clip-path"],
    ["clipRule", "clip-rule"],
    ["colorInterpolation", "color-interpolation"],
    ["colorInterpolationFilters", "color-interpolation-filters"],
    ["colorProfile", "color-profile"],
    ["colorRendering", "color-rendering"],
    ["dominantBaseline", "dominant-baseline"],
    ["enableBackground", "enable-background"],
    ["fillOpacity", "fill-opacity"],
    ["fillRule", "fill-rule"],
    ["floodColor", "flood-color"],
    ["floodOpacity", "flood-opacity"],
    ["fontFamily", "font-family"],
    ["fontSize", "font-size"],
    ["fontSizeAdjust", "font-size-adjust"],
    ["fontStretch", "font-stretch"],
    ["fontStyle", "font-style"],
    ["fontVariant", "font-variant"],
    ["fontWeight", "font-weight"],
    ["glyphName", "glyph-name"],
    ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
    ["glyphOrientationVertical", "glyph-orientation-vertical"],
    ["horizAdvX", "horiz-adv-x"],
    ["horizOriginX", "horiz-origin-x"],
    ["imageRendering", "image-rendering"],
    ["letterSpacing", "letter-spacing"],
    ["lightingColor", "lighting-color"],
    ["markerEnd", "marker-end"],
    ["markerMid", "marker-mid"],
    ["markerStart", "marker-start"],
    ["overlinePosition", "overline-position"],
    ["overlineThickness", "overline-thickness"],
    ["paintOrder", "paint-order"],
    ["panose-1", "panose-1"],
    ["pointerEvents", "pointer-events"],
    ["renderingIntent", "rendering-intent"],
    ["shapeRendering", "shape-rendering"],
    ["stopColor", "stop-color"],
    ["stopOpacity", "stop-opacity"],
    ["strikethroughPosition", "strikethrough-position"],
    ["strikethroughThickness", "strikethrough-thickness"],
    ["strokeDasharray", "stroke-dasharray"],
    ["strokeDashoffset", "stroke-dashoffset"],
    ["strokeLinecap", "stroke-linecap"],
    ["strokeLinejoin", "stroke-linejoin"],
    ["strokeMiterlimit", "stroke-miterlimit"],
    ["strokeOpacity", "stroke-opacity"],
    ["strokeWidth", "stroke-width"],
    ["textAnchor", "text-anchor"],
    ["textDecoration", "text-decoration"],
    ["textRendering", "text-rendering"],
    ["transformOrigin", "transform-origin"],
    ["underlinePosition", "underline-position"],
    ["underlineThickness", "underline-thickness"],
    ["unicodeBidi", "unicode-bidi"],
    ["unicodeRange", "unicode-range"],
    ["unitsPerEm", "units-per-em"],
    ["vAlphabetic", "v-alphabetic"],
    ["vHanging", "v-hanging"],
    ["vIdeographic", "v-ideographic"],
    ["vMathematical", "v-mathematical"],
    ["vectorEffect", "vector-effect"],
    ["vertAdvY", "vert-adv-y"],
    ["vertOriginX", "vert-origin-x"],
    ["vertOriginY", "vert-origin-y"],
    ["wordSpacing", "word-spacing"],
    ["writingMode", "writing-mode"],
    ["xmlnsXlink", "xmlns:xlink"],
    ["xHeight", "x-height"]
  ]), Qw = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
  function cu(i) {
    return Qw.test("" + i) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : i;
  }
  function Ps() {
  }
  var fh = null;
  function dh(i) {
    return i = i.target || i.srcElement || window, i.correspondingUseElement && (i = i.correspondingUseElement), i.nodeType === 3 ? i.parentNode : i;
  }
  var to = null, eo = null;
  function Tv(i) {
    var r = us(i);
    if (r && (i = r.stateNode)) {
      var l = i[hn] || null;
      t: switch (i = r.stateNode, r.type) {
        case "input":
          if (Dn(
            i,
            l.value,
            l.defaultValue,
            l.defaultValue,
            l.checked,
            l.defaultChecked,
            l.type,
            l.name
          ), r = l.name, l.type === "radio" && r != null) {
            for (l = i; l.parentNode; ) l = l.parentNode;
            for (l = l.querySelectorAll(
              'input[name="' + he(
                "" + r
              ) + '"][type="radio"]'
            ), r = 0; r < l.length; r++) {
              var f = l[r];
              if (f !== i && f.form === i.form) {
                var v = f[hn] || null;
                if (!v) throw Error(s(90));
                Dn(
                  f,
                  v.value,
                  v.defaultValue,
                  v.defaultValue,
                  v.checked,
                  v.defaultChecked,
                  v.type,
                  v.name
                );
              }
            }
            for (r = 0; r < l.length; r++)
              f = l[r], f.form === i.form && pn(f);
          }
          break t;
        case "textarea":
          Ge(i, l.value, l.defaultValue);
          break t;
        case "select":
          r = l.value, r != null && qn(i, !!l.multiple, r, !1);
      }
    }
  }
  var hh = !1;
  function Cv(i, r, l) {
    if (hh) return i(r, l);
    hh = !0;
    try {
      var f = i(r);
      return f;
    } finally {
      if (hh = !1, (to !== null || eo !== null) && ($u(), to && (r = to, i = eo, eo = to = null, Tv(r), i)))
        for (r = 0; r < i.length; r++) Tv(i[r]);
    }
  }
  function El(i, r) {
    var l = i.stateNode;
    if (l === null) return null;
    var f = l[hn] || null;
    if (f === null) return null;
    l = f[r];
    t: switch (r) {
      case "onClick":
      case "onClickCapture":
      case "onDoubleClick":
      case "onDoubleClickCapture":
      case "onMouseDown":
      case "onMouseDownCapture":
      case "onMouseMove":
      case "onMouseMoveCapture":
      case "onMouseUp":
      case "onMouseUpCapture":
      case "onMouseEnter":
        (f = !f.disabled) || (i = i.type, f = !(i === "button" || i === "input" || i === "select" || i === "textarea")), i = !f;
        break t;
      default:
        i = !1;
    }
    if (i) return null;
    if (l && typeof l != "function")
      throw Error(
        s(231, r, typeof l)
      );
    return l;
  }
  var Is = !(typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u"), ph = !1;
  if (Is)
    try {
      var wl = {};
      Object.defineProperty(wl, "passive", {
        get: function() {
          ph = !0;
        }
      }), window.addEventListener("test", wl, wl), window.removeEventListener("test", wl, wl);
    } catch {
      ph = !1;
    }
  var Sr = null, mh = null, uu = null;
  function Rv() {
    if (uu) return uu;
    var i, r = mh, l = r.length, f, v = "value" in Sr ? Sr.value : Sr.textContent, S = v.length;
    for (i = 0; i < l && r[i] === v[i]; i++) ;
    var P = l - i;
    for (f = 1; f <= P && r[l - f] === v[S - f]; f++) ;
    return uu = v.slice(i, 1 < f ? 1 - f : void 0);
  }
  function fu(i) {
    var r = i.keyCode;
    return "charCode" in i ? (i = i.charCode, i === 0 && r === 13 && (i = 13)) : i = r, i === 10 && (i = 13), 32 <= i || i === 13 ? i : 0;
  }
  function du() {
    return !0;
  }
  function Dv() {
    return !1;
  }
  function ri(i) {
    function r(l, f, v, S, P) {
      this._reactName = l, this._targetInst = v, this.type = f, this.nativeEvent = S, this.target = P, this.currentTarget = null;
      for (var q in i)
        i.hasOwnProperty(q) && (l = i[q], this[q] = l ? l(S) : S[q]);
      return this.isDefaultPrevented = (S.defaultPrevented != null ? S.defaultPrevented : S.returnValue === !1) ? du : Dv, this.isPropagationStopped = Dv, this;
    }
    return p(r.prototype, {
      preventDefault: function() {
        this.defaultPrevented = !0;
        var l = this.nativeEvent;
        l && (l.preventDefault ? l.preventDefault() : typeof l.returnValue != "unknown" && (l.returnValue = !1), this.isDefaultPrevented = du);
      },
      stopPropagation: function() {
        var l = this.nativeEvent;
        l && (l.stopPropagation ? l.stopPropagation() : typeof l.cancelBubble != "unknown" && (l.cancelBubble = !0), this.isPropagationStopped = du);
      },
      persist: function() {
      },
      isPersistent: du
    }), r;
  }
  var ua = {
    eventPhase: 0,
    bubbles: 0,
    cancelable: 0,
    timeStamp: function(i) {
      return i.timeStamp || Date.now();
    },
    defaultPrevented: 0,
    isTrusted: 0
  }, hu = ri(ua), Al = p({}, ua, { view: 0, detail: 0 }), Jw = ri(Al), gh, vh, Tl, pu = p({}, Al, {
    screenX: 0,
    screenY: 0,
    clientX: 0,
    clientY: 0,
    pageX: 0,
    pageY: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    getModifierState: yh,
    button: 0,
    buttons: 0,
    relatedTarget: function(i) {
      return i.relatedTarget === void 0 ? i.fromElement === i.srcElement ? i.toElement : i.fromElement : i.relatedTarget;
    },
    movementX: function(i) {
      return "movementX" in i ? i.movementX : (i !== Tl && (Tl && i.type === "mousemove" ? (gh = i.screenX - Tl.screenX, vh = i.screenY - Tl.screenY) : vh = gh = 0, Tl = i), gh);
    },
    movementY: function(i) {
      return "movementY" in i ? i.movementY : vh;
    }
  }), Nv = ri(pu), tA = p({}, pu, { dataTransfer: 0 }), eA = ri(tA), nA = p({}, Al, { relatedTarget: 0 }), _h = ri(nA), iA = p({}, ua, {
    animationName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  }), sA = ri(iA), rA = p({}, ua, {
    clipboardData: function(i) {
      return "clipboardData" in i ? i.clipboardData : window.clipboardData;
    }
  }), aA = ri(rA), oA = p({}, ua, { data: 0 }), Ov = ri(oA), lA = {
    Esc: "Escape",
    Spacebar: " ",
    Left: "ArrowLeft",
    Up: "ArrowUp",
    Right: "ArrowRight",
    Down: "ArrowDown",
    Del: "Delete",
    Win: "OS",
    Menu: "ContextMenu",
    Apps: "ContextMenu",
    Scroll: "ScrollLock",
    MozPrintableKey: "Unidentified"
  }, cA = {
    8: "Backspace",
    9: "Tab",
    12: "Clear",
    13: "Enter",
    16: "Shift",
    17: "Control",
    18: "Alt",
    19: "Pause",
    20: "CapsLock",
    27: "Escape",
    32: " ",
    33: "PageUp",
    34: "PageDown",
    35: "End",
    36: "Home",
    37: "ArrowLeft",
    38: "ArrowUp",
    39: "ArrowRight",
    40: "ArrowDown",
    45: "Insert",
    46: "Delete",
    112: "F1",
    113: "F2",
    114: "F3",
    115: "F4",
    116: "F5",
    117: "F6",
    118: "F7",
    119: "F8",
    120: "F9",
    121: "F10",
    122: "F11",
    123: "F12",
    144: "NumLock",
    145: "ScrollLock",
    224: "Meta"
  }, uA = {
    Alt: "altKey",
    Control: "ctrlKey",
    Meta: "metaKey",
    Shift: "shiftKey"
  };
  function fA(i) {
    var r = this.nativeEvent;
    return r.getModifierState ? r.getModifierState(i) : (i = uA[i]) ? !!r[i] : !1;
  }
  function yh() {
    return fA;
  }
  var dA = p({}, Al, {
    key: function(i) {
      if (i.key) {
        var r = lA[i.key] || i.key;
        if (r !== "Unidentified") return r;
      }
      return i.type === "keypress" ? (i = fu(i), i === 13 ? "Enter" : String.fromCharCode(i)) : i.type === "keydown" || i.type === "keyup" ? cA[i.keyCode] || "Unidentified" : "";
    },
    code: 0,
    location: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    repeat: 0,
    locale: 0,
    getModifierState: yh,
    charCode: function(i) {
      return i.type === "keypress" ? fu(i) : 0;
    },
    keyCode: function(i) {
      return i.type === "keydown" || i.type === "keyup" ? i.keyCode : 0;
    },
    which: function(i) {
      return i.type === "keypress" ? fu(i) : i.type === "keydown" || i.type === "keyup" ? i.keyCode : 0;
    }
  }), hA = ri(dA), pA = p({}, pu, {
    pointerId: 0,
    width: 0,
    height: 0,
    pressure: 0,
    tangentialPressure: 0,
    tiltX: 0,
    tiltY: 0,
    twist: 0,
    pointerType: 0,
    isPrimary: 0
  }), Lv = ri(pA), mA = p({}, Al, {
    touches: 0,
    targetTouches: 0,
    changedTouches: 0,
    altKey: 0,
    metaKey: 0,
    ctrlKey: 0,
    shiftKey: 0,
    getModifierState: yh
  }), gA = ri(mA), vA = p({}, ua, {
    propertyName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  }), _A = ri(vA), yA = p({}, pu, {
    deltaX: function(i) {
      return "deltaX" in i ? i.deltaX : "wheelDeltaX" in i ? -i.wheelDeltaX : 0;
    },
    deltaY: function(i) {
      return "deltaY" in i ? i.deltaY : "wheelDeltaY" in i ? -i.wheelDeltaY : "wheelDelta" in i ? -i.wheelDelta : 0;
    },
    deltaZ: 0,
    deltaMode: 0
  }), xA = ri(yA), SA = p({}, ua, {
    newState: 0,
    oldState: 0
  }), bA = ri(SA), MA = [9, 13, 27, 32], xh = Is && "CompositionEvent" in window, Cl = null;
  Is && "documentMode" in document && (Cl = document.documentMode);
  var EA = Is && "TextEvent" in window && !Cl, Uv = Is && (!xh || Cl && 8 < Cl && 11 >= Cl), Pv = " ", Iv = !1;
  function Bv(i, r) {
    switch (i) {
      case "keyup":
        return MA.indexOf(r.keyCode) !== -1;
      case "keydown":
        return r.keyCode !== 229;
      case "keypress":
      case "mousedown":
      case "focusout":
        return !0;
      default:
        return !1;
    }
  }
  function zv(i) {
    return i = i.detail, typeof i == "object" && "data" in i ? i.data : null;
  }
  var no = !1;
  function wA(i, r) {
    switch (i) {
      case "compositionend":
        return zv(r);
      case "keypress":
        return r.which !== 32 ? null : (Iv = !0, Pv);
      case "textInput":
        return i = r.data, i === Pv && Iv ? null : i;
      default:
        return null;
    }
  }
  function AA(i, r) {
    if (no)
      return i === "compositionend" || !xh && Bv(i, r) ? (i = Rv(), uu = mh = Sr = null, no = !1, i) : null;
    switch (i) {
      case "paste":
        return null;
      case "keypress":
        if (!(r.ctrlKey || r.altKey || r.metaKey) || r.ctrlKey && r.altKey) {
          if (r.char && 1 < r.char.length)
            return r.char;
          if (r.which) return String.fromCharCode(r.which);
        }
        return null;
      case "compositionend":
        return Uv && r.locale !== "ko" ? null : r.data;
      default:
        return null;
    }
  }
  var TA = {
    color: !0,
    date: !0,
    datetime: !0,
    "datetime-local": !0,
    email: !0,
    month: !0,
    number: !0,
    password: !0,
    range: !0,
    search: !0,
    tel: !0,
    text: !0,
    time: !0,
    url: !0,
    week: !0
  };
  function Fv(i) {
    var r = i && i.nodeName && i.nodeName.toLowerCase();
    return r === "input" ? !!TA[i.type] : r === "textarea";
  }
  function Hv(i, r, l, f) {
    to ? eo ? eo.push(f) : eo = [f] : to = f, r = sf(r, "onChange"), 0 < r.length && (l = new hu(
      "onChange",
      "change",
      null,
      l,
      f
    ), i.push({ event: l, listeners: r }));
  }
  var Rl = null, Dl = null;
  function CA(i) {
    bx(i, 0);
  }
  function mu(i) {
    var r = fs(i);
    if (pn(r)) return i;
  }
  function Vv(i, r) {
    if (i === "change") return r;
  }
  var Gv = !1;
  if (Is) {
    var Sh;
    if (Is) {
      var bh = "oninput" in document;
      if (!bh) {
        var kv = document.createElement("div");
        kv.setAttribute("oninput", "return;"), bh = typeof kv.oninput == "function";
      }
      Sh = bh;
    } else Sh = !1;
    Gv = Sh && (!document.documentMode || 9 < document.documentMode);
  }
  function Xv() {
    Rl && (Rl.detachEvent("onpropertychange", Wv), Dl = Rl = null);
  }
  function Wv(i) {
    if (i.propertyName === "value" && mu(Dl)) {
      var r = [];
      Hv(
        r,
        Dl,
        i,
        dh(i)
      ), Cv(CA, r);
    }
  }
  function RA(i, r, l) {
    i === "focusin" ? (Xv(), Rl = r, Dl = l, Rl.attachEvent("onpropertychange", Wv)) : i === "focusout" && Xv();
  }
  function DA(i) {
    if (i === "selectionchange" || i === "keyup" || i === "keydown")
      return mu(Dl);
  }
  function NA(i, r) {
    if (i === "click") return mu(r);
  }
  function OA(i, r) {
    if (i === "input" || i === "change")
      return mu(r);
  }
  function LA(i, r) {
    return i === r && (i !== 0 || 1 / i === 1 / r) || i !== i && r !== r;
  }
  var _i = typeof Object.is == "function" ? Object.is : LA;
  function Nl(i, r) {
    if (_i(i, r)) return !0;
    if (typeof i != "object" || i === null || typeof r != "object" || r === null)
      return !1;
    var l = Object.keys(i), f = Object.keys(r);
    if (l.length !== f.length) return !1;
    for (f = 0; f < l.length; f++) {
      var v = l[f];
      if (!Ue.call(r, v) || !_i(i[v], r[v]))
        return !1;
    }
    return !0;
  }
  function Yv(i) {
    for (; i && i.firstChild; ) i = i.firstChild;
    return i;
  }
  function jv(i, r) {
    var l = Yv(i);
    i = 0;
    for (var f; l; ) {
      if (l.nodeType === 3) {
        if (f = i + l.textContent.length, i <= r && f >= r)
          return { node: l, offset: r - i };
        i = f;
      }
      t: {
        for (; l; ) {
          if (l.nextSibling) {
            l = l.nextSibling;
            break t;
          }
          l = l.parentNode;
        }
        l = void 0;
      }
      l = Yv(l);
    }
  }
  function qv(i, r) {
    return i && r ? i === r ? !0 : i && i.nodeType === 3 ? !1 : r && r.nodeType === 3 ? qv(i, r.parentNode) : "contains" in i ? i.contains(r) : i.compareDocumentPosition ? !!(i.compareDocumentPosition(r) & 16) : !1 : !1;
  }
  function Zv(i) {
    i = i != null && i.ownerDocument != null && i.ownerDocument.defaultView != null ? i.ownerDocument.defaultView : window;
    for (var r = Qt(i.document); r instanceof i.HTMLIFrameElement; ) {
      try {
        var l = typeof r.contentWindow.location.href == "string";
      } catch {
        l = !1;
      }
      if (l) i = r.contentWindow;
      else break;
      r = Qt(i.document);
    }
    return r;
  }
  function Mh(i) {
    var r = i && i.nodeName && i.nodeName.toLowerCase();
    return r && (r === "input" && (i.type === "text" || i.type === "search" || i.type === "tel" || i.type === "url" || i.type === "password") || r === "textarea" || i.contentEditable === "true");
  }
  var UA = Is && "documentMode" in document && 11 >= document.documentMode, io = null, Eh = null, Ol = null, wh = !1;
  function $v(i, r, l) {
    var f = l.window === l ? l.document : l.nodeType === 9 ? l : l.ownerDocument;
    wh || io == null || io !== Qt(f) || (f = io, "selectionStart" in f && Mh(f) ? f = { start: f.selectionStart, end: f.selectionEnd } : (f = (f.ownerDocument && f.ownerDocument.defaultView || window).getSelection(), f = {
      anchorNode: f.anchorNode,
      anchorOffset: f.anchorOffset,
      focusNode: f.focusNode,
      focusOffset: f.focusOffset
    }), Ol && Nl(Ol, f) || (Ol = f, f = sf(Eh, "onSelect"), 0 < f.length && (r = new hu(
      "onSelect",
      "select",
      null,
      r,
      l
    ), i.push({ event: r, listeners: f }), r.target = io)));
  }
  function fa(i, r) {
    var l = {};
    return l[i.toLowerCase()] = r.toLowerCase(), l["Webkit" + i] = "webkit" + r, l["Moz" + i] = "moz" + r, l;
  }
  var so = {
    animationend: fa("Animation", "AnimationEnd"),
    animationiteration: fa("Animation", "AnimationIteration"),
    animationstart: fa("Animation", "AnimationStart"),
    transitionrun: fa("Transition", "TransitionRun"),
    transitionstart: fa("Transition", "TransitionStart"),
    transitioncancel: fa("Transition", "TransitionCancel"),
    transitionend: fa("Transition", "TransitionEnd")
  }, Ah = {}, Kv = {};
  Is && (Kv = document.createElement("div").style, "AnimationEvent" in window || (delete so.animationend.animation, delete so.animationiteration.animation, delete so.animationstart.animation), "TransitionEvent" in window || delete so.transitionend.transition);
  function da(i) {
    if (Ah[i]) return Ah[i];
    if (!so[i]) return i;
    var r = so[i], l;
    for (l in r)
      if (r.hasOwnProperty(l) && l in Kv)
        return Ah[i] = r[l];
    return i;
  }
  var Qv = da("animationend"), Jv = da("animationiteration"), t_ = da("animationstart"), PA = da("transitionrun"), IA = da("transitionstart"), BA = da("transitioncancel"), e_ = da("transitionend"), n_ = /* @__PURE__ */ new Map(), Th = "abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(
    " "
  );
  Th.push("scrollEnd");
  function qi(i, r) {
    n_.set(i, r), ft(r, [i]);
  }
  var gu = typeof reportError == "function" ? reportError : function(i) {
    if (typeof window == "object" && typeof window.ErrorEvent == "function") {
      var r = new window.ErrorEvent("error", {
        bubbles: !0,
        cancelable: !0,
        message: typeof i == "object" && i !== null && typeof i.message == "string" ? String(i.message) : String(i),
        error: i
      });
      if (!window.dispatchEvent(r)) return;
    } else if (typeof process == "object" && typeof process.emit == "function") {
      process.emit("uncaughtException", i);
      return;
    }
    console.error(i);
  }, Pi = [], ro = 0, Ch = 0;
  function vu() {
    for (var i = ro, r = Ch = ro = 0; r < i; ) {
      var l = Pi[r];
      Pi[r++] = null;
      var f = Pi[r];
      Pi[r++] = null;
      var v = Pi[r];
      Pi[r++] = null;
      var S = Pi[r];
      if (Pi[r++] = null, f !== null && v !== null) {
        var P = f.pending;
        P === null ? v.next = v : (v.next = P.next, P.next = v), f.pending = v;
      }
      S !== 0 && i_(l, v, S);
    }
  }
  function _u(i, r, l, f) {
    Pi[ro++] = i, Pi[ro++] = r, Pi[ro++] = l, Pi[ro++] = f, Ch |= f, i.lanes |= f, i = i.alternate, i !== null && (i.lanes |= f);
  }
  function Rh(i, r, l, f) {
    return _u(i, r, l, f), yu(i);
  }
  function ha(i, r) {
    return _u(i, null, null, r), yu(i);
  }
  function i_(i, r, l) {
    i.lanes |= l;
    var f = i.alternate;
    f !== null && (f.lanes |= l);
    for (var v = !1, S = i.return; S !== null; )
      S.childLanes |= l, f = S.alternate, f !== null && (f.childLanes |= l), S.tag === 22 && (i = S.stateNode, i === null || i._visibility & 1 || (v = !0)), i = S, S = S.return;
    return i.tag === 3 ? (S = i.stateNode, v && r !== null && (v = 31 - kt(l), i = S.hiddenUpdates, f = i[v], f === null ? i[v] = [r] : f.push(r), r.lane = l | 536870912), S) : null;
  }
  function yu(i) {
    if (50 < tc)
      throw tc = 0, zp = null, Error(s(185));
    for (var r = i.return; r !== null; )
      i = r, r = i.return;
    return i.tag === 3 ? i.stateNode : null;
  }
  var ao = {};
  function zA(i, r, l, f) {
    this.tag = i, this.key = l, this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null, this.index = 0, this.refCleanup = this.ref = null, this.pendingProps = r, this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null, this.mode = f, this.subtreeFlags = this.flags = 0, this.deletions = null, this.childLanes = this.lanes = 0, this.alternate = null;
  }
  function yi(i, r, l, f) {
    return new zA(i, r, l, f);
  }
  function Dh(i) {
    return i = i.prototype, !(!i || !i.isReactComponent);
  }
  function Bs(i, r) {
    var l = i.alternate;
    return l === null ? (l = yi(
      i.tag,
      r,
      i.key,
      i.mode
    ), l.elementType = i.elementType, l.type = i.type, l.stateNode = i.stateNode, l.alternate = i, i.alternate = l) : (l.pendingProps = r, l.type = i.type, l.flags = 0, l.subtreeFlags = 0, l.deletions = null), l.flags = i.flags & 65011712, l.childLanes = i.childLanes, l.lanes = i.lanes, l.child = i.child, l.memoizedProps = i.memoizedProps, l.memoizedState = i.memoizedState, l.updateQueue = i.updateQueue, r = i.dependencies, l.dependencies = r === null ? null : { lanes: r.lanes, firstContext: r.firstContext }, l.sibling = i.sibling, l.index = i.index, l.ref = i.ref, l.refCleanup = i.refCleanup, l;
  }
  function s_(i, r) {
    i.flags &= 65011714;
    var l = i.alternate;
    return l === null ? (i.childLanes = 0, i.lanes = r, i.child = null, i.subtreeFlags = 0, i.memoizedProps = null, i.memoizedState = null, i.updateQueue = null, i.dependencies = null, i.stateNode = null) : (i.childLanes = l.childLanes, i.lanes = l.lanes, i.child = l.child, i.subtreeFlags = 0, i.deletions = null, i.memoizedProps = l.memoizedProps, i.memoizedState = l.memoizedState, i.updateQueue = l.updateQueue, i.type = l.type, r = l.dependencies, i.dependencies = r === null ? null : {
      lanes: r.lanes,
      firstContext: r.firstContext
    }), i;
  }
  function xu(i, r, l, f, v, S) {
    var P = 0;
    if (f = i, typeof i == "function") Dh(i) && (P = 1);
    else if (typeof i == "string")
      P = kT(
        i,
        l,
        $.current
      ) ? 26 : i === "html" || i === "head" || i === "body" ? 27 : 5;
    else
      t: switch (i) {
        case L:
          return i = yi(31, l, r, v), i.elementType = L, i.lanes = S, i;
        case A:
          return pa(l.children, v, S, r);
        case b:
          P = 8, v |= 24;
          break;
        case y:
          return i = yi(12, l, r, v | 2), i.elementType = y, i.lanes = S, i;
        case O:
          return i = yi(13, l, r, v), i.elementType = O, i.lanes = S, i;
        case C:
          return i = yi(19, l, r, v), i.elementType = C, i.lanes = S, i;
        default:
          if (typeof i == "object" && i !== null)
            switch (i.$$typeof) {
              case w:
                P = 10;
                break t;
              case E:
                P = 9;
                break t;
              case M:
                P = 11;
                break t;
              case D:
                P = 14;
                break t;
              case T:
                P = 16, f = null;
                break t;
            }
          P = 29, l = Error(
            s(130, i === null ? "null" : typeof i, "")
          ), f = null;
      }
    return r = yi(P, l, r, v), r.elementType = i, r.type = f, r.lanes = S, r;
  }
  function pa(i, r, l, f) {
    return i = yi(7, i, f, r), i.lanes = l, i;
  }
  function Nh(i, r, l) {
    return i = yi(6, i, null, r), i.lanes = l, i;
  }
  function r_(i) {
    var r = yi(18, null, null, 0);
    return r.stateNode = i, r;
  }
  function Oh(i, r, l) {
    return r = yi(
      4,
      i.children !== null ? i.children : [],
      i.key,
      r
    ), r.lanes = l, r.stateNode = {
      containerInfo: i.containerInfo,
      pendingChildren: null,
      implementation: i.implementation
    }, r;
  }
  var a_ = /* @__PURE__ */ new WeakMap();
  function Ii(i, r) {
    if (typeof i == "object" && i !== null) {
      var l = a_.get(i);
      return l !== void 0 ? l : (r = {
        value: i,
        source: r,
        stack: it(r)
      }, a_.set(i, r), r);
    }
    return {
      value: i,
      source: r,
      stack: it(r)
    };
  }
  var oo = [], lo = 0, Su = null, Ll = 0, Bi = [], zi = 0, br = null, ds = 1, hs = "";
  function zs(i, r) {
    oo[lo++] = Ll, oo[lo++] = Su, Su = i, Ll = r;
  }
  function o_(i, r, l) {
    Bi[zi++] = ds, Bi[zi++] = hs, Bi[zi++] = br, br = i;
    var f = ds;
    i = hs;
    var v = 32 - kt(f) - 1;
    f &= ~(1 << v), l += 1;
    var S = 32 - kt(r) + v;
    if (30 < S) {
      var P = v - v % 5;
      S = (f & (1 << P) - 1).toString(32), f >>= P, v -= P, ds = 1 << 32 - kt(r) + v | l << v | f, hs = S + i;
    } else
      ds = 1 << S | l << v | f, hs = i;
  }
  function Lh(i) {
    i.return !== null && (zs(i, 1), o_(i, 1, 0));
  }
  function Uh(i) {
    for (; i === Su; )
      Su = oo[--lo], oo[lo] = null, Ll = oo[--lo], oo[lo] = null;
    for (; i === br; )
      br = Bi[--zi], Bi[zi] = null, hs = Bi[--zi], Bi[zi] = null, ds = Bi[--zi], Bi[zi] = null;
  }
  function l_(i, r) {
    Bi[zi++] = ds, Bi[zi++] = hs, Bi[zi++] = br, ds = r.id, hs = r.overflow, br = i;
  }
  var Vn = null, sn = null, Le = !1, Mr = null, Fi = !1, Ph = Error(s(519));
  function Er(i) {
    var r = Error(
      s(
        418,
        1 < arguments.length && arguments[1] !== void 0 && arguments[1] ? "text" : "HTML",
        ""
      )
    );
    throw Ul(Ii(r, i)), Ph;
  }
  function c_(i) {
    var r = i.stateNode, l = i.type, f = i.memoizedProps;
    switch (r[cn] = i, r[hn] = f, l) {
      case "dialog":
        Ce("cancel", r), Ce("close", r);
        break;
      case "iframe":
      case "object":
      case "embed":
        Ce("load", r);
        break;
      case "video":
      case "audio":
        for (l = 0; l < nc.length; l++)
          Ce(nc[l], r);
        break;
      case "source":
        Ce("error", r);
        break;
      case "img":
      case "image":
      case "link":
        Ce("error", r), Ce("load", r);
        break;
      case "details":
        Ce("toggle", r);
        break;
      case "input":
        Ce("invalid", r), ti(
          r,
          f.value,
          f.defaultValue,
          f.checked,
          f.defaultChecked,
          f.type,
          f.name,
          !0
        );
        break;
      case "select":
        Ce("invalid", r);
        break;
      case "textarea":
        Ce("invalid", r), yn(r, f.value, f.defaultValue, f.children);
    }
    l = f.children, typeof l != "string" && typeof l != "number" && typeof l != "bigint" || r.textContent === "" + l || f.suppressHydrationWarning === !0 || Ax(r.textContent, l) ? (f.popover != null && (Ce("beforetoggle", r), Ce("toggle", r)), f.onScroll != null && Ce("scroll", r), f.onScrollEnd != null && Ce("scrollend", r), f.onClick != null && (r.onclick = Ps), r = !0) : r = !1, r || Er(i, !0);
  }
  function u_(i) {
    for (Vn = i.return; Vn; )
      switch (Vn.tag) {
        case 5:
        case 31:
        case 13:
          Fi = !1;
          return;
        case 27:
        case 3:
          Fi = !0;
          return;
        default:
          Vn = Vn.return;
      }
  }
  function co(i) {
    if (i !== Vn) return !1;
    if (!Le) return u_(i), Le = !0, !1;
    var r = i.tag, l;
    if ((l = r !== 3 && r !== 27) && ((l = r === 5) && (l = i.type, l = !(l !== "form" && l !== "button") || Jp(i.type, i.memoizedProps)), l = !l), l && sn && Er(i), u_(i), r === 13) {
      if (i = i.memoizedState, i = i !== null ? i.dehydrated : null, !i) throw Error(s(317));
      sn = Px(i);
    } else if (r === 31) {
      if (i = i.memoizedState, i = i !== null ? i.dehydrated : null, !i) throw Error(s(317));
      sn = Px(i);
    } else
      r === 27 ? (r = sn, zr(i.type) ? (i = sm, sm = null, sn = i) : sn = r) : sn = Vn ? Vi(i.stateNode.nextSibling) : null;
    return !0;
  }
  function ma() {
    sn = Vn = null, Le = !1;
  }
  function Ih() {
    var i = Mr;
    return i !== null && (ci === null ? ci = i : ci.push.apply(
      ci,
      i
    ), Mr = null), i;
  }
  function Ul(i) {
    Mr === null ? Mr = [i] : Mr.push(i);
  }
  var Bh = F(null), ga = null, Fs = null;
  function wr(i, r, l) {
    et(Bh, r._currentValue), r._currentValue = l;
  }
  function Hs(i) {
    i._currentValue = Bh.current, W(Bh);
  }
  function zh(i, r, l) {
    for (; i !== null; ) {
      var f = i.alternate;
      if ((i.childLanes & r) !== r ? (i.childLanes |= r, f !== null && (f.childLanes |= r)) : f !== null && (f.childLanes & r) !== r && (f.childLanes |= r), i === l) break;
      i = i.return;
    }
  }
  function Fh(i, r, l, f) {
    var v = i.child;
    for (v !== null && (v.return = i); v !== null; ) {
      var S = v.dependencies;
      if (S !== null) {
        var P = v.child;
        S = S.firstContext;
        t: for (; S !== null; ) {
          var q = S;
          S = v;
          for (var nt = 0; nt < r.length; nt++)
            if (q.context === r[nt]) {
              S.lanes |= l, q = S.alternate, q !== null && (q.lanes |= l), zh(
                S.return,
                l,
                i
              ), f || (P = null);
              break t;
            }
          S = q.next;
        }
      } else if (v.tag === 18) {
        if (P = v.return, P === null) throw Error(s(341));
        P.lanes |= l, S = P.alternate, S !== null && (S.lanes |= l), zh(P, l, i), P = null;
      } else P = v.child;
      if (P !== null) P.return = v;
      else
        for (P = v; P !== null; ) {
          if (P === i) {
            P = null;
            break;
          }
          if (v = P.sibling, v !== null) {
            v.return = P.return, P = v;
            break;
          }
          P = P.return;
        }
      v = P;
    }
  }
  function uo(i, r, l, f) {
    i = null;
    for (var v = r, S = !1; v !== null; ) {
      if (!S) {
        if ((v.flags & 524288) !== 0) S = !0;
        else if ((v.flags & 262144) !== 0) break;
      }
      if (v.tag === 10) {
        var P = v.alternate;
        if (P === null) throw Error(s(387));
        if (P = P.memoizedProps, P !== null) {
          var q = v.type;
          _i(v.pendingProps.value, P.value) || (i !== null ? i.push(q) : i = [q]);
        }
      } else if (v === K.current) {
        if (P = v.alternate, P === null) throw Error(s(387));
        P.memoizedState.memoizedState !== v.memoizedState.memoizedState && (i !== null ? i.push(oc) : i = [oc]);
      }
      v = v.return;
    }
    i !== null && Fh(
      r,
      i,
      l,
      f
    ), r.flags |= 262144;
  }
  function bu(i) {
    for (i = i.firstContext; i !== null; ) {
      if (!_i(
        i.context._currentValue,
        i.memoizedValue
      ))
        return !0;
      i = i.next;
    }
    return !1;
  }
  function va(i) {
    ga = i, Fs = null, i = i.dependencies, i !== null && (i.firstContext = null);
  }
  function Gn(i) {
    return f_(ga, i);
  }
  function Mu(i, r) {
    return ga === null && va(i), f_(i, r);
  }
  function f_(i, r) {
    var l = r._currentValue;
    if (r = { context: r, memoizedValue: l, next: null }, Fs === null) {
      if (i === null) throw Error(s(308));
      Fs = r, i.dependencies = { lanes: 0, firstContext: r }, i.flags |= 524288;
    } else Fs = Fs.next = r;
    return l;
  }
  var FA = typeof AbortController < "u" ? AbortController : function() {
    var i = [], r = this.signal = {
      aborted: !1,
      addEventListener: function(l, f) {
        i.push(f);
      }
    };
    this.abort = function() {
      r.aborted = !0, i.forEach(function(l) {
        return l();
      });
    };
  }, HA = n.unstable_scheduleCallback, VA = n.unstable_NormalPriority, Sn = {
    $$typeof: w,
    Consumer: null,
    Provider: null,
    _currentValue: null,
    _currentValue2: null,
    _threadCount: 0
  };
  function Hh() {
    return {
      controller: new FA(),
      data: /* @__PURE__ */ new Map(),
      refCount: 0
    };
  }
  function Pl(i) {
    i.refCount--, i.refCount === 0 && HA(VA, function() {
      i.controller.abort();
    });
  }
  var Il = null, Vh = 0, fo = 0, ho = null;
  function GA(i, r) {
    if (Il === null) {
      var l = Il = [];
      Vh = 0, fo = Xp(), ho = {
        status: "pending",
        value: void 0,
        then: function(f) {
          l.push(f);
        }
      };
    }
    return Vh++, r.then(d_, d_), r;
  }
  function d_() {
    if (--Vh === 0 && Il !== null) {
      ho !== null && (ho.status = "fulfilled");
      var i = Il;
      Il = null, fo = 0, ho = null;
      for (var r = 0; r < i.length; r++) (0, i[r])();
    }
  }
  function kA(i, r) {
    var l = [], f = {
      status: "pending",
      value: null,
      reason: null,
      then: function(v) {
        l.push(v);
      }
    };
    return i.then(
      function() {
        f.status = "fulfilled", f.value = r;
        for (var v = 0; v < l.length; v++) (0, l[v])(r);
      },
      function(v) {
        for (f.status = "rejected", f.reason = v, v = 0; v < l.length; v++)
          (0, l[v])(void 0);
      }
    ), f;
  }
  var h_ = N.S;
  N.S = function(i, r) {
    $y = G(), typeof r == "object" && r !== null && typeof r.then == "function" && GA(i, r), h_ !== null && h_(i, r);
  };
  var _a = F(null);
  function Gh() {
    var i = _a.current;
    return i !== null ? i : tn.pooledCache;
  }
  function Eu(i, r) {
    r === null ? et(_a, _a.current) : et(_a, r.pool);
  }
  function p_() {
    var i = Gh();
    return i === null ? null : { parent: Sn._currentValue, pool: i };
  }
  var po = Error(s(460)), kh = Error(s(474)), wu = Error(s(542)), Au = { then: function() {
  } };
  function m_(i) {
    return i = i.status, i === "fulfilled" || i === "rejected";
  }
  function g_(i, r, l) {
    switch (l = i[l], l === void 0 ? i.push(r) : l !== r && (r.then(Ps, Ps), r = l), r.status) {
      case "fulfilled":
        return r.value;
      case "rejected":
        throw i = r.reason, __(i), i;
      default:
        if (typeof r.status == "string") r.then(Ps, Ps);
        else {
          if (i = tn, i !== null && 100 < i.shellSuspendCounter)
            throw Error(s(482));
          i = r, i.status = "pending", i.then(
            function(f) {
              if (r.status === "pending") {
                var v = r;
                v.status = "fulfilled", v.value = f;
              }
            },
            function(f) {
              if (r.status === "pending") {
                var v = r;
                v.status = "rejected", v.reason = f;
              }
            }
          );
        }
        switch (r.status) {
          case "fulfilled":
            return r.value;
          case "rejected":
            throw i = r.reason, __(i), i;
        }
        throw xa = r, po;
    }
  }
  function ya(i) {
    try {
      var r = i._init;
      return r(i._payload);
    } catch (l) {
      throw l !== null && typeof l == "object" && typeof l.then == "function" ? (xa = l, po) : l;
    }
  }
  var xa = null;
  function v_() {
    if (xa === null) throw Error(s(459));
    var i = xa;
    return xa = null, i;
  }
  function __(i) {
    if (i === po || i === wu)
      throw Error(s(483));
  }
  var mo = null, Bl = 0;
  function Tu(i) {
    var r = Bl;
    return Bl += 1, mo === null && (mo = []), g_(mo, i, r);
  }
  function zl(i, r) {
    r = r.props.ref, i.ref = r !== void 0 ? r : null;
  }
  function Cu(i, r) {
    throw r.$$typeof === g ? Error(s(525)) : (i = Object.prototype.toString.call(r), Error(
      s(
        31,
        i === "[object Object]" ? "object with keys {" + Object.keys(r).join(", ") + "}" : i
      )
    ));
  }
  function y_(i) {
    function r(ut, at) {
      if (i) {
        var ht = ut.deletions;
        ht === null ? (ut.deletions = [at], ut.flags |= 16) : ht.push(at);
      }
    }
    function l(ut, at) {
      if (!i) return null;
      for (; at !== null; )
        r(ut, at), at = at.sibling;
      return null;
    }
    function f(ut) {
      for (var at = /* @__PURE__ */ new Map(); ut !== null; )
        ut.key !== null ? at.set(ut.key, ut) : at.set(ut.index, ut), ut = ut.sibling;
      return at;
    }
    function v(ut, at) {
      return ut = Bs(ut, at), ut.index = 0, ut.sibling = null, ut;
    }
    function S(ut, at, ht) {
      return ut.index = ht, i ? (ht = ut.alternate, ht !== null ? (ht = ht.index, ht < at ? (ut.flags |= 67108866, at) : ht) : (ut.flags |= 67108866, at)) : (ut.flags |= 1048576, at);
    }
    function P(ut) {
      return i && ut.alternate === null && (ut.flags |= 67108866), ut;
    }
    function q(ut, at, ht, Tt) {
      return at === null || at.tag !== 6 ? (at = Nh(ht, ut.mode, Tt), at.return = ut, at) : (at = v(at, ht), at.return = ut, at);
    }
    function nt(ut, at, ht, Tt) {
      var re = ht.type;
      return re === A ? wt(
        ut,
        at,
        ht.props.children,
        Tt,
        ht.key
      ) : at !== null && (at.elementType === re || typeof re == "object" && re !== null && re.$$typeof === T && ya(re) === at.type) ? (at = v(at, ht.props), zl(at, ht), at.return = ut, at) : (at = xu(
        ht.type,
        ht.key,
        ht.props,
        null,
        ut.mode,
        Tt
      ), zl(at, ht), at.return = ut, at);
    }
    function pt(ut, at, ht, Tt) {
      return at === null || at.tag !== 4 || at.stateNode.containerInfo !== ht.containerInfo || at.stateNode.implementation !== ht.implementation ? (at = Oh(ht, ut.mode, Tt), at.return = ut, at) : (at = v(at, ht.children || []), at.return = ut, at);
    }
    function wt(ut, at, ht, Tt, re) {
      return at === null || at.tag !== 7 ? (at = pa(
        ht,
        ut.mode,
        Tt,
        re
      ), at.return = ut, at) : (at = v(at, ht), at.return = ut, at);
    }
    function Ct(ut, at, ht) {
      if (typeof at == "string" && at !== "" || typeof at == "number" || typeof at == "bigint")
        return at = Nh(
          "" + at,
          ut.mode,
          ht
        ), at.return = ut, at;
      if (typeof at == "object" && at !== null) {
        switch (at.$$typeof) {
          case _:
            return ht = xu(
              at.type,
              at.key,
              at.props,
              null,
              ut.mode,
              ht
            ), zl(ht, at), ht.return = ut, ht;
          case x:
            return at = Oh(
              at,
              ut.mode,
              ht
            ), at.return = ut, at;
          case T:
            return at = ya(at), Ct(ut, at, ht);
        }
        if (V(at) || B(at))
          return at = pa(
            at,
            ut.mode,
            ht,
            null
          ), at.return = ut, at;
        if (typeof at.then == "function")
          return Ct(ut, Tu(at), ht);
        if (at.$$typeof === w)
          return Ct(
            ut,
            Mu(ut, at),
            ht
          );
        Cu(ut, at);
      }
      return null;
    }
    function gt(ut, at, ht, Tt) {
      var re = at !== null ? at.key : null;
      if (typeof ht == "string" && ht !== "" || typeof ht == "number" || typeof ht == "bigint")
        return re !== null ? null : q(ut, at, "" + ht, Tt);
      if (typeof ht == "object" && ht !== null) {
        switch (ht.$$typeof) {
          case _:
            return ht.key === re ? nt(ut, at, ht, Tt) : null;
          case x:
            return ht.key === re ? pt(ut, at, ht, Tt) : null;
          case T:
            return ht = ya(ht), gt(ut, at, ht, Tt);
        }
        if (V(ht) || B(ht))
          return re !== null ? null : wt(ut, at, ht, Tt, null);
        if (typeof ht.then == "function")
          return gt(
            ut,
            at,
            Tu(ht),
            Tt
          );
        if (ht.$$typeof === w)
          return gt(
            ut,
            at,
            Mu(ut, ht),
            Tt
          );
        Cu(ut, ht);
      }
      return null;
    }
    function St(ut, at, ht, Tt, re) {
      if (typeof Tt == "string" && Tt !== "" || typeof Tt == "number" || typeof Tt == "bigint")
        return ut = ut.get(ht) || null, q(at, ut, "" + Tt, re);
      if (typeof Tt == "object" && Tt !== null) {
        switch (Tt.$$typeof) {
          case _:
            return ut = ut.get(
              Tt.key === null ? ht : Tt.key
            ) || null, nt(at, ut, Tt, re);
          case x:
            return ut = ut.get(
              Tt.key === null ? ht : Tt.key
            ) || null, pt(at, ut, Tt, re);
          case T:
            return Tt = ya(Tt), St(
              ut,
              at,
              ht,
              Tt,
              re
            );
        }
        if (V(Tt) || B(Tt))
          return ut = ut.get(ht) || null, wt(at, ut, Tt, re, null);
        if (typeof Tt.then == "function")
          return St(
            ut,
            at,
            ht,
            Tu(Tt),
            re
          );
        if (Tt.$$typeof === w)
          return St(
            ut,
            at,
            ht,
            Mu(at, Tt),
            re
          );
        Cu(at, Tt);
      }
      return null;
    }
    function ee(ut, at, ht, Tt) {
      for (var re = null, ze = null, ie = at, be = at = 0, Ne = null; ie !== null && be < ht.length; be++) {
        ie.index > be ? (Ne = ie, ie = null) : Ne = ie.sibling;
        var Fe = gt(
          ut,
          ie,
          ht[be],
          Tt
        );
        if (Fe === null) {
          ie === null && (ie = Ne);
          break;
        }
        i && ie && Fe.alternate === null && r(ut, ie), at = S(Fe, at, be), ze === null ? re = Fe : ze.sibling = Fe, ze = Fe, ie = Ne;
      }
      if (be === ht.length)
        return l(ut, ie), Le && zs(ut, be), re;
      if (ie === null) {
        for (; be < ht.length; be++)
          ie = Ct(ut, ht[be], Tt), ie !== null && (at = S(
            ie,
            at,
            be
          ), ze === null ? re = ie : ze.sibling = ie, ze = ie);
        return Le && zs(ut, be), re;
      }
      for (ie = f(ie); be < ht.length; be++)
        Ne = St(
          ie,
          ut,
          be,
          ht[be],
          Tt
        ), Ne !== null && (i && Ne.alternate !== null && ie.delete(
          Ne.key === null ? be : Ne.key
        ), at = S(
          Ne,
          at,
          be
        ), ze === null ? re = Ne : ze.sibling = Ne, ze = Ne);
      return i && ie.forEach(function(kr) {
        return r(ut, kr);
      }), Le && zs(ut, be), re;
    }
    function ce(ut, at, ht, Tt) {
      if (ht == null) throw Error(s(151));
      for (var re = null, ze = null, ie = at, be = at = 0, Ne = null, Fe = ht.next(); ie !== null && !Fe.done; be++, Fe = ht.next()) {
        ie.index > be ? (Ne = ie, ie = null) : Ne = ie.sibling;
        var kr = gt(ut, ie, Fe.value, Tt);
        if (kr === null) {
          ie === null && (ie = Ne);
          break;
        }
        i && ie && kr.alternate === null && r(ut, ie), at = S(kr, at, be), ze === null ? re = kr : ze.sibling = kr, ze = kr, ie = Ne;
      }
      if (Fe.done)
        return l(ut, ie), Le && zs(ut, be), re;
      if (ie === null) {
        for (; !Fe.done; be++, Fe = ht.next())
          Fe = Ct(ut, Fe.value, Tt), Fe !== null && (at = S(Fe, at, be), ze === null ? re = Fe : ze.sibling = Fe, ze = Fe);
        return Le && zs(ut, be), re;
      }
      for (ie = f(ie); !Fe.done; be++, Fe = ht.next())
        Fe = St(ie, ut, be, Fe.value, Tt), Fe !== null && (i && Fe.alternate !== null && ie.delete(Fe.key === null ? be : Fe.key), at = S(Fe, at, be), ze === null ? re = Fe : ze.sibling = Fe, ze = Fe);
      return i && ie.forEach(function(t2) {
        return r(ut, t2);
      }), Le && zs(ut, be), re;
    }
    function Ke(ut, at, ht, Tt) {
      if (typeof ht == "object" && ht !== null && ht.type === A && ht.key === null && (ht = ht.props.children), typeof ht == "object" && ht !== null) {
        switch (ht.$$typeof) {
          case _:
            t: {
              for (var re = ht.key; at !== null; ) {
                if (at.key === re) {
                  if (re = ht.type, re === A) {
                    if (at.tag === 7) {
                      l(
                        ut,
                        at.sibling
                      ), Tt = v(
                        at,
                        ht.props.children
                      ), Tt.return = ut, ut = Tt;
                      break t;
                    }
                  } else if (at.elementType === re || typeof re == "object" && re !== null && re.$$typeof === T && ya(re) === at.type) {
                    l(
                      ut,
                      at.sibling
                    ), Tt = v(at, ht.props), zl(Tt, ht), Tt.return = ut, ut = Tt;
                    break t;
                  }
                  l(ut, at);
                  break;
                } else r(ut, at);
                at = at.sibling;
              }
              ht.type === A ? (Tt = pa(
                ht.props.children,
                ut.mode,
                Tt,
                ht.key
              ), Tt.return = ut, ut = Tt) : (Tt = xu(
                ht.type,
                ht.key,
                ht.props,
                null,
                ut.mode,
                Tt
              ), zl(Tt, ht), Tt.return = ut, ut = Tt);
            }
            return P(ut);
          case x:
            t: {
              for (re = ht.key; at !== null; ) {
                if (at.key === re)
                  if (at.tag === 4 && at.stateNode.containerInfo === ht.containerInfo && at.stateNode.implementation === ht.implementation) {
                    l(
                      ut,
                      at.sibling
                    ), Tt = v(at, ht.children || []), Tt.return = ut, ut = Tt;
                    break t;
                  } else {
                    l(ut, at);
                    break;
                  }
                else r(ut, at);
                at = at.sibling;
              }
              Tt = Oh(ht, ut.mode, Tt), Tt.return = ut, ut = Tt;
            }
            return P(ut);
          case T:
            return ht = ya(ht), Ke(
              ut,
              at,
              ht,
              Tt
            );
        }
        if (V(ht))
          return ee(
            ut,
            at,
            ht,
            Tt
          );
        if (B(ht)) {
          if (re = B(ht), typeof re != "function") throw Error(s(150));
          return ht = re.call(ht), ce(
            ut,
            at,
            ht,
            Tt
          );
        }
        if (typeof ht.then == "function")
          return Ke(
            ut,
            at,
            Tu(ht),
            Tt
          );
        if (ht.$$typeof === w)
          return Ke(
            ut,
            at,
            Mu(ut, ht),
            Tt
          );
        Cu(ut, ht);
      }
      return typeof ht == "string" && ht !== "" || typeof ht == "number" || typeof ht == "bigint" ? (ht = "" + ht, at !== null && at.tag === 6 ? (l(ut, at.sibling), Tt = v(at, ht), Tt.return = ut, ut = Tt) : (l(ut, at), Tt = Nh(ht, ut.mode, Tt), Tt.return = ut, ut = Tt), P(ut)) : l(ut, at);
    }
    return function(ut, at, ht, Tt) {
      try {
        Bl = 0;
        var re = Ke(
          ut,
          at,
          ht,
          Tt
        );
        return mo = null, re;
      } catch (ie) {
        if (ie === po || ie === wu) throw ie;
        var ze = yi(29, ie, null, ut.mode);
        return ze.lanes = Tt, ze.return = ut, ze;
      } finally {
      }
    };
  }
  var Sa = y_(!0), x_ = y_(!1), Ar = !1;
  function Xh(i) {
    i.updateQueue = {
      baseState: i.memoizedState,
      firstBaseUpdate: null,
      lastBaseUpdate: null,
      shared: { pending: null, lanes: 0, hiddenCallbacks: null },
      callbacks: null
    };
  }
  function Wh(i, r) {
    i = i.updateQueue, r.updateQueue === i && (r.updateQueue = {
      baseState: i.baseState,
      firstBaseUpdate: i.firstBaseUpdate,
      lastBaseUpdate: i.lastBaseUpdate,
      shared: i.shared,
      callbacks: null
    });
  }
  function Tr(i) {
    return { lane: i, tag: 0, payload: null, callback: null, next: null };
  }
  function Cr(i, r, l) {
    var f = i.updateQueue;
    if (f === null) return null;
    if (f = f.shared, (Ve & 2) !== 0) {
      var v = f.pending;
      return v === null ? r.next = r : (r.next = v.next, v.next = r), f.pending = r, r = yu(i), i_(i, null, l), r;
    }
    return _u(i, f, r, l), yu(i);
  }
  function Fl(i, r, l) {
    if (r = r.updateQueue, r !== null && (r = r.shared, (l & 4194048) !== 0)) {
      var f = r.lanes;
      f &= i.pendingLanes, l |= f, r.lanes = l, vr(i, l);
    }
  }
  function Yh(i, r) {
    var l = i.updateQueue, f = i.alternate;
    if (f !== null && (f = f.updateQueue, l === f)) {
      var v = null, S = null;
      if (l = l.firstBaseUpdate, l !== null) {
        do {
          var P = {
            lane: l.lane,
            tag: l.tag,
            payload: l.payload,
            callback: null,
            next: null
          };
          S === null ? v = S = P : S = S.next = P, l = l.next;
        } while (l !== null);
        S === null ? v = S = r : S = S.next = r;
      } else v = S = r;
      l = {
        baseState: f.baseState,
        firstBaseUpdate: v,
        lastBaseUpdate: S,
        shared: f.shared,
        callbacks: f.callbacks
      }, i.updateQueue = l;
      return;
    }
    i = l.lastBaseUpdate, i === null ? l.firstBaseUpdate = r : i.next = r, l.lastBaseUpdate = r;
  }
  var jh = !1;
  function Hl() {
    if (jh) {
      var i = ho;
      if (i !== null) throw i;
    }
  }
  function Vl(i, r, l, f) {
    jh = !1;
    var v = i.updateQueue;
    Ar = !1;
    var S = v.firstBaseUpdate, P = v.lastBaseUpdate, q = v.shared.pending;
    if (q !== null) {
      v.shared.pending = null;
      var nt = q, pt = nt.next;
      nt.next = null, P === null ? S = pt : P.next = pt, P = nt;
      var wt = i.alternate;
      wt !== null && (wt = wt.updateQueue, q = wt.lastBaseUpdate, q !== P && (q === null ? wt.firstBaseUpdate = pt : q.next = pt, wt.lastBaseUpdate = nt));
    }
    if (S !== null) {
      var Ct = v.baseState;
      P = 0, wt = pt = nt = null, q = S;
      do {
        var gt = q.lane & -536870913, St = gt !== q.lane;
        if (St ? (De & gt) === gt : (f & gt) === gt) {
          gt !== 0 && gt === fo && (jh = !0), wt !== null && (wt = wt.next = {
            lane: 0,
            tag: q.tag,
            payload: q.payload,
            callback: null,
            next: null
          });
          t: {
            var ee = i, ce = q;
            gt = r;
            var Ke = l;
            switch (ce.tag) {
              case 1:
                if (ee = ce.payload, typeof ee == "function") {
                  Ct = ee.call(Ke, Ct, gt);
                  break t;
                }
                Ct = ee;
                break t;
              case 3:
                ee.flags = ee.flags & -65537 | 128;
              case 0:
                if (ee = ce.payload, gt = typeof ee == "function" ? ee.call(Ke, Ct, gt) : ee, gt == null) break t;
                Ct = p({}, Ct, gt);
                break t;
              case 2:
                Ar = !0;
            }
          }
          gt = q.callback, gt !== null && (i.flags |= 64, St && (i.flags |= 8192), St = v.callbacks, St === null ? v.callbacks = [gt] : St.push(gt));
        } else
          St = {
            lane: gt,
            tag: q.tag,
            payload: q.payload,
            callback: q.callback,
            next: null
          }, wt === null ? (pt = wt = St, nt = Ct) : wt = wt.next = St, P |= gt;
        if (q = q.next, q === null) {
          if (q = v.shared.pending, q === null)
            break;
          St = q, q = St.next, St.next = null, v.lastBaseUpdate = St, v.shared.pending = null;
        }
      } while (!0);
      wt === null && (nt = Ct), v.baseState = nt, v.firstBaseUpdate = pt, v.lastBaseUpdate = wt, S === null && (v.shared.lanes = 0), Lr |= P, i.lanes = P, i.memoizedState = Ct;
    }
  }
  function S_(i, r) {
    if (typeof i != "function")
      throw Error(s(191, i));
    i.call(r);
  }
  function b_(i, r) {
    var l = i.callbacks;
    if (l !== null)
      for (i.callbacks = null, i = 0; i < l.length; i++)
        S_(l[i], r);
  }
  var go = F(null), Ru = F(0);
  function M_(i, r) {
    i = Zs, et(Ru, i), et(go, r), Zs = i | r.baseLanes;
  }
  function qh() {
    et(Ru, Zs), et(go, go.current);
  }
  function Zh() {
    Zs = Ru.current, W(go), W(Ru);
  }
  var xi = F(null), Hi = null;
  function Rr(i) {
    var r = i.alternate;
    et(mn, mn.current & 1), et(xi, i), Hi === null && (r === null || go.current !== null || r.memoizedState !== null) && (Hi = i);
  }
  function $h(i) {
    et(mn, mn.current), et(xi, i), Hi === null && (Hi = i);
  }
  function E_(i) {
    i.tag === 22 ? (et(mn, mn.current), et(xi, i), Hi === null && (Hi = i)) : Dr();
  }
  function Dr() {
    et(mn, mn.current), et(xi, xi.current);
  }
  function Si(i) {
    W(xi), Hi === i && (Hi = null), W(mn);
  }
  var mn = F(0);
  function Du(i) {
    for (var r = i; r !== null; ) {
      if (r.tag === 13) {
        var l = r.memoizedState;
        if (l !== null && (l = l.dehydrated, l === null || nm(l) || im(l)))
          return r;
      } else if (r.tag === 19 && (r.memoizedProps.revealOrder === "forwards" || r.memoizedProps.revealOrder === "backwards" || r.memoizedProps.revealOrder === "unstable_legacy-backwards" || r.memoizedProps.revealOrder === "together")) {
        if ((r.flags & 128) !== 0) return r;
      } else if (r.child !== null) {
        r.child.return = r, r = r.child;
        continue;
      }
      if (r === i) break;
      for (; r.sibling === null; ) {
        if (r.return === null || r.return === i) return null;
        r = r.return;
      }
      r.sibling.return = r.return, r = r.sibling;
    }
    return null;
  }
  var Vs = 0, Se = null, Ze = null, bn = null, Nu = !1, vo = !1, ba = !1, Ou = 0, Gl = 0, _o = null, XA = 0;
  function un() {
    throw Error(s(321));
  }
  function Kh(i, r) {
    if (r === null) return !1;
    for (var l = 0; l < r.length && l < i.length; l++)
      if (!_i(i[l], r[l])) return !1;
    return !0;
  }
  function Qh(i, r, l, f, v, S) {
    return Vs = S, Se = r, r.memoizedState = null, r.updateQueue = null, r.lanes = 0, N.H = i === null || i.memoizedState === null ? oy : hp, ba = !1, S = l(f, v), ba = !1, vo && (S = A_(
      r,
      l,
      f,
      v
    )), w_(i), S;
  }
  function w_(i) {
    N.H = Wl;
    var r = Ze !== null && Ze.next !== null;
    if (Vs = 0, bn = Ze = Se = null, Nu = !1, Gl = 0, _o = null, r) throw Error(s(300));
    i === null || Mn || (i = i.dependencies, i !== null && bu(i) && (Mn = !0));
  }
  function A_(i, r, l, f) {
    Se = i;
    var v = 0;
    do {
      if (vo && (_o = null), Gl = 0, vo = !1, 25 <= v) throw Error(s(301));
      if (v += 1, bn = Ze = null, i.updateQueue != null) {
        var S = i.updateQueue;
        S.lastEffect = null, S.events = null, S.stores = null, S.memoCache != null && (S.memoCache.index = 0);
      }
      N.H = ly, S = r(l, f);
    } while (vo);
    return S;
  }
  function WA() {
    var i = N.H, r = i.useState()[0];
    return r = typeof r.then == "function" ? kl(r) : r, i = i.useState()[0], (Ze !== null ? Ze.memoizedState : null) !== i && (Se.flags |= 1024), r;
  }
  function Jh() {
    var i = Ou !== 0;
    return Ou = 0, i;
  }
  function tp(i, r, l) {
    r.updateQueue = i.updateQueue, r.flags &= -2053, i.lanes &= ~l;
  }
  function ep(i) {
    if (Nu) {
      for (i = i.memoizedState; i !== null; ) {
        var r = i.queue;
        r !== null && (r.pending = null), i = i.next;
      }
      Nu = !1;
    }
    Vs = 0, bn = Ze = Se = null, vo = !1, Gl = Ou = 0, _o = null;
  }
  function ni() {
    var i = {
      memoizedState: null,
      baseState: null,
      baseQueue: null,
      queue: null,
      next: null
    };
    return bn === null ? Se.memoizedState = bn = i : bn = bn.next = i, bn;
  }
  function gn() {
    if (Ze === null) {
      var i = Se.alternate;
      i = i !== null ? i.memoizedState : null;
    } else i = Ze.next;
    var r = bn === null ? Se.memoizedState : bn.next;
    if (r !== null)
      bn = r, Ze = i;
    else {
      if (i === null)
        throw Se.alternate === null ? Error(s(467)) : Error(s(310));
      Ze = i, i = {
        memoizedState: Ze.memoizedState,
        baseState: Ze.baseState,
        baseQueue: Ze.baseQueue,
        queue: Ze.queue,
        next: null
      }, bn === null ? Se.memoizedState = bn = i : bn = bn.next = i;
    }
    return bn;
  }
  function Lu() {
    return { lastEffect: null, events: null, stores: null, memoCache: null };
  }
  function kl(i) {
    var r = Gl;
    return Gl += 1, _o === null && (_o = []), i = g_(_o, i, r), r = Se, (bn === null ? r.memoizedState : bn.next) === null && (r = r.alternate, N.H = r === null || r.memoizedState === null ? oy : hp), i;
  }
  function Uu(i) {
    if (i !== null && typeof i == "object") {
      if (typeof i.then == "function") return kl(i);
      if (i.$$typeof === w) return Gn(i);
    }
    throw Error(s(438, String(i)));
  }
  function np(i) {
    var r = null, l = Se.updateQueue;
    if (l !== null && (r = l.memoCache), r == null) {
      var f = Se.alternate;
      f !== null && (f = f.updateQueue, f !== null && (f = f.memoCache, f != null && (r = {
        data: f.data.map(function(v) {
          return v.slice();
        }),
        index: 0
      })));
    }
    if (r == null && (r = { data: [], index: 0 }), l === null && (l = Lu(), Se.updateQueue = l), l.memoCache = r, l = r.data[r.index], l === void 0)
      for (l = r.data[r.index] = Array(i), f = 0; f < i; f++)
        l[f] = z;
    return r.index++, l;
  }
  function Gs(i, r) {
    return typeof r == "function" ? r(i) : r;
  }
  function Pu(i) {
    var r = gn();
    return ip(r, Ze, i);
  }
  function ip(i, r, l) {
    var f = i.queue;
    if (f === null) throw Error(s(311));
    f.lastRenderedReducer = l;
    var v = i.baseQueue, S = f.pending;
    if (S !== null) {
      if (v !== null) {
        var P = v.next;
        v.next = S.next, S.next = P;
      }
      r.baseQueue = v = S, f.pending = null;
    }
    if (S = i.baseState, v === null) i.memoizedState = S;
    else {
      r = v.next;
      var q = P = null, nt = null, pt = r, wt = !1;
      do {
        var Ct = pt.lane & -536870913;
        if (Ct !== pt.lane ? (De & Ct) === Ct : (Vs & Ct) === Ct) {
          var gt = pt.revertLane;
          if (gt === 0)
            nt !== null && (nt = nt.next = {
              lane: 0,
              revertLane: 0,
              gesture: null,
              action: pt.action,
              hasEagerState: pt.hasEagerState,
              eagerState: pt.eagerState,
              next: null
            }), Ct === fo && (wt = !0);
          else if ((Vs & gt) === gt) {
            pt = pt.next, gt === fo && (wt = !0);
            continue;
          } else
            Ct = {
              lane: 0,
              revertLane: pt.revertLane,
              gesture: null,
              action: pt.action,
              hasEagerState: pt.hasEagerState,
              eagerState: pt.eagerState,
              next: null
            }, nt === null ? (q = nt = Ct, P = S) : nt = nt.next = Ct, Se.lanes |= gt, Lr |= gt;
          Ct = pt.action, ba && l(S, Ct), S = pt.hasEagerState ? pt.eagerState : l(S, Ct);
        } else
          gt = {
            lane: Ct,
            revertLane: pt.revertLane,
            gesture: pt.gesture,
            action: pt.action,
            hasEagerState: pt.hasEagerState,
            eagerState: pt.eagerState,
            next: null
          }, nt === null ? (q = nt = gt, P = S) : nt = nt.next = gt, Se.lanes |= Ct, Lr |= Ct;
        pt = pt.next;
      } while (pt !== null && pt !== r);
      if (nt === null ? P = S : nt.next = q, !_i(S, i.memoizedState) && (Mn = !0, wt && (l = ho, l !== null)))
        throw l;
      i.memoizedState = S, i.baseState = P, i.baseQueue = nt, f.lastRenderedState = S;
    }
    return v === null && (f.lanes = 0), [i.memoizedState, f.dispatch];
  }
  function sp(i) {
    var r = gn(), l = r.queue;
    if (l === null) throw Error(s(311));
    l.lastRenderedReducer = i;
    var f = l.dispatch, v = l.pending, S = r.memoizedState;
    if (v !== null) {
      l.pending = null;
      var P = v = v.next;
      do
        S = i(S, P.action), P = P.next;
      while (P !== v);
      _i(S, r.memoizedState) || (Mn = !0), r.memoizedState = S, r.baseQueue === null && (r.baseState = S), l.lastRenderedState = S;
    }
    return [S, f];
  }
  function T_(i, r, l) {
    var f = Se, v = gn(), S = Le;
    if (S) {
      if (l === void 0) throw Error(s(407));
      l = l();
    } else l = r();
    var P = !_i(
      (Ze || v).memoizedState,
      l
    );
    if (P && (v.memoizedState = l, Mn = !0), v = v.queue, op(D_.bind(null, f, v, i), [
      i
    ]), v.getSnapshot !== r || P || bn !== null && bn.memoizedState.tag & 1) {
      if (f.flags |= 2048, yo(
        9,
        { destroy: void 0 },
        R_.bind(
          null,
          f,
          v,
          l,
          r
        ),
        null
      ), tn === null) throw Error(s(349));
      S || (Vs & 127) !== 0 || C_(f, r, l);
    }
    return l;
  }
  function C_(i, r, l) {
    i.flags |= 16384, i = { getSnapshot: r, value: l }, r = Se.updateQueue, r === null ? (r = Lu(), Se.updateQueue = r, r.stores = [i]) : (l = r.stores, l === null ? r.stores = [i] : l.push(i));
  }
  function R_(i, r, l, f) {
    r.value = l, r.getSnapshot = f, N_(r) && O_(i);
  }
  function D_(i, r, l) {
    return l(function() {
      N_(r) && O_(i);
    });
  }
  function N_(i) {
    var r = i.getSnapshot;
    i = i.value;
    try {
      var l = r();
      return !_i(i, l);
    } catch {
      return !0;
    }
  }
  function O_(i) {
    var r = ha(i, 2);
    r !== null && ui(r, i, 2);
  }
  function rp(i) {
    var r = ni();
    if (typeof i == "function") {
      var l = i;
      if (i = l(), ba) {
        Wt(!0);
        try {
          l();
        } finally {
          Wt(!1);
        }
      }
    }
    return r.memoizedState = r.baseState = i, r.queue = {
      pending: null,
      lanes: 0,
      dispatch: null,
      lastRenderedReducer: Gs,
      lastRenderedState: i
    }, r;
  }
  function L_(i, r, l, f) {
    return i.baseState = l, ip(
      i,
      Ze,
      typeof f == "function" ? f : Gs
    );
  }
  function YA(i, r, l, f, v) {
    if (zu(i)) throw Error(s(485));
    if (i = r.action, i !== null) {
      var S = {
        payload: v,
        action: i,
        next: null,
        isTransition: !0,
        status: "pending",
        value: null,
        reason: null,
        listeners: [],
        then: function(P) {
          S.listeners.push(P);
        }
      };
      N.T !== null ? l(!0) : S.isTransition = !1, f(S), l = r.pending, l === null ? (S.next = r.pending = S, U_(r, S)) : (S.next = l.next, r.pending = l.next = S);
    }
  }
  function U_(i, r) {
    var l = r.action, f = r.payload, v = i.state;
    if (r.isTransition) {
      var S = N.T, P = {};
      N.T = P;
      try {
        var q = l(v, f), nt = N.S;
        nt !== null && nt(P, q), P_(i, r, q);
      } catch (pt) {
        ap(i, r, pt);
      } finally {
        S !== null && P.types !== null && (S.types = P.types), N.T = S;
      }
    } else
      try {
        S = l(v, f), P_(i, r, S);
      } catch (pt) {
        ap(i, r, pt);
      }
  }
  function P_(i, r, l) {
    l !== null && typeof l == "object" && typeof l.then == "function" ? l.then(
      function(f) {
        I_(i, r, f);
      },
      function(f) {
        return ap(i, r, f);
      }
    ) : I_(i, r, l);
  }
  function I_(i, r, l) {
    r.status = "fulfilled", r.value = l, B_(r), i.state = l, r = i.pending, r !== null && (l = r.next, l === r ? i.pending = null : (l = l.next, r.next = l, U_(i, l)));
  }
  function ap(i, r, l) {
    var f = i.pending;
    if (i.pending = null, f !== null) {
      f = f.next;
      do
        r.status = "rejected", r.reason = l, B_(r), r = r.next;
      while (r !== f);
    }
    i.action = null;
  }
  function B_(i) {
    i = i.listeners;
    for (var r = 0; r < i.length; r++) (0, i[r])();
  }
  function z_(i, r) {
    return r;
  }
  function F_(i, r) {
    if (Le) {
      var l = tn.formState;
      if (l !== null) {
        t: {
          var f = Se;
          if (Le) {
            if (sn) {
              e: {
                for (var v = sn, S = Fi; v.nodeType !== 8; ) {
                  if (!S) {
                    v = null;
                    break e;
                  }
                  if (v = Vi(
                    v.nextSibling
                  ), v === null) {
                    v = null;
                    break e;
                  }
                }
                S = v.data, v = S === "F!" || S === "F" ? v : null;
              }
              if (v) {
                sn = Vi(
                  v.nextSibling
                ), f = v.data === "F!";
                break t;
              }
            }
            Er(f);
          }
          f = !1;
        }
        f && (r = l[0]);
      }
    }
    return l = ni(), l.memoizedState = l.baseState = r, f = {
      pending: null,
      lanes: 0,
      dispatch: null,
      lastRenderedReducer: z_,
      lastRenderedState: r
    }, l.queue = f, l = sy.bind(
      null,
      Se,
      f
    ), f.dispatch = l, f = rp(!1), S = dp.bind(
      null,
      Se,
      !1,
      f.queue
    ), f = ni(), v = {
      state: r,
      dispatch: null,
      action: i,
      pending: null
    }, f.queue = v, l = YA.bind(
      null,
      Se,
      v,
      S,
      l
    ), v.dispatch = l, f.memoizedState = i, [r, l, !1];
  }
  function H_(i) {
    var r = gn();
    return V_(r, Ze, i);
  }
  function V_(i, r, l) {
    if (r = ip(
      i,
      r,
      z_
    )[0], i = Pu(Gs)[0], typeof r == "object" && r !== null && typeof r.then == "function")
      try {
        var f = kl(r);
      } catch (P) {
        throw P === po ? wu : P;
      }
    else f = r;
    r = gn();
    var v = r.queue, S = v.dispatch;
    return l !== r.memoizedState && (Se.flags |= 2048, yo(
      9,
      { destroy: void 0 },
      jA.bind(null, v, l),
      null
    )), [f, S, i];
  }
  function jA(i, r) {
    i.action = r;
  }
  function G_(i) {
    var r = gn(), l = Ze;
    if (l !== null)
      return V_(r, l, i);
    gn(), r = r.memoizedState, l = gn();
    var f = l.queue.dispatch;
    return l.memoizedState = i, [r, f, !1];
  }
  function yo(i, r, l, f) {
    return i = { tag: i, create: l, deps: f, inst: r, next: null }, r = Se.updateQueue, r === null && (r = Lu(), Se.updateQueue = r), l = r.lastEffect, l === null ? r.lastEffect = i.next = i : (f = l.next, l.next = i, i.next = f, r.lastEffect = i), i;
  }
  function k_() {
    return gn().memoizedState;
  }
  function Iu(i, r, l, f) {
    var v = ni();
    Se.flags |= i, v.memoizedState = yo(
      1 | r,
      { destroy: void 0 },
      l,
      f === void 0 ? null : f
    );
  }
  function Bu(i, r, l, f) {
    var v = gn();
    f = f === void 0 ? null : f;
    var S = v.memoizedState.inst;
    Ze !== null && f !== null && Kh(f, Ze.memoizedState.deps) ? v.memoizedState = yo(r, S, l, f) : (Se.flags |= i, v.memoizedState = yo(
      1 | r,
      S,
      l,
      f
    ));
  }
  function X_(i, r) {
    Iu(8390656, 8, i, r);
  }
  function op(i, r) {
    Bu(2048, 8, i, r);
  }
  function qA(i) {
    Se.flags |= 4;
    var r = Se.updateQueue;
    if (r === null)
      r = Lu(), Se.updateQueue = r, r.events = [i];
    else {
      var l = r.events;
      l === null ? r.events = [i] : l.push(i);
    }
  }
  function W_(i) {
    var r = gn().memoizedState;
    return qA({ ref: r, nextImpl: i }), function() {
      if ((Ve & 2) !== 0) throw Error(s(440));
      return r.impl.apply(void 0, arguments);
    };
  }
  function Y_(i, r) {
    return Bu(4, 2, i, r);
  }
  function j_(i, r) {
    return Bu(4, 4, i, r);
  }
  function q_(i, r) {
    if (typeof r == "function") {
      i = i();
      var l = r(i);
      return function() {
        typeof l == "function" ? l() : r(null);
      };
    }
    if (r != null)
      return i = i(), r.current = i, function() {
        r.current = null;
      };
  }
  function Z_(i, r, l) {
    l = l != null ? l.concat([i]) : null, Bu(4, 4, q_.bind(null, r, i), l);
  }
  function lp() {
  }
  function $_(i, r) {
    var l = gn();
    r = r === void 0 ? null : r;
    var f = l.memoizedState;
    return r !== null && Kh(r, f[1]) ? f[0] : (l.memoizedState = [i, r], i);
  }
  function K_(i, r) {
    var l = gn();
    r = r === void 0 ? null : r;
    var f = l.memoizedState;
    if (r !== null && Kh(r, f[1]))
      return f[0];
    if (f = i(), ba) {
      Wt(!0);
      try {
        i();
      } finally {
        Wt(!1);
      }
    }
    return l.memoizedState = [f, r], f;
  }
  function cp(i, r, l) {
    return l === void 0 || (Vs & 1073741824) !== 0 && (De & 261930) === 0 ? i.memoizedState = r : (i.memoizedState = l, i = Qy(), Se.lanes |= i, Lr |= i, l);
  }
  function Q_(i, r, l, f) {
    return _i(l, r) ? l : go.current !== null ? (i = cp(i, l, f), _i(i, r) || (Mn = !0), i) : (Vs & 42) === 0 || (Vs & 1073741824) !== 0 && (De & 261930) === 0 ? (Mn = !0, i.memoizedState = l) : (i = Qy(), Se.lanes |= i, Lr |= i, r);
  }
  function J_(i, r, l, f, v) {
    var S = I.p;
    I.p = S !== 0 && 8 > S ? S : 8;
    var P = N.T, q = {};
    N.T = q, dp(i, !1, r, l);
    try {
      var nt = v(), pt = N.S;
      if (pt !== null && pt(q, nt), nt !== null && typeof nt == "object" && typeof nt.then == "function") {
        var wt = kA(
          nt,
          f
        );
        Xl(
          i,
          r,
          wt,
          Ei(i)
        );
      } else
        Xl(
          i,
          r,
          f,
          Ei(i)
        );
    } catch (Ct) {
      Xl(
        i,
        r,
        { then: function() {
        }, status: "rejected", reason: Ct },
        Ei()
      );
    } finally {
      I.p = S, P !== null && q.types !== null && (P.types = q.types), N.T = P;
    }
  }
  function ZA() {
  }
  function up(i, r, l, f) {
    if (i.tag !== 5) throw Error(s(476));
    var v = ty(i).queue;
    J_(
      i,
      v,
      r,
      k,
      l === null ? ZA : function() {
        return ey(i), l(f);
      }
    );
  }
  function ty(i) {
    var r = i.memoizedState;
    if (r !== null) return r;
    r = {
      memoizedState: k,
      baseState: k,
      baseQueue: null,
      queue: {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: Gs,
        lastRenderedState: k
      },
      next: null
    };
    var l = {};
    return r.next = {
      memoizedState: l,
      baseState: l,
      baseQueue: null,
      queue: {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: Gs,
        lastRenderedState: l
      },
      next: null
    }, i.memoizedState = r, i = i.alternate, i !== null && (i.memoizedState = r), r;
  }
  function ey(i) {
    var r = ty(i);
    r.next === null && (r = i.alternate.memoizedState), Xl(
      i,
      r.next.queue,
      {},
      Ei()
    );
  }
  function fp() {
    return Gn(oc);
  }
  function ny() {
    return gn().memoizedState;
  }
  function iy() {
    return gn().memoizedState;
  }
  function $A(i) {
    for (var r = i.return; r !== null; ) {
      switch (r.tag) {
        case 24:
        case 3:
          var l = Ei();
          i = Tr(l);
          var f = Cr(r, i, l);
          f !== null && (ui(f, r, l), Fl(f, r, l)), r = { cache: Hh() }, i.payload = r;
          return;
      }
      r = r.return;
    }
  }
  function KA(i, r, l) {
    var f = Ei();
    l = {
      lane: f,
      revertLane: 0,
      gesture: null,
      action: l,
      hasEagerState: !1,
      eagerState: null,
      next: null
    }, zu(i) ? ry(r, l) : (l = Rh(i, r, l, f), l !== null && (ui(l, i, f), ay(l, r, f)));
  }
  function sy(i, r, l) {
    var f = Ei();
    Xl(i, r, l, f);
  }
  function Xl(i, r, l, f) {
    var v = {
      lane: f,
      revertLane: 0,
      gesture: null,
      action: l,
      hasEagerState: !1,
      eagerState: null,
      next: null
    };
    if (zu(i)) ry(r, v);
    else {
      var S = i.alternate;
      if (i.lanes === 0 && (S === null || S.lanes === 0) && (S = r.lastRenderedReducer, S !== null))
        try {
          var P = r.lastRenderedState, q = S(P, l);
          if (v.hasEagerState = !0, v.eagerState = q, _i(q, P))
            return _u(i, r, v, 0), tn === null && vu(), !1;
        } catch {
        } finally {
        }
      if (l = Rh(i, r, v, f), l !== null)
        return ui(l, i, f), ay(l, r, f), !0;
    }
    return !1;
  }
  function dp(i, r, l, f) {
    if (f = {
      lane: 2,
      revertLane: Xp(),
      gesture: null,
      action: f,
      hasEagerState: !1,
      eagerState: null,
      next: null
    }, zu(i)) {
      if (r) throw Error(s(479));
    } else
      r = Rh(
        i,
        l,
        f,
        2
      ), r !== null && ui(r, i, 2);
  }
  function zu(i) {
    var r = i.alternate;
    return i === Se || r !== null && r === Se;
  }
  function ry(i, r) {
    vo = Nu = !0;
    var l = i.pending;
    l === null ? r.next = r : (r.next = l.next, l.next = r), i.pending = r;
  }
  function ay(i, r, l) {
    if ((l & 4194048) !== 0) {
      var f = r.lanes;
      f &= i.pendingLanes, l |= f, r.lanes = l, vr(i, l);
    }
  }
  var Wl = {
    readContext: Gn,
    use: Uu,
    useCallback: un,
    useContext: un,
    useEffect: un,
    useImperativeHandle: un,
    useLayoutEffect: un,
    useInsertionEffect: un,
    useMemo: un,
    useReducer: un,
    useRef: un,
    useState: un,
    useDebugValue: un,
    useDeferredValue: un,
    useTransition: un,
    useSyncExternalStore: un,
    useId: un,
    useHostTransitionStatus: un,
    useFormState: un,
    useActionState: un,
    useOptimistic: un,
    useMemoCache: un,
    useCacheRefresh: un
  };
  Wl.useEffectEvent = un;
  var oy = {
    readContext: Gn,
    use: Uu,
    useCallback: function(i, r) {
      return ni().memoizedState = [
        i,
        r === void 0 ? null : r
      ], i;
    },
    useContext: Gn,
    useEffect: X_,
    useImperativeHandle: function(i, r, l) {
      l = l != null ? l.concat([i]) : null, Iu(
        4194308,
        4,
        q_.bind(null, r, i),
        l
      );
    },
    useLayoutEffect: function(i, r) {
      return Iu(4194308, 4, i, r);
    },
    useInsertionEffect: function(i, r) {
      Iu(4, 2, i, r);
    },
    useMemo: function(i, r) {
      var l = ni();
      r = r === void 0 ? null : r;
      var f = i();
      if (ba) {
        Wt(!0);
        try {
          i();
        } finally {
          Wt(!1);
        }
      }
      return l.memoizedState = [f, r], f;
    },
    useReducer: function(i, r, l) {
      var f = ni();
      if (l !== void 0) {
        var v = l(r);
        if (ba) {
          Wt(!0);
          try {
            l(r);
          } finally {
            Wt(!1);
          }
        }
      } else v = r;
      return f.memoizedState = f.baseState = v, i = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: i,
        lastRenderedState: v
      }, f.queue = i, i = i.dispatch = KA.bind(
        null,
        Se,
        i
      ), [f.memoizedState, i];
    },
    useRef: function(i) {
      var r = ni();
      return i = { current: i }, r.memoizedState = i;
    },
    useState: function(i) {
      i = rp(i);
      var r = i.queue, l = sy.bind(null, Se, r);
      return r.dispatch = l, [i.memoizedState, l];
    },
    useDebugValue: lp,
    useDeferredValue: function(i, r) {
      var l = ni();
      return cp(l, i, r);
    },
    useTransition: function() {
      var i = rp(!1);
      return i = J_.bind(
        null,
        Se,
        i.queue,
        !0,
        !1
      ), ni().memoizedState = i, [!1, i];
    },
    useSyncExternalStore: function(i, r, l) {
      var f = Se, v = ni();
      if (Le) {
        if (l === void 0)
          throw Error(s(407));
        l = l();
      } else {
        if (l = r(), tn === null)
          throw Error(s(349));
        (De & 127) !== 0 || C_(f, r, l);
      }
      v.memoizedState = l;
      var S = { value: l, getSnapshot: r };
      return v.queue = S, X_(D_.bind(null, f, S, i), [
        i
      ]), f.flags |= 2048, yo(
        9,
        { destroy: void 0 },
        R_.bind(
          null,
          f,
          S,
          l,
          r
        ),
        null
      ), l;
    },
    useId: function() {
      var i = ni(), r = tn.identifierPrefix;
      if (Le) {
        var l = hs, f = ds;
        l = (f & ~(1 << 32 - kt(f) - 1)).toString(32) + l, r = "_" + r + "R_" + l, l = Ou++, 0 < l && (r += "H" + l.toString(32)), r += "_";
      } else
        l = XA++, r = "_" + r + "r_" + l.toString(32) + "_";
      return i.memoizedState = r;
    },
    useHostTransitionStatus: fp,
    useFormState: F_,
    useActionState: F_,
    useOptimistic: function(i) {
      var r = ni();
      r.memoizedState = r.baseState = i;
      var l = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: null,
        lastRenderedState: null
      };
      return r.queue = l, r = dp.bind(
        null,
        Se,
        !0,
        l
      ), l.dispatch = r, [i, r];
    },
    useMemoCache: np,
    useCacheRefresh: function() {
      return ni().memoizedState = $A.bind(
        null,
        Se
      );
    },
    useEffectEvent: function(i) {
      var r = ni(), l = { impl: i };
      return r.memoizedState = l, function() {
        if ((Ve & 2) !== 0)
          throw Error(s(440));
        return l.impl.apply(void 0, arguments);
      };
    }
  }, hp = {
    readContext: Gn,
    use: Uu,
    useCallback: $_,
    useContext: Gn,
    useEffect: op,
    useImperativeHandle: Z_,
    useInsertionEffect: Y_,
    useLayoutEffect: j_,
    useMemo: K_,
    useReducer: Pu,
    useRef: k_,
    useState: function() {
      return Pu(Gs);
    },
    useDebugValue: lp,
    useDeferredValue: function(i, r) {
      var l = gn();
      return Q_(
        l,
        Ze.memoizedState,
        i,
        r
      );
    },
    useTransition: function() {
      var i = Pu(Gs)[0], r = gn().memoizedState;
      return [
        typeof i == "boolean" ? i : kl(i),
        r
      ];
    },
    useSyncExternalStore: T_,
    useId: ny,
    useHostTransitionStatus: fp,
    useFormState: H_,
    useActionState: H_,
    useOptimistic: function(i, r) {
      var l = gn();
      return L_(l, Ze, i, r);
    },
    useMemoCache: np,
    useCacheRefresh: iy
  };
  hp.useEffectEvent = W_;
  var ly = {
    readContext: Gn,
    use: Uu,
    useCallback: $_,
    useContext: Gn,
    useEffect: op,
    useImperativeHandle: Z_,
    useInsertionEffect: Y_,
    useLayoutEffect: j_,
    useMemo: K_,
    useReducer: sp,
    useRef: k_,
    useState: function() {
      return sp(Gs);
    },
    useDebugValue: lp,
    useDeferredValue: function(i, r) {
      var l = gn();
      return Ze === null ? cp(l, i, r) : Q_(
        l,
        Ze.memoizedState,
        i,
        r
      );
    },
    useTransition: function() {
      var i = sp(Gs)[0], r = gn().memoizedState;
      return [
        typeof i == "boolean" ? i : kl(i),
        r
      ];
    },
    useSyncExternalStore: T_,
    useId: ny,
    useHostTransitionStatus: fp,
    useFormState: G_,
    useActionState: G_,
    useOptimistic: function(i, r) {
      var l = gn();
      return Ze !== null ? L_(l, Ze, i, r) : (l.baseState = i, [i, l.queue.dispatch]);
    },
    useMemoCache: np,
    useCacheRefresh: iy
  };
  ly.useEffectEvent = W_;
  function pp(i, r, l, f) {
    r = i.memoizedState, l = l(f, r), l = l == null ? r : p({}, r, l), i.memoizedState = l, i.lanes === 0 && (i.updateQueue.baseState = l);
  }
  var mp = {
    enqueueSetState: function(i, r, l) {
      i = i._reactInternals;
      var f = Ei(), v = Tr(f);
      v.payload = r, l != null && (v.callback = l), r = Cr(i, v, f), r !== null && (ui(r, i, f), Fl(r, i, f));
    },
    enqueueReplaceState: function(i, r, l) {
      i = i._reactInternals;
      var f = Ei(), v = Tr(f);
      v.tag = 1, v.payload = r, l != null && (v.callback = l), r = Cr(i, v, f), r !== null && (ui(r, i, f), Fl(r, i, f));
    },
    enqueueForceUpdate: function(i, r) {
      i = i._reactInternals;
      var l = Ei(), f = Tr(l);
      f.tag = 2, r != null && (f.callback = r), r = Cr(i, f, l), r !== null && (ui(r, i, l), Fl(r, i, l));
    }
  };
  function cy(i, r, l, f, v, S, P) {
    return i = i.stateNode, typeof i.shouldComponentUpdate == "function" ? i.shouldComponentUpdate(f, S, P) : r.prototype && r.prototype.isPureReactComponent ? !Nl(l, f) || !Nl(v, S) : !0;
  }
  function uy(i, r, l, f) {
    i = r.state, typeof r.componentWillReceiveProps == "function" && r.componentWillReceiveProps(l, f), typeof r.UNSAFE_componentWillReceiveProps == "function" && r.UNSAFE_componentWillReceiveProps(l, f), r.state !== i && mp.enqueueReplaceState(r, r.state, null);
  }
  function Ma(i, r) {
    var l = r;
    if ("ref" in r) {
      l = {};
      for (var f in r)
        f !== "ref" && (l[f] = r[f]);
    }
    if (i = i.defaultProps) {
      l === r && (l = p({}, l));
      for (var v in i)
        l[v] === void 0 && (l[v] = i[v]);
    }
    return l;
  }
  function fy(i) {
    gu(i);
  }
  function dy(i) {
    console.error(i);
  }
  function hy(i) {
    gu(i);
  }
  function Fu(i, r) {
    try {
      var l = i.onUncaughtError;
      l(r.value, { componentStack: r.stack });
    } catch (f) {
      setTimeout(function() {
        throw f;
      });
    }
  }
  function py(i, r, l) {
    try {
      var f = i.onCaughtError;
      f(l.value, {
        componentStack: l.stack,
        errorBoundary: r.tag === 1 ? r.stateNode : null
      });
    } catch (v) {
      setTimeout(function() {
        throw v;
      });
    }
  }
  function gp(i, r, l) {
    return l = Tr(l), l.tag = 3, l.payload = { element: null }, l.callback = function() {
      Fu(i, r);
    }, l;
  }
  function my(i) {
    return i = Tr(i), i.tag = 3, i;
  }
  function gy(i, r, l, f) {
    var v = l.type.getDerivedStateFromError;
    if (typeof v == "function") {
      var S = f.value;
      i.payload = function() {
        return v(S);
      }, i.callback = function() {
        py(r, l, f);
      };
    }
    var P = l.stateNode;
    P !== null && typeof P.componentDidCatch == "function" && (i.callback = function() {
      py(r, l, f), typeof v != "function" && (Ur === null ? Ur = /* @__PURE__ */ new Set([this]) : Ur.add(this));
      var q = f.stack;
      this.componentDidCatch(f.value, {
        componentStack: q !== null ? q : ""
      });
    });
  }
  function QA(i, r, l, f, v) {
    if (l.flags |= 32768, f !== null && typeof f == "object" && typeof f.then == "function") {
      if (r = l.alternate, r !== null && uo(
        r,
        l,
        v,
        !0
      ), l = xi.current, l !== null) {
        switch (l.tag) {
          case 31:
          case 13:
            return Hi === null ? Ku() : l.alternate === null && fn === 0 && (fn = 3), l.flags &= -257, l.flags |= 65536, l.lanes = v, f === Au ? l.flags |= 16384 : (r = l.updateQueue, r === null ? l.updateQueue = /* @__PURE__ */ new Set([f]) : r.add(f), Vp(i, f, v)), !1;
          case 22:
            return l.flags |= 65536, f === Au ? l.flags |= 16384 : (r = l.updateQueue, r === null ? (r = {
              transitions: null,
              markerInstances: null,
              retryQueue: /* @__PURE__ */ new Set([f])
            }, l.updateQueue = r) : (l = r.retryQueue, l === null ? r.retryQueue = /* @__PURE__ */ new Set([f]) : l.add(f)), Vp(i, f, v)), !1;
        }
        throw Error(s(435, l.tag));
      }
      return Vp(i, f, v), Ku(), !1;
    }
    if (Le)
      return r = xi.current, r !== null ? ((r.flags & 65536) === 0 && (r.flags |= 256), r.flags |= 65536, r.lanes = v, f !== Ph && (i = Error(s(422), { cause: f }), Ul(Ii(i, l)))) : (f !== Ph && (r = Error(s(423), {
        cause: f
      }), Ul(
        Ii(r, l)
      )), i = i.current.alternate, i.flags |= 65536, v &= -v, i.lanes |= v, f = Ii(f, l), v = gp(
        i.stateNode,
        f,
        v
      ), Yh(i, v), fn !== 4 && (fn = 2)), !1;
    var S = Error(s(520), { cause: f });
    if (S = Ii(S, l), Jl === null ? Jl = [S] : Jl.push(S), fn !== 4 && (fn = 2), r === null) return !0;
    f = Ii(f, l), l = r;
    do {
      switch (l.tag) {
        case 3:
          return l.flags |= 65536, i = v & -v, l.lanes |= i, i = gp(l.stateNode, f, i), Yh(l, i), !1;
        case 1:
          if (r = l.type, S = l.stateNode, (l.flags & 128) === 0 && (typeof r.getDerivedStateFromError == "function" || S !== null && typeof S.componentDidCatch == "function" && (Ur === null || !Ur.has(S))))
            return l.flags |= 65536, v &= -v, l.lanes |= v, v = my(v), gy(
              v,
              i,
              l,
              f
            ), Yh(l, v), !1;
      }
      l = l.return;
    } while (l !== null);
    return !1;
  }
  var vp = Error(s(461)), Mn = !1;
  function kn(i, r, l, f) {
    r.child = i === null ? x_(r, null, l, f) : Sa(
      r,
      i.child,
      l,
      f
    );
  }
  function vy(i, r, l, f, v) {
    l = l.render;
    var S = r.ref;
    if ("ref" in f) {
      var P = {};
      for (var q in f)
        q !== "ref" && (P[q] = f[q]);
    } else P = f;
    return va(r), f = Qh(
      i,
      r,
      l,
      P,
      S,
      v
    ), q = Jh(), i !== null && !Mn ? (tp(i, r, v), ks(i, r, v)) : (Le && q && Lh(r), r.flags |= 1, kn(i, r, f, v), r.child);
  }
  function _y(i, r, l, f, v) {
    if (i === null) {
      var S = l.type;
      return typeof S == "function" && !Dh(S) && S.defaultProps === void 0 && l.compare === null ? (r.tag = 15, r.type = S, yy(
        i,
        r,
        S,
        f,
        v
      )) : (i = xu(
        l.type,
        null,
        f,
        r,
        r.mode,
        v
      ), i.ref = r.ref, i.return = r, r.child = i);
    }
    if (S = i.child, !wp(i, v)) {
      var P = S.memoizedProps;
      if (l = l.compare, l = l !== null ? l : Nl, l(P, f) && i.ref === r.ref)
        return ks(i, r, v);
    }
    return r.flags |= 1, i = Bs(S, f), i.ref = r.ref, i.return = r, r.child = i;
  }
  function yy(i, r, l, f, v) {
    if (i !== null) {
      var S = i.memoizedProps;
      if (Nl(S, f) && i.ref === r.ref)
        if (Mn = !1, r.pendingProps = f = S, wp(i, v))
          (i.flags & 131072) !== 0 && (Mn = !0);
        else
          return r.lanes = i.lanes, ks(i, r, v);
    }
    return _p(
      i,
      r,
      l,
      f,
      v
    );
  }
  function xy(i, r, l, f) {
    var v = f.children, S = i !== null ? i.memoizedState : null;
    if (i === null && r.stateNode === null && (r.stateNode = {
      _visibility: 1,
      _pendingMarkers: null,
      _retryCache: null,
      _transitions: null
    }), f.mode === "hidden") {
      if ((r.flags & 128) !== 0) {
        if (S = S !== null ? S.baseLanes | l : l, i !== null) {
          for (f = r.child = i.child, v = 0; f !== null; )
            v = v | f.lanes | f.childLanes, f = f.sibling;
          f = v & ~S;
        } else f = 0, r.child = null;
        return Sy(
          i,
          r,
          S,
          l,
          f
        );
      }
      if ((l & 536870912) !== 0)
        r.memoizedState = { baseLanes: 0, cachePool: null }, i !== null && Eu(
          r,
          S !== null ? S.cachePool : null
        ), S !== null ? M_(r, S) : qh(), E_(r);
      else
        return f = r.lanes = 536870912, Sy(
          i,
          r,
          S !== null ? S.baseLanes | l : l,
          l,
          f
        );
    } else
      S !== null ? (Eu(r, S.cachePool), M_(r, S), Dr(), r.memoizedState = null) : (i !== null && Eu(r, null), qh(), Dr());
    return kn(i, r, v, l), r.child;
  }
  function Yl(i, r) {
    return i !== null && i.tag === 22 || r.stateNode !== null || (r.stateNode = {
      _visibility: 1,
      _pendingMarkers: null,
      _retryCache: null,
      _transitions: null
    }), r.sibling;
  }
  function Sy(i, r, l, f, v) {
    var S = Gh();
    return S = S === null ? null : { parent: Sn._currentValue, pool: S }, r.memoizedState = {
      baseLanes: l,
      cachePool: S
    }, i !== null && Eu(r, null), qh(), E_(r), i !== null && uo(i, r, f, !0), r.childLanes = v, null;
  }
  function Hu(i, r) {
    return r = Gu(
      { mode: r.mode, children: r.children },
      i.mode
    ), r.ref = i.ref, i.child = r, r.return = i, r;
  }
  function by(i, r, l) {
    return Sa(r, i.child, null, l), i = Hu(r, r.pendingProps), i.flags |= 2, Si(r), r.memoizedState = null, i;
  }
  function JA(i, r, l) {
    var f = r.pendingProps, v = (r.flags & 128) !== 0;
    if (r.flags &= -129, i === null) {
      if (Le) {
        if (f.mode === "hidden")
          return i = Hu(r, f), r.lanes = 536870912, Yl(null, i);
        if ($h(r), (i = sn) ? (i = Ux(
          i,
          Fi
        ), i = i !== null && i.data === "&" ? i : null, i !== null && (r.memoizedState = {
          dehydrated: i,
          treeContext: br !== null ? { id: ds, overflow: hs } : null,
          retryLane: 536870912,
          hydrationErrors: null
        }, l = r_(i), l.return = r, r.child = l, Vn = r, sn = null)) : i = null, i === null) throw Er(r);
        return r.lanes = 536870912, null;
      }
      return Hu(r, f);
    }
    var S = i.memoizedState;
    if (S !== null) {
      var P = S.dehydrated;
      if ($h(r), v)
        if (r.flags & 256)
          r.flags &= -257, r = by(
            i,
            r,
            l
          );
        else if (r.memoizedState !== null)
          r.child = i.child, r.flags |= 128, r = null;
        else throw Error(s(558));
      else if (Mn || uo(i, r, l, !1), v = (l & i.childLanes) !== 0, Mn || v) {
        if (f = tn, f !== null && (P = $a(f, l), P !== 0 && P !== S.retryLane))
          throw S.retryLane = P, ha(i, P), ui(f, i, P), vp;
        Ku(), r = by(
          i,
          r,
          l
        );
      } else
        i = S.treeContext, sn = Vi(P.nextSibling), Vn = r, Le = !0, Mr = null, Fi = !1, i !== null && l_(r, i), r = Hu(r, f), r.flags |= 4096;
      return r;
    }
    return i = Bs(i.child, {
      mode: f.mode,
      children: f.children
    }), i.ref = r.ref, r.child = i, i.return = r, i;
  }
  function Vu(i, r) {
    var l = r.ref;
    if (l === null)
      i !== null && i.ref !== null && (r.flags |= 4194816);
    else {
      if (typeof l != "function" && typeof l != "object")
        throw Error(s(284));
      (i === null || i.ref !== l) && (r.flags |= 4194816);
    }
  }
  function _p(i, r, l, f, v) {
    return va(r), l = Qh(
      i,
      r,
      l,
      f,
      void 0,
      v
    ), f = Jh(), i !== null && !Mn ? (tp(i, r, v), ks(i, r, v)) : (Le && f && Lh(r), r.flags |= 1, kn(i, r, l, v), r.child);
  }
  function My(i, r, l, f, v, S) {
    return va(r), r.updateQueue = null, l = A_(
      r,
      f,
      l,
      v
    ), w_(i), f = Jh(), i !== null && !Mn ? (tp(i, r, S), ks(i, r, S)) : (Le && f && Lh(r), r.flags |= 1, kn(i, r, l, S), r.child);
  }
  function Ey(i, r, l, f, v) {
    if (va(r), r.stateNode === null) {
      var S = ao, P = l.contextType;
      typeof P == "object" && P !== null && (S = Gn(P)), S = new l(f, S), r.memoizedState = S.state !== null && S.state !== void 0 ? S.state : null, S.updater = mp, r.stateNode = S, S._reactInternals = r, S = r.stateNode, S.props = f, S.state = r.memoizedState, S.refs = {}, Xh(r), P = l.contextType, S.context = typeof P == "object" && P !== null ? Gn(P) : ao, S.state = r.memoizedState, P = l.getDerivedStateFromProps, typeof P == "function" && (pp(
        r,
        l,
        P,
        f
      ), S.state = r.memoizedState), typeof l.getDerivedStateFromProps == "function" || typeof S.getSnapshotBeforeUpdate == "function" || typeof S.UNSAFE_componentWillMount != "function" && typeof S.componentWillMount != "function" || (P = S.state, typeof S.componentWillMount == "function" && S.componentWillMount(), typeof S.UNSAFE_componentWillMount == "function" && S.UNSAFE_componentWillMount(), P !== S.state && mp.enqueueReplaceState(S, S.state, null), Vl(r, f, S, v), Hl(), S.state = r.memoizedState), typeof S.componentDidMount == "function" && (r.flags |= 4194308), f = !0;
    } else if (i === null) {
      S = r.stateNode;
      var q = r.memoizedProps, nt = Ma(l, q);
      S.props = nt;
      var pt = S.context, wt = l.contextType;
      P = ao, typeof wt == "object" && wt !== null && (P = Gn(wt));
      var Ct = l.getDerivedStateFromProps;
      wt = typeof Ct == "function" || typeof S.getSnapshotBeforeUpdate == "function", q = r.pendingProps !== q, wt || typeof S.UNSAFE_componentWillReceiveProps != "function" && typeof S.componentWillReceiveProps != "function" || (q || pt !== P) && uy(
        r,
        S,
        f,
        P
      ), Ar = !1;
      var gt = r.memoizedState;
      S.state = gt, Vl(r, f, S, v), Hl(), pt = r.memoizedState, q || gt !== pt || Ar ? (typeof Ct == "function" && (pp(
        r,
        l,
        Ct,
        f
      ), pt = r.memoizedState), (nt = Ar || cy(
        r,
        l,
        nt,
        f,
        gt,
        pt,
        P
      )) ? (wt || typeof S.UNSAFE_componentWillMount != "function" && typeof S.componentWillMount != "function" || (typeof S.componentWillMount == "function" && S.componentWillMount(), typeof S.UNSAFE_componentWillMount == "function" && S.UNSAFE_componentWillMount()), typeof S.componentDidMount == "function" && (r.flags |= 4194308)) : (typeof S.componentDidMount == "function" && (r.flags |= 4194308), r.memoizedProps = f, r.memoizedState = pt), S.props = f, S.state = pt, S.context = P, f = nt) : (typeof S.componentDidMount == "function" && (r.flags |= 4194308), f = !1);
    } else {
      S = r.stateNode, Wh(i, r), P = r.memoizedProps, wt = Ma(l, P), S.props = wt, Ct = r.pendingProps, gt = S.context, pt = l.contextType, nt = ao, typeof pt == "object" && pt !== null && (nt = Gn(pt)), q = l.getDerivedStateFromProps, (pt = typeof q == "function" || typeof S.getSnapshotBeforeUpdate == "function") || typeof S.UNSAFE_componentWillReceiveProps != "function" && typeof S.componentWillReceiveProps != "function" || (P !== Ct || gt !== nt) && uy(
        r,
        S,
        f,
        nt
      ), Ar = !1, gt = r.memoizedState, S.state = gt, Vl(r, f, S, v), Hl();
      var St = r.memoizedState;
      P !== Ct || gt !== St || Ar || i !== null && i.dependencies !== null && bu(i.dependencies) ? (typeof q == "function" && (pp(
        r,
        l,
        q,
        f
      ), St = r.memoizedState), (wt = Ar || cy(
        r,
        l,
        wt,
        f,
        gt,
        St,
        nt
      ) || i !== null && i.dependencies !== null && bu(i.dependencies)) ? (pt || typeof S.UNSAFE_componentWillUpdate != "function" && typeof S.componentWillUpdate != "function" || (typeof S.componentWillUpdate == "function" && S.componentWillUpdate(f, St, nt), typeof S.UNSAFE_componentWillUpdate == "function" && S.UNSAFE_componentWillUpdate(
        f,
        St,
        nt
      )), typeof S.componentDidUpdate == "function" && (r.flags |= 4), typeof S.getSnapshotBeforeUpdate == "function" && (r.flags |= 1024)) : (typeof S.componentDidUpdate != "function" || P === i.memoizedProps && gt === i.memoizedState || (r.flags |= 4), typeof S.getSnapshotBeforeUpdate != "function" || P === i.memoizedProps && gt === i.memoizedState || (r.flags |= 1024), r.memoizedProps = f, r.memoizedState = St), S.props = f, S.state = St, S.context = nt, f = wt) : (typeof S.componentDidUpdate != "function" || P === i.memoizedProps && gt === i.memoizedState || (r.flags |= 4), typeof S.getSnapshotBeforeUpdate != "function" || P === i.memoizedProps && gt === i.memoizedState || (r.flags |= 1024), f = !1);
    }
    return S = f, Vu(i, r), f = (r.flags & 128) !== 0, S || f ? (S = r.stateNode, l = f && typeof l.getDerivedStateFromError != "function" ? null : S.render(), r.flags |= 1, i !== null && f ? (r.child = Sa(
      r,
      i.child,
      null,
      v
    ), r.child = Sa(
      r,
      null,
      l,
      v
    )) : kn(i, r, l, v), r.memoizedState = S.state, i = r.child) : i = ks(
      i,
      r,
      v
    ), i;
  }
  function wy(i, r, l, f) {
    return ma(), r.flags |= 256, kn(i, r, l, f), r.child;
  }
  var yp = {
    dehydrated: null,
    treeContext: null,
    retryLane: 0,
    hydrationErrors: null
  };
  function xp(i) {
    return { baseLanes: i, cachePool: p_() };
  }
  function Sp(i, r, l) {
    return i = i !== null ? i.childLanes & ~l : 0, r && (i |= Mi), i;
  }
  function Ay(i, r, l) {
    var f = r.pendingProps, v = !1, S = (r.flags & 128) !== 0, P;
    if ((P = S) || (P = i !== null && i.memoizedState === null ? !1 : (mn.current & 2) !== 0), P && (v = !0, r.flags &= -129), P = (r.flags & 32) !== 0, r.flags &= -33, i === null) {
      if (Le) {
        if (v ? Rr(r) : Dr(), (i = sn) ? (i = Ux(
          i,
          Fi
        ), i = i !== null && i.data !== "&" ? i : null, i !== null && (r.memoizedState = {
          dehydrated: i,
          treeContext: br !== null ? { id: ds, overflow: hs } : null,
          retryLane: 536870912,
          hydrationErrors: null
        }, l = r_(i), l.return = r, r.child = l, Vn = r, sn = null)) : i = null, i === null) throw Er(r);
        return im(i) ? r.lanes = 32 : r.lanes = 536870912, null;
      }
      var q = f.children;
      return f = f.fallback, v ? (Dr(), v = r.mode, q = Gu(
        { mode: "hidden", children: q },
        v
      ), f = pa(
        f,
        v,
        l,
        null
      ), q.return = r, f.return = r, q.sibling = f, r.child = q, f = r.child, f.memoizedState = xp(l), f.childLanes = Sp(
        i,
        P,
        l
      ), r.memoizedState = yp, Yl(null, f)) : (Rr(r), bp(r, q));
    }
    var nt = i.memoizedState;
    if (nt !== null && (q = nt.dehydrated, q !== null)) {
      if (S)
        r.flags & 256 ? (Rr(r), r.flags &= -257, r = Mp(
          i,
          r,
          l
        )) : r.memoizedState !== null ? (Dr(), r.child = i.child, r.flags |= 128, r = null) : (Dr(), q = f.fallback, v = r.mode, f = Gu(
          { mode: "visible", children: f.children },
          v
        ), q = pa(
          q,
          v,
          l,
          null
        ), q.flags |= 2, f.return = r, q.return = r, f.sibling = q, r.child = f, Sa(
          r,
          i.child,
          null,
          l
        ), f = r.child, f.memoizedState = xp(l), f.childLanes = Sp(
          i,
          P,
          l
        ), r.memoizedState = yp, r = Yl(null, f));
      else if (Rr(r), im(q)) {
        if (P = q.nextSibling && q.nextSibling.dataset, P) var pt = P.dgst;
        P = pt, f = Error(s(419)), f.stack = "", f.digest = P, Ul({ value: f, source: null, stack: null }), r = Mp(
          i,
          r,
          l
        );
      } else if (Mn || uo(i, r, l, !1), P = (l & i.childLanes) !== 0, Mn || P) {
        if (P = tn, P !== null && (f = $a(P, l), f !== 0 && f !== nt.retryLane))
          throw nt.retryLane = f, ha(i, f), ui(P, i, f), vp;
        nm(q) || Ku(), r = Mp(
          i,
          r,
          l
        );
      } else
        nm(q) ? (r.flags |= 192, r.child = i.child, r = null) : (i = nt.treeContext, sn = Vi(
          q.nextSibling
        ), Vn = r, Le = !0, Mr = null, Fi = !1, i !== null && l_(r, i), r = bp(
          r,
          f.children
        ), r.flags |= 4096);
      return r;
    }
    return v ? (Dr(), q = f.fallback, v = r.mode, nt = i.child, pt = nt.sibling, f = Bs(nt, {
      mode: "hidden",
      children: f.children
    }), f.subtreeFlags = nt.subtreeFlags & 65011712, pt !== null ? q = Bs(
      pt,
      q
    ) : (q = pa(
      q,
      v,
      l,
      null
    ), q.flags |= 2), q.return = r, f.return = r, f.sibling = q, r.child = f, Yl(null, f), f = r.child, q = i.child.memoizedState, q === null ? q = xp(l) : (v = q.cachePool, v !== null ? (nt = Sn._currentValue, v = v.parent !== nt ? { parent: nt, pool: nt } : v) : v = p_(), q = {
      baseLanes: q.baseLanes | l,
      cachePool: v
    }), f.memoizedState = q, f.childLanes = Sp(
      i,
      P,
      l
    ), r.memoizedState = yp, Yl(i.child, f)) : (Rr(r), l = i.child, i = l.sibling, l = Bs(l, {
      mode: "visible",
      children: f.children
    }), l.return = r, l.sibling = null, i !== null && (P = r.deletions, P === null ? (r.deletions = [i], r.flags |= 16) : P.push(i)), r.child = l, r.memoizedState = null, l);
  }
  function bp(i, r) {
    return r = Gu(
      { mode: "visible", children: r },
      i.mode
    ), r.return = i, i.child = r;
  }
  function Gu(i, r) {
    return i = yi(22, i, null, r), i.lanes = 0, i;
  }
  function Mp(i, r, l) {
    return Sa(r, i.child, null, l), i = bp(
      r,
      r.pendingProps.children
    ), i.flags |= 2, r.memoizedState = null, i;
  }
  function Ty(i, r, l) {
    i.lanes |= r;
    var f = i.alternate;
    f !== null && (f.lanes |= r), zh(i.return, r, l);
  }
  function Ep(i, r, l, f, v, S) {
    var P = i.memoizedState;
    P === null ? i.memoizedState = {
      isBackwards: r,
      rendering: null,
      renderingStartTime: 0,
      last: f,
      tail: l,
      tailMode: v,
      treeForkCount: S
    } : (P.isBackwards = r, P.rendering = null, P.renderingStartTime = 0, P.last = f, P.tail = l, P.tailMode = v, P.treeForkCount = S);
  }
  function Cy(i, r, l) {
    var f = r.pendingProps, v = f.revealOrder, S = f.tail;
    f = f.children;
    var P = mn.current, q = (P & 2) !== 0;
    if (q ? (P = P & 1 | 2, r.flags |= 128) : P &= 1, et(mn, P), kn(i, r, f, l), f = Le ? Ll : 0, !q && i !== null && (i.flags & 128) !== 0)
      t: for (i = r.child; i !== null; ) {
        if (i.tag === 13)
          i.memoizedState !== null && Ty(i, l, r);
        else if (i.tag === 19)
          Ty(i, l, r);
        else if (i.child !== null) {
          i.child.return = i, i = i.child;
          continue;
        }
        if (i === r) break t;
        for (; i.sibling === null; ) {
          if (i.return === null || i.return === r)
            break t;
          i = i.return;
        }
        i.sibling.return = i.return, i = i.sibling;
      }
    switch (v) {
      case "forwards":
        for (l = r.child, v = null; l !== null; )
          i = l.alternate, i !== null && Du(i) === null && (v = l), l = l.sibling;
        l = v, l === null ? (v = r.child, r.child = null) : (v = l.sibling, l.sibling = null), Ep(
          r,
          !1,
          v,
          l,
          S,
          f
        );
        break;
      case "backwards":
      case "unstable_legacy-backwards":
        for (l = null, v = r.child, r.child = null; v !== null; ) {
          if (i = v.alternate, i !== null && Du(i) === null) {
            r.child = v;
            break;
          }
          i = v.sibling, v.sibling = l, l = v, v = i;
        }
        Ep(
          r,
          !0,
          l,
          null,
          S,
          f
        );
        break;
      case "together":
        Ep(
          r,
          !1,
          null,
          null,
          void 0,
          f
        );
        break;
      default:
        r.memoizedState = null;
    }
    return r.child;
  }
  function ks(i, r, l) {
    if (i !== null && (r.dependencies = i.dependencies), Lr |= r.lanes, (l & r.childLanes) === 0)
      if (i !== null) {
        if (uo(
          i,
          r,
          l,
          !1
        ), (l & r.childLanes) === 0)
          return null;
      } else return null;
    if (i !== null && r.child !== i.child)
      throw Error(s(153));
    if (r.child !== null) {
      for (i = r.child, l = Bs(i, i.pendingProps), r.child = l, l.return = r; i.sibling !== null; )
        i = i.sibling, l = l.sibling = Bs(i, i.pendingProps), l.return = r;
      l.sibling = null;
    }
    return r.child;
  }
  function wp(i, r) {
    return (i.lanes & r) !== 0 ? !0 : (i = i.dependencies, !!(i !== null && bu(i)));
  }
  function tT(i, r, l) {
    switch (r.tag) {
      case 3:
        J(r, r.stateNode.containerInfo), wr(r, Sn, i.memoizedState.cache), ma();
        break;
      case 27:
      case 5:
        dt(r);
        break;
      case 4:
        J(r, r.stateNode.containerInfo);
        break;
      case 10:
        wr(
          r,
          r.type,
          r.memoizedProps.value
        );
        break;
      case 31:
        if (r.memoizedState !== null)
          return r.flags |= 128, $h(r), null;
        break;
      case 13:
        var f = r.memoizedState;
        if (f !== null)
          return f.dehydrated !== null ? (Rr(r), r.flags |= 128, null) : (l & r.child.childLanes) !== 0 ? Ay(i, r, l) : (Rr(r), i = ks(
            i,
            r,
            l
          ), i !== null ? i.sibling : null);
        Rr(r);
        break;
      case 19:
        var v = (i.flags & 128) !== 0;
        if (f = (l & r.childLanes) !== 0, f || (uo(
          i,
          r,
          l,
          !1
        ), f = (l & r.childLanes) !== 0), v) {
          if (f)
            return Cy(
              i,
              r,
              l
            );
          r.flags |= 128;
        }
        if (v = r.memoizedState, v !== null && (v.rendering = null, v.tail = null, v.lastEffect = null), et(mn, mn.current), f) break;
        return null;
      case 22:
        return r.lanes = 0, xy(
          i,
          r,
          l,
          r.pendingProps
        );
      case 24:
        wr(r, Sn, i.memoizedState.cache);
    }
    return ks(i, r, l);
  }
  function Ry(i, r, l) {
    if (i !== null)
      if (i.memoizedProps !== r.pendingProps)
        Mn = !0;
      else {
        if (!wp(i, l) && (r.flags & 128) === 0)
          return Mn = !1, tT(
            i,
            r,
            l
          );
        Mn = (i.flags & 131072) !== 0;
      }
    else
      Mn = !1, Le && (r.flags & 1048576) !== 0 && o_(r, Ll, r.index);
    switch (r.lanes = 0, r.tag) {
      case 16:
        t: {
          var f = r.pendingProps;
          if (i = ya(r.elementType), r.type = i, typeof i == "function")
            Dh(i) ? (f = Ma(i, f), r.tag = 1, r = Ey(
              null,
              r,
              i,
              f,
              l
            )) : (r.tag = 0, r = _p(
              null,
              r,
              i,
              f,
              l
            ));
          else {
            if (i != null) {
              var v = i.$$typeof;
              if (v === M) {
                r.tag = 11, r = vy(
                  null,
                  r,
                  i,
                  f,
                  l
                );
                break t;
              } else if (v === D) {
                r.tag = 14, r = _y(
                  null,
                  r,
                  i,
                  f,
                  l
                );
                break t;
              }
            }
            throw r = U(i) || i, Error(s(306, r, ""));
          }
        }
        return r;
      case 0:
        return _p(
          i,
          r,
          r.type,
          r.pendingProps,
          l
        );
      case 1:
        return f = r.type, v = Ma(
          f,
          r.pendingProps
        ), Ey(
          i,
          r,
          f,
          v,
          l
        );
      case 3:
        t: {
          if (J(
            r,
            r.stateNode.containerInfo
          ), i === null) throw Error(s(387));
          f = r.pendingProps;
          var S = r.memoizedState;
          v = S.element, Wh(i, r), Vl(r, f, null, l);
          var P = r.memoizedState;
          if (f = P.cache, wr(r, Sn, f), f !== S.cache && Fh(
            r,
            [Sn],
            l,
            !0
          ), Hl(), f = P.element, S.isDehydrated)
            if (S = {
              element: f,
              isDehydrated: !1,
              cache: P.cache
            }, r.updateQueue.baseState = S, r.memoizedState = S, r.flags & 256) {
              r = wy(
                i,
                r,
                f,
                l
              );
              break t;
            } else if (f !== v) {
              v = Ii(
                Error(s(424)),
                r
              ), Ul(v), r = wy(
                i,
                r,
                f,
                l
              );
              break t;
            } else {
              switch (i = r.stateNode.containerInfo, i.nodeType) {
                case 9:
                  i = i.body;
                  break;
                default:
                  i = i.nodeName === "HTML" ? i.ownerDocument.body : i;
              }
              for (sn = Vi(i.firstChild), Vn = r, Le = !0, Mr = null, Fi = !0, l = x_(
                r,
                null,
                f,
                l
              ), r.child = l; l; )
                l.flags = l.flags & -3 | 4096, l = l.sibling;
            }
          else {
            if (ma(), f === v) {
              r = ks(
                i,
                r,
                l
              );
              break t;
            }
            kn(i, r, f, l);
          }
          r = r.child;
        }
        return r;
      case 26:
        return Vu(i, r), i === null ? (l = Hx(
          r.type,
          null,
          r.pendingProps,
          null
        )) ? r.memoizedState = l : Le || (l = r.type, i = r.pendingProps, f = rf(
          Y.current
        ).createElement(l), f[cn] = r, f[hn] = i, Xn(f, l, i), ot(f), r.stateNode = f) : r.memoizedState = Hx(
          r.type,
          i.memoizedProps,
          r.pendingProps,
          i.memoizedState
        ), null;
      case 27:
        return dt(r), i === null && Le && (f = r.stateNode = Bx(
          r.type,
          r.pendingProps,
          Y.current
        ), Vn = r, Fi = !0, v = sn, zr(r.type) ? (sm = v, sn = Vi(f.firstChild)) : sn = v), kn(
          i,
          r,
          r.pendingProps.children,
          l
        ), Vu(i, r), i === null && (r.flags |= 4194304), r.child;
      case 5:
        return i === null && Le && ((v = f = sn) && (f = DT(
          f,
          r.type,
          r.pendingProps,
          Fi
        ), f !== null ? (r.stateNode = f, Vn = r, sn = Vi(f.firstChild), Fi = !1, v = !0) : v = !1), v || Er(r)), dt(r), v = r.type, S = r.pendingProps, P = i !== null ? i.memoizedProps : null, f = S.children, Jp(v, S) ? f = null : P !== null && Jp(v, P) && (r.flags |= 32), r.memoizedState !== null && (v = Qh(
          i,
          r,
          WA,
          null,
          null,
          l
        ), oc._currentValue = v), Vu(i, r), kn(i, r, f, l), r.child;
      case 6:
        return i === null && Le && ((i = l = sn) && (l = NT(
          l,
          r.pendingProps,
          Fi
        ), l !== null ? (r.stateNode = l, Vn = r, sn = null, i = !0) : i = !1), i || Er(r)), null;
      case 13:
        return Ay(i, r, l);
      case 4:
        return J(
          r,
          r.stateNode.containerInfo
        ), f = r.pendingProps, i === null ? r.child = Sa(
          r,
          null,
          f,
          l
        ) : kn(i, r, f, l), r.child;
      case 11:
        return vy(
          i,
          r,
          r.type,
          r.pendingProps,
          l
        );
      case 7:
        return kn(
          i,
          r,
          r.pendingProps,
          l
        ), r.child;
      case 8:
        return kn(
          i,
          r,
          r.pendingProps.children,
          l
        ), r.child;
      case 12:
        return kn(
          i,
          r,
          r.pendingProps.children,
          l
        ), r.child;
      case 10:
        return f = r.pendingProps, wr(r, r.type, f.value), kn(i, r, f.children, l), r.child;
      case 9:
        return v = r.type._context, f = r.pendingProps.children, va(r), v = Gn(v), f = f(v), r.flags |= 1, kn(i, r, f, l), r.child;
      case 14:
        return _y(
          i,
          r,
          r.type,
          r.pendingProps,
          l
        );
      case 15:
        return yy(
          i,
          r,
          r.type,
          r.pendingProps,
          l
        );
      case 19:
        return Cy(i, r, l);
      case 31:
        return JA(i, r, l);
      case 22:
        return xy(
          i,
          r,
          l,
          r.pendingProps
        );
      case 24:
        return va(r), f = Gn(Sn), i === null ? (v = Gh(), v === null && (v = tn, S = Hh(), v.pooledCache = S, S.refCount++, S !== null && (v.pooledCacheLanes |= l), v = S), r.memoizedState = { parent: f, cache: v }, Xh(r), wr(r, Sn, v)) : ((i.lanes & l) !== 0 && (Wh(i, r), Vl(r, null, null, l), Hl()), v = i.memoizedState, S = r.memoizedState, v.parent !== f ? (v = { parent: f, cache: f }, r.memoizedState = v, r.lanes === 0 && (r.memoizedState = r.updateQueue.baseState = v), wr(r, Sn, f)) : (f = S.cache, wr(r, Sn, f), f !== v.cache && Fh(
          r,
          [Sn],
          l,
          !0
        ))), kn(
          i,
          r,
          r.pendingProps.children,
          l
        ), r.child;
      case 29:
        throw r.pendingProps;
    }
    throw Error(s(156, r.tag));
  }
  function Xs(i) {
    i.flags |= 4;
  }
  function Ap(i, r, l, f, v) {
    if ((r = (i.mode & 32) !== 0) && (r = !1), r) {
      if (i.flags |= 16777216, (v & 335544128) === v)
        if (i.stateNode.complete) i.flags |= 8192;
        else if (nx()) i.flags |= 8192;
        else
          throw xa = Au, kh;
    } else i.flags &= -16777217;
  }
  function Dy(i, r) {
    if (r.type !== "stylesheet" || (r.state.loading & 4) !== 0)
      i.flags &= -16777217;
    else if (i.flags |= 16777216, !Wx(r))
      if (nx()) i.flags |= 8192;
      else
        throw xa = Au, kh;
  }
  function ku(i, r) {
    r !== null && (i.flags |= 4), i.flags & 16384 && (r = i.tag !== 22 ? He() : 536870912, i.lanes |= r, Mo |= r);
  }
  function jl(i, r) {
    if (!Le)
      switch (i.tailMode) {
        case "hidden":
          r = i.tail;
          for (var l = null; r !== null; )
            r.alternate !== null && (l = r), r = r.sibling;
          l === null ? i.tail = null : l.sibling = null;
          break;
        case "collapsed":
          l = i.tail;
          for (var f = null; l !== null; )
            l.alternate !== null && (f = l), l = l.sibling;
          f === null ? r || i.tail === null ? i.tail = null : i.tail.sibling = null : f.sibling = null;
      }
  }
  function rn(i) {
    var r = i.alternate !== null && i.alternate.child === i.child, l = 0, f = 0;
    if (r)
      for (var v = i.child; v !== null; )
        l |= v.lanes | v.childLanes, f |= v.subtreeFlags & 65011712, f |= v.flags & 65011712, v.return = i, v = v.sibling;
    else
      for (v = i.child; v !== null; )
        l |= v.lanes | v.childLanes, f |= v.subtreeFlags, f |= v.flags, v.return = i, v = v.sibling;
    return i.subtreeFlags |= f, i.childLanes = l, r;
  }
  function eT(i, r, l) {
    var f = r.pendingProps;
    switch (Uh(r), r.tag) {
      case 16:
      case 15:
      case 0:
      case 11:
      case 7:
      case 8:
      case 12:
      case 9:
      case 14:
        return rn(r), null;
      case 1:
        return rn(r), null;
      case 3:
        return l = r.stateNode, f = null, i !== null && (f = i.memoizedState.cache), r.memoizedState.cache !== f && (r.flags |= 2048), Hs(Sn), rt(), l.pendingContext && (l.context = l.pendingContext, l.pendingContext = null), (i === null || i.child === null) && (co(r) ? Xs(r) : i === null || i.memoizedState.isDehydrated && (r.flags & 256) === 0 || (r.flags |= 1024, Ih())), rn(r), null;
      case 26:
        var v = r.type, S = r.memoizedState;
        return i === null ? (Xs(r), S !== null ? (rn(r), Dy(r, S)) : (rn(r), Ap(
          r,
          v,
          null,
          f,
          l
        ))) : S ? S !== i.memoizedState ? (Xs(r), rn(r), Dy(r, S)) : (rn(r), r.flags &= -16777217) : (i = i.memoizedProps, i !== f && Xs(r), rn(r), Ap(
          r,
          v,
          i,
          f,
          l
        )), null;
      case 27:
        if (yt(r), l = Y.current, v = r.type, i !== null && r.stateNode != null)
          i.memoizedProps !== f && Xs(r);
        else {
          if (!f) {
            if (r.stateNode === null)
              throw Error(s(166));
            return rn(r), null;
          }
          i = $.current, co(r) ? c_(r) : (i = Bx(v, f, l), r.stateNode = i, Xs(r));
        }
        return rn(r), null;
      case 5:
        if (yt(r), v = r.type, i !== null && r.stateNode != null)
          i.memoizedProps !== f && Xs(r);
        else {
          if (!f) {
            if (r.stateNode === null)
              throw Error(s(166));
            return rn(r), null;
          }
          if (S = $.current, co(r))
            c_(r);
          else {
            var P = rf(
              Y.current
            );
            switch (S) {
              case 1:
                S = P.createElementNS(
                  "http://www.w3.org/2000/svg",
                  v
                );
                break;
              case 2:
                S = P.createElementNS(
                  "http://www.w3.org/1998/Math/MathML",
                  v
                );
                break;
              default:
                switch (v) {
                  case "svg":
                    S = P.createElementNS(
                      "http://www.w3.org/2000/svg",
                      v
                    );
                    break;
                  case "math":
                    S = P.createElementNS(
                      "http://www.w3.org/1998/Math/MathML",
                      v
                    );
                    break;
                  case "script":
                    S = P.createElement("div"), S.innerHTML = "<script><\/script>", S = S.removeChild(
                      S.firstChild
                    );
                    break;
                  case "select":
                    S = typeof f.is == "string" ? P.createElement("select", {
                      is: f.is
                    }) : P.createElement("select"), f.multiple ? S.multiple = !0 : f.size && (S.size = f.size);
                    break;
                  default:
                    S = typeof f.is == "string" ? P.createElement(v, { is: f.is }) : P.createElement(v);
                }
            }
            S[cn] = r, S[hn] = f;
            t: for (P = r.child; P !== null; ) {
              if (P.tag === 5 || P.tag === 6)
                S.appendChild(P.stateNode);
              else if (P.tag !== 4 && P.tag !== 27 && P.child !== null) {
                P.child.return = P, P = P.child;
                continue;
              }
              if (P === r) break t;
              for (; P.sibling === null; ) {
                if (P.return === null || P.return === r)
                  break t;
                P = P.return;
              }
              P.sibling.return = P.return, P = P.sibling;
            }
            r.stateNode = S;
            t: switch (Xn(S, v, f), v) {
              case "button":
              case "input":
              case "select":
              case "textarea":
                f = !!f.autoFocus;
                break t;
              case "img":
                f = !0;
                break t;
              default:
                f = !1;
            }
            f && Xs(r);
          }
        }
        return rn(r), Ap(
          r,
          r.type,
          i === null ? null : i.memoizedProps,
          r.pendingProps,
          l
        ), null;
      case 6:
        if (i && r.stateNode != null)
          i.memoizedProps !== f && Xs(r);
        else {
          if (typeof f != "string" && r.stateNode === null)
            throw Error(s(166));
          if (i = Y.current, co(r)) {
            if (i = r.stateNode, l = r.memoizedProps, f = null, v = Vn, v !== null)
              switch (v.tag) {
                case 27:
                case 5:
                  f = v.memoizedProps;
              }
            i[cn] = r, i = !!(i.nodeValue === l || f !== null && f.suppressHydrationWarning === !0 || Ax(i.nodeValue, l)), i || Er(r, !0);
          } else
            i = rf(i).createTextNode(
              f
            ), i[cn] = r, r.stateNode = i;
        }
        return rn(r), null;
      case 31:
        if (l = r.memoizedState, i === null || i.memoizedState !== null) {
          if (f = co(r), l !== null) {
            if (i === null) {
              if (!f) throw Error(s(318));
              if (i = r.memoizedState, i = i !== null ? i.dehydrated : null, !i) throw Error(s(557));
              i[cn] = r;
            } else
              ma(), (r.flags & 128) === 0 && (r.memoizedState = null), r.flags |= 4;
            rn(r), i = !1;
          } else
            l = Ih(), i !== null && i.memoizedState !== null && (i.memoizedState.hydrationErrors = l), i = !0;
          if (!i)
            return r.flags & 256 ? (Si(r), r) : (Si(r), null);
          if ((r.flags & 128) !== 0)
            throw Error(s(558));
        }
        return rn(r), null;
      case 13:
        if (f = r.memoizedState, i === null || i.memoizedState !== null && i.memoizedState.dehydrated !== null) {
          if (v = co(r), f !== null && f.dehydrated !== null) {
            if (i === null) {
              if (!v) throw Error(s(318));
              if (v = r.memoizedState, v = v !== null ? v.dehydrated : null, !v) throw Error(s(317));
              v[cn] = r;
            } else
              ma(), (r.flags & 128) === 0 && (r.memoizedState = null), r.flags |= 4;
            rn(r), v = !1;
          } else
            v = Ih(), i !== null && i.memoizedState !== null && (i.memoizedState.hydrationErrors = v), v = !0;
          if (!v)
            return r.flags & 256 ? (Si(r), r) : (Si(r), null);
        }
        return Si(r), (r.flags & 128) !== 0 ? (r.lanes = l, r) : (l = f !== null, i = i !== null && i.memoizedState !== null, l && (f = r.child, v = null, f.alternate !== null && f.alternate.memoizedState !== null && f.alternate.memoizedState.cachePool !== null && (v = f.alternate.memoizedState.cachePool.pool), S = null, f.memoizedState !== null && f.memoizedState.cachePool !== null && (S = f.memoizedState.cachePool.pool), S !== v && (f.flags |= 2048)), l !== i && l && (r.child.flags |= 8192), ku(r, r.updateQueue), rn(r), null);
      case 4:
        return rt(), i === null && qp(r.stateNode.containerInfo), rn(r), null;
      case 10:
        return Hs(r.type), rn(r), null;
      case 19:
        if (W(mn), f = r.memoizedState, f === null) return rn(r), null;
        if (v = (r.flags & 128) !== 0, S = f.rendering, S === null)
          if (v) jl(f, !1);
          else {
            if (fn !== 0 || i !== null && (i.flags & 128) !== 0)
              for (i = r.child; i !== null; ) {
                if (S = Du(i), S !== null) {
                  for (r.flags |= 128, jl(f, !1), i = S.updateQueue, r.updateQueue = i, ku(r, i), r.subtreeFlags = 0, i = l, l = r.child; l !== null; )
                    s_(l, i), l = l.sibling;
                  return et(
                    mn,
                    mn.current & 1 | 2
                  ), Le && zs(r, f.treeForkCount), r.child;
                }
                i = i.sibling;
              }
            f.tail !== null && G() > qu && (r.flags |= 128, v = !0, jl(f, !1), r.lanes = 4194304);
          }
        else {
          if (!v)
            if (i = Du(S), i !== null) {
              if (r.flags |= 128, v = !0, i = i.updateQueue, r.updateQueue = i, ku(r, i), jl(f, !0), f.tail === null && f.tailMode === "hidden" && !S.alternate && !Le)
                return rn(r), null;
            } else
              2 * G() - f.renderingStartTime > qu && l !== 536870912 && (r.flags |= 128, v = !0, jl(f, !1), r.lanes = 4194304);
          f.isBackwards ? (S.sibling = r.child, r.child = S) : (i = f.last, i !== null ? i.sibling = S : r.child = S, f.last = S);
        }
        return f.tail !== null ? (i = f.tail, f.rendering = i, f.tail = i.sibling, f.renderingStartTime = G(), i.sibling = null, l = mn.current, et(
          mn,
          v ? l & 1 | 2 : l & 1
        ), Le && zs(r, f.treeForkCount), i) : (rn(r), null);
      case 22:
      case 23:
        return Si(r), Zh(), f = r.memoizedState !== null, i !== null ? i.memoizedState !== null !== f && (r.flags |= 8192) : f && (r.flags |= 8192), f ? (l & 536870912) !== 0 && (r.flags & 128) === 0 && (rn(r), r.subtreeFlags & 6 && (r.flags |= 8192)) : rn(r), l = r.updateQueue, l !== null && ku(r, l.retryQueue), l = null, i !== null && i.memoizedState !== null && i.memoizedState.cachePool !== null && (l = i.memoizedState.cachePool.pool), f = null, r.memoizedState !== null && r.memoizedState.cachePool !== null && (f = r.memoizedState.cachePool.pool), f !== l && (r.flags |= 2048), i !== null && W(_a), null;
      case 24:
        return l = null, i !== null && (l = i.memoizedState.cache), r.memoizedState.cache !== l && (r.flags |= 2048), Hs(Sn), rn(r), null;
      case 25:
        return null;
      case 30:
        return null;
    }
    throw Error(s(156, r.tag));
  }
  function nT(i, r) {
    switch (Uh(r), r.tag) {
      case 1:
        return i = r.flags, i & 65536 ? (r.flags = i & -65537 | 128, r) : null;
      case 3:
        return Hs(Sn), rt(), i = r.flags, (i & 65536) !== 0 && (i & 128) === 0 ? (r.flags = i & -65537 | 128, r) : null;
      case 26:
      case 27:
      case 5:
        return yt(r), null;
      case 31:
        if (r.memoizedState !== null) {
          if (Si(r), r.alternate === null)
            throw Error(s(340));
          ma();
        }
        return i = r.flags, i & 65536 ? (r.flags = i & -65537 | 128, r) : null;
      case 13:
        if (Si(r), i = r.memoizedState, i !== null && i.dehydrated !== null) {
          if (r.alternate === null)
            throw Error(s(340));
          ma();
        }
        return i = r.flags, i & 65536 ? (r.flags = i & -65537 | 128, r) : null;
      case 19:
        return W(mn), null;
      case 4:
        return rt(), null;
      case 10:
        return Hs(r.type), null;
      case 22:
      case 23:
        return Si(r), Zh(), i !== null && W(_a), i = r.flags, i & 65536 ? (r.flags = i & -65537 | 128, r) : null;
      case 24:
        return Hs(Sn), null;
      case 25:
        return null;
      default:
        return null;
    }
  }
  function Ny(i, r) {
    switch (Uh(r), r.tag) {
      case 3:
        Hs(Sn), rt();
        break;
      case 26:
      case 27:
      case 5:
        yt(r);
        break;
      case 4:
        rt();
        break;
      case 31:
        r.memoizedState !== null && Si(r);
        break;
      case 13:
        Si(r);
        break;
      case 19:
        W(mn);
        break;
      case 10:
        Hs(r.type);
        break;
      case 22:
      case 23:
        Si(r), Zh(), i !== null && W(_a);
        break;
      case 24:
        Hs(Sn);
    }
  }
  function ql(i, r) {
    try {
      var l = r.updateQueue, f = l !== null ? l.lastEffect : null;
      if (f !== null) {
        var v = f.next;
        l = v;
        do {
          if ((l.tag & i) === i) {
            f = void 0;
            var S = l.create, P = l.inst;
            f = S(), P.destroy = f;
          }
          l = l.next;
        } while (l !== v);
      }
    } catch (q) {
      Xe(r, r.return, q);
    }
  }
  function Nr(i, r, l) {
    try {
      var f = r.updateQueue, v = f !== null ? f.lastEffect : null;
      if (v !== null) {
        var S = v.next;
        f = S;
        do {
          if ((f.tag & i) === i) {
            var P = f.inst, q = P.destroy;
            if (q !== void 0) {
              P.destroy = void 0, v = r;
              var nt = l, pt = q;
              try {
                pt();
              } catch (wt) {
                Xe(
                  v,
                  nt,
                  wt
                );
              }
            }
          }
          f = f.next;
        } while (f !== S);
      }
    } catch (wt) {
      Xe(r, r.return, wt);
    }
  }
  function Oy(i) {
    var r = i.updateQueue;
    if (r !== null) {
      var l = i.stateNode;
      try {
        b_(r, l);
      } catch (f) {
        Xe(i, i.return, f);
      }
    }
  }
  function Ly(i, r, l) {
    l.props = Ma(
      i.type,
      i.memoizedProps
    ), l.state = i.memoizedState;
    try {
      l.componentWillUnmount();
    } catch (f) {
      Xe(i, r, f);
    }
  }
  function Zl(i, r) {
    try {
      var l = i.ref;
      if (l !== null) {
        switch (i.tag) {
          case 26:
          case 27:
          case 5:
            var f = i.stateNode;
            break;
          case 30:
            f = i.stateNode;
            break;
          default:
            f = i.stateNode;
        }
        typeof l == "function" ? i.refCleanup = l(f) : l.current = f;
      }
    } catch (v) {
      Xe(i, r, v);
    }
  }
  function ps(i, r) {
    var l = i.ref, f = i.refCleanup;
    if (l !== null)
      if (typeof f == "function")
        try {
          f();
        } catch (v) {
          Xe(i, r, v);
        } finally {
          i.refCleanup = null, i = i.alternate, i != null && (i.refCleanup = null);
        }
      else if (typeof l == "function")
        try {
          l(null);
        } catch (v) {
          Xe(i, r, v);
        }
      else l.current = null;
  }
  function Uy(i) {
    var r = i.type, l = i.memoizedProps, f = i.stateNode;
    try {
      t: switch (r) {
        case "button":
        case "input":
        case "select":
        case "textarea":
          l.autoFocus && f.focus();
          break t;
        case "img":
          l.src ? f.src = l.src : l.srcSet && (f.srcset = l.srcSet);
      }
    } catch (v) {
      Xe(i, i.return, v);
    }
  }
  function Tp(i, r, l) {
    try {
      var f = i.stateNode;
      ET(f, i.type, l, r), f[hn] = r;
    } catch (v) {
      Xe(i, i.return, v);
    }
  }
  function Py(i) {
    return i.tag === 5 || i.tag === 3 || i.tag === 26 || i.tag === 27 && zr(i.type) || i.tag === 4;
  }
  function Cp(i) {
    t: for (; ; ) {
      for (; i.sibling === null; ) {
        if (i.return === null || Py(i.return)) return null;
        i = i.return;
      }
      for (i.sibling.return = i.return, i = i.sibling; i.tag !== 5 && i.tag !== 6 && i.tag !== 18; ) {
        if (i.tag === 27 && zr(i.type) || i.flags & 2 || i.child === null || i.tag === 4) continue t;
        i.child.return = i, i = i.child;
      }
      if (!(i.flags & 2)) return i.stateNode;
    }
  }
  function Rp(i, r, l) {
    var f = i.tag;
    if (f === 5 || f === 6)
      i = i.stateNode, r ? (l.nodeType === 9 ? l.body : l.nodeName === "HTML" ? l.ownerDocument.body : l).insertBefore(i, r) : (r = l.nodeType === 9 ? l.body : l.nodeName === "HTML" ? l.ownerDocument.body : l, r.appendChild(i), l = l._reactRootContainer, l != null || r.onclick !== null || (r.onclick = Ps));
    else if (f !== 4 && (f === 27 && zr(i.type) && (l = i.stateNode, r = null), i = i.child, i !== null))
      for (Rp(i, r, l), i = i.sibling; i !== null; )
        Rp(i, r, l), i = i.sibling;
  }
  function Xu(i, r, l) {
    var f = i.tag;
    if (f === 5 || f === 6)
      i = i.stateNode, r ? l.insertBefore(i, r) : l.appendChild(i);
    else if (f !== 4 && (f === 27 && zr(i.type) && (l = i.stateNode), i = i.child, i !== null))
      for (Xu(i, r, l), i = i.sibling; i !== null; )
        Xu(i, r, l), i = i.sibling;
  }
  function Iy(i) {
    var r = i.stateNode, l = i.memoizedProps;
    try {
      for (var f = i.type, v = r.attributes; v.length; )
        r.removeAttributeNode(v[0]);
      Xn(r, f, l), r[cn] = i, r[hn] = l;
    } catch (S) {
      Xe(i, i.return, S);
    }
  }
  var Ws = !1, En = !1, Dp = !1, By = typeof WeakSet == "function" ? WeakSet : Set, Bn = null;
  function iT(i, r) {
    if (i = i.containerInfo, Kp = df, i = Zv(i), Mh(i)) {
      if ("selectionStart" in i)
        var l = {
          start: i.selectionStart,
          end: i.selectionEnd
        };
      else
        t: {
          l = (l = i.ownerDocument) && l.defaultView || window;
          var f = l.getSelection && l.getSelection();
          if (f && f.rangeCount !== 0) {
            l = f.anchorNode;
            var v = f.anchorOffset, S = f.focusNode;
            f = f.focusOffset;
            try {
              l.nodeType, S.nodeType;
            } catch {
              l = null;
              break t;
            }
            var P = 0, q = -1, nt = -1, pt = 0, wt = 0, Ct = i, gt = null;
            e: for (; ; ) {
              for (var St; Ct !== l || v !== 0 && Ct.nodeType !== 3 || (q = P + v), Ct !== S || f !== 0 && Ct.nodeType !== 3 || (nt = P + f), Ct.nodeType === 3 && (P += Ct.nodeValue.length), (St = Ct.firstChild) !== null; )
                gt = Ct, Ct = St;
              for (; ; ) {
                if (Ct === i) break e;
                if (gt === l && ++pt === v && (q = P), gt === S && ++wt === f && (nt = P), (St = Ct.nextSibling) !== null) break;
                Ct = gt, gt = Ct.parentNode;
              }
              Ct = St;
            }
            l = q === -1 || nt === -1 ? null : { start: q, end: nt };
          } else l = null;
        }
      l = l || { start: 0, end: 0 };
    } else l = null;
    for (Qp = { focusedElem: i, selectionRange: l }, df = !1, Bn = r; Bn !== null; )
      if (r = Bn, i = r.child, (r.subtreeFlags & 1028) !== 0 && i !== null)
        i.return = r, Bn = i;
      else
        for (; Bn !== null; ) {
          switch (r = Bn, S = r.alternate, i = r.flags, r.tag) {
            case 0:
              if ((i & 4) !== 0 && (i = r.updateQueue, i = i !== null ? i.events : null, i !== null))
                for (l = 0; l < i.length; l++)
                  v = i[l], v.ref.impl = v.nextImpl;
              break;
            case 11:
            case 15:
              break;
            case 1:
              if ((i & 1024) !== 0 && S !== null) {
                i = void 0, l = r, v = S.memoizedProps, S = S.memoizedState, f = l.stateNode;
                try {
                  var ee = Ma(
                    l.type,
                    v
                  );
                  i = f.getSnapshotBeforeUpdate(
                    ee,
                    S
                  ), f.__reactInternalSnapshotBeforeUpdate = i;
                } catch (ce) {
                  Xe(
                    l,
                    l.return,
                    ce
                  );
                }
              }
              break;
            case 3:
              if ((i & 1024) !== 0) {
                if (i = r.stateNode.containerInfo, l = i.nodeType, l === 9)
                  em(i);
                else if (l === 1)
                  switch (i.nodeName) {
                    case "HEAD":
                    case "HTML":
                    case "BODY":
                      em(i);
                      break;
                    default:
                      i.textContent = "";
                  }
              }
              break;
            case 5:
            case 26:
            case 27:
            case 6:
            case 4:
            case 17:
              break;
            default:
              if ((i & 1024) !== 0) throw Error(s(163));
          }
          if (i = r.sibling, i !== null) {
            i.return = r.return, Bn = i;
            break;
          }
          Bn = r.return;
        }
  }
  function zy(i, r, l) {
    var f = l.flags;
    switch (l.tag) {
      case 0:
      case 11:
      case 15:
        js(i, l), f & 4 && ql(5, l);
        break;
      case 1:
        if (js(i, l), f & 4)
          if (i = l.stateNode, r === null)
            try {
              i.componentDidMount();
            } catch (P) {
              Xe(l, l.return, P);
            }
          else {
            var v = Ma(
              l.type,
              r.memoizedProps
            );
            r = r.memoizedState;
            try {
              i.componentDidUpdate(
                v,
                r,
                i.__reactInternalSnapshotBeforeUpdate
              );
            } catch (P) {
              Xe(
                l,
                l.return,
                P
              );
            }
          }
        f & 64 && Oy(l), f & 512 && Zl(l, l.return);
        break;
      case 3:
        if (js(i, l), f & 64 && (i = l.updateQueue, i !== null)) {
          if (r = null, l.child !== null)
            switch (l.child.tag) {
              case 27:
              case 5:
                r = l.child.stateNode;
                break;
              case 1:
                r = l.child.stateNode;
            }
          try {
            b_(i, r);
          } catch (P) {
            Xe(l, l.return, P);
          }
        }
        break;
      case 27:
        r === null && f & 4 && Iy(l);
      case 26:
      case 5:
        js(i, l), r === null && f & 4 && Uy(l), f & 512 && Zl(l, l.return);
        break;
      case 12:
        js(i, l);
        break;
      case 31:
        js(i, l), f & 4 && Vy(i, l);
        break;
      case 13:
        js(i, l), f & 4 && Gy(i, l), f & 64 && (i = l.memoizedState, i !== null && (i = i.dehydrated, i !== null && (l = dT.bind(
          null,
          l
        ), OT(i, l))));
        break;
      case 22:
        if (f = l.memoizedState !== null || Ws, !f) {
          r = r !== null && r.memoizedState !== null || En, v = Ws;
          var S = En;
          Ws = f, (En = r) && !S ? qs(
            i,
            l,
            (l.subtreeFlags & 8772) !== 0
          ) : js(i, l), Ws = v, En = S;
        }
        break;
      case 30:
        break;
      default:
        js(i, l);
    }
  }
  function Fy(i) {
    var r = i.alternate;
    r !== null && (i.alternate = null, Fy(r)), i.child = null, i.deletions = null, i.sibling = null, i.tag === 5 && (r = i.stateNode, r !== null && ca(r)), i.stateNode = null, i.return = null, i.dependencies = null, i.memoizedProps = null, i.memoizedState = null, i.pendingProps = null, i.stateNode = null, i.updateQueue = null;
  }
  var an = null, ai = !1;
  function Ys(i, r, l) {
    for (l = l.child; l !== null; )
      Hy(i, r, l), l = l.sibling;
  }
  function Hy(i, r, l) {
    if (Dt && typeof Dt.onCommitFiberUnmount == "function")
      try {
        Dt.onCommitFiberUnmount(Ot, l);
      } catch {
      }
    switch (l.tag) {
      case 26:
        En || ps(l, r), Ys(
          i,
          r,
          l
        ), l.memoizedState ? l.memoizedState.count-- : l.stateNode && (l = l.stateNode, l.parentNode.removeChild(l));
        break;
      case 27:
        En || ps(l, r);
        var f = an, v = ai;
        zr(l.type) && (an = l.stateNode, ai = !1), Ys(
          i,
          r,
          l
        ), sc(l.stateNode), an = f, ai = v;
        break;
      case 5:
        En || ps(l, r);
      case 6:
        if (f = an, v = ai, an = null, Ys(
          i,
          r,
          l
        ), an = f, ai = v, an !== null)
          if (ai)
            try {
              (an.nodeType === 9 ? an.body : an.nodeName === "HTML" ? an.ownerDocument.body : an).removeChild(l.stateNode);
            } catch (S) {
              Xe(
                l,
                r,
                S
              );
            }
          else
            try {
              an.removeChild(l.stateNode);
            } catch (S) {
              Xe(
                l,
                r,
                S
              );
            }
        break;
      case 18:
        an !== null && (ai ? (i = an, Ox(
          i.nodeType === 9 ? i.body : i.nodeName === "HTML" ? i.ownerDocument.body : i,
          l.stateNode
        ), No(i)) : Ox(an, l.stateNode));
        break;
      case 4:
        f = an, v = ai, an = l.stateNode.containerInfo, ai = !0, Ys(
          i,
          r,
          l
        ), an = f, ai = v;
        break;
      case 0:
      case 11:
      case 14:
      case 15:
        Nr(2, l, r), En || Nr(4, l, r), Ys(
          i,
          r,
          l
        );
        break;
      case 1:
        En || (ps(l, r), f = l.stateNode, typeof f.componentWillUnmount == "function" && Ly(
          l,
          r,
          f
        )), Ys(
          i,
          r,
          l
        );
        break;
      case 21:
        Ys(
          i,
          r,
          l
        );
        break;
      case 22:
        En = (f = En) || l.memoizedState !== null, Ys(
          i,
          r,
          l
        ), En = f;
        break;
      default:
        Ys(
          i,
          r,
          l
        );
    }
  }
  function Vy(i, r) {
    if (r.memoizedState === null && (i = r.alternate, i !== null && (i = i.memoizedState, i !== null))) {
      i = i.dehydrated;
      try {
        No(i);
      } catch (l) {
        Xe(r, r.return, l);
      }
    }
  }
  function Gy(i, r) {
    if (r.memoizedState === null && (i = r.alternate, i !== null && (i = i.memoizedState, i !== null && (i = i.dehydrated, i !== null))))
      try {
        No(i);
      } catch (l) {
        Xe(r, r.return, l);
      }
  }
  function sT(i) {
    switch (i.tag) {
      case 31:
      case 13:
      case 19:
        var r = i.stateNode;
        return r === null && (r = i.stateNode = new By()), r;
      case 22:
        return i = i.stateNode, r = i._retryCache, r === null && (r = i._retryCache = new By()), r;
      default:
        throw Error(s(435, i.tag));
    }
  }
  function Wu(i, r) {
    var l = sT(i);
    r.forEach(function(f) {
      if (!l.has(f)) {
        l.add(f);
        var v = hT.bind(null, i, f);
        f.then(v, v);
      }
    });
  }
  function oi(i, r) {
    var l = r.deletions;
    if (l !== null)
      for (var f = 0; f < l.length; f++) {
        var v = l[f], S = i, P = r, q = P;
        t: for (; q !== null; ) {
          switch (q.tag) {
            case 27:
              if (zr(q.type)) {
                an = q.stateNode, ai = !1;
                break t;
              }
              break;
            case 5:
              an = q.stateNode, ai = !1;
              break t;
            case 3:
            case 4:
              an = q.stateNode.containerInfo, ai = !0;
              break t;
          }
          q = q.return;
        }
        if (an === null) throw Error(s(160));
        Hy(S, P, v), an = null, ai = !1, S = v.alternate, S !== null && (S.return = null), v.return = null;
      }
    if (r.subtreeFlags & 13886)
      for (r = r.child; r !== null; )
        ky(r, i), r = r.sibling;
  }
  var Zi = null;
  function ky(i, r) {
    var l = i.alternate, f = i.flags;
    switch (i.tag) {
      case 0:
      case 11:
      case 14:
      case 15:
        oi(r, i), li(i), f & 4 && (Nr(3, i, i.return), ql(3, i), Nr(5, i, i.return));
        break;
      case 1:
        oi(r, i), li(i), f & 512 && (En || l === null || ps(l, l.return)), f & 64 && Ws && (i = i.updateQueue, i !== null && (f = i.callbacks, f !== null && (l = i.shared.hiddenCallbacks, i.shared.hiddenCallbacks = l === null ? f : l.concat(f))));
        break;
      case 26:
        var v = Zi;
        if (oi(r, i), li(i), f & 512 && (En || l === null || ps(l, l.return)), f & 4) {
          var S = l !== null ? l.memoizedState : null;
          if (f = i.memoizedState, l === null)
            if (f === null)
              if (i.stateNode === null) {
                t: {
                  f = i.type, l = i.memoizedProps, v = v.ownerDocument || v;
                  e: switch (f) {
                    case "title":
                      S = v.getElementsByTagName("title")[0], (!S || S[Ls] || S[cn] || S.namespaceURI === "http://www.w3.org/2000/svg" || S.hasAttribute("itemprop")) && (S = v.createElement(f), v.head.insertBefore(
                        S,
                        v.querySelector("head > title")
                      )), Xn(S, f, l), S[cn] = i, ot(S), f = S;
                      break t;
                    case "link":
                      var P = kx(
                        "link",
                        "href",
                        v
                      ).get(f + (l.href || ""));
                      if (P) {
                        for (var q = 0; q < P.length; q++)
                          if (S = P[q], S.getAttribute("href") === (l.href == null || l.href === "" ? null : l.href) && S.getAttribute("rel") === (l.rel == null ? null : l.rel) && S.getAttribute("title") === (l.title == null ? null : l.title) && S.getAttribute("crossorigin") === (l.crossOrigin == null ? null : l.crossOrigin)) {
                            P.splice(q, 1);
                            break e;
                          }
                      }
                      S = v.createElement(f), Xn(S, f, l), v.head.appendChild(S);
                      break;
                    case "meta":
                      if (P = kx(
                        "meta",
                        "content",
                        v
                      ).get(f + (l.content || ""))) {
                        for (q = 0; q < P.length; q++)
                          if (S = P[q], S.getAttribute("content") === (l.content == null ? null : "" + l.content) && S.getAttribute("name") === (l.name == null ? null : l.name) && S.getAttribute("property") === (l.property == null ? null : l.property) && S.getAttribute("http-equiv") === (l.httpEquiv == null ? null : l.httpEquiv) && S.getAttribute("charset") === (l.charSet == null ? null : l.charSet)) {
                            P.splice(q, 1);
                            break e;
                          }
                      }
                      S = v.createElement(f), Xn(S, f, l), v.head.appendChild(S);
                      break;
                    default:
                      throw Error(s(468, f));
                  }
                  S[cn] = i, ot(S), f = S;
                }
                i.stateNode = f;
              } else
                Xx(
                  v,
                  i.type,
                  i.stateNode
                );
            else
              i.stateNode = Gx(
                v,
                f,
                i.memoizedProps
              );
          else
            S !== f ? (S === null ? l.stateNode !== null && (l = l.stateNode, l.parentNode.removeChild(l)) : S.count--, f === null ? Xx(
              v,
              i.type,
              i.stateNode
            ) : Gx(
              v,
              f,
              i.memoizedProps
            )) : f === null && i.stateNode !== null && Tp(
              i,
              i.memoizedProps,
              l.memoizedProps
            );
        }
        break;
      case 27:
        oi(r, i), li(i), f & 512 && (En || l === null || ps(l, l.return)), l !== null && f & 4 && Tp(
          i,
          i.memoizedProps,
          l.memoizedProps
        );
        break;
      case 5:
        if (oi(r, i), li(i), f & 512 && (En || l === null || ps(l, l.return)), i.flags & 32) {
          v = i.stateNode;
          try {
            ei(v, "");
          } catch (ee) {
            Xe(i, i.return, ee);
          }
        }
        f & 4 && i.stateNode != null && (v = i.memoizedProps, Tp(
          i,
          v,
          l !== null ? l.memoizedProps : v
        )), f & 1024 && (Dp = !0);
        break;
      case 6:
        if (oi(r, i), li(i), f & 4) {
          if (i.stateNode === null)
            throw Error(s(162));
          f = i.memoizedProps, l = i.stateNode;
          try {
            l.nodeValue = f;
          } catch (ee) {
            Xe(i, i.return, ee);
          }
        }
        break;
      case 3:
        if (lf = null, v = Zi, Zi = af(r.containerInfo), oi(r, i), Zi = v, li(i), f & 4 && l !== null && l.memoizedState.isDehydrated)
          try {
            No(r.containerInfo);
          } catch (ee) {
            Xe(i, i.return, ee);
          }
        Dp && (Dp = !1, Xy(i));
        break;
      case 4:
        f = Zi, Zi = af(
          i.stateNode.containerInfo
        ), oi(r, i), li(i), Zi = f;
        break;
      case 12:
        oi(r, i), li(i);
        break;
      case 31:
        oi(r, i), li(i), f & 4 && (f = i.updateQueue, f !== null && (i.updateQueue = null, Wu(i, f)));
        break;
      case 13:
        oi(r, i), li(i), i.child.flags & 8192 && i.memoizedState !== null != (l !== null && l.memoizedState !== null) && (ju = G()), f & 4 && (f = i.updateQueue, f !== null && (i.updateQueue = null, Wu(i, f)));
        break;
      case 22:
        v = i.memoizedState !== null;
        var nt = l !== null && l.memoizedState !== null, pt = Ws, wt = En;
        if (Ws = pt || v, En = wt || nt, oi(r, i), En = wt, Ws = pt, li(i), f & 8192)
          t: for (r = i.stateNode, r._visibility = v ? r._visibility & -2 : r._visibility | 1, v && (l === null || nt || Ws || En || Ea(i)), l = null, r = i; ; ) {
            if (r.tag === 5 || r.tag === 26) {
              if (l === null) {
                nt = l = r;
                try {
                  if (S = nt.stateNode, v)
                    P = S.style, typeof P.setProperty == "function" ? P.setProperty("display", "none", "important") : P.display = "none";
                  else {
                    q = nt.stateNode;
                    var Ct = nt.memoizedProps.style, gt = Ct != null && Ct.hasOwnProperty("display") ? Ct.display : null;
                    q.style.display = gt == null || typeof gt == "boolean" ? "" : ("" + gt).trim();
                  }
                } catch (ee) {
                  Xe(nt, nt.return, ee);
                }
              }
            } else if (r.tag === 6) {
              if (l === null) {
                nt = r;
                try {
                  nt.stateNode.nodeValue = v ? "" : nt.memoizedProps;
                } catch (ee) {
                  Xe(nt, nt.return, ee);
                }
              }
            } else if (r.tag === 18) {
              if (l === null) {
                nt = r;
                try {
                  var St = nt.stateNode;
                  v ? Lx(St, !0) : Lx(nt.stateNode, !1);
                } catch (ee) {
                  Xe(nt, nt.return, ee);
                }
              }
            } else if ((r.tag !== 22 && r.tag !== 23 || r.memoizedState === null || r === i) && r.child !== null) {
              r.child.return = r, r = r.child;
              continue;
            }
            if (r === i) break t;
            for (; r.sibling === null; ) {
              if (r.return === null || r.return === i) break t;
              l === r && (l = null), r = r.return;
            }
            l === r && (l = null), r.sibling.return = r.return, r = r.sibling;
          }
        f & 4 && (f = i.updateQueue, f !== null && (l = f.retryQueue, l !== null && (f.retryQueue = null, Wu(i, l))));
        break;
      case 19:
        oi(r, i), li(i), f & 4 && (f = i.updateQueue, f !== null && (i.updateQueue = null, Wu(i, f)));
        break;
      case 30:
        break;
      case 21:
        break;
      default:
        oi(r, i), li(i);
    }
  }
  function li(i) {
    var r = i.flags;
    if (r & 2) {
      try {
        for (var l, f = i.return; f !== null; ) {
          if (Py(f)) {
            l = f;
            break;
          }
          f = f.return;
        }
        if (l == null) throw Error(s(160));
        switch (l.tag) {
          case 27:
            var v = l.stateNode, S = Cp(i);
            Xu(i, S, v);
            break;
          case 5:
            var P = l.stateNode;
            l.flags & 32 && (ei(P, ""), l.flags &= -33);
            var q = Cp(i);
            Xu(i, q, P);
            break;
          case 3:
          case 4:
            var nt = l.stateNode.containerInfo, pt = Cp(i);
            Rp(
              i,
              pt,
              nt
            );
            break;
          default:
            throw Error(s(161));
        }
      } catch (wt) {
        Xe(i, i.return, wt);
      }
      i.flags &= -3;
    }
    r & 4096 && (i.flags &= -4097);
  }
  function Xy(i) {
    if (i.subtreeFlags & 1024)
      for (i = i.child; i !== null; ) {
        var r = i;
        Xy(r), r.tag === 5 && r.flags & 1024 && r.stateNode.reset(), i = i.sibling;
      }
  }
  function js(i, r) {
    if (r.subtreeFlags & 8772)
      for (r = r.child; r !== null; )
        zy(i, r.alternate, r), r = r.sibling;
  }
  function Ea(i) {
    for (i = i.child; i !== null; ) {
      var r = i;
      switch (r.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          Nr(4, r, r.return), Ea(r);
          break;
        case 1:
          ps(r, r.return);
          var l = r.stateNode;
          typeof l.componentWillUnmount == "function" && Ly(
            r,
            r.return,
            l
          ), Ea(r);
          break;
        case 27:
          sc(r.stateNode);
        case 26:
        case 5:
          ps(r, r.return), Ea(r);
          break;
        case 22:
          r.memoizedState === null && Ea(r);
          break;
        case 30:
          Ea(r);
          break;
        default:
          Ea(r);
      }
      i = i.sibling;
    }
  }
  function qs(i, r, l) {
    for (l = l && (r.subtreeFlags & 8772) !== 0, r = r.child; r !== null; ) {
      var f = r.alternate, v = i, S = r, P = S.flags;
      switch (S.tag) {
        case 0:
        case 11:
        case 15:
          qs(
            v,
            S,
            l
          ), ql(4, S);
          break;
        case 1:
          if (qs(
            v,
            S,
            l
          ), f = S, v = f.stateNode, typeof v.componentDidMount == "function")
            try {
              v.componentDidMount();
            } catch (pt) {
              Xe(f, f.return, pt);
            }
          if (f = S, v = f.updateQueue, v !== null) {
            var q = f.stateNode;
            try {
              var nt = v.shared.hiddenCallbacks;
              if (nt !== null)
                for (v.shared.hiddenCallbacks = null, v = 0; v < nt.length; v++)
                  S_(nt[v], q);
            } catch (pt) {
              Xe(f, f.return, pt);
            }
          }
          l && P & 64 && Oy(S), Zl(S, S.return);
          break;
        case 27:
          Iy(S);
        case 26:
        case 5:
          qs(
            v,
            S,
            l
          ), l && f === null && P & 4 && Uy(S), Zl(S, S.return);
          break;
        case 12:
          qs(
            v,
            S,
            l
          );
          break;
        case 31:
          qs(
            v,
            S,
            l
          ), l && P & 4 && Vy(v, S);
          break;
        case 13:
          qs(
            v,
            S,
            l
          ), l && P & 4 && Gy(v, S);
          break;
        case 22:
          S.memoizedState === null && qs(
            v,
            S,
            l
          ), Zl(S, S.return);
          break;
        case 30:
          break;
        default:
          qs(
            v,
            S,
            l
          );
      }
      r = r.sibling;
    }
  }
  function Np(i, r) {
    var l = null;
    i !== null && i.memoizedState !== null && i.memoizedState.cachePool !== null && (l = i.memoizedState.cachePool.pool), i = null, r.memoizedState !== null && r.memoizedState.cachePool !== null && (i = r.memoizedState.cachePool.pool), i !== l && (i != null && i.refCount++, l != null && Pl(l));
  }
  function Op(i, r) {
    i = null, r.alternate !== null && (i = r.alternate.memoizedState.cache), r = r.memoizedState.cache, r !== i && (r.refCount++, i != null && Pl(i));
  }
  function $i(i, r, l, f) {
    if (r.subtreeFlags & 10256)
      for (r = r.child; r !== null; )
        Wy(
          i,
          r,
          l,
          f
        ), r = r.sibling;
  }
  function Wy(i, r, l, f) {
    var v = r.flags;
    switch (r.tag) {
      case 0:
      case 11:
      case 15:
        $i(
          i,
          r,
          l,
          f
        ), v & 2048 && ql(9, r);
        break;
      case 1:
        $i(
          i,
          r,
          l,
          f
        );
        break;
      case 3:
        $i(
          i,
          r,
          l,
          f
        ), v & 2048 && (i = null, r.alternate !== null && (i = r.alternate.memoizedState.cache), r = r.memoizedState.cache, r !== i && (r.refCount++, i != null && Pl(i)));
        break;
      case 12:
        if (v & 2048) {
          $i(
            i,
            r,
            l,
            f
          ), i = r.stateNode;
          try {
            var S = r.memoizedProps, P = S.id, q = S.onPostCommit;
            typeof q == "function" && q(
              P,
              r.alternate === null ? "mount" : "update",
              i.passiveEffectDuration,
              -0
            );
          } catch (nt) {
            Xe(r, r.return, nt);
          }
        } else
          $i(
            i,
            r,
            l,
            f
          );
        break;
      case 31:
        $i(
          i,
          r,
          l,
          f
        );
        break;
      case 13:
        $i(
          i,
          r,
          l,
          f
        );
        break;
      case 23:
        break;
      case 22:
        S = r.stateNode, P = r.alternate, r.memoizedState !== null ? S._visibility & 2 ? $i(
          i,
          r,
          l,
          f
        ) : $l(i, r) : S._visibility & 2 ? $i(
          i,
          r,
          l,
          f
        ) : (S._visibility |= 2, xo(
          i,
          r,
          l,
          f,
          (r.subtreeFlags & 10256) !== 0 || !1
        )), v & 2048 && Np(P, r);
        break;
      case 24:
        $i(
          i,
          r,
          l,
          f
        ), v & 2048 && Op(r.alternate, r);
        break;
      default:
        $i(
          i,
          r,
          l,
          f
        );
    }
  }
  function xo(i, r, l, f, v) {
    for (v = v && ((r.subtreeFlags & 10256) !== 0 || !1), r = r.child; r !== null; ) {
      var S = i, P = r, q = l, nt = f, pt = P.flags;
      switch (P.tag) {
        case 0:
        case 11:
        case 15:
          xo(
            S,
            P,
            q,
            nt,
            v
          ), ql(8, P);
          break;
        case 23:
          break;
        case 22:
          var wt = P.stateNode;
          P.memoizedState !== null ? wt._visibility & 2 ? xo(
            S,
            P,
            q,
            nt,
            v
          ) : $l(
            S,
            P
          ) : (wt._visibility |= 2, xo(
            S,
            P,
            q,
            nt,
            v
          )), v && pt & 2048 && Np(
            P.alternate,
            P
          );
          break;
        case 24:
          xo(
            S,
            P,
            q,
            nt,
            v
          ), v && pt & 2048 && Op(P.alternate, P);
          break;
        default:
          xo(
            S,
            P,
            q,
            nt,
            v
          );
      }
      r = r.sibling;
    }
  }
  function $l(i, r) {
    if (r.subtreeFlags & 10256)
      for (r = r.child; r !== null; ) {
        var l = i, f = r, v = f.flags;
        switch (f.tag) {
          case 22:
            $l(l, f), v & 2048 && Np(
              f.alternate,
              f
            );
            break;
          case 24:
            $l(l, f), v & 2048 && Op(f.alternate, f);
            break;
          default:
            $l(l, f);
        }
        r = r.sibling;
      }
  }
  var Kl = 8192;
  function So(i, r, l) {
    if (i.subtreeFlags & Kl)
      for (i = i.child; i !== null; )
        Yy(
          i,
          r,
          l
        ), i = i.sibling;
  }
  function Yy(i, r, l) {
    switch (i.tag) {
      case 26:
        So(
          i,
          r,
          l
        ), i.flags & Kl && i.memoizedState !== null && XT(
          l,
          Zi,
          i.memoizedState,
          i.memoizedProps
        );
        break;
      case 5:
        So(
          i,
          r,
          l
        );
        break;
      case 3:
      case 4:
        var f = Zi;
        Zi = af(i.stateNode.containerInfo), So(
          i,
          r,
          l
        ), Zi = f;
        break;
      case 22:
        i.memoizedState === null && (f = i.alternate, f !== null && f.memoizedState !== null ? (f = Kl, Kl = 16777216, So(
          i,
          r,
          l
        ), Kl = f) : So(
          i,
          r,
          l
        ));
        break;
      default:
        So(
          i,
          r,
          l
        );
    }
  }
  function jy(i) {
    var r = i.alternate;
    if (r !== null && (i = r.child, i !== null)) {
      r.child = null;
      do
        r = i.sibling, i.sibling = null, i = r;
      while (i !== null);
    }
  }
  function Ql(i) {
    var r = i.deletions;
    if ((i.flags & 16) !== 0) {
      if (r !== null)
        for (var l = 0; l < r.length; l++) {
          var f = r[l];
          Bn = f, Zy(
            f,
            i
          );
        }
      jy(i);
    }
    if (i.subtreeFlags & 10256)
      for (i = i.child; i !== null; )
        qy(i), i = i.sibling;
  }
  function qy(i) {
    switch (i.tag) {
      case 0:
      case 11:
      case 15:
        Ql(i), i.flags & 2048 && Nr(9, i, i.return);
        break;
      case 3:
        Ql(i);
        break;
      case 12:
        Ql(i);
        break;
      case 22:
        var r = i.stateNode;
        i.memoizedState !== null && r._visibility & 2 && (i.return === null || i.return.tag !== 13) ? (r._visibility &= -3, Yu(i)) : Ql(i);
        break;
      default:
        Ql(i);
    }
  }
  function Yu(i) {
    var r = i.deletions;
    if ((i.flags & 16) !== 0) {
      if (r !== null)
        for (var l = 0; l < r.length; l++) {
          var f = r[l];
          Bn = f, Zy(
            f,
            i
          );
        }
      jy(i);
    }
    for (i = i.child; i !== null; ) {
      switch (r = i, r.tag) {
        case 0:
        case 11:
        case 15:
          Nr(8, r, r.return), Yu(r);
          break;
        case 22:
          l = r.stateNode, l._visibility & 2 && (l._visibility &= -3, Yu(r));
          break;
        default:
          Yu(r);
      }
      i = i.sibling;
    }
  }
  function Zy(i, r) {
    for (; Bn !== null; ) {
      var l = Bn;
      switch (l.tag) {
        case 0:
        case 11:
        case 15:
          Nr(8, l, r);
          break;
        case 23:
        case 22:
          if (l.memoizedState !== null && l.memoizedState.cachePool !== null) {
            var f = l.memoizedState.cachePool.pool;
            f != null && f.refCount++;
          }
          break;
        case 24:
          Pl(l.memoizedState.cache);
      }
      if (f = l.child, f !== null) f.return = l, Bn = f;
      else
        t: for (l = i; Bn !== null; ) {
          f = Bn;
          var v = f.sibling, S = f.return;
          if (Fy(f), f === l) {
            Bn = null;
            break t;
          }
          if (v !== null) {
            v.return = S, Bn = v;
            break t;
          }
          Bn = S;
        }
    }
  }
  var rT = {
    getCacheForType: function(i) {
      var r = Gn(Sn), l = r.data.get(i);
      return l === void 0 && (l = i(), r.data.set(i, l)), l;
    },
    cacheSignal: function() {
      return Gn(Sn).controller.signal;
    }
  }, aT = typeof WeakMap == "function" ? WeakMap : Map, Ve = 0, tn = null, Te = null, De = 0, ke = 0, bi = null, Or = !1, bo = !1, Lp = !1, Zs = 0, fn = 0, Lr = 0, wa = 0, Up = 0, Mi = 0, Mo = 0, Jl = null, ci = null, Pp = !1, ju = 0, $y = 0, qu = 1 / 0, Zu = null, Ur = null, Nn = 0, Pr = null, Eo = null, $s = 0, Ip = 0, Bp = null, Ky = null, tc = 0, zp = null;
  function Ei() {
    return (Ve & 2) !== 0 && De !== 0 ? De & -De : N.T !== null ? Xp() : Li();
  }
  function Qy() {
    if (Mi === 0)
      if ((De & 536870912) === 0 || Le) {
        var i = Ut;
        Ut <<= 1, (Ut & 3932160) === 0 && (Ut = 262144), Mi = i;
      } else Mi = 536870912;
    return i = xi.current, i !== null && (i.flags |= 32), Mi;
  }
  function ui(i, r, l) {
    (i === tn && (ke === 2 || ke === 9) || i.cancelPendingCommit !== null) && (wo(i, 0), Ir(
      i,
      De,
      Mi,
      !1
    )), Fn(i, l), ((Ve & 2) === 0 || i !== tn) && (i === tn && ((Ve & 2) === 0 && (wa |= l), fn === 4 && Ir(
      i,
      De,
      Mi,
      !1
    )), ms(i));
  }
  function Jy(i, r, l) {
    if ((Ve & 6) !== 0) throw Error(s(327));
    var f = !l && (r & 127) === 0 && (r & i.expiredLanes) === 0 || Zt(i, r), v = f ? cT(i, r) : Hp(i, r, !0), S = f;
    do {
      if (v === 0) {
        bo && !f && Ir(i, r, 0, !1);
        break;
      } else {
        if (l = i.current.alternate, S && !oT(l)) {
          v = Hp(i, r, !1), S = !1;
          continue;
        }
        if (v === 2) {
          if (S = r, i.errorRecoveryDisabledLanes & S)
            var P = 0;
          else
            P = i.pendingLanes & -536870913, P = P !== 0 ? P : P & 536870912 ? 536870912 : 0;
          if (P !== 0) {
            r = P;
            t: {
              var q = i;
              v = Jl;
              var nt = q.current.memoizedState.isDehydrated;
              if (nt && (wo(q, P).flags |= 256), P = Hp(
                q,
                P,
                !1
              ), P !== 2) {
                if (Lp && !nt) {
                  q.errorRecoveryDisabledLanes |= S, wa |= S, v = 4;
                  break t;
                }
                S = ci, ci = v, S !== null && (ci === null ? ci = S : ci.push.apply(
                  ci,
                  S
                ));
              }
              v = P;
            }
            if (S = !1, v !== 2) continue;
          }
        }
        if (v === 1) {
          wo(i, 0), Ir(i, r, 0, !0);
          break;
        }
        t: {
          switch (f = i, S = v, S) {
            case 0:
            case 1:
              throw Error(s(345));
            case 4:
              if ((r & 4194048) !== r) break;
            case 6:
              Ir(
                f,
                r,
                Mi,
                !Or
              );
              break t;
            case 2:
              ci = null;
              break;
            case 3:
            case 5:
              break;
            default:
              throw Error(s(329));
          }
          if ((r & 62914560) === r && (v = ju + 300 - G(), 10 < v)) {
            if (Ir(
              f,
              r,
              Mi,
              !Or
            ), bt(f, 0, !0) !== 0) break t;
            $s = r, f.timeoutHandle = Dx(
              tx.bind(
                null,
                f,
                l,
                ci,
                Zu,
                Pp,
                r,
                Mi,
                wa,
                Mo,
                Or,
                S,
                "Throttled",
                -0,
                0
              ),
              v
            );
            break t;
          }
          tx(
            f,
            l,
            ci,
            Zu,
            Pp,
            r,
            Mi,
            wa,
            Mo,
            Or,
            S,
            null,
            -0,
            0
          );
        }
      }
      break;
    } while (!0);
    ms(i);
  }
  function tx(i, r, l, f, v, S, P, q, nt, pt, wt, Ct, gt, St) {
    if (i.timeoutHandle = -1, Ct = r.subtreeFlags, Ct & 8192 || (Ct & 16785408) === 16785408) {
      Ct = {
        stylesheets: null,
        count: 0,
        imgCount: 0,
        imgBytes: 0,
        suspenseyImages: [],
        waitingForImages: !0,
        waitingForViewTransition: !1,
        unsuspend: Ps
      }, Yy(
        r,
        S,
        Ct
      );
      var ee = (S & 62914560) === S ? ju - G() : (S & 4194048) === S ? $y - G() : 0;
      if (ee = WT(
        Ct,
        ee
      ), ee !== null) {
        $s = S, i.cancelPendingCommit = ee(
          lx.bind(
            null,
            i,
            r,
            S,
            l,
            f,
            v,
            P,
            q,
            nt,
            wt,
            Ct,
            null,
            gt,
            St
          )
        ), Ir(i, S, P, !pt);
        return;
      }
    }
    lx(
      i,
      r,
      S,
      l,
      f,
      v,
      P,
      q,
      nt
    );
  }
  function oT(i) {
    for (var r = i; ; ) {
      var l = r.tag;
      if ((l === 0 || l === 11 || l === 15) && r.flags & 16384 && (l = r.updateQueue, l !== null && (l = l.stores, l !== null)))
        for (var f = 0; f < l.length; f++) {
          var v = l[f], S = v.getSnapshot;
          v = v.value;
          try {
            if (!_i(S(), v)) return !1;
          } catch {
            return !1;
          }
        }
      if (l = r.child, r.subtreeFlags & 16384 && l !== null)
        l.return = r, r = l;
      else {
        if (r === i) break;
        for (; r.sibling === null; ) {
          if (r.return === null || r.return === i) return !0;
          r = r.return;
        }
        r.sibling.return = r.return, r = r.sibling;
      }
    }
    return !0;
  }
  function Ir(i, r, l, f) {
    r &= ~Up, r &= ~wa, i.suspendedLanes |= r, i.pingedLanes &= ~r, f && (i.warmLanes |= r), f = i.expirationTimes;
    for (var v = r; 0 < v; ) {
      var S = 31 - kt(v), P = 1 << S;
      f[S] = -1, v &= ~P;
    }
    l !== 0 && oa(i, l, r);
  }
  function $u() {
    return (Ve & 6) === 0 ? (ec(0), !1) : !0;
  }
  function Fp() {
    if (Te !== null) {
      if (ke === 0)
        var i = Te.return;
      else
        i = Te, Fs = ga = null, ep(i), mo = null, Bl = 0, i = Te;
      for (; i !== null; )
        Ny(i.alternate, i), i = i.return;
      Te = null;
    }
  }
  function wo(i, r) {
    var l = i.timeoutHandle;
    l !== -1 && (i.timeoutHandle = -1, TT(l)), l = i.cancelPendingCommit, l !== null && (i.cancelPendingCommit = null, l()), $s = 0, Fp(), tn = i, Te = l = Bs(i.current, null), De = r, ke = 0, bi = null, Or = !1, bo = Zt(i, r), Lp = !1, Mo = Mi = Up = wa = Lr = fn = 0, ci = Jl = null, Pp = !1, (r & 8) !== 0 && (r |= r & 32);
    var f = i.entangledLanes;
    if (f !== 0)
      for (i = i.entanglements, f &= r; 0 < f; ) {
        var v = 31 - kt(f), S = 1 << v;
        r |= i[v], f &= ~S;
      }
    return Zs = r, vu(), l;
  }
  function ex(i, r) {
    Se = null, N.H = Wl, r === po || r === wu ? (r = v_(), ke = 3) : r === kh ? (r = v_(), ke = 4) : ke = r === vp ? 8 : r !== null && typeof r == "object" && typeof r.then == "function" ? 6 : 1, bi = r, Te === null && (fn = 1, Fu(
      i,
      Ii(r, i.current)
    ));
  }
  function nx() {
    var i = xi.current;
    return i === null ? !0 : (De & 4194048) === De ? Hi === null : (De & 62914560) === De || (De & 536870912) !== 0 ? i === Hi : !1;
  }
  function ix() {
    var i = N.H;
    return N.H = Wl, i === null ? Wl : i;
  }
  function sx() {
    var i = N.A;
    return N.A = rT, i;
  }
  function Ku() {
    fn = 4, Or || (De & 4194048) !== De && xi.current !== null || (bo = !0), (Lr & 134217727) === 0 && (wa & 134217727) === 0 || tn === null || Ir(
      tn,
      De,
      Mi,
      !1
    );
  }
  function Hp(i, r, l) {
    var f = Ve;
    Ve |= 2;
    var v = ix(), S = sx();
    (tn !== i || De !== r) && (Zu = null, wo(i, r)), r = !1;
    var P = fn;
    t: do
      try {
        if (ke !== 0 && Te !== null) {
          var q = Te, nt = bi;
          switch (ke) {
            case 8:
              Fp(), P = 6;
              break t;
            case 3:
            case 2:
            case 9:
            case 6:
              xi.current === null && (r = !0);
              var pt = ke;
              if (ke = 0, bi = null, Ao(i, q, nt, pt), l && bo) {
                P = 0;
                break t;
              }
              break;
            default:
              pt = ke, ke = 0, bi = null, Ao(i, q, nt, pt);
          }
        }
        lT(), P = fn;
        break;
      } catch (wt) {
        ex(i, wt);
      }
    while (!0);
    return r && i.shellSuspendCounter++, Fs = ga = null, Ve = f, N.H = v, N.A = S, Te === null && (tn = null, De = 0, vu()), P;
  }
  function lT() {
    for (; Te !== null; ) rx(Te);
  }
  function cT(i, r) {
    var l = Ve;
    Ve |= 2;
    var f = ix(), v = sx();
    tn !== i || De !== r ? (Zu = null, qu = G() + 500, wo(i, r)) : bo = Zt(
      i,
      r
    );
    t: do
      try {
        if (ke !== 0 && Te !== null) {
          r = Te;
          var S = bi;
          e: switch (ke) {
            case 1:
              ke = 0, bi = null, Ao(i, r, S, 1);
              break;
            case 2:
            case 9:
              if (m_(S)) {
                ke = 0, bi = null, ax(r);
                break;
              }
              r = function() {
                ke !== 2 && ke !== 9 || tn !== i || (ke = 7), ms(i);
              }, S.then(r, r);
              break t;
            case 3:
              ke = 7;
              break t;
            case 4:
              ke = 5;
              break t;
            case 7:
              m_(S) ? (ke = 0, bi = null, ax(r)) : (ke = 0, bi = null, Ao(i, r, S, 7));
              break;
            case 5:
              var P = null;
              switch (Te.tag) {
                case 26:
                  P = Te.memoizedState;
                case 5:
                case 27:
                  var q = Te;
                  if (P ? Wx(P) : q.stateNode.complete) {
                    ke = 0, bi = null;
                    var nt = q.sibling;
                    if (nt !== null) Te = nt;
                    else {
                      var pt = q.return;
                      pt !== null ? (Te = pt, Qu(pt)) : Te = null;
                    }
                    break e;
                  }
              }
              ke = 0, bi = null, Ao(i, r, S, 5);
              break;
            case 6:
              ke = 0, bi = null, Ao(i, r, S, 6);
              break;
            case 8:
              Fp(), fn = 6;
              break t;
            default:
              throw Error(s(462));
          }
        }
        uT();
        break;
      } catch (wt) {
        ex(i, wt);
      }
    while (!0);
    return Fs = ga = null, N.H = f, N.A = v, Ve = l, Te !== null ? 0 : (tn = null, De = 0, vu(), fn);
  }
  function uT() {
    for (; Te !== null && !Kt(); )
      rx(Te);
  }
  function rx(i) {
    var r = Ry(i.alternate, i, Zs);
    i.memoizedProps = i.pendingProps, r === null ? Qu(i) : Te = r;
  }
  function ax(i) {
    var r = i, l = r.alternate;
    switch (r.tag) {
      case 15:
      case 0:
        r = My(
          l,
          r,
          r.pendingProps,
          r.type,
          void 0,
          De
        );
        break;
      case 11:
        r = My(
          l,
          r,
          r.pendingProps,
          r.type.render,
          r.ref,
          De
        );
        break;
      case 5:
        ep(r);
      default:
        Ny(l, r), r = Te = s_(r, Zs), r = Ry(l, r, Zs);
    }
    i.memoizedProps = i.pendingProps, r === null ? Qu(i) : Te = r;
  }
  function Ao(i, r, l, f) {
    Fs = ga = null, ep(r), mo = null, Bl = 0;
    var v = r.return;
    try {
      if (QA(
        i,
        v,
        r,
        l,
        De
      )) {
        fn = 1, Fu(
          i,
          Ii(l, i.current)
        ), Te = null;
        return;
      }
    } catch (S) {
      if (v !== null) throw Te = v, S;
      fn = 1, Fu(
        i,
        Ii(l, i.current)
      ), Te = null;
      return;
    }
    r.flags & 32768 ? (Le || f === 1 ? i = !0 : bo || (De & 536870912) !== 0 ? i = !1 : (Or = i = !0, (f === 2 || f === 9 || f === 3 || f === 6) && (f = xi.current, f !== null && f.tag === 13 && (f.flags |= 16384))), ox(r, i)) : Qu(r);
  }
  function Qu(i) {
    var r = i;
    do {
      if ((r.flags & 32768) !== 0) {
        ox(
          r,
          Or
        );
        return;
      }
      i = r.return;
      var l = eT(
        r.alternate,
        r,
        Zs
      );
      if (l !== null) {
        Te = l;
        return;
      }
      if (r = r.sibling, r !== null) {
        Te = r;
        return;
      }
      Te = r = i;
    } while (r !== null);
    fn === 0 && (fn = 5);
  }
  function ox(i, r) {
    do {
      var l = nT(i.alternate, i);
      if (l !== null) {
        l.flags &= 32767, Te = l;
        return;
      }
      if (l = i.return, l !== null && (l.flags |= 32768, l.subtreeFlags = 0, l.deletions = null), !r && (i = i.sibling, i !== null)) {
        Te = i;
        return;
      }
      Te = i = l;
    } while (i !== null);
    fn = 6, Te = null;
  }
  function lx(i, r, l, f, v, S, P, q, nt) {
    i.cancelPendingCommit = null;
    do
      Ju();
    while (Nn !== 0);
    if ((Ve & 6) !== 0) throw Error(s(327));
    if (r !== null) {
      if (r === i.current) throw Error(s(177));
      if (S = r.lanes | r.childLanes, S |= Ch, mi(
        i,
        l,
        S,
        P,
        q,
        nt
      ), i === tn && (Te = tn = null, De = 0), Eo = r, Pr = i, $s = l, Ip = S, Bp = v, Ky = f, (r.subtreeFlags & 10256) !== 0 || (r.flags & 10256) !== 0 ? (i.callbackNode = null, i.callbackPriority = 0, pT(Mt, function() {
        return hx(), null;
      })) : (i.callbackNode = null, i.callbackPriority = 0), f = (r.flags & 13878) !== 0, (r.subtreeFlags & 13878) !== 0 || f) {
        f = N.T, N.T = null, v = I.p, I.p = 2, P = Ve, Ve |= 4;
        try {
          iT(i, r, l);
        } finally {
          Ve = P, I.p = v, N.T = f;
        }
      }
      Nn = 1, cx(), ux(), fx();
    }
  }
  function cx() {
    if (Nn === 1) {
      Nn = 0;
      var i = Pr, r = Eo, l = (r.flags & 13878) !== 0;
      if ((r.subtreeFlags & 13878) !== 0 || l) {
        l = N.T, N.T = null;
        var f = I.p;
        I.p = 2;
        var v = Ve;
        Ve |= 4;
        try {
          ky(r, i);
          var S = Qp, P = Zv(i.containerInfo), q = S.focusedElem, nt = S.selectionRange;
          if (P !== q && q && q.ownerDocument && qv(
            q.ownerDocument.documentElement,
            q
          )) {
            if (nt !== null && Mh(q)) {
              var pt = nt.start, wt = nt.end;
              if (wt === void 0 && (wt = pt), "selectionStart" in q)
                q.selectionStart = pt, q.selectionEnd = Math.min(
                  wt,
                  q.value.length
                );
              else {
                var Ct = q.ownerDocument || document, gt = Ct && Ct.defaultView || window;
                if (gt.getSelection) {
                  var St = gt.getSelection(), ee = q.textContent.length, ce = Math.min(nt.start, ee), Ke = nt.end === void 0 ? ce : Math.min(nt.end, ee);
                  !St.extend && ce > Ke && (P = Ke, Ke = ce, ce = P);
                  var ut = jv(
                    q,
                    ce
                  ), at = jv(
                    q,
                    Ke
                  );
                  if (ut && at && (St.rangeCount !== 1 || St.anchorNode !== ut.node || St.anchorOffset !== ut.offset || St.focusNode !== at.node || St.focusOffset !== at.offset)) {
                    var ht = Ct.createRange();
                    ht.setStart(ut.node, ut.offset), St.removeAllRanges(), ce > Ke ? (St.addRange(ht), St.extend(at.node, at.offset)) : (ht.setEnd(at.node, at.offset), St.addRange(ht));
                  }
                }
              }
            }
            for (Ct = [], St = q; St = St.parentNode; )
              St.nodeType === 1 && Ct.push({
                element: St,
                left: St.scrollLeft,
                top: St.scrollTop
              });
            for (typeof q.focus == "function" && q.focus(), q = 0; q < Ct.length; q++) {
              var Tt = Ct[q];
              Tt.element.scrollLeft = Tt.left, Tt.element.scrollTop = Tt.top;
            }
          }
          df = !!Kp, Qp = Kp = null;
        } finally {
          Ve = v, I.p = f, N.T = l;
        }
      }
      i.current = r, Nn = 2;
    }
  }
  function ux() {
    if (Nn === 2) {
      Nn = 0;
      var i = Pr, r = Eo, l = (r.flags & 8772) !== 0;
      if ((r.subtreeFlags & 8772) !== 0 || l) {
        l = N.T, N.T = null;
        var f = I.p;
        I.p = 2;
        var v = Ve;
        Ve |= 4;
        try {
          zy(i, r.alternate, r);
        } finally {
          Ve = v, I.p = f, N.T = l;
        }
      }
      Nn = 3;
    }
  }
  function fx() {
    if (Nn === 4 || Nn === 3) {
      Nn = 0, tt();
      var i = Pr, r = Eo, l = $s, f = Ky;
      (r.subtreeFlags & 10256) !== 0 || (r.flags & 10256) !== 0 ? Nn = 5 : (Nn = 0, Eo = Pr = null, dx(i, i.pendingLanes));
      var v = i.pendingLanes;
      if (v === 0 && (Ur = null), yr(l), r = r.stateNode, Dt && typeof Dt.onCommitFiberRoot == "function")
        try {
          Dt.onCommitFiberRoot(
            Ot,
            r,
            void 0,
            (r.current.flags & 128) === 128
          );
        } catch {
        }
      if (f !== null) {
        r = N.T, v = I.p, I.p = 2, N.T = null;
        try {
          for (var S = i.onRecoverableError, P = 0; P < f.length; P++) {
            var q = f[P];
            S(q.value, {
              componentStack: q.stack
            });
          }
        } finally {
          N.T = r, I.p = v;
        }
      }
      ($s & 3) !== 0 && Ju(), ms(i), v = i.pendingLanes, (l & 261930) !== 0 && (v & 42) !== 0 ? i === zp ? tc++ : (tc = 0, zp = i) : tc = 0, ec(0);
    }
  }
  function dx(i, r) {
    (i.pooledCacheLanes &= r) === 0 && (r = i.pooledCache, r != null && (i.pooledCache = null, Pl(r)));
  }
  function Ju() {
    return cx(), ux(), fx(), hx();
  }
  function hx() {
    if (Nn !== 5) return !1;
    var i = Pr, r = Ip;
    Ip = 0;
    var l = yr($s), f = N.T, v = I.p;
    try {
      I.p = 32 > l ? 32 : l, N.T = null, l = Bp, Bp = null;
      var S = Pr, P = $s;
      if (Nn = 0, Eo = Pr = null, $s = 0, (Ve & 6) !== 0) throw Error(s(331));
      var q = Ve;
      if (Ve |= 4, qy(S.current), Wy(
        S,
        S.current,
        P,
        l
      ), Ve = q, ec(0, !1), Dt && typeof Dt.onPostCommitFiberRoot == "function")
        try {
          Dt.onPostCommitFiberRoot(Ot, S);
        } catch {
        }
      return !0;
    } finally {
      I.p = v, N.T = f, dx(i, r);
    }
  }
  function px(i, r, l) {
    r = Ii(l, r), r = gp(i.stateNode, r, 2), i = Cr(i, r, 2), i !== null && (Fn(i, 2), ms(i));
  }
  function Xe(i, r, l) {
    if (i.tag === 3)
      px(i, i, l);
    else
      for (; r !== null; ) {
        if (r.tag === 3) {
          px(
            r,
            i,
            l
          );
          break;
        } else if (r.tag === 1) {
          var f = r.stateNode;
          if (typeof r.type.getDerivedStateFromError == "function" || typeof f.componentDidCatch == "function" && (Ur === null || !Ur.has(f))) {
            i = Ii(l, i), l = my(2), f = Cr(r, l, 2), f !== null && (gy(
              l,
              f,
              r,
              i
            ), Fn(f, 2), ms(f));
            break;
          }
        }
        r = r.return;
      }
  }
  function Vp(i, r, l) {
    var f = i.pingCache;
    if (f === null) {
      f = i.pingCache = new aT();
      var v = /* @__PURE__ */ new Set();
      f.set(r, v);
    } else
      v = f.get(r), v === void 0 && (v = /* @__PURE__ */ new Set(), f.set(r, v));
    v.has(l) || (Lp = !0, v.add(l), i = fT.bind(null, i, r, l), r.then(i, i));
  }
  function fT(i, r, l) {
    var f = i.pingCache;
    f !== null && f.delete(r), i.pingedLanes |= i.suspendedLanes & l, i.warmLanes &= ~l, tn === i && (De & l) === l && (fn === 4 || fn === 3 && (De & 62914560) === De && 300 > G() - ju ? (Ve & 2) === 0 && wo(i, 0) : Up |= l, Mo === De && (Mo = 0)), ms(i);
  }
  function mx(i, r) {
    r === 0 && (r = He()), i = ha(i, r), i !== null && (Fn(i, r), ms(i));
  }
  function dT(i) {
    var r = i.memoizedState, l = 0;
    r !== null && (l = r.retryLane), mx(i, l);
  }
  function hT(i, r) {
    var l = 0;
    switch (i.tag) {
      case 31:
      case 13:
        var f = i.stateNode, v = i.memoizedState;
        v !== null && (l = v.retryLane);
        break;
      case 19:
        f = i.stateNode;
        break;
      case 22:
        f = i.stateNode._retryCache;
        break;
      default:
        throw Error(s(314));
    }
    f !== null && f.delete(r), mx(i, l);
  }
  function pT(i, r) {
    return xe(i, r);
  }
  var tf = null, To = null, Gp = !1, ef = !1, kp = !1, Br = 0;
  function ms(i) {
    i !== To && i.next === null && (To === null ? tf = To = i : To = To.next = i), ef = !0, Gp || (Gp = !0, gT());
  }
  function ec(i, r) {
    if (!kp && ef) {
      kp = !0;
      do
        for (var l = !1, f = tf; f !== null; ) {
          if (i !== 0) {
            var v = f.pendingLanes;
            if (v === 0) var S = 0;
            else {
              var P = f.suspendedLanes, q = f.pingedLanes;
              S = (1 << 31 - kt(42 | i) + 1) - 1, S &= v & ~(P & ~q), S = S & 201326741 ? S & 201326741 | 1 : S ? S | 2 : 0;
            }
            S !== 0 && (l = !0, yx(f, S));
          } else
            S = De, S = bt(
              f,
              f === tn ? S : 0,
              f.cancelPendingCommit !== null || f.timeoutHandle !== -1
            ), (S & 3) === 0 || Zt(f, S) || (l = !0, yx(f, S));
          f = f.next;
        }
      while (l);
      kp = !1;
    }
  }
  function mT() {
    gx();
  }
  function gx() {
    ef = Gp = !1;
    var i = 0;
    Br !== 0 && AT() && (i = Br);
    for (var r = G(), l = null, f = tf; f !== null; ) {
      var v = f.next, S = vx(f, r);
      S === 0 ? (f.next = null, l === null ? tf = v : l.next = v, v === null && (To = l)) : (l = f, (i !== 0 || (S & 3) !== 0) && (ef = !0)), f = v;
    }
    Nn !== 0 && Nn !== 5 || ec(i), Br !== 0 && (Br = 0);
  }
  function vx(i, r) {
    for (var l = i.suspendedLanes, f = i.pingedLanes, v = i.expirationTimes, S = i.pendingLanes & -62914561; 0 < S; ) {
      var P = 31 - kt(S), q = 1 << P, nt = v[P];
      nt === -1 ? ((q & l) === 0 || (q & f) !== 0) && (v[P] = fe(q, r)) : nt <= r && (i.expiredLanes |= q), S &= ~q;
    }
    if (r = tn, l = De, l = bt(
      i,
      i === r ? l : 0,
      i.cancelPendingCommit !== null || i.timeoutHandle !== -1
    ), f = i.callbackNode, l === 0 || i === r && (ke === 2 || ke === 9) || i.cancelPendingCommit !== null)
      return f !== null && f !== null && Re(f), i.callbackNode = null, i.callbackPriority = 0;
    if ((l & 3) === 0 || Zt(i, l)) {
      if (r = l & -l, r === i.callbackPriority) return r;
      switch (f !== null && Re(f), yr(l)) {
        case 2:
        case 8:
          l = Rt;
          break;
        case 32:
          l = Mt;
          break;
        case 268435456:
          l = It;
          break;
        default:
          l = Mt;
      }
      return f = _x.bind(null, i), l = xe(l, f), i.callbackPriority = r, i.callbackNode = l, r;
    }
    return f !== null && f !== null && Re(f), i.callbackPriority = 2, i.callbackNode = null, 2;
  }
  function _x(i, r) {
    if (Nn !== 0 && Nn !== 5)
      return i.callbackNode = null, i.callbackPriority = 0, null;
    var l = i.callbackNode;
    if (Ju() && i.callbackNode !== l)
      return null;
    var f = De;
    return f = bt(
      i,
      i === tn ? f : 0,
      i.cancelPendingCommit !== null || i.timeoutHandle !== -1
    ), f === 0 ? null : (Jy(i, f, r), vx(i, G()), i.callbackNode != null && i.callbackNode === l ? _x.bind(null, i) : null);
  }
  function yx(i, r) {
    if (Ju()) return null;
    Jy(i, r, !0);
  }
  function gT() {
    CT(function() {
      (Ve & 6) !== 0 ? xe(
        Et,
        mT
      ) : gx();
    });
  }
  function Xp() {
    if (Br === 0) {
      var i = fo;
      i === 0 && (i = Bt, Bt <<= 1, (Bt & 261888) === 0 && (Bt = 256)), Br = i;
    }
    return Br;
  }
  function xx(i) {
    return i == null || typeof i == "symbol" || typeof i == "boolean" ? null : typeof i == "function" ? i : cu("" + i);
  }
  function Sx(i, r) {
    var l = r.ownerDocument.createElement("input");
    return l.name = r.name, l.value = r.value, i.id && l.setAttribute("form", i.id), r.parentNode.insertBefore(l, r), i = new FormData(i), l.parentNode.removeChild(l), i;
  }
  function vT(i, r, l, f, v) {
    if (r === "submit" && l && l.stateNode === v) {
      var S = xx(
        (v[hn] || null).action
      ), P = f.submitter;
      P && (r = (r = P[hn] || null) ? xx(r.formAction) : P.getAttribute("formAction"), r !== null && (S = r, P = null));
      var q = new hu(
        "action",
        "action",
        null,
        f,
        v
      );
      i.push({
        event: q,
        listeners: [
          {
            instance: null,
            listener: function() {
              if (f.defaultPrevented) {
                if (Br !== 0) {
                  var nt = P ? Sx(v, P) : new FormData(v);
                  up(
                    l,
                    {
                      pending: !0,
                      data: nt,
                      method: v.method,
                      action: S
                    },
                    null,
                    nt
                  );
                }
              } else
                typeof S == "function" && (q.preventDefault(), nt = P ? Sx(v, P) : new FormData(v), up(
                  l,
                  {
                    pending: !0,
                    data: nt,
                    method: v.method,
                    action: S
                  },
                  S,
                  nt
                ));
            },
            currentTarget: v
          }
        ]
      });
    }
  }
  for (var Wp = 0; Wp < Th.length; Wp++) {
    var Yp = Th[Wp], _T = Yp.toLowerCase(), yT = Yp[0].toUpperCase() + Yp.slice(1);
    qi(
      _T,
      "on" + yT
    );
  }
  qi(Qv, "onAnimationEnd"), qi(Jv, "onAnimationIteration"), qi(t_, "onAnimationStart"), qi("dblclick", "onDoubleClick"), qi("focusin", "onFocus"), qi("focusout", "onBlur"), qi(PA, "onTransitionRun"), qi(IA, "onTransitionStart"), qi(BA, "onTransitionCancel"), qi(e_, "onTransitionEnd"), Ht("onMouseEnter", ["mouseout", "mouseover"]), Ht("onMouseLeave", ["mouseout", "mouseover"]), Ht("onPointerEnter", ["pointerout", "pointerover"]), Ht("onPointerLeave", ["pointerout", "pointerover"]), ft(
    "onChange",
    "change click focusin focusout input keydown keyup selectionchange".split(" ")
  ), ft(
    "onSelect",
    "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(
      " "
    )
  ), ft("onBeforeInput", [
    "compositionend",
    "keypress",
    "textInput",
    "paste"
  ]), ft(
    "onCompositionEnd",
    "compositionend focusout keydown keypress keyup mousedown".split(" ")
  ), ft(
    "onCompositionStart",
    "compositionstart focusout keydown keypress keyup mousedown".split(" ")
  ), ft(
    "onCompositionUpdate",
    "compositionupdate focusout keydown keypress keyup mousedown".split(" ")
  );
  var nc = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(
    " "
  ), xT = new Set(
    "beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(nc)
  );
  function bx(i, r) {
    r = (r & 4) !== 0;
    for (var l = 0; l < i.length; l++) {
      var f = i[l], v = f.event;
      f = f.listeners;
      t: {
        var S = void 0;
        if (r)
          for (var P = f.length - 1; 0 <= P; P--) {
            var q = f[P], nt = q.instance, pt = q.currentTarget;
            if (q = q.listener, nt !== S && v.isPropagationStopped())
              break t;
            S = q, v.currentTarget = pt;
            try {
              S(v);
            } catch (wt) {
              gu(wt);
            }
            v.currentTarget = null, S = nt;
          }
        else
          for (P = 0; P < f.length; P++) {
            if (q = f[P], nt = q.instance, pt = q.currentTarget, q = q.listener, nt !== S && v.isPropagationStopped())
              break t;
            S = q, v.currentTarget = pt;
            try {
              S(v);
            } catch (wt) {
              gu(wt);
            }
            v.currentTarget = null, S = nt;
          }
      }
    }
  }
  function Ce(i, r) {
    var l = r[Yi];
    l === void 0 && (l = r[Yi] = /* @__PURE__ */ new Set());
    var f = i + "__bubble";
    l.has(f) || (Mx(r, i, 2, !1), l.add(f));
  }
  function jp(i, r, l) {
    var f = 0;
    r && (f |= 4), Mx(
      l,
      i,
      f,
      r
    );
  }
  var nf = "_reactListening" + Math.random().toString(36).slice(2);
  function qp(i) {
    if (!i[nf]) {
      i[nf] = !0, xt.forEach(function(l) {
        l !== "selectionchange" && (xT.has(l) || jp(l, !1, i), jp(l, !0, i));
      });
      var r = i.nodeType === 9 ? i : i.ownerDocument;
      r === null || r[nf] || (r[nf] = !0, jp("selectionchange", !1, r));
    }
  }
  function Mx(i, r, l, f) {
    switch (Qx(r)) {
      case 2:
        var v = qT;
        break;
      case 8:
        v = ZT;
        break;
      default:
        v = cm;
    }
    l = v.bind(
      null,
      r,
      l,
      i
    ), v = void 0, !ph || r !== "touchstart" && r !== "touchmove" && r !== "wheel" || (v = !0), f ? v !== void 0 ? i.addEventListener(r, l, {
      capture: !0,
      passive: v
    }) : i.addEventListener(r, l, !0) : v !== void 0 ? i.addEventListener(r, l, {
      passive: v
    }) : i.addEventListener(r, l, !1);
  }
  function Zp(i, r, l, f, v) {
    var S = f;
    if ((r & 1) === 0 && (r & 2) === 0 && f !== null)
      t: for (; ; ) {
        if (f === null) return;
        var P = f.tag;
        if (P === 3 || P === 4) {
          var q = f.stateNode.containerInfo;
          if (q === v) break;
          if (P === 4)
            for (P = f.return; P !== null; ) {
              var nt = P.tag;
              if ((nt === 3 || nt === 4) && P.stateNode.containerInfo === v)
                return;
              P = P.return;
            }
          for (; q !== null; ) {
            if (P = cs(q), P === null) return;
            if (nt = P.tag, nt === 5 || nt === 6 || nt === 26 || nt === 27) {
              f = S = P;
              continue t;
            }
            q = q.parentNode;
          }
        }
        f = f.return;
      }
    Cv(function() {
      var pt = S, wt = dh(l), Ct = [];
      t: {
        var gt = n_.get(i);
        if (gt !== void 0) {
          var St = hu, ee = i;
          switch (i) {
            case "keypress":
              if (fu(l) === 0) break t;
            case "keydown":
            case "keyup":
              St = hA;
              break;
            case "focusin":
              ee = "focus", St = _h;
              break;
            case "focusout":
              ee = "blur", St = _h;
              break;
            case "beforeblur":
            case "afterblur":
              St = _h;
              break;
            case "click":
              if (l.button === 2) break t;
            case "auxclick":
            case "dblclick":
            case "mousedown":
            case "mousemove":
            case "mouseup":
            case "mouseout":
            case "mouseover":
            case "contextmenu":
              St = Nv;
              break;
            case "drag":
            case "dragend":
            case "dragenter":
            case "dragexit":
            case "dragleave":
            case "dragover":
            case "dragstart":
            case "drop":
              St = eA;
              break;
            case "touchcancel":
            case "touchend":
            case "touchmove":
            case "touchstart":
              St = gA;
              break;
            case Qv:
            case Jv:
            case t_:
              St = sA;
              break;
            case e_:
              St = _A;
              break;
            case "scroll":
            case "scrollend":
              St = Jw;
              break;
            case "wheel":
              St = xA;
              break;
            case "copy":
            case "cut":
            case "paste":
              St = aA;
              break;
            case "gotpointercapture":
            case "lostpointercapture":
            case "pointercancel":
            case "pointerdown":
            case "pointermove":
            case "pointerout":
            case "pointerover":
            case "pointerup":
              St = Lv;
              break;
            case "toggle":
            case "beforetoggle":
              St = bA;
          }
          var ce = (r & 4) !== 0, Ke = !ce && (i === "scroll" || i === "scrollend"), ut = ce ? gt !== null ? gt + "Capture" : null : gt;
          ce = [];
          for (var at = pt, ht; at !== null; ) {
            var Tt = at;
            if (ht = Tt.stateNode, Tt = Tt.tag, Tt !== 5 && Tt !== 26 && Tt !== 27 || ht === null || ut === null || (Tt = El(at, ut), Tt != null && ce.push(
              ic(at, Tt, ht)
            )), Ke) break;
            at = at.return;
          }
          0 < ce.length && (gt = new St(
            gt,
            ee,
            null,
            l,
            wt
          ), Ct.push({ event: gt, listeners: ce }));
        }
      }
      if ((r & 7) === 0) {
        t: {
          if (gt = i === "mouseover" || i === "pointerover", St = i === "mouseout" || i === "pointerout", gt && l !== fh && (ee = l.relatedTarget || l.fromElement) && (cs(ee) || ee[Ui]))
            break t;
          if ((St || gt) && (gt = wt.window === wt ? wt : (gt = wt.ownerDocument) ? gt.defaultView || gt.parentWindow : window, St ? (ee = l.relatedTarget || l.toElement, St = pt, ee = ee ? cs(ee) : null, ee !== null && (Ke = o(ee), ce = ee.tag, ee !== Ke || ce !== 5 && ce !== 27 && ce !== 6) && (ee = null)) : (St = null, ee = pt), St !== ee)) {
            if (ce = Nv, Tt = "onMouseLeave", ut = "onMouseEnter", at = "mouse", (i === "pointerout" || i === "pointerover") && (ce = Lv, Tt = "onPointerLeave", ut = "onPointerEnter", at = "pointer"), Ke = St == null ? gt : fs(St), ht = ee == null ? gt : fs(ee), gt = new ce(
              Tt,
              at + "leave",
              St,
              l,
              wt
            ), gt.target = Ke, gt.relatedTarget = ht, Tt = null, cs(wt) === pt && (ce = new ce(
              ut,
              at + "enter",
              ee,
              l,
              wt
            ), ce.target = ht, ce.relatedTarget = Ke, Tt = ce), Ke = Tt, St && ee)
              e: {
                for (ce = ST, ut = St, at = ee, ht = 0, Tt = ut; Tt; Tt = ce(Tt))
                  ht++;
                Tt = 0;
                for (var re = at; re; re = ce(re))
                  Tt++;
                for (; 0 < ht - Tt; )
                  ut = ce(ut), ht--;
                for (; 0 < Tt - ht; )
                  at = ce(at), Tt--;
                for (; ht--; ) {
                  if (ut === at || at !== null && ut === at.alternate) {
                    ce = ut;
                    break e;
                  }
                  ut = ce(ut), at = ce(at);
                }
                ce = null;
              }
            else ce = null;
            St !== null && Ex(
              Ct,
              gt,
              St,
              ce,
              !1
            ), ee !== null && Ke !== null && Ex(
              Ct,
              Ke,
              ee,
              ce,
              !0
            );
          }
        }
        t: {
          if (gt = pt ? fs(pt) : window, St = gt.nodeName && gt.nodeName.toLowerCase(), St === "select" || St === "input" && gt.type === "file")
            var ze = Vv;
          else if (Fv(gt))
            if (Gv)
              ze = OA;
            else {
              ze = DA;
              var ie = RA;
            }
          else
            St = gt.nodeName, !St || St.toLowerCase() !== "input" || gt.type !== "checkbox" && gt.type !== "radio" ? pt && Ja(pt.elementType) && (ze = Vv) : ze = NA;
          if (ze && (ze = ze(i, pt))) {
            Hv(
              Ct,
              ze,
              l,
              wt
            );
            break t;
          }
          ie && ie(i, gt, pt), i === "focusout" && pt && gt.type === "number" && pt.memoizedProps.value != null && vi(gt, "number", gt.value);
        }
        switch (ie = pt ? fs(pt) : window, i) {
          case "focusin":
            (Fv(ie) || ie.contentEditable === "true") && (io = ie, Eh = pt, Ol = null);
            break;
          case "focusout":
            Ol = Eh = io = null;
            break;
          case "mousedown":
            wh = !0;
            break;
          case "contextmenu":
          case "mouseup":
          case "dragend":
            wh = !1, $v(Ct, l, wt);
            break;
          case "selectionchange":
            if (UA) break;
          case "keydown":
          case "keyup":
            $v(Ct, l, wt);
        }
        var be;
        if (xh)
          t: {
            switch (i) {
              case "compositionstart":
                var Ne = "onCompositionStart";
                break t;
              case "compositionend":
                Ne = "onCompositionEnd";
                break t;
              case "compositionupdate":
                Ne = "onCompositionUpdate";
                break t;
            }
            Ne = void 0;
          }
        else
          no ? Bv(i, l) && (Ne = "onCompositionEnd") : i === "keydown" && l.keyCode === 229 && (Ne = "onCompositionStart");
        Ne && (Uv && l.locale !== "ko" && (no || Ne !== "onCompositionStart" ? Ne === "onCompositionEnd" && no && (be = Rv()) : (Sr = wt, mh = "value" in Sr ? Sr.value : Sr.textContent, no = !0)), ie = sf(pt, Ne), 0 < ie.length && (Ne = new Ov(
          Ne,
          i,
          null,
          l,
          wt
        ), Ct.push({ event: Ne, listeners: ie }), be ? Ne.data = be : (be = zv(l), be !== null && (Ne.data = be)))), (be = EA ? wA(i, l) : AA(i, l)) && (Ne = sf(pt, "onBeforeInput"), 0 < Ne.length && (ie = new Ov(
          "onBeforeInput",
          "beforeinput",
          null,
          l,
          wt
        ), Ct.push({
          event: ie,
          listeners: Ne
        }), ie.data = be)), vT(
          Ct,
          i,
          pt,
          l,
          wt
        );
      }
      bx(Ct, r);
    });
  }
  function ic(i, r, l) {
    return {
      instance: i,
      listener: r,
      currentTarget: l
    };
  }
  function sf(i, r) {
    for (var l = r + "Capture", f = []; i !== null; ) {
      var v = i, S = v.stateNode;
      if (v = v.tag, v !== 5 && v !== 26 && v !== 27 || S === null || (v = El(i, l), v != null && f.unshift(
        ic(i, v, S)
      ), v = El(i, r), v != null && f.push(
        ic(i, v, S)
      )), i.tag === 3) return f;
      i = i.return;
    }
    return [];
  }
  function ST(i) {
    if (i === null) return null;
    do
      i = i.return;
    while (i && i.tag !== 5 && i.tag !== 27);
    return i || null;
  }
  function Ex(i, r, l, f, v) {
    for (var S = r._reactName, P = []; l !== null && l !== f; ) {
      var q = l, nt = q.alternate, pt = q.stateNode;
      if (q = q.tag, nt !== null && nt === f) break;
      q !== 5 && q !== 26 && q !== 27 || pt === null || (nt = pt, v ? (pt = El(l, S), pt != null && P.unshift(
        ic(l, pt, nt)
      )) : v || (pt = El(l, S), pt != null && P.push(
        ic(l, pt, nt)
      ))), l = l.return;
    }
    P.length !== 0 && i.push({ event: r, listeners: P });
  }
  var bT = /\r\n?/g, MT = /\u0000|\uFFFD/g;
  function wx(i) {
    return (typeof i == "string" ? i : "" + i).replace(bT, `
`).replace(MT, "");
  }
  function Ax(i, r) {
    return r = wx(r), wx(i) === r;
  }
  function $e(i, r, l, f, v, S) {
    switch (l) {
      case "children":
        typeof f == "string" ? r === "body" || r === "textarea" && f === "" || ei(i, f) : (typeof f == "number" || typeof f == "bigint") && r !== "body" && ei(i, "" + f);
        break;
      case "className":
        pe(i, "class", f);
        break;
      case "tabIndex":
        pe(i, "tabindex", f);
        break;
      case "dir":
      case "role":
      case "viewBox":
      case "width":
      case "height":
        pe(i, l, f);
        break;
      case "style":
        Us(i, f, S);
        break;
      case "data":
        if (r !== "object") {
          pe(i, "data", f);
          break;
        }
      case "src":
      case "href":
        if (f === "" && (r !== "a" || l !== "href")) {
          i.removeAttribute(l);
          break;
        }
        if (f == null || typeof f == "function" || typeof f == "symbol" || typeof f == "boolean") {
          i.removeAttribute(l);
          break;
        }
        f = cu("" + f), i.setAttribute(l, f);
        break;
      case "action":
      case "formAction":
        if (typeof f == "function") {
          i.setAttribute(
            l,
            "javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
          );
          break;
        } else
          typeof S == "function" && (l === "formAction" ? (r !== "input" && $e(i, r, "name", v.name, v, null), $e(
            i,
            r,
            "formEncType",
            v.formEncType,
            v,
            null
          ), $e(
            i,
            r,
            "formMethod",
            v.formMethod,
            v,
            null
          ), $e(
            i,
            r,
            "formTarget",
            v.formTarget,
            v,
            null
          )) : ($e(i, r, "encType", v.encType, v, null), $e(i, r, "method", v.method, v, null), $e(i, r, "target", v.target, v, null)));
        if (f == null || typeof f == "symbol" || typeof f == "boolean") {
          i.removeAttribute(l);
          break;
        }
        f = cu("" + f), i.setAttribute(l, f);
        break;
      case "onClick":
        f != null && (i.onclick = Ps);
        break;
      case "onScroll":
        f != null && Ce("scroll", i);
        break;
      case "onScrollEnd":
        f != null && Ce("scrollend", i);
        break;
      case "dangerouslySetInnerHTML":
        if (f != null) {
          if (typeof f != "object" || !("__html" in f))
            throw Error(s(61));
          if (l = f.__html, l != null) {
            if (v.children != null) throw Error(s(60));
            i.innerHTML = l;
          }
        }
        break;
      case "multiple":
        i.multiple = f && typeof f != "function" && typeof f != "symbol";
        break;
      case "muted":
        i.muted = f && typeof f != "function" && typeof f != "symbol";
        break;
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
      case "defaultValue":
      case "defaultChecked":
      case "innerHTML":
      case "ref":
        break;
      case "autoFocus":
        break;
      case "xlinkHref":
        if (f == null || typeof f == "function" || typeof f == "boolean" || typeof f == "symbol") {
          i.removeAttribute("xlink:href");
          break;
        }
        l = cu("" + f), i.setAttributeNS(
          "http://www.w3.org/1999/xlink",
          "xlink:href",
          l
        );
        break;
      case "contentEditable":
      case "spellCheck":
      case "draggable":
      case "value":
      case "autoReverse":
      case "externalResourcesRequired":
      case "focusable":
      case "preserveAlpha":
        f != null && typeof f != "function" && typeof f != "symbol" ? i.setAttribute(l, "" + f) : i.removeAttribute(l);
        break;
      case "inert":
      case "allowFullScreen":
      case "async":
      case "autoPlay":
      case "controls":
      case "default":
      case "defer":
      case "disabled":
      case "disablePictureInPicture":
      case "disableRemotePlayback":
      case "formNoValidate":
      case "hidden":
      case "loop":
      case "noModule":
      case "noValidate":
      case "open":
      case "playsInline":
      case "readOnly":
      case "required":
      case "reversed":
      case "scoped":
      case "seamless":
      case "itemScope":
        f && typeof f != "function" && typeof f != "symbol" ? i.setAttribute(l, "") : i.removeAttribute(l);
        break;
      case "capture":
      case "download":
        f === !0 ? i.setAttribute(l, "") : f !== !1 && f != null && typeof f != "function" && typeof f != "symbol" ? i.setAttribute(l, f) : i.removeAttribute(l);
        break;
      case "cols":
      case "rows":
      case "size":
      case "span":
        f != null && typeof f != "function" && typeof f != "symbol" && !isNaN(f) && 1 <= f ? i.setAttribute(l, f) : i.removeAttribute(l);
        break;
      case "rowSpan":
      case "start":
        f == null || typeof f == "function" || typeof f == "symbol" || isNaN(f) ? i.removeAttribute(l) : i.setAttribute(l, f);
        break;
      case "popover":
        Ce("beforetoggle", i), Ce("toggle", i), ue(i, "popover", f);
        break;
      case "xlinkActuate":
        $t(
          i,
          "http://www.w3.org/1999/xlink",
          "xlink:actuate",
          f
        );
        break;
      case "xlinkArcrole":
        $t(
          i,
          "http://www.w3.org/1999/xlink",
          "xlink:arcrole",
          f
        );
        break;
      case "xlinkRole":
        $t(
          i,
          "http://www.w3.org/1999/xlink",
          "xlink:role",
          f
        );
        break;
      case "xlinkShow":
        $t(
          i,
          "http://www.w3.org/1999/xlink",
          "xlink:show",
          f
        );
        break;
      case "xlinkTitle":
        $t(
          i,
          "http://www.w3.org/1999/xlink",
          "xlink:title",
          f
        );
        break;
      case "xlinkType":
        $t(
          i,
          "http://www.w3.org/1999/xlink",
          "xlink:type",
          f
        );
        break;
      case "xmlBase":
        $t(
          i,
          "http://www.w3.org/XML/1998/namespace",
          "xml:base",
          f
        );
        break;
      case "xmlLang":
        $t(
          i,
          "http://www.w3.org/XML/1998/namespace",
          "xml:lang",
          f
        );
        break;
      case "xmlSpace":
        $t(
          i,
          "http://www.w3.org/XML/1998/namespace",
          "xml:space",
          f
        );
        break;
      case "is":
        ue(i, "is", f);
        break;
      case "innerText":
      case "textContent":
        break;
      default:
        (!(2 < l.length) || l[0] !== "o" && l[0] !== "O" || l[1] !== "n" && l[1] !== "N") && (l = Kw.get(l) || l, ue(i, l, f));
    }
  }
  function $p(i, r, l, f, v, S) {
    switch (l) {
      case "style":
        Us(i, f, S);
        break;
      case "dangerouslySetInnerHTML":
        if (f != null) {
          if (typeof f != "object" || !("__html" in f))
            throw Error(s(61));
          if (l = f.__html, l != null) {
            if (v.children != null) throw Error(s(60));
            i.innerHTML = l;
          }
        }
        break;
      case "children":
        typeof f == "string" ? ei(i, f) : (typeof f == "number" || typeof f == "bigint") && ei(i, "" + f);
        break;
      case "onScroll":
        f != null && Ce("scroll", i);
        break;
      case "onScrollEnd":
        f != null && Ce("scrollend", i);
        break;
      case "onClick":
        f != null && (i.onclick = Ps);
        break;
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
      case "innerHTML":
      case "ref":
        break;
      case "innerText":
      case "textContent":
        break;
      default:
        if (!mt.hasOwnProperty(l))
          t: {
            if (l[0] === "o" && l[1] === "n" && (v = l.endsWith("Capture"), r = l.slice(2, v ? l.length - 7 : void 0), S = i[hn] || null, S = S != null ? S[l] : null, typeof S == "function" && i.removeEventListener(r, S, v), typeof f == "function")) {
              typeof S != "function" && S !== null && (l in i ? i[l] = null : i.hasAttribute(l) && i.removeAttribute(l)), i.addEventListener(r, f, v);
              break t;
            }
            l in i ? i[l] = f : f === !0 ? i.setAttribute(l, "") : ue(i, l, f);
          }
    }
  }
  function Xn(i, r, l) {
    switch (r) {
      case "div":
      case "span":
      case "svg":
      case "path":
      case "a":
      case "g":
      case "p":
      case "li":
        break;
      case "img":
        Ce("error", i), Ce("load", i);
        var f = !1, v = !1, S;
        for (S in l)
          if (l.hasOwnProperty(S)) {
            var P = l[S];
            if (P != null)
              switch (S) {
                case "src":
                  f = !0;
                  break;
                case "srcSet":
                  v = !0;
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(s(137, r));
                default:
                  $e(i, r, S, P, l, null);
              }
          }
        v && $e(i, r, "srcSet", l.srcSet, l, null), f && $e(i, r, "src", l.src, l, null);
        return;
      case "input":
        Ce("invalid", i);
        var q = S = P = v = null, nt = null, pt = null;
        for (f in l)
          if (l.hasOwnProperty(f)) {
            var wt = l[f];
            if (wt != null)
              switch (f) {
                case "name":
                  v = wt;
                  break;
                case "type":
                  P = wt;
                  break;
                case "checked":
                  nt = wt;
                  break;
                case "defaultChecked":
                  pt = wt;
                  break;
                case "value":
                  S = wt;
                  break;
                case "defaultValue":
                  q = wt;
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  if (wt != null)
                    throw Error(s(137, r));
                  break;
                default:
                  $e(i, r, f, wt, l, null);
              }
          }
        ti(
          i,
          S,
          q,
          nt,
          pt,
          P,
          v,
          !1
        );
        return;
      case "select":
        Ce("invalid", i), f = P = S = null;
        for (v in l)
          if (l.hasOwnProperty(v) && (q = l[v], q != null))
            switch (v) {
              case "value":
                S = q;
                break;
              case "defaultValue":
                P = q;
                break;
              case "multiple":
                f = q;
              default:
                $e(i, r, v, q, l, null);
            }
        r = S, l = P, i.multiple = !!f, r != null ? qn(i, !!f, r, !1) : l != null && qn(i, !!f, l, !0);
        return;
      case "textarea":
        Ce("invalid", i), S = v = f = null;
        for (P in l)
          if (l.hasOwnProperty(P) && (q = l[P], q != null))
            switch (P) {
              case "value":
                f = q;
                break;
              case "defaultValue":
                v = q;
                break;
              case "children":
                S = q;
                break;
              case "dangerouslySetInnerHTML":
                if (q != null) throw Error(s(91));
                break;
              default:
                $e(i, r, P, q, l, null);
            }
        yn(i, f, v, S);
        return;
      case "option":
        for (nt in l)
          if (l.hasOwnProperty(nt) && (f = l[nt], f != null))
            switch (nt) {
              case "selected":
                i.selected = f && typeof f != "function" && typeof f != "symbol";
                break;
              default:
                $e(i, r, nt, f, l, null);
            }
        return;
      case "dialog":
        Ce("beforetoggle", i), Ce("toggle", i), Ce("cancel", i), Ce("close", i);
        break;
      case "iframe":
      case "object":
        Ce("load", i);
        break;
      case "video":
      case "audio":
        for (f = 0; f < nc.length; f++)
          Ce(nc[f], i);
        break;
      case "image":
        Ce("error", i), Ce("load", i);
        break;
      case "details":
        Ce("toggle", i);
        break;
      case "embed":
      case "source":
      case "link":
        Ce("error", i), Ce("load", i);
      case "area":
      case "base":
      case "br":
      case "col":
      case "hr":
      case "keygen":
      case "meta":
      case "param":
      case "track":
      case "wbr":
      case "menuitem":
        for (pt in l)
          if (l.hasOwnProperty(pt) && (f = l[pt], f != null))
            switch (pt) {
              case "children":
              case "dangerouslySetInnerHTML":
                throw Error(s(137, r));
              default:
                $e(i, r, pt, f, l, null);
            }
        return;
      default:
        if (Ja(r)) {
          for (wt in l)
            l.hasOwnProperty(wt) && (f = l[wt], f !== void 0 && $p(
              i,
              r,
              wt,
              f,
              l,
              void 0
            ));
          return;
        }
    }
    for (q in l)
      l.hasOwnProperty(q) && (f = l[q], f != null && $e(i, r, q, f, l, null));
  }
  function ET(i, r, l, f) {
    switch (r) {
      case "div":
      case "span":
      case "svg":
      case "path":
      case "a":
      case "g":
      case "p":
      case "li":
        break;
      case "input":
        var v = null, S = null, P = null, q = null, nt = null, pt = null, wt = null;
        for (St in l) {
          var Ct = l[St];
          if (l.hasOwnProperty(St) && Ct != null)
            switch (St) {
              case "checked":
                break;
              case "value":
                break;
              case "defaultValue":
                nt = Ct;
              default:
                f.hasOwnProperty(St) || $e(i, r, St, null, f, Ct);
            }
        }
        for (var gt in f) {
          var St = f[gt];
          if (Ct = l[gt], f.hasOwnProperty(gt) && (St != null || Ct != null))
            switch (gt) {
              case "type":
                S = St;
                break;
              case "name":
                v = St;
                break;
              case "checked":
                pt = St;
                break;
              case "defaultChecked":
                wt = St;
                break;
              case "value":
                P = St;
                break;
              case "defaultValue":
                q = St;
                break;
              case "children":
              case "dangerouslySetInnerHTML":
                if (St != null)
                  throw Error(s(137, r));
                break;
              default:
                St !== Ct && $e(
                  i,
                  r,
                  gt,
                  St,
                  f,
                  Ct
                );
            }
        }
        Dn(
          i,
          P,
          q,
          nt,
          pt,
          wt,
          S,
          v
        );
        return;
      case "select":
        St = P = q = gt = null;
        for (S in l)
          if (nt = l[S], l.hasOwnProperty(S) && nt != null)
            switch (S) {
              case "value":
                break;
              case "multiple":
                St = nt;
              default:
                f.hasOwnProperty(S) || $e(
                  i,
                  r,
                  S,
                  null,
                  f,
                  nt
                );
            }
        for (v in f)
          if (S = f[v], nt = l[v], f.hasOwnProperty(v) && (S != null || nt != null))
            switch (v) {
              case "value":
                gt = S;
                break;
              case "defaultValue":
                q = S;
                break;
              case "multiple":
                P = S;
              default:
                S !== nt && $e(
                  i,
                  r,
                  v,
                  S,
                  f,
                  nt
                );
            }
        r = q, l = P, f = St, gt != null ? qn(i, !!l, gt, !1) : !!f != !!l && (r != null ? qn(i, !!l, r, !0) : qn(i, !!l, l ? [] : "", !1));
        return;
      case "textarea":
        St = gt = null;
        for (q in l)
          if (v = l[q], l.hasOwnProperty(q) && v != null && !f.hasOwnProperty(q))
            switch (q) {
              case "value":
                break;
              case "children":
                break;
              default:
                $e(i, r, q, null, f, v);
            }
        for (P in f)
          if (v = f[P], S = l[P], f.hasOwnProperty(P) && (v != null || S != null))
            switch (P) {
              case "value":
                gt = v;
                break;
              case "defaultValue":
                St = v;
                break;
              case "children":
                break;
              case "dangerouslySetInnerHTML":
                if (v != null) throw Error(s(91));
                break;
              default:
                v !== S && $e(i, r, P, v, f, S);
            }
        Ge(i, gt, St);
        return;
      case "option":
        for (var ee in l)
          if (gt = l[ee], l.hasOwnProperty(ee) && gt != null && !f.hasOwnProperty(ee))
            switch (ee) {
              case "selected":
                i.selected = !1;
                break;
              default:
                $e(
                  i,
                  r,
                  ee,
                  null,
                  f,
                  gt
                );
            }
        for (nt in f)
          if (gt = f[nt], St = l[nt], f.hasOwnProperty(nt) && gt !== St && (gt != null || St != null))
            switch (nt) {
              case "selected":
                i.selected = gt && typeof gt != "function" && typeof gt != "symbol";
                break;
              default:
                $e(
                  i,
                  r,
                  nt,
                  gt,
                  f,
                  St
                );
            }
        return;
      case "img":
      case "link":
      case "area":
      case "base":
      case "br":
      case "col":
      case "embed":
      case "hr":
      case "keygen":
      case "meta":
      case "param":
      case "source":
      case "track":
      case "wbr":
      case "menuitem":
        for (var ce in l)
          gt = l[ce], l.hasOwnProperty(ce) && gt != null && !f.hasOwnProperty(ce) && $e(i, r, ce, null, f, gt);
        for (pt in f)
          if (gt = f[pt], St = l[pt], f.hasOwnProperty(pt) && gt !== St && (gt != null || St != null))
            switch (pt) {
              case "children":
              case "dangerouslySetInnerHTML":
                if (gt != null)
                  throw Error(s(137, r));
                break;
              default:
                $e(
                  i,
                  r,
                  pt,
                  gt,
                  f,
                  St
                );
            }
        return;
      default:
        if (Ja(r)) {
          for (var Ke in l)
            gt = l[Ke], l.hasOwnProperty(Ke) && gt !== void 0 && !f.hasOwnProperty(Ke) && $p(
              i,
              r,
              Ke,
              void 0,
              f,
              gt
            );
          for (wt in f)
            gt = f[wt], St = l[wt], !f.hasOwnProperty(wt) || gt === St || gt === void 0 && St === void 0 || $p(
              i,
              r,
              wt,
              gt,
              f,
              St
            );
          return;
        }
    }
    for (var ut in l)
      gt = l[ut], l.hasOwnProperty(ut) && gt != null && !f.hasOwnProperty(ut) && $e(i, r, ut, null, f, gt);
    for (Ct in f)
      gt = f[Ct], St = l[Ct], !f.hasOwnProperty(Ct) || gt === St || gt == null && St == null || $e(i, r, Ct, gt, f, St);
  }
  function Tx(i) {
    switch (i) {
      case "css":
      case "script":
      case "font":
      case "img":
      case "image":
      case "input":
      case "link":
        return !0;
      default:
        return !1;
    }
  }
  function wT() {
    if (typeof performance.getEntriesByType == "function") {
      for (var i = 0, r = 0, l = performance.getEntriesByType("resource"), f = 0; f < l.length; f++) {
        var v = l[f], S = v.transferSize, P = v.initiatorType, q = v.duration;
        if (S && q && Tx(P)) {
          for (P = 0, q = v.responseEnd, f += 1; f < l.length; f++) {
            var nt = l[f], pt = nt.startTime;
            if (pt > q) break;
            var wt = nt.transferSize, Ct = nt.initiatorType;
            wt && Tx(Ct) && (nt = nt.responseEnd, P += wt * (nt < q ? 1 : (q - pt) / (nt - pt)));
          }
          if (--f, r += 8 * (S + P) / (v.duration / 1e3), i++, 10 < i) break;
        }
      }
      if (0 < i) return r / i / 1e6;
    }
    return navigator.connection && (i = navigator.connection.downlink, typeof i == "number") ? i : 5;
  }
  var Kp = null, Qp = null;
  function rf(i) {
    return i.nodeType === 9 ? i : i.ownerDocument;
  }
  function Cx(i) {
    switch (i) {
      case "http://www.w3.org/2000/svg":
        return 1;
      case "http://www.w3.org/1998/Math/MathML":
        return 2;
      default:
        return 0;
    }
  }
  function Rx(i, r) {
    if (i === 0)
      switch (r) {
        case "svg":
          return 1;
        case "math":
          return 2;
        default:
          return 0;
      }
    return i === 1 && r === "foreignObject" ? 0 : i;
  }
  function Jp(i, r) {
    return i === "textarea" || i === "noscript" || typeof r.children == "string" || typeof r.children == "number" || typeof r.children == "bigint" || typeof r.dangerouslySetInnerHTML == "object" && r.dangerouslySetInnerHTML !== null && r.dangerouslySetInnerHTML.__html != null;
  }
  var tm = null;
  function AT() {
    var i = window.event;
    return i && i.type === "popstate" ? i === tm ? !1 : (tm = i, !0) : (tm = null, !1);
  }
  var Dx = typeof setTimeout == "function" ? setTimeout : void 0, TT = typeof clearTimeout == "function" ? clearTimeout : void 0, Nx = typeof Promise == "function" ? Promise : void 0, CT = typeof queueMicrotask == "function" ? queueMicrotask : typeof Nx < "u" ? function(i) {
    return Nx.resolve(null).then(i).catch(RT);
  } : Dx;
  function RT(i) {
    setTimeout(function() {
      throw i;
    });
  }
  function zr(i) {
    return i === "head";
  }
  function Ox(i, r) {
    var l = r, f = 0;
    do {
      var v = l.nextSibling;
      if (i.removeChild(l), v && v.nodeType === 8)
        if (l = v.data, l === "/$" || l === "/&") {
          if (f === 0) {
            i.removeChild(v), No(r);
            return;
          }
          f--;
        } else if (l === "$" || l === "$?" || l === "$~" || l === "$!" || l === "&")
          f++;
        else if (l === "html")
          sc(i.ownerDocument.documentElement);
        else if (l === "head") {
          l = i.ownerDocument.head, sc(l);
          for (var S = l.firstChild; S; ) {
            var P = S.nextSibling, q = S.nodeName;
            S[Ls] || q === "SCRIPT" || q === "STYLE" || q === "LINK" && S.rel.toLowerCase() === "stylesheet" || l.removeChild(S), S = P;
          }
        } else
          l === "body" && sc(i.ownerDocument.body);
      l = v;
    } while (l);
    No(r);
  }
  function Lx(i, r) {
    var l = i;
    i = 0;
    do {
      var f = l.nextSibling;
      if (l.nodeType === 1 ? r ? (l._stashedDisplay = l.style.display, l.style.display = "none") : (l.style.display = l._stashedDisplay || "", l.getAttribute("style") === "" && l.removeAttribute("style")) : l.nodeType === 3 && (r ? (l._stashedText = l.nodeValue, l.nodeValue = "") : l.nodeValue = l._stashedText || ""), f && f.nodeType === 8)
        if (l = f.data, l === "/$") {
          if (i === 0) break;
          i--;
        } else
          l !== "$" && l !== "$?" && l !== "$~" && l !== "$!" || i++;
      l = f;
    } while (l);
  }
  function em(i) {
    var r = i.firstChild;
    for (r && r.nodeType === 10 && (r = r.nextSibling); r; ) {
      var l = r;
      switch (r = r.nextSibling, l.nodeName) {
        case "HTML":
        case "HEAD":
        case "BODY":
          em(l), ca(l);
          continue;
        case "SCRIPT":
        case "STYLE":
          continue;
        case "LINK":
          if (l.rel.toLowerCase() === "stylesheet") continue;
      }
      i.removeChild(l);
    }
  }
  function DT(i, r, l, f) {
    for (; i.nodeType === 1; ) {
      var v = l;
      if (i.nodeName.toLowerCase() !== r.toLowerCase()) {
        if (!f && (i.nodeName !== "INPUT" || i.type !== "hidden"))
          break;
      } else if (f) {
        if (!i[Ls])
          switch (r) {
            case "meta":
              if (!i.hasAttribute("itemprop")) break;
              return i;
            case "link":
              if (S = i.getAttribute("rel"), S === "stylesheet" && i.hasAttribute("data-precedence"))
                break;
              if (S !== v.rel || i.getAttribute("href") !== (v.href == null || v.href === "" ? null : v.href) || i.getAttribute("crossorigin") !== (v.crossOrigin == null ? null : v.crossOrigin) || i.getAttribute("title") !== (v.title == null ? null : v.title))
                break;
              return i;
            case "style":
              if (i.hasAttribute("data-precedence")) break;
              return i;
            case "script":
              if (S = i.getAttribute("src"), (S !== (v.src == null ? null : v.src) || i.getAttribute("type") !== (v.type == null ? null : v.type) || i.getAttribute("crossorigin") !== (v.crossOrigin == null ? null : v.crossOrigin)) && S && i.hasAttribute("async") && !i.hasAttribute("itemprop"))
                break;
              return i;
            default:
              return i;
          }
      } else if (r === "input" && i.type === "hidden") {
        var S = v.name == null ? null : "" + v.name;
        if (v.type === "hidden" && i.getAttribute("name") === S)
          return i;
      } else return i;
      if (i = Vi(i.nextSibling), i === null) break;
    }
    return null;
  }
  function NT(i, r, l) {
    if (r === "") return null;
    for (; i.nodeType !== 3; )
      if ((i.nodeType !== 1 || i.nodeName !== "INPUT" || i.type !== "hidden") && !l || (i = Vi(i.nextSibling), i === null)) return null;
    return i;
  }
  function Ux(i, r) {
    for (; i.nodeType !== 8; )
      if ((i.nodeType !== 1 || i.nodeName !== "INPUT" || i.type !== "hidden") && !r || (i = Vi(i.nextSibling), i === null)) return null;
    return i;
  }
  function nm(i) {
    return i.data === "$?" || i.data === "$~";
  }
  function im(i) {
    return i.data === "$!" || i.data === "$?" && i.ownerDocument.readyState !== "loading";
  }
  function OT(i, r) {
    var l = i.ownerDocument;
    if (i.data === "$~") i._reactRetry = r;
    else if (i.data !== "$?" || l.readyState !== "loading")
      r();
    else {
      var f = function() {
        r(), l.removeEventListener("DOMContentLoaded", f);
      };
      l.addEventListener("DOMContentLoaded", f), i._reactRetry = f;
    }
  }
  function Vi(i) {
    for (; i != null; i = i.nextSibling) {
      var r = i.nodeType;
      if (r === 1 || r === 3) break;
      if (r === 8) {
        if (r = i.data, r === "$" || r === "$!" || r === "$?" || r === "$~" || r === "&" || r === "F!" || r === "F")
          break;
        if (r === "/$" || r === "/&") return null;
      }
    }
    return i;
  }
  var sm = null;
  function Px(i) {
    i = i.nextSibling;
    for (var r = 0; i; ) {
      if (i.nodeType === 8) {
        var l = i.data;
        if (l === "/$" || l === "/&") {
          if (r === 0)
            return Vi(i.nextSibling);
          r--;
        } else
          l !== "$" && l !== "$!" && l !== "$?" && l !== "$~" && l !== "&" || r++;
      }
      i = i.nextSibling;
    }
    return null;
  }
  function Ix(i) {
    i = i.previousSibling;
    for (var r = 0; i; ) {
      if (i.nodeType === 8) {
        var l = i.data;
        if (l === "$" || l === "$!" || l === "$?" || l === "$~" || l === "&") {
          if (r === 0) return i;
          r--;
        } else l !== "/$" && l !== "/&" || r++;
      }
      i = i.previousSibling;
    }
    return null;
  }
  function Bx(i, r, l) {
    switch (r = rf(l), i) {
      case "html":
        if (i = r.documentElement, !i) throw Error(s(452));
        return i;
      case "head":
        if (i = r.head, !i) throw Error(s(453));
        return i;
      case "body":
        if (i = r.body, !i) throw Error(s(454));
        return i;
      default:
        throw Error(s(451));
    }
  }
  function sc(i) {
    for (var r = i.attributes; r.length; )
      i.removeAttributeNode(r[0]);
    ca(i);
  }
  var Gi = /* @__PURE__ */ new Map(), zx = /* @__PURE__ */ new Set();
  function af(i) {
    return typeof i.getRootNode == "function" ? i.getRootNode() : i.nodeType === 9 ? i : i.ownerDocument;
  }
  var Ks = I.d;
  I.d = {
    f: LT,
    r: UT,
    D: PT,
    C: IT,
    L: BT,
    m: zT,
    X: HT,
    S: FT,
    M: VT
  };
  function LT() {
    var i = Ks.f(), r = $u();
    return i || r;
  }
  function UT(i) {
    var r = us(i);
    r !== null && r.tag === 5 && r.type === "form" ? ey(r) : Ks.r(i);
  }
  var Co = typeof document > "u" ? null : document;
  function Fx(i, r, l) {
    var f = Co;
    if (f && typeof r == "string" && r) {
      var v = he(r);
      v = 'link[rel="' + i + '"][href="' + v + '"]', typeof l == "string" && (v += '[crossorigin="' + l + '"]'), zx.has(v) || (zx.add(v), i = { rel: i, crossOrigin: l, href: r }, f.querySelector(v) === null && (r = f.createElement("link"), Xn(r, "link", i), ot(r), f.head.appendChild(r)));
    }
  }
  function PT(i) {
    Ks.D(i), Fx("dns-prefetch", i, null);
  }
  function IT(i, r) {
    Ks.C(i, r), Fx("preconnect", i, r);
  }
  function BT(i, r, l) {
    Ks.L(i, r, l);
    var f = Co;
    if (f && i && r) {
      var v = 'link[rel="preload"][as="' + he(r) + '"]';
      r === "image" && l && l.imageSrcSet ? (v += '[imagesrcset="' + he(
        l.imageSrcSet
      ) + '"]', typeof l.imageSizes == "string" && (v += '[imagesizes="' + he(
        l.imageSizes
      ) + '"]')) : v += '[href="' + he(i) + '"]';
      var S = v;
      switch (r) {
        case "style":
          S = Ro(i);
          break;
        case "script":
          S = Do(i);
      }
      Gi.has(S) || (i = p(
        {
          rel: "preload",
          href: r === "image" && l && l.imageSrcSet ? void 0 : i,
          as: r
        },
        l
      ), Gi.set(S, i), f.querySelector(v) !== null || r === "style" && f.querySelector(rc(S)) || r === "script" && f.querySelector(ac(S)) || (r = f.createElement("link"), Xn(r, "link", i), ot(r), f.head.appendChild(r)));
    }
  }
  function zT(i, r) {
    Ks.m(i, r);
    var l = Co;
    if (l && i) {
      var f = r && typeof r.as == "string" ? r.as : "script", v = 'link[rel="modulepreload"][as="' + he(f) + '"][href="' + he(i) + '"]', S = v;
      switch (f) {
        case "audioworklet":
        case "paintworklet":
        case "serviceworker":
        case "sharedworker":
        case "worker":
        case "script":
          S = Do(i);
      }
      if (!Gi.has(S) && (i = p({ rel: "modulepreload", href: i }, r), Gi.set(S, i), l.querySelector(v) === null)) {
        switch (f) {
          case "audioworklet":
          case "paintworklet":
          case "serviceworker":
          case "sharedworker":
          case "worker":
          case "script":
            if (l.querySelector(ac(S)))
              return;
        }
        f = l.createElement("link"), Xn(f, "link", i), ot(f), l.head.appendChild(f);
      }
    }
  }
  function FT(i, r, l) {
    Ks.S(i, r, l);
    var f = Co;
    if (f && i) {
      var v = Z(f).hoistableStyles, S = Ro(i);
      r = r || "default";
      var P = v.get(S);
      if (!P) {
        var q = { loading: 0, preload: null };
        if (P = f.querySelector(
          rc(S)
        ))
          q.loading = 5;
        else {
          i = p(
            { rel: "stylesheet", href: i, "data-precedence": r },
            l
          ), (l = Gi.get(S)) && rm(i, l);
          var nt = P = f.createElement("link");
          ot(nt), Xn(nt, "link", i), nt._p = new Promise(function(pt, wt) {
            nt.onload = pt, nt.onerror = wt;
          }), nt.addEventListener("load", function() {
            q.loading |= 1;
          }), nt.addEventListener("error", function() {
            q.loading |= 2;
          }), q.loading |= 4, of(P, r, f);
        }
        P = {
          type: "stylesheet",
          instance: P,
          count: 1,
          state: q
        }, v.set(S, P);
      }
    }
  }
  function HT(i, r) {
    Ks.X(i, r);
    var l = Co;
    if (l && i) {
      var f = Z(l).hoistableScripts, v = Do(i), S = f.get(v);
      S || (S = l.querySelector(ac(v)), S || (i = p({ src: i, async: !0 }, r), (r = Gi.get(v)) && am(i, r), S = l.createElement("script"), ot(S), Xn(S, "link", i), l.head.appendChild(S)), S = {
        type: "script",
        instance: S,
        count: 1,
        state: null
      }, f.set(v, S));
    }
  }
  function VT(i, r) {
    Ks.M(i, r);
    var l = Co;
    if (l && i) {
      var f = Z(l).hoistableScripts, v = Do(i), S = f.get(v);
      S || (S = l.querySelector(ac(v)), S || (i = p({ src: i, async: !0, type: "module" }, r), (r = Gi.get(v)) && am(i, r), S = l.createElement("script"), ot(S), Xn(S, "link", i), l.head.appendChild(S)), S = {
        type: "script",
        instance: S,
        count: 1,
        state: null
      }, f.set(v, S));
    }
  }
  function Hx(i, r, l, f) {
    var v = (v = Y.current) ? af(v) : null;
    if (!v) throw Error(s(446));
    switch (i) {
      case "meta":
      case "title":
        return null;
      case "style":
        return typeof l.precedence == "string" && typeof l.href == "string" ? (r = Ro(l.href), l = Z(
          v
        ).hoistableStyles, f = l.get(r), f || (f = {
          type: "style",
          instance: null,
          count: 0,
          state: null
        }, l.set(r, f)), f) : { type: "void", instance: null, count: 0, state: null };
      case "link":
        if (l.rel === "stylesheet" && typeof l.href == "string" && typeof l.precedence == "string") {
          i = Ro(l.href);
          var S = Z(
            v
          ).hoistableStyles, P = S.get(i);
          if (P || (v = v.ownerDocument || v, P = {
            type: "stylesheet",
            instance: null,
            count: 0,
            state: { loading: 0, preload: null }
          }, S.set(i, P), (S = v.querySelector(
            rc(i)
          )) && !S._p && (P.instance = S, P.state.loading = 5), Gi.has(i) || (l = {
            rel: "preload",
            as: "style",
            href: l.href,
            crossOrigin: l.crossOrigin,
            integrity: l.integrity,
            media: l.media,
            hrefLang: l.hrefLang,
            referrerPolicy: l.referrerPolicy
          }, Gi.set(i, l), S || GT(
            v,
            i,
            l,
            P.state
          ))), r && f === null)
            throw Error(s(528, ""));
          return P;
        }
        if (r && f !== null)
          throw Error(s(529, ""));
        return null;
      case "script":
        return r = l.async, l = l.src, typeof l == "string" && r && typeof r != "function" && typeof r != "symbol" ? (r = Do(l), l = Z(
          v
        ).hoistableScripts, f = l.get(r), f || (f = {
          type: "script",
          instance: null,
          count: 0,
          state: null
        }, l.set(r, f)), f) : { type: "void", instance: null, count: 0, state: null };
      default:
        throw Error(s(444, i));
    }
  }
  function Ro(i) {
    return 'href="' + he(i) + '"';
  }
  function rc(i) {
    return 'link[rel="stylesheet"][' + i + "]";
  }
  function Vx(i) {
    return p({}, i, {
      "data-precedence": i.precedence,
      precedence: null
    });
  }
  function GT(i, r, l, f) {
    i.querySelector('link[rel="preload"][as="style"][' + r + "]") ? f.loading = 1 : (r = i.createElement("link"), f.preload = r, r.addEventListener("load", function() {
      return f.loading |= 1;
    }), r.addEventListener("error", function() {
      return f.loading |= 2;
    }), Xn(r, "link", l), ot(r), i.head.appendChild(r));
  }
  function Do(i) {
    return '[src="' + he(i) + '"]';
  }
  function ac(i) {
    return "script[async]" + i;
  }
  function Gx(i, r, l) {
    if (r.count++, r.instance === null)
      switch (r.type) {
        case "style":
          var f = i.querySelector(
            'style[data-href~="' + he(l.href) + '"]'
          );
          if (f)
            return r.instance = f, ot(f), f;
          var v = p({}, l, {
            "data-href": l.href,
            "data-precedence": l.precedence,
            href: null,
            precedence: null
          });
          return f = (i.ownerDocument || i).createElement(
            "style"
          ), ot(f), Xn(f, "style", v), of(f, l.precedence, i), r.instance = f;
        case "stylesheet":
          v = Ro(l.href);
          var S = i.querySelector(
            rc(v)
          );
          if (S)
            return r.state.loading |= 4, r.instance = S, ot(S), S;
          f = Vx(l), (v = Gi.get(v)) && rm(f, v), S = (i.ownerDocument || i).createElement("link"), ot(S);
          var P = S;
          return P._p = new Promise(function(q, nt) {
            P.onload = q, P.onerror = nt;
          }), Xn(S, "link", f), r.state.loading |= 4, of(S, l.precedence, i), r.instance = S;
        case "script":
          return S = Do(l.src), (v = i.querySelector(
            ac(S)
          )) ? (r.instance = v, ot(v), v) : (f = l, (v = Gi.get(S)) && (f = p({}, l), am(f, v)), i = i.ownerDocument || i, v = i.createElement("script"), ot(v), Xn(v, "link", f), i.head.appendChild(v), r.instance = v);
        case "void":
          return null;
        default:
          throw Error(s(443, r.type));
      }
    else
      r.type === "stylesheet" && (r.state.loading & 4) === 0 && (f = r.instance, r.state.loading |= 4, of(f, l.precedence, i));
    return r.instance;
  }
  function of(i, r, l) {
    for (var f = l.querySelectorAll(
      'link[rel="stylesheet"][data-precedence],style[data-precedence]'
    ), v = f.length ? f[f.length - 1] : null, S = v, P = 0; P < f.length; P++) {
      var q = f[P];
      if (q.dataset.precedence === r) S = q;
      else if (S !== v) break;
    }
    S ? S.parentNode.insertBefore(i, S.nextSibling) : (r = l.nodeType === 9 ? l.head : l, r.insertBefore(i, r.firstChild));
  }
  function rm(i, r) {
    i.crossOrigin == null && (i.crossOrigin = r.crossOrigin), i.referrerPolicy == null && (i.referrerPolicy = r.referrerPolicy), i.title == null && (i.title = r.title);
  }
  function am(i, r) {
    i.crossOrigin == null && (i.crossOrigin = r.crossOrigin), i.referrerPolicy == null && (i.referrerPolicy = r.referrerPolicy), i.integrity == null && (i.integrity = r.integrity);
  }
  var lf = null;
  function kx(i, r, l) {
    if (lf === null) {
      var f = /* @__PURE__ */ new Map(), v = lf = /* @__PURE__ */ new Map();
      v.set(l, f);
    } else
      v = lf, f = v.get(l), f || (f = /* @__PURE__ */ new Map(), v.set(l, f));
    if (f.has(i)) return f;
    for (f.set(i, null), l = l.getElementsByTagName(i), v = 0; v < l.length; v++) {
      var S = l[v];
      if (!(S[Ls] || S[cn] || i === "link" && S.getAttribute("rel") === "stylesheet") && S.namespaceURI !== "http://www.w3.org/2000/svg") {
        var P = S.getAttribute(r) || "";
        P = i + P;
        var q = f.get(P);
        q ? q.push(S) : f.set(P, [S]);
      }
    }
    return f;
  }
  function Xx(i, r, l) {
    i = i.ownerDocument || i, i.head.insertBefore(
      l,
      r === "title" ? i.querySelector("head > title") : null
    );
  }
  function kT(i, r, l) {
    if (l === 1 || r.itemProp != null) return !1;
    switch (i) {
      case "meta":
      case "title":
        return !0;
      case "style":
        if (typeof r.precedence != "string" || typeof r.href != "string" || r.href === "")
          break;
        return !0;
      case "link":
        if (typeof r.rel != "string" || typeof r.href != "string" || r.href === "" || r.onLoad || r.onError)
          break;
        switch (r.rel) {
          case "stylesheet":
            return i = r.disabled, typeof r.precedence == "string" && i == null;
          default:
            return !0;
        }
      case "script":
        if (r.async && typeof r.async != "function" && typeof r.async != "symbol" && !r.onLoad && !r.onError && r.src && typeof r.src == "string")
          return !0;
    }
    return !1;
  }
  function Wx(i) {
    return !(i.type === "stylesheet" && (i.state.loading & 3) === 0);
  }
  function XT(i, r, l, f) {
    if (l.type === "stylesheet" && (typeof f.media != "string" || matchMedia(f.media).matches !== !1) && (l.state.loading & 4) === 0) {
      if (l.instance === null) {
        var v = Ro(f.href), S = r.querySelector(
          rc(v)
        );
        if (S) {
          r = S._p, r !== null && typeof r == "object" && typeof r.then == "function" && (i.count++, i = cf.bind(i), r.then(i, i)), l.state.loading |= 4, l.instance = S, ot(S);
          return;
        }
        S = r.ownerDocument || r, f = Vx(f), (v = Gi.get(v)) && rm(f, v), S = S.createElement("link"), ot(S);
        var P = S;
        P._p = new Promise(function(q, nt) {
          P.onload = q, P.onerror = nt;
        }), Xn(S, "link", f), l.instance = S;
      }
      i.stylesheets === null && (i.stylesheets = /* @__PURE__ */ new Map()), i.stylesheets.set(l, r), (r = l.state.preload) && (l.state.loading & 3) === 0 && (i.count++, l = cf.bind(i), r.addEventListener("load", l), r.addEventListener("error", l));
    }
  }
  var om = 0;
  function WT(i, r) {
    return i.stylesheets && i.count === 0 && ff(i, i.stylesheets), 0 < i.count || 0 < i.imgCount ? function(l) {
      var f = setTimeout(function() {
        if (i.stylesheets && ff(i, i.stylesheets), i.unsuspend) {
          var S = i.unsuspend;
          i.unsuspend = null, S();
        }
      }, 6e4 + r);
      0 < i.imgBytes && om === 0 && (om = 62500 * wT());
      var v = setTimeout(
        function() {
          if (i.waitingForImages = !1, i.count === 0 && (i.stylesheets && ff(i, i.stylesheets), i.unsuspend)) {
            var S = i.unsuspend;
            i.unsuspend = null, S();
          }
        },
        (i.imgBytes > om ? 50 : 800) + r
      );
      return i.unsuspend = l, function() {
        i.unsuspend = null, clearTimeout(f), clearTimeout(v);
      };
    } : null;
  }
  function cf() {
    if (this.count--, this.count === 0 && (this.imgCount === 0 || !this.waitingForImages)) {
      if (this.stylesheets) ff(this, this.stylesheets);
      else if (this.unsuspend) {
        var i = this.unsuspend;
        this.unsuspend = null, i();
      }
    }
  }
  var uf = null;
  function ff(i, r) {
    i.stylesheets = null, i.unsuspend !== null && (i.count++, uf = /* @__PURE__ */ new Map(), r.forEach(YT, i), uf = null, cf.call(i));
  }
  function YT(i, r) {
    if (!(r.state.loading & 4)) {
      var l = uf.get(i);
      if (l) var f = l.get(null);
      else {
        l = /* @__PURE__ */ new Map(), uf.set(i, l);
        for (var v = i.querySelectorAll(
          "link[data-precedence],style[data-precedence]"
        ), S = 0; S < v.length; S++) {
          var P = v[S];
          (P.nodeName === "LINK" || P.getAttribute("media") !== "not all") && (l.set(P.dataset.precedence, P), f = P);
        }
        f && l.set(null, f);
      }
      v = r.instance, P = v.getAttribute("data-precedence"), S = l.get(P) || f, S === f && l.set(null, v), l.set(P, v), this.count++, f = cf.bind(this), v.addEventListener("load", f), v.addEventListener("error", f), S ? S.parentNode.insertBefore(v, S.nextSibling) : (i = i.nodeType === 9 ? i.head : i, i.insertBefore(v, i.firstChild)), r.state.loading |= 4;
    }
  }
  var oc = {
    $$typeof: w,
    Provider: null,
    Consumer: null,
    _currentValue: k,
    _currentValue2: k,
    _threadCount: 0
  };
  function jT(i, r, l, f, v, S, P, q, nt) {
    this.tag = 1, this.containerInfo = i, this.pingCache = this.current = this.pendingChildren = null, this.timeoutHandle = -1, this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null, this.callbackPriority = 0, this.expirationTimes = Oe(-1), this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0, this.entanglements = Oe(0), this.hiddenUpdates = Oe(null), this.identifierPrefix = f, this.onUncaughtError = v, this.onCaughtError = S, this.onRecoverableError = P, this.pooledCache = null, this.pooledCacheLanes = 0, this.formState = nt, this.incompleteTransitions = /* @__PURE__ */ new Map();
  }
  function Yx(i, r, l, f, v, S, P, q, nt, pt, wt, Ct) {
    return i = new jT(
      i,
      r,
      l,
      P,
      nt,
      pt,
      wt,
      Ct,
      q
    ), r = 1, S === !0 && (r |= 24), S = yi(3, null, null, r), i.current = S, S.stateNode = i, r = Hh(), r.refCount++, i.pooledCache = r, r.refCount++, S.memoizedState = {
      element: f,
      isDehydrated: l,
      cache: r
    }, Xh(S), i;
  }
  function jx(i) {
    return i ? (i = ao, i) : ao;
  }
  function qx(i, r, l, f, v, S) {
    v = jx(v), f.context === null ? f.context = v : f.pendingContext = v, f = Tr(r), f.payload = { element: l }, S = S === void 0 ? null : S, S !== null && (f.callback = S), l = Cr(i, f, r), l !== null && (ui(l, i, r), Fl(l, i, r));
  }
  function Zx(i, r) {
    if (i = i.memoizedState, i !== null && i.dehydrated !== null) {
      var l = i.retryLane;
      i.retryLane = l !== 0 && l < r ? l : r;
    }
  }
  function lm(i, r) {
    Zx(i, r), (i = i.alternate) && Zx(i, r);
  }
  function $x(i) {
    if (i.tag === 13 || i.tag === 31) {
      var r = ha(i, 67108864);
      r !== null && ui(r, i, 67108864), lm(i, 67108864);
    }
  }
  function Kx(i) {
    if (i.tag === 13 || i.tag === 31) {
      var r = Ei();
      r = _r(r);
      var l = ha(i, r);
      l !== null && ui(l, i, r), lm(i, r);
    }
  }
  var df = !0;
  function qT(i, r, l, f) {
    var v = N.T;
    N.T = null;
    var S = I.p;
    try {
      I.p = 2, cm(i, r, l, f);
    } finally {
      I.p = S, N.T = v;
    }
  }
  function ZT(i, r, l, f) {
    var v = N.T;
    N.T = null;
    var S = I.p;
    try {
      I.p = 8, cm(i, r, l, f);
    } finally {
      I.p = S, N.T = v;
    }
  }
  function cm(i, r, l, f) {
    if (df) {
      var v = um(f);
      if (v === null)
        Zp(
          i,
          r,
          f,
          hf,
          l
        ), Jx(i, f);
      else if (KT(
        v,
        i,
        r,
        l,
        f
      ))
        f.stopPropagation();
      else if (Jx(i, f), r & 4 && -1 < $T.indexOf(i)) {
        for (; v !== null; ) {
          var S = us(v);
          if (S !== null)
            switch (S.tag) {
              case 3:
                if (S = S.stateNode, S.current.memoizedState.isDehydrated) {
                  var P = Nt(S.pendingLanes);
                  if (P !== 0) {
                    var q = S;
                    for (q.pendingLanes |= 2, q.entangledLanes |= 2; P; ) {
                      var nt = 1 << 31 - kt(P);
                      q.entanglements[1] |= nt, P &= ~nt;
                    }
                    ms(S), (Ve & 6) === 0 && (qu = G() + 500, ec(0));
                  }
                }
                break;
              case 31:
              case 13:
                q = ha(S, 2), q !== null && ui(q, S, 2), $u(), lm(S, 2);
            }
          if (S = um(f), S === null && Zp(
            i,
            r,
            f,
            hf,
            l
          ), S === v) break;
          v = S;
        }
        v !== null && f.stopPropagation();
      } else
        Zp(
          i,
          r,
          f,
          null,
          l
        );
    }
  }
  function um(i) {
    return i = dh(i), fm(i);
  }
  var hf = null;
  function fm(i) {
    if (hf = null, i = cs(i), i !== null) {
      var r = o(i);
      if (r === null) i = null;
      else {
        var l = r.tag;
        if (l === 13) {
          if (i = c(r), i !== null) return i;
          i = null;
        } else if (l === 31) {
          if (i = u(r), i !== null) return i;
          i = null;
        } else if (l === 3) {
          if (r.stateNode.current.memoizedState.isDehydrated)
            return r.tag === 3 ? r.stateNode.containerInfo : null;
          i = null;
        } else r !== i && (i = null);
      }
    }
    return hf = i, null;
  }
  function Qx(i) {
    switch (i) {
      case "beforetoggle":
      case "cancel":
      case "click":
      case "close":
      case "contextmenu":
      case "copy":
      case "cut":
      case "auxclick":
      case "dblclick":
      case "dragend":
      case "dragstart":
      case "drop":
      case "focusin":
      case "focusout":
      case "input":
      case "invalid":
      case "keydown":
      case "keypress":
      case "keyup":
      case "mousedown":
      case "mouseup":
      case "paste":
      case "pause":
      case "play":
      case "pointercancel":
      case "pointerdown":
      case "pointerup":
      case "ratechange":
      case "reset":
      case "resize":
      case "seeked":
      case "submit":
      case "toggle":
      case "touchcancel":
      case "touchend":
      case "touchstart":
      case "volumechange":
      case "change":
      case "selectionchange":
      case "textInput":
      case "compositionstart":
      case "compositionend":
      case "compositionupdate":
      case "beforeblur":
      case "afterblur":
      case "beforeinput":
      case "blur":
      case "fullscreenchange":
      case "focus":
      case "hashchange":
      case "popstate":
      case "select":
      case "selectstart":
        return 2;
      case "drag":
      case "dragenter":
      case "dragexit":
      case "dragleave":
      case "dragover":
      case "mousemove":
      case "mouseout":
      case "mouseover":
      case "pointermove":
      case "pointerout":
      case "pointerover":
      case "scroll":
      case "touchmove":
      case "wheel":
      case "mouseenter":
      case "mouseleave":
      case "pointerenter":
      case "pointerleave":
        return 8;
      case "message":
        switch (ct()) {
          case Et:
            return 2;
          case Rt:
            return 8;
          case Mt:
          case Jt:
            return 32;
          case It:
            return 268435456;
          default:
            return 32;
        }
      default:
        return 32;
    }
  }
  var dm = !1, Fr = null, Hr = null, Vr = null, lc = /* @__PURE__ */ new Map(), cc = /* @__PURE__ */ new Map(), Gr = [], $T = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(
    " "
  );
  function Jx(i, r) {
    switch (i) {
      case "focusin":
      case "focusout":
        Fr = null;
        break;
      case "dragenter":
      case "dragleave":
        Hr = null;
        break;
      case "mouseover":
      case "mouseout":
        Vr = null;
        break;
      case "pointerover":
      case "pointerout":
        lc.delete(r.pointerId);
        break;
      case "gotpointercapture":
      case "lostpointercapture":
        cc.delete(r.pointerId);
    }
  }
  function uc(i, r, l, f, v, S) {
    return i === null || i.nativeEvent !== S ? (i = {
      blockedOn: r,
      domEventName: l,
      eventSystemFlags: f,
      nativeEvent: S,
      targetContainers: [v]
    }, r !== null && (r = us(r), r !== null && $x(r)), i) : (i.eventSystemFlags |= f, r = i.targetContainers, v !== null && r.indexOf(v) === -1 && r.push(v), i);
  }
  function KT(i, r, l, f, v) {
    switch (r) {
      case "focusin":
        return Fr = uc(
          Fr,
          i,
          r,
          l,
          f,
          v
        ), !0;
      case "dragenter":
        return Hr = uc(
          Hr,
          i,
          r,
          l,
          f,
          v
        ), !0;
      case "mouseover":
        return Vr = uc(
          Vr,
          i,
          r,
          l,
          f,
          v
        ), !0;
      case "pointerover":
        var S = v.pointerId;
        return lc.set(
          S,
          uc(
            lc.get(S) || null,
            i,
            r,
            l,
            f,
            v
          )
        ), !0;
      case "gotpointercapture":
        return S = v.pointerId, cc.set(
          S,
          uc(
            cc.get(S) || null,
            i,
            r,
            l,
            f,
            v
          )
        ), !0;
    }
    return !1;
  }
  function tS(i) {
    var r = cs(i.target);
    if (r !== null) {
      var l = o(r);
      if (l !== null) {
        if (r = l.tag, r === 13) {
          if (r = c(l), r !== null) {
            i.blockedOn = r, xr(i.priority, function() {
              Kx(l);
            });
            return;
          }
        } else if (r === 31) {
          if (r = u(l), r !== null) {
            i.blockedOn = r, xr(i.priority, function() {
              Kx(l);
            });
            return;
          }
        } else if (r === 3 && l.stateNode.current.memoizedState.isDehydrated) {
          i.blockedOn = l.tag === 3 ? l.stateNode.containerInfo : null;
          return;
        }
      }
    }
    i.blockedOn = null;
  }
  function pf(i) {
    if (i.blockedOn !== null) return !1;
    for (var r = i.targetContainers; 0 < r.length; ) {
      var l = um(i.nativeEvent);
      if (l === null) {
        l = i.nativeEvent;
        var f = new l.constructor(
          l.type,
          l
        );
        fh = f, l.target.dispatchEvent(f), fh = null;
      } else
        return r = us(l), r !== null && $x(r), i.blockedOn = l, !1;
      r.shift();
    }
    return !0;
  }
  function eS(i, r, l) {
    pf(i) && l.delete(r);
  }
  function QT() {
    dm = !1, Fr !== null && pf(Fr) && (Fr = null), Hr !== null && pf(Hr) && (Hr = null), Vr !== null && pf(Vr) && (Vr = null), lc.forEach(eS), cc.forEach(eS);
  }
  function mf(i, r) {
    i.blockedOn === r && (i.blockedOn = null, dm || (dm = !0, n.unstable_scheduleCallback(
      n.unstable_NormalPriority,
      QT
    )));
  }
  var gf = null;
  function nS(i) {
    gf !== i && (gf = i, n.unstable_scheduleCallback(
      n.unstable_NormalPriority,
      function() {
        gf === i && (gf = null);
        for (var r = 0; r < i.length; r += 3) {
          var l = i[r], f = i[r + 1], v = i[r + 2];
          if (typeof f != "function") {
            if (fm(f || l) === null)
              continue;
            break;
          }
          var S = us(l);
          S !== null && (i.splice(r, 3), r -= 3, up(
            S,
            {
              pending: !0,
              data: v,
              method: l.method,
              action: f
            },
            f,
            v
          ));
        }
      }
    ));
  }
  function No(i) {
    function r(nt) {
      return mf(nt, i);
    }
    Fr !== null && mf(Fr, i), Hr !== null && mf(Hr, i), Vr !== null && mf(Vr, i), lc.forEach(r), cc.forEach(r);
    for (var l = 0; l < Gr.length; l++) {
      var f = Gr[l];
      f.blockedOn === i && (f.blockedOn = null);
    }
    for (; 0 < Gr.length && (l = Gr[0], l.blockedOn === null); )
      tS(l), l.blockedOn === null && Gr.shift();
    if (l = (i.ownerDocument || i).$$reactFormReplay, l != null)
      for (f = 0; f < l.length; f += 3) {
        var v = l[f], S = l[f + 1], P = v[hn] || null;
        if (typeof S == "function")
          P || nS(l);
        else if (P) {
          var q = null;
          if (S && S.hasAttribute("formAction")) {
            if (v = S, P = S[hn] || null)
              q = P.formAction;
            else if (fm(v) !== null) continue;
          } else q = P.action;
          typeof q == "function" ? l[f + 1] = q : (l.splice(f, 3), f -= 3), nS(l);
        }
      }
  }
  function iS() {
    function i(S) {
      S.canIntercept && S.info === "react-transition" && S.intercept({
        handler: function() {
          return new Promise(function(P) {
            return v = P;
          });
        },
        focusReset: "manual",
        scroll: "manual"
      });
    }
    function r() {
      v !== null && (v(), v = null), f || setTimeout(l, 20);
    }
    function l() {
      if (!f && !navigation.transition) {
        var S = navigation.currentEntry;
        S && S.url != null && navigation.navigate(S.url, {
          state: S.getState(),
          info: "react-transition",
          history: "replace"
        });
      }
    }
    if (typeof navigation == "object") {
      var f = !1, v = null;
      return navigation.addEventListener("navigate", i), navigation.addEventListener("navigatesuccess", r), navigation.addEventListener("navigateerror", r), setTimeout(l, 100), function() {
        f = !0, navigation.removeEventListener("navigate", i), navigation.removeEventListener("navigatesuccess", r), navigation.removeEventListener("navigateerror", r), v !== null && (v(), v = null);
      };
    }
  }
  function hm(i) {
    this._internalRoot = i;
  }
  vf.prototype.render = hm.prototype.render = function(i) {
    var r = this._internalRoot;
    if (r === null) throw Error(s(409));
    var l = r.current, f = Ei();
    qx(l, f, i, r, null, null);
  }, vf.prototype.unmount = hm.prototype.unmount = function() {
    var i = this._internalRoot;
    if (i !== null) {
      this._internalRoot = null;
      var r = i.containerInfo;
      qx(i.current, 2, null, i, null, null), $u(), r[Ui] = null;
    }
  };
  function vf(i) {
    this._internalRoot = i;
  }
  vf.prototype.unstable_scheduleHydration = function(i) {
    if (i) {
      var r = Li();
      i = { blockedOn: null, target: i, priority: r };
      for (var l = 0; l < Gr.length && r !== 0 && r < Gr[l].priority; l++) ;
      Gr.splice(l, 0, i), l === 0 && tS(i);
    }
  };
  var sS = t.version;
  if (sS !== "19.2.4")
    throw Error(
      s(
        527,
        sS,
        "19.2.4"
      )
    );
  I.findDOMNode = function(i) {
    var r = i._reactInternals;
    if (r === void 0)
      throw typeof i.render == "function" ? Error(s(188)) : (i = Object.keys(i).join(","), Error(s(268, i)));
    return i = h(r), i = i !== null ? m(i) : null, i = i === null ? null : i.stateNode, i;
  };
  var JT = {
    bundleType: 0,
    version: "19.2.4",
    rendererPackageName: "react-dom",
    currentDispatcherRef: N,
    reconcilerVersion: "19.2.4"
  };
  if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u") {
    var _f = __REACT_DEVTOOLS_GLOBAL_HOOK__;
    if (!_f.isDisabled && _f.supportsFiber)
      try {
        Ot = _f.inject(
          JT
        ), Dt = _f;
      } catch {
      }
  }
  return fc.createRoot = function(i, r) {
    if (!a(i)) throw Error(s(299));
    var l = !1, f = "", v = fy, S = dy, P = hy;
    return r != null && (r.unstable_strictMode === !0 && (l = !0), r.identifierPrefix !== void 0 && (f = r.identifierPrefix), r.onUncaughtError !== void 0 && (v = r.onUncaughtError), r.onCaughtError !== void 0 && (S = r.onCaughtError), r.onRecoverableError !== void 0 && (P = r.onRecoverableError)), r = Yx(
      i,
      1,
      !1,
      null,
      null,
      l,
      f,
      null,
      v,
      S,
      P,
      iS
    ), i[Ui] = r.current, qp(i), new hm(r);
  }, fc.hydrateRoot = function(i, r, l) {
    if (!a(i)) throw Error(s(299));
    var f = !1, v = "", S = fy, P = dy, q = hy, nt = null;
    return l != null && (l.unstable_strictMode === !0 && (f = !0), l.identifierPrefix !== void 0 && (v = l.identifierPrefix), l.onUncaughtError !== void 0 && (S = l.onUncaughtError), l.onCaughtError !== void 0 && (P = l.onCaughtError), l.onRecoverableError !== void 0 && (q = l.onRecoverableError), l.formState !== void 0 && (nt = l.formState)), r = Yx(
      i,
      1,
      !0,
      r,
      l ?? null,
      f,
      v,
      nt,
      S,
      P,
      q,
      iS
    ), r.context = jx(null), l = r.current, f = Ei(), f = _r(f), v = Tr(f), v.callback = null, Cr(l, v, f), l = f, r.current.lanes = l, Fn(r, l), ms(r), i[Ui] = r.current, qp(i), new vf(r);
  }, fc.version = "19.2.4", fc;
}
var dS;
function l2() {
  if (dS) return mm.exports;
  dS = 1;
  function n() {
    if (!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ > "u" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE != "function"))
      try {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n);
      } catch (t) {
        console.error(t);
      }
  }
  return n(), mm.exports = o2(), mm.exports;
}
var c2 = l2(), ym = { exports: {} }, dc = {};
/**
 * @license React
 * react-jsx-runtime.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var hS;
function u2() {
  if (hS) return dc;
  hS = 1;
  var n = Symbol.for("react.transitional.element"), t = Symbol.for("react.fragment");
  function e(s, a, o) {
    var c = null;
    if (o !== void 0 && (c = "" + o), a.key !== void 0 && (c = "" + a.key), "key" in a) {
      o = {};
      for (var u in a)
        u !== "key" && (o[u] = a[u]);
    } else o = a;
    return a = o.ref, {
      $$typeof: n,
      type: s,
      key: c,
      ref: a !== void 0 ? a : null,
      props: o
    };
  }
  return dc.Fragment = t, dc.jsx = e, dc.jsxs = e, dc;
}
var pS;
function f2() {
  return pS || (pS = 1, ym.exports = u2()), ym.exports;
}
var _t = f2();
/**
 * @license
 * Copyright 2010-2026 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
const F0 = "183", al = { ROTATE: 0, DOLLY: 1, PAN: 2 }, il = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }, d2 = 0, mS = 1, h2 = 2, ud = 1, p2 = 2, Dc = 3, ra = 0, pi = 1, Ss = 2, cr = 0, ol = 1, gS = 2, vS = 3, _S = 4, m2 = 5, Ua = 100, g2 = 101, v2 = 102, _2 = 103, y2 = 104, x2 = 200, S2 = 201, b2 = 202, M2 = 203, Ag = 204, Tg = 205, E2 = 206, w2 = 207, A2 = 208, T2 = 209, C2 = 210, R2 = 211, D2 = 212, N2 = 213, O2 = 214, Cg = 0, Rg = 1, Dg = 2, fl = 3, Ng = 4, Og = 5, Lg = 6, Ug = 7, H0 = 0, L2 = 1, U2 = 2, ws = 0, uM = 1, fM = 2, dM = 3, hM = 4, pM = 5, mM = 6, gM = 7, vM = 300, ka = 301, dl = 302, xm = 303, Sm = 304, Wd = 306, Pg = 1e3, or = 1001, Ig = 1002, vn = 1003, P2 = 1004, yf = 1005, Qn = 1006, bm = 1007, Ia = 1008, Ci = 1009, _M = 1010, yM = 1011, zc = 1012, V0 = 1013, Cs = 1014, Di = 1015, dr = 1016, G0 = 1017, k0 = 1018, Fc = 1020, xM = 35902, SM = 35899, bM = 1021, MM = 1022, Ni = 1023, hr = 1026, Ba = 1027, X0 = 1028, W0 = 1029, hl = 1030, Y0 = 1031, j0 = 1033, fd = 33776, dd = 33777, hd = 33778, pd = 33779, Bg = 35840, zg = 35841, Fg = 35842, Hg = 35843, Vg = 36196, Gg = 37492, kg = 37496, Xg = 37488, Wg = 37489, Yg = 37490, jg = 37491, qg = 37808, Zg = 37809, $g = 37810, Kg = 37811, Qg = 37812, Jg = 37813, t0 = 37814, e0 = 37815, n0 = 37816, i0 = 37817, s0 = 37818, r0 = 37819, a0 = 37820, o0 = 37821, l0 = 36492, c0 = 36494, u0 = 36495, f0 = 36283, d0 = 36284, h0 = 36285, p0 = 36286, I2 = 3200, EM = 0, B2 = 1, ta = "", Xi = "srgb", pl = "srgb-linear", Md = "linear", We = "srgb", Oo = 7680, yS = 519, z2 = 512, F2 = 513, H2 = 514, q0 = 515, V2 = 516, G2 = 517, Z0 = 518, k2 = 519, za = 35044, Lo = 35048, Ed = "300 es", Ms = 2e3, Hc = 2001;
function X2(n) {
  for (let t = n.length - 1; t >= 0; --t)
    if (n[t] >= 65535) return !0;
  return !1;
}
function wd(n) {
  return document.createElementNS("http://www.w3.org/1999/xhtml", n);
}
function W2() {
  const n = wd("canvas");
  return n.style.display = "block", n;
}
const xS = {};
function Ad(...n) {
  const t = "THREE." + n.shift();
  console.log(t, ...n);
}
function wM(n) {
  const t = n[0];
  if (typeof t == "string" && t.startsWith("TSL:")) {
    const e = n[1];
    e && e.isStackTrace ? n[0] += " " + e.getLocation() : n[1] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.';
  }
  return n;
}
function de(...n) {
  n = wM(n);
  const t = "THREE." + n.shift();
  {
    const e = n[0];
    e && e.isStackTrace ? console.warn(e.getError(t)) : console.warn(t, ...n);
  }
}
function Ie(...n) {
  n = wM(n);
  const t = "THREE." + n.shift();
  {
    const e = n[0];
    e && e.isStackTrace ? console.error(e.getError(t)) : console.error(t, ...n);
  }
}
function Td(...n) {
  const t = n.join(" ");
  t in xS || (xS[t] = !0, de(...n));
}
function Y2(n, t, e) {
  return new Promise(function(s, a) {
    function o() {
      switch (n.clientWaitSync(t, n.SYNC_FLUSH_COMMANDS_BIT, 0)) {
        case n.WAIT_FAILED:
          a();
          break;
        case n.TIMEOUT_EXPIRED:
          setTimeout(o, e);
          break;
        default:
          s();
      }
    }
    setTimeout(o, e);
  });
}
const j2 = {
  [Cg]: Rg,
  [Dg]: Lg,
  [Ng]: Ug,
  [fl]: Og,
  [Rg]: Cg,
  [Lg]: Dg,
  [Ug]: Ng,
  [Og]: fl
};
class qa {
  /**
   * 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 s = this._listeners;
    s[t] === void 0 && (s[t] = []), s[t].indexOf(e) === -1 && s[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 s = this._listeners;
    return s === void 0 ? !1 : s[t] !== void 0 && s[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 s = this._listeners;
    if (s === void 0) return;
    const a = s[t];
    if (a !== void 0) {
      const o = a.indexOf(e);
      o !== -1 && a.splice(o, 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 s = e[t.type];
    if (s !== void 0) {
      t.target = this;
      const a = s.slice(0);
      for (let o = 0, c = a.length; o < c; o++)
        a[o].call(this, t);
      t.target = null;
    }
  }
}
const $n = ["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 SS = 1234567;
const Uc = Math.PI / 180, Vc = 180 / Math.PI;
function ur() {
  const n = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, e = Math.random() * 4294967295 | 0, s = Math.random() * 4294967295 | 0;
  return ($n[n & 255] + $n[n >> 8 & 255] + $n[n >> 16 & 255] + $n[n >> 24 & 255] + "-" + $n[t & 255] + $n[t >> 8 & 255] + "-" + $n[t >> 16 & 15 | 64] + $n[t >> 24 & 255] + "-" + $n[e & 63 | 128] + $n[e >> 8 & 255] + "-" + $n[e >> 16 & 255] + $n[e >> 24 & 255] + $n[s & 255] + $n[s >> 8 & 255] + $n[s >> 16 & 255] + $n[s >> 24 & 255]).toLowerCase();
}
function ge(n, t, e) {
  return Math.max(t, Math.min(e, n));
}
function $0(n, t) {
  return (n % t + t) % t;
}
function q2(n, t, e, s, a) {
  return s + (n - t) * (a - s) / (e - t);
}
function Z2(n, t, e) {
  return n !== t ? (e - n) / (t - n) : 0;
}
function Pc(n, t, e) {
  return (1 - e) * n + e * t;
}
function $2(n, t, e, s) {
  return Pc(n, t, 1 - Math.exp(-e * s));
}
function K2(n, t = 1) {
  return t - Math.abs($0(n, t * 2) - t);
}
function Q2(n, t, e) {
  return n <= t ? 0 : n >= e ? 1 : (n = (n - t) / (e - t), n * n * (3 - 2 * n));
}
function J2(n, t, e) {
  return n <= t ? 0 : n >= e ? 1 : (n = (n - t) / (e - t), n * n * n * (n * (n * 6 - 15) + 10));
}
function t3(n, t) {
  return n + Math.floor(Math.random() * (t - n + 1));
}
function e3(n, t) {
  return n + Math.random() * (t - n);
}
function n3(n) {
  return n * (0.5 - Math.random());
}
function i3(n) {
  n !== void 0 && (SS = n);
  let t = SS += 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 s3(n) {
  return n * Uc;
}
function r3(n) {
  return n * Vc;
}
function a3(n) {
  return (n & n - 1) === 0 && n !== 0;
}
function o3(n) {
  return Math.pow(2, Math.ceil(Math.log(n) / Math.LN2));
}
function l3(n) {
  return Math.pow(2, Math.floor(Math.log(n) / Math.LN2));
}
function c3(n, t, e, s, a) {
  const o = Math.cos, c = Math.sin, u = o(e / 2), d = c(e / 2), h = o((t + s) / 2), m = c((t + s) / 2), p = o((t - s) / 2), g = c((t - s) / 2), _ = o((s - t) / 2), x = c((s - t) / 2);
  switch (a) {
    case "XYX":
      n.set(u * m, d * p, d * g, u * h);
      break;
    case "YZY":
      n.set(d * g, u * m, d * p, u * h);
      break;
    case "ZXZ":
      n.set(d * p, d * g, u * m, u * h);
      break;
    case "XZX":
      n.set(u * m, d * x, d * _, u * h);
      break;
    case "YXY":
      n.set(d * _, u * m, d * x, u * h);
      break;
    case "ZYZ":
      n.set(d * x, d * _, u * m, u * h);
      break;
    default:
      de("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + a);
  }
}
function es(n, t) {
  switch (t.constructor) {
    case Float32Array:
      return n;
    case Uint32Array:
      return n / 4294967295;
    case Uint16Array:
      return n / 65535;
    case Uint8Array:
      return n / 255;
    case Int32Array:
      return Math.max(n / 2147483647, -1);
    case Int16Array:
      return Math.max(n / 32767, -1);
    case Int8Array:
      return Math.max(n / 127, -1);
    default:
      throw new Error("Invalid component type.");
  }
}
function Ye(n, t) {
  switch (t.constructor) {
    case Float32Array:
      return n;
    case Uint32Array:
      return Math.round(n * 4294967295);
    case Uint16Array:
      return Math.round(n * 65535);
    case Uint8Array:
      return Math.round(n * 255);
    case Int32Array:
      return Math.round(n * 2147483647);
    case Int16Array:
      return Math.round(n * 32767);
    case Int8Array:
      return Math.round(n * 127);
    default:
      throw new Error("Invalid component type.");
  }
}
const AM = {
  DEG2RAD: Uc,
  RAD2DEG: Vc,
  /**
   * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
   * (universally unique identifier).
   *
   * @static
   * @method
   * @return {string} The UUID.
   */
  generateUUID: ur,
  /**
   * 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: ge,
  /**
   * 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: $0,
  /**
   * 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: q2,
  /**
   * 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: Z2,
  /**
   * 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: Pc,
  /**
   * 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](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: $2,
  /**
   * 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: K2,
  /**
   * 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](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: Q2,
  /**
   * A [variation on smoothstep](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: J2,
  /**
   * 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: t3,
  /**
   * 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: e3,
  /**
   * 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: n3,
  /**
   * 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: i3,
  /**
   * Converts degrees to radians.
   *
   * @static
   * @method
   * @param {number} degrees - A value in degrees.
   * @return {number} The converted value in radians.
   */
  degToRad: s3,
  /**
   * Converts radians to degrees.
   *
   * @static
   * @method
   * @param {number} radians - A value in radians.
   * @return {number} The converted value in degrees.
   */
  radToDeg: r3,
  /**
   * 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: a3,
  /**
   * 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: o3,
  /**
   * 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: l3,
  /**
   * Sets the given quaternion from the [Intrinsic Proper Euler Angles](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: c3,
  /**
   * 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: Ye,
  /**
   * 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: es
};
class ae {
  /**
   * 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) {
    ae.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, s = this.y, a = t.elements;
    return this.x = a[0] * e + a[3] * s + a[6], this.y = a[1] * e + a[4] * s + a[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 = ge(this.x, t.x, e.x), this.y = ge(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 = ge(this.x, t, e), this.y = ge(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 s = this.length();
    return this.divideScalar(s || 1).multiplyScalar(ge(s, 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 s = this.dot(t) / e;
    return Math.acos(ge(s, -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, s = this.y - t.y;
    return e * e + s * s;
  }
  /**
   * 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, s) {
    return this.x = t.x + (e.x - t.x) * s, this.y = t.y + (e.y - t.y) * s, 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 s = Math.cos(e), a = Math.sin(e), o = this.x - t.x, c = this.y - t.y;
    return this.x = o * s - c * a + t.x, this.y = o * a + c * s + 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 pr {
  /**
   * 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, s = 0, a = 1) {
    this.isQuaternion = !0, this._x = t, this._y = e, this._z = s, this._w = a;
  }
  /**
   * 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. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
   * @see {@link Quaternion#slerp}
   */
  static slerpFlat(t, e, s, a, o, c, u) {
    let d = s[a + 0], h = s[a + 1], m = s[a + 2], p = s[a + 3], g = o[c + 0], _ = o[c + 1], x = o[c + 2], A = o[c + 3];
    if (p !== A || d !== g || h !== _ || m !== x) {
      let b = d * g + h * _ + m * x + p * A;
      b < 0 && (g = -g, _ = -_, x = -x, A = -A, b = -b);
      let y = 1 - u;
      if (b < 0.9995) {
        const E = Math.acos(b), w = Math.sin(E);
        y = Math.sin(y * E) / w, u = Math.sin(u * E) / w, d = d * y + g * u, h = h * y + _ * u, m = m * y + x * u, p = p * y + A * u;
      } else {
        d = d * y + g * u, h = h * y + _ * u, m = m * y + x * u, p = p * y + A * u;
        const E = 1 / Math.sqrt(d * d + h * h + m * m + p * p);
        d *= E, h *= E, m *= E, p *= E;
      }
    }
    t[e] = d, t[e + 1] = h, t[e + 2] = m, t[e + 3] = p;
  }
  /**
   * 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, s, a, o, c) {
    const u = s[a], d = s[a + 1], h = s[a + 2], m = s[a + 3], p = o[c], g = o[c + 1], _ = o[c + 2], x = o[c + 3];
    return t[e] = u * x + m * p + d * _ - h * g, t[e + 1] = d * x + m * g + h * p - u * _, t[e + 2] = h * x + m * _ + u * g - d * p, t[e + 3] = m * x - u * p - d * g - h * _, 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, s, a) {
    return this._x = t, this._y = e, this._z = s, this._w = a, 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 s = t._x, a = t._y, o = t._z, c = t._order, u = Math.cos, d = Math.sin, h = u(s / 2), m = u(a / 2), p = u(o / 2), g = d(s / 2), _ = d(a / 2), x = d(o / 2);
    switch (c) {
      case "XYZ":
        this._x = g * m * p + h * _ * x, this._y = h * _ * p - g * m * x, this._z = h * m * x + g * _ * p, this._w = h * m * p - g * _ * x;
        break;
      case "YXZ":
        this._x = g * m * p + h * _ * x, this._y = h * _ * p - g * m * x, this._z = h * m * x - g * _ * p, this._w = h * m * p + g * _ * x;
        break;
      case "ZXY":
        this._x = g * m * p - h * _ * x, this._y = h * _ * p + g * m * x, this._z = h * m * x + g * _ * p, this._w = h * m * p - g * _ * x;
        break;
      case "ZYX":
        this._x = g * m * p - h * _ * x, this._y = h * _ * p + g * m * x, this._z = h * m * x - g * _ * p, this._w = h * m * p + g * _ * x;
        break;
      case "YZX":
        this._x = g * m * p + h * _ * x, this._y = h * _ * p + g * m * x, this._z = h * m * x - g * _ * p, this._w = h * m * p - g * _ * x;
        break;
      case "XZY":
        this._x = g * m * p - h * _ * x, this._y = h * _ * p - g * m * x, this._z = h * m * x + g * _ * p, this._w = h * m * p + g * _ * x;
        break;
      default:
        de("Quaternion: .setFromEuler() encountered an unknown order: " + c);
    }
    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 s = e / 2, a = Math.sin(s);
    return this._x = t.x * a, this._y = t.y * a, this._z = t.z * a, this._w = Math.cos(s), 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, s = e[0], a = e[4], o = e[8], c = e[1], u = e[5], d = e[9], h = e[2], m = e[6], p = e[10], g = s + u + p;
    if (g > 0) {
      const _ = 0.5 / Math.sqrt(g + 1);
      this._w = 0.25 / _, this._x = (m - d) * _, this._y = (o - h) * _, this._z = (c - a) * _;
    } else if (s > u && s > p) {
      const _ = 2 * Math.sqrt(1 + s - u - p);
      this._w = (m - d) / _, this._x = 0.25 * _, this._y = (a + c) / _, this._z = (o + h) / _;
    } else if (u > p) {
      const _ = 2 * Math.sqrt(1 + u - s - p);
      this._w = (o - h) / _, this._x = (a + c) / _, this._y = 0.25 * _, this._z = (d + m) / _;
    } else {
      const _ = 2 * Math.sqrt(1 + p - s - u);
      this._w = (c - a) / _, this._x = (o + h) / _, this._y = (d + m) / _, this._z = 0.25 * _;
    }
    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 s = t.dot(e) + 1;
    return s < 1e-8 ? (s = 0, Math.abs(t.x) > Math.abs(t.z) ? (this._x = -t.y, this._y = t.x, this._z = 0, this._w = s) : (this._x = 0, this._y = -t.z, this._z = t.y, this._w = s)) : (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 = s), 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(ge(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 s = this.angleTo(t);
    if (s === 0) return this;
    const a = Math.min(1, e / s);
    return this.slerp(t, a), 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 s = t._x, a = t._y, o = t._z, c = t._w, u = e._x, d = e._y, h = e._z, m = e._w;
    return this._x = s * m + c * u + a * h - o * d, this._y = a * m + c * d + o * u - s * h, this._z = o * m + c * h + s * d - a * u, this._w = c * m - s * u - a * d - o * h, this._onChangeCallback(), this;
  }
  /**
   * Performs a spherical linear interpolation between this quaternion and the target quaternion.
   *
   * @param {Quaternion} qb - The target quaternion.
   * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
   * @return {Quaternion} A reference to this quaternion.
   */
  slerp(t, e) {
    let s = t._x, a = t._y, o = t._z, c = t._w, u = this.dot(t);
    u < 0 && (s = -s, a = -a, o = -o, c = -c, u = -u);
    let d = 1 - e;
    if (u < 0.9995) {
      const h = Math.acos(u), m = Math.sin(h);
      d = Math.sin(d * h) / m, e = Math.sin(e * h) / m, this._x = this._x * d + s * e, this._y = this._y * d + a * e, this._z = this._z * d + o * e, this._w = this._w * d + c * e, this._onChangeCallback();
    } else
      this._x = this._x * d + s * e, this._y = this._y * d + a * e, this._z = this._z * d + o * e, this._w = this._w * d + c * e, this.normalize();
    return 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, s) {
    return this.copy(t).slerp(e, s);
  }
  /**
   * 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(), s = Math.random(), a = Math.sqrt(1 - s), o = Math.sqrt(s);
    return this.set(
      a * Math.sin(t),
      a * Math.cos(t),
      o * Math.sin(e),
      o * 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 st {
  /**
   * 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, s = 0) {
    st.prototype.isVector3 = !0, this.x = t, this.y = e, this.z = s;
  }
  /**
   * 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, s) {
    return s === void 0 && (s = this.z), this.x = t, this.y = e, this.z = s, 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(bS.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(bS.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, s = this.y, a = this.z, o = t.elements;
    return this.x = o[0] * e + o[3] * s + o[6] * a, this.y = o[1] * e + o[4] * s + o[7] * a, this.z = o[2] * e + o[5] * s + o[8] * a, 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, s = this.y, a = this.z, o = t.elements, c = 1 / (o[3] * e + o[7] * s + o[11] * a + o[15]);
    return this.x = (o[0] * e + o[4] * s + o[8] * a + o[12]) * c, this.y = (o[1] * e + o[5] * s + o[9] * a + o[13]) * c, this.z = (o[2] * e + o[6] * s + o[10] * a + o[14]) * c, 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, s = this.y, a = this.z, o = t.x, c = t.y, u = t.z, d = t.w, h = 2 * (c * a - u * s), m = 2 * (u * e - o * a), p = 2 * (o * s - c * e);
    return this.x = e + d * h + c * p - u * m, this.y = s + d * m + u * h - o * p, this.z = a + d * p + o * m - c * 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, s = this.y, a = this.z, o = t.elements;
    return this.x = o[0] * e + o[4] * s + o[8] * a, this.y = o[1] * e + o[5] * s + o[9] * a, this.z = o[2] * e + o[6] * s + o[10] * a, 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 = ge(this.x, t.x, e.x), this.y = ge(this.y, t.y, e.y), this.z = ge(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 = ge(this.x, t, e), this.y = ge(this.y, t, e), this.z = ge(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 s = this.length();
    return this.divideScalar(s || 1).multiplyScalar(ge(s, 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;
  }
  /**
   * 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, s) {
    return this.x = t.x + (e.x - t.x) * s, this.y = t.y + (e.y - t.y) * s, this.z = t.z + (e.z - t.z) * s, 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 s = t.x, a = t.y, o = t.z, c = e.x, u = e.y, d = e.z;
    return this.x = a * d - o * u, this.y = o * c - s * d, this.z = s * u - a * c, 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 s = t.dot(this) / e;
    return this.copy(t).multiplyScalar(s);
  }
  /**
   * 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 Mm.copy(this).projectOnVector(t), this.sub(Mm);
  }
  /**
   * 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(Mm.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 s = this.dot(t) / e;
    return Math.acos(ge(s, -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, s = this.y - t.y, a = this.z - t.z;
    return e * e + s * s + a * a;
  }
  /**
   * 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, s) {
    const a = Math.sin(e) * t;
    return this.x = a * Math.sin(s), this.y = Math.cos(e) * t, this.z = a * Math.cos(s), 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, s) {
    return this.x = t * Math.sin(e), this.y = s, 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(), s = this.setFromMatrixColumn(t, 1).length(), a = this.setFromMatrixColumn(t, 2).length();
    return this.x = e, this.y = s, this.z = a, 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, s = Math.sqrt(1 - e * e);
    return this.x = s * Math.cos(t), this.y = e, this.z = s * Math.sin(t), this;
  }
  *[Symbol.iterator]() {
    yield this.x, yield this.y, yield this.z;
  }
}
const Mm = /* @__PURE__ */ new st(), bS = /* @__PURE__ */ new pr();
class Me {
  /**
   * 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, s, a, o, c, u, d, h) {
    Me.prototype.isMatrix3 = !0, this.elements = [
      1,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      1
    ], t !== void 0 && this.set(t, e, s, a, o, c, u, d, 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, s, a, o, c, u, d, h) {
    const m = this.elements;
    return m[0] = t, m[1] = a, m[2] = u, m[3] = e, m[4] = o, m[5] = d, m[6] = s, m[7] = c, m[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, s = t.elements;
    return e[0] = s[0], e[1] = s[1], e[2] = s[2], e[3] = s[3], e[4] = s[4], e[5] = s[5], e[6] = s[6], e[7] = s[7], e[8] = s[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, s) {
    return t.setFromMatrix3Column(this, 0), e.setFromMatrix3Column(this, 1), s.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 s = t.elements, a = e.elements, o = this.elements, c = s[0], u = s[3], d = s[6], h = s[1], m = s[4], p = s[7], g = s[2], _ = s[5], x = s[8], A = a[0], b = a[3], y = a[6], E = a[1], w = a[4], M = a[7], O = a[2], C = a[5], D = a[8];
    return o[0] = c * A + u * E + d * O, o[3] = c * b + u * w + d * C, o[6] = c * y + u * M + d * D, o[1] = h * A + m * E + p * O, o[4] = h * b + m * w + p * C, o[7] = h * y + m * M + p * D, o[2] = g * A + _ * E + x * O, o[5] = g * b + _ * w + x * C, o[8] = g * y + _ * M + x * D, 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], s = t[1], a = t[2], o = t[3], c = t[4], u = t[5], d = t[6], h = t[7], m = t[8];
    return e * c * m - e * u * h - s * o * m + s * u * d + a * o * h - a * c * d;
  }
  /**
   * Inverts this matrix, using the [analytic method](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], s = t[1], a = t[2], o = t[3], c = t[4], u = t[5], d = t[6], h = t[7], m = t[8], p = m * c - u * h, g = u * d - m * o, _ = h * o - c * d, x = e * p + s * g + a * _;
    if (x === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
    const A = 1 / x;
    return t[0] = p * A, t[1] = (a * h - m * s) * A, t[2] = (u * s - a * c) * A, t[3] = g * A, t[4] = (m * e - a * d) * A, t[5] = (a * o - u * e) * A, t[6] = _ * A, t[7] = (s * d - h * e) * A, t[8] = (c * e - s * o) * A, 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, s, a, o, c, u) {
    const d = Math.cos(o), h = Math.sin(o);
    return this.set(
      s * d,
      s * h,
      -s * (d * c + h * u) + c + t,
      -a * h,
      a * d,
      -a * (-h * c + d * u) + u + 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(Em.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(Em.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(Em.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), s = Math.sin(t);
    return this.set(
      e,
      -s,
      0,
      s,
      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, s = t.elements;
    for (let a = 0; a < 9; a++)
      if (e[a] !== s[a]) 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 s = 0; s < 9; s++)
      this.elements[s] = t[s + 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 s = this.elements;
    return t[e] = s[0], t[e + 1] = s[1], t[e + 2] = s[2], t[e + 3] = s[3], t[e + 4] = s[4], t[e + 5] = s[5], t[e + 6] = s[6], t[e + 7] = s[7], t[e + 8] = s[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 Em = /* @__PURE__ */ new Me(), MS = /* @__PURE__ */ new Me().set(
  0.4123908,
  0.3575843,
  0.1804808,
  0.212639,
  0.7151687,
  0.0721923,
  0.0193308,
  0.1191948,
  0.9505322
), ES = /* @__PURE__ */ new Me().set(
  3.2409699,
  -1.5373832,
  -0.4986108,
  -0.9692436,
  1.8759675,
  0.0415551,
  0.0556301,
  -0.203977,
  1.0569715
);
function u3() {
  const n = {
    enabled: !0,
    workingColorSpace: pl,
    /**
     * 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(a, o, c) {
      return this.enabled === !1 || o === c || !o || !c || (this.spaces[o].transfer === We && (a.r = fr(a.r), a.g = fr(a.g), a.b = fr(a.b)), this.spaces[o].primaries !== this.spaces[c].primaries && (a.applyMatrix3(this.spaces[o].toXYZ), a.applyMatrix3(this.spaces[c].fromXYZ)), this.spaces[c].transfer === We && (a.r = ll(a.r), a.g = ll(a.g), a.b = ll(a.b))), a;
    },
    workingToColorSpace: function(a, o) {
      return this.convert(a, this.workingColorSpace, o);
    },
    colorSpaceToWorking: function(a, o) {
      return this.convert(a, o, this.workingColorSpace);
    },
    getPrimaries: function(a) {
      return this.spaces[a].primaries;
    },
    getTransfer: function(a) {
      return a === ta ? Md : this.spaces[a].transfer;
    },
    getToneMappingMode: function(a) {
      return this.spaces[a].outputColorSpaceConfig.toneMappingMode || "standard";
    },
    getLuminanceCoefficients: function(a, o = this.workingColorSpace) {
      return a.fromArray(this.spaces[o].luminanceCoefficients);
    },
    define: function(a) {
      Object.assign(this.spaces, a);
    },
    // Internal APIs
    _getMatrix: function(a, o, c) {
      return a.copy(this.spaces[o].toXYZ).multiply(this.spaces[c].fromXYZ);
    },
    _getDrawingBufferColorSpace: function(a) {
      return this.spaces[a].outputColorSpaceConfig.drawingBufferColorSpace;
    },
    _getUnpackColorSpace: function(a = this.workingColorSpace) {
      return this.spaces[a].workingColorSpaceConfig.unpackColorSpace;
    },
    // Deprecated
    fromWorkingColorSpace: function(a, o) {
      return Td("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."), n.workingToColorSpace(a, o);
    },
    toWorkingColorSpace: function(a, o) {
      return Td("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."), n.colorSpaceToWorking(a, o);
    }
  }, t = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], e = [0.2126, 0.7152, 0.0722], s = [0.3127, 0.329];
  return n.define({
    [pl]: {
      primaries: t,
      whitePoint: s,
      transfer: Md,
      toXYZ: MS,
      fromXYZ: ES,
      luminanceCoefficients: e,
      workingColorSpaceConfig: { unpackColorSpace: Xi },
      outputColorSpaceConfig: { drawingBufferColorSpace: Xi }
    },
    [Xi]: {
      primaries: t,
      whitePoint: s,
      transfer: We,
      toXYZ: MS,
      fromXYZ: ES,
      luminanceCoefficients: e,
      outputColorSpaceConfig: { drawingBufferColorSpace: Xi }
    }
  }), n;
}
const Be = /* @__PURE__ */ u3();
function fr(n) {
  return n < 0.04045 ? n * 0.0773993808 : Math.pow(n * 0.9478672986 + 0.0521327014, 2.4);
}
function ll(n) {
  return n < 31308e-7 ? n * 12.92 : 1.055 * Math.pow(n, 0.41666) - 0.055;
}
let Uo;
class f3 {
  /**
   * 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 s;
    if (t instanceof HTMLCanvasElement)
      s = t;
    else {
      Uo === void 0 && (Uo = wd("canvas")), Uo.width = t.width, Uo.height = t.height;
      const a = Uo.getContext("2d");
      t instanceof ImageData ? a.putImageData(t, 0, 0) : a.drawImage(t, 0, 0, t.width, t.height), s = Uo;
    }
    return s.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 = wd("canvas");
      e.width = t.width, e.height = t.height;
      const s = e.getContext("2d");
      s.drawImage(t, 0, 0, t.width, t.height);
      const a = s.getImageData(0, 0, t.width, t.height), o = a.data;
      for (let c = 0; c < o.length; c++)
        o[c] = fr(o[c] / 255) * 255;
      return s.putImageData(a, 0, 0), e;
    } else if (t.data) {
      const e = t.data.slice(0);
      for (let s = 0; s < e.length; s++)
        e instanceof Uint8Array || e instanceof Uint8ClampedArray ? e[s] = Math.floor(fr(e[s] / 255) * 255) : e[s] = fr(e[s]);
      return {
        data: e,
        width: t.width,
        height: t.height
      };
    } else
      return de("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), t;
  }
}
let d3 = 0;
class K0 {
  /**
   * 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: d3++ }), this.uuid = ur(), 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) : typeof VideoFrame < "u" && 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 s = {
      uuid: this.uuid,
      url: ""
    }, a = this.data;
    if (a !== null) {
      let o;
      if (Array.isArray(a)) {
        o = [];
        for (let c = 0, u = a.length; c < u; c++)
          a[c].isDataTexture ? o.push(wm(a[c].image)) : o.push(wm(a[c]));
      } else
        o = wm(a);
      s.url = o;
    }
    return e || (t.images[this.uuid] = s), s;
  }
}
function wm(n) {
  return typeof HTMLImageElement < "u" && n instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && n instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && n instanceof ImageBitmap ? f3.getDataURL(n) : n.data ? {
    data: Array.from(n.data),
    width: n.width,
    height: n.height,
    type: n.data.constructor.name
  } : (de("Texture: Unable to serialize Texture."), {});
}
let h3 = 0;
const Am = /* @__PURE__ */ new st();
class Jn extends qa {
  /**
   * 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 = Jn.DEFAULT_IMAGE, e = Jn.DEFAULT_MAPPING, s = or, a = or, o = Qn, c = Ia, u = Ni, d = Ci, h = Jn.DEFAULT_ANISOTROPY, m = ta) {
    super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: h3++ }), this.uuid = ur(), this.name = "", this.source = new K0(t), this.mipmaps = [], this.mapping = e, this.channel = 0, this.wrapS = s, this.wrapT = a, this.magFilter = o, this.minFilter = c, this.anisotropy = h, this.format = u, this.internalFormat = null, this.type = d, this.offset = new ae(0, 0), this.repeat = new ae(1, 1), this.center = new ae(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new Me(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = m, 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(Am).x;
  }
  /**
   * The height of the texture in pixels.
   */
  get height() {
    return this.source.getSize(Am).y;
  }
  /**
   * The depth of the texture in pixels.
   */
  get depth() {
    return this.source.getSize(Am).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 s = t[e];
      if (s === void 0) {
        de(`Texture.setValues(): parameter '${e}' has value of undefined.`);
        continue;
      }
      const a = this[e];
      if (a === void 0) {
        de(`Texture.setValues(): property '${e}' does not exist.`);
        continue;
      }
      a && s && a.isVector2 && s.isVector2 || a && s && a.isVector3 && s.isVector3 || a && s && a.isMatrix3 && s.isMatrix3 ? a.copy(s) : this[e] = s;
    }
  }
  /**
   * 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 s = {
      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 && (s.userData = this.userData), e || (t.textures[this.uuid] = s), s;
  }
  /**
   * 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 !== vM) return t;
    if (t.applyMatrix3(this.matrix), t.x < 0 || t.x > 1)
      switch (this.wrapS) {
        case Pg:
          t.x = t.x - Math.floor(t.x);
          break;
        case or:
          t.x = t.x < 0 ? 0 : 1;
          break;
        case Ig:
          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 Pg:
          t.y = t.y - Math.floor(t.y);
          break;
        case or:
          t.y = t.y < 0 ? 0 : 1;
          break;
        case Ig:
          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++;
  }
}
Jn.DEFAULT_IMAGE = null;
Jn.DEFAULT_MAPPING = vM;
Jn.DEFAULT_ANISOTROPY = 1;
class Je {
  /**
   * 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, s = 0, a = 1) {
    Je.prototype.isVector4 = !0, this.x = t, this.y = e, this.z = s, this.w = a;
  }
  /**
   * 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, s, a) {
    return this.x = t, this.y = e, this.z = s, this.w = a, 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, s = this.y, a = this.z, o = this.w, c = t.elements;
    return this.x = c[0] * e + c[4] * s + c[8] * a + c[12] * o, this.y = c[1] * e + c[5] * s + c[9] * a + c[13] * o, this.z = c[2] * e + c[6] * s + c[10] * a + c[14] * o, this.w = c[3] * e + c[7] * s + c[11] * a + c[15] * o, 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, s, a, o;
    const d = t.elements, h = d[0], m = d[4], p = d[8], g = d[1], _ = d[5], x = d[9], A = d[2], b = d[6], y = d[10];
    if (Math.abs(m - g) < 0.01 && Math.abs(p - A) < 0.01 && Math.abs(x - b) < 0.01) {
      if (Math.abs(m + g) < 0.1 && Math.abs(p + A) < 0.1 && Math.abs(x + b) < 0.1 && Math.abs(h + _ + y - 3) < 0.1)
        return this.set(1, 0, 0, 0), this;
      e = Math.PI;
      const w = (h + 1) / 2, M = (_ + 1) / 2, O = (y + 1) / 2, C = (m + g) / 4, D = (p + A) / 4, T = (x + b) / 4;
      return w > M && w > O ? w < 0.01 ? (s = 0, a = 0.707106781, o = 0.707106781) : (s = Math.sqrt(w), a = C / s, o = D / s) : M > O ? M < 0.01 ? (s = 0.707106781, a = 0, o = 0.707106781) : (a = Math.sqrt(M), s = C / a, o = T / a) : O < 0.01 ? (s = 0.707106781, a = 0.707106781, o = 0) : (o = Math.sqrt(O), s = D / o, a = T / o), this.set(s, a, o, e), this;
    }
    let E = Math.sqrt((b - x) * (b - x) + (p - A) * (p - A) + (g - m) * (g - m));
    return Math.abs(E) < 1e-3 && (E = 1), this.x = (b - x) / E, this.y = (p - A) / E, this.z = (g - m) / E, this.w = Math.acos((h + _ + y - 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 = ge(this.x, t.x, e.x), this.y = ge(this.y, t.y, e.y), this.z = ge(this.z, t.z, e.z), this.w = ge(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 = ge(this.x, t, e), this.y = ge(this.y, t, e), this.z = ge(this.z, t, e), this.w = ge(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 s = this.length();
    return this.divideScalar(s || 1).multiplyScalar(ge(s, 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, s) {
    return this.x = t.x + (e.x - t.x) * s, this.y = t.y + (e.y - t.y) * s, this.z = t.z + (e.z - t.z) * s, this.w = t.w + (e.w - t.w) * s, 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 p3 extends qa {
  /**
   * 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, s = {}) {
    super(), s = Object.assign({
      generateMipmaps: !1,
      internalFormat: null,
      minFilter: Qn,
      depthBuffer: !0,
      stencilBuffer: !1,
      resolveDepthBuffer: !0,
      resolveStencilBuffer: !0,
      depthTexture: null,
      samples: 0,
      count: 1,
      depth: 1,
      multiview: !1
    }, s), this.isRenderTarget = !0, this.width = t, this.height = e, this.depth = s.depth, this.scissor = new Je(0, 0, t, e), this.scissorTest = !1, this.viewport = new Je(0, 0, t, e), this.textures = [];
    const a = { width: t, height: e, depth: s.depth }, o = new Jn(a), c = s.count;
    for (let u = 0; u < c; u++)
      this.textures[u] = o.clone(), this.textures[u].isRenderTargetTexture = !0, this.textures[u].renderTarget = this;
    this._setTextureOptions(s), this.depthBuffer = s.depthBuffer, this.stencilBuffer = s.stencilBuffer, this.resolveDepthBuffer = s.resolveDepthBuffer, this.resolveStencilBuffer = s.resolveStencilBuffer, this._depthTexture = null, this.depthTexture = s.depthTexture, this.samples = s.samples, this.multiview = s.multiview;
  }
  _setTextureOptions(t = {}) {
    const e = {
      minFilter: Qn,
      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 s = 0; s < this.textures.length; s++)
      this.textures[s].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, s = 1) {
    if (this.width !== t || this.height !== e || this.depth !== s) {
      this.width = t, this.height = e, this.depth = s;
      for (let a = 0, o = this.textures.length; a < o; a++)
        this.textures[a].image.width = t, this.textures[a].image.height = e, this.textures[a].image.depth = s, this.textures[a].isData3DTexture !== !0 && (this.textures[a].isArrayTexture = this.textures[a].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, s = t.textures.length; e < s; e++) {
      this.textures[e] = t.textures[e].clone(), this.textures[e].isRenderTargetTexture = !0, this.textures[e].renderTarget = this;
      const a = Object.assign({}, t.textures[e].image);
      this.textures[e].source = new K0(a);
    }
    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 As extends p3 {
  /**
   * 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, s = {}) {
    super(t, e, s), this.isWebGLRenderTarget = !0;
  }
}
class TM extends Jn {
  /**
   * 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, s = 1, a = 1) {
    super(null), this.isDataArrayTexture = !0, this.image = { data: t, width: e, height: s, depth: a }, this.magFilter = vn, this.minFilter = vn, this.wrapR = or, 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 m3 extends Jn {
  /**
   * 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, s = 1, a = 1) {
    super(null), this.isData3DTexture = !0, this.image = { data: t, width: e, height: s, depth: a }, this.magFilter = vn, this.minFilter = vn, this.wrapR = or, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
  }
}
class je {
  /**
   * 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, s, a, o, c, u, d, h, m, p, g, _, x, A, b) {
    je.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, s, a, o, c, u, d, h, m, p, g, _, x, A, b);
  }
  /**
   * 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, s, a, o, c, u, d, h, m, p, g, _, x, A, b) {
    const y = this.elements;
    return y[0] = t, y[4] = e, y[8] = s, y[12] = a, y[1] = o, y[5] = c, y[9] = u, y[13] = d, y[2] = h, y[6] = m, y[10] = p, y[14] = g, y[3] = _, y[7] = x, y[11] = A, y[15] = b, 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 je().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, s = t.elements;
    return e[0] = s[0], e[1] = s[1], e[2] = s[2], e[3] = s[3], e[4] = s[4], e[5] = s[5], e[6] = s[6], e[7] = s[7], e[8] = s[8], e[9] = s[9], e[10] = s[10], e[11] = s[11], e[12] = s[12], e[13] = s[13], e[14] = s[14], e[15] = s[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, s = t.elements;
    return e[12] = s[12], e[13] = s[13], e[14] = s[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, s) {
    return this.determinant() === 0 ? (t.set(1, 0, 0), e.set(0, 1, 0), s.set(0, 0, 1), this) : (t.setFromMatrixColumn(this, 0), e.setFromMatrixColumn(this, 1), s.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, s) {
    return this.set(
      t.x,
      e.x,
      s.x,
      0,
      t.y,
      e.y,
      s.y,
      0,
      t.z,
      e.z,
      s.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) {
    if (t.determinant() === 0)
      return this.identity();
    const e = this.elements, s = t.elements, a = 1 / Po.setFromMatrixColumn(t, 0).length(), o = 1 / Po.setFromMatrixColumn(t, 1).length(), c = 1 / Po.setFromMatrixColumn(t, 2).length();
    return e[0] = s[0] * a, e[1] = s[1] * a, e[2] = s[2] * a, e[3] = 0, e[4] = s[4] * o, e[5] = s[5] * o, e[6] = s[6] * o, e[7] = 0, e[8] = s[8] * c, e[9] = s[9] * c, e[10] = s[10] * c, 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](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, s = t.x, a = t.y, o = t.z, c = Math.cos(s), u = Math.sin(s), d = Math.cos(a), h = Math.sin(a), m = Math.cos(o), p = Math.sin(o);
    if (t.order === "XYZ") {
      const g = c * m, _ = c * p, x = u * m, A = u * p;
      e[0] = d * m, e[4] = -d * p, e[8] = h, e[1] = _ + x * h, e[5] = g - A * h, e[9] = -u * d, e[2] = A - g * h, e[6] = x + _ * h, e[10] = c * d;
    } else if (t.order === "YXZ") {
      const g = d * m, _ = d * p, x = h * m, A = h * p;
      e[0] = g + A * u, e[4] = x * u - _, e[8] = c * h, e[1] = c * p, e[5] = c * m, e[9] = -u, e[2] = _ * u - x, e[6] = A + g * u, e[10] = c * d;
    } else if (t.order === "ZXY") {
      const g = d * m, _ = d * p, x = h * m, A = h * p;
      e[0] = g - A * u, e[4] = -c * p, e[8] = x + _ * u, e[1] = _ + x * u, e[5] = c * m, e[9] = A - g * u, e[2] = -c * h, e[6] = u, e[10] = c * d;
    } else if (t.order === "ZYX") {
      const g = c * m, _ = c * p, x = u * m, A = u * p;
      e[0] = d * m, e[4] = x * h - _, e[8] = g * h + A, e[1] = d * p, e[5] = A * h + g, e[9] = _ * h - x, e[2] = -h, e[6] = u * d, e[10] = c * d;
    } else if (t.order === "YZX") {
      const g = c * d, _ = c * h, x = u * d, A = u * h;
      e[0] = d * m, e[4] = A - g * p, e[8] = x * p + _, e[1] = p, e[5] = c * m, e[9] = -u * m, e[2] = -h * m, e[6] = _ * p + x, e[10] = g - A * p;
    } else if (t.order === "XZY") {
      const g = c * d, _ = c * h, x = u * d, A = u * h;
      e[0] = d * m, e[4] = -p, e[8] = h * m, e[1] = g * p + A, e[5] = c * m, e[9] = _ * p - x, e[2] = x * p - _, e[6] = u * m, e[10] = A * p + g;
    }
    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](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(g3, t, v3);
  }
  /**
   * 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, s) {
    const a = this.elements;
    return wi.subVectors(t, e), wi.lengthSq() === 0 && (wi.z = 1), wi.normalize(), Xr.crossVectors(s, wi), Xr.lengthSq() === 0 && (Math.abs(s.z) === 1 ? wi.x += 1e-4 : wi.z += 1e-4, wi.normalize(), Xr.crossVectors(s, wi)), Xr.normalize(), xf.crossVectors(wi, Xr), a[0] = Xr.x, a[4] = xf.x, a[8] = wi.x, a[1] = Xr.y, a[5] = xf.y, a[9] = wi.y, a[2] = Xr.z, a[6] = xf.z, a[10] = wi.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 s = t.elements, a = e.elements, o = this.elements, c = s[0], u = s[4], d = s[8], h = s[12], m = s[1], p = s[5], g = s[9], _ = s[13], x = s[2], A = s[6], b = s[10], y = s[14], E = s[3], w = s[7], M = s[11], O = s[15], C = a[0], D = a[4], T = a[8], L = a[12], z = a[1], R = a[5], B = a[9], H = a[13], U = a[2], V = a[6], N = a[10], I = a[14], k = a[3], X = a[7], Q = a[11], F = a[15];
    return o[0] = c * C + u * z + d * U + h * k, o[4] = c * D + u * R + d * V + h * X, o[8] = c * T + u * B + d * N + h * Q, o[12] = c * L + u * H + d * I + h * F, o[1] = m * C + p * z + g * U + _ * k, o[5] = m * D + p * R + g * V + _ * X, o[9] = m * T + p * B + g * N + _ * Q, o[13] = m * L + p * H + g * I + _ * F, o[2] = x * C + A * z + b * U + y * k, o[6] = x * D + A * R + b * V + y * X, o[10] = x * T + A * B + b * N + y * Q, o[14] = x * L + A * H + b * I + y * F, o[3] = E * C + w * z + M * U + O * k, o[7] = E * D + w * R + M * V + O * X, o[11] = E * T + w * B + M * N + O * Q, o[15] = E * L + w * H + M * I + O * F, 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](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
   *
   * @return {number} The determinant.
   */
  determinant() {
    const t = this.elements, e = t[0], s = t[4], a = t[8], o = t[12], c = t[1], u = t[5], d = t[9], h = t[13], m = t[2], p = t[6], g = t[10], _ = t[14], x = t[3], A = t[7], b = t[11], y = t[15], E = d * _ - h * g, w = u * _ - h * p, M = u * g - d * p, O = c * _ - h * m, C = c * g - d * m, D = c * p - u * m;
    return e * (A * E - b * w + y * M) - s * (x * E - b * O + y * C) + a * (x * w - A * O + y * D) - o * (x * M - A * C + b * D);
  }
  /**
   * 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, s) {
    const a = this.elements;
    return t.isVector3 ? (a[12] = t.x, a[13] = t.y, a[14] = t.z) : (a[12] = t, a[13] = e, a[14] = s), this;
  }
  /**
   * Inverts this matrix, using the [analytic method](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], s = t[1], a = t[2], o = t[3], c = t[4], u = t[5], d = t[6], h = t[7], m = t[8], p = t[9], g = t[10], _ = t[11], x = t[12], A = t[13], b = t[14], y = t[15], E = e * u - s * c, w = e * d - a * c, M = e * h - o * c, O = s * d - a * u, C = s * h - o * u, D = a * h - o * d, T = m * A - p * x, L = m * b - g * x, z = m * y - _ * x, R = p * b - g * A, B = p * y - _ * A, H = g * y - _ * b, U = E * H - w * B + M * R + O * z - C * L + D * T;
    if (U === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    const V = 1 / U;
    return t[0] = (u * H - d * B + h * R) * V, t[1] = (a * B - s * H - o * R) * V, t[2] = (A * D - b * C + y * O) * V, t[3] = (g * C - p * D - _ * O) * V, t[4] = (d * z - c * H - h * L) * V, t[5] = (e * H - a * z + o * L) * V, t[6] = (b * M - x * D - y * w) * V, t[7] = (m * D - g * M + _ * w) * V, t[8] = (c * B - u * z + h * T) * V, t[9] = (s * z - e * B - o * T) * V, t[10] = (x * C - A * M + y * E) * V, t[11] = (p * M - m * C - _ * E) * V, t[12] = (u * L - c * R - d * T) * V, t[13] = (e * R - s * L + a * T) * V, t[14] = (A * w - x * O - b * E) * V, t[15] = (m * O - p * w + g * E) * V, 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, s = t.x, a = t.y, o = t.z;
    return e[0] *= s, e[4] *= a, e[8] *= o, e[1] *= s, e[5] *= a, e[9] *= o, e[2] *= s, e[6] *= a, e[10] *= o, e[3] *= s, e[7] *= a, e[11] *= o, 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], s = t[4] * t[4] + t[5] * t[5] + t[6] * t[6], a = t[8] * t[8] + t[9] * t[9] + t[10] * t[10];
    return Math.sqrt(Math.max(e, s, a));
  }
  /**
   * 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, s) {
    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,
      s,
      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), s = Math.sin(t);
    return this.set(
      1,
      0,
      0,
      0,
      0,
      e,
      -s,
      0,
      0,
      s,
      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), s = Math.sin(t);
    return this.set(
      e,
      0,
      s,
      0,
      0,
      1,
      0,
      0,
      -s,
      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), s = Math.sin(t);
    return this.set(
      e,
      -s,
      0,
      0,
      s,
      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](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 s = Math.cos(e), a = Math.sin(e), o = 1 - s, c = t.x, u = t.y, d = t.z, h = o * c, m = o * u;
    return this.set(
      h * c + s,
      h * u - a * d,
      h * d + a * u,
      0,
      h * u + a * d,
      m * u + s,
      m * d - a * c,
      0,
      h * d - a * u,
      m * d + a * c,
      o * d * d + s,
      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, s) {
    return this.set(
      t,
      0,
      0,
      0,
      0,
      e,
      0,
      0,
      0,
      0,
      s,
      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, s, a, o, c) {
    return this.set(
      1,
      s,
      o,
      0,
      t,
      1,
      c,
      0,
      e,
      a,
      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, s) {
    const a = this.elements, o = e._x, c = e._y, u = e._z, d = e._w, h = o + o, m = c + c, p = u + u, g = o * h, _ = o * m, x = o * p, A = c * m, b = c * p, y = u * p, E = d * h, w = d * m, M = d * p, O = s.x, C = s.y, D = s.z;
    return a[0] = (1 - (A + y)) * O, a[1] = (_ + M) * O, a[2] = (x - w) * O, a[3] = 0, a[4] = (_ - M) * C, a[5] = (1 - (g + y)) * C, a[6] = (b + E) * C, a[7] = 0, a[8] = (x + w) * D, a[9] = (b - E) * D, a[10] = (1 - (g + A)) * D, a[11] = 0, a[12] = t.x, a[13] = t.y, a[14] = t.z, a[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, s) {
    const a = this.elements;
    t.x = a[12], t.y = a[13], t.z = a[14];
    const o = this.determinant();
    if (o === 0)
      return s.set(1, 1, 1), e.identity(), this;
    let c = Po.set(a[0], a[1], a[2]).length();
    const u = Po.set(a[4], a[5], a[6]).length(), d = Po.set(a[8], a[9], a[10]).length();
    o < 0 && (c = -c), Ki.copy(this);
    const h = 1 / c, m = 1 / u, p = 1 / d;
    return Ki.elements[0] *= h, Ki.elements[1] *= h, Ki.elements[2] *= h, Ki.elements[4] *= m, Ki.elements[5] *= m, Ki.elements[6] *= m, Ki.elements[8] *= p, Ki.elements[9] *= p, Ki.elements[10] *= p, e.setFromRotationMatrix(Ki), s.x = c, s.y = u, s.z = d, 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, s, a, o, c, u = Ms, d = !1) {
    const h = this.elements, m = 2 * o / (e - t), p = 2 * o / (s - a), g = (e + t) / (e - t), _ = (s + a) / (s - a);
    let x, A;
    if (d)
      x = o / (c - o), A = c * o / (c - o);
    else if (u === Ms)
      x = -(c + o) / (c - o), A = -2 * c * o / (c - o);
    else if (u === Hc)
      x = -c / (c - o), A = -c * o / (c - o);
    else
      throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + u);
    return h[0] = m, h[4] = 0, h[8] = g, h[12] = 0, h[1] = 0, h[5] = p, h[9] = _, h[13] = 0, h[2] = 0, h[6] = 0, h[10] = x, h[14] = A, 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, s, a, o, c, u = Ms, d = !1) {
    const h = this.elements, m = 2 / (e - t), p = 2 / (s - a), g = -(e + t) / (e - t), _ = -(s + a) / (s - a);
    let x, A;
    if (d)
      x = 1 / (c - o), A = c / (c - o);
    else if (u === Ms)
      x = -2 / (c - o), A = -(c + o) / (c - o);
    else if (u === Hc)
      x = -1 / (c - o), A = -o / (c - o);
    else
      throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + u);
    return h[0] = m, h[4] = 0, h[8] = 0, h[12] = g, h[1] = 0, h[5] = p, h[9] = 0, h[13] = _, h[2] = 0, h[6] = 0, h[10] = x, h[14] = A, 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, s = t.elements;
    for (let a = 0; a < 16; a++)
      if (e[a] !== s[a]) 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 s = 0; s < 16; s++)
      this.elements[s] = t[s + 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 s = this.elements;
    return t[e] = s[0], t[e + 1] = s[1], t[e + 2] = s[2], t[e + 3] = s[3], t[e + 4] = s[4], t[e + 5] = s[5], t[e + 6] = s[6], t[e + 7] = s[7], t[e + 8] = s[8], t[e + 9] = s[9], t[e + 10] = s[10], t[e + 11] = s[11], t[e + 12] = s[12], t[e + 13] = s[13], t[e + 14] = s[14], t[e + 15] = s[15], t;
  }
}
const Po = /* @__PURE__ */ new st(), Ki = /* @__PURE__ */ new je(), g3 = /* @__PURE__ */ new st(0, 0, 0), v3 = /* @__PURE__ */ new st(1, 1, 1), Xr = /* @__PURE__ */ new st(), xf = /* @__PURE__ */ new st(), wi = /* @__PURE__ */ new st(), wS = /* @__PURE__ */ new je(), AS = /* @__PURE__ */ new pr();
class Rs {
  /**
   * 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, s = 0, a = Rs.DEFAULT_ORDER) {
    this.isEuler = !0, this._x = t, this._y = e, this._z = s, this._order = a;
  }
  /**
   * 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, s, a = this._order) {
    return this._x = t, this._y = e, this._z = s, this._order = a, 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, s = !0) {
    const a = t.elements, o = a[0], c = a[4], u = a[8], d = a[1], h = a[5], m = a[9], p = a[2], g = a[6], _ = a[10];
    switch (e) {
      case "XYZ":
        this._y = Math.asin(ge(u, -1, 1)), Math.abs(u) < 0.9999999 ? (this._x = Math.atan2(-m, _), this._z = Math.atan2(-c, o)) : (this._x = Math.atan2(g, h), this._z = 0);
        break;
      case "YXZ":
        this._x = Math.asin(-ge(m, -1, 1)), Math.abs(m) < 0.9999999 ? (this._y = Math.atan2(u, _), this._z = Math.atan2(d, h)) : (this._y = Math.atan2(-p, o), this._z = 0);
        break;
      case "ZXY":
        this._x = Math.asin(ge(g, -1, 1)), Math.abs(g) < 0.9999999 ? (this._y = Math.atan2(-p, _), this._z = Math.atan2(-c, h)) : (this._y = 0, this._z = Math.atan2(d, o));
        break;
      case "ZYX":
        this._y = Math.asin(-ge(p, -1, 1)), Math.abs(p) < 0.9999999 ? (this._x = Math.atan2(g, _), this._z = Math.atan2(d, o)) : (this._x = 0, this._z = Math.atan2(-c, h));
        break;
      case "YZX":
        this._z = Math.asin(ge(d, -1, 1)), Math.abs(d) < 0.9999999 ? (this._x = Math.atan2(-m, h), this._y = Math.atan2(-p, o)) : (this._x = 0, this._y = Math.atan2(u, _));
        break;
      case "XZY":
        this._z = Math.asin(-ge(c, -1, 1)), Math.abs(c) < 0.9999999 ? (this._x = Math.atan2(g, h), this._y = Math.atan2(u, o)) : (this._x = Math.atan2(-m, _), this._y = 0);
        break;
      default:
        de("Euler: .setFromRotationMatrix() encountered an unknown order: " + e);
    }
    return this._order = e, s === !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, s) {
    return wS.makeRotationFromQuaternion(t), this.setFromRotationMatrix(wS, e, s);
  }
  /**
   * 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 AS.setFromEuler(this), this.setFromQuaternion(AS, 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;
  }
}
Rs.DEFAULT_ORDER = "XYZ";
class CM {
  /**
   * 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 _3 = 0;
const TS = /* @__PURE__ */ new st(), Io = /* @__PURE__ */ new pr(), Qs = /* @__PURE__ */ new je(), Sf = /* @__PURE__ */ new st(), hc = /* @__PURE__ */ new st(), y3 = /* @__PURE__ */ new st(), x3 = /* @__PURE__ */ new pr(), CS = /* @__PURE__ */ new st(1, 0, 0), RS = /* @__PURE__ */ new st(0, 1, 0), DS = /* @__PURE__ */ new st(0, 0, 1), NS = { type: "added" }, S3 = { type: "removed" }, Bo = { type: "childadded", child: null }, Tm = { type: "childremoved", child: null };
class Tn extends qa {
  /**
   * Constructs a new 3D object.
   */
  constructor() {
    super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: _3++ }), this.uuid = ur(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = Tn.DEFAULT_UP.clone();
    const t = new st(), e = new Rs(), s = new pr(), a = new st(1, 1, 1);
    function o() {
      s.setFromEuler(e, !1);
    }
    function c() {
      e.setFromQuaternion(s, void 0, !1);
    }
    e._onChange(o), s._onChange(c), 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: s
      },
      /**
       * Represents the object's local scale.
       *
       * @name Object3D#scale
       * @type {Vector3}
       * @default (1,1,1)
       */
      scale: {
        configurable: !0,
        enumerable: !0,
        value: a
      },
      /**
       * Represents the object's model-view matrix.
       *
       * @name Object3D#modelViewMatrix
       * @type {Matrix4}
       */
      modelViewMatrix: {
        value: new je()
      },
      /**
       * Represents the object's normal matrix.
       *
       * @name Object3D#normalMatrix
       * @type {Matrix3}
       */
      normalMatrix: {
        value: new Me()
      }
    }), this.matrix = new je(), this.matrixWorld = new je(), this.matrixAutoUpdate = Tn.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = Tn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new CM(), 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.static = !1, this.userData = {}, this.pivot = null;
  }
  /**
   * 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 Io.setFromAxisAngle(t, e), this.quaternion.multiply(Io), 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 Io.setFromAxisAngle(t, e), this.quaternion.premultiply(Io), 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(CS, 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(RS, 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(DS, 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 TS.copy(t).applyQuaternion(this.quaternion), this.position.add(TS.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(CS, 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(RS, 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(DS, 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 world 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(Qs.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, s) {
    t.isVector3 ? Sf.copy(t) : Sf.set(t, e, s);
    const a = this.parent;
    this.updateWorldMatrix(!0, !1), hc.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? Qs.lookAt(hc, Sf, this.up) : Qs.lookAt(Sf, hc, this.up), this.quaternion.setFromRotationMatrix(Qs), a && (Qs.extractRotation(a.matrixWorld), Io.setFromRotationMatrix(Qs), this.quaternion.premultiply(Io.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 ? (Ie("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(NS), Bo.child = t, this.dispatchEvent(Bo), Bo.child = null) : Ie("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 s = 0; s < arguments.length; s++)
        this.remove(arguments[s]);
      return this;
    }
    const e = this.children.indexOf(t);
    return e !== -1 && (t.parent = null, this.children.splice(e, 1), t.dispatchEvent(S3), Tm.child = t, this.dispatchEvent(Tm), Tm.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), Qs.copy(this.matrixWorld).invert(), t.parent !== null && (t.parent.updateWorldMatrix(!0, !1), Qs.multiply(t.parent.matrixWorld)), t.applyMatrix4(Qs), t.removeFromParent(), t.parent = this, this.children.push(t), t.updateWorldMatrix(!1, !0), t.dispatchEvent(NS), Bo.child = t, this.dispatchEvent(Bo), Bo.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 s = 0, a = this.children.length; s < a; s++) {
      const c = this.children[s].getObjectByProperty(t, e);
      if (c !== void 0)
        return c;
    }
  }
  /**
   * 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, s = []) {
    this[t] === e && s.push(this);
    const a = this.children;
    for (let o = 0, c = a.length; o < c; o++)
      a[o].getObjectsByProperty(t, e, s);
    return s;
  }
  /**
   * 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(hc, t, y3), 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(hc, x3, 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 s = 0, a = e.length; s < a; s++)
      e[s].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 s = 0, a = e.length; s < a; s++)
      e[s].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);
    const t = this.pivot;
    if (t !== null) {
      const e = t.x, s = t.y, a = t.z, o = this.matrix.elements;
      o[12] += e - o[0] * e - o[4] * s - o[8] * a, o[13] += s - o[1] * e - o[5] * s - o[9] * a, o[14] += a - o[2] * e - o[6] * s - o[10] * a;
    }
    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#matrixWorldNeedsUpdate} is `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 s = 0, a = e.length; s < a; s++)
      e[s].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 s = this.parent;
    if (t === !0 && s !== null && s.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 a = this.children;
      for (let o = 0, c = a.length; o < c; o++)
        a[o].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", s = {};
    e && (t = {
      geometries: {},
      materials: {},
      textures: {},
      images: {},
      shapes: {},
      skeletons: {},
      animations: {},
      nodes: {}
    }, s.metadata = {
      version: 4.7,
      type: "Object",
      generator: "Object3D.toJSON"
    });
    const a = {};
    a.uuid = this.uuid, a.type = this.type, this.name !== "" && (a.name = this.name), this.castShadow === !0 && (a.castShadow = !0), this.receiveShadow === !0 && (a.receiveShadow = !0), this.visible === !1 && (a.visible = !1), this.frustumCulled === !1 && (a.frustumCulled = !1), this.renderOrder !== 0 && (a.renderOrder = this.renderOrder), this.static !== !1 && (a.static = this.static), Object.keys(this.userData).length > 0 && (a.userData = this.userData), a.layers = this.layers.mask, a.matrix = this.matrix.toArray(), a.up = this.up.toArray(), this.pivot !== null && (a.pivot = this.pivot.toArray()), this.matrixAutoUpdate === !1 && (a.matrixAutoUpdate = !1), this.morphTargetDictionary !== void 0 && (a.morphTargetDictionary = Object.assign({}, this.morphTargetDictionary)), this.morphTargetInfluences !== void 0 && (a.morphTargetInfluences = this.morphTargetInfluences.slice()), this.isInstancedMesh && (a.type = "InstancedMesh", a.count = this.count, a.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (a.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (a.type = "BatchedMesh", a.perObjectFrustumCulled = this.perObjectFrustumCulled, a.sortObjects = this.sortObjects, a.drawRanges = this._drawRanges, a.reservedRanges = this._reservedRanges, a.geometryInfo = this._geometryInfo.map((u) => ({
      ...u,
      boundingBox: u.boundingBox ? u.boundingBox.toJSON() : void 0,
      boundingSphere: u.boundingSphere ? u.boundingSphere.toJSON() : void 0
    })), a.instanceInfo = this._instanceInfo.map((u) => ({ ...u })), a.availableInstanceIds = this._availableInstanceIds.slice(), a.availableGeometryIds = this._availableGeometryIds.slice(), a.nextIndexStart = this._nextIndexStart, a.nextVertexStart = this._nextVertexStart, a.geometryCount = this._geometryCount, a.maxInstanceCount = this._maxInstanceCount, a.maxVertexCount = this._maxVertexCount, a.maxIndexCount = this._maxIndexCount, a.geometryInitialized = this._geometryInitialized, a.matricesTexture = this._matricesTexture.toJSON(t), a.indirectTexture = this._indirectTexture.toJSON(t), this._colorsTexture !== null && (a.colorsTexture = this._colorsTexture.toJSON(t)), this.boundingSphere !== null && (a.boundingSphere = this.boundingSphere.toJSON()), this.boundingBox !== null && (a.boundingBox = this.boundingBox.toJSON()));
    function o(u, d) {
      return u[d.uuid] === void 0 && (u[d.uuid] = d.toJSON(t)), d.uuid;
    }
    if (this.isScene)
      this.background && (this.background.isColor ? a.background = this.background.toJSON() : this.background.isTexture && (a.background = this.background.toJSON(t).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (a.environment = this.environment.toJSON(t).uuid);
    else if (this.isMesh || this.isLine || this.isPoints) {
      a.geometry = o(t.geometries, this.geometry);
      const u = this.geometry.parameters;
      if (u !== void 0 && u.shapes !== void 0) {
        const d = u.shapes;
        if (Array.isArray(d))
          for (let h = 0, m = d.length; h < m; h++) {
            const p = d[h];
            o(t.shapes, p);
          }
        else
          o(t.shapes, d);
      }
    }
    if (this.isSkinnedMesh && (a.bindMode = this.bindMode, a.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (o(t.skeletons, this.skeleton), a.skeleton = this.skeleton.uuid)), this.material !== void 0)
      if (Array.isArray(this.material)) {
        const u = [];
        for (let d = 0, h = this.material.length; d < h; d++)
          u.push(o(t.materials, this.material[d]));
        a.material = u;
      } else
        a.material = o(t.materials, this.material);
    if (this.children.length > 0) {
      a.children = [];
      for (let u = 0; u < this.children.length; u++)
        a.children.push(this.children[u].toJSON(t).object);
    }
    if (this.animations.length > 0) {
      a.animations = [];
      for (let u = 0; u < this.animations.length; u++) {
        const d = this.animations[u];
        a.animations.push(o(t.animations, d));
      }
    }
    if (e) {
      const u = c(t.geometries), d = c(t.materials), h = c(t.textures), m = c(t.images), p = c(t.shapes), g = c(t.skeletons), _ = c(t.animations), x = c(t.nodes);
      u.length > 0 && (s.geometries = u), d.length > 0 && (s.materials = d), h.length > 0 && (s.textures = h), m.length > 0 && (s.images = m), p.length > 0 && (s.shapes = p), g.length > 0 && (s.skeletons = g), _.length > 0 && (s.animations = _), x.length > 0 && (s.nodes = x);
    }
    return s.object = a, s;
    function c(u) {
      const d = [];
      for (const h in u) {
        const m = u[h];
        delete m.metadata, d.push(m);
      }
      return d;
    }
  }
  /**
   * 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), t.pivot !== null && (this.pivot = t.pivot.clone()), 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.static = t.static, this.animations = t.animations.slice(), this.userData = JSON.parse(JSON.stringify(t.userData)), e === !0)
      for (let s = 0; s < t.children.length; s++) {
        const a = t.children[s];
        this.add(a.clone());
      }
    return this;
  }
}
Tn.DEFAULT_UP = /* @__PURE__ */ new st(0, 1, 0);
Tn.DEFAULT_MATRIX_AUTO_UPDATE = !0;
Tn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0;
class na extends Tn {
  constructor() {
    super(), this.isGroup = !0, this.type = "Group";
  }
}
const b3 = { type: "move" };
class Cm {
  /**
   * 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 na(), 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 na(), this._targetRay.matrixAutoUpdate = !1, this._targetRay.visible = !1, this._targetRay.hasLinearVelocity = !1, this._targetRay.linearVelocity = new st(), this._targetRay.hasAngularVelocity = !1, this._targetRay.angularVelocity = new st()), 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 na(), this._grip.matrixAutoUpdate = !1, this._grip.visible = !1, this._grip.hasLinearVelocity = !1, this._grip.linearVelocity = new st(), this._grip.hasAngularVelocity = !1, this._grip.angularVelocity = new st()), 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 s of t.hand.values())
          this._getHandJoint(e, s);
    }
    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, s) {
    let a = null, o = null, c = null;
    const u = this._targetRay, d = this._grip, h = this._hand;
    if (t && e.session.visibilityState !== "visible-blurred") {
      if (h && t.hand) {
        c = !0;
        for (const A of t.hand.values()) {
          const b = e.getJointPose(A, s), y = this._getHandJoint(h, A);
          b !== null && (y.matrix.fromArray(b.transform.matrix), y.matrix.decompose(y.position, y.rotation, y.scale), y.matrixWorldNeedsUpdate = !0, y.jointRadius = b.radius), y.visible = b !== null;
        }
        const m = h.joints["index-finger-tip"], p = h.joints["thumb-tip"], g = m.position.distanceTo(p.position), _ = 0.02, x = 5e-3;
        h.inputState.pinching && g > _ + x ? (h.inputState.pinching = !1, this.dispatchEvent({
          type: "pinchend",
          handedness: t.handedness,
          target: this
        })) : !h.inputState.pinching && g <= _ - x && (h.inputState.pinching = !0, this.dispatchEvent({
          type: "pinchstart",
          handedness: t.handedness,
          target: this
        }));
      } else
        d !== null && t.gripSpace && (o = e.getPose(t.gripSpace, s), o !== null && (d.matrix.fromArray(o.transform.matrix), d.matrix.decompose(d.position, d.rotation, d.scale), d.matrixWorldNeedsUpdate = !0, o.linearVelocity ? (d.hasLinearVelocity = !0, d.linearVelocity.copy(o.linearVelocity)) : d.hasLinearVelocity = !1, o.angularVelocity ? (d.hasAngularVelocity = !0, d.angularVelocity.copy(o.angularVelocity)) : d.hasAngularVelocity = !1));
      u !== null && (a = e.getPose(t.targetRaySpace, s), a === null && o !== null && (a = o), a !== null && (u.matrix.fromArray(a.transform.matrix), u.matrix.decompose(u.position, u.rotation, u.scale), u.matrixWorldNeedsUpdate = !0, a.linearVelocity ? (u.hasLinearVelocity = !0, u.linearVelocity.copy(a.linearVelocity)) : u.hasLinearVelocity = !1, a.angularVelocity ? (u.hasAngularVelocity = !0, u.angularVelocity.copy(a.angularVelocity)) : u.hasAngularVelocity = !1, this.dispatchEvent(b3)));
    }
    return u !== null && (u.visible = a !== null), d !== null && (d.visible = o !== null), h !== null && (h.visible = c !== 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 s = new na();
      s.matrixAutoUpdate = !1, s.visible = !1, t.joints[e.jointName] = s, t.add(s);
    }
    return t.joints[e.jointName];
  }
}
const RM = {
  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
}, Wr = { h: 0, s: 0, l: 0 }, bf = { h: 0, s: 0, l: 0 };
function Rm(n, t, e) {
  return e < 0 && (e += 1), e > 1 && (e -= 1), e < 1 / 6 ? n + (t - n) * 6 * e : e < 1 / 2 ? t : e < 2 / 3 ? n + (t - n) * 6 * (2 / 3 - e) : n;
}
let we = 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, s) {
    return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(t, e, s);
  }
  /**
   * 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, s) {
    if (e === void 0 && s === void 0) {
      const a = t;
      a && a.isColor ? this.copy(a) : typeof a == "number" ? this.setHex(a) : typeof a == "string" && this.setStyle(a);
    } else
      this.setRGB(t, e, s);
    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 = Xi) {
    return t = Math.floor(t), this.r = (t >> 16 & 255) / 255, this.g = (t >> 8 & 255) / 255, this.b = (t & 255) / 255, Be.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, s, a = Be.workingColorSpace) {
    return this.r = t, this.g = e, this.b = s, Be.colorSpaceToWorking(this, a), 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, s, a = Be.workingColorSpace) {
    if (t = $0(t, 1), e = ge(e, 0, 1), s = ge(s, 0, 1), e === 0)
      this.r = this.g = this.b = s;
    else {
      const o = s <= 0.5 ? s * (1 + e) : s + e - s * e, c = 2 * s - o;
      this.r = Rm(c, o, t + 1 / 3), this.g = Rm(c, o, t), this.b = Rm(c, o, t - 1 / 3);
    }
    return Be.colorSpaceToWorking(this, a), 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](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 = Xi) {
    function s(o) {
      o !== void 0 && parseFloat(o) < 1 && de("Color: Alpha component of " + t + " will be ignored.");
    }
    let a;
    if (a = /^(\w+)\(([^\)]*)\)/.exec(t)) {
      let o;
      const c = a[1], u = a[2];
      switch (c) {
        case "rgb":
        case "rgba":
          if (o = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))
            return s(o[4]), this.setRGB(
              Math.min(255, parseInt(o[1], 10)) / 255,
              Math.min(255, parseInt(o[2], 10)) / 255,
              Math.min(255, parseInt(o[3], 10)) / 255,
              e
            );
          if (o = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))
            return s(o[4]), this.setRGB(
              Math.min(100, parseInt(o[1], 10)) / 100,
              Math.min(100, parseInt(o[2], 10)) / 100,
              Math.min(100, parseInt(o[3], 10)) / 100,
              e
            );
          break;
        case "hsl":
        case "hsla":
          if (o = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))
            return s(o[4]), this.setHSL(
              parseFloat(o[1]) / 360,
              parseFloat(o[2]) / 100,
              parseFloat(o[3]) / 100,
              e
            );
          break;
        default:
          de("Color: Unknown color model " + t);
      }
    } else if (a = /^\#([A-Fa-f\d]+)$/.exec(t)) {
      const o = a[1], c = o.length;
      if (c === 3)
        return this.setRGB(
          parseInt(o.charAt(0), 16) / 15,
          parseInt(o.charAt(1), 16) / 15,
          parseInt(o.charAt(2), 16) / 15,
          e
        );
      if (c === 6)
        return this.setHex(parseInt(o, 16), e);
      de("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 = Xi) {
    const s = RM[t.toLowerCase()];
    return s !== void 0 ? this.setHex(s, e) : de("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 = fr(t.r), this.g = fr(t.g), this.b = fr(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 = ll(t.r), this.g = ll(t.g), this.b = ll(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 = Xi) {
    return Be.workingToColorSpace(Kn.copy(this), t), Math.round(ge(Kn.r * 255, 0, 255)) * 65536 + Math.round(ge(Kn.g * 255, 0, 255)) * 256 + Math.round(ge(Kn.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 = Xi) {
    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 = Be.workingColorSpace) {
    Be.workingToColorSpace(Kn.copy(this), e);
    const s = Kn.r, a = Kn.g, o = Kn.b, c = Math.max(s, a, o), u = Math.min(s, a, o);
    let d, h;
    const m = (u + c) / 2;
    if (u === c)
      d = 0, h = 0;
    else {
      const p = c - u;
      switch (h = m <= 0.5 ? p / (c + u) : p / (2 - c - u), c) {
        case s:
          d = (a - o) / p + (a < o ? 6 : 0);
          break;
        case a:
          d = (o - s) / p + 2;
          break;
        case o:
          d = (s - a) / p + 4;
          break;
      }
      d /= 6;
    }
    return t.h = d, t.s = h, t.l = m, 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 = Be.workingColorSpace) {
    return Be.workingToColorSpace(Kn.copy(this), e), t.r = Kn.r, t.g = Kn.g, t.b = Kn.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 = Xi) {
    Be.workingToColorSpace(Kn.copy(this), t);
    const e = Kn.r, s = Kn.g, a = Kn.b;
    return t !== Xi ? `color(${t} ${e.toFixed(3)} ${s.toFixed(3)} ${a.toFixed(3)})` : `rgb(${Math.round(e * 255)},${Math.round(s * 255)},${Math.round(a * 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, s) {
    return this.getHSL(Wr), this.setHSL(Wr.h + t, Wr.s + e, Wr.l + s);
  }
  /**
   * 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, s) {
    return this.r = t.r + (e.r - t.r) * s, this.g = t.g + (e.g - t.g) * s, this.b = t.b + (e.b - t.b) * s, 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(Wr), t.getHSL(bf);
    const s = Pc(Wr.h, bf.h, e), a = Pc(Wr.s, bf.s, e), o = Pc(Wr.l, bf.l, e);
    return this.setHSL(s, a, o), 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, s = this.g, a = this.b, o = t.elements;
    return this.r = o[0] * e + o[3] * s + o[6] * a, this.g = o[1] * e + o[4] * s + o[7] * a, this.b = o[2] * e + o[5] * s + o[8] * a, 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 Kn = /* @__PURE__ */ new we();
we.NAMES = RM;
class DM extends Tn {
  /**
   * 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 Rs(), this.environmentIntensity = 1, this.environmentRotation = new Rs(), 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;
  }
}
const Qi = /* @__PURE__ */ new st(), Js = /* @__PURE__ */ new st(), Dm = /* @__PURE__ */ new st(), tr = /* @__PURE__ */ new st(), zo = /* @__PURE__ */ new st(), Fo = /* @__PURE__ */ new st(), OS = /* @__PURE__ */ new st(), Nm = /* @__PURE__ */ new st(), Om = /* @__PURE__ */ new st(), Lm = /* @__PURE__ */ new st(), Um = /* @__PURE__ */ new Je(), Pm = /* @__PURE__ */ new Je(), Im = /* @__PURE__ */ new Je();
class Wi {
  /**
   * 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 st(), e = new st(), s = new st()) {
    this.a = t, this.b = e, this.c = s;
  }
  /**
   * 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, s, a) {
    a.subVectors(s, e), Qi.subVectors(t, e), a.cross(Qi);
    const o = a.lengthSq();
    return o > 0 ? a.multiplyScalar(1 / Math.sqrt(o)) : a.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, s, a, o) {
    Qi.subVectors(a, e), Js.subVectors(s, e), Dm.subVectors(t, e);
    const c = Qi.dot(Qi), u = Qi.dot(Js), d = Qi.dot(Dm), h = Js.dot(Js), m = Js.dot(Dm), p = c * h - u * u;
    if (p === 0)
      return o.set(0, 0, 0), null;
    const g = 1 / p, _ = (h * d - u * m) * g, x = (c * m - u * d) * g;
    return o.set(1 - _ - x, x, _);
  }
  /**
   * 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, s, a) {
    return this.getBarycoord(t, e, s, a, tr) === null ? !1 : tr.x >= 0 && tr.y >= 0 && tr.x + tr.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, s, a, o, c, u, d) {
    return this.getBarycoord(t, e, s, a, tr) === null ? (d.x = 0, d.y = 0, "z" in d && (d.z = 0), "w" in d && (d.w = 0), null) : (d.setScalar(0), d.addScaledVector(o, tr.x), d.addScaledVector(c, tr.y), d.addScaledVector(u, tr.z), d);
  }
  /**
   * 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, s, a, o, c) {
    return Um.setScalar(0), Pm.setScalar(0), Im.setScalar(0), Um.fromBufferAttribute(t, e), Pm.fromBufferAttribute(t, s), Im.fromBufferAttribute(t, a), c.setScalar(0), c.addScaledVector(Um, o.x), c.addScaledVector(Pm, o.y), c.addScaledVector(Im, o.z), c;
  }
  /**
   * 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, s, a) {
    return Qi.subVectors(s, e), Js.subVectors(t, e), Qi.cross(Js).dot(a) < 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, s) {
    return this.a.copy(t), this.b.copy(e), this.c.copy(s), 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, s, a) {
    return this.a.copy(t[e]), this.b.copy(t[s]), this.c.copy(t[a]), 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, s, a) {
    return this.a.fromBufferAttribute(t, e), this.b.fromBufferAttribute(t, s), this.c.fromBufferAttribute(t, a), 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 Qi.subVectors(this.c, this.b), Js.subVectors(this.a, this.b), Qi.cross(Js).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 Wi.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 Wi.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, s, a, o) {
    return Wi.getInterpolation(t, this.a, this.b, this.c, e, s, a, o);
  }
  /**
   * 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 Wi.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 Wi.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 s = this.a, a = this.b, o = this.c;
    let c, u;
    zo.subVectors(a, s), Fo.subVectors(o, s), Nm.subVectors(t, s);
    const d = zo.dot(Nm), h = Fo.dot(Nm);
    if (d <= 0 && h <= 0)
      return e.copy(s);
    Om.subVectors(t, a);
    const m = zo.dot(Om), p = Fo.dot(Om);
    if (m >= 0 && p <= m)
      return e.copy(a);
    const g = d * p - m * h;
    if (g <= 0 && d >= 0 && m <= 0)
      return c = d / (d - m), e.copy(s).addScaledVector(zo, c);
    Lm.subVectors(t, o);
    const _ = zo.dot(Lm), x = Fo.dot(Lm);
    if (x >= 0 && _ <= x)
      return e.copy(o);
    const A = _ * h - d * x;
    if (A <= 0 && h >= 0 && x <= 0)
      return u = h / (h - x), e.copy(s).addScaledVector(Fo, u);
    const b = m * x - _ * p;
    if (b <= 0 && p - m >= 0 && _ - x >= 0)
      return OS.subVectors(o, a), u = (p - m) / (p - m + (_ - x)), e.copy(a).addScaledVector(OS, u);
    const y = 1 / (b + A + g);
    return c = A * y, u = g * y, e.copy(s).addScaledVector(zo, c).addScaledVector(Fo, u);
  }
  /**
   * 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);
  }
}
class Ns {
  /**
   * 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 st(1 / 0, 1 / 0, 1 / 0), e = new st(-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, s = t.length; e < s; e += 3)
      this.expandByPoint(Ji.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, s = t.count; e < s; e++)
      this.expandByPoint(Ji.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, s = t.length; e < s; 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 s = Ji.copy(e).multiplyScalar(0.5);
    return this.min.copy(t).sub(s), this.max.copy(t).add(s), 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 s = t.geometry;
    if (s !== void 0) {
      const o = s.getAttribute("position");
      if (e === !0 && o !== void 0 && t.isInstancedMesh !== !0)
        for (let c = 0, u = o.count; c < u; c++)
          t.isMesh === !0 ? t.getVertexPosition(c, Ji) : Ji.fromBufferAttribute(o, c), Ji.applyMatrix4(t.matrixWorld), this.expandByPoint(Ji);
      else
        t.boundingBox !== void 0 ? (t.boundingBox === null && t.computeBoundingBox(), Mf.copy(t.boundingBox)) : (s.boundingBox === null && s.computeBoundingBox(), Mf.copy(s.boundingBox)), Mf.applyMatrix4(t.matrixWorld), this.union(Mf);
    }
    const a = t.children;
    for (let o = 0, c = a.length; o < c; o++)
      this.expandByObject(a[o], 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, Ji), Ji.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, s;
    return t.normal.x > 0 ? (e = t.normal.x * this.min.x, s = t.normal.x * this.max.x) : (e = t.normal.x * this.max.x, s = t.normal.x * this.min.x), t.normal.y > 0 ? (e += t.normal.y * this.min.y, s += t.normal.y * this.max.y) : (e += t.normal.y * this.max.y, s += t.normal.y * this.min.y), t.normal.z > 0 ? (e += t.normal.z * this.min.z, s += t.normal.z * this.max.z) : (e += t.normal.z * this.max.z, s += t.normal.z * this.min.z), e <= -t.constant && s >= -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(pc), Ef.subVectors(this.max, pc), Ho.subVectors(t.a, pc), Vo.subVectors(t.b, pc), Go.subVectors(t.c, pc), Yr.subVectors(Vo, Ho), jr.subVectors(Go, Vo), Aa.subVectors(Ho, Go);
    let e = [
      0,
      -Yr.z,
      Yr.y,
      0,
      -jr.z,
      jr.y,
      0,
      -Aa.z,
      Aa.y,
      Yr.z,
      0,
      -Yr.x,
      jr.z,
      0,
      -jr.x,
      Aa.z,
      0,
      -Aa.x,
      -Yr.y,
      Yr.x,
      0,
      -jr.y,
      jr.x,
      0,
      -Aa.y,
      Aa.x,
      0
    ];
    return !Bm(e, Ho, Vo, Go, Ef) || (e = [1, 0, 0, 0, 1, 0, 0, 0, 1], !Bm(e, Ho, Vo, Go, Ef)) ? !1 : (wf.crossVectors(Yr, jr), e = [wf.x, wf.y, wf.z], Bm(e, Ho, Vo, Go, Ef));
  }
  /**
   * 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, Ji).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(Ji).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 : (er[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(t), er[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(t), er[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(t), er[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(t), er[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(t), er[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(t), er[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(t), er[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(t), this.setFromPoints(er), 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 er = [
  /* @__PURE__ */ new st(),
  /* @__PURE__ */ new st(),
  /* @__PURE__ */ new st(),
  /* @__PURE__ */ new st(),
  /* @__PURE__ */ new st(),
  /* @__PURE__ */ new st(),
  /* @__PURE__ */ new st(),
  /* @__PURE__ */ new st()
], Ji = /* @__PURE__ */ new st(), Mf = /* @__PURE__ */ new Ns(), Ho = /* @__PURE__ */ new st(), Vo = /* @__PURE__ */ new st(), Go = /* @__PURE__ */ new st(), Yr = /* @__PURE__ */ new st(), jr = /* @__PURE__ */ new st(), Aa = /* @__PURE__ */ new st(), pc = /* @__PURE__ */ new st(), Ef = /* @__PURE__ */ new st(), wf = /* @__PURE__ */ new st(), Ta = /* @__PURE__ */ new st();
function Bm(n, t, e, s, a) {
  for (let o = 0, c = n.length - 3; o <= c; o += 3) {
    Ta.fromArray(n, o);
    const u = a.x * Math.abs(Ta.x) + a.y * Math.abs(Ta.y) + a.z * Math.abs(Ta.z), d = t.dot(Ta), h = e.dot(Ta), m = s.dot(Ta);
    if (Math.max(-Math.max(d, h, m), Math.min(d, h, m)) > u)
      return !1;
  }
  return !0;
}
const wn = /* @__PURE__ */ new st(), Af = /* @__PURE__ */ new ae();
let M3 = 0;
class dn {
  /**
   * 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, s = !1) {
    if (Array.isArray(t))
      throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
    this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: M3++ }), this.name = "", this.array = t, this.itemSize = e, this.count = t !== void 0 ? t.length / e : 0, this.normalized = s, this.usage = za, this.updateRanges = [], this.gpuType = Di, 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, s) {
    t *= this.itemSize, s *= e.itemSize;
    for (let a = 0, o = this.itemSize; a < o; a++)
      this.array[t + a] = e.array[s + a];
    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, s = this.count; e < s; e++)
        Af.fromBufferAttribute(this, e), Af.applyMatrix3(t), this.setXY(e, Af.x, Af.y);
    else if (this.itemSize === 3)
      for (let e = 0, s = this.count; e < s; e++)
        wn.fromBufferAttribute(this, e), wn.applyMatrix3(t), this.setXYZ(e, wn.x, wn.y, wn.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, s = this.count; e < s; e++)
      wn.fromBufferAttribute(this, e), wn.applyMatrix4(t), this.setXYZ(e, wn.x, wn.y, wn.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, s = this.count; e < s; e++)
      wn.fromBufferAttribute(this, e), wn.applyNormalMatrix(t), this.setXYZ(e, wn.x, wn.y, wn.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, s = this.count; e < s; e++)
      wn.fromBufferAttribute(this, e), wn.transformDirection(t), this.setXYZ(e, wn.x, wn.y, wn.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 s = this.array[t * this.itemSize + e];
    return this.normalized && (s = es(s, this.array)), s;
  }
  /**
   * 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, s) {
    return this.normalized && (s = Ye(s, this.array)), this.array[t * this.itemSize + e] = s, 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 = es(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 = Ye(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 = es(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 = Ye(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 = es(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 = Ye(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 = es(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 = Ye(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, s) {
    return t *= this.itemSize, this.normalized && (e = Ye(e, this.array), s = Ye(s, this.array)), this.array[t + 0] = e, this.array[t + 1] = s, 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, s, a) {
    return t *= this.itemSize, this.normalized && (e = Ye(e, this.array), s = Ye(s, this.array), a = Ye(a, this.array)), this.array[t + 0] = e, this.array[t + 1] = s, this.array[t + 2] = a, 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, s, a, o) {
    return t *= this.itemSize, this.normalized && (e = Ye(e, this.array), s = Ye(s, this.array), a = Ye(a, this.array), o = Ye(o, this.array)), this.array[t + 0] = e, this.array[t + 1] = s, this.array[t + 2] = a, this.array[t + 3] = o, 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 !== za && (t.usage = this.usage), t;
  }
}
class NM extends dn {
  /**
   * 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, s) {
    super(new Uint16Array(t), e, s);
  }
}
class OM extends dn {
  /**
   * 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, s) {
    super(new Uint32Array(t), e, s);
  }
}
class _n extends dn {
  /**
   * 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, s) {
    super(new Float32Array(t), e, s);
  }
}
const E3 = /* @__PURE__ */ new Ns(), mc = /* @__PURE__ */ new st(), zm = /* @__PURE__ */ new st();
class aa {
  /**
   * 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 st(), 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 s = this.center;
    e !== void 0 ? s.copy(e) : E3.setFromPoints(t).getCenter(s);
    let a = 0;
    for (let o = 0, c = t.length; o < c; o++)
      a = Math.max(a, s.distanceToSquared(t[o]));
    return this.radius = Math.sqrt(a), 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 s = this.center.distanceToSquared(t);
    return e.copy(t), s > 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;
    mc.subVectors(t, this.center);
    const e = mc.lengthSq();
    if (e > this.radius * this.radius) {
      const s = Math.sqrt(e), a = (s - this.radius) * 0.5;
      this.center.addScaledVector(mc, a / s), this.radius += a;
    }
    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) : (zm.subVectors(t.center, this.center).setLength(t.radius), this.expandByPoint(mc.copy(t.center).add(zm)), this.expandByPoint(mc.copy(t.center).sub(zm))), 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 {Sphere} A reference to this bounding sphere.
   */
  fromJSON(t) {
    return this.radius = t.radius, this.center.fromArray(t.center), this;
  }
}
let w3 = 0;
const ki = /* @__PURE__ */ new je(), Fm = /* @__PURE__ */ new Tn(), ko = /* @__PURE__ */ new st(), Ai = /* @__PURE__ */ new Ns(), gc = /* @__PURE__ */ new Ns(), zn = /* @__PURE__ */ new st();
class In extends qa {
  /**
   * Constructs a new geometry.
   */
  constructor() {
    super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: w3++ }), this.uuid = ur(), this.name = "", this.type = "BufferGeometry", this.index = null, this.indirect = null, this.indirectOffset = 0, 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 (X2(t) ? OM : NM)(t, 1) : this.index = t, this;
  }
  /**
   * Sets the given indirect attribute to this geometry.
   *
   * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
   * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
   * @return {BufferGeometry} A reference to this instance.
   */
  setIndirect(t, e = 0) {
    return this.indirect = t, this.indirectOffset = e, 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, s = 0) {
    this.groups.push({
      start: t,
      count: e,
      materialIndex: s
    });
  }
  /**
   * 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 s = this.attributes.normal;
    if (s !== void 0) {
      const o = new Me().getNormalMatrix(t);
      s.applyNormalMatrix(o), s.needsUpdate = !0;
    }
    const a = this.attributes.tangent;
    return a !== void 0 && (a.transformDirection(t), a.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 ki.makeRotationFromQuaternion(t), this.applyMatrix4(ki), 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 ki.makeRotationX(t), this.applyMatrix4(ki), 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 ki.makeRotationY(t), this.applyMatrix4(ki), 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 ki.makeRotationZ(t), this.applyMatrix4(ki), 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, s) {
    return ki.makeTranslation(t, e, s), this.applyMatrix4(ki), 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, s) {
    return ki.makeScale(t, e, s), this.applyMatrix4(ki), 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 Fm.lookAt(t), Fm.updateMatrix(), this.applyMatrix4(Fm.matrix), this;
  }
  /**
   * Center the geometry based on its bounding box.
   *
   * @return {BufferGeometry} A reference to this instance.
   */
  center() {
    return this.computeBoundingBox(), this.boundingBox.getCenter(ko).negate(), this.translate(ko.x, ko.y, ko.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 s = [];
      for (let a = 0, o = t.length; a < o; a++) {
        const c = t[a];
        s.push(c.x, c.y, c.z || 0);
      }
      this.setAttribute("position", new _n(s, 3));
    } else {
      const s = Math.min(t.length, e.count);
      for (let a = 0; a < s; a++) {
        const o = t[a];
        e.setXYZ(a, o.x, o.y, o.z || 0);
      }
      t.length > e.count && de("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 Ns());
    const t = this.attributes.position, e = this.morphAttributes.position;
    if (t && t.isGLBufferAttribute) {
      Ie("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this), this.boundingBox.set(
        new st(-1 / 0, -1 / 0, -1 / 0),
        new st(1 / 0, 1 / 0, 1 / 0)
      );
      return;
    }
    if (t !== void 0) {
      if (this.boundingBox.setFromBufferAttribute(t), e)
        for (let s = 0, a = e.length; s < a; s++) {
          const o = e[s];
          Ai.setFromBufferAttribute(o), this.morphTargetsRelative ? (zn.addVectors(this.boundingBox.min, Ai.min), this.boundingBox.expandByPoint(zn), zn.addVectors(this.boundingBox.max, Ai.max), this.boundingBox.expandByPoint(zn)) : (this.boundingBox.expandByPoint(Ai.min), this.boundingBox.expandByPoint(Ai.max));
        }
    } else
      this.boundingBox.makeEmpty();
    (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) && Ie('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 aa());
    const t = this.attributes.position, e = this.morphAttributes.position;
    if (t && t.isGLBufferAttribute) {
      Ie("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this), this.boundingSphere.set(new st(), 1 / 0);
      return;
    }
    if (t) {
      const s = this.boundingSphere.center;
      if (Ai.setFromBufferAttribute(t), e)
        for (let o = 0, c = e.length; o < c; o++) {
          const u = e[o];
          gc.setFromBufferAttribute(u), this.morphTargetsRelative ? (zn.addVectors(Ai.min, gc.min), Ai.expandByPoint(zn), zn.addVectors(Ai.max, gc.max), Ai.expandByPoint(zn)) : (Ai.expandByPoint(gc.min), Ai.expandByPoint(gc.max));
        }
      Ai.getCenter(s);
      let a = 0;
      for (let o = 0, c = t.count; o < c; o++)
        zn.fromBufferAttribute(t, o), a = Math.max(a, s.distanceToSquared(zn));
      if (e)
        for (let o = 0, c = e.length; o < c; o++) {
          const u = e[o], d = this.morphTargetsRelative;
          for (let h = 0, m = u.count; h < m; h++)
            zn.fromBufferAttribute(u, h), d && (ko.fromBufferAttribute(t, h), zn.add(ko)), a = Math.max(a, s.distanceToSquared(zn));
        }
      this.boundingSphere.radius = Math.sqrt(a), isNaN(this.boundingSphere.radius) && Ie('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) {
      Ie("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");
      return;
    }
    const s = e.position, a = e.normal, o = e.uv;
    this.hasAttribute("tangent") === !1 && this.setAttribute("tangent", new dn(new Float32Array(4 * s.count), 4));
    const c = this.getAttribute("tangent"), u = [], d = [];
    for (let T = 0; T < s.count; T++)
      u[T] = new st(), d[T] = new st();
    const h = new st(), m = new st(), p = new st(), g = new ae(), _ = new ae(), x = new ae(), A = new st(), b = new st();
    function y(T, L, z) {
      h.fromBufferAttribute(s, T), m.fromBufferAttribute(s, L), p.fromBufferAttribute(s, z), g.fromBufferAttribute(o, T), _.fromBufferAttribute(o, L), x.fromBufferAttribute(o, z), m.sub(h), p.sub(h), _.sub(g), x.sub(g);
      const R = 1 / (_.x * x.y - x.x * _.y);
      isFinite(R) && (A.copy(m).multiplyScalar(x.y).addScaledVector(p, -_.y).multiplyScalar(R), b.copy(p).multiplyScalar(_.x).addScaledVector(m, -x.x).multiplyScalar(R), u[T].add(A), u[L].add(A), u[z].add(A), d[T].add(b), d[L].add(b), d[z].add(b));
    }
    let E = this.groups;
    E.length === 0 && (E = [{
      start: 0,
      count: t.count
    }]);
    for (let T = 0, L = E.length; T < L; ++T) {
      const z = E[T], R = z.start, B = z.count;
      for (let H = R, U = R + B; H < U; H += 3)
        y(
          t.getX(H + 0),
          t.getX(H + 1),
          t.getX(H + 2)
        );
    }
    const w = new st(), M = new st(), O = new st(), C = new st();
    function D(T) {
      O.fromBufferAttribute(a, T), C.copy(O);
      const L = u[T];
      w.copy(L), w.sub(O.multiplyScalar(O.dot(L))).normalize(), M.crossVectors(C, L);
      const R = M.dot(d[T]) < 0 ? -1 : 1;
      c.setXYZW(T, w.x, w.y, w.z, R);
    }
    for (let T = 0, L = E.length; T < L; ++T) {
      const z = E[T], R = z.start, B = z.count;
      for (let H = R, U = R + B; H < U; H += 3)
        D(t.getX(H + 0)), D(t.getX(H + 1)), D(t.getX(H + 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 s = this.getAttribute("normal");
      if (s === void 0)
        s = new dn(new Float32Array(e.count * 3), 3), this.setAttribute("normal", s);
      else
        for (let g = 0, _ = s.count; g < _; g++)
          s.setXYZ(g, 0, 0, 0);
      const a = new st(), o = new st(), c = new st(), u = new st(), d = new st(), h = new st(), m = new st(), p = new st();
      if (t)
        for (let g = 0, _ = t.count; g < _; g += 3) {
          const x = t.getX(g + 0), A = t.getX(g + 1), b = t.getX(g + 2);
          a.fromBufferAttribute(e, x), o.fromBufferAttribute(e, A), c.fromBufferAttribute(e, b), m.subVectors(c, o), p.subVectors(a, o), m.cross(p), u.fromBufferAttribute(s, x), d.fromBufferAttribute(s, A), h.fromBufferAttribute(s, b), u.add(m), d.add(m), h.add(m), s.setXYZ(x, u.x, u.y, u.z), s.setXYZ(A, d.x, d.y, d.z), s.setXYZ(b, h.x, h.y, h.z);
        }
      else
        for (let g = 0, _ = e.count; g < _; g += 3)
          a.fromBufferAttribute(e, g + 0), o.fromBufferAttribute(e, g + 1), c.fromBufferAttribute(e, g + 2), m.subVectors(c, o), p.subVectors(a, o), m.cross(p), s.setXYZ(g + 0, m.x, m.y, m.z), s.setXYZ(g + 1, m.x, m.y, m.z), s.setXYZ(g + 2, m.x, m.y, m.z);
      this.normalizeNormals(), s.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, s = t.count; e < s; e++)
      zn.fromBufferAttribute(t, e), zn.normalize(), t.setXYZ(e, zn.x, zn.y, zn.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(u, d) {
      const h = u.array, m = u.itemSize, p = u.normalized, g = new h.constructor(d.length * m);
      let _ = 0, x = 0;
      for (let A = 0, b = d.length; A < b; A++) {
        u.isInterleavedBufferAttribute ? _ = d[A] * u.data.stride + u.offset : _ = d[A] * m;
        for (let y = 0; y < m; y++)
          g[x++] = h[_++];
      }
      return new dn(g, m, p);
    }
    if (this.index === null)
      return de("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."), this;
    const e = new In(), s = this.index.array, a = this.attributes;
    for (const u in a) {
      const d = a[u], h = t(d, s);
      e.setAttribute(u, h);
    }
    const o = this.morphAttributes;
    for (const u in o) {
      const d = [], h = o[u];
      for (let m = 0, p = h.length; m < p; m++) {
        const g = h[m], _ = t(g, s);
        d.push(_);
      }
      e.morphAttributes[u] = d;
    }
    e.morphTargetsRelative = this.morphTargetsRelative;
    const c = this.groups;
    for (let u = 0, d = c.length; u < d; u++) {
      const h = c[u];
      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 d = this.parameters;
      for (const h in d)
        d[h] !== void 0 && (t[h] = d[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 s = this.attributes;
    for (const d in s) {
      const h = s[d];
      t.data.attributes[d] = h.toJSON(t.data);
    }
    const a = {};
    let o = !1;
    for (const d in this.morphAttributes) {
      const h = this.morphAttributes[d], m = [];
      for (let p = 0, g = h.length; p < g; p++) {
        const _ = h[p];
        m.push(_.toJSON(t.data));
      }
      m.length > 0 && (a[d] = m, o = !0);
    }
    o && (t.data.morphAttributes = a, t.data.morphTargetsRelative = this.morphTargetsRelative);
    const c = this.groups;
    c.length > 0 && (t.data.groups = JSON.parse(JSON.stringify(c)));
    const u = this.boundingSphere;
    return u !== null && (t.data.boundingSphere = u.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 s = t.index;
    s !== null && this.setIndex(s.clone());
    const a = t.attributes;
    for (const h in a) {
      const m = a[h];
      this.setAttribute(h, m.clone(e));
    }
    const o = t.morphAttributes;
    for (const h in o) {
      const m = [], p = o[h];
      for (let g = 0, _ = p.length; g < _; g++)
        m.push(p[g].clone(e));
      this.morphAttributes[h] = m;
    }
    this.morphTargetsRelative = t.morphTargetsRelative;
    const c = t.groups;
    for (let h = 0, m = c.length; h < m; h++) {
      const p = c[h];
      this.addGroup(p.start, p.count, p.materialIndex);
    }
    const u = t.boundingBox;
    u !== null && (this.boundingBox = u.clone());
    const d = t.boundingSphere;
    return d !== null && (this.boundingSphere = d.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" });
  }
}
class LM {
  /**
   * 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 = za, this.updateRanges = [], this.version = 0, this.uuid = ur();
  }
  /**
   * 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, s) {
    t *= this.stride, s *= e.stride;
    for (let a = 0, o = this.stride; a < o; a++)
      this.array[t + a] = e.array[s + a];
    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 = ur()), 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]), s = new this.constructor(e, this.stride);
    return s.setUsage(this.usage), s;
  }
  /**
   * 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 = ur()), 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 ii = /* @__PURE__ */ new st();
class Es {
  /**
   * 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, s, a = !1) {
    this.isInterleavedBufferAttribute = !0, this.name = "", this.data = t, this.itemSize = e, this.offset = s, this.normalized = a;
  }
  /**
   * 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, s = this.data.count; e < s; e++)
      ii.fromBufferAttribute(this, e), ii.applyMatrix4(t), this.setXYZ(e, ii.x, ii.y, ii.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, s = this.count; e < s; e++)
      ii.fromBufferAttribute(this, e), ii.applyNormalMatrix(t), this.setXYZ(e, ii.x, ii.y, ii.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, s = this.count; e < s; e++)
      ii.fromBufferAttribute(this, e), ii.transformDirection(t), this.setXYZ(e, ii.x, ii.y, ii.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 s = this.array[t * this.data.stride + this.offset + e];
    return this.normalized && (s = es(s, this.array)), s;
  }
  /**
   * 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, s) {
    return this.normalized && (s = Ye(s, this.array)), this.data.array[t * this.data.stride + this.offset + e] = s, 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 = Ye(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 = Ye(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 = Ye(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 = Ye(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 = es(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 = es(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 = es(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 = es(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, s) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = Ye(e, this.array), s = Ye(s, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = s, 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, s, a) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = Ye(e, this.array), s = Ye(s, this.array), a = Ye(a, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = s, this.data.array[t + 2] = a, 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, s, a, o) {
    return t = t * this.data.stride + this.offset, this.normalized && (e = Ye(e, this.array), s = Ye(s, this.array), a = Ye(a, this.array), o = Ye(o, this.array)), this.data.array[t + 0] = e, this.data.array[t + 1] = s, this.data.array[t + 2] = a, this.data.array[t + 3] = o, 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) {
      Ad("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");
      const e = [];
      for (let s = 0; s < this.count; s++) {
        const a = s * this.data.stride + this.offset;
        for (let o = 0; o < this.itemSize; o++)
          e.push(this.data.array[a + o]);
      }
      return new dn(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 Es(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) {
      Ad("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");
      const e = [];
      for (let s = 0; s < this.count; s++) {
        const a = s * this.data.stride + this.offset;
        for (let o = 0; o < this.itemSize; o++)
          e.push(this.data.array[a + o]);
      }
      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
      };
  }
}
let A3 = 0;
class Za extends qa {
  /**
   * Constructs a new material.
   */
  constructor() {
    super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: A3++ }), this.uuid = ur(), this.name = "", this.type = "Material", this.blending = ol, this.side = ra, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = Ag, this.blendDst = Tg, this.blendEquation = Ua, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new we(0, 0, 0), this.blendAlpha = 0, this.depthFunc = fl, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = yS, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = Oo, this.stencilZFail = Oo, this.stencilZPass = Oo, 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](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 s = t[e];
        if (s === void 0) {
          de(`Material: parameter '${e}' has value of undefined.`);
          continue;
        }
        const a = this[e];
        if (a === void 0) {
          de(`Material: '${e}' is not a property of THREE.${this.type}.`);
          continue;
        }
        a && a.isColor ? a.set(s) : a && a.isVector3 && s && s.isVector3 ? a.copy(s) : this[e] = s;
      }
  }
  /**
   * 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 s = {
      metadata: {
        version: 4.7,
        type: "Material",
        generator: "Material.toJSON"
      }
    };
    s.uuid = this.uuid, s.type = this.type, this.name !== "" && (s.name = this.name), this.color && this.color.isColor && (s.color = this.color.getHex()), this.roughness !== void 0 && (s.roughness = this.roughness), this.metalness !== void 0 && (s.metalness = this.metalness), this.sheen !== void 0 && (s.sheen = this.sheen), this.sheenColor && this.sheenColor.isColor && (s.sheenColor = this.sheenColor.getHex()), this.sheenRoughness !== void 0 && (s.sheenRoughness = this.sheenRoughness), this.emissive && this.emissive.isColor && (s.emissive = this.emissive.getHex()), this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1 && (s.emissiveIntensity = this.emissiveIntensity), this.specular && this.specular.isColor && (s.specular = this.specular.getHex()), this.specularIntensity !== void 0 && (s.specularIntensity = this.specularIntensity), this.specularColor && this.specularColor.isColor && (s.specularColor = this.specularColor.getHex()), this.shininess !== void 0 && (s.shininess = this.shininess), this.clearcoat !== void 0 && (s.clearcoat = this.clearcoat), this.clearcoatRoughness !== void 0 && (s.clearcoatRoughness = this.clearcoatRoughness), this.clearcoatMap && this.clearcoatMap.isTexture && (s.clearcoatMap = this.clearcoatMap.toJSON(t).uuid), this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture && (s.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(t).uuid), this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture && (s.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(t).uuid, s.clearcoatNormalScale = this.clearcoatNormalScale.toArray()), this.sheenColorMap && this.sheenColorMap.isTexture && (s.sheenColorMap = this.sheenColorMap.toJSON(t).uuid), this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture && (s.sheenRoughnessMap = this.sheenRoughnessMap.toJSON(t).uuid), this.dispersion !== void 0 && (s.dispersion = this.dispersion), this.iridescence !== void 0 && (s.iridescence = this.iridescence), this.iridescenceIOR !== void 0 && (s.iridescenceIOR = this.iridescenceIOR), this.iridescenceThicknessRange !== void 0 && (s.iridescenceThicknessRange = this.iridescenceThicknessRange), this.iridescenceMap && this.iridescenceMap.isTexture && (s.iridescenceMap = this.iridescenceMap.toJSON(t).uuid), this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture && (s.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(t).uuid), this.anisotropy !== void 0 && (s.anisotropy = this.anisotropy), this.anisotropyRotation !== void 0 && (s.anisotropyRotation = this.anisotropyRotation), this.anisotropyMap && this.anisotropyMap.isTexture && (s.anisotropyMap = this.anisotropyMap.toJSON(t).uuid), this.map && this.map.isTexture && (s.map = this.map.toJSON(t).uuid), this.matcap && this.matcap.isTexture && (s.matcap = this.matcap.toJSON(t).uuid), this.alphaMap && this.alphaMap.isTexture && (s.alphaMap = this.alphaMap.toJSON(t).uuid), this.lightMap && this.lightMap.isTexture && (s.lightMap = this.lightMap.toJSON(t).uuid, s.lightMapIntensity = this.lightMapIntensity), this.aoMap && this.aoMap.isTexture && (s.aoMap = this.aoMap.toJSON(t).uuid, s.aoMapIntensity = this.aoMapIntensity), this.bumpMap && this.bumpMap.isTexture && (s.bumpMap = this.bumpMap.toJSON(t).uuid, s.bumpScale = this.bumpScale), this.normalMap && this.normalMap.isTexture && (s.normalMap = this.normalMap.toJSON(t).uuid, s.normalMapType = this.normalMapType, s.normalScale = this.normalScale.toArray()), this.displacementMap && this.displacementMap.isTexture && (s.displacementMap = this.displacementMap.toJSON(t).uuid, s.displacementScale = this.displacementScale, s.displacementBias = this.displacementBias), this.roughnessMap && this.roughnessMap.isTexture && (s.roughnessMap = this.roughnessMap.toJSON(t).uuid), this.metalnessMap && this.metalnessMap.isTexture && (s.metalnessMap = this.metalnessMap.toJSON(t).uuid), this.emissiveMap && this.emissiveMap.isTexture && (s.emissiveMap = this.emissiveMap.toJSON(t).uuid), this.specularMap && this.specularMap.isTexture && (s.specularMap = this.specularMap.toJSON(t).uuid), this.specularIntensityMap && this.specularIntensityMap.isTexture && (s.specularIntensityMap = this.specularIntensityMap.toJSON(t).uuid), this.specularColorMap && this.specularColorMap.isTexture && (s.specularColorMap = this.specularColorMap.toJSON(t).uuid), this.envMap && this.envMap.isTexture && (s.envMap = this.envMap.toJSON(t).uuid, this.combine !== void 0 && (s.combine = this.combine)), this.envMapRotation !== void 0 && (s.envMapRotation = this.envMapRotation.toArray()), this.envMapIntensity !== void 0 && (s.envMapIntensity = this.envMapIntensity), this.reflectivity !== void 0 && (s.reflectivity = this.reflectivity), this.refractionRatio !== void 0 && (s.refractionRatio = this.refractionRatio), this.gradientMap && this.gradientMap.isTexture && (s.gradientMap = this.gradientMap.toJSON(t).uuid), this.transmission !== void 0 && (s.transmission = this.transmission), this.transmissionMap && this.transmissionMap.isTexture && (s.transmissionMap = this.transmissionMap.toJSON(t).uuid), this.thickness !== void 0 && (s.thickness = this.thickness), this.thicknessMap && this.thicknessMap.isTexture && (s.thicknessMap = this.thicknessMap.toJSON(t).uuid), this.attenuationDistance !== void 0 && this.attenuationDistance !== 1 / 0 && (s.attenuationDistance = this.attenuationDistance), this.attenuationColor !== void 0 && (s.attenuationColor = this.attenuationColor.getHex()), this.size !== void 0 && (s.size = this.size), this.shadowSide !== null && (s.shadowSide = this.shadowSide), this.sizeAttenuation !== void 0 && (s.sizeAttenuation = this.sizeAttenuation), this.blending !== ol && (s.blending = this.blending), this.side !== ra && (s.side = this.side), this.vertexColors === !0 && (s.vertexColors = !0), this.opacity < 1 && (s.opacity = this.opacity), this.transparent === !0 && (s.transparent = !0), this.blendSrc !== Ag && (s.blendSrc = this.blendSrc), this.blendDst !== Tg && (s.blendDst = this.blendDst), this.blendEquation !== Ua && (s.blendEquation = this.blendEquation), this.blendSrcAlpha !== null && (s.blendSrcAlpha = this.blendSrcAlpha), this.blendDstAlpha !== null && (s.blendDstAlpha = this.blendDstAlpha), this.blendEquationAlpha !== null && (s.blendEquationAlpha = this.blendEquationAlpha), this.blendColor && this.blendColor.isColor && (s.blendColor = this.blendColor.getHex()), this.blendAlpha !== 0 && (s.blendAlpha = this.blendAlpha), this.depthFunc !== fl && (s.depthFunc = this.depthFunc), this.depthTest === !1 && (s.depthTest = this.depthTest), this.depthWrite === !1 && (s.depthWrite = this.depthWrite), this.colorWrite === !1 && (s.colorWrite = this.colorWrite), this.stencilWriteMask !== 255 && (s.stencilWriteMask = this.stencilWriteMask), this.stencilFunc !== yS && (s.stencilFunc = this.stencilFunc), this.stencilRef !== 0 && (s.stencilRef = this.stencilRef), this.stencilFuncMask !== 255 && (s.stencilFuncMask = this.stencilFuncMask), this.stencilFail !== Oo && (s.stencilFail = this.stencilFail), this.stencilZFail !== Oo && (s.stencilZFail = this.stencilZFail), this.stencilZPass !== Oo && (s.stencilZPass = this.stencilZPass), this.stencilWrite === !0 && (s.stencilWrite = this.stencilWrite), this.rotation !== void 0 && this.rotation !== 0 && (s.rotation = this.rotation), this.polygonOffset === !0 && (s.polygonOffset = !0), this.polygonOffsetFactor !== 0 && (s.polygonOffsetFactor = this.polygonOffsetFactor), this.polygonOffsetUnits !== 0 && (s.polygonOffsetUnits = this.polygonOffsetUnits), this.linewidth !== void 0 && this.linewidth !== 1 && (s.linewidth = this.linewidth), this.dashSize !== void 0 && (s.dashSize = this.dashSize), this.gapSize !== void 0 && (s.gapSize = this.gapSize), this.scale !== void 0 && (s.scale = this.scale), this.dithering === !0 && (s.dithering = !0), this.alphaTest > 0 && (s.alphaTest = this.alphaTest), this.alphaHash === !0 && (s.alphaHash = !0), this.alphaToCoverage === !0 && (s.alphaToCoverage = !0), this.premultipliedAlpha === !0 && (s.premultipliedAlpha = !0), this.forceSinglePass === !0 && (s.forceSinglePass = !0), this.allowOverride === !1 && (s.allowOverride = !1), this.wireframe === !0 && (s.wireframe = !0), this.wireframeLinewidth > 1 && (s.wireframeLinewidth = this.wireframeLinewidth), this.wireframeLinecap !== "round" && (s.wireframeLinecap = this.wireframeLinecap), this.wireframeLinejoin !== "round" && (s.wireframeLinejoin = this.wireframeLinejoin), this.flatShading === !0 && (s.flatShading = !0), this.visible === !1 && (s.visible = !1), this.toneMapped === !1 && (s.toneMapped = !1), this.fog === !1 && (s.fog = !1), Object.keys(this.userData).length > 0 && (s.userData = this.userData);
    function a(o) {
      const c = [];
      for (const u in o) {
        const d = o[u];
        delete d.metadata, c.push(d);
      }
      return c;
    }
    if (e) {
      const o = a(t.textures), c = a(t.images);
      o.length > 0 && (s.textures = o), c.length > 0 && (s.images = c);
    }
    return s;
  }
  /**
   * 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 s = null;
    if (e !== null) {
      const a = e.length;
      s = new Array(a);
      for (let o = 0; o !== a; ++o)
        s[o] = e[o].clone();
    }
    return this.clippingPlanes = s, 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.allowOverride = t.allowOverride, 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++;
  }
}
class m0 extends Za {
  /**
   * 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 we(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 Xo;
const vc = /* @__PURE__ */ new st(), Wo = /* @__PURE__ */ new st(), Yo = /* @__PURE__ */ new st(), jo = /* @__PURE__ */ new ae(), _c = /* @__PURE__ */ new ae(), UM = /* @__PURE__ */ new je(), Tf = /* @__PURE__ */ new st(), yc = /* @__PURE__ */ new st(), Cf = /* @__PURE__ */ new st(), LS = /* @__PURE__ */ new ae(), Hm = /* @__PURE__ */ new ae(), US = /* @__PURE__ */ new ae();
class Vm extends Tn {
  /**
   * Constructs a new sprite.
   *
   * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
   */
  constructor(t = new m0()) {
    if (super(), this.isSprite = !0, this.type = "Sprite", Xo === void 0) {
      Xo = new In();
      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
      ]), s = new LM(e, 5);
      Xo.setIndex([0, 1, 2, 0, 2, 3]), Xo.setAttribute("position", new Es(s, 3, 0, !1)), Xo.setAttribute("uv", new Es(s, 2, 3, !1));
    }
    this.geometry = Xo, this.material = t, this.center = new ae(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 && Ie('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'), Wo.setFromMatrixScale(this.matrixWorld), UM.copy(t.camera.matrixWorld), this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse, this.matrixWorld), Yo.setFromMatrixPosition(this.modelViewMatrix), t.camera.isPerspectiveCamera && this.material.sizeAttenuation === !1 && Wo.multiplyScalar(-Yo.z);
    const s = this.material.rotation;
    let a, o;
    s !== 0 && (o = Math.cos(s), a = Math.sin(s));
    const c = this.center;
    Rf(Tf.set(-0.5, -0.5, 0), Yo, c, Wo, a, o), Rf(yc.set(0.5, -0.5, 0), Yo, c, Wo, a, o), Rf(Cf.set(0.5, 0.5, 0), Yo, c, Wo, a, o), LS.set(0, 0), Hm.set(1, 0), US.set(1, 1);
    let u = t.ray.intersectTriangle(Tf, yc, Cf, !1, vc);
    if (u === null && (Rf(yc.set(-0.5, 0.5, 0), Yo, c, Wo, a, o), Hm.set(0, 1), u = t.ray.intersectTriangle(Tf, Cf, yc, !1, vc), u === null))
      return;
    const d = t.ray.origin.distanceTo(vc);
    d < t.near || d > t.far || e.push({
      distance: d,
      point: vc.clone(),
      uv: Wi.getInterpolation(vc, Tf, yc, Cf, LS, Hm, US, new ae()),
      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 Rf(n, t, e, s, a, o) {
  jo.subVectors(n, e).addScalar(0.5).multiply(s), a !== void 0 ? (_c.x = o * jo.x - a * jo.y, _c.y = a * jo.x + o * jo.y) : _c.copy(jo), n.copy(t), n.x += _c.x, n.y += _c.y, n.applyMatrix4(UM);
}
const nr = /* @__PURE__ */ new st(), Gm = /* @__PURE__ */ new st(), Df = /* @__PURE__ */ new st(), qr = /* @__PURE__ */ new st(), km = /* @__PURE__ */ new st(), Nf = /* @__PURE__ */ new st(), Xm = /* @__PURE__ */ new st();
class Q0 {
  /**
   * 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 st(), e = new st(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, nr)), 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 s = e.dot(this.direction);
    return s < 0 ? e.copy(this.origin) : e.copy(this.origin).addScaledVector(this.direction, s);
  }
  /**
   * 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 = nr.subVectors(t, this.origin).dot(this.direction);
    return e < 0 ? this.origin.distanceToSquared(t) : (nr.copy(this.origin).addScaledVector(this.direction, e), nr.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, s, a) {
    Gm.copy(t).add(e).multiplyScalar(0.5), Df.copy(e).sub(t).normalize(), qr.copy(this.origin).sub(Gm);
    const o = t.distanceTo(e) * 0.5, c = -this.direction.dot(Df), u = qr.dot(this.direction), d = -qr.dot(Df), h = qr.lengthSq(), m = Math.abs(1 - c * c);
    let p, g, _, x;
    if (m > 0)
      if (p = c * d - u, g = c * u - d, x = o * m, p >= 0)
        if (g >= -x)
          if (g <= x) {
            const A = 1 / m;
            p *= A, g *= A, _ = p * (p + c * g + 2 * u) + g * (c * p + g + 2 * d) + h;
          } else
            g = o, p = Math.max(0, -(c * g + u)), _ = -p * p + g * (g + 2 * d) + h;
        else
          g = -o, p = Math.max(0, -(c * g + u)), _ = -p * p + g * (g + 2 * d) + h;
      else
        g <= -x ? (p = Math.max(0, -(-c * o + u)), g = p > 0 ? -o : Math.min(Math.max(-o, -d), o), _ = -p * p + g * (g + 2 * d) + h) : g <= x ? (p = 0, g = Math.min(Math.max(-o, -d), o), _ = g * (g + 2 * d) + h) : (p = Math.max(0, -(c * o + u)), g = p > 0 ? o : Math.min(Math.max(-o, -d), o), _ = -p * p + g * (g + 2 * d) + h);
    else
      g = c > 0 ? -o : o, p = Math.max(0, -(c * g + u)), _ = -p * p + g * (g + 2 * d) + h;
    return s && s.copy(this.origin).addScaledVector(this.direction, p), a && a.copy(Gm).addScaledVector(Df, g), _;
  }
  /**
   * 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) {
    nr.subVectors(t.center, this.origin);
    const s = nr.dot(this.direction), a = nr.dot(nr) - s * s, o = t.radius * t.radius;
    if (a > o) return null;
    const c = Math.sqrt(o - a), u = s - c, d = s + c;
    return d < 0 ? null : u < 0 ? this.at(d, e) : this.at(u, 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 s = -(this.origin.dot(t.normal) + t.constant) / e;
    return s >= 0 ? s : 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 s = this.distanceToPlane(t);
    return s === null ? null : this.at(s, 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 s, a, o, c, u, d;
    const h = 1 / this.direction.x, m = 1 / this.direction.y, p = 1 / this.direction.z, g = this.origin;
    return h >= 0 ? (s = (t.min.x - g.x) * h, a = (t.max.x - g.x) * h) : (s = (t.max.x - g.x) * h, a = (t.min.x - g.x) * h), m >= 0 ? (o = (t.min.y - g.y) * m, c = (t.max.y - g.y) * m) : (o = (t.max.y - g.y) * m, c = (t.min.y - g.y) * m), s > c || o > a || ((o > s || isNaN(s)) && (s = o), (c < a || isNaN(a)) && (a = c), p >= 0 ? (u = (t.min.z - g.z) * p, d = (t.max.z - g.z) * p) : (u = (t.max.z - g.z) * p, d = (t.min.z - g.z) * p), s > d || u > a) || ((u > s || s !== s) && (s = u), (d < a || a !== a) && (a = d), a < 0) ? null : this.at(s >= 0 ? s : a, 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, nr) !== 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, s, a, o) {
    km.subVectors(e, t), Nf.subVectors(s, t), Xm.crossVectors(km, Nf);
    let c = this.direction.dot(Xm), u;
    if (c > 0) {
      if (a) return null;
      u = 1;
    } else if (c < 0)
      u = -1, c = -c;
    else
      return null;
    qr.subVectors(this.origin, t);
    const d = u * this.direction.dot(Nf.crossVectors(qr, Nf));
    if (d < 0)
      return null;
    const h = u * this.direction.dot(km.cross(qr));
    if (h < 0 || d + h > c)
      return null;
    const m = -u * qr.dot(Xm);
    return m < 0 ? null : this.at(m / c, o);
  }
  /**
   * 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);
  }
}
class Yd extends Za {
  /**
   * 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 we(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 Rs(), this.combine = H0, 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 PS = /* @__PURE__ */ new je(), Ca = /* @__PURE__ */ new Q0(), Of = /* @__PURE__ */ new aa(), IS = /* @__PURE__ */ new st(), Lf = /* @__PURE__ */ new st(), Uf = /* @__PURE__ */ new st(), Pf = /* @__PURE__ */ new st(), Wm = /* @__PURE__ */ new st(), If = /* @__PURE__ */ new st(), BS = /* @__PURE__ */ new st(), Bf = /* @__PURE__ */ new st();
class Ln extends Tn {
  /**
   * Constructs a new mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(t = new In(), e = new Yd()) {
    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, s = Object.keys(e);
    if (s.length > 0) {
      const a = e[s[0]];
      if (a !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let o = 0, c = a.length; o < c; o++) {
          const u = a[o].name || String(o);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[u] = o;
        }
      }
    }
  }
  /**
   * 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 s = this.geometry, a = s.attributes.position, o = s.morphAttributes.position, c = s.morphTargetsRelative;
    e.fromBufferAttribute(a, t);
    const u = this.morphTargetInfluences;
    if (o && u) {
      If.set(0, 0, 0);
      for (let d = 0, h = o.length; d < h; d++) {
        const m = u[d], p = o[d];
        m !== 0 && (Wm.fromBufferAttribute(p, t), c ? If.addScaledVector(Wm, m) : If.addScaledVector(Wm.sub(e), m));
      }
      e.add(If);
    }
    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 s = this.geometry, a = this.material, o = this.matrixWorld;
    a !== void 0 && (s.boundingSphere === null && s.computeBoundingSphere(), Of.copy(s.boundingSphere), Of.applyMatrix4(o), Ca.copy(t.ray).recast(t.near), !(Of.containsPoint(Ca.origin) === !1 && (Ca.intersectSphere(Of, IS) === null || Ca.origin.distanceToSquared(IS) > (t.far - t.near) ** 2)) && (PS.copy(o).invert(), Ca.copy(t.ray).applyMatrix4(PS), !(s.boundingBox !== null && Ca.intersectsBox(s.boundingBox) === !1) && this._computeIntersections(t, e, Ca)));
  }
  _computeIntersections(t, e, s) {
    let a;
    const o = this.geometry, c = this.material, u = o.index, d = o.attributes.position, h = o.attributes.uv, m = o.attributes.uv1, p = o.attributes.normal, g = o.groups, _ = o.drawRange;
    if (u !== null)
      if (Array.isArray(c))
        for (let x = 0, A = g.length; x < A; x++) {
          const b = g[x], y = c[b.materialIndex], E = Math.max(b.start, _.start), w = Math.min(u.count, Math.min(b.start + b.count, _.start + _.count));
          for (let M = E, O = w; M < O; M += 3) {
            const C = u.getX(M), D = u.getX(M + 1), T = u.getX(M + 2);
            a = zf(this, y, t, s, h, m, p, C, D, T), a && (a.faceIndex = Math.floor(M / 3), a.face.materialIndex = b.materialIndex, e.push(a));
          }
        }
      else {
        const x = Math.max(0, _.start), A = Math.min(u.count, _.start + _.count);
        for (let b = x, y = A; b < y; b += 3) {
          const E = u.getX(b), w = u.getX(b + 1), M = u.getX(b + 2);
          a = zf(this, c, t, s, h, m, p, E, w, M), a && (a.faceIndex = Math.floor(b / 3), e.push(a));
        }
      }
    else if (d !== void 0)
      if (Array.isArray(c))
        for (let x = 0, A = g.length; x < A; x++) {
          const b = g[x], y = c[b.materialIndex], E = Math.max(b.start, _.start), w = Math.min(d.count, Math.min(b.start + b.count, _.start + _.count));
          for (let M = E, O = w; M < O; M += 3) {
            const C = M, D = M + 1, T = M + 2;
            a = zf(this, y, t, s, h, m, p, C, D, T), a && (a.faceIndex = Math.floor(M / 3), a.face.materialIndex = b.materialIndex, e.push(a));
          }
        }
      else {
        const x = Math.max(0, _.start), A = Math.min(d.count, _.start + _.count);
        for (let b = x, y = A; b < y; b += 3) {
          const E = b, w = b + 1, M = b + 2;
          a = zf(this, c, t, s, h, m, p, E, w, M), a && (a.faceIndex = Math.floor(b / 3), e.push(a));
        }
      }
  }
}
function T3(n, t, e, s, a, o, c, u) {
  let d;
  if (t.side === pi ? d = s.intersectTriangle(c, o, a, !0, u) : d = s.intersectTriangle(a, o, c, t.side === ra, u), d === null) return null;
  Bf.copy(u), Bf.applyMatrix4(n.matrixWorld);
  const h = e.ray.origin.distanceTo(Bf);
  return h < e.near || h > e.far ? null : {
    distance: h,
    point: Bf.clone(),
    object: n
  };
}
function zf(n, t, e, s, a, o, c, u, d, h) {
  n.getVertexPosition(u, Lf), n.getVertexPosition(d, Uf), n.getVertexPosition(h, Pf);
  const m = T3(n, t, e, s, Lf, Uf, Pf, BS);
  if (m) {
    const p = new st();
    Wi.getBarycoord(BS, Lf, Uf, Pf, p), a && (m.uv = Wi.getInterpolatedAttribute(a, u, d, h, p, new ae())), o && (m.uv1 = Wi.getInterpolatedAttribute(o, u, d, h, p, new ae())), c && (m.normal = Wi.getInterpolatedAttribute(c, u, d, h, p, new st()), m.normal.dot(s.direction) > 0 && m.normal.multiplyScalar(-1));
    const g = {
      a: u,
      b: d,
      c: h,
      normal: new st(),
      materialIndex: 0
    };
    Wi.getNormal(Lf, Uf, Pf, g.normal), m.face = g, m.barycoord = p;
  }
  return m;
}
class Cd extends Jn {
  /**
   * 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, s = 1, a, o, c, u, d, h = vn, m = vn, p, g) {
    super(null, c, u, d, h, m, a, o, p, g), this.isDataTexture = !0, this.image = { data: t, width: e, height: s }, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
  }
}
class An extends dn {
  /**
   * 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, s, a = 1) {
    super(t, e, s), this.isInstancedBufferAttribute = !0, this.meshPerAttribute = a;
  }
  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 qo = /* @__PURE__ */ new je(), zS = /* @__PURE__ */ new je(), Ff = [], FS = /* @__PURE__ */ new Ns(), C3 = /* @__PURE__ */ new je(), xc = /* @__PURE__ */ new Ln(), Sc = /* @__PURE__ */ new aa();
class HS extends Ln {
  /**
   * 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, s) {
    super(t, e), this.isInstancedMesh = !0, this.instanceMatrix = new An(new Float32Array(s * 16), 16), this.previousInstanceMatrix = null, this.instanceColor = null, this.morphTexture = null, this.count = s, this.boundingBox = null, this.boundingSphere = null;
    for (let a = 0; a < s; a++)
      this.setMatrixAt(a, C3);
  }
  /**
   * 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 Ns()), t.boundingBox === null && t.computeBoundingBox(), this.boundingBox.makeEmpty();
    for (let s = 0; s < e; s++)
      this.getMatrixAt(s, qo), FS.copy(t.boundingBox).applyMatrix4(qo), this.boundingBox.union(FS);
  }
  /**
   * 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 aa()), t.boundingSphere === null && t.computeBoundingSphere(), this.boundingSphere.makeEmpty();
    for (let s = 0; s < e; s++)
      this.getMatrixAt(s, qo), Sc.copy(t.boundingSphere).applyMatrix4(qo), this.boundingSphere.union(Sc);
  }
  copy(t, e) {
    return super.copy(t, e), this.instanceMatrix.copy(t.instanceMatrix), t.previousInstanceMatrix !== null && (this.previousInstanceMatrix = t.previousInstanceMatrix.clone()), 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 s = e.morphTargetInfluences, a = this.morphTexture.source.data.data, o = s.length + 1, c = t * o + 1;
    for (let u = 0; u < s.length; u++)
      s[u] = a[c + u];
  }
  raycast(t, e) {
    const s = this.matrixWorld, a = this.count;
    if (xc.geometry = this.geometry, xc.material = this.material, xc.material !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), Sc.copy(this.boundingSphere), Sc.applyMatrix4(s), t.ray.intersectsSphere(Sc) !== !1))
      for (let o = 0; o < a; o++) {
        this.getMatrixAt(o, qo), zS.multiplyMatrices(s, qo), xc.matrixWorld = zS, xc.raycast(t, Ff);
        for (let c = 0, u = Ff.length; c < u; c++) {
          const d = Ff[c];
          d.instanceId = o, d.object = this, e.push(d);
        }
        Ff.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 An(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 s = e.morphTargetInfluences, a = s.length + 1;
    this.morphTexture === null && (this.morphTexture = new Cd(new Float32Array(a * this.count), a, this.count, X0, Di));
    const o = this.morphTexture.source.data.data;
    let c = 0;
    for (let h = 0; h < s.length; h++)
      c += s[h];
    const u = this.geometry.morphTargetsRelative ? 1 : 1 - c, d = a * t;
    o[d] = u, o.set(s, d + 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 Ym = /* @__PURE__ */ new st(), R3 = /* @__PURE__ */ new st(), D3 = /* @__PURE__ */ new Me();
class Jr {
  /**
   * 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 st(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, s, a) {
    return this.normal.set(t, e, s), this.constant = a, 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, s) {
    const a = Ym.subVectors(s, e).cross(R3.subVectors(t, e)).normalize();
    return this.setFromNormalAndCoplanarPoint(a, 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 s = t.delta(Ym), a = this.normal.dot(s);
    if (a === 0)
      return this.distanceToPoint(t.start) === 0 ? e.copy(t.start) : null;
    const o = -(t.start.dot(this.normal) + this.constant) / a;
    return o < 0 || o > 1 ? null : e.copy(t.start).addScaledVector(s, o);
  }
  /**
   * 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), s = this.distanceToPoint(t.end);
    return e < 0 && s > 0 || s < 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 s = e || D3.getNormalMatrix(t), a = this.coplanarPoint(Ym).applyMatrix4(t), o = this.normal.applyMatrix3(s).normalize();
    return this.constant = -a.dot(o), 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 Ra = /* @__PURE__ */ new aa(), N3 = /* @__PURE__ */ new ae(0.5, 0.5), Hf = /* @__PURE__ */ new st();
class J0 {
  /**
   * 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 Jr(), e = new Jr(), s = new Jr(), a = new Jr(), o = new Jr(), c = new Jr()) {
    this.planes = [t, e, s, a, o, c];
  }
  /**
   * 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, s, a, o, c) {
    const u = this.planes;
    return u[0].copy(t), u[1].copy(e), u[2].copy(s), u[3].copy(a), u[4].copy(o), u[5].copy(c), 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 s = 0; s < 6; s++)
      e[s].copy(t.planes[s]);
    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 = Ms, s = !1) {
    const a = this.planes, o = t.elements, c = o[0], u = o[1], d = o[2], h = o[3], m = o[4], p = o[5], g = o[6], _ = o[7], x = o[8], A = o[9], b = o[10], y = o[11], E = o[12], w = o[13], M = o[14], O = o[15];
    if (a[0].setComponents(h - c, _ - m, y - x, O - E).normalize(), a[1].setComponents(h + c, _ + m, y + x, O + E).normalize(), a[2].setComponents(h + u, _ + p, y + A, O + w).normalize(), a[3].setComponents(h - u, _ - p, y - A, O - w).normalize(), s)
      a[4].setComponents(d, g, b, M).normalize(), a[5].setComponents(h - d, _ - g, y - b, O - M).normalize();
    else if (a[4].setComponents(h - d, _ - g, y - b, O - M).normalize(), e === Ms)
      a[5].setComponents(h + d, _ + g, y + b, O + M).normalize();
    else if (e === Hc)
      a[5].setComponents(d, g, b, M).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(), Ra.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);
    else {
      const e = t.geometry;
      e.boundingSphere === null && e.computeBoundingSphere(), Ra.copy(e.boundingSphere).applyMatrix4(t.matrixWorld);
    }
    return this.intersectsSphere(Ra);
  }
  /**
   * 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) {
    Ra.center.set(0, 0, 0);
    const e = N3.distanceTo(t.center);
    return Ra.radius = 0.7071067811865476 + e, Ra.applyMatrix4(t.matrixWorld), this.intersectsSphere(Ra);
  }
  /**
   * 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, s = t.center, a = -t.radius;
    for (let o = 0; o < 6; o++)
      if (e[o].distanceToPoint(s) < a)
        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 s = 0; s < 6; s++) {
      const a = e[s];
      if (Hf.x = a.normal.x > 0 ? t.max.x : t.min.x, Hf.y = a.normal.y > 0 ? t.max.y : t.min.y, Hf.z = a.normal.z > 0 ? t.max.z : t.min.z, a.distanceToPoint(Hf) < 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 s = 0; s < 6; s++)
      if (e[s].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);
  }
}
class jd extends Za {
  /**
   * 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 we(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 Rd = /* @__PURE__ */ new st(), Dd = /* @__PURE__ */ new st(), VS = /* @__PURE__ */ new je(), bc = /* @__PURE__ */ new Q0(), Vf = /* @__PURE__ */ new aa(), jm = /* @__PURE__ */ new st(), GS = /* @__PURE__ */ new st();
class Gc extends Tn {
  /**
   * Constructs a new line.
   *
   * @param {BufferGeometry} [geometry] - The line geometry.
   * @param {Material|Array<Material>} [material] - The line material.
   */
  constructor(t = new In(), e = new jd()) {
    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, s = [0];
      for (let a = 1, o = e.count; a < o; a++)
        Rd.fromBufferAttribute(e, a - 1), Dd.fromBufferAttribute(e, a), s[a] = s[a - 1], s[a] += Rd.distanceTo(Dd);
      t.setAttribute("lineDistance", new _n(s, 1));
    } else
      de("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 s = this.geometry, a = this.matrixWorld, o = t.params.Line.threshold, c = s.drawRange;
    if (s.boundingSphere === null && s.computeBoundingSphere(), Vf.copy(s.boundingSphere), Vf.applyMatrix4(a), Vf.radius += o, t.ray.intersectsSphere(Vf) === !1) return;
    VS.copy(a).invert(), bc.copy(t.ray).applyMatrix4(VS);
    const u = o / ((this.scale.x + this.scale.y + this.scale.z) / 3), d = u * u, h = this.isLineSegments ? 2 : 1, m = s.index, g = s.attributes.position;
    if (m !== null) {
      const _ = Math.max(0, c.start), x = Math.min(m.count, c.start + c.count);
      for (let A = _, b = x - 1; A < b; A += h) {
        const y = m.getX(A), E = m.getX(A + 1), w = Gf(this, t, bc, d, y, E, A);
        w && e.push(w);
      }
      if (this.isLineLoop) {
        const A = m.getX(x - 1), b = m.getX(_), y = Gf(this, t, bc, d, A, b, x - 1);
        y && e.push(y);
      }
    } else {
      const _ = Math.max(0, c.start), x = Math.min(g.count, c.start + c.count);
      for (let A = _, b = x - 1; A < b; A += h) {
        const y = Gf(this, t, bc, d, A, A + 1, A);
        y && e.push(y);
      }
      if (this.isLineLoop) {
        const A = Gf(this, t, bc, d, x - 1, _, x - 1);
        A && e.push(A);
      }
    }
  }
  /**
   * 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, s = Object.keys(e);
    if (s.length > 0) {
      const a = e[s[0]];
      if (a !== void 0) {
        this.morphTargetInfluences = [], this.morphTargetDictionary = {};
        for (let o = 0, c = a.length; o < c; o++) {
          const u = a[o].name || String(o);
          this.morphTargetInfluences.push(0), this.morphTargetDictionary[u] = o;
        }
      }
    }
  }
}
function Gf(n, t, e, s, a, o, c) {
  const u = n.geometry.attributes.position;
  if (Rd.fromBufferAttribute(u, a), Dd.fromBufferAttribute(u, o), e.distanceSqToSegment(Rd, Dd, jm, GS) > s) return;
  jm.applyMatrix4(n.matrixWorld);
  const h = t.ray.origin.distanceTo(jm);
  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: GS.clone().applyMatrix4(n.matrixWorld),
      index: c,
      face: null,
      faceIndex: null,
      barycoord: null,
      object: n
    };
}
const kS = /* @__PURE__ */ new st(), XS = /* @__PURE__ */ new st();
class O3 extends Gc {
  /**
   * 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, s = [];
      for (let a = 0, o = e.count; a < o; a += 2)
        kS.fromBufferAttribute(e, a), XS.fromBufferAttribute(e, a + 1), s[a] = a === 0 ? 0 : s[a - 1], s[a + 1] = s[a] + kS.distanceTo(XS);
      t.setAttribute("lineDistance", new _n(s, 1));
    } else
      de("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
    return this;
  }
}
class PM extends Jn {
  /**
   * 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 = ka, s, a, o, c, u, d, h, m) {
    super(t, e, s, a, o, c, u, d, h, m), 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 L3 extends Jn {
  /**
   * 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, s, a, o, c, u, d, h) {
    super(t, e, s, a, o, c, u, d, h), this.isCanvasTexture = !0, this.needsUpdate = !0;
  }
}
class kc extends Jn {
  /**
   * 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, s = Cs, a, o, c, u = vn, d = vn, h, m = hr, p = 1) {
    if (m !== hr && m !== Ba)
      throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");
    const g = { width: t, height: e, depth: p };
    super(g, a, o, c, u, d, m, s, h), this.isDepthTexture = !0, this.flipY = !1, this.generateMipmaps = !1, this.compareFunction = null;
  }
  copy(t) {
    return super.copy(t), this.source = new K0(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 U3 extends kc {
  /**
   * Constructs a new cube depth texture.
   *
   * @param {number} size - The size (width and height) of each cube face.
   * @param {number} [type=UnsignedIntType] - The texture type.
   * @param {number} [mapping=CubeReflectionMapping] - 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 {number} [format=DepthFormat] - The texture format.
   */
  constructor(t, e = Cs, s = ka, a, o, c = vn, u = vn, d, h = hr) {
    const m = { width: t, height: t, depth: 1 }, p = [m, m, m, m, m, m];
    super(t, t, e, s, a, o, c, u, d, h), this.image = p, this.isCubeDepthTexture = !0, this.isCubeTexture = !0;
  }
  /**
   * Alias for {@link CubeDepthTexture#image}.
   *
   * @type {Array<Image>}
   */
  get images() {
    return this.image;
  }
  set images(t) {
    this.image = t;
  }
}
class IM extends Jn {
  /**
   * 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 nu extends In {
  /**
   * 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, s = 1, a = 1, o = 1, c = 1) {
    super(), this.type = "BoxGeometry", this.parameters = {
      width: t,
      height: e,
      depth: s,
      widthSegments: a,
      heightSegments: o,
      depthSegments: c
    };
    const u = this;
    a = Math.floor(a), o = Math.floor(o), c = Math.floor(c);
    const d = [], h = [], m = [], p = [];
    let g = 0, _ = 0;
    x("z", "y", "x", -1, -1, s, e, t, c, o, 0), x("z", "y", "x", 1, -1, s, e, -t, c, o, 1), x("x", "z", "y", 1, 1, t, s, e, a, c, 2), x("x", "z", "y", 1, -1, t, s, -e, a, c, 3), x("x", "y", "z", 1, -1, t, e, s, a, o, 4), x("x", "y", "z", -1, -1, t, e, -s, a, o, 5), this.setIndex(d), this.setAttribute("position", new _n(h, 3)), this.setAttribute("normal", new _n(m, 3)), this.setAttribute("uv", new _n(p, 2));
    function x(A, b, y, E, w, M, O, C, D, T, L) {
      const z = M / D, R = O / T, B = M / 2, H = O / 2, U = C / 2, V = D + 1, N = T + 1;
      let I = 0, k = 0;
      const X = new st();
      for (let Q = 0; Q < N; Q++) {
        const F = Q * R - H;
        for (let W = 0; W < V; W++) {
          const et = W * z - B;
          X[A] = et * E, X[b] = F * w, X[y] = U, h.push(X.x, X.y, X.z), X[A] = 0, X[b] = 0, X[y] = C > 0 ? 1 : -1, m.push(X.x, X.y, X.z), p.push(W / D), p.push(1 - Q / T), I += 1;
        }
      }
      for (let Q = 0; Q < T; Q++)
        for (let F = 0; F < D; F++) {
          const W = g + F + V * Q, et = g + F + V * (Q + 1), $ = g + (F + 1) + V * (Q + 1), j = g + (F + 1) + V * Q;
          d.push(W, et, j), d.push(et, $, j), k += 6;
        }
      u.addGroup(_, k, L), _ += k, g += I;
    }
  }
  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 nu(t.width, t.height, t.depth, t.widthSegments, t.heightSegments, t.depthSegments);
  }
}
class qd extends In {
  /**
   * 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, s = 1, a = 32, o = 1, c = !1, u = 0, d = Math.PI * 2) {
    super(), this.type = "CylinderGeometry", this.parameters = {
      radiusTop: t,
      radiusBottom: e,
      height: s,
      radialSegments: a,
      heightSegments: o,
      openEnded: c,
      thetaStart: u,
      thetaLength: d
    };
    const h = this;
    a = Math.floor(a), o = Math.floor(o);
    const m = [], p = [], g = [], _ = [];
    let x = 0;
    const A = [], b = s / 2;
    let y = 0;
    E(), c === !1 && (t > 0 && w(!0), e > 0 && w(!1)), this.setIndex(m), this.setAttribute("position", new _n(p, 3)), this.setAttribute("normal", new _n(g, 3)), this.setAttribute("uv", new _n(_, 2));
    function E() {
      const M = new st(), O = new st();
      let C = 0;
      const D = (e - t) / s;
      for (let T = 0; T <= o; T++) {
        const L = [], z = T / o, R = z * (e - t) + t;
        for (let B = 0; B <= a; B++) {
          const H = B / a, U = H * d + u, V = Math.sin(U), N = Math.cos(U);
          O.x = R * V, O.y = -z * s + b, O.z = R * N, p.push(O.x, O.y, O.z), M.set(V, D, N).normalize(), g.push(M.x, M.y, M.z), _.push(H, 1 - z), L.push(x++);
        }
        A.push(L);
      }
      for (let T = 0; T < a; T++)
        for (let L = 0; L < o; L++) {
          const z = A[L][T], R = A[L + 1][T], B = A[L + 1][T + 1], H = A[L][T + 1];
          (t > 0 || L !== 0) && (m.push(z, R, H), C += 3), (e > 0 || L !== o - 1) && (m.push(R, B, H), C += 3);
        }
      h.addGroup(y, C, 0), y += C;
    }
    function w(M) {
      const O = x, C = new ae(), D = new st();
      let T = 0;
      const L = M === !0 ? t : e, z = M === !0 ? 1 : -1;
      for (let B = 1; B <= a; B++)
        p.push(0, b * z, 0), g.push(0, z, 0), _.push(0.5, 0.5), x++;
      const R = x;
      for (let B = 0; B <= a; B++) {
        const U = B / a * d + u, V = Math.cos(U), N = Math.sin(U);
        D.x = L * N, D.y = b * z, D.z = L * V, p.push(D.x, D.y, D.z), g.push(0, z, 0), C.x = V * 0.5 + 0.5, C.y = N * 0.5 * z + 0.5, _.push(C.x, C.y), x++;
      }
      for (let B = 0; B < a; B++) {
        const H = O + B, U = R + B;
        M === !0 ? m.push(U, U + 1, H) : m.push(U + 1, U, H), T += 3;
      }
      h.addGroup(y, T, M === !0 ? 1 : 2), y += T;
    }
  }
  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 qd(t.radiusTop, t.radiusBottom, t.height, t.radialSegments, t.heightSegments, t.openEnded, t.thetaStart, t.thetaLength);
  }
}
class Zd extends qd {
  /**
   * 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, s = 32, a = 1, o = !1, c = 0, u = Math.PI * 2) {
    super(0, t, e, s, a, o, c, u), this.type = "ConeGeometry", this.parameters = {
      radius: t,
      height: e,
      radialSegments: s,
      heightSegments: a,
      openEnded: o,
      thetaStart: c,
      thetaLength: u
    };
  }
  /**
   * 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 Zd(t.radius, t.height, t.radialSegments, t.heightSegments, t.openEnded, t.thetaStart, t.thetaLength);
  }
}
class $d extends In {
  /**
   * 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, s = 1, a = 1) {
    super(), this.type = "PlaneGeometry", this.parameters = {
      width: t,
      height: e,
      widthSegments: s,
      heightSegments: a
    };
    const o = t / 2, c = e / 2, u = Math.floor(s), d = Math.floor(a), h = u + 1, m = d + 1, p = t / u, g = e / d, _ = [], x = [], A = [], b = [];
    for (let y = 0; y < m; y++) {
      const E = y * g - c;
      for (let w = 0; w < h; w++) {
        const M = w * p - o;
        x.push(M, -E, 0), A.push(0, 0, 1), b.push(w / u), b.push(1 - y / d);
      }
    }
    for (let y = 0; y < d; y++)
      for (let E = 0; E < u; E++) {
        const w = E + h * y, M = E + h * (y + 1), O = E + 1 + h * (y + 1), C = E + 1 + h * y;
        _.push(w, M, C), _.push(M, O, C);
      }
    this.setIndex(_), this.setAttribute("position", new _n(x, 3)), this.setAttribute("normal", new _n(A, 3)), this.setAttribute("uv", new _n(b, 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 $d(t.width, t.height, t.widthSegments, t.heightSegments);
  }
}
class tv extends In {
  /**
   * 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, s = 16, a = 0, o = Math.PI * 2, c = 0, u = Math.PI) {
    super(), this.type = "SphereGeometry", this.parameters = {
      radius: t,
      widthSegments: e,
      heightSegments: s,
      phiStart: a,
      phiLength: o,
      thetaStart: c,
      thetaLength: u
    }, e = Math.max(3, Math.floor(e)), s = Math.max(2, Math.floor(s));
    const d = Math.min(c + u, Math.PI);
    let h = 0;
    const m = [], p = new st(), g = new st(), _ = [], x = [], A = [], b = [];
    for (let y = 0; y <= s; y++) {
      const E = [], w = y / s;
      let M = 0;
      y === 0 && c === 0 ? M = 0.5 / e : y === s && d === Math.PI && (M = -0.5 / e);
      for (let O = 0; O <= e; O++) {
        const C = O / e;
        p.x = -t * Math.cos(a + C * o) * Math.sin(c + w * u), p.y = t * Math.cos(c + w * u), p.z = t * Math.sin(a + C * o) * Math.sin(c + w * u), x.push(p.x, p.y, p.z), g.copy(p).normalize(), A.push(g.x, g.y, g.z), b.push(C + M, 1 - w), E.push(h++);
      }
      m.push(E);
    }
    for (let y = 0; y < s; y++)
      for (let E = 0; E < e; E++) {
        const w = m[y][E + 1], M = m[y][E], O = m[y + 1][E], C = m[y + 1][E + 1];
        (y !== 0 || c > 0) && _.push(w, M, C), (y !== s - 1 || d < Math.PI) && _.push(M, O, C);
      }
    this.setIndex(_), this.setAttribute("position", new _n(x, 3)), this.setAttribute("normal", new _n(A, 3)), this.setAttribute("uv", new _n(b, 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 tv(t.radius, t.widthSegments, t.heightSegments, t.phiStart, t.phiLength, t.thetaStart, t.thetaLength);
  }
}
class P3 extends In {
  /**
   * 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 = [], s = /* @__PURE__ */ new Set(), a = new st(), o = new st();
      if (t.index !== null) {
        const c = t.attributes.position, u = t.index;
        let d = t.groups;
        d.length === 0 && (d = [{ start: 0, count: u.count, materialIndex: 0 }]);
        for (let h = 0, m = d.length; h < m; ++h) {
          const p = d[h], g = p.start, _ = p.count;
          for (let x = g, A = g + _; x < A; x += 3)
            for (let b = 0; b < 3; b++) {
              const y = u.getX(x + b), E = u.getX(x + (b + 1) % 3);
              a.fromBufferAttribute(c, y), o.fromBufferAttribute(c, E), WS(a, o, s) === !0 && (e.push(a.x, a.y, a.z), e.push(o.x, o.y, o.z));
            }
        }
      } else {
        const c = t.attributes.position;
        for (let u = 0, d = c.count / 3; u < d; u++)
          for (let h = 0; h < 3; h++) {
            const m = 3 * u + h, p = 3 * u + (h + 1) % 3;
            a.fromBufferAttribute(c, m), o.fromBufferAttribute(c, p), WS(a, o, s) === !0 && (e.push(a.x, a.y, a.z), e.push(o.x, o.y, o.z));
          }
      }
      this.setAttribute("position", new _n(e, 3));
    }
  }
  copy(t) {
    return super.copy(t), this.parameters = Object.assign({}, t.parameters), this;
  }
}
function WS(n, t, e) {
  const s = `${n.x},${n.y},${n.z}-${t.x},${t.y},${t.z}`, a = `${t.x},${t.y},${t.z}-${n.x},${n.y},${n.z}`;
  return e.has(s) === !0 || e.has(a) === !0 ? !1 : (e.add(s), e.add(a), !0);
}
function ml(n) {
  const t = {};
  for (const e in n) {
    t[e] = {};
    for (const s in n[e]) {
      const a = n[e][s];
      a && (a.isColor || a.isMatrix3 || a.isMatrix4 || a.isVector2 || a.isVector3 || a.isVector4 || a.isTexture || a.isQuaternion) ? a.isRenderTargetTexture ? (de("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), t[e][s] = null) : t[e][s] = a.clone() : Array.isArray(a) ? t[e][s] = a.slice() : t[e][s] = a;
    }
  }
  return t;
}
function si(n) {
  const t = {};
  for (let e = 0; e < n.length; e++) {
    const s = ml(n[e]);
    for (const a in s)
      t[a] = s[a];
  }
  return t;
}
function I3(n) {
  const t = [];
  for (let e = 0; e < n.length; e++)
    t.push(n[e].clone());
  return t;
}
function BM(n) {
  const t = n.getRenderTarget();
  return t === null ? n.outputColorSpace : t.isXRRenderTarget === !0 ? t.texture.colorSpace : Be.workingColorSpace;
}
const ev = { clone: ml, merge: si };
var B3 = `void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`, z3 = `void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`;
class as extends Za {
  /**
   * 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 = B3, this.fragmentShader = z3, 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 = ml(t.uniforms), this.uniformsGroups = I3(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.defaultAttributeValues = Object.assign({}, t.defaultAttributeValues), this.index0AttributeName = t.index0AttributeName, this.uniformsNeedUpdate = t.uniformsNeedUpdate, this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    e.glslVersion = this.glslVersion, e.uniforms = {};
    for (const a in this.uniforms) {
      const c = this.uniforms[a].value;
      c && c.isTexture ? e.uniforms[a] = {
        type: "t",
        value: c.toJSON(t).uuid
      } : c && c.isColor ? e.uniforms[a] = {
        type: "c",
        value: c.getHex()
      } : c && c.isVector2 ? e.uniforms[a] = {
        type: "v2",
        value: c.toArray()
      } : c && c.isVector3 ? e.uniforms[a] = {
        type: "v3",
        value: c.toArray()
      } : c && c.isVector4 ? e.uniforms[a] = {
        type: "v4",
        value: c.toArray()
      } : c && c.isMatrix3 ? e.uniforms[a] = {
        type: "m3",
        value: c.toArray()
      } : c && c.isMatrix4 ? e.uniforms[a] = {
        type: "m4",
        value: c.toArray()
      } : e.uniforms[a] = {
        value: c
      };
    }
    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 s = {};
    for (const a in this.extensions)
      this.extensions[a] === !0 && (s[a] = !0);
    return Object.keys(s).length > 0 && (e.extensions = s), e;
  }
}
class nv extends as {
  /**
   * 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";
  }
}
class g0 extends Za {
  /**
   * 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 we(16777215), this.specular = new we(1118481), this.shininess = 30, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new we(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = EM, this.normalScale = new ae(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new Rs(), this.combine = H0, this.reflectivity = 1, this.envMapIntensity = 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.envMapIntensity = t.envMapIntensity, 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 F3 extends Za {
  /**
   * 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 = I2, 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 H3 extends Za {
  /**
   * 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 iv extends Tn {
  /**
   * 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 we(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() {
    this.dispatchEvent({ type: "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, e;
  }
}
class V3 extends iv {
  /**
   * 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, s) {
    super(t, s), this.isHemisphereLight = !0, this.type = "HemisphereLight", this.position.copy(Tn.DEFAULT_UP), this.updateMatrix(), this.groundColor = new we(e);
  }
  copy(t, e) {
    return super.copy(t, e), this.groundColor.copy(t.groundColor), this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.object.groundColor = this.groundColor.getHex(), e;
  }
}
const qm = /* @__PURE__ */ new je(), YS = /* @__PURE__ */ new st(), jS = /* @__PURE__ */ new st();
class G3 {
  /**
   * 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.biasNode = null, this.normalBias = 0, this.radius = 1, this.blurSamples = 8, this.mapSize = new ae(512, 512), this.mapType = Ci, this.map = null, this.mapPass = null, this.matrix = new je(), this.autoUpdate = !0, this.needsUpdate = !1, this._frustum = new J0(), this._frameExtents = new ae(1, 1), this._viewportCount = 1, this._viewports = [
      new Je(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, s = this.matrix;
    YS.setFromMatrixPosition(t.matrixWorld), e.position.copy(YS), jS.setFromMatrixPosition(t.target.matrixWorld), e.lookAt(jS), e.updateMatrixWorld(), qm.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse), this._frustum.setFromProjectionMatrix(qm, e.coordinateSystem, e.reversedDepth), e.coordinateSystem === Hc || e.reversedDepth ? s.set(
      0.5,
      0,
      0,
      0.5,
      0,
      0.5,
      0,
      0.5,
      0,
      0,
      1,
      0,
      // Identity Z (preserving the correct [0, 1] range from the projection matrix)
      0,
      0,
      0,
      1
    ) : s.set(
      0.5,
      0,
      0,
      0.5,
      0,
      0.5,
      0,
      0.5,
      0,
      0,
      0.5,
      0.5,
      0,
      0,
      0,
      1
    ), s.multiply(qm);
  }
  /**
   * 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.biasNode = t.biasNode, 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;
  }
}
const kf = /* @__PURE__ */ new st(), Xf = /* @__PURE__ */ new pr(), gs = /* @__PURE__ */ new st();
class zM extends Tn {
  /**
   * Constructs a new camera.
   */
  constructor() {
    super(), this.isCamera = !0, this.type = "Camera", this.matrixWorldInverse = new je(), this.projectionMatrix = new je(), this.projectionMatrixInverse = new je(), this.coordinateSystem = Ms, 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.matrixWorld.decompose(kf, Xf, gs), gs.x === 1 && gs.y === 1 && gs.z === 1 ? this.matrixWorldInverse.copy(this.matrixWorld).invert() : this.matrixWorldInverse.compose(kf, Xf, gs.set(1, 1, 1)).invert();
  }
  updateWorldMatrix(t, e) {
    super.updateWorldMatrix(t, e), this.matrixWorld.decompose(kf, Xf, gs), gs.x === 1 && gs.y === 1 && gs.z === 1 ? this.matrixWorldInverse.copy(this.matrixWorld).invert() : this.matrixWorldInverse.compose(kf, Xf, gs.set(1, 1, 1)).invert();
  }
  clone() {
    return new this.constructor().copy(this);
  }
}
const Zr = /* @__PURE__ */ new st(), qS = /* @__PURE__ */ new ae(), ZS = /* @__PURE__ */ new ae();
class Ti extends zM {
  /**
   * 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, s = 0.1, a = 2e3) {
    super(), this.isPerspectiveCamera = !0, this.type = "PerspectiveCamera", this.fov = t, this.zoom = 1, this.near = s, this.far = a, 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 = Vc * 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(Uc * 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 Vc * 2 * Math.atan(
      Math.tan(Uc * 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, s) {
    Zr.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse), e.set(Zr.x, Zr.y).multiplyScalar(-t / Zr.z), Zr.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse), s.set(Zr.x, Zr.y).multiplyScalar(-t / Zr.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, qS, ZS), e.subVectors(ZS, qS);
  }
  /**
   * 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, s, a, o, c) {
    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 = s, this.view.offsetY = a, this.view.width = o, this.view.height = c, 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(Uc * 0.5 * this.fov) / this.zoom, s = 2 * e, a = this.aspect * s, o = -0.5 * a;
    const c = this.view;
    if (this.view !== null && this.view.enabled) {
      const d = c.fullWidth, h = c.fullHeight;
      o += c.offsetX * a / d, e -= c.offsetY * s / h, a *= c.width / d, s *= c.height / h;
    }
    const u = this.filmOffset;
    u !== 0 && (o += t * u / this.getFilmWidth()), this.projectionMatrix.makePerspective(o, o + a, e, e - s, 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;
  }
}
class ns extends zM {
  /**
   * 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, s = 1, a = -1, o = 0.1, c = 2e3) {
    super(), this.isOrthographicCamera = !0, this.type = "OrthographicCamera", this.zoom = 1, this.view = null, this.left = t, this.right = e, this.top = s, this.bottom = a, this.near = o, this.far = c, 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, s, a, o, c) {
    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 = s, this.view.offsetY = a, this.view.width = o, this.view.height = c, 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), s = (this.right + this.left) / 2, a = (this.top + this.bottom) / 2;
    let o = s - t, c = s + t, u = a + e, d = a - e;
    if (this.view !== null && this.view.enabled) {
      const h = (this.right - this.left) / this.view.fullWidth / this.zoom, m = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
      o += h * this.view.offsetX, c = o + h * this.view.width, u -= m * this.view.offsetY, d = u - m * this.view.height;
    }
    this.projectionMatrix.makeOrthographic(o, c, u, d, 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 k3 extends G3 {
  /**
   * Constructs a new directional light shadow.
   */
  constructor() {
    super(new ns(-5, 5, 5, -5, 0.5, 500)), this.isDirectionalLightShadow = !0;
  }
}
class md extends iv {
  /**
   * 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(Tn.DEFAULT_UP), this.updateMatrix(), this.target = new Tn(), this.shadow = new k3();
  }
  dispose() {
    super.dispose(), this.shadow.dispose();
  }
  copy(t) {
    return super.copy(t), this.target = t.target.clone(), this.shadow = t.shadow.clone(), this;
  }
  toJSON(t) {
    const e = super.toJSON(t);
    return e.object.shadow = this.shadow.toJSON(), e.object.target = this.target.uuid, e;
  }
}
class X3 extends iv {
  /**
   * 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 sv extends In {
  /**
   * 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;
  }
}
const Zo = -90, $o = 1;
class W3 extends Tn {
  /**
   * 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, s) {
    super(), this.type = "CubeCamera", this.renderTarget = s, this.coordinateSystem = null, this.activeMipmapLevel = 0;
    const a = new Ti(Zo, $o, t, e);
    a.layers = this.layers, this.add(a);
    const o = new Ti(Zo, $o, t, e);
    o.layers = this.layers, this.add(o);
    const c = new Ti(Zo, $o, t, e);
    c.layers = this.layers, this.add(c);
    const u = new Ti(Zo, $o, t, e);
    u.layers = this.layers, this.add(u);
    const d = new Ti(Zo, $o, t, e);
    d.layers = this.layers, this.add(d);
    const h = new Ti(Zo, $o, 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(), [s, a, o, c, u, d] = e;
    for (const h of e) this.remove(h);
    if (t === Ms)
      s.up.set(0, 1, 0), s.lookAt(1, 0, 0), a.up.set(0, 1, 0), a.lookAt(-1, 0, 0), o.up.set(0, 0, -1), o.lookAt(0, 1, 0), c.up.set(0, 0, 1), c.lookAt(0, -1, 0), u.up.set(0, 1, 0), u.lookAt(0, 0, 1), d.up.set(0, 1, 0), d.lookAt(0, 0, -1);
    else if (t === Hc)
      s.up.set(0, -1, 0), s.lookAt(-1, 0, 0), a.up.set(0, -1, 0), a.lookAt(1, 0, 0), o.up.set(0, 0, 1), o.lookAt(0, 1, 0), c.up.set(0, 0, -1), c.lookAt(0, -1, 0), u.up.set(0, -1, 0), u.lookAt(0, 0, 1), d.up.set(0, -1, 0), d.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: s, activeMipmapLevel: a } = this;
    this.coordinateSystem !== t.coordinateSystem && (this.coordinateSystem = t.coordinateSystem, this.updateCoordinateSystem());
    const [o, c, u, d, h, m] = this.children, p = t.getRenderTarget(), g = t.getActiveCubeFace(), _ = t.getActiveMipmapLevel(), x = t.xr.enabled;
    t.xr.enabled = !1;
    const A = s.texture.generateMipmaps;
    s.texture.generateMipmaps = !1;
    let b = !1;
    t.isWebGLRenderer === !0 ? b = t.state.buffers.depth.getReversed() : b = t.reversedDepthBuffer, t.setRenderTarget(s, 0, a), b && t.autoClear === !1 && t.clearDepth(), t.render(e, o), t.setRenderTarget(s, 1, a), b && t.autoClear === !1 && t.clearDepth(), t.render(e, c), t.setRenderTarget(s, 2, a), b && t.autoClear === !1 && t.clearDepth(), t.render(e, u), t.setRenderTarget(s, 3, a), b && t.autoClear === !1 && t.clearDepth(), t.render(e, d), t.setRenderTarget(s, 4, a), b && t.autoClear === !1 && t.clearDepth(), t.render(e, h), s.texture.generateMipmaps = A, t.setRenderTarget(s, 5, a), b && t.autoClear === !1 && t.clearDepth(), t.render(e, m), t.setRenderTarget(p, g, _), t.xr.enabled = x, s.texture.needsPMREMUpdate = !0;
  }
}
class Y3 extends Ti {
  /**
   * 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 v0 extends LM {
  /**
   * 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, s = 1) {
    super(t, e), this.isInstancedInterleavedBuffer = !0, this.meshPerAttribute = s;
  }
  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 $S {
  /**
   * 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, s = 0) {
    this.radius = t, this.phi = e, this.theta = s;
  }
  /**
   * 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, s) {
    return this.radius = t, this.phi = e, this.theta = s, 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 = ge(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, s) {
    return this.radius = Math.sqrt(t * t + e * e + s * s), this.radius === 0 ? (this.theta = 0, this.phi = 0) : (this.theta = Math.atan2(t, s), this.phi = Math.acos(ge(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);
  }
}
const KS = /* @__PURE__ */ new st(), Wf = /* @__PURE__ */ new st(), Ko = /* @__PURE__ */ new st(), Qo = /* @__PURE__ */ new st(), Zm = /* @__PURE__ */ new st(), j3 = /* @__PURE__ */ new st(), q3 = /* @__PURE__ */ new st();
class Z3 {
  /**
   * 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 st(), e = new st()) {
    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) {
    KS.subVectors(t, this.start), Wf.subVectors(this.end, this.start);
    const s = Wf.dot(Wf);
    let o = Wf.dot(KS) / s;
    return e && (o = ge(o, 0, 1)), o;
  }
  /**
   * 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, s) {
    const a = this.closestPointToPointParameter(t, e);
    return this.delta(s).multiplyScalar(a).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 = j3, s = q3) {
    const a = 10000000000000001e-32;
    let o, c;
    const u = this.start, d = t.start, h = this.end, m = t.end;
    Ko.subVectors(h, u), Qo.subVectors(m, d), Zm.subVectors(u, d);
    const p = Ko.dot(Ko), g = Qo.dot(Qo), _ = Qo.dot(Zm);
    if (p <= a && g <= a)
      return e.copy(u), s.copy(d), e.sub(s), e.dot(e);
    if (p <= a)
      o = 0, c = _ / g, c = ge(c, 0, 1);
    else {
      const x = Ko.dot(Zm);
      if (g <= a)
        c = 0, o = ge(-x / p, 0, 1);
      else {
        const A = Ko.dot(Qo), b = p * g - A * A;
        b !== 0 ? o = ge((A * _ - x * g) / b, 0, 1) : o = 0, c = (A * o + _) / g, c < 0 ? (c = 0, o = ge(-x / p, 0, 1)) : c > 1 && (c = 1, o = ge((A - x) / p, 0, 1));
      }
    }
    return e.copy(u).addScaledVector(Ko, o), s.copy(d).addScaledVector(Qo, c), e.distanceToSquared(s);
  }
  /**
   * 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 QS = /* @__PURE__ */ new st();
let Yf, $m;
class $3 extends Tn {
  /**
   * 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 st(0, 0, 1), e = new st(0, 0, 0), s = 1, a = 16776960, o = s * 0.2, c = o * 0.2) {
    super(), this.type = "ArrowHelper", Yf === void 0 && (Yf = new In(), Yf.setAttribute("position", new _n([0, 0, 0, 0, 1, 0], 3)), $m = new Zd(0.5, 1, 5, 1), $m.translate(0, -0.5, 0)), this.position.copy(e), this.line = new Gc(Yf, new jd({ color: a, toneMapped: !1 })), this.line.matrixAutoUpdate = !1, this.add(this.line), this.cone = new Ln($m, new Yd({ color: a, toneMapped: !1 })), this.cone.matrixAutoUpdate = !1, this.add(this.cone), this.setDirection(t), this.setLength(s, o, c);
  }
  /**
   * 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 {
      QS.set(t.z, 0, -t.x).normalize();
      const e = Math.acos(t.y);
      this.quaternion.setFromAxisAngle(QS, 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, s = e * 0.2) {
    this.line.scale.set(1, Math.max(1e-4, t - e), 1), this.line.updateMatrix(), this.cone.scale.set(s, e, s), 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();
  }
}
class K3 extends qa {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLElement} 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 {HTMLElement} element - The DOM element to connect to.
   */
  connect(t) {
    if (t === void 0) {
      de("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 JS(n, t, e, s) {
  const a = Q3(s);
  switch (e) {
    // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
    case bM:
      return n * t;
    case X0:
      return n * t / a.components * a.byteLength;
    case W0:
      return n * t / a.components * a.byteLength;
    case hl:
      return n * t * 2 / a.components * a.byteLength;
    case Y0:
      return n * t * 2 / a.components * a.byteLength;
    case MM:
      return n * t * 3 / a.components * a.byteLength;
    case Ni:
      return n * t * 4 / a.components * a.byteLength;
    case j0:
      return n * t * 4 / a.components * a.byteLength;
    // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
    case fd:
    case dd:
      return Math.floor((n + 3) / 4) * Math.floor((t + 3) / 4) * 8;
    case hd:
    case pd:
      return Math.floor((n + 3) / 4) * Math.floor((t + 3) / 4) * 16;
    // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
    case zg:
    case Hg:
      return Math.max(n, 16) * Math.max(t, 8) / 4;
    case Bg:
    case Fg:
      return Math.max(n, 8) * Math.max(t, 8) / 2;
    // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
    case Vg:
    case Gg:
    case Xg:
    case Wg:
      return Math.floor((n + 3) / 4) * Math.floor((t + 3) / 4) * 8;
    case kg:
    case Yg:
    case jg:
      return Math.floor((n + 3) / 4) * Math.floor((t + 3) / 4) * 16;
    // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
    case qg:
      return Math.floor((n + 3) / 4) * Math.floor((t + 3) / 4) * 16;
    case Zg:
      return Math.floor((n + 4) / 5) * Math.floor((t + 3) / 4) * 16;
    case $g:
      return Math.floor((n + 4) / 5) * Math.floor((t + 4) / 5) * 16;
    case Kg:
      return Math.floor((n + 5) / 6) * Math.floor((t + 4) / 5) * 16;
    case Qg:
      return Math.floor((n + 5) / 6) * Math.floor((t + 5) / 6) * 16;
    case Jg:
      return Math.floor((n + 7) / 8) * Math.floor((t + 4) / 5) * 16;
    case t0:
      return Math.floor((n + 7) / 8) * Math.floor((t + 5) / 6) * 16;
    case e0:
      return Math.floor((n + 7) / 8) * Math.floor((t + 7) / 8) * 16;
    case n0:
      return Math.floor((n + 9) / 10) * Math.floor((t + 4) / 5) * 16;
    case i0:
      return Math.floor((n + 9) / 10) * Math.floor((t + 5) / 6) * 16;
    case s0:
      return Math.floor((n + 9) / 10) * Math.floor((t + 7) / 8) * 16;
    case r0:
      return Math.floor((n + 9) / 10) * Math.floor((t + 9) / 10) * 16;
    case a0:
      return Math.floor((n + 11) / 12) * Math.floor((t + 9) / 10) * 16;
    case o0:
      return Math.floor((n + 11) / 12) * Math.floor((t + 11) / 12) * 16;
    // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
    case l0:
    case c0:
    case u0:
      return Math.ceil(n / 4) * Math.ceil(t / 4) * 16;
    // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
    case f0:
    case d0:
      return Math.ceil(n / 4) * Math.ceil(t / 4) * 8;
    case h0:
    case p0:
      return Math.ceil(n / 4) * Math.ceil(t / 4) * 16;
  }
  throw new Error(
    `Unable to determine texture byte length for ${e} format.`
  );
}
function Q3(n) {
  switch (n) {
    case Ci:
    case _M:
      return { byteLength: 1, components: 1 };
    case zc:
    case yM:
    case dr:
      return { byteLength: 2, components: 1 };
    case G0:
    case k0:
      return { byteLength: 2, components: 4 };
    case Cs:
    case V0:
    case Di:
      return { byteLength: 4, components: 1 };
    case xM:
    case SM:
      return { byteLength: 4, components: 3 };
  }
  throw new Error(`Unknown texture type ${n}.`);
}
typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: {
  revision: F0
} }));
typeof window < "u" && (window.__THREE__ ? de("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = F0);
/**
 * @license
 * Copyright 2010-2026 Three.js Authors
 * SPDX-License-Identifier: MIT
 */
function FM() {
  let n = null, t = !1, e = null, s = null;
  function a(o, c) {
    e(o, c), s = n.requestAnimationFrame(a);
  }
  return {
    start: function() {
      t !== !0 && e !== null && (s = n.requestAnimationFrame(a), t = !0);
    },
    stop: function() {
      n.cancelAnimationFrame(s), t = !1;
    },
    setAnimationLoop: function(o) {
      e = o;
    },
    setContext: function(o) {
      n = o;
    }
  };
}
function J3(n) {
  const t = /* @__PURE__ */ new WeakMap();
  function e(u, d) {
    const h = u.array, m = u.usage, p = h.byteLength, g = n.createBuffer();
    n.bindBuffer(d, g), n.bufferData(d, h, m), u.onUploadCallback();
    let _;
    if (h instanceof Float32Array)
      _ = n.FLOAT;
    else if (typeof Float16Array < "u" && h instanceof Float16Array)
      _ = n.HALF_FLOAT;
    else if (h instanceof Uint16Array)
      u.isFloat16BufferAttribute ? _ = n.HALF_FLOAT : _ = n.UNSIGNED_SHORT;
    else if (h instanceof Int16Array)
      _ = n.SHORT;
    else if (h instanceof Uint32Array)
      _ = n.UNSIGNED_INT;
    else if (h instanceof Int32Array)
      _ = n.INT;
    else if (h instanceof Int8Array)
      _ = n.BYTE;
    else if (h instanceof Uint8Array)
      _ = n.UNSIGNED_BYTE;
    else if (h instanceof Uint8ClampedArray)
      _ = n.UNSIGNED_BYTE;
    else
      throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + h);
    return {
      buffer: g,
      type: _,
      bytesPerElement: h.BYTES_PER_ELEMENT,
      version: u.version,
      size: p
    };
  }
  function s(u, d, h) {
    const m = d.array, p = d.updateRanges;
    if (n.bindBuffer(h, u), p.length === 0)
      n.bufferSubData(h, 0, m);
    else {
      p.sort((_, x) => _.start - x.start);
      let g = 0;
      for (let _ = 1; _ < p.length; _++) {
        const x = p[g], A = p[_];
        A.start <= x.start + x.count + 1 ? x.count = Math.max(
          x.count,
          A.start + A.count - x.start
        ) : (++g, p[g] = A);
      }
      p.length = g + 1;
      for (let _ = 0, x = p.length; _ < x; _++) {
        const A = p[_];
        n.bufferSubData(
          h,
          A.start * m.BYTES_PER_ELEMENT,
          m,
          A.start,
          A.count
        );
      }
      d.clearUpdateRanges();
    }
    d.onUploadCallback();
  }
  function a(u) {
    return u.isInterleavedBufferAttribute && (u = u.data), t.get(u);
  }
  function o(u) {
    u.isInterleavedBufferAttribute && (u = u.data);
    const d = t.get(u);
    d && (n.deleteBuffer(d.buffer), t.delete(u));
  }
  function c(u, d) {
    if (u.isInterleavedBufferAttribute && (u = u.data), u.isGLBufferAttribute) {
      const m = t.get(u);
      (!m || m.version < u.version) && t.set(u, {
        buffer: u.buffer,
        type: u.type,
        bytesPerElement: u.elementSize,
        version: u.version
      });
      return;
    }
    const h = t.get(u);
    if (h === void 0)
      t.set(u, e(u, d));
    else if (h.version < u.version) {
      if (h.size !== u.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.");
      s(h.buffer, u, d), h.version = u.version;
    }
  }
  return {
    get: a,
    remove: o,
    update: c
  };
}
var tC = `#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`, eC = `#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`, nC = `#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`, iC = `#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`, sC = `#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`, rC = `#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`, aC = `#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`, oC = `#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`, lC = `#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;
	vec4 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 );
	}
#endif`, cC = `#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`, uC = `vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`, fC = `vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`, dC = `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`, hC = `#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`, pC = `#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`, mC = `#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`, gC = `#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`, vC = `#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`, _C = `#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`, yC = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#endif`, xC = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#endif`, SC = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec4 vColor;
#endif`, bC = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec4( 1.0 );
#endif
#ifdef USE_COLOR_ALPHA
	vColor *= color;
#elif defined( USE_COLOR )
	vColor.rgb *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.rgb *= instanceColor.rgb;
#endif
#ifdef USE_BATCHING_COLOR
	vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );
#endif`, MC = `#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 );
}
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`, EC = `#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`, wC = `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`, AC = `#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`, TC = `#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`, CC = `#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
		emissiveColor = sRGBTransferEOTF( emissiveColor );
	#endif
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`, RC = `#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`, DC = "gl_FragColor = linearToOutputTexel( gl_FragColor );", NC = `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 );
}`, OC = `#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 ) );
		#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
#endif`, LC = `#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`, UC = `#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`, PC = `#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`, IC = `#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`, BC = `#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`, zC = `#ifdef USE_FOG
	varying float vFogDepth;
#endif`, FC = `#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`, HC = `#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`, VC = `#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
}`, GC = `#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`, kC = `LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`, XC = `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`, WC = `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`, YC = `#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, pow4( 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`, jC = `ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`, qC = `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`, ZC = `BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`, $C = `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`, KC = `PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );
material.metalness = 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 = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;
	material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = vec3( 0.04 );
	material.specularColorBlended = mix( material.specularColor, 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.0001, 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`, QC = `uniform sampler2D dfgLUT;
struct PhysicalMaterial {
	vec3 diffuseColor;
	vec3 diffuseContribution;
	vec3 specularColor;
	vec3 specularColorBlended;
	float roughness;
	float metalness;
	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;
		vec3 iridescenceFresnelDielectric;
		vec3 iridescenceFresnelMetallic;
	#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 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.specularColorBlended;
	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 * transpose( 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 rInv = 1.0 / ( roughness + 0.1 );
	float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;
	float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;
	float DG = exp( a * dotNV + b );
	return saturate( DG );
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
	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
	float dotNV = saturate( dot( normal, viewDir ) );
	vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;
	#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;
}
vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;
	vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;
	vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;
	vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;
	float Ess_V = dfgV.x + dfgV.y;
	float Ess_L = dfgL.x + dfgL.y;
	float Ems_V = 1.0 - Ess_V;
	float Ems_L = 1.0 - Ess_L;
	vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;
	vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );
	float compensationFactor = Ems_V * Ems_L;
	vec3 multiScatter = Fms * compensationFactor;
	return singleScatter + multiScatter;
}
#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.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
		#ifdef USE_CLEARCOAT
			vec3 Ncc = geometryClearcoatNormal;
			vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );
			vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );
			vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );
			mat3 mInvClearcoat = mat3(
				vec3( t1Clearcoat.x, 0, t1Clearcoat.y ),
				vec3(             0, 1,             0 ),
				vec3( t1Clearcoat.z, 0, t1Clearcoat.w )
			);
			vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;
			clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );
		#endif
	}
#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 );
 
 		float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
 		float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );
 
 		float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );
 
 		irradiance *= sheenEnergyComp;
 
 	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );
}
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 ) {
	vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );
	#ifdef USE_SHEEN
		float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
		float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
		diffuse *= sheenEnergyComp;
	#endif
	reflectedLight.indirectDiffuse += diffuse;
}
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 ) * RECIPROCAL_PI;
 	#endif
	vec3 singleScatteringDielectric = vec3( 0.0 );
	vec3 multiScatteringDielectric = vec3( 0.0 );
	vec3 singleScatteringMetallic = vec3( 0.0 );
	vec3 multiScatteringMetallic = vec3( 0.0 );
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );
		computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );
	#endif
	vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );
	vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );
	vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;
	vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	vec3 indirectSpecular = radiance * singleScattering;
	indirectSpecular += multiScattering * cosineWeightedIrradiance;
	vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;
	#ifdef USE_SHEEN
		float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
		float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;
		indirectSpecular *= sheenEnergyComp;
		indirectDiffuse *= sheenEnergyComp;
	#endif
	reflectedLight.indirectSpecular += indirectSpecular;
	reflectedLight.indirectDiffuse += indirectDiffuse;
}
#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 );
}`, JC = `
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.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );
		material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );
		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 ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )
		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`, tR = `#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( ENVMAP_TYPE_CUBE_UV )
		#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )
			iblIrradiance += getIBLIrradiance( geometryNormal );
		#endif
	#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`, eR = `#if defined( RE_IndirectDiffuse )
	#if defined( LAMBERT ) || defined( PHONG )
		irradiance += iblIrradiance;
	#endif
	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`, nR = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`, iR = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`, sR = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`, rR = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`, aR = `#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`, oR = `#ifdef USE_MAP
	uniform sampler2D map;
#endif`, lR = `#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`, cR = `#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`, uR = `float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`, fR = `#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`, dR = `#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`, hR = `#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`, pR = `#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`, mR = `#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`, gR = `#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`, vR = `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;`, _R = `#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`, yR = `#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`, xR = `#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`, SR = `#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`, bR = `#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`, MR = `#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`, ER = `#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`, wR = `#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`, AR = `#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`, TR = `#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`, CR = `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 ) {
	#ifdef USE_REVERSED_DEPTH_BUFFER
	
		return depth * ( far - near ) - far;
	#else
		return depth * ( near - far ) - near;
	#endif
}
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 ) {
	
	#ifdef USE_REVERSED_DEPTH_BUFFER
		return ( near * far ) / ( ( near - far ) * depth - near );
	#else
		return ( near * far ) / ( ( far - near ) * depth - far );
	#endif
}`, RR = `#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`, DR = `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;`, NR = `#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`, OR = `#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`, LR = `float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`, UR = `#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`, PR = `#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
		#if defined( SHADOWMAP_TYPE_PCF )
			uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		#else
			uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		#endif
		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
		#if defined( SHADOWMAP_TYPE_PCF )
			uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		#else
			uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		#endif
		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
		#if defined( SHADOWMAP_TYPE_PCF )
			uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		#elif defined( SHADOWMAP_TYPE_BASIC )
			uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		#endif
		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
	#if defined( SHADOWMAP_TYPE_PCF )
		float interleavedGradientNoise( vec2 position ) {
			return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );
		}
		vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {
			const float goldenAngle = 2.399963229728653;
			float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );
			float theta = float( sampleIndex ) * goldenAngle + phi;
			return vec2( cos( theta ), sin( theta ) ) * r;
		}
	#endif
	#if defined( SHADOWMAP_TYPE_PCF )
		float getShadow( sampler2DShadow 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 ) {
				vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
				float radius = shadowRadius * texelSize.x;
				float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;
				shadow = (
					texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +
					texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +
					texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +
					texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +
					texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )
				) * 0.2;
			}
			return mix( 1.0, shadow, shadowIntensity );
		}
	#elif defined( SHADOWMAP_TYPE_VSM )
		float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
			float shadow = 1.0;
			shadowCoord.xyz /= shadowCoord.w;
			#ifdef USE_REVERSED_DEPTH_BUFFER
				shadowCoord.z -= shadowBias;
			#else
				shadowCoord.z += shadowBias;
			#endif
			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 ) {
				vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;
				float mean = distribution.x;
				float variance = distribution.y * distribution.y;
				#ifdef USE_REVERSED_DEPTH_BUFFER
					float hard_shadow = step( mean, shadowCoord.z );
				#else
					float hard_shadow = step( shadowCoord.z, mean );
				#endif
				
				if ( hard_shadow == 1.0 ) {
					shadow = 1.0;
				} else {
					variance = max( variance, 0.0000001 );
					float d = shadowCoord.z - mean;
					float p_max = variance / ( variance + d * d );
					p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );
					shadow = max( hard_shadow, p_max );
				}
			}
			return mix( 1.0, shadow, shadowIntensity );
		}
	#else
		float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
			float shadow = 1.0;
			shadowCoord.xyz /= shadowCoord.w;
			#ifdef USE_REVERSED_DEPTH_BUFFER
				shadowCoord.z -= shadowBias;
			#else
				shadowCoord.z += shadowBias;
			#endif
			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 ) {
				float depth = texture2D( shadowMap, shadowCoord.xy ).r;
				#ifdef USE_REVERSED_DEPTH_BUFFER
					shadow = step( depth, shadowCoord.z );
				#else
					shadow = step( shadowCoord.z, depth );
				#endif
			}
			return mix( 1.0, shadow, shadowIntensity );
		}
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	#if defined( SHADOWMAP_TYPE_PCF )
	float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		vec3 bd3D = normalize( lightToPosition );
		vec3 absVec = abs( lightToPosition );
		float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );
		if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {
			#ifdef USE_REVERSED_DEPTH_BUFFER
				float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
				dp -= shadowBias;
			#else
				float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
				dp += shadowBias;
			#endif
			float texelSize = shadowRadius / shadowMapSize.x;
			vec3 absDir = abs( bd3D );
			vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );
			tangent = normalize( cross( bd3D, tangent ) );
			vec3 bitangent = cross( bd3D, tangent );
			float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;
			vec2 sample0 = vogelDiskSample( 0, 5, phi );
			vec2 sample1 = vogelDiskSample( 1, 5, phi );
			vec2 sample2 = vogelDiskSample( 2, 5, phi );
			vec2 sample3 = vogelDiskSample( 3, 5, phi );
			vec2 sample4 = vogelDiskSample( 4, 5, phi );
			shadow = (
				texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +
				texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +
				texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +
				texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +
				texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )
			) * 0.2;
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	#elif defined( SHADOWMAP_TYPE_BASIC )
	float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		vec3 absVec = abs( lightToPosition );
		float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );
		if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {
			float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			float depth = textureCube( shadowMap, bd3D ).r;
			#ifdef USE_REVERSED_DEPTH_BUFFER
				depth = 1.0 - depth;
			#endif
			shadow = step( dp, depth );
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	#endif
	#endif
#endif`, IR = `#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`, BR = `#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`, zR = `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 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )
	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;
}`, FR = `#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`, HR = `#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`, VR = `#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`, GR = `#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`, kR = `float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`, XR = `#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`, WR = `#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`, YR = `#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; }`, jR = `#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.diffuseContribution, material.specularColorBlended, 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`, qR = `#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`, ZR = `#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`, $R = `#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`, KR = `#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`, QR = `#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 JR = `varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`, tD = `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>
}`, eD = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`, nD = `#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>
}`, iD = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`, sD = `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>
}`, rD = `#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;
}`, aD = `#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
}`, oD = `#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;
}`, lD = `#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#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 = vec4( dist, 0.0, 0.0, 1.0 );
}`, cD = `varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`, uD = `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>
}`, fD = `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>
}`, dD = `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>
}`, hD = `#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>
}`, pD = `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>
}`, mD = `#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>
}`, gD = `#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#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 <emissivemap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <envmap_physical_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>
}`, vD = `#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;
}`, _D = `#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>
}`, yD = `#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
}`, xD = `#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#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( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );
	#ifdef OPAQUE
		gl_FragColor.a = 1.0;
	#endif
}`, SD = `#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>
}`, bD = `#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#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 <emissivemap_pars_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <envmap_physical_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>
}`, MD = `#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
}`, ED = `#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 <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
 
		outgoingLight = outgoingLight + 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>
}`, wD = `#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>
}`, AD = `#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#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 <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>
}`, TD = `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>
}`, CD = `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>
}`, RD = `#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>
}`, DD = `uniform vec3 color;
uniform float opacity;
#include <common>
#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>
	#include <premultiplied_alpha_fragment>
}`, ND = `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>
}`, OD = `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>
}`, Ee = {
  alphahash_fragment: tC,
  alphahash_pars_fragment: eC,
  alphamap_fragment: nC,
  alphamap_pars_fragment: iC,
  alphatest_fragment: sC,
  alphatest_pars_fragment: rC,
  aomap_fragment: aC,
  aomap_pars_fragment: oC,
  batching_pars_vertex: lC,
  batching_vertex: cC,
  begin_vertex: uC,
  beginnormal_vertex: fC,
  bsdfs: dC,
  iridescence_fragment: hC,
  bumpmap_pars_fragment: pC,
  clipping_planes_fragment: mC,
  clipping_planes_pars_fragment: gC,
  clipping_planes_pars_vertex: vC,
  clipping_planes_vertex: _C,
  color_fragment: yC,
  color_pars_fragment: xC,
  color_pars_vertex: SC,
  color_vertex: bC,
  common: MC,
  cube_uv_reflection_fragment: EC,
  defaultnormal_vertex: wC,
  displacementmap_pars_vertex: AC,
  displacementmap_vertex: TC,
  emissivemap_fragment: CC,
  emissivemap_pars_fragment: RC,
  colorspace_fragment: DC,
  colorspace_pars_fragment: NC,
  envmap_fragment: OC,
  envmap_common_pars_fragment: LC,
  envmap_pars_fragment: UC,
  envmap_pars_vertex: PC,
  envmap_physical_pars_fragment: YC,
  envmap_vertex: IC,
  fog_vertex: BC,
  fog_pars_vertex: zC,
  fog_fragment: FC,
  fog_pars_fragment: HC,
  gradientmap_pars_fragment: VC,
  lightmap_pars_fragment: GC,
  lights_lambert_fragment: kC,
  lights_lambert_pars_fragment: XC,
  lights_pars_begin: WC,
  lights_toon_fragment: jC,
  lights_toon_pars_fragment: qC,
  lights_phong_fragment: ZC,
  lights_phong_pars_fragment: $C,
  lights_physical_fragment: KC,
  lights_physical_pars_fragment: QC,
  lights_fragment_begin: JC,
  lights_fragment_maps: tR,
  lights_fragment_end: eR,
  logdepthbuf_fragment: nR,
  logdepthbuf_pars_fragment: iR,
  logdepthbuf_pars_vertex: sR,
  logdepthbuf_vertex: rR,
  map_fragment: aR,
  map_pars_fragment: oR,
  map_particle_fragment: lR,
  map_particle_pars_fragment: cR,
  metalnessmap_fragment: uR,
  metalnessmap_pars_fragment: fR,
  morphinstance_vertex: dR,
  morphcolor_vertex: hR,
  morphnormal_vertex: pR,
  morphtarget_pars_vertex: mR,
  morphtarget_vertex: gR,
  normal_fragment_begin: vR,
  normal_fragment_maps: _R,
  normal_pars_fragment: yR,
  normal_pars_vertex: xR,
  normal_vertex: SR,
  normalmap_pars_fragment: bR,
  clearcoat_normal_fragment_begin: MR,
  clearcoat_normal_fragment_maps: ER,
  clearcoat_pars_fragment: wR,
  iridescence_pars_fragment: AR,
  opaque_fragment: TR,
  packing: CR,
  premultiplied_alpha_fragment: RR,
  project_vertex: DR,
  dithering_fragment: NR,
  dithering_pars_fragment: OR,
  roughnessmap_fragment: LR,
  roughnessmap_pars_fragment: UR,
  shadowmap_pars_fragment: PR,
  shadowmap_pars_vertex: IR,
  shadowmap_vertex: BR,
  shadowmask_pars_fragment: zR,
  skinbase_vertex: FR,
  skinning_pars_vertex: HR,
  skinning_vertex: VR,
  skinnormal_vertex: GR,
  specularmap_fragment: kR,
  specularmap_pars_fragment: XR,
  tonemapping_fragment: WR,
  tonemapping_pars_fragment: YR,
  transmission_fragment: jR,
  transmission_pars_fragment: qR,
  uv_pars_fragment: ZR,
  uv_pars_vertex: $R,
  uv_vertex: KR,
  worldpos_vertex: QR,
  background_vert: JR,
  background_frag: tD,
  backgroundCube_vert: eD,
  backgroundCube_frag: nD,
  cube_vert: iD,
  cube_frag: sD,
  depth_vert: rD,
  depth_frag: aD,
  distance_vert: oD,
  distance_frag: lD,
  equirect_vert: cD,
  equirect_frag: uD,
  linedashed_vert: fD,
  linedashed_frag: dD,
  meshbasic_vert: hD,
  meshbasic_frag: pD,
  meshlambert_vert: mD,
  meshlambert_frag: gD,
  meshmatcap_vert: vD,
  meshmatcap_frag: _D,
  meshnormal_vert: yD,
  meshnormal_frag: xD,
  meshphong_vert: SD,
  meshphong_frag: bD,
  meshphysical_vert: MD,
  meshphysical_frag: ED,
  meshtoon_vert: wD,
  meshtoon_frag: AD,
  points_vert: TD,
  points_frag: CD,
  shadow_vert: RD,
  shadow_frag: DD,
  sprite_vert: ND,
  sprite_frag: OD
}, Gt = {
  common: {
    diffuse: { value: /* @__PURE__ */ new we(16777215) },
    opacity: { value: 1 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new Me() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Me() },
    alphaTest: { value: 0 }
  },
  specularmap: {
    specularMap: { value: null },
    specularMapTransform: { value: /* @__PURE__ */ new Me() }
  },
  envmap: {
    envMap: { value: null },
    envMapRotation: { value: /* @__PURE__ */ new Me() },
    flipEnvMap: { value: -1 },
    reflectivity: { value: 1 },
    // basic, lambert, phong
    ior: { value: 1.5 },
    // physical
    refractionRatio: { value: 0.98 },
    // basic, lambert, phong
    dfgLUT: { value: null }
    // DFG LUT for physically-based rendering
  },
  aomap: {
    aoMap: { value: null },
    aoMapIntensity: { value: 1 },
    aoMapTransform: { value: /* @__PURE__ */ new Me() }
  },
  lightmap: {
    lightMap: { value: null },
    lightMapIntensity: { value: 1 },
    lightMapTransform: { value: /* @__PURE__ */ new Me() }
  },
  bumpmap: {
    bumpMap: { value: null },
    bumpMapTransform: { value: /* @__PURE__ */ new Me() },
    bumpScale: { value: 1 }
  },
  normalmap: {
    normalMap: { value: null },
    normalMapTransform: { value: /* @__PURE__ */ new Me() },
    normalScale: { value: /* @__PURE__ */ new ae(1, 1) }
  },
  displacementmap: {
    displacementMap: { value: null },
    displacementMapTransform: { value: /* @__PURE__ */ new Me() },
    displacementScale: { value: 1 },
    displacementBias: { value: 0 }
  },
  emissivemap: {
    emissiveMap: { value: null },
    emissiveMapTransform: { value: /* @__PURE__ */ new Me() }
  },
  metalnessmap: {
    metalnessMap: { value: null },
    metalnessMapTransform: { value: /* @__PURE__ */ new Me() }
  },
  roughnessmap: {
    roughnessMap: { value: null },
    roughnessMapTransform: { value: /* @__PURE__ */ new Me() }
  },
  gradientmap: {
    gradientMap: { value: null }
  },
  fog: {
    fogDensity: { value: 25e-5 },
    fogNear: { value: 1 },
    fogFar: { value: 2e3 },
    fogColor: { value: /* @__PURE__ */ new we(16777215) }
  },
  lights: {
    ambientLightColor: { value: [] },
    lightProbe: { value: [] },
    directionalLights: { value: [], properties: {
      direction: {},
      color: {}
    } },
    directionalLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    directionalShadowMatrix: { value: [] },
    spotLights: { value: [], properties: {
      color: {},
      position: {},
      direction: {},
      distance: {},
      coneCos: {},
      penumbraCos: {},
      decay: {}
    } },
    spotLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {}
    } },
    spotLightMap: { value: [] },
    spotLightMatrix: { value: [] },
    pointLights: { value: [], properties: {
      color: {},
      position: {},
      decay: {},
      distance: {}
    } },
    pointLightShadows: { value: [], properties: {
      shadowIntensity: 1,
      shadowBias: {},
      shadowNormalBias: {},
      shadowRadius: {},
      shadowMapSize: {},
      shadowCameraNear: {},
      shadowCameraFar: {}
    } },
    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 we(16777215) },
    opacity: { value: 1 },
    size: { value: 1 },
    scale: { value: 1 },
    map: { value: null },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Me() },
    alphaTest: { value: 0 },
    uvTransform: { value: /* @__PURE__ */ new Me() }
  },
  sprite: {
    diffuse: { value: /* @__PURE__ */ new we(16777215) },
    opacity: { value: 1 },
    center: { value: /* @__PURE__ */ new ae(0.5, 0.5) },
    rotation: { value: 0 },
    map: { value: null },
    mapTransform: { value: /* @__PURE__ */ new Me() },
    alphaMap: { value: null },
    alphaMapTransform: { value: /* @__PURE__ */ new Me() },
    alphaTest: { value: 0 }
  }
}, di = {
  basic: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.specularmap,
      Gt.envmap,
      Gt.aomap,
      Gt.lightmap,
      Gt.fog
    ]),
    vertexShader: Ee.meshbasic_vert,
    fragmentShader: Ee.meshbasic_frag
  },
  lambert: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.specularmap,
      Gt.envmap,
      Gt.aomap,
      Gt.lightmap,
      Gt.emissivemap,
      Gt.bumpmap,
      Gt.normalmap,
      Gt.displacementmap,
      Gt.fog,
      Gt.lights,
      {
        emissive: { value: /* @__PURE__ */ new we(0) },
        envMapIntensity: { value: 1 }
      }
    ]),
    vertexShader: Ee.meshlambert_vert,
    fragmentShader: Ee.meshlambert_frag
  },
  phong: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.specularmap,
      Gt.envmap,
      Gt.aomap,
      Gt.lightmap,
      Gt.emissivemap,
      Gt.bumpmap,
      Gt.normalmap,
      Gt.displacementmap,
      Gt.fog,
      Gt.lights,
      {
        emissive: { value: /* @__PURE__ */ new we(0) },
        specular: { value: /* @__PURE__ */ new we(1118481) },
        shininess: { value: 30 },
        envMapIntensity: { value: 1 }
      }
    ]),
    vertexShader: Ee.meshphong_vert,
    fragmentShader: Ee.meshphong_frag
  },
  standard: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.envmap,
      Gt.aomap,
      Gt.lightmap,
      Gt.emissivemap,
      Gt.bumpmap,
      Gt.normalmap,
      Gt.displacementmap,
      Gt.roughnessmap,
      Gt.metalnessmap,
      Gt.fog,
      Gt.lights,
      {
        emissive: { value: /* @__PURE__ */ new we(0) },
        roughness: { value: 1 },
        metalness: { value: 0 },
        envMapIntensity: { value: 1 }
      }
    ]),
    vertexShader: Ee.meshphysical_vert,
    fragmentShader: Ee.meshphysical_frag
  },
  toon: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.aomap,
      Gt.lightmap,
      Gt.emissivemap,
      Gt.bumpmap,
      Gt.normalmap,
      Gt.displacementmap,
      Gt.gradientmap,
      Gt.fog,
      Gt.lights,
      {
        emissive: { value: /* @__PURE__ */ new we(0) }
      }
    ]),
    vertexShader: Ee.meshtoon_vert,
    fragmentShader: Ee.meshtoon_frag
  },
  matcap: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.bumpmap,
      Gt.normalmap,
      Gt.displacementmap,
      Gt.fog,
      {
        matcap: { value: null }
      }
    ]),
    vertexShader: Ee.meshmatcap_vert,
    fragmentShader: Ee.meshmatcap_frag
  },
  points: {
    uniforms: /* @__PURE__ */ si([
      Gt.points,
      Gt.fog
    ]),
    vertexShader: Ee.points_vert,
    fragmentShader: Ee.points_frag
  },
  dashed: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.fog,
      {
        scale: { value: 1 },
        dashSize: { value: 1 },
        totalSize: { value: 2 }
      }
    ]),
    vertexShader: Ee.linedashed_vert,
    fragmentShader: Ee.linedashed_frag
  },
  depth: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.displacementmap
    ]),
    vertexShader: Ee.depth_vert,
    fragmentShader: Ee.depth_frag
  },
  normal: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.bumpmap,
      Gt.normalmap,
      Gt.displacementmap,
      {
        opacity: { value: 1 }
      }
    ]),
    vertexShader: Ee.meshnormal_vert,
    fragmentShader: Ee.meshnormal_frag
  },
  sprite: {
    uniforms: /* @__PURE__ */ si([
      Gt.sprite,
      Gt.fog
    ]),
    vertexShader: Ee.sprite_vert,
    fragmentShader: Ee.sprite_frag
  },
  background: {
    uniforms: {
      uvTransform: { value: /* @__PURE__ */ new Me() },
      t2D: { value: null },
      backgroundIntensity: { value: 1 }
    },
    vertexShader: Ee.background_vert,
    fragmentShader: Ee.background_frag
  },
  backgroundCube: {
    uniforms: {
      envMap: { value: null },
      flipEnvMap: { value: -1 },
      backgroundBlurriness: { value: 0 },
      backgroundIntensity: { value: 1 },
      backgroundRotation: { value: /* @__PURE__ */ new Me() }
    },
    vertexShader: Ee.backgroundCube_vert,
    fragmentShader: Ee.backgroundCube_frag
  },
  cube: {
    uniforms: {
      tCube: { value: null },
      tFlip: { value: -1 },
      opacity: { value: 1 }
    },
    vertexShader: Ee.cube_vert,
    fragmentShader: Ee.cube_frag
  },
  equirect: {
    uniforms: {
      tEquirect: { value: null }
    },
    vertexShader: Ee.equirect_vert,
    fragmentShader: Ee.equirect_frag
  },
  distance: {
    uniforms: /* @__PURE__ */ si([
      Gt.common,
      Gt.displacementmap,
      {
        referencePosition: { value: /* @__PURE__ */ new st() },
        nearDistance: { value: 1 },
        farDistance: { value: 1e3 }
      }
    ]),
    vertexShader: Ee.distance_vert,
    fragmentShader: Ee.distance_frag
  },
  shadow: {
    uniforms: /* @__PURE__ */ si([
      Gt.lights,
      Gt.fog,
      {
        color: { value: /* @__PURE__ */ new we(0) },
        opacity: { value: 1 }
      }
    ]),
    vertexShader: Ee.shadow_vert,
    fragmentShader: Ee.shadow_frag
  }
};
di.physical = {
  uniforms: /* @__PURE__ */ si([
    di.standard.uniforms,
    {
      clearcoat: { value: 0 },
      clearcoatMap: { value: null },
      clearcoatMapTransform: { value: /* @__PURE__ */ new Me() },
      clearcoatNormalMap: { value: null },
      clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Me() },
      clearcoatNormalScale: { value: /* @__PURE__ */ new ae(1, 1) },
      clearcoatRoughness: { value: 0 },
      clearcoatRoughnessMap: { value: null },
      clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Me() },
      dispersion: { value: 0 },
      iridescence: { value: 0 },
      iridescenceMap: { value: null },
      iridescenceMapTransform: { value: /* @__PURE__ */ new Me() },
      iridescenceIOR: { value: 1.3 },
      iridescenceThicknessMinimum: { value: 100 },
      iridescenceThicknessMaximum: { value: 400 },
      iridescenceThicknessMap: { value: null },
      iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Me() },
      sheen: { value: 0 },
      sheenColor: { value: /* @__PURE__ */ new we(0) },
      sheenColorMap: { value: null },
      sheenColorMapTransform: { value: /* @__PURE__ */ new Me() },
      sheenRoughness: { value: 1 },
      sheenRoughnessMap: { value: null },
      sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Me() },
      transmission: { value: 0 },
      transmissionMap: { value: null },
      transmissionMapTransform: { value: /* @__PURE__ */ new Me() },
      transmissionSamplerSize: { value: /* @__PURE__ */ new ae() },
      transmissionSamplerMap: { value: null },
      thickness: { value: 0 },
      thicknessMap: { value: null },
      thicknessMapTransform: { value: /* @__PURE__ */ new Me() },
      attenuationDistance: { value: 0 },
      attenuationColor: { value: /* @__PURE__ */ new we(0) },
      specularColor: { value: /* @__PURE__ */ new we(1, 1, 1) },
      specularColorMap: { value: null },
      specularColorMapTransform: { value: /* @__PURE__ */ new Me() },
      specularIntensity: { value: 1 },
      specularIntensityMap: { value: null },
      specularIntensityMapTransform: { value: /* @__PURE__ */ new Me() },
      anisotropyVector: { value: /* @__PURE__ */ new ae() },
      anisotropyMap: { value: null },
      anisotropyMapTransform: { value: /* @__PURE__ */ new Me() }
    }
  ]),
  vertexShader: Ee.meshphysical_vert,
  fragmentShader: Ee.meshphysical_frag
};
const jf = { r: 0, b: 0, g: 0 }, Da = /* @__PURE__ */ new Rs(), LD = /* @__PURE__ */ new je();
function UD(n, t, e, s, a, o) {
  const c = new we(0);
  let u = a === !0 ? 0 : 1, d, h, m = null, p = 0, g = null;
  function _(E) {
    let w = E.isScene === !0 ? E.background : null;
    if (w && w.isTexture) {
      const M = E.backgroundBlurriness > 0;
      w = t.get(w, M);
    }
    return w;
  }
  function x(E) {
    let w = !1;
    const M = _(E);
    M === null ? b(c, u) : M && M.isColor && (b(M, 1), w = !0);
    const O = n.xr.getEnvironmentBlendMode();
    O === "additive" ? e.buffers.color.setClear(0, 0, 0, 1, o) : O === "alpha-blend" && e.buffers.color.setClear(0, 0, 0, 0, o), (n.autoClear || w) && (e.buffers.depth.setTest(!0), e.buffers.depth.setMask(!0), e.buffers.color.setMask(!0), n.clear(n.autoClearColor, n.autoClearDepth, n.autoClearStencil));
  }
  function A(E, w) {
    const M = _(w);
    M && (M.isCubeTexture || M.mapping === Wd) ? (h === void 0 && (h = new Ln(
      new nu(1, 1, 1),
      new as({
        name: "BackgroundCubeMaterial",
        uniforms: ml(di.backgroundCube.uniforms),
        vertexShader: di.backgroundCube.vertexShader,
        fragmentShader: di.backgroundCube.fragmentShader,
        side: pi,
        depthTest: !1,
        depthWrite: !1,
        fog: !1,
        allowOverride: !1
      })
    ), h.geometry.deleteAttribute("normal"), h.geometry.deleteAttribute("uv"), h.onBeforeRender = function(O, C, D) {
      this.matrixWorld.copyPosition(D.matrixWorld);
    }, Object.defineProperty(h.material, "envMap", {
      get: function() {
        return this.uniforms.envMap.value;
      }
    }), s.update(h)), Da.copy(w.backgroundRotation), Da.x *= -1, Da.y *= -1, Da.z *= -1, M.isCubeTexture && M.isRenderTargetTexture === !1 && (Da.y *= -1, Da.z *= -1), h.material.uniforms.envMap.value = M, h.material.uniforms.flipEnvMap.value = M.isCubeTexture && M.isRenderTargetTexture === !1 ? -1 : 1, h.material.uniforms.backgroundBlurriness.value = w.backgroundBlurriness, h.material.uniforms.backgroundIntensity.value = w.backgroundIntensity, h.material.uniforms.backgroundRotation.value.setFromMatrix4(LD.makeRotationFromEuler(Da)), h.material.toneMapped = Be.getTransfer(M.colorSpace) !== We, (m !== M || p !== M.version || g !== n.toneMapping) && (h.material.needsUpdate = !0, m = M, p = M.version, g = n.toneMapping), h.layers.enableAll(), E.unshift(h, h.geometry, h.material, 0, 0, null)) : M && M.isTexture && (d === void 0 && (d = new Ln(
      new $d(2, 2),
      new as({
        name: "BackgroundMaterial",
        uniforms: ml(di.background.uniforms),
        vertexShader: di.background.vertexShader,
        fragmentShader: di.background.fragmentShader,
        side: ra,
        depthTest: !1,
        depthWrite: !1,
        fog: !1,
        allowOverride: !1
      })
    ), d.geometry.deleteAttribute("normal"), Object.defineProperty(d.material, "map", {
      get: function() {
        return this.uniforms.t2D.value;
      }
    }), s.update(d)), d.material.uniforms.t2D.value = M, d.material.uniforms.backgroundIntensity.value = w.backgroundIntensity, d.material.toneMapped = Be.getTransfer(M.colorSpace) !== We, M.matrixAutoUpdate === !0 && M.updateMatrix(), d.material.uniforms.uvTransform.value.copy(M.matrix), (m !== M || p !== M.version || g !== n.toneMapping) && (d.material.needsUpdate = !0, m = M, p = M.version, g = n.toneMapping), d.layers.enableAll(), E.unshift(d, d.geometry, d.material, 0, 0, null));
  }
  function b(E, w) {
    E.getRGB(jf, BM(n)), e.buffers.color.setClear(jf.r, jf.g, jf.b, w, o);
  }
  function y() {
    h !== void 0 && (h.geometry.dispose(), h.material.dispose(), h = void 0), d !== void 0 && (d.geometry.dispose(), d.material.dispose(), d = void 0);
  }
  return {
    getClearColor: function() {
      return c;
    },
    setClearColor: function(E, w = 1) {
      c.set(E), u = w, b(c, u);
    },
    getClearAlpha: function() {
      return u;
    },
    setClearAlpha: function(E) {
      u = E, b(c, u);
    },
    render: x,
    addToRenderList: A,
    dispose: y
  };
}
function PD(n, t) {
  const e = n.getParameter(n.MAX_VERTEX_ATTRIBS), s = {}, a = g(null);
  let o = a, c = !1;
  function u(R, B, H, U, V) {
    let N = !1;
    const I = p(R, U, H, B);
    o !== I && (o = I, h(o.object)), N = _(R, U, H, V), N && x(R, U, H, V), V !== null && t.update(V, n.ELEMENT_ARRAY_BUFFER), (N || c) && (c = !1, M(R, B, H, U), V !== null && n.bindBuffer(n.ELEMENT_ARRAY_BUFFER, t.get(V).buffer));
  }
  function d() {
    return n.createVertexArray();
  }
  function h(R) {
    return n.bindVertexArray(R);
  }
  function m(R) {
    return n.deleteVertexArray(R);
  }
  function p(R, B, H, U) {
    const V = U.wireframe === !0;
    let N = s[B.id];
    N === void 0 && (N = {}, s[B.id] = N);
    const I = R.isInstancedMesh === !0 ? R.id : 0;
    let k = N[I];
    k === void 0 && (k = {}, N[I] = k);
    let X = k[H.id];
    X === void 0 && (X = {}, k[H.id] = X);
    let Q = X[V];
    return Q === void 0 && (Q = g(d()), X[V] = Q), Q;
  }
  function g(R) {
    const B = [], H = [], U = [];
    for (let V = 0; V < e; V++)
      B[V] = 0, H[V] = 0, U[V] = 0;
    return {
      // for backward compatibility on non-VAO support browser
      geometry: null,
      program: null,
      wireframe: !1,
      newAttributes: B,
      enabledAttributes: H,
      attributeDivisors: U,
      object: R,
      attributes: {},
      index: null
    };
  }
  function _(R, B, H, U) {
    const V = o.attributes, N = B.attributes;
    let I = 0;
    const k = H.getAttributes();
    for (const X in k)
      if (k[X].location >= 0) {
        const F = V[X];
        let W = N[X];
        if (W === void 0 && (X === "instanceMatrix" && R.instanceMatrix && (W = R.instanceMatrix), X === "instanceColor" && R.instanceColor && (W = R.instanceColor)), F === void 0 || F.attribute !== W || W && F.data !== W.data) return !0;
        I++;
      }
    return o.attributesNum !== I || o.index !== U;
  }
  function x(R, B, H, U) {
    const V = {}, N = B.attributes;
    let I = 0;
    const k = H.getAttributes();
    for (const X in k)
      if (k[X].location >= 0) {
        let F = N[X];
        F === void 0 && (X === "instanceMatrix" && R.instanceMatrix && (F = R.instanceMatrix), X === "instanceColor" && R.instanceColor && (F = R.instanceColor));
        const W = {};
        W.attribute = F, F && F.data && (W.data = F.data), V[X] = W, I++;
      }
    o.attributes = V, o.attributesNum = I, o.index = U;
  }
  function A() {
    const R = o.newAttributes;
    for (let B = 0, H = R.length; B < H; B++)
      R[B] = 0;
  }
  function b(R) {
    y(R, 0);
  }
  function y(R, B) {
    const H = o.newAttributes, U = o.enabledAttributes, V = o.attributeDivisors;
    H[R] = 1, U[R] === 0 && (n.enableVertexAttribArray(R), U[R] = 1), V[R] !== B && (n.vertexAttribDivisor(R, B), V[R] = B);
  }
  function E() {
    const R = o.newAttributes, B = o.enabledAttributes;
    for (let H = 0, U = B.length; H < U; H++)
      B[H] !== R[H] && (n.disableVertexAttribArray(H), B[H] = 0);
  }
  function w(R, B, H, U, V, N, I) {
    I === !0 ? n.vertexAttribIPointer(R, B, H, V, N) : n.vertexAttribPointer(R, B, H, U, V, N);
  }
  function M(R, B, H, U) {
    A();
    const V = U.attributes, N = H.getAttributes(), I = B.defaultAttributeValues;
    for (const k in N) {
      const X = N[k];
      if (X.location >= 0) {
        let Q = V[k];
        if (Q === void 0 && (k === "instanceMatrix" && R.instanceMatrix && (Q = R.instanceMatrix), k === "instanceColor" && R.instanceColor && (Q = R.instanceColor)), Q !== void 0) {
          const F = Q.normalized, W = Q.itemSize, et = t.get(Q);
          if (et === void 0) continue;
          const $ = et.buffer, j = et.type, Y = et.bytesPerElement, K = j === n.INT || j === n.UNSIGNED_INT || Q.gpuType === V0;
          if (Q.isInterleavedBufferAttribute) {
            const J = Q.data, rt = J.stride, dt = Q.offset;
            if (J.isInstancedInterleavedBuffer) {
              for (let yt = 0; yt < X.locationSize; yt++)
                y(X.location + yt, J.meshPerAttribute);
              R.isInstancedMesh !== !0 && U._maxInstanceCount === void 0 && (U._maxInstanceCount = J.meshPerAttribute * J.count);
            } else
              for (let yt = 0; yt < X.locationSize; yt++)
                b(X.location + yt);
            n.bindBuffer(n.ARRAY_BUFFER, $);
            for (let yt = 0; yt < X.locationSize; yt++)
              w(
                X.location + yt,
                W / X.locationSize,
                j,
                F,
                rt * Y,
                (dt + W / X.locationSize * yt) * Y,
                K
              );
          } else {
            if (Q.isInstancedBufferAttribute) {
              for (let J = 0; J < X.locationSize; J++)
                y(X.location + J, Q.meshPerAttribute);
              R.isInstancedMesh !== !0 && U._maxInstanceCount === void 0 && (U._maxInstanceCount = Q.meshPerAttribute * Q.count);
            } else
              for (let J = 0; J < X.locationSize; J++)
                b(X.location + J);
            n.bindBuffer(n.ARRAY_BUFFER, $);
            for (let J = 0; J < X.locationSize; J++)
              w(
                X.location + J,
                W / X.locationSize,
                j,
                F,
                W * Y,
                W / X.locationSize * J * Y,
                K
              );
          }
        } else if (I !== void 0) {
          const F = I[k];
          if (F !== void 0)
            switch (F.length) {
              case 2:
                n.vertexAttrib2fv(X.location, F);
                break;
              case 3:
                n.vertexAttrib3fv(X.location, F);
                break;
              case 4:
                n.vertexAttrib4fv(X.location, F);
                break;
              default:
                n.vertexAttrib1fv(X.location, F);
            }
        }
      }
    }
    E();
  }
  function O() {
    L();
    for (const R in s) {
      const B = s[R];
      for (const H in B) {
        const U = B[H];
        for (const V in U) {
          const N = U[V];
          for (const I in N)
            m(N[I].object), delete N[I];
          delete U[V];
        }
      }
      delete s[R];
    }
  }
  function C(R) {
    if (s[R.id] === void 0) return;
    const B = s[R.id];
    for (const H in B) {
      const U = B[H];
      for (const V in U) {
        const N = U[V];
        for (const I in N)
          m(N[I].object), delete N[I];
        delete U[V];
      }
    }
    delete s[R.id];
  }
  function D(R) {
    for (const B in s) {
      const H = s[B];
      for (const U in H) {
        const V = H[U];
        if (V[R.id] === void 0) continue;
        const N = V[R.id];
        for (const I in N)
          m(N[I].object), delete N[I];
        delete V[R.id];
      }
    }
  }
  function T(R) {
    for (const B in s) {
      const H = s[B], U = R.isInstancedMesh === !0 ? R.id : 0, V = H[U];
      if (V !== void 0) {
        for (const N in V) {
          const I = V[N];
          for (const k in I)
            m(I[k].object), delete I[k];
          delete V[N];
        }
        delete H[U], Object.keys(H).length === 0 && delete s[B];
      }
    }
  }
  function L() {
    z(), c = !0, o !== a && (o = a, h(o.object));
  }
  function z() {
    a.geometry = null, a.program = null, a.wireframe = !1;
  }
  return {
    setup: u,
    reset: L,
    resetDefaultState: z,
    dispose: O,
    releaseStatesOfGeometry: C,
    releaseStatesOfObject: T,
    releaseStatesOfProgram: D,
    initAttributes: A,
    enableAttribute: b,
    disableUnusedAttributes: E
  };
}
function ID(n, t, e) {
  let s;
  function a(h) {
    s = h;
  }
  function o(h, m) {
    n.drawArrays(s, h, m), e.update(m, s, 1);
  }
  function c(h, m, p) {
    p !== 0 && (n.drawArraysInstanced(s, h, m, p), e.update(m, s, p));
  }
  function u(h, m, p) {
    if (p === 0) return;
    t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(s, h, 0, m, 0, p);
    let _ = 0;
    for (let x = 0; x < p; x++)
      _ += m[x];
    e.update(_, s, 1);
  }
  function d(h, m, p, g) {
    if (p === 0) return;
    const _ = t.get("WEBGL_multi_draw");
    if (_ === null)
      for (let x = 0; x < h.length; x++)
        c(h[x], m[x], g[x]);
    else {
      _.multiDrawArraysInstancedWEBGL(s, h, 0, m, 0, g, 0, p);
      let x = 0;
      for (let A = 0; A < p; A++)
        x += m[A] * g[A];
      e.update(x, s, 1);
    }
  }
  this.setMode = a, this.render = o, this.renderInstances = c, this.renderMultiDraw = u, this.renderMultiDrawInstances = d;
}
function BD(n, t, e, s) {
  let a;
  function o() {
    if (a !== void 0) return a;
    if (t.has("EXT_texture_filter_anisotropic") === !0) {
      const D = t.get("EXT_texture_filter_anisotropic");
      a = n.getParameter(D.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
    } else
      a = 0;
    return a;
  }
  function c(D) {
    return !(D !== Ni && s.convert(D) !== n.getParameter(n.IMPLEMENTATION_COLOR_READ_FORMAT));
  }
  function u(D) {
    const T = D === dr && (t.has("EXT_color_buffer_half_float") || t.has("EXT_color_buffer_float"));
    return !(D !== Ci && s.convert(D) !== n.getParameter(n.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
    D !== Di && !T);
  }
  function d(D) {
    if (D === "highp") {
      if (n.getShaderPrecisionFormat(n.VERTEX_SHADER, n.HIGH_FLOAT).precision > 0 && n.getShaderPrecisionFormat(n.FRAGMENT_SHADER, n.HIGH_FLOAT).precision > 0)
        return "highp";
      D = "mediump";
    }
    return D === "mediump" && n.getShaderPrecisionFormat(n.VERTEX_SHADER, n.MEDIUM_FLOAT).precision > 0 && n.getShaderPrecisionFormat(n.FRAGMENT_SHADER, n.MEDIUM_FLOAT).precision > 0 ? "mediump" : "lowp";
  }
  let h = e.precision !== void 0 ? e.precision : "highp";
  const m = d(h);
  m !== h && (de("WebGLRenderer:", h, "not supported, using", m, "instead."), h = m);
  const p = e.logarithmicDepthBuffer === !0, g = e.reversedDepthBuffer === !0 && t.has("EXT_clip_control"), _ = n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS), x = n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS), A = n.getParameter(n.MAX_TEXTURE_SIZE), b = n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE), y = n.getParameter(n.MAX_VERTEX_ATTRIBS), E = n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS), w = n.getParameter(n.MAX_VARYING_VECTORS), M = n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS), O = n.getParameter(n.MAX_SAMPLES), C = n.getParameter(n.SAMPLES);
  return {
    isWebGL2: !0,
    // keeping this for backwards compatibility
    getMaxAnisotropy: o,
    getMaxPrecision: d,
    textureFormatReadable: c,
    textureTypeReadable: u,
    precision: h,
    logarithmicDepthBuffer: p,
    reversedDepthBuffer: g,
    maxTextures: _,
    maxVertexTextures: x,
    maxTextureSize: A,
    maxCubemapSize: b,
    maxAttributes: y,
    maxVertexUniforms: E,
    maxVaryings: w,
    maxFragmentUniforms: M,
    maxSamples: O,
    samples: C
  };
}
function zD(n) {
  const t = this;
  let e = null, s = 0, a = !1, o = !1;
  const c = new Jr(), u = new Me(), d = { value: null, needsUpdate: !1 };
  this.uniform = d, this.numPlanes = 0, this.numIntersection = 0, this.init = function(p, g) {
    const _ = p.length !== 0 || g || // enable state of previous frame - the clipping code has to
    // run another frame in order to reset the state:
    s !== 0 || a;
    return a = g, s = p.length, _;
  }, this.beginShadows = function() {
    o = !0, m(null);
  }, this.endShadows = function() {
    o = !1;
  }, this.setGlobalState = function(p, g) {
    e = m(p, g, 0);
  }, this.setState = function(p, g, _) {
    const x = p.clippingPlanes, A = p.clipIntersection, b = p.clipShadows, y = n.get(p);
    if (!a || x === null || x.length === 0 || o && !b)
      o ? m(null) : h();
    else {
      const E = o ? 0 : s, w = E * 4;
      let M = y.clippingState || null;
      d.value = M, M = m(x, g, w, _);
      for (let O = 0; O !== w; ++O)
        M[O] = e[O];
      y.clippingState = M, this.numIntersection = A ? this.numPlanes : 0, this.numPlanes += E;
    }
  };
  function h() {
    d.value !== e && (d.value = e, d.needsUpdate = s > 0), t.numPlanes = s, t.numIntersection = 0;
  }
  function m(p, g, _, x) {
    const A = p !== null ? p.length : 0;
    let b = null;
    if (A !== 0) {
      if (b = d.value, x !== !0 || b === null) {
        const y = _ + A * 4, E = g.matrixWorldInverse;
        u.getNormalMatrix(E), (b === null || b.length < y) && (b = new Float32Array(y));
        for (let w = 0, M = _; w !== A; ++w, M += 4)
          c.copy(p[w]).applyMatrix4(E, u), c.normal.toArray(b, M), b[M + 3] = c.constant;
      }
      d.value = b, d.needsUpdate = !0;
    }
    return t.numPlanes = A, t.numIntersection = 0, b;
  }
}
const ia = 4, tb = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582], Pa = 20, FD = 256, Mc = /* @__PURE__ */ new ns(), eb = /* @__PURE__ */ new we();
let Km = null, Qm = 0, Jm = 0, tg = !1;
const HD = /* @__PURE__ */ new st();
class nb {
  /**
   * 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._sizeLods = [], this._sigmas = [], this._lodMeshes = [], this._backgroundBox = null, this._cubemapMaterial = null, this._equirectMaterial = null, this._blurMaterial = null, this._ggxMaterial = null;
  }
  /**
   * 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.position=origin] - The position of the internal cube camera that renders the scene.
   * @return {WebGLRenderTarget} The resulting PMREM.
   */
  fromScene(t, e = 0, s = 0.1, a = 100, o = {}) {
    const {
      size: c = 256,
      position: u = HD
    } = o;
    Km = this._renderer.getRenderTarget(), Qm = this._renderer.getActiveCubeFace(), Jm = this._renderer.getActiveMipmapLevel(), tg = this._renderer.xr.enabled, this._renderer.xr.enabled = !1, this._setSize(c);
    const d = this._allocateTargets();
    return d.depthBuffer = !0, this._sceneToCubeUV(t, s, a, d, u), e > 0 && this._blur(d, 0, 0, e), this._applyPMREM(d), this._cleanup(d), d;
  }
  /**
   * 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 = rb(), 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 = sb(), 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(), this._backgroundBox !== null && (this._backgroundBox.geometry.dispose(), this._backgroundBox.material.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._ggxMaterial !== null && this._ggxMaterial.dispose(), this._pingPongRenderTarget !== null && this._pingPongRenderTarget.dispose();
    for (let t = 0; t < this._lodMeshes.length; t++)
      this._lodMeshes[t].geometry.dispose();
  }
  _cleanup(t) {
    this._renderer.setRenderTarget(Km, Qm, Jm), this._renderer.xr.enabled = tg, t.scissorTest = !1, Jo(t, 0, 0, t.width, t.height);
  }
  _fromTexture(t, e) {
    t.mapping === ka || t.mapping === dl ? this._setSize(t.image.length === 0 ? 16 : t.image[0].width || t.image[0].image.width) : this._setSize(t.image.width / 4), Km = this._renderer.getRenderTarget(), Qm = this._renderer.getActiveCubeFace(), Jm = this._renderer.getActiveMipmapLevel(), tg = this._renderer.xr.enabled, this._renderer.xr.enabled = !1;
    const s = e || this._allocateTargets();
    return this._textureToCubeUV(t, s), this._applyPMREM(s), this._cleanup(s), s;
  }
  _allocateTargets() {
    const t = 3 * Math.max(this._cubeSize, 112), e = 4 * this._cubeSize, s = {
      magFilter: Qn,
      minFilter: Qn,
      generateMipmaps: !1,
      type: dr,
      format: Ni,
      colorSpace: pl,
      depthBuffer: !1
    }, a = ib(t, e, s);
    if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== t || this._pingPongRenderTarget.height !== e) {
      this._pingPongRenderTarget !== null && this._dispose(), this._pingPongRenderTarget = ib(t, e, s);
      const { _lodMax: o } = this;
      ({ lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = VD(o)), this._blurMaterial = kD(o, t, e), this._ggxMaterial = GD(o, t, e);
    }
    return a;
  }
  _compileMaterial(t) {
    const e = new Ln(new In(), t);
    this._renderer.compile(e, Mc);
  }
  _sceneToCubeUV(t, e, s, a, o) {
    const d = new Ti(90, 1, e, s), h = [1, -1, 1, 1, 1, 1], m = [1, 1, 1, -1, -1, -1], p = this._renderer, g = p.autoClear, _ = p.toneMapping;
    p.getClearColor(eb), p.toneMapping = ws, p.autoClear = !1, p.state.buffers.depth.getReversed() && (p.setRenderTarget(a), p.clearDepth(), p.setRenderTarget(null)), this._backgroundBox === null && (this._backgroundBox = new Ln(
      new nu(),
      new Yd({
        name: "PMREM.Background",
        side: pi,
        depthWrite: !1,
        depthTest: !1
      })
    ));
    const A = this._backgroundBox, b = A.material;
    let y = !1;
    const E = t.background;
    E ? E.isColor && (b.color.copy(E), t.background = null, y = !0) : (b.color.copy(eb), y = !0);
    for (let w = 0; w < 6; w++) {
      const M = w % 3;
      M === 0 ? (d.up.set(0, h[w], 0), d.position.set(o.x, o.y, o.z), d.lookAt(o.x + m[w], o.y, o.z)) : M === 1 ? (d.up.set(0, 0, h[w]), d.position.set(o.x, o.y, o.z), d.lookAt(o.x, o.y + m[w], o.z)) : (d.up.set(0, h[w], 0), d.position.set(o.x, o.y, o.z), d.lookAt(o.x, o.y, o.z + m[w]));
      const O = this._cubeSize;
      Jo(a, M * O, w > 2 ? O : 0, O, O), p.setRenderTarget(a), y && p.render(A, d), p.render(t, d);
    }
    p.toneMapping = _, p.autoClear = g, t.background = E;
  }
  _textureToCubeUV(t, e) {
    const s = this._renderer, a = t.mapping === ka || t.mapping === dl;
    a ? (this._cubemapMaterial === null && (this._cubemapMaterial = rb()), this._cubemapMaterial.uniforms.flipEnvMap.value = t.isRenderTargetTexture === !1 ? -1 : 1) : this._equirectMaterial === null && (this._equirectMaterial = sb());
    const o = a ? this._cubemapMaterial : this._equirectMaterial, c = this._lodMeshes[0];
    c.material = o;
    const u = o.uniforms;
    u.envMap.value = t;
    const d = this._cubeSize;
    Jo(e, 0, 0, 3 * d, 2 * d), s.setRenderTarget(e), s.render(c, Mc);
  }
  _applyPMREM(t) {
    const e = this._renderer, s = e.autoClear;
    e.autoClear = !1;
    const a = this._lodMeshes.length;
    for (let o = 1; o < a; o++)
      this._applyGGXFilter(t, o - 1, o);
    e.autoClear = s;
  }
  /**
   * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
   * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
   * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
   * applies incremental roughness filtering to avoid over-blurring.
   *
   * @private
   * @param {WebGLRenderTarget} cubeUVRenderTarget
   * @param {number} lodIn - Source LOD level to read from
   * @param {number} lodOut - Target LOD level to write to
   */
  _applyGGXFilter(t, e, s) {
    const a = this._renderer, o = this._pingPongRenderTarget, c = this._ggxMaterial, u = this._lodMeshes[s];
    u.material = c;
    const d = c.uniforms, h = s / (this._lodMeshes.length - 1), m = e / (this._lodMeshes.length - 1), p = Math.sqrt(h * h - m * m), g = 0 + h * 1.25, _ = p * g, { _lodMax: x } = this, A = this._sizeLods[s], b = 3 * A * (s > x - ia ? s - x + ia : 0), y = 4 * (this._cubeSize - A);
    d.envMap.value = t.texture, d.roughness.value = _, d.mipInt.value = x - e, Jo(o, b, y, 3 * A, 2 * A), a.setRenderTarget(o), a.render(u, Mc), d.envMap.value = o.texture, d.roughness.value = 0, d.mipInt.value = x - s, Jo(t, b, y, 3 * A, 2 * A), a.setRenderTarget(t), a.render(u, Mc);
  }
  /**
   * 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.
   *
   * Used for initial scene blur in fromScene() method when sigma > 0.
   *
   * @private
   * @param {WebGLRenderTarget} cubeUVRenderTarget
   * @param {number} lodIn
   * @param {number} lodOut
   * @param {number} sigma
   * @param {Vector3} [poleAxis]
   */
  _blur(t, e, s, a, o) {
    const c = this._pingPongRenderTarget;
    this._halfBlur(
      t,
      c,
      e,
      s,
      a,
      "latitudinal",
      o
    ), this._halfBlur(
      c,
      t,
      s,
      s,
      a,
      "longitudinal",
      o
    );
  }
  _halfBlur(t, e, s, a, o, c, u) {
    const d = this._renderer, h = this._blurMaterial;
    c !== "latitudinal" && c !== "longitudinal" && Ie(
      "blur direction must be either latitudinal or longitudinal!"
    );
    const m = 3, p = this._lodMeshes[a];
    p.material = h;
    const g = h.uniforms, _ = this._sizeLods[s] - 1, x = isFinite(o) ? Math.PI / (2 * _) : 2 * Math.PI / (2 * Pa - 1), A = o / x, b = isFinite(o) ? 1 + Math.floor(m * A) : Pa;
    b > Pa && de(`sigmaRadians, ${o}, is too large and will clip, as it requested ${b} samples when the maximum is set to ${Pa}`);
    const y = [];
    let E = 0;
    for (let D = 0; D < Pa; ++D) {
      const T = D / A, L = Math.exp(-T * T / 2);
      y.push(L), D === 0 ? E += L : D < b && (E += 2 * L);
    }
    for (let D = 0; D < y.length; D++)
      y[D] = y[D] / E;
    g.envMap.value = t.texture, g.samples.value = b, g.weights.value = y, g.latitudinal.value = c === "latitudinal", u && (g.poleAxis.value = u);
    const { _lodMax: w } = this;
    g.dTheta.value = x, g.mipInt.value = w - s;
    const M = this._sizeLods[a], O = 3 * M * (a > w - ia ? a - w + ia : 0), C = 4 * (this._cubeSize - M);
    Jo(e, O, C, 3 * M, 2 * M), d.setRenderTarget(e), d.render(p, Mc);
  }
}
function VD(n) {
  const t = [], e = [], s = [];
  let a = n;
  const o = n - ia + 1 + tb.length;
  for (let c = 0; c < o; c++) {
    const u = Math.pow(2, a);
    t.push(u);
    let d = 1 / u;
    c > n - ia ? d = tb[c - n + ia - 1] : c === 0 && (d = 0), e.push(d);
    const h = 1 / (u - 2), m = -h, p = 1 + h, g = [m, m, p, m, p, p, m, m, p, p, m, p], _ = 6, x = 6, A = 3, b = 2, y = 1, E = new Float32Array(A * x * _), w = new Float32Array(b * x * _), M = new Float32Array(y * x * _);
    for (let C = 0; C < _; C++) {
      const D = C % 3 * 2 / 3 - 1, T = C > 2 ? 0 : -1, L = [
        D,
        T,
        0,
        D + 2 / 3,
        T,
        0,
        D + 2 / 3,
        T + 1,
        0,
        D,
        T,
        0,
        D + 2 / 3,
        T + 1,
        0,
        D,
        T + 1,
        0
      ];
      E.set(L, A * x * C), w.set(g, b * x * C);
      const z = [C, C, C, C, C, C];
      M.set(z, y * x * C);
    }
    const O = new In();
    O.setAttribute("position", new dn(E, A)), O.setAttribute("uv", new dn(w, b)), O.setAttribute("faceIndex", new dn(M, y)), s.push(new Ln(O, null)), a > ia && a--;
  }
  return { lodMeshes: s, sizeLods: t, sigmas: e };
}
function ib(n, t, e) {
  const s = new As(n, t, e);
  return s.texture.mapping = Wd, s.texture.name = "PMREM.cubeUv", s.scissorTest = !0, s;
}
function Jo(n, t, e, s, a) {
  n.viewport.set(t, e, s, a), n.scissor.set(t, e, s, a);
}
function GD(n, t, e) {
  return new as({
    name: "PMREMGGXConvolution",
    defines: {
      GGX_SAMPLES: FD,
      CUBEUV_TEXEL_WIDTH: 1 / t,
      CUBEUV_TEXEL_HEIGHT: 1 / e,
      CUBEUV_MAX_MIP: `${n}.0`
    },
    uniforms: {
      envMap: { value: null },
      roughness: { value: 0 },
      mipInt: { value: 0 }
    },
    vertexShader: Kd(),
    fragmentShader: (
      /* glsl */
      `

			precision highp float;
			precision highp int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform float roughness;
			uniform float mipInt;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			#define PI 3.14159265359

			// Van der Corput radical inverse
			float radicalInverse_VdC(uint bits) {
				bits = (bits << 16u) | (bits >> 16u);
				bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
				bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
				bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
				bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
				return float(bits) * 2.3283064365386963e-10; // / 0x100000000
			}

			// Hammersley sequence
			vec2 hammersley(uint i, uint N) {
				return vec2(float(i) / float(N), radicalInverse_VdC(i));
			}

			// GGX VNDF importance sampling (Eric Heitz 2018)
			// "Sampling the GGX Distribution of Visible Normals"
			// https://jcgt.org/published/0007/04/01/
			vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
				float alpha = roughness * roughness;

				// Section 4.1: Orthonormal basis
				vec3 T1 = vec3(1.0, 0.0, 0.0);
				vec3 T2 = cross(V, T1);

				// Section 4.2: Parameterization of projected area
				float r = sqrt(Xi.x);
				float phi = 2.0 * PI * Xi.y;
				float t1 = r * cos(phi);
				float t2 = r * sin(phi);
				float s = 0.5 * (1.0 + V.z);
				t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;

				// Section 4.3: Reprojection onto hemisphere
				vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;

				// Section 3.4: Transform back to ellipsoid configuration
				return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
			}

			void main() {
				vec3 N = normalize(vOutputDirection);
				vec3 V = N; // Assume view direction equals normal for pre-filtering

				vec3 prefilteredColor = vec3(0.0);
				float totalWeight = 0.0;

				// For very low roughness, just sample the environment directly
				if (roughness < 0.001) {
					gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
					return;
				}

				// Tangent space basis for VNDF sampling
				vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
				vec3 tangent = normalize(cross(up, N));
				vec3 bitangent = cross(N, tangent);

				for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
					vec2 Xi = hammersley(i, uint(GGX_SAMPLES));

					// For PMREM, V = N, so in tangent space V is always (0, 0, 1)
					vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);

					// Transform H back to world space
					vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
					vec3 L = normalize(2.0 * dot(V, H) * H - V);

					float NdotL = max(dot(N, L), 0.0);

					if(NdotL > 0.0) {
						// Sample environment at fixed mip level
						// VNDF importance sampling handles the distribution filtering
						vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);

						// Weight by NdotL for the split-sum approximation
						// VNDF PDF naturally accounts for the visible microfacet distribution
						prefilteredColor += sampleColor * NdotL;
						totalWeight += NdotL;
					}
				}

				if (totalWeight > 0.0) {
					prefilteredColor = prefilteredColor / totalWeight;
				}

				gl_FragColor = vec4(prefilteredColor, 1.0);
			}
		`
    ),
    blending: cr,
    depthTest: !1,
    depthWrite: !1
  });
}
function kD(n, t, e) {
  const s = new Float32Array(Pa), a = new st(0, 1, 0);
  return new as({
    name: "SphericalGaussianBlur",
    defines: {
      n: Pa,
      CUBEUV_TEXEL_WIDTH: 1 / t,
      CUBEUV_TEXEL_HEIGHT: 1 / e,
      CUBEUV_MAX_MIP: `${n}.0`
    },
    uniforms: {
      envMap: { value: null },
      samples: { value: 1 },
      weights: { value: s },
      latitudinal: { value: !1 },
      dTheta: { value: 0 },
      mipInt: { value: 0 },
      poleAxis: { value: a }
    },
    vertexShader: Kd(),
    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: cr,
    depthTest: !1,
    depthWrite: !1
  });
}
function sb() {
  return new as({
    name: "EquirectangularToCubeUV",
    uniforms: {
      envMap: { value: null }
    },
    vertexShader: Kd(),
    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: cr,
    depthTest: !1,
    depthWrite: !1
  });
}
function rb() {
  return new as({
    name: "CubemapToCubeUV",
    uniforms: {
      envMap: { value: null },
      flipEnvMap: { value: -1 }
    },
    vertexShader: Kd(),
    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: cr,
    depthTest: !1,
    depthWrite: !1
  });
}
function Kd() {
  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 );

		}
	`
  );
}
class HM extends As {
  /**
   * 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 s = { width: t, height: t, depth: 1 }, a = [s, s, s, s, s, s];
    this.texture = new PM(a), 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 s = {
      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 );

				}
			`
      )
    }, a = new nu(5, 5, 5), o = new as({
      name: "CubemapFromEquirect",
      uniforms: ml(s.uniforms),
      vertexShader: s.vertexShader,
      fragmentShader: s.fragmentShader,
      side: pi,
      blending: cr
    });
    o.uniforms.tEquirect.value = e;
    const c = new Ln(a, o), u = e.minFilter;
    return e.minFilter === Ia && (e.minFilter = Qn), new W3(1, 10, this).update(t, c), e.minFilter = u, c.geometry.dispose(), c.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, s = !0, a = !0) {
    const o = t.getRenderTarget();
    for (let c = 0; c < 6; c++)
      t.setRenderTarget(this, c), t.clear(e, s, a);
    t.setRenderTarget(o);
  }
}
function XD(n) {
  let t = /* @__PURE__ */ new WeakMap(), e = /* @__PURE__ */ new WeakMap(), s = null;
  function a(g, _ = !1) {
    return g == null ? null : _ ? c(g) : o(g);
  }
  function o(g) {
    if (g && g.isTexture) {
      const _ = g.mapping;
      if (_ === xm || _ === Sm)
        if (t.has(g)) {
          const x = t.get(g).texture;
          return u(x, g.mapping);
        } else {
          const x = g.image;
          if (x && x.height > 0) {
            const A = new HM(x.height);
            return A.fromEquirectangularTexture(n, g), t.set(g, A), g.addEventListener("dispose", h), u(A.texture, g.mapping);
          } else
            return null;
        }
    }
    return g;
  }
  function c(g) {
    if (g && g.isTexture) {
      const _ = g.mapping, x = _ === xm || _ === Sm, A = _ === ka || _ === dl;
      if (x || A) {
        let b = e.get(g);
        const y = b !== void 0 ? b.texture.pmremVersion : 0;
        if (g.isRenderTargetTexture && g.pmremVersion !== y)
          return s === null && (s = new nb(n)), b = x ? s.fromEquirectangular(g, b) : s.fromCubemap(g, b), b.texture.pmremVersion = g.pmremVersion, e.set(g, b), b.texture;
        if (b !== void 0)
          return b.texture;
        {
          const E = g.image;
          return x && E && E.height > 0 || A && E && d(E) ? (s === null && (s = new nb(n)), b = x ? s.fromEquirectangular(g) : s.fromCubemap(g), b.texture.pmremVersion = g.pmremVersion, e.set(g, b), g.addEventListener("dispose", m), b.texture) : null;
        }
      }
    }
    return g;
  }
  function u(g, _) {
    return _ === xm ? g.mapping = ka : _ === Sm && (g.mapping = dl), g;
  }
  function d(g) {
    let _ = 0;
    const x = 6;
    for (let A = 0; A < x; A++)
      g[A] !== void 0 && _++;
    return _ === x;
  }
  function h(g) {
    const _ = g.target;
    _.removeEventListener("dispose", h);
    const x = t.get(_);
    x !== void 0 && (t.delete(_), x.dispose());
  }
  function m(g) {
    const _ = g.target;
    _.removeEventListener("dispose", m);
    const x = e.get(_);
    x !== void 0 && (e.delete(_), x.dispose());
  }
  function p() {
    t = /* @__PURE__ */ new WeakMap(), e = /* @__PURE__ */ new WeakMap(), s !== null && (s.dispose(), s = null);
  }
  return {
    get: a,
    dispose: p
  };
}
function WD(n) {
  const t = {};
  function e(s) {
    if (t[s] !== void 0)
      return t[s];
    const a = n.getExtension(s);
    return t[s] = a, a;
  }
  return {
    has: function(s) {
      return e(s) !== 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(s) {
      const a = e(s);
      return a === null && Td("WebGLRenderer: " + s + " extension not supported."), a;
    }
  };
}
function YD(n, t, e, s) {
  const a = {}, o = /* @__PURE__ */ new WeakMap();
  function c(p) {
    const g = p.target;
    g.index !== null && t.remove(g.index);
    for (const x in g.attributes)
      t.remove(g.attributes[x]);
    g.removeEventListener("dispose", c), delete a[g.id];
    const _ = o.get(g);
    _ && (t.remove(_), o.delete(g)), s.releaseStatesOfGeometry(g), g.isInstancedBufferGeometry === !0 && delete g._maxInstanceCount, e.memory.geometries--;
  }
  function u(p, g) {
    return a[g.id] === !0 || (g.addEventListener("dispose", c), a[g.id] = !0, e.memory.geometries++), g;
  }
  function d(p) {
    const g = p.attributes;
    for (const _ in g)
      t.update(g[_], n.ARRAY_BUFFER);
  }
  function h(p) {
    const g = [], _ = p.index, x = p.attributes.position;
    let A = 0;
    if (x === void 0)
      return;
    if (_ !== null) {
      const E = _.array;
      A = _.version;
      for (let w = 0, M = E.length; w < M; w += 3) {
        const O = E[w + 0], C = E[w + 1], D = E[w + 2];
        g.push(O, C, C, D, D, O);
      }
    } else {
      const E = x.array;
      A = x.version;
      for (let w = 0, M = E.length / 3 - 1; w < M; w += 3) {
        const O = w + 0, C = w + 1, D = w + 2;
        g.push(O, C, C, D, D, O);
      }
    }
    const b = new (x.count >= 65535 ? OM : NM)(g, 1);
    b.version = A;
    const y = o.get(p);
    y && t.remove(y), o.set(p, b);
  }
  function m(p) {
    const g = o.get(p);
    if (g) {
      const _ = p.index;
      _ !== null && g.version < _.version && h(p);
    } else
      h(p);
    return o.get(p);
  }
  return {
    get: u,
    update: d,
    getWireframeAttribute: m
  };
}
function jD(n, t, e) {
  let s;
  function a(g) {
    s = g;
  }
  let o, c;
  function u(g) {
    o = g.type, c = g.bytesPerElement;
  }
  function d(g, _) {
    n.drawElements(s, _, o, g * c), e.update(_, s, 1);
  }
  function h(g, _, x) {
    x !== 0 && (n.drawElementsInstanced(s, _, o, g * c, x), e.update(_, s, x));
  }
  function m(g, _, x) {
    if (x === 0) return;
    t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(s, _, 0, o, g, 0, x);
    let b = 0;
    for (let y = 0; y < x; y++)
      b += _[y];
    e.update(b, s, 1);
  }
  function p(g, _, x, A) {
    if (x === 0) return;
    const b = t.get("WEBGL_multi_draw");
    if (b === null)
      for (let y = 0; y < g.length; y++)
        h(g[y] / c, _[y], A[y]);
    else {
      b.multiDrawElementsInstancedWEBGL(s, _, 0, o, g, 0, A, 0, x);
      let y = 0;
      for (let E = 0; E < x; E++)
        y += _[E] * A[E];
      e.update(y, s, 1);
    }
  }
  this.setMode = a, this.setIndex = u, this.render = d, this.renderInstances = h, this.renderMultiDraw = m, this.renderMultiDrawInstances = p;
}
function qD(n) {
  const t = {
    geometries: 0,
    textures: 0
  }, e = {
    frame: 0,
    calls: 0,
    triangles: 0,
    points: 0,
    lines: 0
  };
  function s(o, c, u) {
    switch (e.calls++, c) {
      case n.TRIANGLES:
        e.triangles += u * (o / 3);
        break;
      case n.LINES:
        e.lines += u * (o / 2);
        break;
      case n.LINE_STRIP:
        e.lines += u * (o - 1);
        break;
      case n.LINE_LOOP:
        e.lines += u * o;
        break;
      case n.POINTS:
        e.points += u * o;
        break;
      default:
        Ie("WebGLInfo: Unknown draw mode:", c);
        break;
    }
  }
  function a() {
    e.calls = 0, e.triangles = 0, e.points = 0, e.lines = 0;
  }
  return {
    memory: t,
    render: e,
    programs: null,
    autoReset: !0,
    reset: a,
    update: s
  };
}
function ZD(n, t, e) {
  const s = /* @__PURE__ */ new WeakMap(), a = new Je();
  function o(c, u, d) {
    const h = c.morphTargetInfluences, m = u.morphAttributes.position || u.morphAttributes.normal || u.morphAttributes.color, p = m !== void 0 ? m.length : 0;
    let g = s.get(u);
    if (g === void 0 || g.count !== p) {
      let L = function() {
        D.dispose(), s.delete(u), u.removeEventListener("dispose", L);
      };
      g !== void 0 && g.texture.dispose();
      const _ = u.morphAttributes.position !== void 0, x = u.morphAttributes.normal !== void 0, A = u.morphAttributes.color !== void 0, b = u.morphAttributes.position || [], y = u.morphAttributes.normal || [], E = u.morphAttributes.color || [];
      let w = 0;
      _ === !0 && (w = 1), x === !0 && (w = 2), A === !0 && (w = 3);
      let M = u.attributes.position.count * w, O = 1;
      M > t.maxTextureSize && (O = Math.ceil(M / t.maxTextureSize), M = t.maxTextureSize);
      const C = new Float32Array(M * O * 4 * p), D = new TM(C, M, O, p);
      D.type = Di, D.needsUpdate = !0;
      const T = w * 4;
      for (let z = 0; z < p; z++) {
        const R = b[z], B = y[z], H = E[z], U = M * O * 4 * z;
        for (let V = 0; V < R.count; V++) {
          const N = V * T;
          _ === !0 && (a.fromBufferAttribute(R, V), C[U + N + 0] = a.x, C[U + N + 1] = a.y, C[U + N + 2] = a.z, C[U + N + 3] = 0), x === !0 && (a.fromBufferAttribute(B, V), C[U + N + 4] = a.x, C[U + N + 5] = a.y, C[U + N + 6] = a.z, C[U + N + 7] = 0), A === !0 && (a.fromBufferAttribute(H, V), C[U + N + 8] = a.x, C[U + N + 9] = a.y, C[U + N + 10] = a.z, C[U + N + 11] = H.itemSize === 4 ? a.w : 1);
        }
      }
      g = {
        count: p,
        texture: D,
        size: new ae(M, O)
      }, s.set(u, g), u.addEventListener("dispose", L);
    }
    if (c.isInstancedMesh === !0 && c.morphTexture !== null)
      d.getUniforms().setValue(n, "morphTexture", c.morphTexture, e);
    else {
      let _ = 0;
      for (let A = 0; A < h.length; A++)
        _ += h[A];
      const x = u.morphTargetsRelative ? 1 : 1 - _;
      d.getUniforms().setValue(n, "morphTargetBaseInfluence", x), d.getUniforms().setValue(n, "morphTargetInfluences", h);
    }
    d.getUniforms().setValue(n, "morphTargetsTexture", g.texture, e), d.getUniforms().setValue(n, "morphTargetsTextureSize", g.size);
  }
  return {
    update: o
  };
}
function $D(n, t, e, s, a) {
  let o = /* @__PURE__ */ new WeakMap();
  function c(h) {
    const m = a.render.frame, p = h.geometry, g = t.get(h, p);
    if (o.get(g) !== m && (t.update(g), o.set(g, m)), h.isInstancedMesh && (h.hasEventListener("dispose", d) === !1 && h.addEventListener("dispose", d), o.get(h) !== m && (e.update(h.instanceMatrix, n.ARRAY_BUFFER), h.instanceColor !== null && e.update(h.instanceColor, n.ARRAY_BUFFER), o.set(h, m))), h.isSkinnedMesh) {
      const _ = h.skeleton;
      o.get(_) !== m && (_.update(), o.set(_, m));
    }
    return g;
  }
  function u() {
    o = /* @__PURE__ */ new WeakMap();
  }
  function d(h) {
    const m = h.target;
    m.removeEventListener("dispose", d), s.releaseStatesOfObject(m), e.remove(m.instanceMatrix), m.instanceColor !== null && e.remove(m.instanceColor);
  }
  return {
    update: c,
    dispose: u
  };
}
const KD = {
  [uM]: "LINEAR_TONE_MAPPING",
  [fM]: "REINHARD_TONE_MAPPING",
  [dM]: "CINEON_TONE_MAPPING",
  [hM]: "ACES_FILMIC_TONE_MAPPING",
  [mM]: "AGX_TONE_MAPPING",
  [gM]: "NEUTRAL_TONE_MAPPING",
  [pM]: "CUSTOM_TONE_MAPPING"
};
function QD(n, t, e, s, a) {
  const o = new As(t, e, {
    type: n,
    depthBuffer: s,
    stencilBuffer: a
  }), c = new As(t, e, {
    type: dr,
    depthBuffer: !1,
    stencilBuffer: !1
  }), u = new In();
  u.setAttribute("position", new _n([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)), u.setAttribute("uv", new _n([0, 2, 0, 0, 2, 0], 2));
  const d = new nv({
    uniforms: {
      tDiffuse: { value: null }
    },
    vertexShader: (
      /* glsl */
      `
			precision highp float;

			uniform mat4 modelViewMatrix;
			uniform mat4 projectionMatrix;

			attribute vec3 position;
			attribute vec2 uv;

			varying vec2 vUv;

			void main() {
				vUv = uv;
				gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
			}`
    ),
    fragmentShader: (
      /* glsl */
      `
			precision highp float;

			uniform sampler2D tDiffuse;

			varying vec2 vUv;

			#include <tonemapping_pars_fragment>
			#include <colorspace_pars_fragment>

			void main() {
				gl_FragColor = texture2D( tDiffuse, vUv );

				#ifdef LINEAR_TONE_MAPPING
					gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
				#elif defined( REINHARD_TONE_MAPPING )
					gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
				#elif defined( CINEON_TONE_MAPPING )
					gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
				#elif defined( ACES_FILMIC_TONE_MAPPING )
					gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
				#elif defined( AGX_TONE_MAPPING )
					gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
				#elif defined( NEUTRAL_TONE_MAPPING )
					gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
				#elif defined( CUSTOM_TONE_MAPPING )
					gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
				#endif

				#ifdef SRGB_TRANSFER
					gl_FragColor = sRGBTransferOETF( gl_FragColor );
				#endif
			}`
    ),
    depthTest: !1,
    depthWrite: !1
  }), h = new Ln(u, d), m = new ns(-1, 1, 1, -1, 0, 1);
  let p = null, g = null, _ = !1, x, A = null, b = [], y = !1;
  this.setSize = function(E, w) {
    o.setSize(E, w), c.setSize(E, w);
    for (let M = 0; M < b.length; M++) {
      const O = b[M];
      O.setSize && O.setSize(E, w);
    }
  }, this.setEffects = function(E) {
    b = E, y = b.length > 0 && b[0].isRenderPass === !0;
    const w = o.width, M = o.height;
    for (let O = 0; O < b.length; O++) {
      const C = b[O];
      C.setSize && C.setSize(w, M);
    }
  }, this.begin = function(E, w) {
    if (_ || E.toneMapping === ws && b.length === 0) return !1;
    if (A = w, w !== null) {
      const M = w.width, O = w.height;
      (o.width !== M || o.height !== O) && this.setSize(M, O);
    }
    return y === !1 && E.setRenderTarget(o), x = E.toneMapping, E.toneMapping = ws, !0;
  }, this.hasRenderPass = function() {
    return y;
  }, this.end = function(E, w) {
    E.toneMapping = x, _ = !0;
    let M = o, O = c;
    for (let C = 0; C < b.length; C++) {
      const D = b[C];
      if (D.enabled !== !1 && (D.render(E, O, M, w), D.needsSwap !== !1)) {
        const T = M;
        M = O, O = T;
      }
    }
    if (p !== E.outputColorSpace || g !== E.toneMapping) {
      p = E.outputColorSpace, g = E.toneMapping, d.defines = {}, Be.getTransfer(p) === We && (d.defines.SRGB_TRANSFER = "");
      const C = KD[g];
      C && (d.defines[C] = ""), d.needsUpdate = !0;
    }
    d.uniforms.tDiffuse.value = M.texture, E.setRenderTarget(A), E.render(h, m), A = null, _ = !1;
  }, this.isCompositing = function() {
    return _;
  }, this.dispose = function() {
    o.dispose(), c.dispose(), u.dispose(), d.dispose();
  };
}
const VM = /* @__PURE__ */ new Jn(), _0 = /* @__PURE__ */ new kc(1, 1), GM = /* @__PURE__ */ new TM(), kM = /* @__PURE__ */ new m3(), XM = /* @__PURE__ */ new PM(), ab = [], ob = [], lb = new Float32Array(16), cb = new Float32Array(9), ub = new Float32Array(4);
function Ml(n, t, e) {
  const s = n[0];
  if (s <= 0 || s > 0) return n;
  const a = t * e;
  let o = ab[a];
  if (o === void 0 && (o = new Float32Array(a), ab[a] = o), t !== 0) {
    s.toArray(o, 0);
    for (let c = 1, u = 0; c !== t; ++c)
      u += e, n[c].toArray(o, u);
  }
  return o;
}
function Un(n, t) {
  if (n.length !== t.length) return !1;
  for (let e = 0, s = n.length; e < s; e++)
    if (n[e] !== t[e]) return !1;
  return !0;
}
function Pn(n, t) {
  for (let e = 0, s = t.length; e < s; e++)
    n[e] = t[e];
}
function Qd(n, t) {
  let e = ob[t];
  e === void 0 && (e = new Int32Array(t), ob[t] = e);
  for (let s = 0; s !== t; ++s)
    e[s] = n.allocateTextureUnit();
  return e;
}
function JD(n, t) {
  const e = this.cache;
  e[0] !== t && (n.uniform1f(this.addr, t), e[0] = t);
}
function tN(n, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y) && (n.uniform2f(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y);
  else {
    if (Un(e, t)) return;
    n.uniform2fv(this.addr, t), Pn(e, t);
  }
}
function eN(n, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (n.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) && (n.uniform3f(this.addr, t.r, t.g, t.b), e[0] = t.r, e[1] = t.g, e[2] = t.b);
  else {
    if (Un(e, t)) return;
    n.uniform3fv(this.addr, t), Pn(e, t);
  }
}
function nN(n, 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) && (n.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 (Un(e, t)) return;
    n.uniform4fv(this.addr, t), Pn(e, t);
  }
}
function iN(n, t) {
  const e = this.cache, s = t.elements;
  if (s === void 0) {
    if (Un(e, t)) return;
    n.uniformMatrix2fv(this.addr, !1, t), Pn(e, t);
  } else {
    if (Un(e, s)) return;
    ub.set(s), n.uniformMatrix2fv(this.addr, !1, ub), Pn(e, s);
  }
}
function sN(n, t) {
  const e = this.cache, s = t.elements;
  if (s === void 0) {
    if (Un(e, t)) return;
    n.uniformMatrix3fv(this.addr, !1, t), Pn(e, t);
  } else {
    if (Un(e, s)) return;
    cb.set(s), n.uniformMatrix3fv(this.addr, !1, cb), Pn(e, s);
  }
}
function rN(n, t) {
  const e = this.cache, s = t.elements;
  if (s === void 0) {
    if (Un(e, t)) return;
    n.uniformMatrix4fv(this.addr, !1, t), Pn(e, t);
  } else {
    if (Un(e, s)) return;
    lb.set(s), n.uniformMatrix4fv(this.addr, !1, lb), Pn(e, s);
  }
}
function aN(n, t) {
  const e = this.cache;
  e[0] !== t && (n.uniform1i(this.addr, t), e[0] = t);
}
function oN(n, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y) && (n.uniform2i(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y);
  else {
    if (Un(e, t)) return;
    n.uniform2iv(this.addr, t), Pn(e, t);
  }
}
function lN(n, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (n.uniform3i(this.addr, t.x, t.y, t.z), e[0] = t.x, e[1] = t.y, e[2] = t.z);
  else {
    if (Un(e, t)) return;
    n.uniform3iv(this.addr, t), Pn(e, t);
  }
}
function cN(n, 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) && (n.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 (Un(e, t)) return;
    n.uniform4iv(this.addr, t), Pn(e, t);
  }
}
function uN(n, t) {
  const e = this.cache;
  e[0] !== t && (n.uniform1ui(this.addr, t), e[0] = t);
}
function fN(n, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y) && (n.uniform2ui(this.addr, t.x, t.y), e[0] = t.x, e[1] = t.y);
  else {
    if (Un(e, t)) return;
    n.uniform2uiv(this.addr, t), Pn(e, t);
  }
}
function dN(n, t) {
  const e = this.cache;
  if (t.x !== void 0)
    (e[0] !== t.x || e[1] !== t.y || e[2] !== t.z) && (n.uniform3ui(this.addr, t.x, t.y, t.z), e[0] = t.x, e[1] = t.y, e[2] = t.z);
  else {
    if (Un(e, t)) return;
    n.uniform3uiv(this.addr, t), Pn(e, t);
  }
}
function hN(n, 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) && (n.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 (Un(e, t)) return;
    n.uniform4uiv(this.addr, t), Pn(e, t);
  }
}
function pN(n, t, e) {
  const s = this.cache, a = e.allocateTextureUnit();
  s[0] !== a && (n.uniform1i(this.addr, a), s[0] = a);
  let o;
  this.type === n.SAMPLER_2D_SHADOW ? (_0.compareFunction = e.isReversedDepthBuffer() ? Z0 : q0, o = _0) : o = VM, e.setTexture2D(t || o, a);
}
function mN(n, t, e) {
  const s = this.cache, a = e.allocateTextureUnit();
  s[0] !== a && (n.uniform1i(this.addr, a), s[0] = a), e.setTexture3D(t || kM, a);
}
function gN(n, t, e) {
  const s = this.cache, a = e.allocateTextureUnit();
  s[0] !== a && (n.uniform1i(this.addr, a), s[0] = a), e.setTextureCube(t || XM, a);
}
function vN(n, t, e) {
  const s = this.cache, a = e.allocateTextureUnit();
  s[0] !== a && (n.uniform1i(this.addr, a), s[0] = a), e.setTexture2DArray(t || GM, a);
}
function _N(n) {
  switch (n) {
    case 5126:
      return JD;
    // FLOAT
    case 35664:
      return tN;
    // _VEC2
    case 35665:
      return eN;
    // _VEC3
    case 35666:
      return nN;
    // _VEC4
    case 35674:
      return iN;
    // _MAT2
    case 35675:
      return sN;
    // _MAT3
    case 35676:
      return rN;
    // _MAT4
    case 5124:
    case 35670:
      return aN;
    // INT, BOOL
    case 35667:
    case 35671:
      return oN;
    // _VEC2
    case 35668:
    case 35672:
      return lN;
    // _VEC3
    case 35669:
    case 35673:
      return cN;
    // _VEC4
    case 5125:
      return uN;
    // UINT
    case 36294:
      return fN;
    // _VEC2
    case 36295:
      return dN;
    // _VEC3
    case 36296:
      return hN;
    // _VEC4
    case 35678:
    // SAMPLER_2D
    case 36198:
    // SAMPLER_EXTERNAL_OES
    case 36298:
    // INT_SAMPLER_2D
    case 36306:
    // UNSIGNED_INT_SAMPLER_2D
    case 35682:
      return pN;
    case 35679:
    // SAMPLER_3D
    case 36299:
    // INT_SAMPLER_3D
    case 36307:
      return mN;
    case 35680:
    // SAMPLER_CUBE
    case 36300:
    // INT_SAMPLER_CUBE
    case 36308:
    // UNSIGNED_INT_SAMPLER_CUBE
    case 36293:
      return gN;
    case 36289:
    // SAMPLER_2D_ARRAY
    case 36303:
    // INT_SAMPLER_2D_ARRAY
    case 36311:
    // UNSIGNED_INT_SAMPLER_2D_ARRAY
    case 36292:
      return vN;
  }
}
function yN(n, t) {
  n.uniform1fv(this.addr, t);
}
function xN(n, t) {
  const e = Ml(t, this.size, 2);
  n.uniform2fv(this.addr, e);
}
function SN(n, t) {
  const e = Ml(t, this.size, 3);
  n.uniform3fv(this.addr, e);
}
function bN(n, t) {
  const e = Ml(t, this.size, 4);
  n.uniform4fv(this.addr, e);
}
function MN(n, t) {
  const e = Ml(t, this.size, 4);
  n.uniformMatrix2fv(this.addr, !1, e);
}
function EN(n, t) {
  const e = Ml(t, this.size, 9);
  n.uniformMatrix3fv(this.addr, !1, e);
}
function wN(n, t) {
  const e = Ml(t, this.size, 16);
  n.uniformMatrix4fv(this.addr, !1, e);
}
function AN(n, t) {
  n.uniform1iv(this.addr, t);
}
function TN(n, t) {
  n.uniform2iv(this.addr, t);
}
function CN(n, t) {
  n.uniform3iv(this.addr, t);
}
function RN(n, t) {
  n.uniform4iv(this.addr, t);
}
function DN(n, t) {
  n.uniform1uiv(this.addr, t);
}
function NN(n, t) {
  n.uniform2uiv(this.addr, t);
}
function ON(n, t) {
  n.uniform3uiv(this.addr, t);
}
function LN(n, t) {
  n.uniform4uiv(this.addr, t);
}
function UN(n, t, e) {
  const s = this.cache, a = t.length, o = Qd(e, a);
  Un(s, o) || (n.uniform1iv(this.addr, o), Pn(s, o));
  let c;
  this.type === n.SAMPLER_2D_SHADOW ? c = _0 : c = VM;
  for (let u = 0; u !== a; ++u)
    e.setTexture2D(t[u] || c, o[u]);
}
function PN(n, t, e) {
  const s = this.cache, a = t.length, o = Qd(e, a);
  Un(s, o) || (n.uniform1iv(this.addr, o), Pn(s, o));
  for (let c = 0; c !== a; ++c)
    e.setTexture3D(t[c] || kM, o[c]);
}
function IN(n, t, e) {
  const s = this.cache, a = t.length, o = Qd(e, a);
  Un(s, o) || (n.uniform1iv(this.addr, o), Pn(s, o));
  for (let c = 0; c !== a; ++c)
    e.setTextureCube(t[c] || XM, o[c]);
}
function BN(n, t, e) {
  const s = this.cache, a = t.length, o = Qd(e, a);
  Un(s, o) || (n.uniform1iv(this.addr, o), Pn(s, o));
  for (let c = 0; c !== a; ++c)
    e.setTexture2DArray(t[c] || GM, o[c]);
}
function zN(n) {
  switch (n) {
    case 5126:
      return yN;
    // FLOAT
    case 35664:
      return xN;
    // _VEC2
    case 35665:
      return SN;
    // _VEC3
    case 35666:
      return bN;
    // _VEC4
    case 35674:
      return MN;
    // _MAT2
    case 35675:
      return EN;
    // _MAT3
    case 35676:
      return wN;
    // _MAT4
    case 5124:
    case 35670:
      return AN;
    // INT, BOOL
    case 35667:
    case 35671:
      return TN;
    // _VEC2
    case 35668:
    case 35672:
      return CN;
    // _VEC3
    case 35669:
    case 35673:
      return RN;
    // _VEC4
    case 5125:
      return DN;
    // UINT
    case 36294:
      return NN;
    // _VEC2
    case 36295:
      return ON;
    // _VEC3
    case 36296:
      return LN;
    // _VEC4
    case 35678:
    // SAMPLER_2D
    case 36198:
    // SAMPLER_EXTERNAL_OES
    case 36298:
    // INT_SAMPLER_2D
    case 36306:
    // UNSIGNED_INT_SAMPLER_2D
    case 35682:
      return UN;
    case 35679:
    // SAMPLER_3D
    case 36299:
    // INT_SAMPLER_3D
    case 36307:
      return PN;
    case 35680:
    // SAMPLER_CUBE
    case 36300:
    // INT_SAMPLER_CUBE
    case 36308:
    // UNSIGNED_INT_SAMPLER_CUBE
    case 36293:
      return IN;
    case 36289:
    // SAMPLER_2D_ARRAY
    case 36303:
    // INT_SAMPLER_2D_ARRAY
    case 36311:
    // UNSIGNED_INT_SAMPLER_2D_ARRAY
    case 36292:
      return BN;
  }
}
class FN {
  constructor(t, e, s) {
    this.id = t, this.addr = s, this.cache = [], this.type = e.type, this.setValue = _N(e.type);
  }
}
class HN {
  constructor(t, e, s) {
    this.id = t, this.addr = s, this.cache = [], this.type = e.type, this.size = e.size, this.setValue = zN(e.type);
  }
}
class VN {
  constructor(t) {
    this.id = t, this.seq = [], this.map = {};
  }
  setValue(t, e, s) {
    const a = this.seq;
    for (let o = 0, c = a.length; o !== c; ++o) {
      const u = a[o];
      u.setValue(t, e[u.id], s);
    }
  }
}
const eg = /(\w+)(\])?(\[|\.)?/g;
function fb(n, t) {
  n.seq.push(t), n.map[t.id] = t;
}
function GN(n, t, e) {
  const s = n.name, a = s.length;
  for (eg.lastIndex = 0; ; ) {
    const o = eg.exec(s), c = eg.lastIndex;
    let u = o[1];
    const d = o[2] === "]", h = o[3];
    if (d && (u = u | 0), h === void 0 || h === "[" && c + 2 === a) {
      fb(e, h === void 0 ? new FN(u, n, t) : new HN(u, n, t));
      break;
    } else {
      let p = e.map[u];
      p === void 0 && (p = new VN(u), fb(e, p)), e = p;
    }
  }
}
class gd {
  constructor(t, e) {
    this.seq = [], this.map = {};
    const s = t.getProgramParameter(e, t.ACTIVE_UNIFORMS);
    for (let c = 0; c < s; ++c) {
      const u = t.getActiveUniform(e, c), d = t.getUniformLocation(e, u.name);
      GN(u, d, this);
    }
    const a = [], o = [];
    for (const c of this.seq)
      c.type === t.SAMPLER_2D_SHADOW || c.type === t.SAMPLER_CUBE_SHADOW || c.type === t.SAMPLER_2D_ARRAY_SHADOW ? a.push(c) : o.push(c);
    a.length > 0 && (this.seq = a.concat(o));
  }
  setValue(t, e, s, a) {
    const o = this.map[e];
    o !== void 0 && o.setValue(t, s, a);
  }
  setOptional(t, e, s) {
    const a = e[s];
    a !== void 0 && this.setValue(t, s, a);
  }
  static upload(t, e, s, a) {
    for (let o = 0, c = e.length; o !== c; ++o) {
      const u = e[o], d = s[u.id];
      d.needsUpdate !== !1 && u.setValue(t, d.value, a);
    }
  }
  static seqWithValue(t, e) {
    const s = [];
    for (let a = 0, o = t.length; a !== o; ++a) {
      const c = t[a];
      c.id in e && s.push(c);
    }
    return s;
  }
}
function db(n, t, e) {
  const s = n.createShader(t);
  return n.shaderSource(s, e), n.compileShader(s), s;
}
const kN = 37297;
let XN = 0;
function WN(n, t) {
  const e = n.split(`
`), s = [], a = Math.max(t - 6, 0), o = Math.min(t + 6, e.length);
  for (let c = a; c < o; c++) {
    const u = c + 1;
    s.push(`${u === t ? ">" : " "} ${u}: ${e[c]}`);
  }
  return s.join(`
`);
}
const hb = /* @__PURE__ */ new Me();
function YN(n) {
  Be._getMatrix(hb, Be.workingColorSpace, n);
  const t = `mat3( ${hb.elements.map((e) => e.toFixed(4))} )`;
  switch (Be.getTransfer(n)) {
    case Md:
      return [t, "LinearTransferOETF"];
    case We:
      return [t, "sRGBTransferOETF"];
    default:
      return de("WebGLProgram: Unsupported color space: ", n), [t, "LinearTransferOETF"];
  }
}
function pb(n, t, e) {
  const s = n.getShaderParameter(t, n.COMPILE_STATUS), o = (n.getShaderInfoLog(t) || "").trim();
  if (s && o === "") return "";
  const c = /ERROR: 0:(\d+)/.exec(o);
  if (c) {
    const u = parseInt(c[1]);
    return e.toUpperCase() + `

` + o + `

` + WN(n.getShaderSource(t), u);
  } else
    return o;
}
function jN(n, t) {
  const e = YN(t);
  return [
    `vec4 ${n}( vec4 value ) {`,
    `	return ${e[1]}( vec4( value.rgb * ${e[0]}, value.a ) );`,
    "}"
  ].join(`
`);
}
const qN = {
  [uM]: "Linear",
  [fM]: "Reinhard",
  [dM]: "Cineon",
  [hM]: "ACESFilmic",
  [mM]: "AgX",
  [gM]: "Neutral",
  [pM]: "Custom"
};
function ZN(n, t) {
  const e = qN[t];
  return e === void 0 ? (de("WebGLProgram: Unsupported toneMapping:", t), "vec3 " + n + "( vec3 color ) { return LinearToneMapping( color ); }") : "vec3 " + n + "( vec3 color ) { return " + e + "ToneMapping( color ); }";
}
const qf = /* @__PURE__ */ new st();
function $N() {
  Be.getLuminanceCoefficients(qf);
  const n = qf.x.toFixed(4), t = qf.y.toFixed(4), e = qf.z.toFixed(4);
  return [
    "float luminance( const in vec3 rgb ) {",
    `	const vec3 weights = vec3( ${n}, ${t}, ${e} );`,
    "	return dot( weights, rgb );",
    "}"
  ].join(`
`);
}
function KN(n) {
  return [
    n.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "",
    n.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : ""
  ].filter(Nc).join(`
`);
}
function QN(n) {
  const t = [];
  for (const e in n) {
    const s = n[e];
    s !== !1 && t.push("#define " + e + " " + s);
  }
  return t.join(`
`);
}
function JN(n, t) {
  const e = {}, s = n.getProgramParameter(t, n.ACTIVE_ATTRIBUTES);
  for (let a = 0; a < s; a++) {
    const o = n.getActiveAttrib(t, a), c = o.name;
    let u = 1;
    o.type === n.FLOAT_MAT2 && (u = 2), o.type === n.FLOAT_MAT3 && (u = 3), o.type === n.FLOAT_MAT4 && (u = 4), e[c] = {
      type: o.type,
      location: n.getAttribLocation(t, c),
      locationSize: u
    };
  }
  return e;
}
function Nc(n) {
  return n !== "";
}
function mb(n, t) {
  const e = t.numSpotLightShadows + t.numSpotLightMaps - t.numSpotLightShadowsWithMaps;
  return n.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 gb(n, t) {
  return n.replace(/NUM_CLIPPING_PLANES/g, t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, t.numClippingPlanes - t.numClipIntersection);
}
const tO = /^[ \t]*#include +<([\w\d./]+)>/gm;
function y0(n) {
  return n.replace(tO, nO);
}
const eO = /* @__PURE__ */ new Map();
function nO(n, t) {
  let e = Ee[t];
  if (e === void 0) {
    const s = eO.get(t);
    if (s !== void 0)
      e = Ee[s], de('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', t, s);
    else
      throw new Error("Can not resolve #include <" + t + ">");
  }
  return y0(e);
}
const iO = /#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 vb(n) {
  return n.replace(iO, sO);
}
function sO(n, t, e, s) {
  let a = "";
  for (let o = parseInt(t); o < parseInt(e); o++)
    a += s.replace(/\[\s*i\s*\]/g, "[ " + o + " ]").replace(/UNROLLED_LOOP_INDEX/g, o);
  return a;
}
function _b(n) {
  let t = `precision ${n.precision} float;
	precision ${n.precision} int;
	precision ${n.precision} sampler2D;
	precision ${n.precision} samplerCube;
	precision ${n.precision} sampler3D;
	precision ${n.precision} sampler2DArray;
	precision ${n.precision} sampler2DShadow;
	precision ${n.precision} samplerCubeShadow;
	precision ${n.precision} sampler2DArrayShadow;
	precision ${n.precision} isampler2D;
	precision ${n.precision} isampler3D;
	precision ${n.precision} isamplerCube;
	precision ${n.precision} isampler2DArray;
	precision ${n.precision} usampler2D;
	precision ${n.precision} usampler3D;
	precision ${n.precision} usamplerCube;
	precision ${n.precision} usampler2DArray;
	`;
  return n.precision === "highp" ? t += `
#define HIGH_PRECISION` : n.precision === "mediump" ? t += `
#define MEDIUM_PRECISION` : n.precision === "lowp" && (t += `
#define LOW_PRECISION`), t;
}
const rO = {
  [ud]: "SHADOWMAP_TYPE_PCF",
  [Dc]: "SHADOWMAP_TYPE_VSM"
};
function aO(n) {
  return rO[n.shadowMapType] || "SHADOWMAP_TYPE_BASIC";
}
const oO = {
  [ka]: "ENVMAP_TYPE_CUBE",
  [dl]: "ENVMAP_TYPE_CUBE",
  [Wd]: "ENVMAP_TYPE_CUBE_UV"
};
function lO(n) {
  return n.envMap === !1 ? "ENVMAP_TYPE_CUBE" : oO[n.envMapMode] || "ENVMAP_TYPE_CUBE";
}
const cO = {
  [dl]: "ENVMAP_MODE_REFRACTION"
};
function uO(n) {
  return n.envMap === !1 ? "ENVMAP_MODE_REFLECTION" : cO[n.envMapMode] || "ENVMAP_MODE_REFLECTION";
}
const fO = {
  [H0]: "ENVMAP_BLENDING_MULTIPLY",
  [L2]: "ENVMAP_BLENDING_MIX",
  [U2]: "ENVMAP_BLENDING_ADD"
};
function dO(n) {
  return n.envMap === !1 ? "ENVMAP_BLENDING_NONE" : fO[n.combine] || "ENVMAP_BLENDING_NONE";
}
function hO(n) {
  const t = n.envMapCubeUVHeight;
  if (t === null) return null;
  const e = Math.log2(t) - 2, s = 1 / t;
  return { texelWidth: 1 / (3 * Math.max(Math.pow(2, e), 112)), texelHeight: s, maxMip: e };
}
function pO(n, t, e, s) {
  const a = n.getContext(), o = e.defines;
  let c = e.vertexShader, u = e.fragmentShader;
  const d = aO(e), h = lO(e), m = uO(e), p = dO(e), g = hO(e), _ = KN(e), x = QN(o), A = a.createProgram();
  let b, y, E = e.glslVersion ? "#version " + e.glslVersion + `
` : "";
  e.isRawShaderMaterial ? (b = [
    "#define SHADER_TYPE " + e.shaderType,
    "#define SHADER_NAME " + e.shaderName,
    x
  ].filter(Nc).join(`
`), b.length > 0 && (b += `
`), y = [
    "#define SHADER_TYPE " + e.shaderType,
    "#define SHADER_NAME " + e.shaderName,
    x
  ].filter(Nc).join(`
`), y.length > 0 && (y += `
`)) : (b = [
    _b(e),
    "#define SHADER_TYPE " + e.shaderType,
    "#define SHADER_NAME " + e.shaderName,
    x,
    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 " + m : "",
    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 " + d : "",
    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(Nc).join(`
`), y = [
    _b(e),
    "#define SHADER_TYPE " + e.shaderType,
    "#define SHADER_NAME " + e.shaderName,
    x,
    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 " + m : "",
    e.envMap ? "#define " + p : "",
    g ? "#define CUBEUV_TEXEL_WIDTH " + g.texelWidth : "",
    g ? "#define CUBEUV_TEXEL_HEIGHT " + g.texelHeight : "",
    g ? "#define CUBEUV_MAX_MIP " + g.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 ? "#define USE_COLOR" : "",
    e.vertexAlphas || e.batchingColor ? "#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 " + d : "",
    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 !== ws ? "#define TONE_MAPPING" : "",
    e.toneMapping !== ws ? Ee.tonemapping_pars_fragment : "",
    // this code is required here because it is used by the toneMapping() function defined below
    e.toneMapping !== ws ? ZN("toneMapping", e.toneMapping) : "",
    e.dithering ? "#define DITHERING" : "",
    e.opaque ? "#define OPAQUE" : "",
    Ee.colorspace_pars_fragment,
    // this code is required here because it is used by the various encoding/decoding function defined below
    jN("linearToOutputTexel", e.outputColorSpace),
    $N(),
    e.useDepthPacking ? "#define DEPTH_PACKING " + e.depthPacking : "",
    `
`
  ].filter(Nc).join(`
`)), c = y0(c), c = mb(c, e), c = gb(c, e), u = y0(u), u = mb(u, e), u = gb(u, e), c = vb(c), u = vb(u), e.isRawShaderMaterial !== !0 && (E = `#version 300 es
`, b = [
    _,
    "#define attribute in",
    "#define varying out",
    "#define texture2D texture"
  ].join(`
`) + `
` + b, y = [
    "#define varying in",
    e.glslVersion === Ed ? "" : "layout(location = 0) out highp vec4 pc_fragColor;",
    e.glslVersion === Ed ? "" : "#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(`
`) + `
` + y);
  const w = E + b + c, M = E + y + u, O = db(a, a.VERTEX_SHADER, w), C = db(a, a.FRAGMENT_SHADER, M);
  a.attachShader(A, O), a.attachShader(A, C), e.index0AttributeName !== void 0 ? a.bindAttribLocation(A, 0, e.index0AttributeName) : e.morphTargets === !0 && a.bindAttribLocation(A, 0, "position"), a.linkProgram(A);
  function D(R) {
    if (n.debug.checkShaderErrors) {
      const B = a.getProgramInfoLog(A) || "", H = a.getShaderInfoLog(O) || "", U = a.getShaderInfoLog(C) || "", V = B.trim(), N = H.trim(), I = U.trim();
      let k = !0, X = !0;
      if (a.getProgramParameter(A, a.LINK_STATUS) === !1)
        if (k = !1, typeof n.debug.onShaderError == "function")
          n.debug.onShaderError(a, A, O, C);
        else {
          const Q = pb(a, O, "vertex"), F = pb(a, C, "fragment");
          Ie(
            "THREE.WebGLProgram: Shader Error " + a.getError() + " - VALIDATE_STATUS " + a.getProgramParameter(A, a.VALIDATE_STATUS) + `

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

Program Info Log: ` + V + `
` + Q + `
` + F
          );
        }
      else V !== "" ? de("WebGLProgram: Program Info Log:", V) : (N === "" || I === "") && (X = !1);
      X && (R.diagnostics = {
        runnable: k,
        programLog: V,
        vertexShader: {
          log: N,
          prefix: b
        },
        fragmentShader: {
          log: I,
          prefix: y
        }
      });
    }
    a.deleteShader(O), a.deleteShader(C), T = new gd(a, A), L = JN(a, A);
  }
  let T;
  this.getUniforms = function() {
    return T === void 0 && D(this), T;
  };
  let L;
  this.getAttributes = function() {
    return L === void 0 && D(this), L;
  };
  let z = e.rendererExtensionParallelShaderCompile === !1;
  return this.isReady = function() {
    return z === !1 && (z = a.getProgramParameter(A, kN)), z;
  }, this.destroy = function() {
    s.releaseStatesOfProgram(this), a.deleteProgram(A), this.program = void 0;
  }, this.type = e.shaderType, this.name = e.shaderName, this.id = XN++, this.cacheKey = t, this.usedTimes = 1, this.program = A, this.vertexShader = O, this.fragmentShader = C, this;
}
let mO = 0;
class gO {
  constructor() {
    this.shaderCache = /* @__PURE__ */ new Map(), this.materialCache = /* @__PURE__ */ new Map();
  }
  update(t) {
    const e = t.vertexShader, s = t.fragmentShader, a = this._getShaderStage(e), o = this._getShaderStage(s), c = this._getShaderCacheForMaterial(t);
    return c.has(a) === !1 && (c.add(a), a.usedTimes++), c.has(o) === !1 && (c.add(o), o.usedTimes++), this;
  }
  remove(t) {
    const e = this.materialCache.get(t);
    for (const s of e)
      s.usedTimes--, s.usedTimes === 0 && this.shaderCache.delete(s.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 s = e.get(t);
    return s === void 0 && (s = /* @__PURE__ */ new Set(), e.set(t, s)), s;
  }
  _getShaderStage(t) {
    const e = this.shaderCache;
    let s = e.get(t);
    return s === void 0 && (s = new vO(t), e.set(t, s)), s;
  }
}
class vO {
  constructor(t) {
    this.id = mO++, this.code = t, this.usedTimes = 0;
  }
}
function _O(n, t, e, s, a, o) {
  const c = new CM(), u = new gO(), d = /* @__PURE__ */ new Set(), h = [], m = /* @__PURE__ */ new Map(), p = s.logarithmicDepthBuffer;
  let g = s.precision;
  const _ = {
    MeshDepthMaterial: "depth",
    MeshDistanceMaterial: "distance",
    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 x(T) {
    return d.add(T), T === 0 ? "uv" : `uv${T}`;
  }
  function A(T, L, z, R, B) {
    const H = R.fog, U = B.geometry, V = T.isMeshStandardMaterial || T.isMeshLambertMaterial || T.isMeshPhongMaterial ? R.environment : null, N = T.isMeshStandardMaterial || T.isMeshLambertMaterial && !T.envMap || T.isMeshPhongMaterial && !T.envMap, I = t.get(T.envMap || V, N), k = I && I.mapping === Wd ? I.image.height : null, X = _[T.type];
    T.precision !== null && (g = s.getMaxPrecision(T.precision), g !== T.precision && de("WebGLProgram.getParameters:", T.precision, "not supported, using", g, "instead."));
    const Q = U.morphAttributes.position || U.morphAttributes.normal || U.morphAttributes.color, F = Q !== void 0 ? Q.length : 0;
    let W = 0;
    U.morphAttributes.position !== void 0 && (W = 1), U.morphAttributes.normal !== void 0 && (W = 2), U.morphAttributes.color !== void 0 && (W = 3);
    let et, $, j, Y;
    if (X) {
      const Oe = di[X];
      et = Oe.vertexShader, $ = Oe.fragmentShader;
    } else
      et = T.vertexShader, $ = T.fragmentShader, u.update(T), j = u.getVertexShaderID(T), Y = u.getFragmentShaderID(T);
    const K = n.getRenderTarget(), J = n.state.buffers.depth.getReversed(), rt = B.isInstancedMesh === !0, dt = B.isBatchedMesh === !0, yt = !!T.map, Pt = !!T.matcap, Lt = !!I, zt = !!T.aoMap, Xt = !!T.lightMap, Ft = !!T.bumpMap, ve = !!T.normalMap, it = !!T.displacementMap, Ue = !!T.emissiveMap, xe = !!T.metalnessMap, Re = !!T.roughnessMap, Kt = T.anisotropy > 0, tt = T.clearcoat > 0, G = T.dispersion > 0, ct = T.iridescence > 0, Et = T.sheen > 0, Rt = T.transmission > 0, Mt = Kt && !!T.anisotropyMap, Jt = tt && !!T.clearcoatMap, It = tt && !!T.clearcoatNormalMap, se = tt && !!T.clearcoatRoughnessMap, le = ct && !!T.iridescenceMap, Ot = ct && !!T.iridescenceThicknessMap, Dt = Et && !!T.sheenColorMap, Wt = Et && !!T.sheenRoughnessMap, kt = !!T.specularMap, Yt = !!T.specularColorMap, _e = !!T.specularIntensityMap, lt = Rt && !!T.transmissionMap, Bt = Rt && !!T.thicknessMap, Ut = !!T.gradientMap, jt = !!T.alphaMap, Nt = T.alphaTest > 0, bt = !!T.alphaHash, Zt = !!T.extensions;
    let fe = ws;
    T.toneMapped && (K === null || K.isXRRenderTarget === !0) && (fe = n.toneMapping);
    const He = {
      shaderID: X,
      shaderType: T.type,
      shaderName: T.name,
      vertexShader: et,
      fragmentShader: $,
      defines: T.defines,
      customVertexShaderID: j,
      customFragmentShaderID: Y,
      isRawShaderMaterial: T.isRawShaderMaterial === !0,
      glslVersion: T.glslVersion,
      precision: g,
      batching: dt,
      batchingColor: dt && B._colorsTexture !== null,
      instancing: rt,
      instancingColor: rt && B.instanceColor !== null,
      instancingMorph: rt && B.morphTexture !== null,
      outputColorSpace: K === null ? n.outputColorSpace : K.isXRRenderTarget === !0 ? K.texture.colorSpace : pl,
      alphaToCoverage: !!T.alphaToCoverage,
      map: yt,
      matcap: Pt,
      envMap: Lt,
      envMapMode: Lt && I.mapping,
      envMapCubeUVHeight: k,
      aoMap: zt,
      lightMap: Xt,
      bumpMap: Ft,
      normalMap: ve,
      displacementMap: it,
      emissiveMap: Ue,
      normalMapObjectSpace: ve && T.normalMapType === B2,
      normalMapTangentSpace: ve && T.normalMapType === EM,
      metalnessMap: xe,
      roughnessMap: Re,
      anisotropy: Kt,
      anisotropyMap: Mt,
      clearcoat: tt,
      clearcoatMap: Jt,
      clearcoatNormalMap: It,
      clearcoatRoughnessMap: se,
      dispersion: G,
      iridescence: ct,
      iridescenceMap: le,
      iridescenceThicknessMap: Ot,
      sheen: Et,
      sheenColorMap: Dt,
      sheenRoughnessMap: Wt,
      specularMap: kt,
      specularColorMap: Yt,
      specularIntensityMap: _e,
      transmission: Rt,
      transmissionMap: lt,
      thicknessMap: Bt,
      gradientMap: Ut,
      opaque: T.transparent === !1 && T.blending === ol && T.alphaToCoverage === !1,
      alphaMap: jt,
      alphaTest: Nt,
      alphaHash: bt,
      combine: T.combine,
      //
      mapUv: yt && x(T.map.channel),
      aoMapUv: zt && x(T.aoMap.channel),
      lightMapUv: Xt && x(T.lightMap.channel),
      bumpMapUv: Ft && x(T.bumpMap.channel),
      normalMapUv: ve && x(T.normalMap.channel),
      displacementMapUv: it && x(T.displacementMap.channel),
      emissiveMapUv: Ue && x(T.emissiveMap.channel),
      metalnessMapUv: xe && x(T.metalnessMap.channel),
      roughnessMapUv: Re && x(T.roughnessMap.channel),
      anisotropyMapUv: Mt && x(T.anisotropyMap.channel),
      clearcoatMapUv: Jt && x(T.clearcoatMap.channel),
      clearcoatNormalMapUv: It && x(T.clearcoatNormalMap.channel),
      clearcoatRoughnessMapUv: se && x(T.clearcoatRoughnessMap.channel),
      iridescenceMapUv: le && x(T.iridescenceMap.channel),
      iridescenceThicknessMapUv: Ot && x(T.iridescenceThicknessMap.channel),
      sheenColorMapUv: Dt && x(T.sheenColorMap.channel),
      sheenRoughnessMapUv: Wt && x(T.sheenRoughnessMap.channel),
      specularMapUv: kt && x(T.specularMap.channel),
      specularColorMapUv: Yt && x(T.specularColorMap.channel),
      specularIntensityMapUv: _e && x(T.specularIntensityMap.channel),
      transmissionMapUv: lt && x(T.transmissionMap.channel),
      thicknessMapUv: Bt && x(T.thicknessMap.channel),
      alphaMapUv: jt && x(T.alphaMap.channel),
      //
      vertexTangents: !!U.attributes.tangent && (ve || Kt),
      vertexColors: T.vertexColors,
      vertexAlphas: T.vertexColors === !0 && !!U.attributes.color && U.attributes.color.itemSize === 4,
      pointsUvs: B.isPoints === !0 && !!U.attributes.uv && (yt || jt),
      fog: !!H,
      useFog: T.fog === !0,
      fogExp2: !!H && H.isFogExp2,
      flatShading: T.wireframe === !1 && (T.flatShading === !0 || U.attributes.normal === void 0 && ve === !1 && (T.isMeshLambertMaterial || T.isMeshPhongMaterial || T.isMeshStandardMaterial || T.isMeshPhysicalMaterial)),
      sizeAttenuation: T.sizeAttenuation === !0,
      logarithmicDepthBuffer: p,
      reversedDepthBuffer: J,
      skinning: B.isSkinnedMesh === !0,
      morphTargets: U.morphAttributes.position !== void 0,
      morphNormals: U.morphAttributes.normal !== void 0,
      morphColors: U.morphAttributes.color !== void 0,
      morphTargetsCount: F,
      morphTextureStride: W,
      numDirLights: L.directional.length,
      numPointLights: L.point.length,
      numSpotLights: L.spot.length,
      numSpotLightMaps: L.spotLightMap.length,
      numRectAreaLights: L.rectArea.length,
      numHemiLights: L.hemi.length,
      numDirLightShadows: L.directionalShadowMap.length,
      numPointLightShadows: L.pointShadowMap.length,
      numSpotLightShadows: L.spotShadowMap.length,
      numSpotLightShadowsWithMaps: L.numSpotLightShadowsWithMaps,
      numLightProbes: L.numLightProbes,
      numClippingPlanes: o.numPlanes,
      numClipIntersection: o.numIntersection,
      dithering: T.dithering,
      shadowMapEnabled: n.shadowMap.enabled && z.length > 0,
      shadowMapType: n.shadowMap.type,
      toneMapping: fe,
      decodeVideoTexture: yt && T.map.isVideoTexture === !0 && Be.getTransfer(T.map.colorSpace) === We,
      decodeVideoTextureEmissive: Ue && T.emissiveMap.isVideoTexture === !0 && Be.getTransfer(T.emissiveMap.colorSpace) === We,
      premultipliedAlpha: T.premultipliedAlpha,
      doubleSided: T.side === Ss,
      flipSided: T.side === pi,
      useDepthPacking: T.depthPacking >= 0,
      depthPacking: T.depthPacking || 0,
      index0AttributeName: T.index0AttributeName,
      extensionClipCullDistance: Zt && T.extensions.clipCullDistance === !0 && e.has("WEBGL_clip_cull_distance"),
      extensionMultiDraw: (Zt && T.extensions.multiDraw === !0 || dt) && e.has("WEBGL_multi_draw"),
      rendererExtensionParallelShaderCompile: e.has("KHR_parallel_shader_compile"),
      customProgramCacheKey: T.customProgramCacheKey()
    };
    return He.vertexUv1s = d.has(1), He.vertexUv2s = d.has(2), He.vertexUv3s = d.has(3), d.clear(), He;
  }
  function b(T) {
    const L = [];
    if (T.shaderID ? L.push(T.shaderID) : (L.push(T.customVertexShaderID), L.push(T.customFragmentShaderID)), T.defines !== void 0)
      for (const z in T.defines)
        L.push(z), L.push(T.defines[z]);
    return T.isRawShaderMaterial === !1 && (y(L, T), E(L, T), L.push(n.outputColorSpace)), L.push(T.customProgramCacheKey), L.join();
  }
  function y(T, L) {
    T.push(L.precision), T.push(L.outputColorSpace), T.push(L.envMapMode), T.push(L.envMapCubeUVHeight), T.push(L.mapUv), T.push(L.alphaMapUv), T.push(L.lightMapUv), T.push(L.aoMapUv), T.push(L.bumpMapUv), T.push(L.normalMapUv), T.push(L.displacementMapUv), T.push(L.emissiveMapUv), T.push(L.metalnessMapUv), T.push(L.roughnessMapUv), T.push(L.anisotropyMapUv), T.push(L.clearcoatMapUv), T.push(L.clearcoatNormalMapUv), T.push(L.clearcoatRoughnessMapUv), T.push(L.iridescenceMapUv), T.push(L.iridescenceThicknessMapUv), T.push(L.sheenColorMapUv), T.push(L.sheenRoughnessMapUv), T.push(L.specularMapUv), T.push(L.specularColorMapUv), T.push(L.specularIntensityMapUv), T.push(L.transmissionMapUv), T.push(L.thicknessMapUv), T.push(L.combine), T.push(L.fogExp2), T.push(L.sizeAttenuation), T.push(L.morphTargetsCount), T.push(L.morphAttributeCount), T.push(L.numDirLights), T.push(L.numPointLights), T.push(L.numSpotLights), T.push(L.numSpotLightMaps), T.push(L.numHemiLights), T.push(L.numRectAreaLights), T.push(L.numDirLightShadows), T.push(L.numPointLightShadows), T.push(L.numSpotLightShadows), T.push(L.numSpotLightShadowsWithMaps), T.push(L.numLightProbes), T.push(L.shadowMapType), T.push(L.toneMapping), T.push(L.numClippingPlanes), T.push(L.numClipIntersection), T.push(L.depthPacking);
  }
  function E(T, L) {
    c.disableAll(), L.instancing && c.enable(0), L.instancingColor && c.enable(1), L.instancingMorph && c.enable(2), L.matcap && c.enable(3), L.envMap && c.enable(4), L.normalMapObjectSpace && c.enable(5), L.normalMapTangentSpace && c.enable(6), L.clearcoat && c.enable(7), L.iridescence && c.enable(8), L.alphaTest && c.enable(9), L.vertexColors && c.enable(10), L.vertexAlphas && c.enable(11), L.vertexUv1s && c.enable(12), L.vertexUv2s && c.enable(13), L.vertexUv3s && c.enable(14), L.vertexTangents && c.enable(15), L.anisotropy && c.enable(16), L.alphaHash && c.enable(17), L.batching && c.enable(18), L.dispersion && c.enable(19), L.batchingColor && c.enable(20), L.gradientMap && c.enable(21), T.push(c.mask), c.disableAll(), L.fog && c.enable(0), L.useFog && c.enable(1), L.flatShading && c.enable(2), L.logarithmicDepthBuffer && c.enable(3), L.reversedDepthBuffer && c.enable(4), L.skinning && c.enable(5), L.morphTargets && c.enable(6), L.morphNormals && c.enable(7), L.morphColors && c.enable(8), L.premultipliedAlpha && c.enable(9), L.shadowMapEnabled && c.enable(10), L.doubleSided && c.enable(11), L.flipSided && c.enable(12), L.useDepthPacking && c.enable(13), L.dithering && c.enable(14), L.transmission && c.enable(15), L.sheen && c.enable(16), L.opaque && c.enable(17), L.pointsUvs && c.enable(18), L.decodeVideoTexture && c.enable(19), L.decodeVideoTextureEmissive && c.enable(20), L.alphaToCoverage && c.enable(21), T.push(c.mask);
  }
  function w(T) {
    const L = _[T.type];
    let z;
    if (L) {
      const R = di[L];
      z = ev.clone(R.uniforms);
    } else
      z = T.uniforms;
    return z;
  }
  function M(T, L) {
    let z = m.get(L);
    return z !== void 0 ? ++z.usedTimes : (z = new pO(n, L, T, a), h.push(z), m.set(L, z)), z;
  }
  function O(T) {
    if (--T.usedTimes === 0) {
      const L = h.indexOf(T);
      h[L] = h[h.length - 1], h.pop(), m.delete(T.cacheKey), T.destroy();
    }
  }
  function C(T) {
    u.remove(T);
  }
  function D() {
    u.dispose();
  }
  return {
    getParameters: A,
    getProgramCacheKey: b,
    getUniforms: w,
    acquireProgram: M,
    releaseProgram: O,
    releaseShaderCache: C,
    // Exposed for resource monitoring & error feedback via renderer.info:
    programs: h,
    dispose: D
  };
}
function yO() {
  let n = /* @__PURE__ */ new WeakMap();
  function t(c) {
    return n.has(c);
  }
  function e(c) {
    let u = n.get(c);
    return u === void 0 && (u = {}, n.set(c, u)), u;
  }
  function s(c) {
    n.delete(c);
  }
  function a(c, u, d) {
    n.get(c)[u] = d;
  }
  function o() {
    n = /* @__PURE__ */ new WeakMap();
  }
  return {
    has: t,
    get: e,
    remove: s,
    update: a,
    dispose: o
  };
}
function xO(n, t) {
  return n.groupOrder !== t.groupOrder ? n.groupOrder - t.groupOrder : n.renderOrder !== t.renderOrder ? n.renderOrder - t.renderOrder : n.material.id !== t.material.id ? n.material.id - t.material.id : n.materialVariant !== t.materialVariant ? n.materialVariant - t.materialVariant : n.z !== t.z ? n.z - t.z : n.id - t.id;
}
function yb(n, t) {
  return n.groupOrder !== t.groupOrder ? n.groupOrder - t.groupOrder : n.renderOrder !== t.renderOrder ? n.renderOrder - t.renderOrder : n.z !== t.z ? t.z - n.z : n.id - t.id;
}
function xb() {
  const n = [];
  let t = 0;
  const e = [], s = [], a = [];
  function o() {
    t = 0, e.length = 0, s.length = 0, a.length = 0;
  }
  function c(g) {
    let _ = 0;
    return g.isInstancedMesh && (_ += 2), g.isSkinnedMesh && (_ += 1), _;
  }
  function u(g, _, x, A, b, y) {
    let E = n[t];
    return E === void 0 ? (E = {
      id: g.id,
      object: g,
      geometry: _,
      material: x,
      materialVariant: c(g),
      groupOrder: A,
      renderOrder: g.renderOrder,
      z: b,
      group: y
    }, n[t] = E) : (E.id = g.id, E.object = g, E.geometry = _, E.material = x, E.materialVariant = c(g), E.groupOrder = A, E.renderOrder = g.renderOrder, E.z = b, E.group = y), t++, E;
  }
  function d(g, _, x, A, b, y) {
    const E = u(g, _, x, A, b, y);
    x.transmission > 0 ? s.push(E) : x.transparent === !0 ? a.push(E) : e.push(E);
  }
  function h(g, _, x, A, b, y) {
    const E = u(g, _, x, A, b, y);
    x.transmission > 0 ? s.unshift(E) : x.transparent === !0 ? a.unshift(E) : e.unshift(E);
  }
  function m(g, _) {
    e.length > 1 && e.sort(g || xO), s.length > 1 && s.sort(_ || yb), a.length > 1 && a.sort(_ || yb);
  }
  function p() {
    for (let g = t, _ = n.length; g < _; g++) {
      const x = n[g];
      if (x.id === null) break;
      x.id = null, x.object = null, x.geometry = null, x.material = null, x.group = null;
    }
  }
  return {
    opaque: e,
    transmissive: s,
    transparent: a,
    init: o,
    push: d,
    unshift: h,
    finish: p,
    sort: m
  };
}
function SO() {
  let n = /* @__PURE__ */ new WeakMap();
  function t(s, a) {
    const o = n.get(s);
    let c;
    return o === void 0 ? (c = new xb(), n.set(s, [c])) : a >= o.length ? (c = new xb(), o.push(c)) : c = o[a], c;
  }
  function e() {
    n = /* @__PURE__ */ new WeakMap();
  }
  return {
    get: t,
    dispose: e
  };
}
function bO() {
  const n = {};
  return {
    get: function(t) {
      if (n[t.id] !== void 0)
        return n[t.id];
      let e;
      switch (t.type) {
        case "DirectionalLight":
          e = {
            direction: new st(),
            color: new we()
          };
          break;
        case "SpotLight":
          e = {
            position: new st(),
            direction: new st(),
            color: new we(),
            distance: 0,
            coneCos: 0,
            penumbraCos: 0,
            decay: 0
          };
          break;
        case "PointLight":
          e = {
            position: new st(),
            color: new we(),
            distance: 0,
            decay: 0
          };
          break;
        case "HemisphereLight":
          e = {
            direction: new st(),
            skyColor: new we(),
            groundColor: new we()
          };
          break;
        case "RectAreaLight":
          e = {
            color: new we(),
            position: new st(),
            halfWidth: new st(),
            halfHeight: new st()
          };
          break;
      }
      return n[t.id] = e, e;
    }
  };
}
function MO() {
  const n = {};
  return {
    get: function(t) {
      if (n[t.id] !== void 0)
        return n[t.id];
      let e;
      switch (t.type) {
        case "DirectionalLight":
          e = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new ae()
          };
          break;
        case "SpotLight":
          e = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new ae()
          };
          break;
        case "PointLight":
          e = {
            shadowIntensity: 1,
            shadowBias: 0,
            shadowNormalBias: 0,
            shadowRadius: 1,
            shadowMapSize: new ae(),
            shadowCameraNear: 1,
            shadowCameraFar: 1e3
          };
          break;
      }
      return n[t.id] = e, e;
    }
  };
}
let EO = 0;
function wO(n, t) {
  return (t.castShadow ? 2 : 0) - (n.castShadow ? 2 : 0) + (t.map ? 1 : 0) - (n.map ? 1 : 0);
}
function AO(n) {
  const t = new bO(), e = MO(), s = {
    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++) s.probe.push(new st());
  const a = new st(), o = new je(), c = new je();
  function u(h) {
    let m = 0, p = 0, g = 0;
    for (let L = 0; L < 9; L++) s.probe[L].set(0, 0, 0);
    let _ = 0, x = 0, A = 0, b = 0, y = 0, E = 0, w = 0, M = 0, O = 0, C = 0, D = 0;
    h.sort(wO);
    for (let L = 0, z = h.length; L < z; L++) {
      const R = h[L], B = R.color, H = R.intensity, U = R.distance;
      let V = null;
      if (R.shadow && R.shadow.map && (R.shadow.map.texture.format === hl ? V = R.shadow.map.texture : V = R.shadow.map.depthTexture || R.shadow.map.texture), R.isAmbientLight)
        m += B.r * H, p += B.g * H, g += B.b * H;
      else if (R.isLightProbe) {
        for (let N = 0; N < 9; N++)
          s.probe[N].addScaledVector(R.sh.coefficients[N], H);
        D++;
      } else if (R.isDirectionalLight) {
        const N = t.get(R);
        if (N.color.copy(R.color).multiplyScalar(R.intensity), R.castShadow) {
          const I = R.shadow, k = e.get(R);
          k.shadowIntensity = I.intensity, k.shadowBias = I.bias, k.shadowNormalBias = I.normalBias, k.shadowRadius = I.radius, k.shadowMapSize = I.mapSize, s.directionalShadow[_] = k, s.directionalShadowMap[_] = V, s.directionalShadowMatrix[_] = R.shadow.matrix, E++;
        }
        s.directional[_] = N, _++;
      } else if (R.isSpotLight) {
        const N = t.get(R);
        N.position.setFromMatrixPosition(R.matrixWorld), N.color.copy(B).multiplyScalar(H), N.distance = U, N.coneCos = Math.cos(R.angle), N.penumbraCos = Math.cos(R.angle * (1 - R.penumbra)), N.decay = R.decay, s.spot[A] = N;
        const I = R.shadow;
        if (R.map && (s.spotLightMap[O] = R.map, O++, I.updateMatrices(R), R.castShadow && C++), s.spotLightMatrix[A] = I.matrix, R.castShadow) {
          const k = e.get(R);
          k.shadowIntensity = I.intensity, k.shadowBias = I.bias, k.shadowNormalBias = I.normalBias, k.shadowRadius = I.radius, k.shadowMapSize = I.mapSize, s.spotShadow[A] = k, s.spotShadowMap[A] = V, M++;
        }
        A++;
      } else if (R.isRectAreaLight) {
        const N = t.get(R);
        N.color.copy(B).multiplyScalar(H), N.halfWidth.set(R.width * 0.5, 0, 0), N.halfHeight.set(0, R.height * 0.5, 0), s.rectArea[b] = N, b++;
      } else if (R.isPointLight) {
        const N = t.get(R);
        if (N.color.copy(R.color).multiplyScalar(R.intensity), N.distance = R.distance, N.decay = R.decay, R.castShadow) {
          const I = R.shadow, k = e.get(R);
          k.shadowIntensity = I.intensity, k.shadowBias = I.bias, k.shadowNormalBias = I.normalBias, k.shadowRadius = I.radius, k.shadowMapSize = I.mapSize, k.shadowCameraNear = I.camera.near, k.shadowCameraFar = I.camera.far, s.pointShadow[x] = k, s.pointShadowMap[x] = V, s.pointShadowMatrix[x] = R.shadow.matrix, w++;
        }
        s.point[x] = N, x++;
      } else if (R.isHemisphereLight) {
        const N = t.get(R);
        N.skyColor.copy(R.color).multiplyScalar(H), N.groundColor.copy(R.groundColor).multiplyScalar(H), s.hemi[y] = N, y++;
      }
    }
    b > 0 && (n.has("OES_texture_float_linear") === !0 ? (s.rectAreaLTC1 = Gt.LTC_FLOAT_1, s.rectAreaLTC2 = Gt.LTC_FLOAT_2) : (s.rectAreaLTC1 = Gt.LTC_HALF_1, s.rectAreaLTC2 = Gt.LTC_HALF_2)), s.ambient[0] = m, s.ambient[1] = p, s.ambient[2] = g;
    const T = s.hash;
    (T.directionalLength !== _ || T.pointLength !== x || T.spotLength !== A || T.rectAreaLength !== b || T.hemiLength !== y || T.numDirectionalShadows !== E || T.numPointShadows !== w || T.numSpotShadows !== M || T.numSpotMaps !== O || T.numLightProbes !== D) && (s.directional.length = _, s.spot.length = A, s.rectArea.length = b, s.point.length = x, s.hemi.length = y, s.directionalShadow.length = E, s.directionalShadowMap.length = E, s.pointShadow.length = w, s.pointShadowMap.length = w, s.spotShadow.length = M, s.spotShadowMap.length = M, s.directionalShadowMatrix.length = E, s.pointShadowMatrix.length = w, s.spotLightMatrix.length = M + O - C, s.spotLightMap.length = O, s.numSpotLightShadowsWithMaps = C, s.numLightProbes = D, T.directionalLength = _, T.pointLength = x, T.spotLength = A, T.rectAreaLength = b, T.hemiLength = y, T.numDirectionalShadows = E, T.numPointShadows = w, T.numSpotShadows = M, T.numSpotMaps = O, T.numLightProbes = D, s.version = EO++);
  }
  function d(h, m) {
    let p = 0, g = 0, _ = 0, x = 0, A = 0;
    const b = m.matrixWorldInverse;
    for (let y = 0, E = h.length; y < E; y++) {
      const w = h[y];
      if (w.isDirectionalLight) {
        const M = s.directional[p];
        M.direction.setFromMatrixPosition(w.matrixWorld), a.setFromMatrixPosition(w.target.matrixWorld), M.direction.sub(a), M.direction.transformDirection(b), p++;
      } else if (w.isSpotLight) {
        const M = s.spot[_];
        M.position.setFromMatrixPosition(w.matrixWorld), M.position.applyMatrix4(b), M.direction.setFromMatrixPosition(w.matrixWorld), a.setFromMatrixPosition(w.target.matrixWorld), M.direction.sub(a), M.direction.transformDirection(b), _++;
      } else if (w.isRectAreaLight) {
        const M = s.rectArea[x];
        M.position.setFromMatrixPosition(w.matrixWorld), M.position.applyMatrix4(b), c.identity(), o.copy(w.matrixWorld), o.premultiply(b), c.extractRotation(o), M.halfWidth.set(w.width * 0.5, 0, 0), M.halfHeight.set(0, w.height * 0.5, 0), M.halfWidth.applyMatrix4(c), M.halfHeight.applyMatrix4(c), x++;
      } else if (w.isPointLight) {
        const M = s.point[g];
        M.position.setFromMatrixPosition(w.matrixWorld), M.position.applyMatrix4(b), g++;
      } else if (w.isHemisphereLight) {
        const M = s.hemi[A];
        M.direction.setFromMatrixPosition(w.matrixWorld), M.direction.transformDirection(b), A++;
      }
    }
  }
  return {
    setup: u,
    setupView: d,
    state: s
  };
}
function Sb(n) {
  const t = new AO(n), e = [], s = [];
  function a(m) {
    h.camera = m, e.length = 0, s.length = 0;
  }
  function o(m) {
    e.push(m);
  }
  function c(m) {
    s.push(m);
  }
  function u() {
    t.setup(e);
  }
  function d(m) {
    t.setupView(e, m);
  }
  const h = {
    lightsArray: e,
    shadowsArray: s,
    camera: null,
    lights: t,
    transmissionRenderTarget: {}
  };
  return {
    init: a,
    state: h,
    setupLights: u,
    setupLightsView: d,
    pushLight: o,
    pushShadow: c
  };
}
function TO(n) {
  let t = /* @__PURE__ */ new WeakMap();
  function e(a, o = 0) {
    const c = t.get(a);
    let u;
    return c === void 0 ? (u = new Sb(n), t.set(a, [u])) : o >= c.length ? (u = new Sb(n), c.push(u)) : u = c[o], u;
  }
  function s() {
    t = /* @__PURE__ */ new WeakMap();
  }
  return {
    get: e,
    dispose: s
  };
}
const CO = `void main() {
	gl_Position = vec4( position, 1.0 );
}`, RO = `uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;
			mean += distribution.x;
			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
		#else
			float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;
			mean += depth;
			squared_mean += depth * depth;
		#endif
	}
	mean = mean / samples;
	squared_mean = squared_mean / samples;
	float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
	gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
}`, DO = [
  /* @__PURE__ */ new st(1, 0, 0),
  /* @__PURE__ */ new st(-1, 0, 0),
  /* @__PURE__ */ new st(0, 1, 0),
  /* @__PURE__ */ new st(0, -1, 0),
  /* @__PURE__ */ new st(0, 0, 1),
  /* @__PURE__ */ new st(0, 0, -1)
], NO = [
  /* @__PURE__ */ new st(0, -1, 0),
  /* @__PURE__ */ new st(0, -1, 0),
  /* @__PURE__ */ new st(0, 0, 1),
  /* @__PURE__ */ new st(0, 0, -1),
  /* @__PURE__ */ new st(0, -1, 0),
  /* @__PURE__ */ new st(0, -1, 0)
], bb = /* @__PURE__ */ new je(), Ec = /* @__PURE__ */ new st(), ng = /* @__PURE__ */ new st();
function OO(n, t, e) {
  let s = new J0();
  const a = new ae(), o = new ae(), c = new Je(), u = new F3(), d = new H3(), h = {}, m = e.maxTextureSize, p = { [ra]: pi, [pi]: ra, [Ss]: Ss }, g = new as({
    defines: {
      VSM_SAMPLES: 8
    },
    uniforms: {
      shadow_pass: { value: null },
      resolution: { value: new ae() },
      radius: { value: 4 }
    },
    vertexShader: CO,
    fragmentShader: RO
  }), _ = g.clone();
  _.defines.HORIZONTAL_PASS = 1;
  const x = new In();
  x.setAttribute(
    "position",
    new dn(
      new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]),
      3
    )
  );
  const A = new Ln(x, g), b = this;
  this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = ud;
  let y = this.type;
  this.render = function(C, D, T) {
    if (b.enabled === !1 || b.autoUpdate === !1 && b.needsUpdate === !1 || C.length === 0) return;
    this.type === p2 && (de("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."), this.type = ud);
    const L = n.getRenderTarget(), z = n.getActiveCubeFace(), R = n.getActiveMipmapLevel(), B = n.state;
    B.setBlending(cr), B.buffers.depth.getReversed() === !0 ? B.buffers.color.setClear(0, 0, 0, 0) : B.buffers.color.setClear(1, 1, 1, 1), B.buffers.depth.setTest(!0), B.setScissorTest(!1);
    const H = y !== this.type;
    H && D.traverse(function(U) {
      U.material && (Array.isArray(U.material) ? U.material.forEach((V) => V.needsUpdate = !0) : U.material.needsUpdate = !0);
    });
    for (let U = 0, V = C.length; U < V; U++) {
      const N = C[U], I = N.shadow;
      if (I === void 0) {
        de("WebGLShadowMap:", N, "has no shadow.");
        continue;
      }
      if (I.autoUpdate === !1 && I.needsUpdate === !1) continue;
      a.copy(I.mapSize);
      const k = I.getFrameExtents();
      a.multiply(k), o.copy(I.mapSize), (a.x > m || a.y > m) && (a.x > m && (o.x = Math.floor(m / k.x), a.x = o.x * k.x, I.mapSize.x = o.x), a.y > m && (o.y = Math.floor(m / k.y), a.y = o.y * k.y, I.mapSize.y = o.y));
      const X = n.state.buffers.depth.getReversed();
      if (I.camera._reversedDepth = X, I.map === null || H === !0) {
        if (I.map !== null && (I.map.depthTexture !== null && (I.map.depthTexture.dispose(), I.map.depthTexture = null), I.map.dispose()), this.type === Dc) {
          if (N.isPointLight) {
            de("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");
            continue;
          }
          I.map = new As(a.x, a.y, {
            format: hl,
            type: dr,
            minFilter: Qn,
            magFilter: Qn,
            generateMipmaps: !1
          }), I.map.texture.name = N.name + ".shadowMap", I.map.depthTexture = new kc(a.x, a.y, Di), I.map.depthTexture.name = N.name + ".shadowMapDepth", I.map.depthTexture.format = hr, I.map.depthTexture.compareFunction = null, I.map.depthTexture.minFilter = vn, I.map.depthTexture.magFilter = vn;
        } else
          N.isPointLight ? (I.map = new HM(a.x), I.map.depthTexture = new U3(a.x, Cs)) : (I.map = new As(a.x, a.y), I.map.depthTexture = new kc(a.x, a.y, Cs)), I.map.depthTexture.name = N.name + ".shadowMap", I.map.depthTexture.format = hr, this.type === ud ? (I.map.depthTexture.compareFunction = X ? Z0 : q0, I.map.depthTexture.minFilter = Qn, I.map.depthTexture.magFilter = Qn) : (I.map.depthTexture.compareFunction = null, I.map.depthTexture.minFilter = vn, I.map.depthTexture.magFilter = vn);
        I.camera.updateProjectionMatrix();
      }
      const Q = I.map.isWebGLCubeRenderTarget ? 6 : 1;
      for (let F = 0; F < Q; F++) {
        if (I.map.isWebGLCubeRenderTarget)
          n.setRenderTarget(I.map, F), n.clear();
        else {
          F === 0 && (n.setRenderTarget(I.map), n.clear());
          const W = I.getViewport(F);
          c.set(
            o.x * W.x,
            o.y * W.y,
            o.x * W.z,
            o.y * W.w
          ), B.viewport(c);
        }
        if (N.isPointLight) {
          const W = I.camera, et = I.matrix, $ = N.distance || W.far;
          $ !== W.far && (W.far = $, W.updateProjectionMatrix()), Ec.setFromMatrixPosition(N.matrixWorld), W.position.copy(Ec), ng.copy(W.position), ng.add(DO[F]), W.up.copy(NO[F]), W.lookAt(ng), W.updateMatrixWorld(), et.makeTranslation(-Ec.x, -Ec.y, -Ec.z), bb.multiplyMatrices(W.projectionMatrix, W.matrixWorldInverse), I._frustum.setFromProjectionMatrix(bb, W.coordinateSystem, W.reversedDepth);
        } else
          I.updateMatrices(N);
        s = I.getFrustum(), M(D, T, I.camera, N, this.type);
      }
      I.isPointLightShadow !== !0 && this.type === Dc && E(I, T), I.needsUpdate = !1;
    }
    y = this.type, b.needsUpdate = !1, n.setRenderTarget(L, z, R);
  };
  function E(C, D) {
    const T = t.update(A);
    g.defines.VSM_SAMPLES !== C.blurSamples && (g.defines.VSM_SAMPLES = C.blurSamples, _.defines.VSM_SAMPLES = C.blurSamples, g.needsUpdate = !0, _.needsUpdate = !0), C.mapPass === null && (C.mapPass = new As(a.x, a.y, {
      format: hl,
      type: dr
    })), g.uniforms.shadow_pass.value = C.map.depthTexture, g.uniforms.resolution.value = C.mapSize, g.uniforms.radius.value = C.radius, n.setRenderTarget(C.mapPass), n.clear(), n.renderBufferDirect(D, null, T, g, A, null), _.uniforms.shadow_pass.value = C.mapPass.texture, _.uniforms.resolution.value = C.mapSize, _.uniforms.radius.value = C.radius, n.setRenderTarget(C.map), n.clear(), n.renderBufferDirect(D, null, T, _, A, null);
  }
  function w(C, D, T, L) {
    let z = null;
    const R = T.isPointLight === !0 ? C.customDistanceMaterial : C.customDepthMaterial;
    if (R !== void 0)
      z = R;
    else if (z = T.isPointLight === !0 ? d : u, n.localClippingEnabled && D.clipShadows === !0 && Array.isArray(D.clippingPlanes) && D.clippingPlanes.length !== 0 || D.displacementMap && D.displacementScale !== 0 || D.alphaMap && D.alphaTest > 0 || D.map && D.alphaTest > 0 || D.alphaToCoverage === !0) {
      const B = z.uuid, H = D.uuid;
      let U = h[B];
      U === void 0 && (U = {}, h[B] = U);
      let V = U[H];
      V === void 0 && (V = z.clone(), U[H] = V, D.addEventListener("dispose", O)), z = V;
    }
    if (z.visible = D.visible, z.wireframe = D.wireframe, L === Dc ? z.side = D.shadowSide !== null ? D.shadowSide : D.side : z.side = D.shadowSide !== null ? D.shadowSide : p[D.side], z.alphaMap = D.alphaMap, z.alphaTest = D.alphaToCoverage === !0 ? 0.5 : D.alphaTest, z.map = D.map, z.clipShadows = D.clipShadows, z.clippingPlanes = D.clippingPlanes, z.clipIntersection = D.clipIntersection, z.displacementMap = D.displacementMap, z.displacementScale = D.displacementScale, z.displacementBias = D.displacementBias, z.wireframeLinewidth = D.wireframeLinewidth, z.linewidth = D.linewidth, T.isPointLight === !0 && z.isMeshDistanceMaterial === !0) {
      const B = n.properties.get(z);
      B.light = T;
    }
    return z;
  }
  function M(C, D, T, L, z) {
    if (C.visible === !1) return;
    if (C.layers.test(D.layers) && (C.isMesh || C.isLine || C.isPoints) && (C.castShadow || C.receiveShadow && z === Dc) && (!C.frustumCulled || s.intersectsObject(C))) {
      C.modelViewMatrix.multiplyMatrices(T.matrixWorldInverse, C.matrixWorld);
      const H = t.update(C), U = C.material;
      if (Array.isArray(U)) {
        const V = H.groups;
        for (let N = 0, I = V.length; N < I; N++) {
          const k = V[N], X = U[k.materialIndex];
          if (X && X.visible) {
            const Q = w(C, X, L, z);
            C.onBeforeShadow(n, C, D, T, H, Q, k), n.renderBufferDirect(T, null, H, Q, C, k), C.onAfterShadow(n, C, D, T, H, Q, k);
          }
        }
      } else if (U.visible) {
        const V = w(C, U, L, z);
        C.onBeforeShadow(n, C, D, T, H, V, null), n.renderBufferDirect(T, null, H, V, C, null), C.onAfterShadow(n, C, D, T, H, V, null);
      }
    }
    const B = C.children;
    for (let H = 0, U = B.length; H < U; H++)
      M(B[H], D, T, L, z);
  }
  function O(C) {
    C.target.removeEventListener("dispose", O);
    for (const T in h) {
      const L = h[T], z = C.target.uuid;
      z in L && (L[z].dispose(), delete L[z]);
    }
  }
}
function LO(n, t) {
  function e() {
    let lt = !1;
    const Bt = new Je();
    let Ut = null;
    const jt = new Je(0, 0, 0, 0);
    return {
      setMask: function(Nt) {
        Ut !== Nt && !lt && (n.colorMask(Nt, Nt, Nt, Nt), Ut = Nt);
      },
      setLocked: function(Nt) {
        lt = Nt;
      },
      setClear: function(Nt, bt, Zt, fe, He) {
        He === !0 && (Nt *= fe, bt *= fe, Zt *= fe), Bt.set(Nt, bt, Zt, fe), jt.equals(Bt) === !1 && (n.clearColor(Nt, bt, Zt, fe), jt.copy(Bt));
      },
      reset: function() {
        lt = !1, Ut = null, jt.set(-1, 0, 0, 0);
      }
    };
  }
  function s() {
    let lt = !1, Bt = !1, Ut = null, jt = null, Nt = null;
    return {
      setReversed: function(bt) {
        if (Bt !== bt) {
          const Zt = t.get("EXT_clip_control");
          bt ? Zt.clipControlEXT(Zt.LOWER_LEFT_EXT, Zt.ZERO_TO_ONE_EXT) : Zt.clipControlEXT(Zt.LOWER_LEFT_EXT, Zt.NEGATIVE_ONE_TO_ONE_EXT), Bt = bt;
          const fe = Nt;
          Nt = null, this.setClear(fe);
        }
      },
      getReversed: function() {
        return Bt;
      },
      setTest: function(bt) {
        bt ? K(n.DEPTH_TEST) : J(n.DEPTH_TEST);
      },
      setMask: function(bt) {
        Ut !== bt && !lt && (n.depthMask(bt), Ut = bt);
      },
      setFunc: function(bt) {
        if (Bt && (bt = j2[bt]), jt !== bt) {
          switch (bt) {
            case Cg:
              n.depthFunc(n.NEVER);
              break;
            case Rg:
              n.depthFunc(n.ALWAYS);
              break;
            case Dg:
              n.depthFunc(n.LESS);
              break;
            case fl:
              n.depthFunc(n.LEQUAL);
              break;
            case Ng:
              n.depthFunc(n.EQUAL);
              break;
            case Og:
              n.depthFunc(n.GEQUAL);
              break;
            case Lg:
              n.depthFunc(n.GREATER);
              break;
            case Ug:
              n.depthFunc(n.NOTEQUAL);
              break;
            default:
              n.depthFunc(n.LEQUAL);
          }
          jt = bt;
        }
      },
      setLocked: function(bt) {
        lt = bt;
      },
      setClear: function(bt) {
        Nt !== bt && (Nt = bt, Bt && (bt = 1 - bt), n.clearDepth(bt));
      },
      reset: function() {
        lt = !1, Ut = null, jt = null, Nt = null, Bt = !1;
      }
    };
  }
  function a() {
    let lt = !1, Bt = null, Ut = null, jt = null, Nt = null, bt = null, Zt = null, fe = null, He = null;
    return {
      setTest: function(Oe) {
        lt || (Oe ? K(n.STENCIL_TEST) : J(n.STENCIL_TEST));
      },
      setMask: function(Oe) {
        Bt !== Oe && !lt && (n.stencilMask(Oe), Bt = Oe);
      },
      setFunc: function(Oe, Fn, mi) {
        (Ut !== Oe || jt !== Fn || Nt !== mi) && (n.stencilFunc(Oe, Fn, mi), Ut = Oe, jt = Fn, Nt = mi);
      },
      setOp: function(Oe, Fn, mi) {
        (bt !== Oe || Zt !== Fn || fe !== mi) && (n.stencilOp(Oe, Fn, mi), bt = Oe, Zt = Fn, fe = mi);
      },
      setLocked: function(Oe) {
        lt = Oe;
      },
      setClear: function(Oe) {
        He !== Oe && (n.clearStencil(Oe), He = Oe);
      },
      reset: function() {
        lt = !1, Bt = null, Ut = null, jt = null, Nt = null, bt = null, Zt = null, fe = null, He = null;
      }
    };
  }
  const o = new e(), c = new s(), u = new a(), d = /* @__PURE__ */ new WeakMap(), h = /* @__PURE__ */ new WeakMap();
  let m = {}, p = {}, g = /* @__PURE__ */ new WeakMap(), _ = [], x = null, A = !1, b = null, y = null, E = null, w = null, M = null, O = null, C = null, D = new we(0, 0, 0), T = 0, L = !1, z = null, R = null, B = null, H = null, U = null;
  const V = n.getParameter(n.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  let N = !1, I = 0;
  const k = n.getParameter(n.VERSION);
  k.indexOf("WebGL") !== -1 ? (I = parseFloat(/^WebGL (\d)/.exec(k)[1]), N = I >= 1) : k.indexOf("OpenGL ES") !== -1 && (I = parseFloat(/^OpenGL ES (\d)/.exec(k)[1]), N = I >= 2);
  let X = null, Q = {};
  const F = n.getParameter(n.SCISSOR_BOX), W = n.getParameter(n.VIEWPORT), et = new Je().fromArray(F), $ = new Je().fromArray(W);
  function j(lt, Bt, Ut, jt) {
    const Nt = new Uint8Array(4), bt = n.createTexture();
    n.bindTexture(lt, bt), n.texParameteri(lt, n.TEXTURE_MIN_FILTER, n.NEAREST), n.texParameteri(lt, n.TEXTURE_MAG_FILTER, n.NEAREST);
    for (let Zt = 0; Zt < Ut; Zt++)
      lt === n.TEXTURE_3D || lt === n.TEXTURE_2D_ARRAY ? n.texImage3D(Bt, 0, n.RGBA, 1, 1, jt, 0, n.RGBA, n.UNSIGNED_BYTE, Nt) : n.texImage2D(Bt + Zt, 0, n.RGBA, 1, 1, 0, n.RGBA, n.UNSIGNED_BYTE, Nt);
    return bt;
  }
  const Y = {};
  Y[n.TEXTURE_2D] = j(n.TEXTURE_2D, n.TEXTURE_2D, 1), Y[n.TEXTURE_CUBE_MAP] = j(n.TEXTURE_CUBE_MAP, n.TEXTURE_CUBE_MAP_POSITIVE_X, 6), Y[n.TEXTURE_2D_ARRAY] = j(n.TEXTURE_2D_ARRAY, n.TEXTURE_2D_ARRAY, 1, 1), Y[n.TEXTURE_3D] = j(n.TEXTURE_3D, n.TEXTURE_3D, 1, 1), o.setClear(0, 0, 0, 1), c.setClear(1), u.setClear(0), K(n.DEPTH_TEST), c.setFunc(fl), Ft(!1), ve(mS), K(n.CULL_FACE), zt(cr);
  function K(lt) {
    m[lt] !== !0 && (n.enable(lt), m[lt] = !0);
  }
  function J(lt) {
    m[lt] !== !1 && (n.disable(lt), m[lt] = !1);
  }
  function rt(lt, Bt) {
    return p[lt] !== Bt ? (n.bindFramebuffer(lt, Bt), p[lt] = Bt, lt === n.DRAW_FRAMEBUFFER && (p[n.FRAMEBUFFER] = Bt), lt === n.FRAMEBUFFER && (p[n.DRAW_FRAMEBUFFER] = Bt), !0) : !1;
  }
  function dt(lt, Bt) {
    let Ut = _, jt = !1;
    if (lt) {
      Ut = g.get(Bt), Ut === void 0 && (Ut = [], g.set(Bt, Ut));
      const Nt = lt.textures;
      if (Ut.length !== Nt.length || Ut[0] !== n.COLOR_ATTACHMENT0) {
        for (let bt = 0, Zt = Nt.length; bt < Zt; bt++)
          Ut[bt] = n.COLOR_ATTACHMENT0 + bt;
        Ut.length = Nt.length, jt = !0;
      }
    } else
      Ut[0] !== n.BACK && (Ut[0] = n.BACK, jt = !0);
    jt && n.drawBuffers(Ut);
  }
  function yt(lt) {
    return x !== lt ? (n.useProgram(lt), x = lt, !0) : !1;
  }
  const Pt = {
    [Ua]: n.FUNC_ADD,
    [g2]: n.FUNC_SUBTRACT,
    [v2]: n.FUNC_REVERSE_SUBTRACT
  };
  Pt[_2] = n.MIN, Pt[y2] = n.MAX;
  const Lt = {
    [x2]: n.ZERO,
    [S2]: n.ONE,
    [b2]: n.SRC_COLOR,
    [Ag]: n.SRC_ALPHA,
    [C2]: n.SRC_ALPHA_SATURATE,
    [A2]: n.DST_COLOR,
    [E2]: n.DST_ALPHA,
    [M2]: n.ONE_MINUS_SRC_COLOR,
    [Tg]: n.ONE_MINUS_SRC_ALPHA,
    [T2]: n.ONE_MINUS_DST_COLOR,
    [w2]: n.ONE_MINUS_DST_ALPHA,
    [R2]: n.CONSTANT_COLOR,
    [D2]: n.ONE_MINUS_CONSTANT_COLOR,
    [N2]: n.CONSTANT_ALPHA,
    [O2]: n.ONE_MINUS_CONSTANT_ALPHA
  };
  function zt(lt, Bt, Ut, jt, Nt, bt, Zt, fe, He, Oe) {
    if (lt === cr) {
      A === !0 && (J(n.BLEND), A = !1);
      return;
    }
    if (A === !1 && (K(n.BLEND), A = !0), lt !== m2) {
      if (lt !== b || Oe !== L) {
        if ((y !== Ua || M !== Ua) && (n.blendEquation(n.FUNC_ADD), y = Ua, M = Ua), Oe)
          switch (lt) {
            case ol:
              n.blendFuncSeparate(n.ONE, n.ONE_MINUS_SRC_ALPHA, n.ONE, n.ONE_MINUS_SRC_ALPHA);
              break;
            case gS:
              n.blendFunc(n.ONE, n.ONE);
              break;
            case vS:
              n.blendFuncSeparate(n.ZERO, n.ONE_MINUS_SRC_COLOR, n.ZERO, n.ONE);
              break;
            case _S:
              n.blendFuncSeparate(n.DST_COLOR, n.ONE_MINUS_SRC_ALPHA, n.ZERO, n.ONE);
              break;
            default:
              Ie("WebGLState: Invalid blending: ", lt);
              break;
          }
        else
          switch (lt) {
            case ol:
              n.blendFuncSeparate(n.SRC_ALPHA, n.ONE_MINUS_SRC_ALPHA, n.ONE, n.ONE_MINUS_SRC_ALPHA);
              break;
            case gS:
              n.blendFuncSeparate(n.SRC_ALPHA, n.ONE, n.ONE, n.ONE);
              break;
            case vS:
              Ie("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");
              break;
            case _S:
              Ie("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");
              break;
            default:
              Ie("WebGLState: Invalid blending: ", lt);
              break;
          }
        E = null, w = null, O = null, C = null, D.set(0, 0, 0), T = 0, b = lt, L = Oe;
      }
      return;
    }
    Nt = Nt || Bt, bt = bt || Ut, Zt = Zt || jt, (Bt !== y || Nt !== M) && (n.blendEquationSeparate(Pt[Bt], Pt[Nt]), y = Bt, M = Nt), (Ut !== E || jt !== w || bt !== O || Zt !== C) && (n.blendFuncSeparate(Lt[Ut], Lt[jt], Lt[bt], Lt[Zt]), E = Ut, w = jt, O = bt, C = Zt), (fe.equals(D) === !1 || He !== T) && (n.blendColor(fe.r, fe.g, fe.b, He), D.copy(fe), T = He), b = lt, L = !1;
  }
  function Xt(lt, Bt) {
    lt.side === Ss ? J(n.CULL_FACE) : K(n.CULL_FACE);
    let Ut = lt.side === pi;
    Bt && (Ut = !Ut), Ft(Ut), lt.blending === ol && lt.transparent === !1 ? zt(cr) : zt(lt.blending, lt.blendEquation, lt.blendSrc, lt.blendDst, lt.blendEquationAlpha, lt.blendSrcAlpha, lt.blendDstAlpha, lt.blendColor, lt.blendAlpha, lt.premultipliedAlpha), c.setFunc(lt.depthFunc), c.setTest(lt.depthTest), c.setMask(lt.depthWrite), o.setMask(lt.colorWrite);
    const jt = lt.stencilWrite;
    u.setTest(jt), jt && (u.setMask(lt.stencilWriteMask), u.setFunc(lt.stencilFunc, lt.stencilRef, lt.stencilFuncMask), u.setOp(lt.stencilFail, lt.stencilZFail, lt.stencilZPass)), Ue(lt.polygonOffset, lt.polygonOffsetFactor, lt.polygonOffsetUnits), lt.alphaToCoverage === !0 ? K(n.SAMPLE_ALPHA_TO_COVERAGE) : J(n.SAMPLE_ALPHA_TO_COVERAGE);
  }
  function Ft(lt) {
    z !== lt && (lt ? n.frontFace(n.CW) : n.frontFace(n.CCW), z = lt);
  }
  function ve(lt) {
    lt !== d2 ? (K(n.CULL_FACE), lt !== R && (lt === mS ? n.cullFace(n.BACK) : lt === h2 ? n.cullFace(n.FRONT) : n.cullFace(n.FRONT_AND_BACK))) : J(n.CULL_FACE), R = lt;
  }
  function it(lt) {
    lt !== B && (N && n.lineWidth(lt), B = lt);
  }
  function Ue(lt, Bt, Ut) {
    lt ? (K(n.POLYGON_OFFSET_FILL), (H !== Bt || U !== Ut) && (H = Bt, U = Ut, c.getReversed() && (Bt = -Bt), n.polygonOffset(Bt, Ut))) : J(n.POLYGON_OFFSET_FILL);
  }
  function xe(lt) {
    lt ? K(n.SCISSOR_TEST) : J(n.SCISSOR_TEST);
  }
  function Re(lt) {
    lt === void 0 && (lt = n.TEXTURE0 + V - 1), X !== lt && (n.activeTexture(lt), X = lt);
  }
  function Kt(lt, Bt, Ut) {
    Ut === void 0 && (X === null ? Ut = n.TEXTURE0 + V - 1 : Ut = X);
    let jt = Q[Ut];
    jt === void 0 && (jt = { type: void 0, texture: void 0 }, Q[Ut] = jt), (jt.type !== lt || jt.texture !== Bt) && (X !== Ut && (n.activeTexture(Ut), X = Ut), n.bindTexture(lt, Bt || Y[lt]), jt.type = lt, jt.texture = Bt);
  }
  function tt() {
    const lt = Q[X];
    lt !== void 0 && lt.type !== void 0 && (n.bindTexture(lt.type, null), lt.type = void 0, lt.texture = void 0);
  }
  function G() {
    try {
      n.compressedTexImage2D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function ct() {
    try {
      n.compressedTexImage3D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function Et() {
    try {
      n.texSubImage2D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function Rt() {
    try {
      n.texSubImage3D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function Mt() {
    try {
      n.compressedTexSubImage2D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function Jt() {
    try {
      n.compressedTexSubImage3D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function It() {
    try {
      n.texStorage2D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function se() {
    try {
      n.texStorage3D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function le() {
    try {
      n.texImage2D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function Ot() {
    try {
      n.texImage3D(...arguments);
    } catch (lt) {
      Ie("WebGLState:", lt);
    }
  }
  function Dt(lt) {
    et.equals(lt) === !1 && (n.scissor(lt.x, lt.y, lt.z, lt.w), et.copy(lt));
  }
  function Wt(lt) {
    $.equals(lt) === !1 && (n.viewport(lt.x, lt.y, lt.z, lt.w), $.copy(lt));
  }
  function kt(lt, Bt) {
    let Ut = h.get(Bt);
    Ut === void 0 && (Ut = /* @__PURE__ */ new WeakMap(), h.set(Bt, Ut));
    let jt = Ut.get(lt);
    jt === void 0 && (jt = n.getUniformBlockIndex(Bt, lt.name), Ut.set(lt, jt));
  }
  function Yt(lt, Bt) {
    const jt = h.get(Bt).get(lt);
    d.get(Bt) !== jt && (n.uniformBlockBinding(Bt, jt, lt.__bindingPointIndex), d.set(Bt, jt));
  }
  function _e() {
    n.disable(n.BLEND), n.disable(n.CULL_FACE), n.disable(n.DEPTH_TEST), n.disable(n.POLYGON_OFFSET_FILL), n.disable(n.SCISSOR_TEST), n.disable(n.STENCIL_TEST), n.disable(n.SAMPLE_ALPHA_TO_COVERAGE), n.blendEquation(n.FUNC_ADD), n.blendFunc(n.ONE, n.ZERO), n.blendFuncSeparate(n.ONE, n.ZERO, n.ONE, n.ZERO), n.blendColor(0, 0, 0, 0), n.colorMask(!0, !0, !0, !0), n.clearColor(0, 0, 0, 0), n.depthMask(!0), n.depthFunc(n.LESS), c.setReversed(!1), n.clearDepth(1), n.stencilMask(4294967295), n.stencilFunc(n.ALWAYS, 0, 4294967295), n.stencilOp(n.KEEP, n.KEEP, n.KEEP), n.clearStencil(0), n.cullFace(n.BACK), n.frontFace(n.CCW), n.polygonOffset(0, 0), n.activeTexture(n.TEXTURE0), n.bindFramebuffer(n.FRAMEBUFFER, null), n.bindFramebuffer(n.DRAW_FRAMEBUFFER, null), n.bindFramebuffer(n.READ_FRAMEBUFFER, null), n.useProgram(null), n.lineWidth(1), n.scissor(0, 0, n.canvas.width, n.canvas.height), n.viewport(0, 0, n.canvas.width, n.canvas.height), m = {}, X = null, Q = {}, p = {}, g = /* @__PURE__ */ new WeakMap(), _ = [], x = null, A = !1, b = null, y = null, E = null, w = null, M = null, O = null, C = null, D = new we(0, 0, 0), T = 0, L = !1, z = null, R = null, B = null, H = null, U = null, et.set(0, 0, n.canvas.width, n.canvas.height), $.set(0, 0, n.canvas.width, n.canvas.height), o.reset(), c.reset(), u.reset();
  }
  return {
    buffers: {
      color: o,
      depth: c,
      stencil: u
    },
    enable: K,
    disable: J,
    bindFramebuffer: rt,
    drawBuffers: dt,
    useProgram: yt,
    setBlending: zt,
    setMaterial: Xt,
    setFlipSided: Ft,
    setCullFace: ve,
    setLineWidth: it,
    setPolygonOffset: Ue,
    setScissorTest: xe,
    activeTexture: Re,
    bindTexture: Kt,
    unbindTexture: tt,
    compressedTexImage2D: G,
    compressedTexImage3D: ct,
    texImage2D: le,
    texImage3D: Ot,
    updateUBOMapping: kt,
    uniformBlockBinding: Yt,
    texStorage2D: It,
    texStorage3D: se,
    texSubImage2D: Et,
    texSubImage3D: Rt,
    compressedTexSubImage2D: Mt,
    compressedTexSubImage3D: Jt,
    scissor: Dt,
    viewport: Wt,
    reset: _e
  };
}
function UO(n, t, e, s, a, o, c) {
  const u = t.has("WEBGL_multisampled_render_to_texture") ? t.get("WEBGL_multisampled_render_to_texture") : null, d = typeof navigator > "u" ? !1 : /OculusBrowser/g.test(navigator.userAgent), h = new ae(), m = /* @__PURE__ */ new WeakMap();
  let p;
  const g = /* @__PURE__ */ new WeakMap();
  let _ = !1;
  try {
    _ = typeof OffscreenCanvas < "u" && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  } catch {
  }
  function x(tt, G) {
    return _ ? new OffscreenCanvas(tt, G) : wd("canvas");
  }
  function A(tt, G, ct) {
    let Et = 1;
    const Rt = Kt(tt);
    if ((Rt.width > ct || Rt.height > ct) && (Et = ct / Math.max(Rt.width, Rt.height)), Et < 1)
      if (typeof HTMLImageElement < "u" && tt instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && tt instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && tt instanceof ImageBitmap || typeof VideoFrame < "u" && tt instanceof VideoFrame) {
        const Mt = Math.floor(Et * Rt.width), Jt = Math.floor(Et * Rt.height);
        p === void 0 && (p = x(Mt, Jt));
        const It = G ? x(Mt, Jt) : p;
        return It.width = Mt, It.height = Jt, It.getContext("2d").drawImage(tt, 0, 0, Mt, Jt), de("WebGLRenderer: Texture has been resized from (" + Rt.width + "x" + Rt.height + ") to (" + Mt + "x" + Jt + ")."), It;
      } else
        return "data" in tt && de("WebGLRenderer: Image in DataTexture is too big (" + Rt.width + "x" + Rt.height + ")."), tt;
    return tt;
  }
  function b(tt) {
    return tt.generateMipmaps;
  }
  function y(tt) {
    n.generateMipmap(tt);
  }
  function E(tt) {
    return tt.isWebGLCubeRenderTarget ? n.TEXTURE_CUBE_MAP : tt.isWebGL3DRenderTarget ? n.TEXTURE_3D : tt.isWebGLArrayRenderTarget || tt.isCompressedArrayTexture ? n.TEXTURE_2D_ARRAY : n.TEXTURE_2D;
  }
  function w(tt, G, ct, Et, Rt = !1) {
    if (tt !== null) {
      if (n[tt] !== void 0) return n[tt];
      de("WebGLRenderer: Attempt to use non-existing WebGL internal format '" + tt + "'");
    }
    let Mt = G;
    if (G === n.RED && (ct === n.FLOAT && (Mt = n.R32F), ct === n.HALF_FLOAT && (Mt = n.R16F), ct === n.UNSIGNED_BYTE && (Mt = n.R8)), G === n.RED_INTEGER && (ct === n.UNSIGNED_BYTE && (Mt = n.R8UI), ct === n.UNSIGNED_SHORT && (Mt = n.R16UI), ct === n.UNSIGNED_INT && (Mt = n.R32UI), ct === n.BYTE && (Mt = n.R8I), ct === n.SHORT && (Mt = n.R16I), ct === n.INT && (Mt = n.R32I)), G === n.RG && (ct === n.FLOAT && (Mt = n.RG32F), ct === n.HALF_FLOAT && (Mt = n.RG16F), ct === n.UNSIGNED_BYTE && (Mt = n.RG8)), G === n.RG_INTEGER && (ct === n.UNSIGNED_BYTE && (Mt = n.RG8UI), ct === n.UNSIGNED_SHORT && (Mt = n.RG16UI), ct === n.UNSIGNED_INT && (Mt = n.RG32UI), ct === n.BYTE && (Mt = n.RG8I), ct === n.SHORT && (Mt = n.RG16I), ct === n.INT && (Mt = n.RG32I)), G === n.RGB_INTEGER && (ct === n.UNSIGNED_BYTE && (Mt = n.RGB8UI), ct === n.UNSIGNED_SHORT && (Mt = n.RGB16UI), ct === n.UNSIGNED_INT && (Mt = n.RGB32UI), ct === n.BYTE && (Mt = n.RGB8I), ct === n.SHORT && (Mt = n.RGB16I), ct === n.INT && (Mt = n.RGB32I)), G === n.RGBA_INTEGER && (ct === n.UNSIGNED_BYTE && (Mt = n.RGBA8UI), ct === n.UNSIGNED_SHORT && (Mt = n.RGBA16UI), ct === n.UNSIGNED_INT && (Mt = n.RGBA32UI), ct === n.BYTE && (Mt = n.RGBA8I), ct === n.SHORT && (Mt = n.RGBA16I), ct === n.INT && (Mt = n.RGBA32I)), G === n.RGB && (ct === n.UNSIGNED_INT_5_9_9_9_REV && (Mt = n.RGB9_E5), ct === n.UNSIGNED_INT_10F_11F_11F_REV && (Mt = n.R11F_G11F_B10F)), G === n.RGBA) {
      const Jt = Rt ? Md : Be.getTransfer(Et);
      ct === n.FLOAT && (Mt = n.RGBA32F), ct === n.HALF_FLOAT && (Mt = n.RGBA16F), ct === n.UNSIGNED_BYTE && (Mt = Jt === We ? n.SRGB8_ALPHA8 : n.RGBA8), ct === n.UNSIGNED_SHORT_4_4_4_4 && (Mt = n.RGBA4), ct === n.UNSIGNED_SHORT_5_5_5_1 && (Mt = n.RGB5_A1);
    }
    return (Mt === n.R16F || Mt === n.R32F || Mt === n.RG16F || Mt === n.RG32F || Mt === n.RGBA16F || Mt === n.RGBA32F) && t.get("EXT_color_buffer_float"), Mt;
  }
  function M(tt, G) {
    let ct;
    return tt ? G === null || G === Cs || G === Fc ? ct = n.DEPTH24_STENCIL8 : G === Di ? ct = n.DEPTH32F_STENCIL8 : G === zc && (ct = n.DEPTH24_STENCIL8, de("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")) : G === null || G === Cs || G === Fc ? ct = n.DEPTH_COMPONENT24 : G === Di ? ct = n.DEPTH_COMPONENT32F : G === zc && (ct = n.DEPTH_COMPONENT16), ct;
  }
  function O(tt, G) {
    return b(tt) === !0 || tt.isFramebufferTexture && tt.minFilter !== vn && tt.minFilter !== Qn ? Math.log2(Math.max(G.width, G.height)) + 1 : tt.mipmaps !== void 0 && tt.mipmaps.length > 0 ? tt.mipmaps.length : tt.isCompressedTexture && Array.isArray(tt.image) ? G.mipmaps.length : 1;
  }
  function C(tt) {
    const G = tt.target;
    G.removeEventListener("dispose", C), T(G), G.isVideoTexture && m.delete(G);
  }
  function D(tt) {
    const G = tt.target;
    G.removeEventListener("dispose", D), z(G);
  }
  function T(tt) {
    const G = s.get(tt);
    if (G.__webglInit === void 0) return;
    const ct = tt.source, Et = g.get(ct);
    if (Et) {
      const Rt = Et[G.__cacheKey];
      Rt.usedTimes--, Rt.usedTimes === 0 && L(tt), Object.keys(Et).length === 0 && g.delete(ct);
    }
    s.remove(tt);
  }
  function L(tt) {
    const G = s.get(tt);
    n.deleteTexture(G.__webglTexture);
    const ct = tt.source, Et = g.get(ct);
    delete Et[G.__cacheKey], c.memory.textures--;
  }
  function z(tt) {
    const G = s.get(tt);
    if (tt.depthTexture && (tt.depthTexture.dispose(), s.remove(tt.depthTexture)), tt.isWebGLCubeRenderTarget)
      for (let Et = 0; Et < 6; Et++) {
        if (Array.isArray(G.__webglFramebuffer[Et]))
          for (let Rt = 0; Rt < G.__webglFramebuffer[Et].length; Rt++) n.deleteFramebuffer(G.__webglFramebuffer[Et][Rt]);
        else
          n.deleteFramebuffer(G.__webglFramebuffer[Et]);
        G.__webglDepthbuffer && n.deleteRenderbuffer(G.__webglDepthbuffer[Et]);
      }
    else {
      if (Array.isArray(G.__webglFramebuffer))
        for (let Et = 0; Et < G.__webglFramebuffer.length; Et++) n.deleteFramebuffer(G.__webglFramebuffer[Et]);
      else
        n.deleteFramebuffer(G.__webglFramebuffer);
      if (G.__webglDepthbuffer && n.deleteRenderbuffer(G.__webglDepthbuffer), G.__webglMultisampledFramebuffer && n.deleteFramebuffer(G.__webglMultisampledFramebuffer), G.__webglColorRenderbuffer)
        for (let Et = 0; Et < G.__webglColorRenderbuffer.length; Et++)
          G.__webglColorRenderbuffer[Et] && n.deleteRenderbuffer(G.__webglColorRenderbuffer[Et]);
      G.__webglDepthRenderbuffer && n.deleteRenderbuffer(G.__webglDepthRenderbuffer);
    }
    const ct = tt.textures;
    for (let Et = 0, Rt = ct.length; Et < Rt; Et++) {
      const Mt = s.get(ct[Et]);
      Mt.__webglTexture && (n.deleteTexture(Mt.__webglTexture), c.memory.textures--), s.remove(ct[Et]);
    }
    s.remove(tt);
  }
  let R = 0;
  function B() {
    R = 0;
  }
  function H() {
    const tt = R;
    return tt >= a.maxTextures && de("WebGLTextures: Trying to use " + tt + " texture units while this GPU supports only " + a.maxTextures), R += 1, tt;
  }
  function U(tt) {
    const G = [];
    return G.push(tt.wrapS), G.push(tt.wrapT), G.push(tt.wrapR || 0), G.push(tt.magFilter), G.push(tt.minFilter), G.push(tt.anisotropy), G.push(tt.internalFormat), G.push(tt.format), G.push(tt.type), G.push(tt.generateMipmaps), G.push(tt.premultiplyAlpha), G.push(tt.flipY), G.push(tt.unpackAlignment), G.push(tt.colorSpace), G.join();
  }
  function V(tt, G) {
    const ct = s.get(tt);
    if (tt.isVideoTexture && xe(tt), tt.isRenderTargetTexture === !1 && tt.isExternalTexture !== !0 && tt.version > 0 && ct.__version !== tt.version) {
      const Et = tt.image;
      if (Et === null)
        de("WebGLRenderer: Texture marked for update but no image data found.");
      else if (Et.complete === !1)
        de("WebGLRenderer: Texture marked for update but image is incomplete");
      else {
        Y(ct, tt, G);
        return;
      }
    } else tt.isExternalTexture && (ct.__webglTexture = tt.sourceTexture ? tt.sourceTexture : null);
    e.bindTexture(n.TEXTURE_2D, ct.__webglTexture, n.TEXTURE0 + G);
  }
  function N(tt, G) {
    const ct = s.get(tt);
    if (tt.isRenderTargetTexture === !1 && tt.version > 0 && ct.__version !== tt.version) {
      Y(ct, tt, G);
      return;
    } else tt.isExternalTexture && (ct.__webglTexture = tt.sourceTexture ? tt.sourceTexture : null);
    e.bindTexture(n.TEXTURE_2D_ARRAY, ct.__webglTexture, n.TEXTURE0 + G);
  }
  function I(tt, G) {
    const ct = s.get(tt);
    if (tt.isRenderTargetTexture === !1 && tt.version > 0 && ct.__version !== tt.version) {
      Y(ct, tt, G);
      return;
    }
    e.bindTexture(n.TEXTURE_3D, ct.__webglTexture, n.TEXTURE0 + G);
  }
  function k(tt, G) {
    const ct = s.get(tt);
    if (tt.isCubeDepthTexture !== !0 && tt.version > 0 && ct.__version !== tt.version) {
      K(ct, tt, G);
      return;
    }
    e.bindTexture(n.TEXTURE_CUBE_MAP, ct.__webglTexture, n.TEXTURE0 + G);
  }
  const X = {
    [Pg]: n.REPEAT,
    [or]: n.CLAMP_TO_EDGE,
    [Ig]: n.MIRRORED_REPEAT
  }, Q = {
    [vn]: n.NEAREST,
    [P2]: n.NEAREST_MIPMAP_NEAREST,
    [yf]: n.NEAREST_MIPMAP_LINEAR,
    [Qn]: n.LINEAR,
    [bm]: n.LINEAR_MIPMAP_NEAREST,
    [Ia]: n.LINEAR_MIPMAP_LINEAR
  }, F = {
    [z2]: n.NEVER,
    [k2]: n.ALWAYS,
    [F2]: n.LESS,
    [q0]: n.LEQUAL,
    [H2]: n.EQUAL,
    [Z0]: n.GEQUAL,
    [V2]: n.GREATER,
    [G2]: n.NOTEQUAL
  };
  function W(tt, G) {
    if (G.type === Di && t.has("OES_texture_float_linear") === !1 && (G.magFilter === Qn || G.magFilter === bm || G.magFilter === yf || G.magFilter === Ia || G.minFilter === Qn || G.minFilter === bm || G.minFilter === yf || G.minFilter === Ia) && de("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."), n.texParameteri(tt, n.TEXTURE_WRAP_S, X[G.wrapS]), n.texParameteri(tt, n.TEXTURE_WRAP_T, X[G.wrapT]), (tt === n.TEXTURE_3D || tt === n.TEXTURE_2D_ARRAY) && n.texParameteri(tt, n.TEXTURE_WRAP_R, X[G.wrapR]), n.texParameteri(tt, n.TEXTURE_MAG_FILTER, Q[G.magFilter]), n.texParameteri(tt, n.TEXTURE_MIN_FILTER, Q[G.minFilter]), G.compareFunction && (n.texParameteri(tt, n.TEXTURE_COMPARE_MODE, n.COMPARE_REF_TO_TEXTURE), n.texParameteri(tt, n.TEXTURE_COMPARE_FUNC, F[G.compareFunction])), t.has("EXT_texture_filter_anisotropic") === !0) {
      if (G.magFilter === vn || G.minFilter !== yf && G.minFilter !== Ia || G.type === Di && t.has("OES_texture_float_linear") === !1) return;
      if (G.anisotropy > 1 || s.get(G).__currentAnisotropy) {
        const ct = t.get("EXT_texture_filter_anisotropic");
        n.texParameterf(tt, ct.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(G.anisotropy, a.getMaxAnisotropy())), s.get(G).__currentAnisotropy = G.anisotropy;
      }
    }
  }
  function et(tt, G) {
    let ct = !1;
    tt.__webglInit === void 0 && (tt.__webglInit = !0, G.addEventListener("dispose", C));
    const Et = G.source;
    let Rt = g.get(Et);
    Rt === void 0 && (Rt = {}, g.set(Et, Rt));
    const Mt = U(G);
    if (Mt !== tt.__cacheKey) {
      Rt[Mt] === void 0 && (Rt[Mt] = {
        texture: n.createTexture(),
        usedTimes: 0
      }, c.memory.textures++, ct = !0), Rt[Mt].usedTimes++;
      const Jt = Rt[tt.__cacheKey];
      Jt !== void 0 && (Rt[tt.__cacheKey].usedTimes--, Jt.usedTimes === 0 && L(G)), tt.__cacheKey = Mt, tt.__webglTexture = Rt[Mt].texture;
    }
    return ct;
  }
  function $(tt, G, ct) {
    return Math.floor(Math.floor(tt / ct) / G);
  }
  function j(tt, G, ct, Et) {
    const Mt = tt.updateRanges;
    if (Mt.length === 0)
      e.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, G.width, G.height, ct, Et, G.data);
    else {
      Mt.sort((Ot, Dt) => Ot.start - Dt.start);
      let Jt = 0;
      for (let Ot = 1; Ot < Mt.length; Ot++) {
        const Dt = Mt[Jt], Wt = Mt[Ot], kt = Dt.start + Dt.count, Yt = $(Wt.start, G.width, 4), _e = $(Dt.start, G.width, 4);
        Wt.start <= kt + 1 && Yt === _e && $(Wt.start + Wt.count - 1, G.width, 4) === Yt ? Dt.count = Math.max(
          Dt.count,
          Wt.start + Wt.count - Dt.start
        ) : (++Jt, Mt[Jt] = Wt);
      }
      Mt.length = Jt + 1;
      const It = n.getParameter(n.UNPACK_ROW_LENGTH), se = n.getParameter(n.UNPACK_SKIP_PIXELS), le = n.getParameter(n.UNPACK_SKIP_ROWS);
      n.pixelStorei(n.UNPACK_ROW_LENGTH, G.width);
      for (let Ot = 0, Dt = Mt.length; Ot < Dt; Ot++) {
        const Wt = Mt[Ot], kt = Math.floor(Wt.start / 4), Yt = Math.ceil(Wt.count / 4), _e = kt % G.width, lt = Math.floor(kt / G.width), Bt = Yt, Ut = 1;
        n.pixelStorei(n.UNPACK_SKIP_PIXELS, _e), n.pixelStorei(n.UNPACK_SKIP_ROWS, lt), e.texSubImage2D(n.TEXTURE_2D, 0, _e, lt, Bt, Ut, ct, Et, G.data);
      }
      tt.clearUpdateRanges(), n.pixelStorei(n.UNPACK_ROW_LENGTH, It), n.pixelStorei(n.UNPACK_SKIP_PIXELS, se), n.pixelStorei(n.UNPACK_SKIP_ROWS, le);
    }
  }
  function Y(tt, G, ct) {
    let Et = n.TEXTURE_2D;
    (G.isDataArrayTexture || G.isCompressedArrayTexture) && (Et = n.TEXTURE_2D_ARRAY), G.isData3DTexture && (Et = n.TEXTURE_3D);
    const Rt = et(tt, G), Mt = G.source;
    e.bindTexture(Et, tt.__webglTexture, n.TEXTURE0 + ct);
    const Jt = s.get(Mt);
    if (Mt.version !== Jt.__version || Rt === !0) {
      e.activeTexture(n.TEXTURE0 + ct);
      const It = Be.getPrimaries(Be.workingColorSpace), se = G.colorSpace === ta ? null : Be.getPrimaries(G.colorSpace), le = G.colorSpace === ta || It === se ? n.NONE : n.BROWSER_DEFAULT_WEBGL;
      n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL, G.flipY), n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL, G.premultiplyAlpha), n.pixelStorei(n.UNPACK_ALIGNMENT, G.unpackAlignment), n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL, le);
      let Ot = A(G.image, !1, a.maxTextureSize);
      Ot = Re(G, Ot);
      const Dt = o.convert(G.format, G.colorSpace), Wt = o.convert(G.type);
      let kt = w(G.internalFormat, Dt, Wt, G.colorSpace, G.isVideoTexture);
      W(Et, G);
      let Yt;
      const _e = G.mipmaps, lt = G.isVideoTexture !== !0, Bt = Jt.__version === void 0 || Rt === !0, Ut = Mt.dataReady, jt = O(G, Ot);
      if (G.isDepthTexture)
        kt = M(G.format === Ba, G.type), Bt && (lt ? e.texStorage2D(n.TEXTURE_2D, 1, kt, Ot.width, Ot.height) : e.texImage2D(n.TEXTURE_2D, 0, kt, Ot.width, Ot.height, 0, Dt, Wt, null));
      else if (G.isDataTexture)
        if (_e.length > 0) {
          lt && Bt && e.texStorage2D(n.TEXTURE_2D, jt, kt, _e[0].width, _e[0].height);
          for (let Nt = 0, bt = _e.length; Nt < bt; Nt++)
            Yt = _e[Nt], lt ? Ut && e.texSubImage2D(n.TEXTURE_2D, Nt, 0, 0, Yt.width, Yt.height, Dt, Wt, Yt.data) : e.texImage2D(n.TEXTURE_2D, Nt, kt, Yt.width, Yt.height, 0, Dt, Wt, Yt.data);
          G.generateMipmaps = !1;
        } else
          lt ? (Bt && e.texStorage2D(n.TEXTURE_2D, jt, kt, Ot.width, Ot.height), Ut && j(G, Ot, Dt, Wt)) : e.texImage2D(n.TEXTURE_2D, 0, kt, Ot.width, Ot.height, 0, Dt, Wt, Ot.data);
      else if (G.isCompressedTexture)
        if (G.isCompressedArrayTexture) {
          lt && Bt && e.texStorage3D(n.TEXTURE_2D_ARRAY, jt, kt, _e[0].width, _e[0].height, Ot.depth);
          for (let Nt = 0, bt = _e.length; Nt < bt; Nt++)
            if (Yt = _e[Nt], G.format !== Ni)
              if (Dt !== null)
                if (lt) {
                  if (Ut)
                    if (G.layerUpdates.size > 0) {
                      const Zt = JS(Yt.width, Yt.height, G.format, G.type);
                      for (const fe of G.layerUpdates) {
                        const He = Yt.data.subarray(
                          fe * Zt / Yt.data.BYTES_PER_ELEMENT,
                          (fe + 1) * Zt / Yt.data.BYTES_PER_ELEMENT
                        );
                        e.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY, Nt, 0, 0, fe, Yt.width, Yt.height, 1, Dt, He);
                      }
                      G.clearLayerUpdates();
                    } else
                      e.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY, Nt, 0, 0, 0, Yt.width, Yt.height, Ot.depth, Dt, Yt.data);
                } else
                  e.compressedTexImage3D(n.TEXTURE_2D_ARRAY, Nt, kt, Yt.width, Yt.height, Ot.depth, 0, Yt.data, 0, 0);
              else
                de("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");
            else
              lt ? Ut && e.texSubImage3D(n.TEXTURE_2D_ARRAY, Nt, 0, 0, 0, Yt.width, Yt.height, Ot.depth, Dt, Wt, Yt.data) : e.texImage3D(n.TEXTURE_2D_ARRAY, Nt, kt, Yt.width, Yt.height, Ot.depth, 0, Dt, Wt, Yt.data);
        } else {
          lt && Bt && e.texStorage2D(n.TEXTURE_2D, jt, kt, _e[0].width, _e[0].height);
          for (let Nt = 0, bt = _e.length; Nt < bt; Nt++)
            Yt = _e[Nt], G.format !== Ni ? Dt !== null ? lt ? Ut && e.compressedTexSubImage2D(n.TEXTURE_2D, Nt, 0, 0, Yt.width, Yt.height, Dt, Yt.data) : e.compressedTexImage2D(n.TEXTURE_2D, Nt, kt, Yt.width, Yt.height, 0, Yt.data) : de("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()") : lt ? Ut && e.texSubImage2D(n.TEXTURE_2D, Nt, 0, 0, Yt.width, Yt.height, Dt, Wt, Yt.data) : e.texImage2D(n.TEXTURE_2D, Nt, kt, Yt.width, Yt.height, 0, Dt, Wt, Yt.data);
        }
      else if (G.isDataArrayTexture)
        if (lt) {
          if (Bt && e.texStorage3D(n.TEXTURE_2D_ARRAY, jt, kt, Ot.width, Ot.height, Ot.depth), Ut)
            if (G.layerUpdates.size > 0) {
              const Nt = JS(Ot.width, Ot.height, G.format, G.type);
              for (const bt of G.layerUpdates) {
                const Zt = Ot.data.subarray(
                  bt * Nt / Ot.data.BYTES_PER_ELEMENT,
                  (bt + 1) * Nt / Ot.data.BYTES_PER_ELEMENT
                );
                e.texSubImage3D(n.TEXTURE_2D_ARRAY, 0, 0, 0, bt, Ot.width, Ot.height, 1, Dt, Wt, Zt);
              }
              G.clearLayerUpdates();
            } else
              e.texSubImage3D(n.TEXTURE_2D_ARRAY, 0, 0, 0, 0, Ot.width, Ot.height, Ot.depth, Dt, Wt, Ot.data);
        } else
          e.texImage3D(n.TEXTURE_2D_ARRAY, 0, kt, Ot.width, Ot.height, Ot.depth, 0, Dt, Wt, Ot.data);
      else if (G.isData3DTexture)
        lt ? (Bt && e.texStorage3D(n.TEXTURE_3D, jt, kt, Ot.width, Ot.height, Ot.depth), Ut && e.texSubImage3D(n.TEXTURE_3D, 0, 0, 0, 0, Ot.width, Ot.height, Ot.depth, Dt, Wt, Ot.data)) : e.texImage3D(n.TEXTURE_3D, 0, kt, Ot.width, Ot.height, Ot.depth, 0, Dt, Wt, Ot.data);
      else if (G.isFramebufferTexture) {
        if (Bt)
          if (lt)
            e.texStorage2D(n.TEXTURE_2D, jt, kt, Ot.width, Ot.height);
          else {
            let Nt = Ot.width, bt = Ot.height;
            for (let Zt = 0; Zt < jt; Zt++)
              e.texImage2D(n.TEXTURE_2D, Zt, kt, Nt, bt, 0, Dt, Wt, null), Nt >>= 1, bt >>= 1;
          }
      } else if (_e.length > 0) {
        if (lt && Bt) {
          const Nt = Kt(_e[0]);
          e.texStorage2D(n.TEXTURE_2D, jt, kt, Nt.width, Nt.height);
        }
        for (let Nt = 0, bt = _e.length; Nt < bt; Nt++)
          Yt = _e[Nt], lt ? Ut && e.texSubImage2D(n.TEXTURE_2D, Nt, 0, 0, Dt, Wt, Yt) : e.texImage2D(n.TEXTURE_2D, Nt, kt, Dt, Wt, Yt);
        G.generateMipmaps = !1;
      } else if (lt) {
        if (Bt) {
          const Nt = Kt(Ot);
          e.texStorage2D(n.TEXTURE_2D, jt, kt, Nt.width, Nt.height);
        }
        Ut && e.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, Dt, Wt, Ot);
      } else
        e.texImage2D(n.TEXTURE_2D, 0, kt, Dt, Wt, Ot);
      b(G) && y(Et), Jt.__version = Mt.version, G.onUpdate && G.onUpdate(G);
    }
    tt.__version = G.version;
  }
  function K(tt, G, ct) {
    if (G.image.length !== 6) return;
    const Et = et(tt, G), Rt = G.source;
    e.bindTexture(n.TEXTURE_CUBE_MAP, tt.__webglTexture, n.TEXTURE0 + ct);
    const Mt = s.get(Rt);
    if (Rt.version !== Mt.__version || Et === !0) {
      e.activeTexture(n.TEXTURE0 + ct);
      const Jt = Be.getPrimaries(Be.workingColorSpace), It = G.colorSpace === ta ? null : Be.getPrimaries(G.colorSpace), se = G.colorSpace === ta || Jt === It ? n.NONE : n.BROWSER_DEFAULT_WEBGL;
      n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL, G.flipY), n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL, G.premultiplyAlpha), n.pixelStorei(n.UNPACK_ALIGNMENT, G.unpackAlignment), n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL, se);
      const le = G.isCompressedTexture || G.image[0].isCompressedTexture, Ot = G.image[0] && G.image[0].isDataTexture, Dt = [];
      for (let bt = 0; bt < 6; bt++)
        !le && !Ot ? Dt[bt] = A(G.image[bt], !0, a.maxCubemapSize) : Dt[bt] = Ot ? G.image[bt].image : G.image[bt], Dt[bt] = Re(G, Dt[bt]);
      const Wt = Dt[0], kt = o.convert(G.format, G.colorSpace), Yt = o.convert(G.type), _e = w(G.internalFormat, kt, Yt, G.colorSpace), lt = G.isVideoTexture !== !0, Bt = Mt.__version === void 0 || Et === !0, Ut = Rt.dataReady;
      let jt = O(G, Wt);
      W(n.TEXTURE_CUBE_MAP, G);
      let Nt;
      if (le) {
        lt && Bt && e.texStorage2D(n.TEXTURE_CUBE_MAP, jt, _e, Wt.width, Wt.height);
        for (let bt = 0; bt < 6; bt++) {
          Nt = Dt[bt].mipmaps;
          for (let Zt = 0; Zt < Nt.length; Zt++) {
            const fe = Nt[Zt];
            G.format !== Ni ? kt !== null ? lt ? Ut && e.compressedTexSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, Zt, 0, 0, fe.width, fe.height, kt, fe.data) : e.compressedTexImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, Zt, _e, fe.width, fe.height, 0, fe.data) : de("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()") : lt ? Ut && e.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, Zt, 0, 0, fe.width, fe.height, kt, Yt, fe.data) : e.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, Zt, _e, fe.width, fe.height, 0, kt, Yt, fe.data);
          }
        }
      } else {
        if (Nt = G.mipmaps, lt && Bt) {
          Nt.length > 0 && jt++;
          const bt = Kt(Dt[0]);
          e.texStorage2D(n.TEXTURE_CUBE_MAP, jt, _e, bt.width, bt.height);
        }
        for (let bt = 0; bt < 6; bt++)
          if (Ot) {
            lt ? Ut && e.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, 0, 0, 0, Dt[bt].width, Dt[bt].height, kt, Yt, Dt[bt].data) : e.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, 0, _e, Dt[bt].width, Dt[bt].height, 0, kt, Yt, Dt[bt].data);
            for (let Zt = 0; Zt < Nt.length; Zt++) {
              const He = Nt[Zt].image[bt].image;
              lt ? Ut && e.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, Zt + 1, 0, 0, He.width, He.height, kt, Yt, He.data) : e.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, Zt + 1, _e, He.width, He.height, 0, kt, Yt, He.data);
            }
          } else {
            lt ? Ut && e.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, 0, 0, 0, kt, Yt, Dt[bt]) : e.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, 0, _e, kt, Yt, Dt[bt]);
            for (let Zt = 0; Zt < Nt.length; Zt++) {
              const fe = Nt[Zt];
              lt ? Ut && e.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, Zt + 1, 0, 0, kt, Yt, fe.image[bt]) : e.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + bt, Zt + 1, _e, kt, Yt, fe.image[bt]);
            }
          }
      }
      b(G) && y(n.TEXTURE_CUBE_MAP), Mt.__version = Rt.version, G.onUpdate && G.onUpdate(G);
    }
    tt.__version = G.version;
  }
  function J(tt, G, ct, Et, Rt, Mt) {
    const Jt = o.convert(ct.format, ct.colorSpace), It = o.convert(ct.type), se = w(ct.internalFormat, Jt, It, ct.colorSpace), le = s.get(G), Ot = s.get(ct);
    if (Ot.__renderTarget = G, !le.__hasExternalTextures) {
      const Dt = Math.max(1, G.width >> Mt), Wt = Math.max(1, G.height >> Mt);
      Rt === n.TEXTURE_3D || Rt === n.TEXTURE_2D_ARRAY ? e.texImage3D(Rt, Mt, se, Dt, Wt, G.depth, 0, Jt, It, null) : e.texImage2D(Rt, Mt, se, Dt, Wt, 0, Jt, It, null);
    }
    e.bindFramebuffer(n.FRAMEBUFFER, tt), Ue(G) ? u.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER, Et, Rt, Ot.__webglTexture, 0, it(G)) : (Rt === n.TEXTURE_2D || Rt >= n.TEXTURE_CUBE_MAP_POSITIVE_X && Rt <= n.TEXTURE_CUBE_MAP_NEGATIVE_Z) && n.framebufferTexture2D(n.FRAMEBUFFER, Et, Rt, Ot.__webglTexture, Mt), e.bindFramebuffer(n.FRAMEBUFFER, null);
  }
  function rt(tt, G, ct) {
    if (n.bindRenderbuffer(n.RENDERBUFFER, tt), G.depthBuffer) {
      const Et = G.depthTexture, Rt = Et && Et.isDepthTexture ? Et.type : null, Mt = M(G.stencilBuffer, Rt), Jt = G.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT;
      Ue(G) ? u.renderbufferStorageMultisampleEXT(n.RENDERBUFFER, it(G), Mt, G.width, G.height) : ct ? n.renderbufferStorageMultisample(n.RENDERBUFFER, it(G), Mt, G.width, G.height) : n.renderbufferStorage(n.RENDERBUFFER, Mt, G.width, G.height), n.framebufferRenderbuffer(n.FRAMEBUFFER, Jt, n.RENDERBUFFER, tt);
    } else {
      const Et = G.textures;
      for (let Rt = 0; Rt < Et.length; Rt++) {
        const Mt = Et[Rt], Jt = o.convert(Mt.format, Mt.colorSpace), It = o.convert(Mt.type), se = w(Mt.internalFormat, Jt, It, Mt.colorSpace);
        Ue(G) ? u.renderbufferStorageMultisampleEXT(n.RENDERBUFFER, it(G), se, G.width, G.height) : ct ? n.renderbufferStorageMultisample(n.RENDERBUFFER, it(G), se, G.width, G.height) : n.renderbufferStorage(n.RENDERBUFFER, se, G.width, G.height);
      }
    }
    n.bindRenderbuffer(n.RENDERBUFFER, null);
  }
  function dt(tt, G, ct) {
    const Et = G.isWebGLCubeRenderTarget === !0;
    if (e.bindFramebuffer(n.FRAMEBUFFER, tt), !(G.depthTexture && G.depthTexture.isDepthTexture))
      throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");
    const Rt = s.get(G.depthTexture);
    if (Rt.__renderTarget = G, (!Rt.__webglTexture || G.depthTexture.image.width !== G.width || G.depthTexture.image.height !== G.height) && (G.depthTexture.image.width = G.width, G.depthTexture.image.height = G.height, G.depthTexture.needsUpdate = !0), Et) {
      if (Rt.__webglInit === void 0 && (Rt.__webglInit = !0, G.depthTexture.addEventListener("dispose", C)), Rt.__webglTexture === void 0) {
        Rt.__webglTexture = n.createTexture(), e.bindTexture(n.TEXTURE_CUBE_MAP, Rt.__webglTexture), W(n.TEXTURE_CUBE_MAP, G.depthTexture);
        const le = o.convert(G.depthTexture.format), Ot = o.convert(G.depthTexture.type);
        let Dt;
        G.depthTexture.format === hr ? Dt = n.DEPTH_COMPONENT24 : G.depthTexture.format === Ba && (Dt = n.DEPTH24_STENCIL8);
        for (let Wt = 0; Wt < 6; Wt++)
          n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + Wt, 0, Dt, G.width, G.height, 0, le, Ot, null);
      }
    } else
      V(G.depthTexture, 0);
    const Mt = Rt.__webglTexture, Jt = it(G), It = Et ? n.TEXTURE_CUBE_MAP_POSITIVE_X + ct : n.TEXTURE_2D, se = G.depthTexture.format === Ba ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT;
    if (G.depthTexture.format === hr)
      Ue(G) ? u.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER, se, It, Mt, 0, Jt) : n.framebufferTexture2D(n.FRAMEBUFFER, se, It, Mt, 0);
    else if (G.depthTexture.format === Ba)
      Ue(G) ? u.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER, se, It, Mt, 0, Jt) : n.framebufferTexture2D(n.FRAMEBUFFER, se, It, Mt, 0);
    else
      throw new Error("Unknown depthTexture format");
  }
  function yt(tt) {
    const G = s.get(tt), ct = tt.isWebGLCubeRenderTarget === !0;
    if (G.__boundDepthTexture !== tt.depthTexture) {
      const Et = tt.depthTexture;
      if (G.__depthDisposeCallback && G.__depthDisposeCallback(), Et) {
        const Rt = () => {
          delete G.__boundDepthTexture, delete G.__depthDisposeCallback, Et.removeEventListener("dispose", Rt);
        };
        Et.addEventListener("dispose", Rt), G.__depthDisposeCallback = Rt;
      }
      G.__boundDepthTexture = Et;
    }
    if (tt.depthTexture && !G.__autoAllocateDepthBuffer)
      if (ct)
        for (let Et = 0; Et < 6; Et++)
          dt(G.__webglFramebuffer[Et], tt, Et);
      else {
        const Et = tt.texture.mipmaps;
        Et && Et.length > 0 ? dt(G.__webglFramebuffer[0], tt, 0) : dt(G.__webglFramebuffer, tt, 0);
      }
    else if (ct) {
      G.__webglDepthbuffer = [];
      for (let Et = 0; Et < 6; Et++)
        if (e.bindFramebuffer(n.FRAMEBUFFER, G.__webglFramebuffer[Et]), G.__webglDepthbuffer[Et] === void 0)
          G.__webglDepthbuffer[Et] = n.createRenderbuffer(), rt(G.__webglDepthbuffer[Et], tt, !1);
        else {
          const Rt = tt.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT, Mt = G.__webglDepthbuffer[Et];
          n.bindRenderbuffer(n.RENDERBUFFER, Mt), n.framebufferRenderbuffer(n.FRAMEBUFFER, Rt, n.RENDERBUFFER, Mt);
        }
    } else {
      const Et = tt.texture.mipmaps;
      if (Et && Et.length > 0 ? e.bindFramebuffer(n.FRAMEBUFFER, G.__webglFramebuffer[0]) : e.bindFramebuffer(n.FRAMEBUFFER, G.__webglFramebuffer), G.__webglDepthbuffer === void 0)
        G.__webglDepthbuffer = n.createRenderbuffer(), rt(G.__webglDepthbuffer, tt, !1);
      else {
        const Rt = tt.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT, Mt = G.__webglDepthbuffer;
        n.bindRenderbuffer(n.RENDERBUFFER, Mt), n.framebufferRenderbuffer(n.FRAMEBUFFER, Rt, n.RENDERBUFFER, Mt);
      }
    }
    e.bindFramebuffer(n.FRAMEBUFFER, null);
  }
  function Pt(tt, G, ct) {
    const Et = s.get(tt);
    G !== void 0 && J(Et.__webglFramebuffer, tt, tt.texture, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, 0), ct !== void 0 && yt(tt);
  }
  function Lt(tt) {
    const G = tt.texture, ct = s.get(tt), Et = s.get(G);
    tt.addEventListener("dispose", D);
    const Rt = tt.textures, Mt = tt.isWebGLCubeRenderTarget === !0, Jt = Rt.length > 1;
    if (Jt || (Et.__webglTexture === void 0 && (Et.__webglTexture = n.createTexture()), Et.__version = G.version, c.memory.textures++), Mt) {
      ct.__webglFramebuffer = [];
      for (let It = 0; It < 6; It++)
        if (G.mipmaps && G.mipmaps.length > 0) {
          ct.__webglFramebuffer[It] = [];
          for (let se = 0; se < G.mipmaps.length; se++)
            ct.__webglFramebuffer[It][se] = n.createFramebuffer();
        } else
          ct.__webglFramebuffer[It] = n.createFramebuffer();
    } else {
      if (G.mipmaps && G.mipmaps.length > 0) {
        ct.__webglFramebuffer = [];
        for (let It = 0; It < G.mipmaps.length; It++)
          ct.__webglFramebuffer[It] = n.createFramebuffer();
      } else
        ct.__webglFramebuffer = n.createFramebuffer();
      if (Jt)
        for (let It = 0, se = Rt.length; It < se; It++) {
          const le = s.get(Rt[It]);
          le.__webglTexture === void 0 && (le.__webglTexture = n.createTexture(), c.memory.textures++);
        }
      if (tt.samples > 0 && Ue(tt) === !1) {
        ct.__webglMultisampledFramebuffer = n.createFramebuffer(), ct.__webglColorRenderbuffer = [], e.bindFramebuffer(n.FRAMEBUFFER, ct.__webglMultisampledFramebuffer);
        for (let It = 0; It < Rt.length; It++) {
          const se = Rt[It];
          ct.__webglColorRenderbuffer[It] = n.createRenderbuffer(), n.bindRenderbuffer(n.RENDERBUFFER, ct.__webglColorRenderbuffer[It]);
          const le = o.convert(se.format, se.colorSpace), Ot = o.convert(se.type), Dt = w(se.internalFormat, le, Ot, se.colorSpace, tt.isXRRenderTarget === !0), Wt = it(tt);
          n.renderbufferStorageMultisample(n.RENDERBUFFER, Wt, Dt, tt.width, tt.height), n.framebufferRenderbuffer(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0 + It, n.RENDERBUFFER, ct.__webglColorRenderbuffer[It]);
        }
        n.bindRenderbuffer(n.RENDERBUFFER, null), tt.depthBuffer && (ct.__webglDepthRenderbuffer = n.createRenderbuffer(), rt(ct.__webglDepthRenderbuffer, tt, !0)), e.bindFramebuffer(n.FRAMEBUFFER, null);
      }
    }
    if (Mt) {
      e.bindTexture(n.TEXTURE_CUBE_MAP, Et.__webglTexture), W(n.TEXTURE_CUBE_MAP, G);
      for (let It = 0; It < 6; It++)
        if (G.mipmaps && G.mipmaps.length > 0)
          for (let se = 0; se < G.mipmaps.length; se++)
            J(ct.__webglFramebuffer[It][se], tt, G, n.COLOR_ATTACHMENT0, n.TEXTURE_CUBE_MAP_POSITIVE_X + It, se);
        else
          J(ct.__webglFramebuffer[It], tt, G, n.COLOR_ATTACHMENT0, n.TEXTURE_CUBE_MAP_POSITIVE_X + It, 0);
      b(G) && y(n.TEXTURE_CUBE_MAP), e.unbindTexture();
    } else if (Jt) {
      for (let It = 0, se = Rt.length; It < se; It++) {
        const le = Rt[It], Ot = s.get(le);
        let Dt = n.TEXTURE_2D;
        (tt.isWebGL3DRenderTarget || tt.isWebGLArrayRenderTarget) && (Dt = tt.isWebGL3DRenderTarget ? n.TEXTURE_3D : n.TEXTURE_2D_ARRAY), e.bindTexture(Dt, Ot.__webglTexture), W(Dt, le), J(ct.__webglFramebuffer, tt, le, n.COLOR_ATTACHMENT0 + It, Dt, 0), b(le) && y(Dt);
      }
      e.unbindTexture();
    } else {
      let It = n.TEXTURE_2D;
      if ((tt.isWebGL3DRenderTarget || tt.isWebGLArrayRenderTarget) && (It = tt.isWebGL3DRenderTarget ? n.TEXTURE_3D : n.TEXTURE_2D_ARRAY), e.bindTexture(It, Et.__webglTexture), W(It, G), G.mipmaps && G.mipmaps.length > 0)
        for (let se = 0; se < G.mipmaps.length; se++)
          J(ct.__webglFramebuffer[se], tt, G, n.COLOR_ATTACHMENT0, It, se);
      else
        J(ct.__webglFramebuffer, tt, G, n.COLOR_ATTACHMENT0, It, 0);
      b(G) && y(It), e.unbindTexture();
    }
    tt.depthBuffer && yt(tt);
  }
  function zt(tt) {
    const G = tt.textures;
    for (let ct = 0, Et = G.length; ct < Et; ct++) {
      const Rt = G[ct];
      if (b(Rt)) {
        const Mt = E(tt), Jt = s.get(Rt).__webglTexture;
        e.bindTexture(Mt, Jt), y(Mt), e.unbindTexture();
      }
    }
  }
  const Xt = [], Ft = [];
  function ve(tt) {
    if (tt.samples > 0) {
      if (Ue(tt) === !1) {
        const G = tt.textures, ct = tt.width, Et = tt.height;
        let Rt = n.COLOR_BUFFER_BIT;
        const Mt = tt.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT, Jt = s.get(tt), It = G.length > 1;
        if (It)
          for (let le = 0; le < G.length; le++)
            e.bindFramebuffer(n.FRAMEBUFFER, Jt.__webglMultisampledFramebuffer), n.framebufferRenderbuffer(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0 + le, n.RENDERBUFFER, null), e.bindFramebuffer(n.FRAMEBUFFER, Jt.__webglFramebuffer), n.framebufferTexture2D(n.DRAW_FRAMEBUFFER, n.COLOR_ATTACHMENT0 + le, n.TEXTURE_2D, null, 0);
        e.bindFramebuffer(n.READ_FRAMEBUFFER, Jt.__webglMultisampledFramebuffer);
        const se = tt.texture.mipmaps;
        se && se.length > 0 ? e.bindFramebuffer(n.DRAW_FRAMEBUFFER, Jt.__webglFramebuffer[0]) : e.bindFramebuffer(n.DRAW_FRAMEBUFFER, Jt.__webglFramebuffer);
        for (let le = 0; le < G.length; le++) {
          if (tt.resolveDepthBuffer && (tt.depthBuffer && (Rt |= n.DEPTH_BUFFER_BIT), tt.stencilBuffer && tt.resolveStencilBuffer && (Rt |= n.STENCIL_BUFFER_BIT)), It) {
            n.framebufferRenderbuffer(n.READ_FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.RENDERBUFFER, Jt.__webglColorRenderbuffer[le]);
            const Ot = s.get(G[le]).__webglTexture;
            n.framebufferTexture2D(n.DRAW_FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, Ot, 0);
          }
          n.blitFramebuffer(0, 0, ct, Et, 0, 0, ct, Et, Rt, n.NEAREST), d === !0 && (Xt.length = 0, Ft.length = 0, Xt.push(n.COLOR_ATTACHMENT0 + le), tt.depthBuffer && tt.resolveDepthBuffer === !1 && (Xt.push(Mt), Ft.push(Mt), n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER, Ft)), n.invalidateFramebuffer(n.READ_FRAMEBUFFER, Xt));
        }
        if (e.bindFramebuffer(n.READ_FRAMEBUFFER, null), e.bindFramebuffer(n.DRAW_FRAMEBUFFER, null), It)
          for (let le = 0; le < G.length; le++) {
            e.bindFramebuffer(n.FRAMEBUFFER, Jt.__webglMultisampledFramebuffer), n.framebufferRenderbuffer(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0 + le, n.RENDERBUFFER, Jt.__webglColorRenderbuffer[le]);
            const Ot = s.get(G[le]).__webglTexture;
            e.bindFramebuffer(n.FRAMEBUFFER, Jt.__webglFramebuffer), n.framebufferTexture2D(n.DRAW_FRAMEBUFFER, n.COLOR_ATTACHMENT0 + le, n.TEXTURE_2D, Ot, 0);
          }
        e.bindFramebuffer(n.DRAW_FRAMEBUFFER, Jt.__webglMultisampledFramebuffer);
      } else if (tt.depthBuffer && tt.resolveDepthBuffer === !1 && d) {
        const G = tt.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT;
        n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER, [G]);
      }
    }
  }
  function it(tt) {
    return Math.min(a.maxSamples, tt.samples);
  }
  function Ue(tt) {
    const G = s.get(tt);
    return tt.samples > 0 && t.has("WEBGL_multisampled_render_to_texture") === !0 && G.__useRenderToTexture !== !1;
  }
  function xe(tt) {
    const G = c.render.frame;
    m.get(tt) !== G && (m.set(tt, G), tt.update());
  }
  function Re(tt, G) {
    const ct = tt.colorSpace, Et = tt.format, Rt = tt.type;
    return tt.isCompressedTexture === !0 || tt.isVideoTexture === !0 || ct !== pl && ct !== ta && (Be.getTransfer(ct) === We ? (Et !== Ni || Rt !== Ci) && de("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.") : Ie("WebGLTextures: Unsupported texture color space:", ct)), G;
  }
  function Kt(tt) {
    return typeof HTMLImageElement < "u" && tt instanceof HTMLImageElement ? (h.width = tt.naturalWidth || tt.width, h.height = tt.naturalHeight || tt.height) : typeof VideoFrame < "u" && tt instanceof VideoFrame ? (h.width = tt.displayWidth, h.height = tt.displayHeight) : (h.width = tt.width, h.height = tt.height), h;
  }
  this.allocateTextureUnit = H, this.resetTextureUnits = B, this.setTexture2D = V, this.setTexture2DArray = N, this.setTexture3D = I, this.setTextureCube = k, this.rebindTextures = Pt, this.setupRenderTarget = Lt, this.updateRenderTargetMipmap = zt, this.updateMultisampleRenderTarget = ve, this.setupDepthRenderbuffer = yt, this.setupFrameBufferTexture = J, this.useMultisampledRTT = Ue, this.isReversedDepthBuffer = function() {
    return e.buffers.depth.getReversed();
  };
}
function PO(n, t) {
  function e(s, a = ta) {
    let o;
    const c = Be.getTransfer(a);
    if (s === Ci) return n.UNSIGNED_BYTE;
    if (s === G0) return n.UNSIGNED_SHORT_4_4_4_4;
    if (s === k0) return n.UNSIGNED_SHORT_5_5_5_1;
    if (s === xM) return n.UNSIGNED_INT_5_9_9_9_REV;
    if (s === SM) return n.UNSIGNED_INT_10F_11F_11F_REV;
    if (s === _M) return n.BYTE;
    if (s === yM) return n.SHORT;
    if (s === zc) return n.UNSIGNED_SHORT;
    if (s === V0) return n.INT;
    if (s === Cs) return n.UNSIGNED_INT;
    if (s === Di) return n.FLOAT;
    if (s === dr) return n.HALF_FLOAT;
    if (s === bM) return n.ALPHA;
    if (s === MM) return n.RGB;
    if (s === Ni) return n.RGBA;
    if (s === hr) return n.DEPTH_COMPONENT;
    if (s === Ba) return n.DEPTH_STENCIL;
    if (s === X0) return n.RED;
    if (s === W0) return n.RED_INTEGER;
    if (s === hl) return n.RG;
    if (s === Y0) return n.RG_INTEGER;
    if (s === j0) return n.RGBA_INTEGER;
    if (s === fd || s === dd || s === hd || s === pd)
      if (c === We)
        if (o = t.get("WEBGL_compressed_texture_s3tc_srgb"), o !== null) {
          if (s === fd) return o.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          if (s === dd) return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          if (s === hd) return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          if (s === pd) return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
        } else
          return null;
      else if (o = t.get("WEBGL_compressed_texture_s3tc"), o !== null) {
        if (s === fd) return o.COMPRESSED_RGB_S3TC_DXT1_EXT;
        if (s === dd) return o.COMPRESSED_RGBA_S3TC_DXT1_EXT;
        if (s === hd) return o.COMPRESSED_RGBA_S3TC_DXT3_EXT;
        if (s === pd) return o.COMPRESSED_RGBA_S3TC_DXT5_EXT;
      } else
        return null;
    if (s === Bg || s === zg || s === Fg || s === Hg)
      if (o = t.get("WEBGL_compressed_texture_pvrtc"), o !== null) {
        if (s === Bg) return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
        if (s === zg) return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
        if (s === Fg) return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
        if (s === Hg) return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
      } else
        return null;
    if (s === Vg || s === Gg || s === kg || s === Xg || s === Wg || s === Yg || s === jg)
      if (o = t.get("WEBGL_compressed_texture_etc"), o !== null) {
        if (s === Vg || s === Gg) return c === We ? o.COMPRESSED_SRGB8_ETC2 : o.COMPRESSED_RGB8_ETC2;
        if (s === kg) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : o.COMPRESSED_RGBA8_ETC2_EAC;
        if (s === Xg) return o.COMPRESSED_R11_EAC;
        if (s === Wg) return o.COMPRESSED_SIGNED_R11_EAC;
        if (s === Yg) return o.COMPRESSED_RG11_EAC;
        if (s === jg) return o.COMPRESSED_SIGNED_RG11_EAC;
      } else
        return null;
    if (s === qg || s === Zg || s === $g || s === Kg || s === Qg || s === Jg || s === t0 || s === e0 || s === n0 || s === i0 || s === s0 || s === r0 || s === a0 || s === o0)
      if (o = t.get("WEBGL_compressed_texture_astc"), o !== null) {
        if (s === qg) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : o.COMPRESSED_RGBA_ASTC_4x4_KHR;
        if (s === Zg) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : o.COMPRESSED_RGBA_ASTC_5x4_KHR;
        if (s === $g) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : o.COMPRESSED_RGBA_ASTC_5x5_KHR;
        if (s === Kg) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : o.COMPRESSED_RGBA_ASTC_6x5_KHR;
        if (s === Qg) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : o.COMPRESSED_RGBA_ASTC_6x6_KHR;
        if (s === Jg) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : o.COMPRESSED_RGBA_ASTC_8x5_KHR;
        if (s === t0) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : o.COMPRESSED_RGBA_ASTC_8x6_KHR;
        if (s === e0) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : o.COMPRESSED_RGBA_ASTC_8x8_KHR;
        if (s === n0) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : o.COMPRESSED_RGBA_ASTC_10x5_KHR;
        if (s === i0) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : o.COMPRESSED_RGBA_ASTC_10x6_KHR;
        if (s === s0) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : o.COMPRESSED_RGBA_ASTC_10x8_KHR;
        if (s === r0) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : o.COMPRESSED_RGBA_ASTC_10x10_KHR;
        if (s === a0) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : o.COMPRESSED_RGBA_ASTC_12x10_KHR;
        if (s === o0) return c === We ? o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : o.COMPRESSED_RGBA_ASTC_12x12_KHR;
      } else
        return null;
    if (s === l0 || s === c0 || s === u0)
      if (o = t.get("EXT_texture_compression_bptc"), o !== null) {
        if (s === l0) return c === We ? o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : o.COMPRESSED_RGBA_BPTC_UNORM_EXT;
        if (s === c0) return o.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
        if (s === u0) return o.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
      } else
        return null;
    if (s === f0 || s === d0 || s === h0 || s === p0)
      if (o = t.get("EXT_texture_compression_rgtc"), o !== null) {
        if (s === f0) return o.COMPRESSED_RED_RGTC1_EXT;
        if (s === d0) return o.COMPRESSED_SIGNED_RED_RGTC1_EXT;
        if (s === h0) return o.COMPRESSED_RED_GREEN_RGTC2_EXT;
        if (s === p0) return o.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
      } else
        return null;
    return s === Fc ? n.UNSIGNED_INT_24_8 : n[s] !== void 0 ? n[s] : null;
  }
  return { convert: e };
}
const IO = `
void main() {

	gl_Position = vec4( position, 1.0 );

}`, BO = `
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 zO {
  /**
   * 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 s = new IM(t.texture);
      (t.depthNear !== e.depthNear || t.depthFar !== e.depthFar) && (this.depthNear = t.depthNear, this.depthFar = t.depthFar), this.texture = s;
    }
  }
  /**
   * 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, s = new as({
        vertexShader: IO,
        fragmentShader: BO,
        uniforms: {
          depthColor: { value: this.texture },
          depthWidth: { value: e.z },
          depthHeight: { value: e.w }
        }
      });
      this.mesh = new Ln(new $d(20, 20), s);
    }
    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 FO extends qa {
  /**
   * Constructs a new WebGL renderer.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGL2RenderingContext} gl - The rendering context.
   */
  constructor(t, e) {
    super();
    const s = this;
    let a = null, o = 1, c = null, u = "local-floor", d = 1, h = null, m = null, p = null, g = null, _ = null, x = null;
    const A = typeof XRWebGLBinding < "u", b = new zO(), y = {}, E = e.getContextAttributes();
    let w = null, M = null;
    const O = [], C = [], D = new ae();
    let T = null;
    const L = new Ti();
    L.viewport = new Je();
    const z = new Ti();
    z.viewport = new Je();
    const R = [L, z], B = new Y3();
    let H = null, U = null;
    this.cameraAutoUpdate = !0, this.enabled = !1, this.isPresenting = !1, this.getController = function(Y) {
      let K = O[Y];
      return K === void 0 && (K = new Cm(), O[Y] = K), K.getTargetRaySpace();
    }, this.getControllerGrip = function(Y) {
      let K = O[Y];
      return K === void 0 && (K = new Cm(), O[Y] = K), K.getGripSpace();
    }, this.getHand = function(Y) {
      let K = O[Y];
      return K === void 0 && (K = new Cm(), O[Y] = K), K.getHandSpace();
    };
    function V(Y) {
      const K = C.indexOf(Y.inputSource);
      if (K === -1)
        return;
      const J = O[K];
      J !== void 0 && (J.update(Y.inputSource, Y.frame, h || c), J.dispatchEvent({ type: Y.type, data: Y.inputSource }));
    }
    function N() {
      a.removeEventListener("select", V), a.removeEventListener("selectstart", V), a.removeEventListener("selectend", V), a.removeEventListener("squeeze", V), a.removeEventListener("squeezestart", V), a.removeEventListener("squeezeend", V), a.removeEventListener("end", N), a.removeEventListener("inputsourceschange", I);
      for (let Y = 0; Y < O.length; Y++) {
        const K = C[Y];
        K !== null && (C[Y] = null, O[Y].disconnect(K));
      }
      H = null, U = null, b.reset();
      for (const Y in y)
        delete y[Y];
      t.setRenderTarget(w), _ = null, g = null, p = null, a = null, M = null, j.stop(), s.isPresenting = !1, t.setPixelRatio(T), t.setSize(D.width, D.height, !1), s.dispatchEvent({ type: "sessionend" });
    }
    this.setFramebufferScaleFactor = function(Y) {
      o = Y, s.isPresenting === !0 && de("WebXRManager: Cannot change framebuffer scale while presenting.");
    }, this.setReferenceSpaceType = function(Y) {
      u = Y, s.isPresenting === !0 && de("WebXRManager: Cannot change reference space type while presenting.");
    }, this.getReferenceSpace = function() {
      return h || c;
    }, this.setReferenceSpace = function(Y) {
      h = Y;
    }, this.getBaseLayer = function() {
      return g !== null ? g : _;
    }, this.getBinding = function() {
      return p === null && A && (p = new XRWebGLBinding(a, e)), p;
    }, this.getFrame = function() {
      return x;
    }, this.getSession = function() {
      return a;
    }, this.setSession = async function(Y) {
      if (a = Y, a !== null) {
        if (w = t.getRenderTarget(), a.addEventListener("select", V), a.addEventListener("selectstart", V), a.addEventListener("selectend", V), a.addEventListener("squeeze", V), a.addEventListener("squeezestart", V), a.addEventListener("squeezeend", V), a.addEventListener("end", N), a.addEventListener("inputsourceschange", I), E.xrCompatible !== !0 && await e.makeXRCompatible(), T = t.getPixelRatio(), t.getSize(D), A && "createProjectionLayer" in XRWebGLBinding.prototype) {
          let J = null, rt = null, dt = null;
          E.depth && (dt = E.stencil ? e.DEPTH24_STENCIL8 : e.DEPTH_COMPONENT24, J = E.stencil ? Ba : hr, rt = E.stencil ? Fc : Cs);
          const yt = {
            colorFormat: e.RGBA8,
            depthFormat: dt,
            scaleFactor: o
          };
          p = this.getBinding(), g = p.createProjectionLayer(yt), a.updateRenderState({ layers: [g] }), t.setPixelRatio(1), t.setSize(g.textureWidth, g.textureHeight, !1), M = new As(
            g.textureWidth,
            g.textureHeight,
            {
              format: Ni,
              type: Ci,
              depthTexture: new kc(g.textureWidth, g.textureHeight, rt, void 0, void 0, void 0, void 0, void 0, void 0, J),
              stencilBuffer: E.stencil,
              colorSpace: t.outputColorSpace,
              samples: E.antialias ? 4 : 0,
              resolveDepthBuffer: g.ignoreDepthValues === !1,
              resolveStencilBuffer: g.ignoreDepthValues === !1
            }
          );
        } else {
          const J = {
            antialias: E.antialias,
            alpha: !0,
            depth: E.depth,
            stencil: E.stencil,
            framebufferScaleFactor: o
          };
          _ = new XRWebGLLayer(a, e, J), a.updateRenderState({ baseLayer: _ }), t.setPixelRatio(1), t.setSize(_.framebufferWidth, _.framebufferHeight, !1), M = new As(
            _.framebufferWidth,
            _.framebufferHeight,
            {
              format: Ni,
              type: Ci,
              colorSpace: t.outputColorSpace,
              stencilBuffer: E.stencil,
              resolveDepthBuffer: _.ignoreDepthValues === !1,
              resolveStencilBuffer: _.ignoreDepthValues === !1
            }
          );
        }
        M.isXRRenderTarget = !0, this.setFoveation(d), h = null, c = await a.requestReferenceSpace(u), j.setContext(a), j.start(), s.isPresenting = !0, s.dispatchEvent({ type: "sessionstart" });
      }
    }, this.getEnvironmentBlendMode = function() {
      if (a !== null)
        return a.environmentBlendMode;
    }, this.getDepthTexture = function() {
      return b.getDepthTexture();
    };
    function I(Y) {
      for (let K = 0; K < Y.removed.length; K++) {
        const J = Y.removed[K], rt = C.indexOf(J);
        rt >= 0 && (C[rt] = null, O[rt].disconnect(J));
      }
      for (let K = 0; K < Y.added.length; K++) {
        const J = Y.added[K];
        let rt = C.indexOf(J);
        if (rt === -1) {
          for (let yt = 0; yt < O.length; yt++)
            if (yt >= C.length) {
              C.push(J), rt = yt;
              break;
            } else if (C[yt] === null) {
              C[yt] = J, rt = yt;
              break;
            }
          if (rt === -1) break;
        }
        const dt = O[rt];
        dt && dt.connect(J);
      }
    }
    const k = new st(), X = new st();
    function Q(Y, K, J) {
      k.setFromMatrixPosition(K.matrixWorld), X.setFromMatrixPosition(J.matrixWorld);
      const rt = k.distanceTo(X), dt = K.projectionMatrix.elements, yt = J.projectionMatrix.elements, Pt = dt[14] / (dt[10] - 1), Lt = dt[14] / (dt[10] + 1), zt = (dt[9] + 1) / dt[5], Xt = (dt[9] - 1) / dt[5], Ft = (dt[8] - 1) / dt[0], ve = (yt[8] + 1) / yt[0], it = Pt * Ft, Ue = Pt * ve, xe = rt / (-Ft + ve), Re = xe * -Ft;
      if (K.matrixWorld.decompose(Y.position, Y.quaternion, Y.scale), Y.translateX(Re), Y.translateZ(xe), Y.matrixWorld.compose(Y.position, Y.quaternion, Y.scale), Y.matrixWorldInverse.copy(Y.matrixWorld).invert(), dt[10] === -1)
        Y.projectionMatrix.copy(K.projectionMatrix), Y.projectionMatrixInverse.copy(K.projectionMatrixInverse);
      else {
        const Kt = Pt + xe, tt = Lt + xe, G = it - Re, ct = Ue + (rt - Re), Et = zt * Lt / tt * Kt, Rt = Xt * Lt / tt * Kt;
        Y.projectionMatrix.makePerspective(G, ct, Et, Rt, Kt, tt), Y.projectionMatrixInverse.copy(Y.projectionMatrix).invert();
      }
    }
    function F(Y, K) {
      K === null ? Y.matrixWorld.copy(Y.matrix) : Y.matrixWorld.multiplyMatrices(K.matrixWorld, Y.matrix), Y.matrixWorldInverse.copy(Y.matrixWorld).invert();
    }
    this.updateCamera = function(Y) {
      if (a === null) return;
      let K = Y.near, J = Y.far;
      b.texture !== null && (b.depthNear > 0 && (K = b.depthNear), b.depthFar > 0 && (J = b.depthFar)), B.near = z.near = L.near = K, B.far = z.far = L.far = J, (H !== B.near || U !== B.far) && (a.updateRenderState({
        depthNear: B.near,
        depthFar: B.far
      }), H = B.near, U = B.far), B.layers.mask = Y.layers.mask | 6, L.layers.mask = B.layers.mask & -5, z.layers.mask = B.layers.mask & -3;
      const rt = Y.parent, dt = B.cameras;
      F(B, rt);
      for (let yt = 0; yt < dt.length; yt++)
        F(dt[yt], rt);
      dt.length === 2 ? Q(B, L, z) : B.projectionMatrix.copy(L.projectionMatrix), W(Y, B, rt);
    };
    function W(Y, K, J) {
      J === null ? Y.matrix.copy(K.matrixWorld) : (Y.matrix.copy(J.matrixWorld), Y.matrix.invert(), Y.matrix.multiply(K.matrixWorld)), Y.matrix.decompose(Y.position, Y.quaternion, Y.scale), Y.updateMatrixWorld(!0), Y.projectionMatrix.copy(K.projectionMatrix), Y.projectionMatrixInverse.copy(K.projectionMatrixInverse), Y.isPerspectiveCamera && (Y.fov = Vc * 2 * Math.atan(1 / Y.projectionMatrix.elements[5]), Y.zoom = 1);
    }
    this.getCamera = function() {
      return B;
    }, this.getFoveation = function() {
      if (!(g === null && _ === null))
        return d;
    }, this.setFoveation = function(Y) {
      d = Y, g !== null && (g.fixedFoveation = Y), _ !== null && _.fixedFoveation !== void 0 && (_.fixedFoveation = Y);
    }, this.hasDepthSensing = function() {
      return b.texture !== null;
    }, this.getDepthSensingMesh = function() {
      return b.getMesh(B);
    }, this.getCameraTexture = function(Y) {
      return y[Y];
    };
    let et = null;
    function $(Y, K) {
      if (m = K.getViewerPose(h || c), x = K, m !== null) {
        const J = m.views;
        _ !== null && (t.setRenderTargetFramebuffer(M, _.framebuffer), t.setRenderTarget(M));
        let rt = !1;
        J.length !== B.cameras.length && (B.cameras.length = 0, rt = !0);
        for (let Lt = 0; Lt < J.length; Lt++) {
          const zt = J[Lt];
          let Xt = null;
          if (_ !== null)
            Xt = _.getViewport(zt);
          else {
            const ve = p.getViewSubImage(g, zt);
            Xt = ve.viewport, Lt === 0 && (t.setRenderTargetTextures(
              M,
              ve.colorTexture,
              ve.depthStencilTexture
            ), t.setRenderTarget(M));
          }
          let Ft = R[Lt];
          Ft === void 0 && (Ft = new Ti(), Ft.layers.enable(Lt), Ft.viewport = new Je(), R[Lt] = Ft), Ft.matrix.fromArray(zt.transform.matrix), Ft.matrix.decompose(Ft.position, Ft.quaternion, Ft.scale), Ft.projectionMatrix.fromArray(zt.projectionMatrix), Ft.projectionMatrixInverse.copy(Ft.projectionMatrix).invert(), Ft.viewport.set(Xt.x, Xt.y, Xt.width, Xt.height), Lt === 0 && (B.matrix.copy(Ft.matrix), B.matrix.decompose(B.position, B.quaternion, B.scale)), rt === !0 && B.cameras.push(Ft);
        }
        const dt = a.enabledFeatures;
        if (dt && dt.includes("depth-sensing") && a.depthUsage == "gpu-optimized" && A) {
          p = s.getBinding();
          const Lt = p.getDepthInformation(J[0]);
          Lt && Lt.isValid && Lt.texture && b.init(Lt, a.renderState);
        }
        if (dt && dt.includes("camera-access") && A) {
          t.state.unbindTexture(), p = s.getBinding();
          for (let Lt = 0; Lt < J.length; Lt++) {
            const zt = J[Lt].camera;
            if (zt) {
              let Xt = y[zt];
              Xt || (Xt = new IM(), y[zt] = Xt);
              const Ft = p.getCameraImage(zt);
              Xt.sourceTexture = Ft;
            }
          }
        }
      }
      for (let J = 0; J < O.length; J++) {
        const rt = C[J], dt = O[J];
        rt !== null && dt !== void 0 && dt.update(rt, K, h || c);
      }
      et && et(Y, K), K.detectedPlanes && s.dispatchEvent({ type: "planesdetected", data: K }), x = null;
    }
    const j = new FM();
    j.setAnimationLoop($), this.setAnimationLoop = function(Y) {
      et = Y;
    }, this.dispose = function() {
    };
  }
}
const Na = /* @__PURE__ */ new Rs(), HO = /* @__PURE__ */ new je();
function VO(n, t) {
  function e(b, y) {
    b.matrixAutoUpdate === !0 && b.updateMatrix(), y.value.copy(b.matrix);
  }
  function s(b, y) {
    y.color.getRGB(b.fogColor.value, BM(n)), y.isFog ? (b.fogNear.value = y.near, b.fogFar.value = y.far) : y.isFogExp2 && (b.fogDensity.value = y.density);
  }
  function a(b, y, E, w, M) {
    y.isMeshBasicMaterial ? o(b, y) : y.isMeshLambertMaterial ? (o(b, y), y.envMap && (b.envMapIntensity.value = y.envMapIntensity)) : y.isMeshToonMaterial ? (o(b, y), p(b, y)) : y.isMeshPhongMaterial ? (o(b, y), m(b, y), y.envMap && (b.envMapIntensity.value = y.envMapIntensity)) : y.isMeshStandardMaterial ? (o(b, y), g(b, y), y.isMeshPhysicalMaterial && _(b, y, M)) : y.isMeshMatcapMaterial ? (o(b, y), x(b, y)) : y.isMeshDepthMaterial ? o(b, y) : y.isMeshDistanceMaterial ? (o(b, y), A(b, y)) : y.isMeshNormalMaterial ? o(b, y) : y.isLineBasicMaterial ? (c(b, y), y.isLineDashedMaterial && u(b, y)) : y.isPointsMaterial ? d(b, y, E, w) : y.isSpriteMaterial ? h(b, y) : y.isShadowMaterial ? (b.color.value.copy(y.color), b.opacity.value = y.opacity) : y.isShaderMaterial && (y.uniformsNeedUpdate = !1);
  }
  function o(b, y) {
    b.opacity.value = y.opacity, y.color && b.diffuse.value.copy(y.color), y.emissive && b.emissive.value.copy(y.emissive).multiplyScalar(y.emissiveIntensity), y.map && (b.map.value = y.map, e(y.map, b.mapTransform)), y.alphaMap && (b.alphaMap.value = y.alphaMap, e(y.alphaMap, b.alphaMapTransform)), y.bumpMap && (b.bumpMap.value = y.bumpMap, e(y.bumpMap, b.bumpMapTransform), b.bumpScale.value = y.bumpScale, y.side === pi && (b.bumpScale.value *= -1)), y.normalMap && (b.normalMap.value = y.normalMap, e(y.normalMap, b.normalMapTransform), b.normalScale.value.copy(y.normalScale), y.side === pi && b.normalScale.value.negate()), y.displacementMap && (b.displacementMap.value = y.displacementMap, e(y.displacementMap, b.displacementMapTransform), b.displacementScale.value = y.displacementScale, b.displacementBias.value = y.displacementBias), y.emissiveMap && (b.emissiveMap.value = y.emissiveMap, e(y.emissiveMap, b.emissiveMapTransform)), y.specularMap && (b.specularMap.value = y.specularMap, e(y.specularMap, b.specularMapTransform)), y.alphaTest > 0 && (b.alphaTest.value = y.alphaTest);
    const E = t.get(y), w = E.envMap, M = E.envMapRotation;
    w && (b.envMap.value = w, Na.copy(M), Na.x *= -1, Na.y *= -1, Na.z *= -1, w.isCubeTexture && w.isRenderTargetTexture === !1 && (Na.y *= -1, Na.z *= -1), b.envMapRotation.value.setFromMatrix4(HO.makeRotationFromEuler(Na)), b.flipEnvMap.value = w.isCubeTexture && w.isRenderTargetTexture === !1 ? -1 : 1, b.reflectivity.value = y.reflectivity, b.ior.value = y.ior, b.refractionRatio.value = y.refractionRatio), y.lightMap && (b.lightMap.value = y.lightMap, b.lightMapIntensity.value = y.lightMapIntensity, e(y.lightMap, b.lightMapTransform)), y.aoMap && (b.aoMap.value = y.aoMap, b.aoMapIntensity.value = y.aoMapIntensity, e(y.aoMap, b.aoMapTransform));
  }
  function c(b, y) {
    b.diffuse.value.copy(y.color), b.opacity.value = y.opacity, y.map && (b.map.value = y.map, e(y.map, b.mapTransform));
  }
  function u(b, y) {
    b.dashSize.value = y.dashSize, b.totalSize.value = y.dashSize + y.gapSize, b.scale.value = y.scale;
  }
  function d(b, y, E, w) {
    b.diffuse.value.copy(y.color), b.opacity.value = y.opacity, b.size.value = y.size * E, b.scale.value = w * 0.5, y.map && (b.map.value = y.map, e(y.map, b.uvTransform)), y.alphaMap && (b.alphaMap.value = y.alphaMap, e(y.alphaMap, b.alphaMapTransform)), y.alphaTest > 0 && (b.alphaTest.value = y.alphaTest);
  }
  function h(b, y) {
    b.diffuse.value.copy(y.color), b.opacity.value = y.opacity, b.rotation.value = y.rotation, y.map && (b.map.value = y.map, e(y.map, b.mapTransform)), y.alphaMap && (b.alphaMap.value = y.alphaMap, e(y.alphaMap, b.alphaMapTransform)), y.alphaTest > 0 && (b.alphaTest.value = y.alphaTest);
  }
  function m(b, y) {
    b.specular.value.copy(y.specular), b.shininess.value = Math.max(y.shininess, 1e-4);
  }
  function p(b, y) {
    y.gradientMap && (b.gradientMap.value = y.gradientMap);
  }
  function g(b, y) {
    b.metalness.value = y.metalness, y.metalnessMap && (b.metalnessMap.value = y.metalnessMap, e(y.metalnessMap, b.metalnessMapTransform)), b.roughness.value = y.roughness, y.roughnessMap && (b.roughnessMap.value = y.roughnessMap, e(y.roughnessMap, b.roughnessMapTransform)), y.envMap && (b.envMapIntensity.value = y.envMapIntensity);
  }
  function _(b, y, E) {
    b.ior.value = y.ior, y.sheen > 0 && (b.sheenColor.value.copy(y.sheenColor).multiplyScalar(y.sheen), b.sheenRoughness.value = y.sheenRoughness, y.sheenColorMap && (b.sheenColorMap.value = y.sheenColorMap, e(y.sheenColorMap, b.sheenColorMapTransform)), y.sheenRoughnessMap && (b.sheenRoughnessMap.value = y.sheenRoughnessMap, e(y.sheenRoughnessMap, b.sheenRoughnessMapTransform))), y.clearcoat > 0 && (b.clearcoat.value = y.clearcoat, b.clearcoatRoughness.value = y.clearcoatRoughness, y.clearcoatMap && (b.clearcoatMap.value = y.clearcoatMap, e(y.clearcoatMap, b.clearcoatMapTransform)), y.clearcoatRoughnessMap && (b.clearcoatRoughnessMap.value = y.clearcoatRoughnessMap, e(y.clearcoatRoughnessMap, b.clearcoatRoughnessMapTransform)), y.clearcoatNormalMap && (b.clearcoatNormalMap.value = y.clearcoatNormalMap, e(y.clearcoatNormalMap, b.clearcoatNormalMapTransform), b.clearcoatNormalScale.value.copy(y.clearcoatNormalScale), y.side === pi && b.clearcoatNormalScale.value.negate())), y.dispersion > 0 && (b.dispersion.value = y.dispersion), y.iridescence > 0 && (b.iridescence.value = y.iridescence, b.iridescenceIOR.value = y.iridescenceIOR, b.iridescenceThicknessMinimum.value = y.iridescenceThicknessRange[0], b.iridescenceThicknessMaximum.value = y.iridescenceThicknessRange[1], y.iridescenceMap && (b.iridescenceMap.value = y.iridescenceMap, e(y.iridescenceMap, b.iridescenceMapTransform)), y.iridescenceThicknessMap && (b.iridescenceThicknessMap.value = y.iridescenceThicknessMap, e(y.iridescenceThicknessMap, b.iridescenceThicknessMapTransform))), y.transmission > 0 && (b.transmission.value = y.transmission, b.transmissionSamplerMap.value = E.texture, b.transmissionSamplerSize.value.set(E.width, E.height), y.transmissionMap && (b.transmissionMap.value = y.transmissionMap, e(y.transmissionMap, b.transmissionMapTransform)), b.thickness.value = y.thickness, y.thicknessMap && (b.thicknessMap.value = y.thicknessMap, e(y.thicknessMap, b.thicknessMapTransform)), b.attenuationDistance.value = y.attenuationDistance, b.attenuationColor.value.copy(y.attenuationColor)), y.anisotropy > 0 && (b.anisotropyVector.value.set(y.anisotropy * Math.cos(y.anisotropyRotation), y.anisotropy * Math.sin(y.anisotropyRotation)), y.anisotropyMap && (b.anisotropyMap.value = y.anisotropyMap, e(y.anisotropyMap, b.anisotropyMapTransform))), b.specularIntensity.value = y.specularIntensity, b.specularColor.value.copy(y.specularColor), y.specularColorMap && (b.specularColorMap.value = y.specularColorMap, e(y.specularColorMap, b.specularColorMapTransform)), y.specularIntensityMap && (b.specularIntensityMap.value = y.specularIntensityMap, e(y.specularIntensityMap, b.specularIntensityMapTransform));
  }
  function x(b, y) {
    y.matcap && (b.matcap.value = y.matcap);
  }
  function A(b, y) {
    const E = t.get(y).light;
    b.referencePosition.value.setFromMatrixPosition(E.matrixWorld), b.nearDistance.value = E.shadow.camera.near, b.farDistance.value = E.shadow.camera.far;
  }
  return {
    refreshFogUniforms: s,
    refreshMaterialUniforms: a
  };
}
function GO(n, t, e, s) {
  let a = {}, o = {}, c = [];
  const u = n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);
  function d(E, w) {
    const M = w.program;
    s.uniformBlockBinding(E, M);
  }
  function h(E, w) {
    let M = a[E.id];
    M === void 0 && (x(E), M = m(E), a[E.id] = M, E.addEventListener("dispose", b));
    const O = w.program;
    s.updateUBOMapping(E, O);
    const C = t.render.frame;
    o[E.id] !== C && (g(E), o[E.id] = C);
  }
  function m(E) {
    const w = p();
    E.__bindingPointIndex = w;
    const M = n.createBuffer(), O = E.__size, C = E.usage;
    return n.bindBuffer(n.UNIFORM_BUFFER, M), n.bufferData(n.UNIFORM_BUFFER, O, C), n.bindBuffer(n.UNIFORM_BUFFER, null), n.bindBufferBase(n.UNIFORM_BUFFER, w, M), M;
  }
  function p() {
    for (let E = 0; E < u; E++)
      if (c.indexOf(E) === -1)
        return c.push(E), E;
    return Ie("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."), 0;
  }
  function g(E) {
    const w = a[E.id], M = E.uniforms, O = E.__cache;
    n.bindBuffer(n.UNIFORM_BUFFER, w);
    for (let C = 0, D = M.length; C < D; C++) {
      const T = Array.isArray(M[C]) ? M[C] : [M[C]];
      for (let L = 0, z = T.length; L < z; L++) {
        const R = T[L];
        if (_(R, C, L, O) === !0) {
          const B = R.__offset, H = Array.isArray(R.value) ? R.value : [R.value];
          let U = 0;
          for (let V = 0; V < H.length; V++) {
            const N = H[V], I = A(N);
            typeof N == "number" || typeof N == "boolean" ? (R.__data[0] = N, n.bufferSubData(n.UNIFORM_BUFFER, B + U, R.__data)) : N.isMatrix3 ? (R.__data[0] = N.elements[0], R.__data[1] = N.elements[1], R.__data[2] = N.elements[2], R.__data[3] = 0, R.__data[4] = N.elements[3], R.__data[5] = N.elements[4], R.__data[6] = N.elements[5], R.__data[7] = 0, R.__data[8] = N.elements[6], R.__data[9] = N.elements[7], R.__data[10] = N.elements[8], R.__data[11] = 0) : (N.toArray(R.__data, U), U += I.storage / Float32Array.BYTES_PER_ELEMENT);
          }
          n.bufferSubData(n.UNIFORM_BUFFER, B, R.__data);
        }
      }
    }
    n.bindBuffer(n.UNIFORM_BUFFER, null);
  }
  function _(E, w, M, O) {
    const C = E.value, D = w + "_" + M;
    if (O[D] === void 0)
      return typeof C == "number" || typeof C == "boolean" ? O[D] = C : O[D] = C.clone(), !0;
    {
      const T = O[D];
      if (typeof C == "number" || typeof C == "boolean") {
        if (T !== C)
          return O[D] = C, !0;
      } else if (T.equals(C) === !1)
        return T.copy(C), !0;
    }
    return !1;
  }
  function x(E) {
    const w = E.uniforms;
    let M = 0;
    const O = 16;
    for (let D = 0, T = w.length; D < T; D++) {
      const L = Array.isArray(w[D]) ? w[D] : [w[D]];
      for (let z = 0, R = L.length; z < R; z++) {
        const B = L[z], H = Array.isArray(B.value) ? B.value : [B.value];
        for (let U = 0, V = H.length; U < V; U++) {
          const N = H[U], I = A(N), k = M % O, X = k % I.boundary, Q = k + X;
          M += X, Q !== 0 && O - Q < I.storage && (M += O - Q), B.__data = new Float32Array(I.storage / Float32Array.BYTES_PER_ELEMENT), B.__offset = M, M += I.storage;
        }
      }
    }
    const C = M % O;
    return C > 0 && (M += O - C), E.__size = M, E.__cache = {}, this;
  }
  function A(E) {
    const w = {
      boundary: 0,
      // bytes
      storage: 0
      // bytes
    };
    return typeof E == "number" || typeof E == "boolean" ? (w.boundary = 4, w.storage = 4) : E.isVector2 ? (w.boundary = 8, w.storage = 8) : E.isVector3 || E.isColor ? (w.boundary = 16, w.storage = 12) : E.isVector4 ? (w.boundary = 16, w.storage = 16) : E.isMatrix3 ? (w.boundary = 48, w.storage = 48) : E.isMatrix4 ? (w.boundary = 64, w.storage = 64) : E.isTexture ? de("WebGLRenderer: Texture samplers can not be part of an uniforms group.") : de("WebGLRenderer: Unsupported uniform value type.", E), w;
  }
  function b(E) {
    const w = E.target;
    w.removeEventListener("dispose", b);
    const M = c.indexOf(w.__bindingPointIndex);
    c.splice(M, 1), n.deleteBuffer(a[w.id]), delete a[w.id], delete o[w.id];
  }
  function y() {
    for (const E in a)
      n.deleteBuffer(a[E]);
    c = [], a = {}, o = {};
  }
  return {
    bind: d,
    update: h,
    dispose: y
  };
}
const kO = new Uint16Array([
  12469,
  15057,
  12620,
  14925,
  13266,
  14620,
  13807,
  14376,
  14323,
  13990,
  14545,
  13625,
  14713,
  13328,
  14840,
  12882,
  14931,
  12528,
  14996,
  12233,
  15039,
  11829,
  15066,
  11525,
  15080,
  11295,
  15085,
  10976,
  15082,
  10705,
  15073,
  10495,
  13880,
  14564,
  13898,
  14542,
  13977,
  14430,
  14158,
  14124,
  14393,
  13732,
  14556,
  13410,
  14702,
  12996,
  14814,
  12596,
  14891,
  12291,
  14937,
  11834,
  14957,
  11489,
  14958,
  11194,
  14943,
  10803,
  14921,
  10506,
  14893,
  10278,
  14858,
  9960,
  14484,
  14039,
  14487,
  14025,
  14499,
  13941,
  14524,
  13740,
  14574,
  13468,
  14654,
  13106,
  14743,
  12678,
  14818,
  12344,
  14867,
  11893,
  14889,
  11509,
  14893,
  11180,
  14881,
  10751,
  14852,
  10428,
  14812,
  10128,
  14765,
  9754,
  14712,
  9466,
  14764,
  13480,
  14764,
  13475,
  14766,
  13440,
  14766,
  13347,
  14769,
  13070,
  14786,
  12713,
  14816,
  12387,
  14844,
  11957,
  14860,
  11549,
  14868,
  11215,
  14855,
  10751,
  14825,
  10403,
  14782,
  10044,
  14729,
  9651,
  14666,
  9352,
  14599,
  9029,
  14967,
  12835,
  14966,
  12831,
  14963,
  12804,
  14954,
  12723,
  14936,
  12564,
  14917,
  12347,
  14900,
  11958,
  14886,
  11569,
  14878,
  11247,
  14859,
  10765,
  14828,
  10401,
  14784,
  10011,
  14727,
  9600,
  14660,
  9289,
  14586,
  8893,
  14508,
  8533,
  15111,
  12234,
  15110,
  12234,
  15104,
  12216,
  15092,
  12156,
  15067,
  12010,
  15028,
  11776,
  14981,
  11500,
  14942,
  11205,
  14902,
  10752,
  14861,
  10393,
  14812,
  9991,
  14752,
  9570,
  14682,
  9252,
  14603,
  8808,
  14519,
  8445,
  14431,
  8145,
  15209,
  11449,
  15208,
  11451,
  15202,
  11451,
  15190,
  11438,
  15163,
  11384,
  15117,
  11274,
  15055,
  10979,
  14994,
  10648,
  14932,
  10343,
  14871,
  9936,
  14803,
  9532,
  14729,
  9218,
  14645,
  8742,
  14556,
  8381,
  14461,
  8020,
  14365,
  7603,
  15273,
  10603,
  15272,
  10607,
  15267,
  10619,
  15256,
  10631,
  15231,
  10614,
  15182,
  10535,
  15118,
  10389,
  15042,
  10167,
  14963,
  9787,
  14883,
  9447,
  14800,
  9115,
  14710,
  8665,
  14615,
  8318,
  14514,
  7911,
  14411,
  7507,
  14279,
  7198,
  15314,
  9675,
  15313,
  9683,
  15309,
  9712,
  15298,
  9759,
  15277,
  9797,
  15229,
  9773,
  15166,
  9668,
  15084,
  9487,
  14995,
  9274,
  14898,
  8910,
  14800,
  8539,
  14697,
  8234,
  14590,
  7790,
  14479,
  7409,
  14367,
  7067,
  14178,
  6621,
  15337,
  8619,
  15337,
  8631,
  15333,
  8677,
  15325,
  8769,
  15305,
  8871,
  15264,
  8940,
  15202,
  8909,
  15119,
  8775,
  15022,
  8565,
  14916,
  8328,
  14804,
  8009,
  14688,
  7614,
  14569,
  7287,
  14448,
  6888,
  14321,
  6483,
  14088,
  6171,
  15350,
  7402,
  15350,
  7419,
  15347,
  7480,
  15340,
  7613,
  15322,
  7804,
  15287,
  7973,
  15229,
  8057,
  15148,
  8012,
  15046,
  7846,
  14933,
  7611,
  14810,
  7357,
  14682,
  7069,
  14552,
  6656,
  14421,
  6316,
  14251,
  5948,
  14007,
  5528,
  15356,
  5942,
  15356,
  5977,
  15353,
  6119,
  15348,
  6294,
  15332,
  6551,
  15302,
  6824,
  15249,
  7044,
  15171,
  7122,
  15070,
  7050,
  14949,
  6861,
  14818,
  6611,
  14679,
  6349,
  14538,
  6067,
  14398,
  5651,
  14189,
  5311,
  13935,
  4958,
  15359,
  4123,
  15359,
  4153,
  15356,
  4296,
  15353,
  4646,
  15338,
  5160,
  15311,
  5508,
  15263,
  5829,
  15188,
  6042,
  15088,
  6094,
  14966,
  6001,
  14826,
  5796,
  14678,
  5543,
  14527,
  5287,
  14377,
  4985,
  14133,
  4586,
  13869,
  4257,
  15360,
  1563,
  15360,
  1642,
  15358,
  2076,
  15354,
  2636,
  15341,
  3350,
  15317,
  4019,
  15273,
  4429,
  15203,
  4732,
  15105,
  4911,
  14981,
  4932,
  14836,
  4818,
  14679,
  4621,
  14517,
  4386,
  14359,
  4156,
  14083,
  3795,
  13808,
  3437,
  15360,
  122,
  15360,
  137,
  15358,
  285,
  15355,
  636,
  15344,
  1274,
  15322,
  2177,
  15281,
  2765,
  15215,
  3223,
  15120,
  3451,
  14995,
  3569,
  14846,
  3567,
  14681,
  3466,
  14511,
  3305,
  14344,
  3121,
  14037,
  2800,
  13753,
  2467,
  15360,
  0,
  15360,
  1,
  15359,
  21,
  15355,
  89,
  15346,
  253,
  15325,
  479,
  15287,
  796,
  15225,
  1148,
  15133,
  1492,
  15008,
  1749,
  14856,
  1882,
  14685,
  1886,
  14506,
  1783,
  14324,
  1608,
  13996,
  1398,
  13702,
  1183
]);
let vs = null;
function XO() {
  return vs === null && (vs = new Cd(kO, 16, 16, hl, dr), vs.name = "DFG_LUT", vs.minFilter = Qn, vs.magFilter = Qn, vs.wrapS = or, vs.wrapT = or, vs.generateMipmaps = !1, vs.needsUpdate = !0), vs;
}
class WO {
  /**
   * Constructs a new WebGL renderer.
   *
   * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
   */
  constructor(t = {}) {
    const {
      canvas: e = W2(),
      context: s = null,
      depth: a = !0,
      stencil: o = !1,
      alpha: c = !1,
      antialias: u = !1,
      premultipliedAlpha: d = !0,
      preserveDrawingBuffer: h = !1,
      powerPreference: m = "default",
      failIfMajorPerformanceCaveat: p = !1,
      reversedDepthBuffer: g = !1,
      outputBufferType: _ = Ci
    } = t;
    this.isWebGLRenderer = !0;
    let x;
    if (s !== null) {
      if (typeof WebGLRenderingContext < "u" && s instanceof WebGLRenderingContext)
        throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");
      x = s.getContextAttributes().alpha;
    } else
      x = c;
    const A = _, b = /* @__PURE__ */ new Set([
      j0,
      Y0,
      W0
    ]), y = /* @__PURE__ */ new Set([
      Ci,
      Cs,
      zc,
      Fc,
      G0,
      k0
    ]), E = new Uint32Array(4), w = new Int32Array(4);
    let M = null, O = null;
    const C = [], D = [];
    let T = null;
    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 = ws, this.toneMappingExposure = 1, this.transmissionResolutionScale = 1;
    const L = this;
    let z = !1;
    this._outputColorSpace = Xi;
    let R = 0, B = 0, H = null, U = -1, V = null;
    const N = new Je(), I = new Je();
    let k = null;
    const X = new we(0);
    let Q = 0, F = e.width, W = e.height, et = 1, $ = null, j = null;
    const Y = new Je(0, 0, F, W), K = new Je(0, 0, F, W);
    let J = !1;
    const rt = new J0();
    let dt = !1, yt = !1;
    const Pt = new je(), Lt = new st(), zt = new Je(), Xt = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: !0 };
    let Ft = !1;
    function ve() {
      return H === null ? et : 1;
    }
    let it = s;
    function Ue(Z, ot) {
      return e.getContext(Z, ot);
    }
    try {
      const Z = {
        alpha: !0,
        depth: a,
        stencil: o,
        antialias: u,
        premultipliedAlpha: d,
        preserveDrawingBuffer: h,
        powerPreference: m,
        failIfMajorPerformanceCaveat: p
      };
      if ("setAttribute" in e && e.setAttribute("data-engine", `three.js r${F0}`), e.addEventListener("webglcontextlost", Zt, !1), e.addEventListener("webglcontextrestored", fe, !1), e.addEventListener("webglcontextcreationerror", He, !1), it === null) {
        const ot = "webgl2";
        if (it = Ue(ot, Z), it === null)
          throw Ue(ot) ? new Error("Error creating WebGL context with your selected attributes.") : new Error("Error creating WebGL context.");
      }
    } catch (Z) {
      throw Ie("WebGLRenderer: " + Z.message), Z;
    }
    let xe, Re, Kt, tt, G, ct, Et, Rt, Mt, Jt, It, se, le, Ot, Dt, Wt, kt, Yt, _e, lt, Bt, Ut, jt;
    function Nt() {
      xe = new WD(it), xe.init(), Bt = new PO(it, xe), Re = new BD(it, xe, t, Bt), Kt = new LO(it, xe), Re.reversedDepthBuffer && g && Kt.buffers.depth.setReversed(!0), tt = new qD(it), G = new yO(), ct = new UO(it, xe, Kt, G, Re, Bt, tt), Et = new XD(L), Rt = new J3(it), Ut = new PD(it, Rt), Mt = new YD(it, Rt, tt, Ut), Jt = new $D(it, Mt, Rt, Ut, tt), Yt = new ZD(it, Re, ct), Dt = new zD(G), It = new _O(L, Et, xe, Re, Ut, Dt), se = new VO(L, G), le = new SO(), Ot = new TO(xe), kt = new UD(L, Et, Kt, Jt, x, d), Wt = new OO(L, Jt, Re), jt = new GO(it, tt, Re, Kt), _e = new ID(it, xe, tt), lt = new jD(it, xe, tt), tt.programs = It.programs, L.capabilities = Re, L.extensions = xe, L.properties = G, L.renderLists = le, L.shadowMap = Wt, L.state = Kt, L.info = tt;
    }
    Nt(), A !== Ci && (T = new QD(A, e.width, e.height, a, o));
    const bt = new FO(L, it);
    this.xr = bt, this.getContext = function() {
      return it;
    }, this.getContextAttributes = function() {
      return it.getContextAttributes();
    }, this.forceContextLoss = function() {
      const Z = xe.get("WEBGL_lose_context");
      Z && Z.loseContext();
    }, this.forceContextRestore = function() {
      const Z = xe.get("WEBGL_lose_context");
      Z && Z.restoreContext();
    }, this.getPixelRatio = function() {
      return et;
    }, this.setPixelRatio = function(Z) {
      Z !== void 0 && (et = Z, this.setSize(F, W, !1));
    }, this.getSize = function(Z) {
      return Z.set(F, W);
    }, this.setSize = function(Z, ot, xt = !0) {
      if (bt.isPresenting) {
        de("WebGLRenderer: Can't change size while VR device is presenting.");
        return;
      }
      F = Z, W = ot, e.width = Math.floor(Z * et), e.height = Math.floor(ot * et), xt === !0 && (e.style.width = Z + "px", e.style.height = ot + "px"), T !== null && T.setSize(e.width, e.height), this.setViewport(0, 0, Z, ot);
    }, this.getDrawingBufferSize = function(Z) {
      return Z.set(F * et, W * et).floor();
    }, this.setDrawingBufferSize = function(Z, ot, xt) {
      F = Z, W = ot, et = xt, e.width = Math.floor(Z * xt), e.height = Math.floor(ot * xt), this.setViewport(0, 0, Z, ot);
    }, this.setEffects = function(Z) {
      if (A === Ci) {
        console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");
        return;
      }
      if (Z) {
        for (let ot = 0; ot < Z.length; ot++)
          if (Z[ot].isOutputPass === !0) {
            console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");
            break;
          }
      }
      T.setEffects(Z || []);
    }, this.getCurrentViewport = function(Z) {
      return Z.copy(N);
    }, this.getViewport = function(Z) {
      return Z.copy(Y);
    }, this.setViewport = function(Z, ot, xt, mt) {
      Z.isVector4 ? Y.set(Z.x, Z.y, Z.z, Z.w) : Y.set(Z, ot, xt, mt), Kt.viewport(N.copy(Y).multiplyScalar(et).round());
    }, this.getScissor = function(Z) {
      return Z.copy(K);
    }, this.setScissor = function(Z, ot, xt, mt) {
      Z.isVector4 ? K.set(Z.x, Z.y, Z.z, Z.w) : K.set(Z, ot, xt, mt), Kt.scissor(I.copy(K).multiplyScalar(et).round());
    }, this.getScissorTest = function() {
      return J;
    }, this.setScissorTest = function(Z) {
      Kt.setScissorTest(J = Z);
    }, this.setOpaqueSort = function(Z) {
      $ = Z;
    }, this.setTransparentSort = function(Z) {
      j = Z;
    }, this.getClearColor = function(Z) {
      return Z.copy(kt.getClearColor());
    }, this.setClearColor = function() {
      kt.setClearColor(...arguments);
    }, this.getClearAlpha = function() {
      return kt.getClearAlpha();
    }, this.setClearAlpha = function() {
      kt.setClearAlpha(...arguments);
    }, this.clear = function(Z = !0, ot = !0, xt = !0) {
      let mt = 0;
      if (Z) {
        let ft = !1;
        if (H !== null) {
          const Ht = H.texture.format;
          ft = b.has(Ht);
        }
        if (ft) {
          const Ht = H.texture.type, qt = y.has(Ht), Vt = kt.getClearColor(), te = kt.getClearAlpha(), ne = Vt.r, ue = Vt.g, pe = Vt.b;
          qt ? (E[0] = ne, E[1] = ue, E[2] = pe, E[3] = te, it.clearBufferuiv(it.COLOR, 0, E)) : (w[0] = ne, w[1] = ue, w[2] = pe, w[3] = te, it.clearBufferiv(it.COLOR, 0, w));
        } else
          mt |= it.COLOR_BUFFER_BIT;
      }
      ot && (mt |= it.DEPTH_BUFFER_BIT), xt && (mt |= it.STENCIL_BUFFER_BIT, this.state.buffers.stencil.setMask(4294967295)), mt !== 0 && it.clear(mt);
    }, 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", Zt, !1), e.removeEventListener("webglcontextrestored", fe, !1), e.removeEventListener("webglcontextcreationerror", He, !1), kt.dispose(), le.dispose(), Ot.dispose(), G.dispose(), Et.dispose(), Jt.dispose(), Ut.dispose(), jt.dispose(), It.dispose(), bt.dispose(), bt.removeEventListener("sessionstart", _r), bt.removeEventListener("sessionend", yr), Li.stop();
    };
    function Zt(Z) {
      Z.preventDefault(), Ad("WebGLRenderer: Context Lost."), z = !0;
    }
    function fe() {
      Ad("WebGLRenderer: Context Restored."), z = !1;
      const Z = tt.autoReset, ot = Wt.enabled, xt = Wt.autoUpdate, mt = Wt.needsUpdate, ft = Wt.type;
      Nt(), tt.autoReset = Z, Wt.enabled = ot, Wt.autoUpdate = xt, Wt.needsUpdate = mt, Wt.type = ft;
    }
    function He(Z) {
      Ie("WebGLRenderer: A WebGL context could not be created. Reason: ", Z.statusMessage);
    }
    function Oe(Z) {
      const ot = Z.target;
      ot.removeEventListener("dispose", Oe), Fn(ot);
    }
    function Fn(Z) {
      mi(Z), G.remove(Z);
    }
    function mi(Z) {
      const ot = G.get(Z).programs;
      ot !== void 0 && (ot.forEach(function(xt) {
        It.releaseProgram(xt);
      }), Z.isShaderMaterial && It.releaseShaderCache(Z));
    }
    this.renderBufferDirect = function(Z, ot, xt, mt, ft, Ht) {
      ot === null && (ot = Xt);
      const qt = ft.isMesh && ft.matrixWorld.determinant() < 0, Vt = Qa(Z, ot, xt, mt, ft);
      Kt.setMaterial(mt, qt);
      let te = xt.index, ne = 1;
      if (mt.wireframe === !0) {
        if (te = Mt.getWireframeAttribute(xt), te === void 0) return;
        ne = 2;
      }
      const ue = xt.drawRange, pe = xt.attributes.position;
      let $t = ue.start * ne, ye = (ue.start + ue.count) * ne;
      Ht !== null && ($t = Math.max($t, Ht.start * ne), ye = Math.min(ye, (Ht.start + Ht.count) * ne)), te !== null ? ($t = Math.max($t, 0), ye = Math.min(ye, te.count)) : pe != null && ($t = Math.max($t, 0), ye = Math.min(ye, pe.count));
      const en = ye - $t;
      if (en < 0 || en === 1 / 0) return;
      Ut.setup(ft, mt, Vt, xt, te);
      let nn, Ae = _e;
      if (te !== null && (nn = Rt.get(te), Ae = lt, Ae.setIndex(nn)), ft.isMesh)
        mt.wireframe === !0 ? (Kt.setLineWidth(mt.wireframeLinewidth * ve()), Ae.setMode(it.LINES)) : Ae.setMode(it.TRIANGLES);
      else if (ft.isLine) {
        let pn = mt.linewidth;
        pn === void 0 && (pn = 1), Kt.setLineWidth(pn * ve()), ft.isLineSegments ? Ae.setMode(it.LINES) : ft.isLineLoop ? Ae.setMode(it.LINE_LOOP) : Ae.setMode(it.LINE_STRIP);
      } else ft.isPoints ? Ae.setMode(it.POINTS) : ft.isSprite && Ae.setMode(it.TRIANGLES);
      if (ft.isBatchedMesh)
        if (ft._multiDrawInstances !== null)
          Td("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."), Ae.renderMultiDrawInstances(ft._multiDrawStarts, ft._multiDrawCounts, ft._multiDrawCount, ft._multiDrawInstances);
        else if (xe.get("WEBGL_multi_draw"))
          Ae.renderMultiDraw(ft._multiDrawStarts, ft._multiDrawCounts, ft._multiDrawCount);
        else {
          const pn = ft._multiDrawStarts, Qt = ft._multiDrawCounts, Hn = ft._multiDrawCount, he = te ? Rt.get(te).bytesPerElement : 1, Dn = G.get(mt).currentProgram.getUniforms();
          for (let ti = 0; ti < Hn; ti++)
            Dn.setValue(it, "_gl_DrawID", ti), Ae.render(pn[ti] / he, Qt[ti]);
        }
      else if (ft.isInstancedMesh)
        Ae.renderInstances($t, en, ft.count);
      else if (xt.isInstancedBufferGeometry) {
        const pn = xt._maxInstanceCount !== void 0 ? xt._maxInstanceCount : 1 / 0, Qt = Math.min(xt.instanceCount, pn);
        Ae.renderInstances($t, en, Qt);
      } else
        Ae.render($t, en);
    };
    function oa(Z, ot, xt) {
      Z.transparent === !0 && Z.side === Ss && Z.forceSinglePass === !1 ? (Z.side = pi, Z.needsUpdate = !0, Yi(Z, ot, xt), Z.side = ra, Z.needsUpdate = !0, Yi(Z, ot, xt), Z.side = Ss) : Yi(Z, ot, xt);
    }
    this.compile = function(Z, ot, xt = null) {
      xt === null && (xt = Z), O = Ot.get(xt), O.init(ot), D.push(O), xt.traverseVisible(function(ft) {
        ft.isLight && ft.layers.test(ot.layers) && (O.pushLight(ft), ft.castShadow && O.pushShadow(ft));
      }), Z !== xt && Z.traverseVisible(function(ft) {
        ft.isLight && ft.layers.test(ot.layers) && (O.pushLight(ft), ft.castShadow && O.pushShadow(ft));
      }), O.setupLights();
      const mt = /* @__PURE__ */ new Set();
      return Z.traverse(function(ft) {
        if (!(ft.isMesh || ft.isPoints || ft.isLine || ft.isSprite))
          return;
        const Ht = ft.material;
        if (Ht)
          if (Array.isArray(Ht))
            for (let qt = 0; qt < Ht.length; qt++) {
              const Vt = Ht[qt];
              oa(Vt, xt, ft), mt.add(Vt);
            }
          else
            oa(Ht, xt, ft), mt.add(Ht);
      }), O = D.pop(), mt;
    }, this.compileAsync = function(Z, ot, xt = null) {
      const mt = this.compile(Z, ot, xt);
      return new Promise((ft) => {
        function Ht() {
          if (mt.forEach(function(qt) {
            G.get(qt).currentProgram.isReady() && mt.delete(qt);
          }), mt.size === 0) {
            ft(Z);
            return;
          }
          setTimeout(Ht, 10);
        }
        xe.get("KHR_parallel_shader_compile") !== null ? Ht() : setTimeout(Ht, 10);
      });
    };
    let vr = null;
    function $a(Z) {
      vr && vr(Z);
    }
    function _r() {
      Li.stop();
    }
    function yr() {
      Li.start();
    }
    const Li = new FM();
    Li.setAnimationLoop($a), typeof self < "u" && Li.setContext(self), this.setAnimationLoop = function(Z) {
      vr = Z, bt.setAnimationLoop(Z), Z === null ? Li.stop() : Li.start();
    }, bt.addEventListener("sessionstart", _r), bt.addEventListener("sessionend", yr), this.render = function(Z, ot) {
      if (ot !== void 0 && ot.isCamera !== !0) {
        Ie("WebGLRenderer.render: camera is not an instance of THREE.Camera.");
        return;
      }
      if (z === !0) return;
      const xt = bt.enabled === !0 && bt.isPresenting === !0, mt = T !== null && (H === null || xt) && T.begin(L, H);
      if (Z.matrixWorldAutoUpdate === !0 && Z.updateMatrixWorld(), ot.parent === null && ot.matrixWorldAutoUpdate === !0 && ot.updateMatrixWorld(), bt.enabled === !0 && bt.isPresenting === !0 && (T === null || T.isCompositing() === !1) && (bt.cameraAutoUpdate === !0 && bt.updateCamera(ot), ot = bt.getCamera()), Z.isScene === !0 && Z.onBeforeRender(L, Z, ot, H), O = Ot.get(Z, D.length), O.init(ot), D.push(O), Pt.multiplyMatrices(ot.projectionMatrix, ot.matrixWorldInverse), rt.setFromProjectionMatrix(Pt, Ms, ot.reversedDepth), yt = this.localClippingEnabled, dt = Dt.init(this.clippingPlanes, yt), M = le.get(Z, C.length), M.init(), C.push(M), bt.enabled === !0 && bt.isPresenting === !0) {
        const qt = L.xr.getDepthSensingMesh();
        qt !== null && xr(qt, ot, -1 / 0, L.sortObjects);
      }
      xr(Z, ot, 0, L.sortObjects), M.finish(), L.sortObjects === !0 && M.sort($, j), Ft = bt.enabled === !1 || bt.isPresenting === !1 || bt.hasDepthSensing() === !1, Ft && kt.addToRenderList(M, Z), this.info.render.frame++, dt === !0 && Dt.beginShadows();
      const ft = O.state.shadowsArray;
      if (Wt.render(ft, Z, ot), dt === !0 && Dt.endShadows(), this.info.autoReset === !0 && this.info.reset(), (mt && T.hasRenderPass()) === !1) {
        const qt = M.opaque, Vt = M.transmissive;
        if (O.setupLights(), ot.isArrayCamera) {
          const te = ot.cameras;
          if (Vt.length > 0)
            for (let ne = 0, ue = te.length; ne < ue; ne++) {
              const pe = te[ne];
              cn(qt, Vt, Z, pe);
            }
          Ft && kt.render(Z);
          for (let ne = 0, ue = te.length; ne < ue; ne++) {
            const pe = te[ne];
            gi(M, Z, pe, pe.viewport);
          }
        } else
          Vt.length > 0 && cn(qt, Vt, Z, ot), Ft && kt.render(Z), gi(M, Z, ot);
      }
      H !== null && B === 0 && (ct.updateMultisampleRenderTarget(H), ct.updateRenderTargetMipmap(H)), mt && T.end(L), Z.isScene === !0 && Z.onAfterRender(L, Z, ot), Ut.resetDefaultState(), U = -1, V = null, D.pop(), D.length > 0 ? (O = D[D.length - 1], dt === !0 && Dt.setGlobalState(L.clippingPlanes, O.state.camera)) : O = null, C.pop(), C.length > 0 ? M = C[C.length - 1] : M = null;
    };
    function xr(Z, ot, xt, mt) {
      if (Z.visible === !1) return;
      if (Z.layers.test(ot.layers)) {
        if (Z.isGroup)
          xt = Z.renderOrder;
        else if (Z.isLOD)
          Z.autoUpdate === !0 && Z.update(ot);
        else if (Z.isLight)
          O.pushLight(Z), Z.castShadow && O.pushShadow(Z);
        else if (Z.isSprite) {
          if (!Z.frustumCulled || rt.intersectsSprite(Z)) {
            mt && zt.setFromMatrixPosition(Z.matrixWorld).applyMatrix4(Pt);
            const qt = Jt.update(Z), Vt = Z.material;
            Vt.visible && M.push(Z, qt, Vt, xt, zt.z, null);
          }
        } else if ((Z.isMesh || Z.isLine || Z.isPoints) && (!Z.frustumCulled || rt.intersectsObject(Z))) {
          const qt = Jt.update(Z), Vt = Z.material;
          if (mt && (Z.boundingSphere !== void 0 ? (Z.boundingSphere === null && Z.computeBoundingSphere(), zt.copy(Z.boundingSphere.center)) : (qt.boundingSphere === null && qt.computeBoundingSphere(), zt.copy(qt.boundingSphere.center)), zt.applyMatrix4(Z.matrixWorld).applyMatrix4(Pt)), Array.isArray(Vt)) {
            const te = qt.groups;
            for (let ne = 0, ue = te.length; ne < ue; ne++) {
              const pe = te[ne], $t = Vt[pe.materialIndex];
              $t && $t.visible && M.push(Z, qt, $t, xt, zt.z, pe);
            }
          } else Vt.visible && M.push(Z, qt, Vt, xt, zt.z, null);
        }
      }
      const Ht = Z.children;
      for (let qt = 0, Vt = Ht.length; qt < Vt; qt++)
        xr(Ht[qt], ot, xt, mt);
    }
    function gi(Z, ot, xt, mt) {
      const { opaque: ft, transmissive: Ht, transparent: qt } = Z;
      O.setupLightsView(xt), dt === !0 && Dt.setGlobalState(L.clippingPlanes, xt), mt && Kt.viewport(N.copy(mt)), ft.length > 0 && hn(ft, ot, xt), Ht.length > 0 && hn(Ht, ot, xt), qt.length > 0 && hn(qt, ot, xt), Kt.buffers.depth.setTest(!0), Kt.buffers.depth.setMask(!0), Kt.buffers.color.setMask(!0), Kt.setPolygonOffset(!1);
    }
    function cn(Z, ot, xt, mt) {
      if ((xt.isScene === !0 ? xt.overrideMaterial : null) !== null)
        return;
      if (O.state.transmissionRenderTarget[mt.id] === void 0) {
        const $t = xe.has("EXT_color_buffer_half_float") || xe.has("EXT_color_buffer_float");
        O.state.transmissionRenderTarget[mt.id] = new As(1, 1, {
          generateMipmaps: !0,
          type: $t ? dr : Ci,
          minFilter: Ia,
          samples: Math.max(4, Re.samples),
          // to avoid feedback loops, the transmission render target requires a resolve, see #26177
          stencilBuffer: o,
          resolveDepthBuffer: !1,
          resolveStencilBuffer: !1,
          colorSpace: Be.workingColorSpace
        });
      }
      const Ht = O.state.transmissionRenderTarget[mt.id], qt = mt.viewport || N;
      Ht.setSize(qt.z * L.transmissionResolutionScale, qt.w * L.transmissionResolutionScale);
      const Vt = L.getRenderTarget(), te = L.getActiveCubeFace(), ne = L.getActiveMipmapLevel();
      L.setRenderTarget(Ht), L.getClearColor(X), Q = L.getClearAlpha(), Q < 1 && L.setClearColor(16777215, 0.5), L.clear(), Ft && kt.render(xt);
      const ue = L.toneMapping;
      L.toneMapping = ws;
      const pe = mt.viewport;
      if (mt.viewport !== void 0 && (mt.viewport = void 0), O.setupLightsView(mt), dt === !0 && Dt.setGlobalState(L.clippingPlanes, mt), hn(Z, xt, mt), ct.updateMultisampleRenderTarget(Ht), ct.updateRenderTargetMipmap(Ht), xe.has("WEBGL_multisampled_render_to_texture") === !1) {
        let $t = !1;
        for (let ye = 0, en = ot.length; ye < en; ye++) {
          const nn = ot[ye], { object: Ae, geometry: pn, material: Qt, group: Hn } = nn;
          if (Qt.side === Ss && Ae.layers.test(mt.layers)) {
            const he = Qt.side;
            Qt.side = pi, Qt.needsUpdate = !0, Ui(Ae, xt, mt, pn, Qt, Hn), Qt.side = he, Qt.needsUpdate = !0, $t = !0;
          }
        }
        $t === !0 && (ct.updateMultisampleRenderTarget(Ht), ct.updateRenderTargetMipmap(Ht));
      }
      L.setRenderTarget(Vt, te, ne), L.setClearColor(X, Q), pe !== void 0 && (mt.viewport = pe), L.toneMapping = ue;
    }
    function hn(Z, ot, xt) {
      const mt = ot.isScene === !0 ? ot.overrideMaterial : null;
      for (let ft = 0, Ht = Z.length; ft < Ht; ft++) {
        const qt = Z[ft], { object: Vt, geometry: te, group: ne } = qt;
        let ue = qt.material;
        ue.allowOverride === !0 && mt !== null && (ue = mt), Vt.layers.test(xt.layers) && Ui(Vt, ot, xt, te, ue, ne);
      }
    }
    function Ui(Z, ot, xt, mt, ft, Ht) {
      Z.onBeforeRender(L, ot, xt, mt, ft, Ht), Z.modelViewMatrix.multiplyMatrices(xt.matrixWorldInverse, Z.matrixWorld), Z.normalMatrix.getNormalMatrix(Z.modelViewMatrix), ft.onBeforeRender(L, ot, xt, mt, Z, Ht), ft.transparent === !0 && ft.side === Ss && ft.forceSinglePass === !1 ? (ft.side = pi, ft.needsUpdate = !0, L.renderBufferDirect(xt, ot, mt, ft, Z, Ht), ft.side = ra, ft.needsUpdate = !0, L.renderBufferDirect(xt, ot, mt, ft, Z, Ht), ft.side = Ss) : L.renderBufferDirect(xt, ot, mt, ft, Z, Ht), Z.onAfterRender(L, ot, xt, mt, ft, Ht);
    }
    function Yi(Z, ot, xt) {
      ot.isScene !== !0 && (ot = Xt);
      const mt = G.get(Z), ft = O.state.lights, Ht = O.state.shadowsArray, qt = ft.state.version, Vt = It.getParameters(Z, ft.state, Ht, ot, xt), te = It.getProgramCacheKey(Vt);
      let ne = mt.programs;
      mt.environment = Z.isMeshStandardMaterial || Z.isMeshLambertMaterial || Z.isMeshPhongMaterial ? ot.environment : null, mt.fog = ot.fog;
      const ue = Z.isMeshStandardMaterial || Z.isMeshLambertMaterial && !Z.envMap || Z.isMeshPhongMaterial && !Z.envMap;
      mt.envMap = Et.get(Z.envMap || mt.environment, ue), mt.envMapRotation = mt.environment !== null && Z.envMap === null ? ot.environmentRotation : Z.envMapRotation, ne === void 0 && (Z.addEventListener("dispose", Oe), ne = /* @__PURE__ */ new Map(), mt.programs = ne);
      let pe = ne.get(te);
      if (pe !== void 0) {
        if (mt.currentProgram === pe && mt.lightsStateVersion === qt)
          return Ka(Z, Vt), pe;
      } else
        Vt.uniforms = It.getUniforms(Z), Z.onBeforeCompile(Vt, L), pe = It.acquireProgram(Vt, te), ne.set(te, pe), mt.uniforms = Vt.uniforms;
      const $t = mt.uniforms;
      return (!Z.isShaderMaterial && !Z.isRawShaderMaterial || Z.clipping === !0) && ($t.clippingPlanes = Dt.uniform), Ka(Z, Vt), mt.needsLights = ca(Z), mt.lightsStateVersion = qt, mt.needsLights && ($t.ambientLightColor.value = ft.state.ambient, $t.lightProbe.value = ft.state.probe, $t.directionalLights.value = ft.state.directional, $t.directionalLightShadows.value = ft.state.directionalShadow, $t.spotLights.value = ft.state.spot, $t.spotLightShadows.value = ft.state.spotShadow, $t.rectAreaLights.value = ft.state.rectArea, $t.ltc_1.value = ft.state.rectAreaLTC1, $t.ltc_2.value = ft.state.rectAreaLTC2, $t.pointLights.value = ft.state.point, $t.pointLightShadows.value = ft.state.pointShadow, $t.hemisphereLights.value = ft.state.hemi, $t.directionalShadowMatrix.value = ft.state.directionalShadowMatrix, $t.spotLightMatrix.value = ft.state.spotLightMatrix, $t.spotLightMap.value = ft.state.spotLightMap, $t.pointShadowMatrix.value = ft.state.pointShadowMatrix), mt.currentProgram = pe, mt.uniformsList = null, pe;
    }
    function la(Z) {
      if (Z.uniformsList === null) {
        const ot = Z.currentProgram.getUniforms();
        Z.uniformsList = gd.seqWithValue(ot.seq, Z.uniforms);
      }
      return Z.uniformsList;
    }
    function Ka(Z, ot) {
      const xt = G.get(Z);
      xt.outputColorSpace = ot.outputColorSpace, xt.batching = ot.batching, xt.batchingColor = ot.batchingColor, xt.instancing = ot.instancing, xt.instancingColor = ot.instancingColor, xt.instancingMorph = ot.instancingMorph, xt.skinning = ot.skinning, xt.morphTargets = ot.morphTargets, xt.morphNormals = ot.morphNormals, xt.morphColors = ot.morphColors, xt.morphTargetsCount = ot.morphTargetsCount, xt.numClippingPlanes = ot.numClippingPlanes, xt.numIntersection = ot.numClipIntersection, xt.vertexAlphas = ot.vertexAlphas, xt.vertexTangents = ot.vertexTangents, xt.toneMapping = ot.toneMapping;
    }
    function Qa(Z, ot, xt, mt, ft) {
      ot.isScene !== !0 && (ot = Xt), ct.resetTextureUnits();
      const Ht = ot.fog, qt = mt.isMeshStandardMaterial || mt.isMeshLambertMaterial || mt.isMeshPhongMaterial ? ot.environment : null, Vt = H === null ? L.outputColorSpace : H.isXRRenderTarget === !0 ? H.texture.colorSpace : pl, te = mt.isMeshStandardMaterial || mt.isMeshLambertMaterial && !mt.envMap || mt.isMeshPhongMaterial && !mt.envMap, ne = Et.get(mt.envMap || qt, te), ue = mt.vertexColors === !0 && !!xt.attributes.color && xt.attributes.color.itemSize === 4, pe = !!xt.attributes.tangent && (!!mt.normalMap || mt.anisotropy > 0), $t = !!xt.morphAttributes.position, ye = !!xt.morphAttributes.normal, en = !!xt.morphAttributes.color;
      let nn = ws;
      mt.toneMapped && (H === null || H.isXRRenderTarget === !0) && (nn = L.toneMapping);
      const Ae = xt.morphAttributes.position || xt.morphAttributes.normal || xt.morphAttributes.color, pn = Ae !== void 0 ? Ae.length : 0, Qt = G.get(mt), Hn = O.state.lights;
      if (dt === !0 && (yt === !0 || Z !== V)) {
        const xn = Z === V && mt.id === U;
        Dt.setState(mt, Z, xn);
      }
      let he = !1;
      mt.version === Qt.__version ? (Qt.needsLights && Qt.lightsStateVersion !== Hn.state.version || Qt.outputColorSpace !== Vt || ft.isBatchedMesh && Qt.batching === !1 || !ft.isBatchedMesh && Qt.batching === !0 || ft.isBatchedMesh && Qt.batchingColor === !0 && ft.colorTexture === null || ft.isBatchedMesh && Qt.batchingColor === !1 && ft.colorTexture !== null || ft.isInstancedMesh && Qt.instancing === !1 || !ft.isInstancedMesh && Qt.instancing === !0 || ft.isSkinnedMesh && Qt.skinning === !1 || !ft.isSkinnedMesh && Qt.skinning === !0 || ft.isInstancedMesh && Qt.instancingColor === !0 && ft.instanceColor === null || ft.isInstancedMesh && Qt.instancingColor === !1 && ft.instanceColor !== null || ft.isInstancedMesh && Qt.instancingMorph === !0 && ft.morphTexture === null || ft.isInstancedMesh && Qt.instancingMorph === !1 && ft.morphTexture !== null || Qt.envMap !== ne || mt.fog === !0 && Qt.fog !== Ht || Qt.numClippingPlanes !== void 0 && (Qt.numClippingPlanes !== Dt.numPlanes || Qt.numIntersection !== Dt.numIntersection) || Qt.vertexAlphas !== ue || Qt.vertexTangents !== pe || Qt.morphTargets !== $t || Qt.morphNormals !== ye || Qt.morphColors !== en || Qt.toneMapping !== nn || Qt.morphTargetsCount !== pn) && (he = !0) : (he = !0, Qt.__version = mt.version);
      let Dn = Qt.currentProgram;
      he === !0 && (Dn = Yi(mt, ot, ft));
      let ti = !1, vi = !1, qn = !1;
      const Ge = Dn.getUniforms(), yn = Qt.uniforms;
      if (Kt.useProgram(Dn.program) && (ti = !0, vi = !0, qn = !0), mt.id !== U && (U = mt.id, vi = !0), ti || V !== Z) {
        Kt.buffers.depth.getReversed() && Z.reversedDepth !== !0 && (Z._reversedDepth = !0, Z.updateProjectionMatrix()), Ge.setValue(it, "projectionMatrix", Z.projectionMatrix), Ge.setValue(it, "viewMatrix", Z.matrixWorldInverse);
        const ji = Ge.map.cameraPosition;
        ji !== void 0 && ji.setValue(it, Lt.setFromMatrixPosition(Z.matrixWorld)), Re.logarithmicDepthBuffer && Ge.setValue(
          it,
          "logDepthBufFC",
          2 / (Math.log(Z.far + 1) / Math.LN2)
        ), (mt.isMeshPhongMaterial || mt.isMeshToonMaterial || mt.isMeshLambertMaterial || mt.isMeshBasicMaterial || mt.isMeshStandardMaterial || mt.isShaderMaterial) && Ge.setValue(it, "isOrthographic", Z.isOrthographicCamera === !0), V !== Z && (V = Z, vi = !0, qn = !0);
      }
      if (Qt.needsLights && (Hn.state.directionalShadowMap.length > 0 && Ge.setValue(it, "directionalShadowMap", Hn.state.directionalShadowMap, ct), Hn.state.spotShadowMap.length > 0 && Ge.setValue(it, "spotShadowMap", Hn.state.spotShadowMap, ct), Hn.state.pointShadowMap.length > 0 && Ge.setValue(it, "pointShadowMap", Hn.state.pointShadowMap, ct)), ft.isSkinnedMesh) {
        Ge.setOptional(it, ft, "bindMatrix"), Ge.setOptional(it, ft, "bindMatrixInverse");
        const xn = ft.skeleton;
        xn && (xn.boneTexture === null && xn.computeBoneTexture(), Ge.setValue(it, "boneTexture", xn.boneTexture, ct));
      }
      ft.isBatchedMesh && (Ge.setOptional(it, ft, "batchingTexture"), Ge.setValue(it, "batchingTexture", ft._matricesTexture, ct), Ge.setOptional(it, ft, "batchingIdTexture"), Ge.setValue(it, "batchingIdTexture", ft._indirectTexture, ct), Ge.setOptional(it, ft, "batchingColorTexture"), ft._colorsTexture !== null && Ge.setValue(it, "batchingColorTexture", ft._colorsTexture, ct));
      const ei = xt.morphAttributes;
      if ((ei.position !== void 0 || ei.normal !== void 0 || ei.color !== void 0) && Yt.update(ft, xt, Dn), (vi || Qt.receiveShadow !== ft.receiveShadow) && (Qt.receiveShadow = ft.receiveShadow, Ge.setValue(it, "receiveShadow", ft.receiveShadow)), (mt.isMeshStandardMaterial || mt.isMeshLambertMaterial || mt.isMeshPhongMaterial) && mt.envMap === null && ot.environment !== null && (yn.envMapIntensity.value = ot.environmentIntensity), yn.dfgLUT !== void 0 && (yn.dfgLUT.value = XO()), vi && (Ge.setValue(it, "toneMappingExposure", L.toneMappingExposure), Qt.needsLights && Ls(yn, qn), Ht && mt.fog === !0 && se.refreshFogUniforms(yn, Ht), se.refreshMaterialUniforms(yn, mt, et, W, O.state.transmissionRenderTarget[Z.id]), gd.upload(it, la(Qt), yn, ct)), mt.isShaderMaterial && mt.uniformsNeedUpdate === !0 && (gd.upload(it, la(Qt), yn, ct), mt.uniformsNeedUpdate = !1), mt.isSpriteMaterial && Ge.setValue(it, "center", ft.center), Ge.setValue(it, "modelViewMatrix", ft.modelViewMatrix), Ge.setValue(it, "normalMatrix", ft.normalMatrix), Ge.setValue(it, "modelMatrix", ft.matrixWorld), mt.isShaderMaterial || mt.isRawShaderMaterial) {
        const xn = mt.uniformsGroups;
        for (let ji = 0, Us = xn.length; ji < Us; ji++) {
          const Ja = xn[ji];
          jt.update(Ja, Dn), jt.bind(Ja, Dn);
        }
      }
      return Dn;
    }
    function Ls(Z, ot) {
      Z.ambientLightColor.needsUpdate = ot, Z.lightProbe.needsUpdate = ot, Z.directionalLights.needsUpdate = ot, Z.directionalLightShadows.needsUpdate = ot, Z.pointLights.needsUpdate = ot, Z.pointLightShadows.needsUpdate = ot, Z.spotLights.needsUpdate = ot, Z.spotLightShadows.needsUpdate = ot, Z.rectAreaLights.needsUpdate = ot, Z.hemisphereLights.needsUpdate = ot;
    }
    function ca(Z) {
      return Z.isMeshLambertMaterial || Z.isMeshToonMaterial || Z.isMeshPhongMaterial || Z.isMeshStandardMaterial || Z.isShadowMaterial || Z.isShaderMaterial && Z.lights === !0;
    }
    this.getActiveCubeFace = function() {
      return R;
    }, this.getActiveMipmapLevel = function() {
      return B;
    }, this.getRenderTarget = function() {
      return H;
    }, this.setRenderTargetTextures = function(Z, ot, xt) {
      const mt = G.get(Z);
      mt.__autoAllocateDepthBuffer = Z.resolveDepthBuffer === !1, mt.__autoAllocateDepthBuffer === !1 && (mt.__useRenderToTexture = !1), G.get(Z.texture).__webglTexture = ot, G.get(Z.depthTexture).__webglTexture = mt.__autoAllocateDepthBuffer ? void 0 : xt, mt.__hasExternalTextures = !0;
    }, this.setRenderTargetFramebuffer = function(Z, ot) {
      const xt = G.get(Z);
      xt.__webglFramebuffer = ot, xt.__useDefaultFramebuffer = ot === void 0;
    };
    const cs = it.createFramebuffer();
    this.setRenderTarget = function(Z, ot = 0, xt = 0) {
      H = Z, R = ot, B = xt;
      let mt = null, ft = !1, Ht = !1;
      if (Z) {
        const Vt = G.get(Z);
        if (Vt.__useDefaultFramebuffer !== void 0) {
          Kt.bindFramebuffer(it.FRAMEBUFFER, Vt.__webglFramebuffer), N.copy(Z.viewport), I.copy(Z.scissor), k = Z.scissorTest, Kt.viewport(N), Kt.scissor(I), Kt.setScissorTest(k), U = -1;
          return;
        } else if (Vt.__webglFramebuffer === void 0)
          ct.setupRenderTarget(Z);
        else if (Vt.__hasExternalTextures)
          ct.rebindTextures(Z, G.get(Z.texture).__webglTexture, G.get(Z.depthTexture).__webglTexture);
        else if (Z.depthBuffer) {
          const ue = Z.depthTexture;
          if (Vt.__boundDepthTexture !== ue) {
            if (ue !== null && G.has(ue) && (Z.width !== ue.image.width || Z.height !== ue.image.height))
              throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");
            ct.setupDepthRenderbuffer(Z);
          }
        }
        const te = Z.texture;
        (te.isData3DTexture || te.isDataArrayTexture || te.isCompressedArrayTexture) && (Ht = !0);
        const ne = G.get(Z).__webglFramebuffer;
        Z.isWebGLCubeRenderTarget ? (Array.isArray(ne[ot]) ? mt = ne[ot][xt] : mt = ne[ot], ft = !0) : Z.samples > 0 && ct.useMultisampledRTT(Z) === !1 ? mt = G.get(Z).__webglMultisampledFramebuffer : Array.isArray(ne) ? mt = ne[xt] : mt = ne, N.copy(Z.viewport), I.copy(Z.scissor), k = Z.scissorTest;
      } else
        N.copy(Y).multiplyScalar(et).floor(), I.copy(K).multiplyScalar(et).floor(), k = J;
      if (xt !== 0 && (mt = cs), Kt.bindFramebuffer(it.FRAMEBUFFER, mt) && Kt.drawBuffers(Z, mt), Kt.viewport(N), Kt.scissor(I), Kt.setScissorTest(k), ft) {
        const Vt = G.get(Z.texture);
        it.framebufferTexture2D(it.FRAMEBUFFER, it.COLOR_ATTACHMENT0, it.TEXTURE_CUBE_MAP_POSITIVE_X + ot, Vt.__webglTexture, xt);
      } else if (Ht) {
        const Vt = ot;
        for (let te = 0; te < Z.textures.length; te++) {
          const ne = G.get(Z.textures[te]);
          it.framebufferTextureLayer(it.FRAMEBUFFER, it.COLOR_ATTACHMENT0 + te, ne.__webglTexture, xt, Vt);
        }
      } else if (Z !== null && xt !== 0) {
        const Vt = G.get(Z.texture);
        it.framebufferTexture2D(it.FRAMEBUFFER, it.COLOR_ATTACHMENT0, it.TEXTURE_2D, Vt.__webglTexture, xt);
      }
      U = -1;
    }, this.readRenderTargetPixels = function(Z, ot, xt, mt, ft, Ht, qt, Vt = 0) {
      if (!(Z && Z.isWebGLRenderTarget)) {
        Ie("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
        return;
      }
      let te = G.get(Z).__webglFramebuffer;
      if (Z.isWebGLCubeRenderTarget && qt !== void 0 && (te = te[qt]), te) {
        Kt.bindFramebuffer(it.FRAMEBUFFER, te);
        try {
          const ne = Z.textures[Vt], ue = ne.format, pe = ne.type;
          if (Z.textures.length > 1 && it.readBuffer(it.COLOR_ATTACHMENT0 + Vt), !Re.textureFormatReadable(ue)) {
            Ie("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");
            return;
          }
          if (!Re.textureTypeReadable(pe)) {
            Ie("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");
            return;
          }
          ot >= 0 && ot <= Z.width - mt && xt >= 0 && xt <= Z.height - ft && it.readPixels(ot, xt, mt, ft, Bt.convert(ue), Bt.convert(pe), Ht);
        } finally {
          const ne = H !== null ? G.get(H).__webglFramebuffer : null;
          Kt.bindFramebuffer(it.FRAMEBUFFER, ne);
        }
      }
    }, this.readRenderTargetPixelsAsync = async function(Z, ot, xt, mt, ft, Ht, qt, Vt = 0) {
      if (!(Z && Z.isWebGLRenderTarget))
        throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
      let te = G.get(Z).__webglFramebuffer;
      if (Z.isWebGLCubeRenderTarget && qt !== void 0 && (te = te[qt]), te)
        if (ot >= 0 && ot <= Z.width - mt && xt >= 0 && xt <= Z.height - ft) {
          Kt.bindFramebuffer(it.FRAMEBUFFER, te);
          const ne = Z.textures[Vt], ue = ne.format, pe = ne.type;
          if (Z.textures.length > 1 && it.readBuffer(it.COLOR_ATTACHMENT0 + Vt), !Re.textureFormatReadable(ue))
            throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");
          if (!Re.textureTypeReadable(pe))
            throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");
          const $t = it.createBuffer();
          it.bindBuffer(it.PIXEL_PACK_BUFFER, $t), it.bufferData(it.PIXEL_PACK_BUFFER, Ht.byteLength, it.STREAM_READ), it.readPixels(ot, xt, mt, ft, Bt.convert(ue), Bt.convert(pe), 0);
          const ye = H !== null ? G.get(H).__webglFramebuffer : null;
          Kt.bindFramebuffer(it.FRAMEBUFFER, ye);
          const en = it.fenceSync(it.SYNC_GPU_COMMANDS_COMPLETE, 0);
          return it.flush(), await Y2(it, en, 4), it.bindBuffer(it.PIXEL_PACK_BUFFER, $t), it.getBufferSubData(it.PIXEL_PACK_BUFFER, 0, Ht), it.deleteBuffer($t), it.deleteSync(en), Ht;
        } else
          throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.");
    }, this.copyFramebufferToTexture = function(Z, ot = null, xt = 0) {
      const mt = Math.pow(2, -xt), ft = Math.floor(Z.image.width * mt), Ht = Math.floor(Z.image.height * mt), qt = ot !== null ? ot.x : 0, Vt = ot !== null ? ot.y : 0;
      ct.setTexture2D(Z, 0), it.copyTexSubImage2D(it.TEXTURE_2D, xt, 0, 0, qt, Vt, ft, Ht), Kt.unbindTexture();
    };
    const us = it.createFramebuffer(), fs = it.createFramebuffer();
    this.copyTextureToTexture = function(Z, ot, xt = null, mt = null, ft = 0, Ht = 0) {
      let qt, Vt, te, ne, ue, pe, $t, ye, en;
      const nn = Z.isCompressedTexture ? Z.mipmaps[Ht] : Z.image;
      if (xt !== null)
        qt = xt.max.x - xt.min.x, Vt = xt.max.y - xt.min.y, te = xt.isBox3 ? xt.max.z - xt.min.z : 1, ne = xt.min.x, ue = xt.min.y, pe = xt.isBox3 ? xt.min.z : 0;
      else {
        const yn = Math.pow(2, -ft);
        qt = Math.floor(nn.width * yn), Vt = Math.floor(nn.height * yn), Z.isDataArrayTexture ? te = nn.depth : Z.isData3DTexture ? te = Math.floor(nn.depth * yn) : te = 1, ne = 0, ue = 0, pe = 0;
      }
      mt !== null ? ($t = mt.x, ye = mt.y, en = mt.z) : ($t = 0, ye = 0, en = 0);
      const Ae = Bt.convert(ot.format), pn = Bt.convert(ot.type);
      let Qt;
      ot.isData3DTexture ? (ct.setTexture3D(ot, 0), Qt = it.TEXTURE_3D) : ot.isDataArrayTexture || ot.isCompressedArrayTexture ? (ct.setTexture2DArray(ot, 0), Qt = it.TEXTURE_2D_ARRAY) : (ct.setTexture2D(ot, 0), Qt = it.TEXTURE_2D), it.pixelStorei(it.UNPACK_FLIP_Y_WEBGL, ot.flipY), it.pixelStorei(it.UNPACK_PREMULTIPLY_ALPHA_WEBGL, ot.premultiplyAlpha), it.pixelStorei(it.UNPACK_ALIGNMENT, ot.unpackAlignment);
      const Hn = it.getParameter(it.UNPACK_ROW_LENGTH), he = it.getParameter(it.UNPACK_IMAGE_HEIGHT), Dn = it.getParameter(it.UNPACK_SKIP_PIXELS), ti = it.getParameter(it.UNPACK_SKIP_ROWS), vi = it.getParameter(it.UNPACK_SKIP_IMAGES);
      it.pixelStorei(it.UNPACK_ROW_LENGTH, nn.width), it.pixelStorei(it.UNPACK_IMAGE_HEIGHT, nn.height), it.pixelStorei(it.UNPACK_SKIP_PIXELS, ne), it.pixelStorei(it.UNPACK_SKIP_ROWS, ue), it.pixelStorei(it.UNPACK_SKIP_IMAGES, pe);
      const qn = Z.isDataArrayTexture || Z.isData3DTexture, Ge = ot.isDataArrayTexture || ot.isData3DTexture;
      if (Z.isDepthTexture) {
        const yn = G.get(Z), ei = G.get(ot), xn = G.get(yn.__renderTarget), ji = G.get(ei.__renderTarget);
        Kt.bindFramebuffer(it.READ_FRAMEBUFFER, xn.__webglFramebuffer), Kt.bindFramebuffer(it.DRAW_FRAMEBUFFER, ji.__webglFramebuffer);
        for (let Us = 0; Us < te; Us++)
          qn && (it.framebufferTextureLayer(it.READ_FRAMEBUFFER, it.COLOR_ATTACHMENT0, G.get(Z).__webglTexture, ft, pe + Us), it.framebufferTextureLayer(it.DRAW_FRAMEBUFFER, it.COLOR_ATTACHMENT0, G.get(ot).__webglTexture, Ht, en + Us)), it.blitFramebuffer(ne, ue, qt, Vt, $t, ye, qt, Vt, it.DEPTH_BUFFER_BIT, it.NEAREST);
        Kt.bindFramebuffer(it.READ_FRAMEBUFFER, null), Kt.bindFramebuffer(it.DRAW_FRAMEBUFFER, null);
      } else if (ft !== 0 || Z.isRenderTargetTexture || G.has(Z)) {
        const yn = G.get(Z), ei = G.get(ot);
        Kt.bindFramebuffer(it.READ_FRAMEBUFFER, us), Kt.bindFramebuffer(it.DRAW_FRAMEBUFFER, fs);
        for (let xn = 0; xn < te; xn++)
          qn ? it.framebufferTextureLayer(it.READ_FRAMEBUFFER, it.COLOR_ATTACHMENT0, yn.__webglTexture, ft, pe + xn) : it.framebufferTexture2D(it.READ_FRAMEBUFFER, it.COLOR_ATTACHMENT0, it.TEXTURE_2D, yn.__webglTexture, ft), Ge ? it.framebufferTextureLayer(it.DRAW_FRAMEBUFFER, it.COLOR_ATTACHMENT0, ei.__webglTexture, Ht, en + xn) : it.framebufferTexture2D(it.DRAW_FRAMEBUFFER, it.COLOR_ATTACHMENT0, it.TEXTURE_2D, ei.__webglTexture, Ht), ft !== 0 ? it.blitFramebuffer(ne, ue, qt, Vt, $t, ye, qt, Vt, it.COLOR_BUFFER_BIT, it.NEAREST) : Ge ? it.copyTexSubImage3D(Qt, Ht, $t, ye, en + xn, ne, ue, qt, Vt) : it.copyTexSubImage2D(Qt, Ht, $t, ye, ne, ue, qt, Vt);
        Kt.bindFramebuffer(it.READ_FRAMEBUFFER, null), Kt.bindFramebuffer(it.DRAW_FRAMEBUFFER, null);
      } else
        Ge ? Z.isDataTexture || Z.isData3DTexture ? it.texSubImage3D(Qt, Ht, $t, ye, en, qt, Vt, te, Ae, pn, nn.data) : ot.isCompressedArrayTexture ? it.compressedTexSubImage3D(Qt, Ht, $t, ye, en, qt, Vt, te, Ae, nn.data) : it.texSubImage3D(Qt, Ht, $t, ye, en, qt, Vt, te, Ae, pn, nn) : Z.isDataTexture ? it.texSubImage2D(it.TEXTURE_2D, Ht, $t, ye, qt, Vt, Ae, pn, nn.data) : Z.isCompressedTexture ? it.compressedTexSubImage2D(it.TEXTURE_2D, Ht, $t, ye, nn.width, nn.height, Ae, nn.data) : it.texSubImage2D(it.TEXTURE_2D, Ht, $t, ye, qt, Vt, Ae, pn, nn);
      it.pixelStorei(it.UNPACK_ROW_LENGTH, Hn), it.pixelStorei(it.UNPACK_IMAGE_HEIGHT, he), it.pixelStorei(it.UNPACK_SKIP_PIXELS, Dn), it.pixelStorei(it.UNPACK_SKIP_ROWS, ti), it.pixelStorei(it.UNPACK_SKIP_IMAGES, vi), Ht === 0 && ot.generateMipmaps && it.generateMipmap(Qt), Kt.unbindTexture();
    }, this.initRenderTarget = function(Z) {
      G.get(Z).__webglFramebuffer === void 0 && ct.setupRenderTarget(Z);
    }, this.initTexture = function(Z) {
      Z.isCubeTexture ? ct.setTextureCube(Z, 0) : Z.isData3DTexture ? ct.setTexture3D(Z, 0) : Z.isDataArrayTexture || Z.isCompressedArrayTexture ? ct.setTexture2DArray(Z, 0) : ct.setTexture2D(Z, 0), Kt.unbindTexture();
    }, this.resetState = function() {
      R = 0, B = 0, H = null, Kt.reset(), Ut.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 Ms;
  }
  /**
   * 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 = Be._getDrawingBufferColorSpace(t), e.unpackColorSpace = Be._getUnpackColorSpace();
  }
}
const Mb = { type: "change" }, rv = { type: "start" }, WM = { type: "end" }, Zf = new Q0(), Eb = new Jr(), YO = Math.cos(70 * AM.DEG2RAD), On = new st(), fi = 2 * Math.PI, Qe = {
  NONE: -1,
  ROTATE: 0,
  DOLLY: 1,
  PAN: 2,
  TOUCH_ROTATE: 3,
  TOUCH_PAN: 4,
  TOUCH_DOLLY_PAN: 5,
  TOUCH_DOLLY_ROTATE: 6
}, ig = 1e-6;
class wb extends K3 {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLElement} domElement - The HTML element used for event listeners.
   */
  constructor(t, e = null) {
    super(t, e), this.state = Qe.NONE, this.target = new st(), this.cursor = new st(), this.minDistance = 0, this.maxDistance = 1 / 0, this.minZoom = 0, this.maxZoom = 1 / 0, this.minTargetRadius = 0, this.maxTargetRadius = 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.keyRotateSpeed = 1, this.enablePan = !0, this.panSpeed = 1, this.screenSpacePanning = !0, this.keyPanSpeed = 7, this.zoomToCursor = !1, this.autoRotate = !1, this.autoRotateSpeed = 2, this.keys = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" }, this.mouseButtons = { LEFT: al.ROTATE, MIDDLE: al.DOLLY, RIGHT: al.PAN }, this.touches = { ONE: il.ROTATE, TWO: il.DOLLY_PAN }, this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.zoom0 = this.object.zoom, this._cursorStyle = "auto", this._domElementKeyEvents = null, this._lastPosition = new st(), this._lastQuaternion = new pr(), this._lastTargetPosition = new st(), this._quat = new pr().setFromUnitVectors(t.up, new st(0, 1, 0)), this._quatInverse = this._quat.clone().invert(), this._spherical = new $S(), this._sphericalDelta = new $S(), this._scale = 1, this._panOffset = new st(), this._rotateStart = new ae(), this._rotateEnd = new ae(), this._rotateDelta = new ae(), this._panStart = new ae(), this._panEnd = new ae(), this._panDelta = new ae(), this._dollyStart = new ae(), this._dollyEnd = new ae(), this._dollyDelta = new ae(), this._dollyDirection = new st(), this._mouse = new ae(), this._performCursorZoom = !1, this._pointers = [], this._pointerPositions = {}, this._controlActive = !1, this._onPointerMove = qO.bind(this), this._onPointerDown = jO.bind(this), this._onPointerUp = ZO.bind(this), this._onContextMenu = nL.bind(this), this._onMouseWheel = QO.bind(this), this._onKeyDown = JO.bind(this), this._onTouchStart = tL.bind(this), this._onTouchMove = eL.bind(this), this._onMouseDown = $O.bind(this), this._onMouseMove = KO.bind(this), this._interceptControlDown = iL.bind(this), this._interceptControlUp = sL.bind(this), this.domElement !== null && this.connect(this.domElement), this.update();
  }
  /**
   * Defines the visual representation of the cursor.
   *
   * @type {('auto'|'grab')}
   * @default 'auto'
   */
  set cursorStyle(t) {
    this._cursorStyle = t, t === "grab" ? this.domElement.style.cursor = "grab" : this.domElement.style.cursor = "auto";
  }
  get cursorStyle() {
    return this._cursorStyle;
  }
  connect(t) {
    super.connect(t), this.domElement.addEventListener("pointerdown", this._onPointerDown), this.domElement.addEventListener("pointercancel", this._onPointerUp), this.domElement.addEventListener("contextmenu", this._onContextMenu), this.domElement.addEventListener("wheel", this._onMouseWheel, { passive: !1 }), this.domElement.getRootNode().addEventListener("keydown", this._interceptControlDown, { passive: !0, capture: !0 }), this.domElement.style.touchAction = "none";
  }
  disconnect() {
    this.domElement.removeEventListener("pointerdown", this._onPointerDown), this.domElement.ownerDocument.removeEventListener("pointermove", this._onPointerMove), this.domElement.ownerDocument.removeEventListener("pointerup", this._onPointerUp), this.domElement.removeEventListener("pointercancel", this._onPointerUp), this.domElement.removeEventListener("wheel", this._onMouseWheel), this.domElement.removeEventListener("contextmenu", this._onContextMenu), this.stopListenToKeyEvents(), this.domElement.getRootNode().removeEventListener("keydown", this._interceptControlDown, { capture: !0 }), this.domElement.style.touchAction = "auto";
  }
  dispose() {
    this.disconnect();
  }
  /**
   * Get the current vertical rotation, in radians.
   *
   * @return {number} The current vertical rotation, in radians.
   */
  getPolarAngle() {
    return this._spherical.phi;
  }
  /**
   * Get the current horizontal rotation, in radians.
   *
   * @return {number} The current horizontal rotation, in radians.
   */
  getAzimuthalAngle() {
    return this._spherical.theta;
  }
  /**
   * Returns the distance from the camera to the target.
   *
   * @return {number} The distance from the camera to the target.
   */
  getDistance() {
    return this.object.position.distanceTo(this.target);
  }
  /**
   * Adds key event listeners to the given DOM element.
   * `window` is a recommended argument for using this method.
   *
   * @param {HTMLElement} domElement - The DOM element
   */
  listenToKeyEvents(t) {
    t.addEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = t;
  }
  /**
   * Removes the key event listener previously defined with `listenToKeyEvents()`.
   */
  stopListenToKeyEvents() {
    this._domElementKeyEvents !== null && (this._domElementKeyEvents.removeEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = null);
  }
  /**
   * Save the current state of the controls. This can later be recovered with `reset()`.
   */
  saveState() {
    this.target0.copy(this.target), this.position0.copy(this.object.position), this.zoom0 = this.object.zoom;
  }
  /**
   * Reset the controls to their state from either the last time the `saveState()`
   * was called, or the initial state.
   */
  reset() {
    this.target.copy(this.target0), this.object.position.copy(this.position0), this.object.zoom = this.zoom0, this.object.updateProjectionMatrix(), this.dispatchEvent(Mb), this.update(), this.state = Qe.NONE;
  }
  /**
   * Programmatically pan the camera.
   *
   * @param {number} deltaX - The horizontal pan amount in pixels.
   * @param {number} deltaY - The vertical pan amount in pixels.
   */
  pan(t, e) {
    this._pan(t, e), this.update();
  }
  /**
   * Programmatically dolly in (zoom in for perspective camera).
   *
   * @param {number} dollyScale - The dolly scale factor.
   */
  dollyIn(t) {
    this._dollyIn(t), this.update();
  }
  /**
   * Programmatically dolly out (zoom out for perspective camera).
   *
   * @param {number} dollyScale - The dolly scale factor.
   */
  dollyOut(t) {
    this._dollyOut(t), this.update();
  }
  /**
   * Programmatically rotate the camera left (around the vertical axis).
   *
   * @param {number} angle - The rotation angle in radians.
   */
  rotateLeft(t) {
    this._rotateLeft(t), this.update();
  }
  /**
   * Programmatically rotate the camera up (around the horizontal axis).
   *
   * @param {number} angle - The rotation angle in radians.
   */
  rotateUp(t) {
    this._rotateUp(t), this.update();
  }
  update(t = null) {
    const e = this.object.position;
    On.copy(e).sub(this.target), On.applyQuaternion(this._quat), this._spherical.setFromVector3(On), this.autoRotate && this.state === Qe.NONE && this._rotateLeft(this._getAutoRotationAngle(t)), this.enableDamping ? (this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor, this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor) : (this._spherical.theta += this._sphericalDelta.theta, this._spherical.phi += this._sphericalDelta.phi);
    let s = this.minAzimuthAngle, a = this.maxAzimuthAngle;
    isFinite(s) && isFinite(a) && (s < -Math.PI ? s += fi : s > Math.PI && (s -= fi), a < -Math.PI ? a += fi : a > Math.PI && (a -= fi), s <= a ? this._spherical.theta = Math.max(s, Math.min(a, this._spherical.theta)) : this._spherical.theta = this._spherical.theta > (s + a) / 2 ? Math.max(s, this._spherical.theta) : Math.min(a, this._spherical.theta)), this._spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this._spherical.phi)), this._spherical.makeSafe(), this.enableDamping === !0 ? this.target.addScaledVector(this._panOffset, this.dampingFactor) : this.target.add(this._panOffset), this.target.sub(this.cursor), this.target.clampLength(this.minTargetRadius, this.maxTargetRadius), this.target.add(this.cursor);
    let o = !1;
    if (this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera)
      this._spherical.radius = this._clampDistance(this._spherical.radius);
    else {
      const c = this._spherical.radius;
      this._spherical.radius = this._clampDistance(this._spherical.radius * this._scale), o = c != this._spherical.radius;
    }
    if (On.setFromSpherical(this._spherical), On.applyQuaternion(this._quatInverse), e.copy(this.target).add(On), this.object.lookAt(this.target), this.enableDamping === !0 ? (this._sphericalDelta.theta *= 1 - this.dampingFactor, this._sphericalDelta.phi *= 1 - this.dampingFactor, this._panOffset.multiplyScalar(1 - this.dampingFactor)) : (this._sphericalDelta.set(0, 0, 0), this._panOffset.set(0, 0, 0)), this.zoomToCursor && this._performCursorZoom) {
      let c = null;
      if (this.object.isPerspectiveCamera) {
        const u = On.length();
        c = this._clampDistance(u * this._scale);
        const d = u - c;
        this.object.position.addScaledVector(this._dollyDirection, d), this.object.updateMatrixWorld(), o = !!d;
      } else if (this.object.isOrthographicCamera) {
        const u = new st(this._mouse.x, this._mouse.y, 0);
        u.unproject(this.object);
        const d = this.object.zoom;
        this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), this.object.updateProjectionMatrix(), o = d !== this.object.zoom;
        const h = new st(this._mouse.x, this._mouse.y, 0);
        h.unproject(this.object), this.object.position.sub(h).add(u), this.object.updateMatrixWorld(), c = On.length();
      } else
        console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."), this.zoomToCursor = !1;
      c !== null && (this.screenSpacePanning ? this.target.set(0, 0, -1).transformDirection(this.object.matrix).multiplyScalar(c).add(this.object.position) : (Zf.origin.copy(this.object.position), Zf.direction.set(0, 0, -1).transformDirection(this.object.matrix), Math.abs(this.object.up.dot(Zf.direction)) < YO ? this.object.lookAt(this.target) : (Eb.setFromNormalAndCoplanarPoint(this.object.up, this.target), Zf.intersectPlane(Eb, this.target))));
    } else if (this.object.isOrthographicCamera) {
      const c = this.object.zoom;
      this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), c !== this.object.zoom && (this.object.updateProjectionMatrix(), o = !0);
    }
    return this._scale = 1, this._performCursorZoom = !1, o || this._lastPosition.distanceToSquared(this.object.position) > ig || 8 * (1 - this._lastQuaternion.dot(this.object.quaternion)) > ig || this._lastTargetPosition.distanceToSquared(this.target) > ig ? (this.dispatchEvent(Mb), this._lastPosition.copy(this.object.position), this._lastQuaternion.copy(this.object.quaternion), this._lastTargetPosition.copy(this.target), !0) : !1;
  }
  _getAutoRotationAngle(t) {
    return t !== null ? fi / 60 * this.autoRotateSpeed * t : fi / 60 / 60 * this.autoRotateSpeed;
  }
  _getZoomScale(t) {
    const e = Math.abs(t * 0.01);
    return Math.pow(0.95, this.zoomSpeed * e);
  }
  _rotateLeft(t) {
    this._sphericalDelta.theta -= t;
  }
  _rotateUp(t) {
    this._sphericalDelta.phi -= t;
  }
  _panLeft(t, e) {
    On.setFromMatrixColumn(e, 0), On.multiplyScalar(-t), this._panOffset.add(On);
  }
  _panUp(t, e) {
    this.screenSpacePanning === !0 ? On.setFromMatrixColumn(e, 1) : (On.setFromMatrixColumn(e, 0), On.crossVectors(this.object.up, On)), On.multiplyScalar(t), this._panOffset.add(On);
  }
  // deltaX and deltaY are in pixels; right and down are positive
  _pan(t, e) {
    const s = this.domElement;
    if (this.object.isPerspectiveCamera) {
      const a = this.object.position;
      On.copy(a).sub(this.target);
      let o = On.length();
      o *= Math.tan(this.object.fov / 2 * Math.PI / 180), this._panLeft(2 * t * o / s.clientHeight, this.object.matrix), this._panUp(2 * e * o / s.clientHeight, this.object.matrix);
    } else this.object.isOrthographicCamera ? (this._panLeft(t * (this.object.right - this.object.left) / this.object.zoom / s.clientWidth, this.object.matrix), this._panUp(e * (this.object.top - this.object.bottom) / this.object.zoom / s.clientHeight, this.object.matrix)) : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."), this.enablePan = !1);
  }
  _dollyOut(t) {
    this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale /= t : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1);
  }
  _dollyIn(t) {
    this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale *= t : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1);
  }
  _updateZoomParameters(t, e) {
    if (!this.zoomToCursor)
      return;
    this._performCursorZoom = !0;
    const s = this.domElement.getBoundingClientRect(), a = t - s.left, o = e - s.top, c = s.width, u = s.height;
    this._mouse.x = a / c * 2 - 1, this._mouse.y = -(o / u) * 2 + 1, this._dollyDirection.set(this._mouse.x, this._mouse.y, 1).unproject(this.object).sub(this.object.position).normalize();
  }
  _clampDistance(t) {
    return Math.max(this.minDistance, Math.min(this.maxDistance, t));
  }
  //
  // event callbacks - update the object state
  //
  _handleMouseDownRotate(t) {
    this._rotateStart.set(t.clientX, t.clientY);
  }
  _handleMouseDownDolly(t) {
    this._updateZoomParameters(t.clientX, t.clientX), this._dollyStart.set(t.clientX, t.clientY);
  }
  _handleMouseDownPan(t) {
    this._panStart.set(t.clientX, t.clientY);
  }
  _handleMouseMoveRotate(t) {
    this._rotateEnd.set(t.clientX, t.clientY), this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed);
    const e = this.domElement;
    this._rotateLeft(fi * this._rotateDelta.x / e.clientHeight), this._rotateUp(fi * this._rotateDelta.y / e.clientHeight), this._rotateStart.copy(this._rotateEnd), this.update();
  }
  _handleMouseMoveDolly(t) {
    this._dollyEnd.set(t.clientX, t.clientY), this._dollyDelta.subVectors(this._dollyEnd, this._dollyStart), this._dollyDelta.y > 0 ? this._dollyOut(this._getZoomScale(this._dollyDelta.y)) : this._dollyDelta.y < 0 && this._dollyIn(this._getZoomScale(this._dollyDelta.y)), this._dollyStart.copy(this._dollyEnd), this.update();
  }
  _handleMouseMovePan(t) {
    this._panEnd.set(t.clientX, t.clientY), this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed), this._pan(this._panDelta.x, this._panDelta.y), this._panStart.copy(this._panEnd), this.update();
  }
  _handleMouseWheel(t) {
    this._updateZoomParameters(t.clientX, t.clientY), t.deltaY < 0 ? this._dollyIn(this._getZoomScale(t.deltaY)) : t.deltaY > 0 && this._dollyOut(this._getZoomScale(t.deltaY)), this.update();
  }
  _handleKeyDown(t) {
    let e = !1;
    switch (t.code) {
      case this.keys.UP:
        t.ctrlKey || t.metaKey || t.shiftKey ? this.enableRotate && this._rotateUp(fi * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, this.keyPanSpeed), e = !0;
        break;
      case this.keys.BOTTOM:
        t.ctrlKey || t.metaKey || t.shiftKey ? this.enableRotate && this._rotateUp(-fi * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, -this.keyPanSpeed), e = !0;
        break;
      case this.keys.LEFT:
        t.ctrlKey || t.metaKey || t.shiftKey ? this.enableRotate && this._rotateLeft(fi * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(this.keyPanSpeed, 0), e = !0;
        break;
      case this.keys.RIGHT:
        t.ctrlKey || t.metaKey || t.shiftKey ? this.enableRotate && this._rotateLeft(-fi * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(-this.keyPanSpeed, 0), e = !0;
        break;
    }
    e && (t.preventDefault(), this.update());
  }
  _handleTouchStartRotate(t) {
    if (this._pointers.length === 1)
      this._rotateStart.set(t.pageX, t.pageY);
    else {
      const e = this._getSecondPointerPosition(t), s = 0.5 * (t.pageX + e.x), a = 0.5 * (t.pageY + e.y);
      this._rotateStart.set(s, a);
    }
  }
  _handleTouchStartPan(t) {
    if (this._pointers.length === 1)
      this._panStart.set(t.pageX, t.pageY);
    else {
      const e = this._getSecondPointerPosition(t), s = 0.5 * (t.pageX + e.x), a = 0.5 * (t.pageY + e.y);
      this._panStart.set(s, a);
    }
  }
  _handleTouchStartDolly(t) {
    const e = this._getSecondPointerPosition(t), s = t.pageX - e.x, a = t.pageY - e.y, o = Math.sqrt(s * s + a * a);
    this._dollyStart.set(0, o);
  }
  _handleTouchStartDollyPan(t) {
    this.enableZoom && this._handleTouchStartDolly(t), this.enablePan && this._handleTouchStartPan(t);
  }
  _handleTouchStartDollyRotate(t) {
    this.enableZoom && this._handleTouchStartDolly(t), this.enableRotate && this._handleTouchStartRotate(t);
  }
  _handleTouchMoveRotate(t) {
    if (this._pointers.length == 1)
      this._rotateEnd.set(t.pageX, t.pageY);
    else {
      const s = this._getSecondPointerPosition(t), a = 0.5 * (t.pageX + s.x), o = 0.5 * (t.pageY + s.y);
      this._rotateEnd.set(a, o);
    }
    this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed);
    const e = this.domElement;
    this._rotateLeft(fi * this._rotateDelta.x / e.clientHeight), this._rotateUp(fi * this._rotateDelta.y / e.clientHeight), this._rotateStart.copy(this._rotateEnd);
  }
  _handleTouchMovePan(t) {
    if (this._pointers.length === 1)
      this._panEnd.set(t.pageX, t.pageY);
    else {
      const e = this._getSecondPointerPosition(t), s = 0.5 * (t.pageX + e.x), a = 0.5 * (t.pageY + e.y);
      this._panEnd.set(s, a);
    }
    this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed), this._pan(this._panDelta.x, this._panDelta.y), this._panStart.copy(this._panEnd);
  }
  _handleTouchMoveDolly(t) {
    const e = this._getSecondPointerPosition(t), s = t.pageX - e.x, a = t.pageY - e.y, o = Math.sqrt(s * s + a * a);
    this._dollyEnd.set(0, o), this._dollyDelta.set(0, Math.pow(this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed)), this._dollyOut(this._dollyDelta.y), this._dollyStart.copy(this._dollyEnd);
    const c = (t.pageX + e.x) * 0.5, u = (t.pageY + e.y) * 0.5;
    this._updateZoomParameters(c, u);
  }
  _handleTouchMoveDollyPan(t) {
    this.enableZoom && this._handleTouchMoveDolly(t), this.enablePan && this._handleTouchMovePan(t);
  }
  _handleTouchMoveDollyRotate(t) {
    this.enableZoom && this._handleTouchMoveDolly(t), this.enableRotate && this._handleTouchMoveRotate(t);
  }
  // pointers
  _addPointer(t) {
    this._pointers.push(t.pointerId);
  }
  _removePointer(t) {
    delete this._pointerPositions[t.pointerId];
    for (let e = 0; e < this._pointers.length; e++)
      if (this._pointers[e] == t.pointerId) {
        this._pointers.splice(e, 1);
        return;
      }
  }
  _isTrackingPointer(t) {
    for (let e = 0; e < this._pointers.length; e++)
      if (this._pointers[e] == t.pointerId) return !0;
    return !1;
  }
  _trackPointer(t) {
    let e = this._pointerPositions[t.pointerId];
    e === void 0 && (e = new ae(), this._pointerPositions[t.pointerId] = e), e.set(t.pageX, t.pageY);
  }
  _getSecondPointerPosition(t) {
    const e = t.pointerId === this._pointers[0] ? this._pointers[1] : this._pointers[0];
    return this._pointerPositions[e];
  }
  //
  _customWheelEvent(t) {
    const e = t.deltaMode, s = {
      clientX: t.clientX,
      clientY: t.clientY,
      deltaY: t.deltaY
    };
    switch (e) {
      case 1:
        s.deltaY *= 16;
        break;
      case 2:
        s.deltaY *= 100;
        break;
    }
    return t.ctrlKey && !this._controlActive && (s.deltaY *= 10), s;
  }
}
function jO(n) {
  this.enabled !== !1 && (this._pointers.length === 0 && (this.domElement.setPointerCapture(n.pointerId), this.domElement.ownerDocument.addEventListener("pointermove", this._onPointerMove), this.domElement.ownerDocument.addEventListener("pointerup", this._onPointerUp)), !this._isTrackingPointer(n) && (this._addPointer(n), n.pointerType === "touch" ? this._onTouchStart(n) : this._onMouseDown(n), this._cursorStyle === "grab" && (this.domElement.style.cursor = "grabbing")));
}
function qO(n) {
  this.enabled !== !1 && (n.pointerType === "touch" ? this._onTouchMove(n) : this._onMouseMove(n));
}
function ZO(n) {
  switch (this._removePointer(n), this._pointers.length) {
    case 0:
      this.domElement.releasePointerCapture(n.pointerId), this.domElement.ownerDocument.removeEventListener("pointermove", this._onPointerMove), this.domElement.ownerDocument.removeEventListener("pointerup", this._onPointerUp), this.dispatchEvent(WM), this.state = Qe.NONE, this._cursorStyle === "grab" && (this.domElement.style.cursor = "grab");
      break;
    case 1:
      const t = this._pointers[0], e = this._pointerPositions[t];
      this._onTouchStart({ pointerId: t, pageX: e.x, pageY: e.y });
      break;
  }
}
function $O(n) {
  let t;
  switch (n.button) {
    case 0:
      t = this.mouseButtons.LEFT;
      break;
    case 1:
      t = this.mouseButtons.MIDDLE;
      break;
    case 2:
      t = this.mouseButtons.RIGHT;
      break;
    default:
      t = -1;
  }
  switch (t) {
    case al.DOLLY:
      if (this.enableZoom === !1) return;
      this._handleMouseDownDolly(n), this.state = Qe.DOLLY;
      break;
    case al.ROTATE:
      if (n.ctrlKey || n.metaKey || n.shiftKey) {
        if (this.enablePan === !1) return;
        this._handleMouseDownPan(n), this.state = Qe.PAN;
      } else {
        if (this.enableRotate === !1) return;
        this._handleMouseDownRotate(n), this.state = Qe.ROTATE;
      }
      break;
    case al.PAN:
      if (n.ctrlKey || n.metaKey || n.shiftKey) {
        if (this.enableRotate === !1) return;
        this._handleMouseDownRotate(n), this.state = Qe.ROTATE;
      } else {
        if (this.enablePan === !1) return;
        this._handleMouseDownPan(n), this.state = Qe.PAN;
      }
      break;
    default:
      this.state = Qe.NONE;
  }
  this.state !== Qe.NONE && this.dispatchEvent(rv);
}
function KO(n) {
  switch (this.state) {
    case Qe.ROTATE:
      if (this.enableRotate === !1) return;
      this._handleMouseMoveRotate(n);
      break;
    case Qe.DOLLY:
      if (this.enableZoom === !1) return;
      this._handleMouseMoveDolly(n);
      break;
    case Qe.PAN:
      if (this.enablePan === !1) return;
      this._handleMouseMovePan(n);
      break;
  }
}
function QO(n) {
  this.enabled === !1 || this.enableZoom === !1 || this.state !== Qe.NONE || (n.preventDefault(), this.dispatchEvent(rv), this._handleMouseWheel(this._customWheelEvent(n)), this.dispatchEvent(WM));
}
function JO(n) {
  this.enabled !== !1 && this._handleKeyDown(n);
}
function tL(n) {
  switch (this._trackPointer(n), this._pointers.length) {
    case 1:
      switch (this.touches.ONE) {
        case il.ROTATE:
          if (this.enableRotate === !1) return;
          this._handleTouchStartRotate(n), this.state = Qe.TOUCH_ROTATE;
          break;
        case il.PAN:
          if (this.enablePan === !1) return;
          this._handleTouchStartPan(n), this.state = Qe.TOUCH_PAN;
          break;
        default:
          this.state = Qe.NONE;
      }
      break;
    case 2:
      switch (this.touches.TWO) {
        case il.DOLLY_PAN:
          if (this.enableZoom === !1 && this.enablePan === !1) return;
          this._handleTouchStartDollyPan(n), this.state = Qe.TOUCH_DOLLY_PAN;
          break;
        case il.DOLLY_ROTATE:
          if (this.enableZoom === !1 && this.enableRotate === !1) return;
          this._handleTouchStartDollyRotate(n), this.state = Qe.TOUCH_DOLLY_ROTATE;
          break;
        default:
          this.state = Qe.NONE;
      }
      break;
    default:
      this.state = Qe.NONE;
  }
  this.state !== Qe.NONE && this.dispatchEvent(rv);
}
function eL(n) {
  switch (this._trackPointer(n), this.state) {
    case Qe.TOUCH_ROTATE:
      if (this.enableRotate === !1) return;
      this._handleTouchMoveRotate(n), this.update();
      break;
    case Qe.TOUCH_PAN:
      if (this.enablePan === !1) return;
      this._handleTouchMovePan(n), this.update();
      break;
    case Qe.TOUCH_DOLLY_PAN:
      if (this.enableZoom === !1 && this.enablePan === !1) return;
      this._handleTouchMoveDollyPan(n), this.update();
      break;
    case Qe.TOUCH_DOLLY_ROTATE:
      if (this.enableZoom === !1 && this.enableRotate === !1) return;
      this._handleTouchMoveDollyRotate(n), this.update();
      break;
    default:
      this.state = Qe.NONE;
  }
}
function nL(n) {
  this.enabled !== !1 && n.preventDefault();
}
function iL(n) {
  n.key === "Control" && (this._controlActive = !0, this.domElement.getRootNode().addEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 }));
}
function sL(n) {
  n.key === "Control" && (this._controlActive = !1, this.domElement.getRootNode().removeEventListener("keyup", this._interceptControlUp, { passive: !0, capture: !0 }));
}
const rL = {
  1: [1, 1, 1],
  // H  - white (CPK)
  2: [0.851, 1, 1],
  // He - light cyan (CPK)
  3: [0.527, 0.88, 0.457],
  // Li (VESTA)
  4: [0.371, 0.846, 0.483],
  // Be (VESTA)
  5: [1, 0.71, 0.71],
  // B  - pink (CPK)
  6: [0.565, 0.565, 0.565],
  // C  - gray (CPK)
  7: [0.188, 0.314, 0.973],
  // N  - blue (CPK)
  8: [1, 0.051, 0.051],
  // O  - red (CPK)
  9: [0.565, 0.878, 0.314],
  // F  - green (CPK)
  10: [1, 0.218, 0.71],
  // Ne (VESTA)
  11: [0.671, 0.361, 0.949],
  // Na - purple (CPK)
  12: [0.541, 1, 0],
  // Mg - green (CPK)
  13: [0.749, 0.651, 0.651],
  // Al - gray-pink (CPK)
  14: [0.941, 0.784, 0.627],
  // Si - tan (CPK)
  15: [1, 0.502, 0],
  // P  - orange (CPK)
  16: [1, 1, 0.188],
  // S  - yellow (CPK)
  17: [0.122, 0.941, 0.122],
  // Cl - green (CPK)
  18: [0.502, 0.82, 0.89],
  // Ar - light blue (CPK)
  19: [0.561, 0.251, 0.831],
  // K  - purple (CPK)
  20: [0.239, 1, 0],
  // Ca - green (CPK)
  21: [0.712, 0.389, 0.673],
  // Sc (VESTA)
  22: [0.472, 0.794, 1],
  // Ti (VESTA)
  23: [0.9, 0.1, 0],
  // V  (VESTA)
  24: [0, 0, 0.62],
  // Cr (VESTA)
  25: [0.661, 0.034, 0.62],
  // Mn (VESTA)
  26: [0.878, 0.4, 0.2],
  // Fe - orange (CPK)
  27: [0, 0, 0.687],
  // Co (VESTA)
  28: [0.72, 0.736, 0.743],
  // Ni (VESTA)
  29: [0.784, 0.502, 0.2],
  // Cu - copper (CPK)
  30: [0.49, 0.502, 0.69],
  // Zn - slate (CPK)
  31: [0.623, 0.893, 0.455],
  // Ga (VESTA)
  32: [0.496, 0.435, 0.652],
  // Ge (VESTA)
  33: [0.458, 0.817, 0.342],
  // As (VESTA)
  34: [1, 0.631, 0],
  // Se - orange (CPK)
  35: [0.651, 0.161, 0.161],
  // Br - dark red (CPK)
  36: [0.981, 0.758, 0.954],
  // Kr (VESTA)
  37: [1, 0, 0.6],
  // Rb (VESTA)
  38: [0, 1, 0.153],
  // Sr (VESTA)
  39: [0.403, 0.597, 0.558],
  // Y  (VESTA)
  40: [0, 1, 0],
  // Zr (VESTA)
  41: [0.3, 0.7, 0.465],
  // Nb (VESTA)
  42: [0.706, 0.526, 0.689],
  // Mo (VESTA)
  43: [0.806, 0.687, 0.795],
  // Tc (VESTA)
  44: [0.812, 0.721, 0.681],
  // Ru (VESTA)
  45: [0.807, 0.822, 0.671],
  // Rh (VESTA)
  46: [0.76, 0.768, 0.725],
  // Pd (VESTA)
  47: [0.753, 0.753, 0.753],
  // Ag - silver
  48: [0.951, 0.121, 0.864],
  // Cd (VESTA)
  49: [0.844, 0.504, 0.735],
  // In (VESTA)
  50: [0.608, 0.561, 0.729],
  // Sn (VESTA)
  51: [0.846, 0.515, 0.313],
  // Sb (VESTA)
  52: [0.68, 0.636, 0.32],
  // Te (VESTA)
  53: [0.58, 0, 0.58],
  // I  - purple (CPK)
  54: [0.607, 0.632, 0.973],
  // Xe (VESTA)
  55: [0.059, 0.999, 0.726],
  // Cs (VESTA)
  56: [0.118, 0.94, 0.176],
  // Ba (VESTA)
  57: [0.353, 0.771, 0.287],
  // La (VESTA)
  58: [0.821, 0.991, 0.024],
  // Ce (VESTA)
  59: [0.991, 0.886, 0.023],
  // Pr (VESTA)
  60: [0.987, 0.556, 0.027],
  // Nd (VESTA)
  61: [0, 0, 0.96],
  // Pm (VESTA)
  62: [0.99, 0.024, 0.492],
  // Sm (VESTA)
  63: [0.984, 0.031, 0.836],
  // Eu (VESTA)
  64: [0.753, 0.014, 1],
  // Gd (VESTA)
  65: [0.443, 0.017, 0.998],
  // Tb (VESTA)
  66: [0.194, 0.024, 0.991],
  // Dy (VESTA)
  67: [0.028, 0.259, 0.986],
  // Ho (VESTA)
  68: [0.287, 0.451, 0.23],
  // Er (VESTA)
  69: [0, 0, 0.88],
  // Tm (VESTA)
  70: [0.153, 0.992, 0.958],
  // Yb (VESTA)
  71: [0.151, 0.994, 0.71],
  // Lu (VESTA)
  72: [0.707, 0.706, 0.351],
  // Hf (VESTA)
  73: [0.72, 0.607, 0.338],
  // Ta (VESTA)
  74: [0.556, 0.543, 0.502],
  // W  (VESTA)
  75: [0.703, 0.694, 0.558],
  // Re (VESTA)
  76: [0.787, 0.695, 0.474],
  // Os (VESTA)
  77: [0.79, 0.81, 0.45],
  // Ir (VESTA)
  78: [0.8, 0.775, 0.751],
  // Pt (VESTA)
  79: [0.996, 0.701, 0.221],
  // Au (VESTA)
  80: [0.829, 0.721, 0.798],
  // Hg (VESTA)
  81: [0.588, 0.539, 0.426],
  // Tl (VESTA)
  82: [0.324, 0.326, 0.357],
  // Pb (VESTA)
  83: [0.824, 0.187, 0.972],
  // Bi (VESTA)
  84: [0, 0, 1],
  // Po (VESTA)
  85: [0.3, 0.2, 0.8],
  // At (adjusted from VESTA to avoid Po duplicate)
  86: [1, 1, 0],
  // Rn (VESTA)
  87: [0, 0, 0],
  // Fr (VESTA)
  88: [0.43, 0.667, 0.348],
  // Ra (VESTA)
  89: [0.393, 0.621, 0.45],
  // Ac (VESTA)
  90: [0.149, 0.996, 0.471],
  // Th (VESTA)
  91: [0.161, 0.984, 0.209],
  // Pa (VESTA)
  92: [0.478, 0.634, 0.667]
  // U  (VESTA)
}, aL = [0.75, 0.4, 0.75], x0 = {
  1: 1.2,
  2: 1.4,
  3: 1.4,
  4: 1.4,
  5: 1.4,
  6: 1.7,
  7: 1.55,
  8: 1.52,
  9: 1.47,
  10: 1.54,
  11: 1.54,
  12: 1.54,
  13: 1.54,
  14: 2.1,
  15: 1.8,
  16: 1.8,
  17: 1.75,
  18: 1.88,
  19: 1.88,
  20: 1.88,
  21: 1.88,
  22: 1.88,
  23: 1.88,
  24: 1.88,
  25: 1.88,
  26: 1.88,
  27: 1.88,
  28: 1.88,
  29: 1.88,
  30: 1.88,
  31: 1.88,
  32: 1.88,
  33: 1.85,
  34: 1.9,
  35: 1.85,
  36: 2.02,
  37: 2.02,
  38: 2.02,
  39: 2.02,
  40: 2.02,
  41: 2.02,
  42: 2.02,
  43: 2.02,
  44: 2.02,
  45: 2.02,
  46: 2.02,
  47: 2.02,
  48: 2.02,
  49: 2.02,
  50: 2.02,
  51: 2,
  52: 2.06,
  53: 1.98,
  54: 2.16,
  55: 2.16,
  56: 2.16,
  57: 2.16,
  58: 2.16,
  59: 2.16,
  60: 2.16,
  61: 2.16,
  62: 2.16,
  63: 2.16,
  64: 2.16,
  65: 2.16,
  66: 2.16,
  67: 2.16,
  68: 2.16,
  69: 2.16,
  70: 2.16,
  71: 2.16,
  72: 2.16,
  73: 2.16,
  74: 2.16,
  75: 2.16,
  76: 2.16,
  77: 2.16,
  78: 2.16,
  79: 2.16,
  80: 2.16,
  81: 2.16,
  82: 2.16,
  83: 2.16,
  84: 2.16,
  85: 2.16,
  86: 2.16,
  87: 2.16,
  88: 2.16,
  89: 2.16,
  90: 2.16,
  91: 2.16,
  92: 2.16
}, S0 = 1.5, av = 0.3, oL = 0.15, Ab = 1, Tb = 2, Cb = 3, Rb = 4, Db = 0.18, lL = 0.1, Nb = 0.2, cL = 0.08, uL = 0.1, fL = 0.06, dL = {
  1: "H",
  2: "He",
  3: "Li",
  4: "Be",
  5: "B",
  6: "C",
  7: "N",
  8: "O",
  9: "F",
  10: "Ne",
  11: "Na",
  12: "Mg",
  13: "Al",
  14: "Si",
  15: "P",
  16: "S",
  17: "Cl",
  18: "Ar",
  19: "K",
  20: "Ca",
  21: "Sc",
  22: "Ti",
  23: "V",
  24: "Cr",
  25: "Mn",
  26: "Fe",
  27: "Co",
  28: "Ni",
  29: "Cu",
  30: "Zn",
  31: "Ga",
  32: "Ge",
  33: "As",
  34: "Se",
  35: "Br",
  36: "Kr",
  37: "Rb",
  38: "Sr",
  39: "Y",
  40: "Zr",
  41: "Nb",
  42: "Mo",
  43: "Tc",
  44: "Ru",
  45: "Rh",
  46: "Pd",
  47: "Ag",
  48: "Cd",
  49: "In",
  50: "Sn",
  51: "Sb",
  52: "Te",
  53: "I",
  54: "Xe",
  55: "Cs",
  56: "Ba",
  57: "La",
  58: "Ce",
  59: "Pr",
  60: "Nd",
  61: "Pm",
  62: "Sm",
  63: "Eu",
  64: "Gd",
  65: "Tb",
  66: "Dy",
  67: "Ho",
  68: "Er",
  69: "Tm",
  70: "Yb",
  71: "Lu",
  72: "Hf",
  73: "Ta",
  74: "W",
  75: "Re",
  76: "Os",
  77: "Ir",
  78: "Pt",
  79: "Au",
  80: "Hg",
  81: "Tl",
  82: "Pb",
  83: "Bi",
  84: "Po",
  85: "At",
  86: "Rn",
  87: "Fr",
  88: "Ra",
  89: "Ac",
  90: "Th",
  91: "Pa",
  92: "U"
};
function Xc(n) {
  return rL[n] ?? aL;
}
function ov(n) {
  return x0[n] ?? S0;
}
const hL = {
  1: 1.008,
  2: 4.003,
  3: 6.941,
  4: 9.012,
  5: 10.81,
  6: 12.011,
  7: 14.007,
  8: 15.999,
  9: 18.998,
  10: 20.18,
  11: 22.99,
  12: 24.305,
  13: 26.982,
  14: 28.086,
  15: 30.974,
  16: 32.06,
  17: 35.45,
  18: 39.948,
  19: 39.098,
  20: 40.078,
  21: 44.956,
  22: 47.867,
  23: 50.942,
  24: 51.996,
  25: 54.938,
  26: 55.845,
  27: 58.933,
  28: 58.693,
  29: 63.546,
  30: 65.38,
  31: 69.723,
  32: 72.63,
  33: 74.922,
  34: 78.96,
  35: 79.904,
  36: 83.798,
  37: 85.468,
  38: 87.62,
  39: 88.906,
  40: 91.224,
  41: 92.906,
  42: 95.95,
  43: 98,
  44: 101.07,
  45: 102.906,
  46: 106.42,
  47: 107.868,
  48: 112.411,
  49: 114.818,
  50: 118.71,
  51: 121.76,
  52: 127.6,
  53: 126.904,
  54: 131.293,
  55: 132.905,
  56: 137.327,
  57: 138.905,
  58: 140.116,
  59: 140.908,
  60: 144.242,
  61: 145,
  62: 150.36,
  63: 151.964,
  64: 157.25,
  65: 158.925,
  66: 162.5,
  67: 164.93,
  68: 167.259,
  69: 168.934,
  70: 173.045,
  71: 174.967,
  72: 178.49,
  73: 180.948,
  74: 183.84,
  75: 186.207,
  76: 190.23,
  77: 192.217,
  78: 195.084,
  79: 196.967,
  80: 200.592,
  81: 204.38,
  82: 207.2,
  83: 208.98,
  84: 209,
  85: 210,
  86: 222,
  87: 223,
  88: 226,
  89: 227,
  90: 232.038,
  91: 231.036,
  92: 238.029
};
function Wc(n) {
  return dL[n] ?? `#${n}`;
}
function pL(n) {
  return hL[n] ?? 0;
}
const mL = (
  /* glsl */
  `precision highp float;
  precision highp int;

  // Three.js built-in uniforms (must declare explicitly for RawShaderMaterial)
  uniform mat4 modelViewMatrix;
  uniform mat4 projectionMatrix;
  uniform float uScaleMultiplier;
  uniform int uUsePerAtomOverrides;

  // Per-vertex (quad corners)
  in vec3 position;

  // Per-instance
  in vec3 instanceCenter;
  in float instanceRadius;
  in vec3 instanceColor;
  in float instanceScaleOverride;
  in float instanceOpacityOverride;

  out vec3 vColor;
  out vec2 vUv;
  out float vRadius;
  out vec3 vViewCenter;
  out float vOpacityOverride;

  void main() {
    vColor = instanceColor;
    vUv = position.xy;
    vOpacityOverride = instanceOpacityOverride;
    float effectiveScale = uScaleMultiplier;
    if (uUsePerAtomOverrides == 1) {
      effectiveScale *= instanceScaleOverride;
    }
    float scaledRadius = instanceRadius * effectiveScale;
    vRadius = scaledRadius;

    vec4 viewCenter = modelViewMatrix * vec4(instanceCenter, 1.0);
    vViewCenter = viewCenter.xyz;

    vec3 viewPos = viewCenter.xyz;
    viewPos.xy += position.xy * scaledRadius;

    gl_Position = projectionMatrix * vec4(viewPos, 1.0);
  }
`
), gL = (
  /* glsl */
  `precision highp float;
  precision highp int;

  in vec3 vColor;
  in vec2 vUv;
  in float vRadius;
  in vec3 vViewCenter;
  in float vOpacityOverride;

  uniform mat4 projectionMatrix;
  uniform float uOpacity;
  uniform int uUsePerAtomOverrides;

  out vec4 fragColor;

  void main() {
    float dist2 = dot(vUv, vUv);
    if (dist2 > 1.0) discard;

    float z = sqrt(1.0 - dist2);
    vec3 normal = vec3(vUv, z);

    // Correct depth
    vec3 fragViewPos = vViewCenter + normal * vRadius;
    vec4 clipPos = projectionMatrix * vec4(fragViewPos, 1.0);
    float ndcDepth = clipPos.z / clipPos.w;
    gl_FragDepth = ndcDepth * 0.5 + 0.5;

    // Hemisphere ambient: sky blue on top, warm brown on bottom
    vec3 skyColor = vec3(0.87, 0.92, 1.0);
    vec3 groundColor = vec3(0.6, 0.47, 0.27);
    float hemiMix = normal.y * 0.5 + 0.5;
    vec3 ambient = mix(groundColor, skyColor, hemiMix) * 0.35;

    // Dual-light diffuse
    vec3 lightDir1 = normalize(vec3(0.5, 0.5, 1.0));
    vec3 lightDir2 = normalize(vec3(-0.3, 0.3, 0.8));
    float diffuse1 = max(dot(normal, lightDir1), 0.0);
    float diffuse2 = max(dot(normal, lightDir2), 0.0);
    float diffuse = diffuse1 * 0.55 + diffuse2 * 0.2;

    // Specular (Blinn-Phong)
    vec3 viewDir = vec3(0.0, 0.0, 1.0);
    vec3 halfDir = normalize(lightDir1 + viewDir);
    float spec = pow(max(dot(normal, halfDir), 0.0), 64.0);

    // Fresnel rim
    float fresnel = pow(1.0 - z, 3.0) * 0.15;

    // Edge darkening
    float edgeFactor = mix(0.7, 1.0, z);

    vec3 color = vColor * (ambient + diffuse) * edgeFactor
               + vec3(1.0) * spec * 0.3
               + vec3(0.15) * fresnel;
    float finalOpacity = uOpacity;
    if (uUsePerAtomOverrides == 1) {
      finalOpacity *= vOpacityOverride;
    }
    fragColor = vec4(color, finalOpacity);
  }
`
), vL = (
  /* glsl */
  `precision highp float;

  uniform mat4 modelViewMatrix;
  uniform mat4 projectionMatrix;
  uniform float uBondScaleMultiplier;
  uniform sampler2D uPositionTex;
  uniform int uPositionTexWidth;

  in vec3 position;
  in vec2 uv;

  in float instanceAtomA;
  in float instanceAtomB;
  in float instanceOffsetX;
  in float instanceOffsetY;
  in vec3 instanceColor;
  in float instanceRadius;
  in float instanceDashed;
  in float instanceBondOpacity;

  out vec3 vColor;
  out vec2 vCylUv;
  out float vDashed;
  out float vBondOpacity;

  vec3 getAtomPos(int idx) {
    int tx = idx % uPositionTexWidth;
    int ty = idx / uPositionTexWidth;
    return texelFetch(uPositionTex, ivec2(tx, ty), 0).rgb;
  }

  void main() {
    vColor = instanceColor;
    vCylUv = uv;
    vDashed = instanceDashed;
    vBondOpacity = instanceBondOpacity;

    int atomA = int(instanceAtomA + 0.5);
    int atomB = int(instanceAtomB + 0.5);
    vec3 posA = getAtomPos(atomA);
    vec3 posB = getAtomPos(atomB);

    vec3 start = posA;
    vec3 end = posB;

    // Apply perpendicular offset for double/triple/aromatic bonds
    if (instanceOffsetX != 0.0 || instanceOffsetY != 0.0) {
      vec3 bdir = normalize(posB - posA);
      vec3 perpX = cross(bdir, vec3(0.0, 1.0, 0.0));
      if (dot(perpX, perpX) < 0.001) {
        perpX = cross(bdir, vec3(1.0, 0.0, 0.0));
      }
      perpX = normalize(perpX);
      vec3 perpY = normalize(cross(bdir, perpX));
      vec3 offset = perpX * instanceOffsetX + perpY * instanceOffsetY;
      start += offset;
      end += offset;
    }

    vec4 viewStart = modelViewMatrix * vec4(start, 1.0);
    vec4 viewEnd = modelViewMatrix * vec4(end, 1.0);

    vec3 viewMid = (viewStart.xyz + viewEnd.xyz) * 0.5;
    vec3 axis = viewEnd.xyz - viewStart.xyz;
    float len = length(axis);
    vec3 dir = axis / max(len, 0.0001);

    vec3 side = normalize(cross(dir, vec3(0.0, 0.0, 1.0)));

    vec3 viewPos = viewMid
      + dir * (position.y * len * 0.5)
      + side * (position.x * instanceRadius * uBondScaleMultiplier);

    gl_Position = projectionMatrix * vec4(viewPos, 1.0);
  }
`
), _L = (
  /* glsl */
  `precision highp float;

  in vec3 vColor;
  in vec2 vCylUv;
  in float vDashed;
  in float vBondOpacity;

  uniform float uOpacity;
  uniform int uUsePerBondOverrides;

  out vec4 fragColor;

  void main() {
    // Dashed bond: discard alternate segments along bond length
    if (vDashed > 0.5) {
      if (sin(vCylUv.y * 30.0) < 0.0) discard;
    }

    float nx = vCylUv.x;
    float nz = sqrt(max(0.0, 1.0 - nx * nx));
    vec3 normal = vec3(nx, 0.0, nz);

    // Hemisphere ambient
    vec3 skyColor = vec3(0.87, 0.92, 1.0);
    vec3 groundColor = vec3(0.6, 0.47, 0.27);
    float hemiMix = normal.y * 0.5 + 0.5;
    vec3 ambient = mix(groundColor, skyColor, hemiMix) * 0.35;

    // Dual-light diffuse
    vec3 lightDir1 = normalize(vec3(0.5, 0.5, 1.0));
    vec3 lightDir2 = normalize(vec3(-0.3, 0.3, 0.8));
    float diffuse1 = max(dot(normal, lightDir1), 0.0);
    float diffuse2 = max(dot(normal, lightDir2), 0.0);
    float diffuse = diffuse1 * 0.55 + diffuse2 * 0.2;

    // Specular
    vec3 viewDir = vec3(0.0, 0.0, 1.0);
    vec3 halfDir = normalize(lightDir1 + viewDir);
    float spec = pow(max(dot(normal, halfDir), 0.0), 64.0);

    // Fresnel rim
    float fresnel = pow(1.0 - nz, 3.0) * 0.1;

    vec3 color = vColor * (ambient + diffuse)
               + vec3(1.0) * spec * 0.2
               + vec3(0.1) * fresnel;
    float finalOpacity = uOpacity;
    if (uUsePerBondOverrides == 1) {
      finalOpacity *= vBondOpacity;
    }
    fragColor = vec4(color, finalOpacity);
  }
`
);
class YM {
  constructor(t = 1e6) {
    At(this, "mesh");
    At(this, "geo");
    At(this, "material");
    At(this, "centerAttr");
    At(this, "radiusAttr");
    At(this, "colorAttr");
    At(this, "scaleOverrideAttr");
    At(this, "opacityOverrideAttr");
    At(this, "centerBuf");
    At(this, "radiusBuf");
    At(this, "colorBuf");
    At(this, "scaleOverrideBuf");
    At(this, "opacityOverrideBuf");
    At(this, "nAtoms", 0);
    At(this, "capacity");
    this.capacity = t, this.geo = new sv();
    const e = new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]), s = new Uint16Array([0, 1, 2, 0, 2, 3]);
    this.geo.setAttribute("position", new dn(e, 3)), this.geo.setIndex(new dn(s, 1)), this.geo.instanceCount = 0, this.centerBuf = new Float32Array(t * 3), this.radiusBuf = new Float32Array(t), this.colorBuf = new Float32Array(t * 3), this.scaleOverrideBuf = new Float32Array(t).fill(1), this.opacityOverrideBuf = new Float32Array(t).fill(1), this.centerAttr = new An(this.centerBuf, 3), this.radiusAttr = new An(this.radiusBuf, 1), this.colorAttr = new An(this.colorBuf, 3), this.scaleOverrideAttr = new An(this.scaleOverrideBuf, 1), this.opacityOverrideAttr = new An(this.opacityOverrideBuf, 1), this.centerAttr.setUsage(Lo), this.radiusAttr.setUsage(za), this.colorAttr.setUsage(za), this.scaleOverrideAttr.setUsage(Lo), this.opacityOverrideAttr.setUsage(Lo), this.geo.setAttribute("instanceCenter", this.centerAttr), this.geo.setAttribute("instanceRadius", this.radiusAttr), this.geo.setAttribute("instanceColor", this.colorAttr), this.geo.setAttribute("instanceScaleOverride", this.scaleOverrideAttr), this.geo.setAttribute("instanceOpacityOverride", this.opacityOverrideAttr), this.material = new nv({
      glslVersion: Ed,
      vertexShader: mL,
      fragmentShader: gL,
      uniforms: {
        uScaleMultiplier: { value: 1 },
        uOpacity: { value: 1 },
        uUsePerAtomOverrides: { value: 0 }
      },
      depthWrite: !0,
      depthTest: !0
    }), this.mesh = new Ln(this.geo, this.material), this.mesh.frustumCulled = !1;
  }
  loadSnapshot(t) {
    const { nAtoms: e, positions: s, elements: a } = t;
    this.nAtoms = e, e > this.capacity && this.grow(e);
    for (let o = 0; o < e; o++) {
      const c = o * 3;
      this.centerBuf[c] = s[c], this.centerBuf[c + 1] = s[c + 1], this.centerBuf[c + 2] = s[c + 2], this.radiusBuf[o] = ov(a[o]) * av;
      const [u, d, h] = Xc(a[o]);
      this.colorBuf[c] = u, this.colorBuf[c + 1] = d, this.colorBuf[c + 2] = h;
    }
    this.scaleOverrideBuf.fill(1, 0, e), this.opacityOverrideBuf.fill(1, 0, e), this.centerAttr.needsUpdate = !0, this.radiusAttr.needsUpdate = !0, this.colorAttr.needsUpdate = !0, this.scaleOverrideAttr.needsUpdate = !0, this.opacityOverrideAttr.needsUpdate = !0, this.geo.instanceCount = e;
  }
  updatePositions(t) {
    this.centerBuf.set(t.subarray(0, this.nAtoms * 3)), this.centerAttr.needsUpdate = !0;
  }
  /** Update atom radius scale (O(1) via shader uniform). */
  setScale(t, e) {
    this.material.uniforms.uScaleMultiplier.value = t;
  }
  /** Set global atom opacity. */
  setOpacity(t) {
    this.material.uniforms.uOpacity.value = t, this.material.transparent = t < 1, this.material.depthWrite = t >= 1, this.material.needsUpdate = !0;
  }
  /** Set per-atom scale overrides. */
  setScaleOverrides(t) {
    this.scaleOverrideBuf.set(t.subarray(0, this.nAtoms)), this.scaleOverrideAttr.needsUpdate = !0, this.material.uniforms.uUsePerAtomOverrides.value = 1;
  }
  /** Set per-atom opacity overrides. */
  setOpacityOverrides(t) {
    this.opacityOverrideBuf.set(t.subarray(0, this.nAtoms)), this.opacityOverrideAttr.needsUpdate = !0, this.material.uniforms.uUsePerAtomOverrides.value = 1;
    let e = !1;
    for (let s = 0; s < this.nAtoms; s++)
      if (this.opacityOverrideBuf[s] < 1) {
        e = !0;
        break;
      }
    e && (this.material.transparent = !0, this.material.depthWrite = !1, this.material.needsUpdate = !0);
  }
  /** Clear all per-atom overrides, reverting to global uniforms. */
  clearOverrides() {
    this.scaleOverrideBuf.fill(1, 0, this.nAtoms), this.opacityOverrideBuf.fill(1, 0, this.nAtoms), this.scaleOverrideAttr.needsUpdate = !0, this.opacityOverrideAttr.needsUpdate = !0, this.material.uniforms.uUsePerAtomOverrides.value = 0;
  }
  grow(t) {
    this.capacity = Math.max(t, this.capacity * 2);
    const e = new Float32Array(this.capacity * 3), s = new Float32Array(this.capacity), a = new Float32Array(this.capacity * 3), o = new Float32Array(this.capacity).fill(1), c = new Float32Array(this.capacity).fill(1);
    e.set(this.centerBuf), s.set(this.radiusBuf), a.set(this.colorBuf), o.set(this.scaleOverrideBuf), c.set(this.opacityOverrideBuf), this.centerBuf = e, this.radiusBuf = s, this.colorBuf = a, this.scaleOverrideBuf = o, this.opacityOverrideBuf = c, this.centerAttr = new An(this.centerBuf, 3), this.radiusAttr = new An(this.radiusBuf, 1), this.colorAttr = new An(this.colorBuf, 3), this.scaleOverrideAttr = new An(this.scaleOverrideBuf, 1), this.opacityOverrideAttr = new An(this.opacityOverrideBuf, 1), this.centerAttr.setUsage(Lo), this.radiusAttr.setUsage(za), this.colorAttr.setUsage(za), this.scaleOverrideAttr.setUsage(Lo), this.opacityOverrideAttr.setUsage(Lo), this.geo.setAttribute("instanceCenter", this.centerAttr), this.geo.setAttribute("instanceRadius", this.radiusAttr), this.geo.setAttribute("instanceColor", this.colorAttr), this.geo.setAttribute("instanceScaleOverride", this.scaleOverrideAttr), this.geo.setAttribute("instanceOpacityOverride", this.opacityOverrideAttr);
  }
  dispose() {
    this.geo.dispose(), this.material.dispose();
  }
}
const yL = 4096;
class jM {
  constructor(t = 3e6) {
    At(this, "mesh");
    At(this, "geo");
    At(this, "bondMaterial");
    // Topology buffers (set at loadSnapshot, static per snapshot)
    At(this, "atomABuf");
    At(this, "atomBBuf");
    At(this, "offsetXBuf");
    At(this, "offsetYBuf");
    At(this, "colorBuf");
    At(this, "radiusBuf");
    At(this, "dashedBuf");
    At(this, "opacityBuf");
    // per-visual-instance opacity override
    At(this, "logicalBondIdx");
    // CPU-only: maps visual instance → logical bond index
    // Position DataTexture (updated per frame)
    At(this, "positionTex");
    At(this, "positionTexData");
    At(this, "positionTexWidth", 1);
    At(this, "positionTexHeight", 1);
    At(this, "nAtoms", 0);
    At(this, "capacity");
    this.capacity = t, this.geo = new sv();
    const e = new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]), s = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), a = new Uint16Array([0, 1, 2, 0, 2, 3]);
    this.geo.setAttribute("position", new dn(e, 3)), this.geo.setAttribute("uv", new dn(s, 2)), this.geo.setIndex(new dn(a, 1)), this.geo.instanceCount = 0, this.atomABuf = new Float32Array(t), this.atomBBuf = new Float32Array(t), this.offsetXBuf = new Float32Array(t), this.offsetYBuf = new Float32Array(t), this.colorBuf = new Float32Array(t * 3), this.radiusBuf = new Float32Array(t), this.dashedBuf = new Float32Array(t), this.opacityBuf = new Float32Array(t).fill(1), this.logicalBondIdx = new Float32Array(t), this.positionTexData = new Float32Array(4), this.positionTex = new Cd(
      this.positionTexData,
      1,
      1,
      Ni,
      Di
    ), this.positionTex.minFilter = vn, this.positionTex.magFilter = vn, this.positionTex.generateMipmaps = !1, this.positionTex.needsUpdate = !0, this.registerAttributes(), this.bondMaterial = new nv({
      glslVersion: Ed,
      vertexShader: vL,
      fragmentShader: _L,
      uniforms: {
        uOpacity: { value: 1 },
        uBondScaleMultiplier: { value: 1 },
        uPositionTex: { value: this.positionTex },
        uPositionTexWidth: { value: 1 },
        uUsePerBondOverrides: { value: 0 }
      },
      depthWrite: !0,
      depthTest: !0
    }), this.mesh = new Ln(this.geo, this.bondMaterial), this.mesh.frustumCulled = !1;
  }
  loadSnapshot(t) {
    const { nAtoms: e, nBonds: s, positions: a, elements: o, bonds: c, bondOrders: u } = t;
    this.nAtoms = e, this.positionTexWidth = Math.min(e, yL), this.positionTexHeight = Math.max(1, Math.ceil(e / this.positionTexWidth)), this.positionTexData = new Float32Array(this.positionTexWidth * this.positionTexHeight * 4), this.copyPositionsToTexData(a), this.positionTex.dispose(), this.positionTex = new Cd(
      this.positionTexData,
      this.positionTexWidth,
      this.positionTexHeight,
      Ni,
      Di
    ), this.positionTex.minFilter = vn, this.positionTex.magFilter = vn, this.positionTex.generateMipmaps = !1, this.positionTex.needsUpdate = !0, this.bondMaterial.uniforms.uPositionTex.value = this.positionTex, this.bondMaterial.uniforms.uPositionTexWidth.value = this.positionTexWidth;
    let d = 0;
    for (let m = 0; m < s; m++) {
      const p = u ? u[m] : Ab;
      p === Tb ? d += 2 : p === Cb ? d += 3 : p === Rb ? d += 2 : d += 1;
    }
    d > this.capacity && this.grow(d);
    let h = 0;
    for (let m = 0; m < s; m++) {
      const p = c[m * 2], g = c[m * 2 + 1], _ = u ? u[m] : Ab, [x, A, b] = Xc(o[p]), [y, E, w] = Xc(o[g]), M = (x + y) * 0.5, O = (A + E) * 0.5, C = (b + w) * 0.5;
      if (_ === Tb)
        for (const D of [-1, 1])
          this.setTopology(
            h,
            p,
            g,
            D * Db,
            0,
            lL,
            M,
            O,
            C,
            0
          ), this.logicalBondIdx[h] = m, this.opacityBuf[h] = 1, h++;
      else if (_ === Cb) {
        const D = [0, 2 * Math.PI / 3, 4 * Math.PI / 3];
        for (const T of D) {
          const L = Math.cos(T) * Nb, z = Math.sin(T) * Nb;
          this.setTopology(h, p, g, L, z, cL, M, O, C, 0), this.logicalBondIdx[h] = m, this.opacityBuf[h] = 1, h++;
        }
      } else _ === Rb ? (this.setTopology(h, p, g, 0, 0, uL, M, O, C, 0), this.logicalBondIdx[h] = m, this.opacityBuf[h] = 1, h++, this.setTopology(h, p, g, Db, 0, fL, M, O, C, 1), this.logicalBondIdx[h] = m, this.opacityBuf[h] = 1, h++) : (this.setTopology(h, p, g, 0, 0, oL, M, O, C, 0), this.logicalBondIdx[h] = m, this.opacityBuf[h] = 1, h++);
    }
    this.bondMaterial.uniforms.uUsePerBondOverrides.value = 0, this.registerAttributes(), this.geo.instanceCount = h;
  }
  updatePositions(t, e, s) {
    this.copyPositionsToTexData(t), this.positionTex.needsUpdate = !0;
  }
  setTopology(t, e, s, a, o, c, u, d, h, m) {
    this.atomABuf[t] = e, this.atomBBuf[t] = s, this.offsetXBuf[t] = a, this.offsetYBuf[t] = o;
    const p = t * 3;
    this.colorBuf[p] = u, this.colorBuf[p + 1] = d, this.colorBuf[p + 2] = h, this.radiusBuf[t] = c, this.dashedBuf[t] = m;
  }
  copyPositionsToTexData(t) {
    const e = this.positionTexData, s = this.nAtoms;
    for (let a = 0; a < s; a++) {
      const o = a * 3, c = a * 4;
      e[c] = t[o], e[c + 1] = t[o + 1], e[c + 2] = t[o + 2];
    }
  }
  /** Recreate all instance attributes and re-register with geometry. */
  registerAttributes() {
    const t = new An(this.atomABuf, 1), e = new An(this.atomBBuf, 1), s = new An(this.offsetXBuf, 1), a = new An(this.offsetYBuf, 1), o = new An(this.colorBuf, 3), c = new An(this.radiusBuf, 1), u = new An(this.dashedBuf, 1), d = new An(this.opacityBuf, 1);
    this.geo.setAttribute("instanceAtomA", t), this.geo.setAttribute("instanceAtomB", e), this.geo.setAttribute("instanceOffsetX", s), this.geo.setAttribute("instanceOffsetY", a), this.geo.setAttribute("instanceColor", o), this.geo.setAttribute("instanceRadius", c), this.geo.setAttribute("instanceDashed", u), this.geo.setAttribute("instanceBondOpacity", d);
  }
  grow(t) {
    this.capacity = Math.max(t, this.capacity * 2);
    const e = new Float32Array(this.capacity), s = new Float32Array(this.capacity), a = new Float32Array(this.capacity), o = new Float32Array(this.capacity), c = new Float32Array(this.capacity * 3), u = new Float32Array(this.capacity), d = new Float32Array(this.capacity), h = new Float32Array(this.capacity).fill(1), m = new Float32Array(this.capacity);
    e.set(this.atomABuf), s.set(this.atomBBuf), a.set(this.offsetXBuf), o.set(this.offsetYBuf), c.set(this.colorBuf), u.set(this.radiusBuf), d.set(this.dashedBuf), h.set(this.opacityBuf), m.set(this.logicalBondIdx), this.atomABuf = e, this.atomBBuf = s, this.offsetXBuf = a, this.offsetYBuf = o, this.colorBuf = c, this.radiusBuf = u, this.dashedBuf = d, this.opacityBuf = h, this.logicalBondIdx = m, this.registerAttributes();
  }
  /** Set global bond opacity. */
  setOpacity(t) {
    this.bondMaterial.uniforms.uOpacity.value = t, this.bondMaterial.transparent = t < 1, this.bondMaterial.depthWrite = t >= 1, this.bondMaterial.needsUpdate = !0;
  }
  /**
   * Apply per-bond opacity overrides (one value per logical bond).
   * Maps logical bond opacities to visual instances and activates per-bond mode.
   */
  setBondOpacityOverrides(t) {
    const e = this.geo.instanceCount;
    for (let a = 0; a < e; a++) {
      const o = this.logicalBondIdx[a];
      this.opacityBuf[a] = t[o] ?? 1;
    }
    const s = this.geo.getAttribute("instanceBondOpacity");
    s && (s.needsUpdate = !0), this.bondMaterial.uniforms.uUsePerBondOverrides.value = 1, this.bondMaterial.transparent = !0, this.bondMaterial.depthWrite = !1, this.bondMaterial.needsUpdate = !0;
  }
  /** Clear per-bond opacity overrides, reverting to global opacity mode. */
  clearBondOpacityOverrides() {
    this.opacityBuf.fill(1);
    const t = this.geo.getAttribute("instanceBondOpacity");
    t && (t.needsUpdate = !0), this.bondMaterial.uniforms.uUsePerBondOverrides.value = 0, this.bondMaterial.needsUpdate = !0;
  }
  /** Set bond radius scale multiplier (O(1) via shader uniform). */
  setScale(t, e) {
    this.bondMaterial.uniforms.uBondScaleMultiplier.value = t;
  }
  dispose() {
    this.geo.dispose(), this.bondMaterial.dispose(), this.positionTex.dispose();
  }
}
class qM {
  constructor() {
    At(this, "mesh");
    At(this, "geometry");
    this.geometry = new In();
    const t = new Float32Array(72);
    this.geometry.setAttribute("position", new dn(t, 3));
    const e = new jd({
      color: 6710886,
      transparent: !0,
      opacity: 0.5
    });
    this.mesh = new O3(this.geometry, e), this.mesh.frustumCulled = !1, this.mesh.visible = !1;
  }
  /**
   * Update the cell box from a 3x3 matrix (row-major Float32Array of length 9).
   * Cell vectors: va = box[0..2], vb = box[3..5], vc = box[6..8].
   */
  loadBox(t) {
    const e = new st(t[0], t[1], t[2]), s = new st(t[3], t[4], t[5]), a = new st(t[6], t[7], t[8]), o = new st(0, 0, 0), c = e.clone(), u = s.clone(), d = a.clone(), h = e.clone().add(s), m = e.clone().add(a), p = s.clone().add(a), g = e.clone().add(s).add(a), _ = [
      // Bottom face
      [o, c],
      [o, u],
      [c, h],
      [u, h],
      // Top face
      [d, m],
      [d, p],
      [m, g],
      [p, g],
      // Vertical edges
      [o, d],
      [c, m],
      [u, p],
      [h, g]
    ], x = this.geometry.getAttribute("position"), A = x.array;
    for (let b = 0; b < 12; b++) {
      const [y, E] = _[b];
      A[b * 6] = y.x, A[b * 6 + 1] = y.y, A[b * 6 + 2] = y.z, A[b * 6 + 3] = E.x, A[b * 6 + 4] = E.y, A[b * 6 + 5] = E.z;
    }
    x.needsUpdate = !0, this.geometry.computeBoundingSphere(), this.mesh.visible = !0;
  }
  setVisible(t) {
    this.mesh.visible = t;
  }
  dispose() {
    this.geometry.dispose(), this.mesh.material.dispose();
  }
}
const Ob = 8, Lb = [14496563, 3385907, 3368669], sg = 1e-4;
class xL {
  constructor() {
    At(this, "axesScene");
    At(this, "axesCamera");
    At(this, "arrowGroup");
    At(this, "visible", !0);
    /** Inset position in CSS pixels (bottom-left corner of the inset). */
    At(this, "posX", Ob);
    At(this, "posY", Ob);
    /** Last computed inset size (CSS pixels), cached for hit-testing. */
    At(this, "lastInsetSize", 60);
    this.axesScene = new DM(), this.axesCamera = new Ti(50, 1, 0.1, 100), this.axesCamera.position.set(0, 0, 3);
    const t = new X3(16777215, 0.6);
    this.axesScene.add(t);
    const e = new md(16777215, 0.8);
    e.position.set(2, 2, 2), this.axesScene.add(e), this.arrowGroup = new na(), this.axesScene.add(this.arrowGroup);
  }
  /**
   * Update from the 3x3 cell matrix (row-major Float32Array of length 9).
   */
  loadBox(t) {
    const e = new st(t[0], t[1], t[2]), s = new st(t[3], t[4], t[5]), a = new st(t[6], t[7], t[8]), o = e.length(), c = s.length(), u = a.length(), h = Math.abs(e.dot(s)) < sg * o * c && Math.abs(e.dot(a)) < sg * o * u && Math.abs(s.dot(a)) < sg * c * u ? ["x", "y", "z"] : ["a", "b", "c"], m = [e.normalize(), s.normalize(), a.normalize()];
    this.buildArrows(m, h);
  }
  buildArrows(t, e) {
    for (; this.arrowGroup.children.length > 0; ) {
      const s = this.arrowGroup.children[0];
      this.arrowGroup.remove(s), this.disposeObject(s);
    }
    for (let s = 0; s < 3; s++) {
      const a = new $3(
        t[s],
        new st(0, 0, 0),
        1,
        Lb[s],
        0.25,
        0.1
      );
      this.arrowGroup.add(a);
      const o = this.makeTextSprite(e[s], Lb[s]);
      o.position.copy(t[s]).multiplyScalar(1.25), o.scale.set(0.3, 0.3, 1), this.arrowGroup.add(o);
    }
  }
  makeTextSprite(t, e) {
    const a = document.createElement("canvas");
    a.width = 64, a.height = 64;
    const o = a.getContext("2d");
    if (!o)
      return new Vm(new m0({ transparent: !0 }));
    o.clearRect(0, 0, 64, 64);
    const c = new we(e);
    o.fillStyle = `rgb(${c.r * 255 | 0},${c.g * 255 | 0},${c.b * 255 | 0})`, o.font = "bold 48px Arial, sans-serif", o.textAlign = "center", o.textBaseline = "middle", o.fillText(t, 64 / 2, 64 / 2);
    const u = new L3(a), d = new m0({
      map: u,
      depthTest: !1,
      transparent: !0
    });
    return new Vm(d);
  }
  // ── Hit-testing & drag ──────────────────────────────────────
  /**
   * Test whether a CSS-pixel coordinate (origin = top-left of container)
   * lies inside the axes inset.
   */
  hitTest(t, e, s) {
    if (!this.visible || this.arrowGroup.children.length === 0) return !1;
    const a = s - e;
    return t >= this.posX && t <= this.posX + this.lastInsetSize && a >= this.posY && a <= this.posY + this.lastInsetSize;
  }
  /**
   * Move the inset by a delta (CSS pixels), clamped to container bounds.
   */
  moveBy(t, e, s, a) {
    this.posX += t, this.posY -= e, this.clampPosition(s, a);
  }
  clampPosition(t, e) {
    const s = this.lastInsetSize, a = 4;
    this.posX = Math.max(a, Math.min(t - s - a, this.posX)), this.posY = Math.max(a, Math.min(e - s - a, this.posY));
  }
  // ── Rendering ───────────────────────────────────────────────
  /**
   * Render the axes inset.
   * Must be called AFTER the main scene render.
   */
  render(t, e, s, a) {
    if (!this.visible || this.arrowGroup.children.length === 0) return;
    this.axesCamera.quaternion.copy(e.quaternion), this.axesCamera.position.set(0, 0, 3).applyQuaternion(e.quaternion);
    const o = Math.min(s, a), c = Math.max(60, Math.min(140, Math.round(o * 0.12)));
    this.lastInsetSize = c, this.clampPosition(s, a);
    const u = t.autoClear;
    t.autoClear = !1, t.setViewport(this.posX, this.posY, c, c), t.setScissor(this.posX, this.posY, c, c), t.setScissorTest(!0), t.clearDepth(), t.render(this.axesScene, this.axesCamera), t.autoClear = u, t.setViewport(0, 0, s, a), t.setScissorTest(!1);
  }
  setVisible(t) {
    this.visible = t;
  }
  isVisible() {
    return this.visible;
  }
  disposeObject(t) {
    t.traverse((e) => {
      var s, a, o;
      (e instanceof Ln || e instanceof Gc) && ((s = e.geometry) == null || s.dispose(), Array.isArray(e.material) ? e.material.forEach((c) => c.dispose()) : (a = e.material) == null || a.dispose()), e instanceof Vm && ((o = e.material.map) == null || o.dispose(), e.material.dispose());
    });
  }
  dispose() {
    for (; this.arrowGroup.children.length > 0; ) {
      const t = this.arrowGroup.children[0];
      this.arrowGroup.remove(t), this.disposeObject(t);
    }
  }
}
const SL = 500, bL = "bold 11px sans-serif", Ub = -8;
class ML {
  constructor() {
    At(this, "canvas");
    At(this, "ctx");
    At(this, "labels", null);
    At(this, "elements", null);
    At(this, "nAtoms", 0);
    At(this, "positions", null);
    At(this, "tmpVec", new st());
    At(this, "lastWidth", 0);
    At(this, "lastHeight", 0);
    At(this, "lastPixelRatio", 1);
    this.canvas = document.createElement("canvas"), this.canvas.style.position = "absolute", this.canvas.style.top = "0", this.canvas.style.left = "0", this.canvas.style.width = "100%", this.canvas.style.height = "100%", this.canvas.style.pointerEvents = "none", this.ctx = this.canvas.getContext("2d");
  }
  getCanvas() {
    return this.canvas;
  }
  setLabels(t) {
    this.labels = t;
  }
  setAtomData(t, e) {
    this.elements = t, this.nAtoms = e;
  }
  setPositions(t) {
    this.positions = t;
  }
  resize(t, e, s) {
    this.lastWidth = t, this.lastHeight = e, this.lastPixelRatio = s, this.canvas.width = Math.round(t * s), this.canvas.height = Math.round(e * s), this.ctx.setTransform(s, 0, 0, s, 0, 0);
  }
  render(t, e, s, a = 1) {
    if ((this.lastWidth !== e || this.lastHeight !== s || this.lastPixelRatio !== a) && this.resize(e, s, a), this.ctx.clearRect(0, 0, e, s), !this.labels || !this.positions || !this.elements || this.nAtoms === 0)
      return;
    const o = e / 2, c = s / 2, u = [];
    for (let h = 0; h < this.nAtoms; h++) {
      if (!this.labels[h] || (this.tmpVec.set(this.positions[h * 3], this.positions[h * 3 + 1], this.positions[h * 3 + 2]), this.tmpVec.project(t), this.tmpVec.z < -1 || this.tmpVec.z > 1)) continue;
      const p = this.tmpVec.x * o + o, g = -(this.tmpVec.y * c) + c;
      p < -50 || p > e + 50 || g < -20 || g > s + 20 || u.push({ sx: p, sy: g, z: this.tmpVec.z, idx: h });
    }
    u.sort((h, m) => h.z - m.z);
    const d = Math.min(u.length, SL);
    this.ctx.font = bL, this.ctx.textAlign = "center", this.ctx.textBaseline = "bottom";
    for (let h = 0; h < d; h++) {
      const { sx: m, sy: p, idx: g } = u[h], _ = this.labels[g], x = this.elements[g], [A, b, y] = Xc(x), E = 0.299 * A + 0.587 * b + 0.114 * y, w = E > 0.5 ? "#000000" : "#ffffff", M = E > 0.5 ? "#ffffff" : "#000000";
      this.ctx.strokeStyle = M, this.ctx.lineWidth = 2.5, this.ctx.lineJoin = "round", this.ctx.strokeText(_, m, p + Ub), this.ctx.fillStyle = w, this.ctx.fillText(_, m, p + Ub);
    }
  }
  dispose() {
    this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas);
  }
}
const Pb = 15158332, Ib = 0.04, EL = 0.1, rg = 0.2, wL = 6, AL = 8, TL = 1e-6, wc = new st(), CL = new st(0, 1, 0), ag = new pr(), $f = new st(), Kf = new st(), Oa = new je();
class RL {
  constructor(t = 1e5) {
    At(this, "mesh");
    At(this, "shaftMesh");
    At(this, "headMesh");
    At(this, "nAtoms", 0);
    At(this, "positions", null);
    At(this, "vectors", null);
    At(this, "arrowScale", 1);
    At(this, "capacity");
    this.capacity = t, this.mesh = new na(), this.mesh.visible = !1;
    const e = new qd(Ib, Ib, 1, wL);
    e.translate(0, 0.5, 0);
    const s = new Zd(EL, rg, AL);
    s.translate(0, rg / 2, 0);
    const a = new g0({
      color: Pb,
      transparent: !0,
      opacity: 0.85
    }), o = new g0({
      color: Pb,
      transparent: !0,
      opacity: 0.85
    });
    this.shaftMesh = new HS(e, a, t), this.headMesh = new HS(s, o, t), this.shaftMesh.count = 0, this.headMesh.count = 0, this.mesh.add(this.shaftMesh), this.mesh.add(this.headMesh);
  }
  setAtomPositions(t, e) {
    this.positions = t, this.nAtoms = e, this.vectors && this.update();
  }
  setVectors(t) {
    this.vectors = t, t ? (this.mesh.visible = !0, this.update()) : (this.mesh.visible = !1, this.shaftMesh.count = 0, this.headMesh.count = 0);
  }
  setScale(t) {
    this.arrowScale = t, this.vectors && this.update();
  }
  update() {
    if (!this.positions || !this.vectors) return;
    const t = Math.min(this.nAtoms, this.capacity);
    this.shaftMesh.count = t, this.headMesh.count = t;
    for (let e = 0; e < t; e++) {
      const s = this.positions[e * 3], a = this.positions[e * 3 + 1], o = this.positions[e * 3 + 2], c = this.vectors[e * 3], u = this.vectors[e * 3 + 1], d = this.vectors[e * 3 + 2], h = Math.sqrt(c * c + u * u + d * d);
      if (h < TL) {
        Oa.makeScale(0, 0, 0), this.shaftMesh.setMatrixAt(e, Oa), this.headMesh.setMatrixAt(e, Oa);
        continue;
      }
      wc.set(c / h, u / h, d / h), ag.setFromUnitVectors(CL, wc);
      const m = h * this.arrowScale, p = Math.max(m - rg, m * 0.7);
      $f.set(s, a, o), Kf.set(1, p, 1), Oa.compose($f, ag, Kf), this.shaftMesh.setMatrixAt(e, Oa), $f.set(s + wc.x * p, a + wc.y * p, o + wc.z * p), Kf.set(1, 1, 1), Oa.compose($f, ag, Kf), this.headMesh.setMatrixAt(e, Oa);
    }
    this.shaftMesh.instanceMatrix.needsUpdate = !0, this.headMesh.instanceMatrix.needsUpdate = !0;
  }
  dispose() {
    this.shaftMesh.geometry.dispose(), this.headMesh.geometry.dispose(), this.shaftMesh.material.dispose(), this.headMesh.material.dispose(), this.mesh.remove(this.shaftMesh), this.mesh.remove(this.headMesh);
  }
}
const Bb = new Ns(), Qf = new st();
class ZM extends sv {
  /**
   * 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], s = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5];
    this.setIndex(s), this.setAttribute("position", new _n(t, 3)), this.setAttribute("uv", new _n(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, s = this.attributes.instanceEnd;
    return e !== void 0 && (e.applyMatrix4(t), s.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 s = new v0(e, 6, 1);
    return this.setAttribute("instanceStart", new Es(s, 3, 0)), this.setAttribute("instanceEnd", new Es(s, 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 s = new v0(e, 6, 1);
    return this.setAttribute("instanceColorStart", new Es(s, 3, 0)), this.setAttribute("instanceColorEnd", new Es(s, 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 P3(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 Ns());
    const t = this.attributes.instanceStart, e = this.attributes.instanceEnd;
    t !== void 0 && e !== void 0 && (this.boundingBox.setFromBufferAttribute(t), Bb.setFromBufferAttribute(e), this.boundingBox.union(Bb));
  }
  computeBoundingSphere() {
    this.boundingSphere === null && (this.boundingSphere = new aa()), this.boundingBox === null && this.computeBoundingBox();
    const t = this.attributes.instanceStart, e = this.attributes.instanceEnd;
    if (t !== void 0 && e !== void 0) {
      const s = this.boundingSphere.center;
      this.boundingBox.getCenter(s);
      let a = 0;
      for (let o = 0, c = t.count; o < c; o++)
        Qf.fromBufferAttribute(t, o), a = Math.max(a, s.distanceToSquared(Qf)), Qf.fromBufferAttribute(e, o), a = Math.max(a, s.distanceToSquared(Qf));
      this.boundingSphere.radius = Math.sqrt(a), 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() {
  }
}
Gt.line = {
  worldUnits: { value: 1 },
  linewidth: { value: 1 },
  resolution: { value: new ae(1, 1) },
  dashOffset: { value: 0 },
  dashScale: { value: 1 },
  dashSize: { value: 1 },
  gapSize: { value: 1 }
  // todo FIX - maybe change to totalSize
};
di.line = {
  uniforms: ev.merge([
    Gt.common,
    Gt.fog,
    Gt.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>

		}
		`
  )
};
class $M extends as {
  /**
   * 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: ev.clone(di.line.uniforms),
      vertexShader: di.line.vertexShader,
      fragmentShader: di.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.worldUnits && (this.needsUpdate = !0), 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 og = new Je(), zb = new st(), Fb = new st(), Wn = new Je(), Yn = new Je(), _s = new Je(), lg = new st(), cg = new je(), jn = new Z3(), Hb = new st(), Jf = new Ns(), td = new aa(), ys = new Je();
let bs, Ha;
function Vb(n, t, e) {
  return ys.set(0, 0, -t, 1).applyMatrix4(n.projectionMatrix), ys.multiplyScalar(1 / ys.w), ys.x = Ha / e.width, ys.y = Ha / e.height, ys.applyMatrix4(n.projectionMatrixInverse), ys.multiplyScalar(1 / ys.w), Math.abs(Math.max(ys.x, ys.y));
}
function DL(n, t) {
  const e = n.matrixWorld, s = n.geometry, a = s.attributes.instanceStart, o = s.attributes.instanceEnd, c = Math.min(s.instanceCount, a.count);
  for (let u = 0, d = c; u < d; u++) {
    jn.start.fromBufferAttribute(a, u), jn.end.fromBufferAttribute(o, u), jn.applyMatrix4(e);
    const h = new st(), m = new st();
    bs.distanceSqToSegment(jn.start, jn.end, m, h), m.distanceTo(h) < Ha * 0.5 && t.push({
      point: m,
      pointOnLine: h,
      distance: bs.origin.distanceTo(m),
      object: n,
      face: null,
      faceIndex: u,
      uv: null,
      uv1: null
    });
  }
}
function NL(n, t, e) {
  const s = t.projectionMatrix, o = n.material.resolution, c = n.matrixWorld, u = n.geometry, d = u.attributes.instanceStart, h = u.attributes.instanceEnd, m = Math.min(u.instanceCount, d.count), p = -t.near;
  bs.at(1, _s), _s.w = 1, _s.applyMatrix4(t.matrixWorldInverse), _s.applyMatrix4(s), _s.multiplyScalar(1 / _s.w), _s.x *= o.x / 2, _s.y *= o.y / 2, _s.z = 0, lg.copy(_s), cg.multiplyMatrices(t.matrixWorldInverse, c);
  for (let g = 0, _ = m; g < _; g++) {
    if (Wn.fromBufferAttribute(d, g), Yn.fromBufferAttribute(h, g), Wn.w = 1, Yn.w = 1, Wn.applyMatrix4(cg), Yn.applyMatrix4(cg), Wn.z > p && Yn.z > p)
      continue;
    if (Wn.z > p) {
      const w = Wn.z - Yn.z, M = (Wn.z - p) / w;
      Wn.lerp(Yn, M);
    } else if (Yn.z > p) {
      const w = Yn.z - Wn.z, M = (Yn.z - p) / w;
      Yn.lerp(Wn, M);
    }
    Wn.applyMatrix4(s), Yn.applyMatrix4(s), Wn.multiplyScalar(1 / Wn.w), Yn.multiplyScalar(1 / Yn.w), Wn.x *= o.x / 2, Wn.y *= o.y / 2, Yn.x *= o.x / 2, Yn.y *= o.y / 2, jn.start.copy(Wn), jn.start.z = 0, jn.end.copy(Yn), jn.end.z = 0;
    const A = jn.closestPointToPointParameter(lg, !0);
    jn.at(A, Hb);
    const b = AM.lerp(Wn.z, Yn.z, A), y = b >= -1 && b <= 1, E = lg.distanceTo(Hb) < Ha * 0.5;
    if (y && E) {
      jn.start.fromBufferAttribute(d, g), jn.end.fromBufferAttribute(h, g), jn.start.applyMatrix4(c), jn.end.applyMatrix4(c);
      const w = new st(), M = new st();
      bs.distanceSqToSegment(jn.start, jn.end, M, w), e.push({
        point: M,
        pointOnLine: w,
        distance: bs.origin.distanceTo(M),
        object: n,
        face: null,
        faceIndex: g,
        uv: null,
        uv1: null
      });
    }
  }
}
class OL extends Ln {
  /**
   * Constructs a new wide line.
   *
   * @param {LineSegmentsGeometry} [geometry] - The line geometry.
   * @param {LineMaterial} [material] - The line material.
   */
  constructor(t = new ZM(), e = new $M({ 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, s = t.attributes.instanceEnd, a = new Float32Array(2 * e.count);
    for (let c = 0, u = 0, d = e.count; c < d; c++, u += 2)
      zb.fromBufferAttribute(e, c), Fb.fromBufferAttribute(s, c), a[u] = u === 0 ? 0 : a[u - 1], a[u + 1] = a[u] + zb.distanceTo(Fb);
    const o = new v0(a, 2, 1);
    return t.setAttribute("instanceDistanceStart", new Es(o, 1, 0)), t.setAttribute("instanceDistanceEnd", new Es(o, 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 s = this.material.worldUnits, a = t.camera;
    a === null && !s && console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');
    const o = t.params.Line2 !== void 0 && t.params.Line2.threshold || 0;
    bs = t.ray;
    const c = this.matrixWorld, u = this.geometry, d = this.material;
    Ha = d.linewidth + o, u.boundingSphere === null && u.computeBoundingSphere(), td.copy(u.boundingSphere).applyMatrix4(c);
    let h;
    if (s)
      h = Ha * 0.5;
    else {
      const p = Math.max(a.near, td.distanceToPoint(bs.origin));
      h = Vb(a, p, d.resolution);
    }
    if (td.radius += h, bs.intersectsSphere(td) === !1)
      return;
    u.boundingBox === null && u.computeBoundingBox(), Jf.copy(u.boundingBox).applyMatrix4(c);
    let m;
    if (s)
      m = Ha * 0.5;
    else {
      const p = Math.max(a.near, Jf.distanceToPoint(bs.origin));
      m = Vb(a, p, d.resolution);
    }
    Jf.expandByScalar(m), bs.intersectsBox(Jf) !== !1 && (s ? DL(this, e) : NL(this, a, e));
  }
  onBeforeRender(t) {
    const e = this.material.uniforms;
    e && e.resolution && (t.getViewport(og), this.material.uniforms.resolution.value.set(og.z, og.w));
  }
}
class LL {
  constructor() {
    At(this, "group");
    At(this, "faceMesh", null);
    At(this, "edgeLines", null);
    At(this, "edgeMaterial", null);
    this.group = new na(), this.group.frustumCulled = !1;
  }
  loadMeshData(t) {
    this.clear();
    const e = t.positions.length / 3;
    if (e === 0 || t.indices.length === 0) return;
    const s = new In();
    s.setAttribute("position", new dn(t.positions, 3)), s.setAttribute("normal", new dn(t.normals, 3));
    const a = new Float32Array(e * 3);
    for (let c = 0; c < e; c++)
      a[c * 3] = t.colors[c * 4], a[c * 3 + 1] = t.colors[c * 4 + 1], a[c * 3 + 2] = t.colors[c * 4 + 2];
    s.setAttribute("color", new dn(a, 3)), s.setIndex(new dn(t.indices, 1));
    const o = new g0({
      vertexColors: !0,
      transparent: !0,
      opacity: t.opacity,
      side: Ss,
      depthWrite: !1,
      shininess: 30
    });
    if (this.faceMesh = new Ln(s, o), this.faceMesh.renderOrder = 1, this.group.add(this.faceMesh), t.showEdges && t.edgePositions && t.edgePositions.length > 0) {
      const c = new ZM();
      c.setPositions(t.edgePositions);
      const u = new $M({
        color: new we(t.edgeColor).getHex(),
        linewidth: t.edgeWidth,
        transparent: !0,
        opacity: 0.9,
        depthTest: !0
      });
      this.edgeMaterial = u, this.edgeLines = new OL(c, u), this.edgeLines.renderOrder = 2, this.group.add(this.edgeLines);
    }
  }
  /** Update the resolution uniform required by LineMaterial. */
  updateResolution(t, e) {
    this.edgeMaterial && this.edgeMaterial.resolution.set(t, e);
  }
  clear() {
    this.faceMesh && (this.faceMesh.geometry.dispose(), this.faceMesh.material.dispose(), this.group.remove(this.faceMesh), this.faceMesh = null), this.edgeLines && (this.edgeLines.geometry.dispose(), this.edgeLines.material.dispose(), this.group.remove(this.edgeLines), this.edgeLines = null, this.edgeMaterial = null);
  }
  setVisible(t) {
    this.group.visible = t;
  }
  dispose() {
    this.clear();
  }
}
class UL {
  constructor(t, e) {
    At(this, "id");
    At(this, "snapshot", null);
    At(this, "currentPositions", null);
    At(this, "scene");
    At(this, "atomRenderer", null);
    At(this, "bondRenderer", null);
    At(this, "cellRenderer", null);
    At(this, "atomScale", 1);
    At(this, "atomOpacity", 1);
    At(this, "bondScale", 1);
    At(this, "bondOpacity", 1);
    this.id = t, this.scene = e;
  }
  loadSnapshot(t) {
    if (this.snapshot = t, this.currentPositions = new Float32Array(t.positions), !this.atomRenderer) {
      const e = new YM();
      this.atomRenderer = e, this.scene.add(e.mesh);
    }
    if (this.atomRenderer.loadSnapshot(t), this.atomScale !== 1 && this.atomRenderer.setScale && this.atomRenderer.setScale(this.atomScale, t), this.atomOpacity !== 1 && this.atomRenderer.setOpacity && this.atomRenderer.setOpacity(this.atomOpacity), !this.bondRenderer) {
      const e = new jM();
      this.bondRenderer = e, this.scene.add(e.mesh);
    }
    t.box && t.box.some((s) => s !== 0) && (this.cellRenderer || (this.cellRenderer = new qM(), this.scene.add(this.cellRenderer.mesh)), this.cellRenderer.loadBox(t.box));
  }
  updateFrame(t) {
    !this.snapshot || !this.atomRenderer || !this.bondRenderer || ((!this.currentPositions || this.currentPositions.length < t.positions.length) && (this.currentPositions = new Float32Array(t.positions.length)), this.currentPositions.set(t.positions), this.atomRenderer.updatePositions(t.positions), this.bondRenderer.updatePositions(t.positions, this.snapshot.bonds, this.snapshot.nBonds));
  }
  updateBondsExt(t, e, s, a, o) {
    if (!this.snapshot || !this.bondRenderer) return;
    const c = s ?? this.currentPositions ?? this.snapshot.positions, u = a ?? this.snapshot.elements, d = o || this.snapshot.nAtoms;
    this.bondRenderer.loadSnapshot({
      ...this.snapshot,
      nAtoms: d,
      nBonds: t.length / 2,
      bonds: t,
      bondOrders: e,
      positions: c,
      elements: u
    }), this.bondScale !== 1 && this.bondRenderer.setScale && this.bondRenderer.setScale(this.bondScale, this.snapshot);
  }
  setAtomScale(t) {
    var e;
    this.atomScale = t, (e = this.atomRenderer) != null && e.setScale && this.snapshot && this.atomRenderer.setScale(t, this.snapshot);
  }
  setAtomOpacity(t) {
    var e, s;
    this.atomOpacity = t, (s = (e = this.atomRenderer) == null ? void 0 : e.setOpacity) == null || s.call(e, t);
  }
  setAtomScaleOverrides(t) {
    var e, s;
    (s = (e = this.atomRenderer) == null ? void 0 : e.setScaleOverrides) == null || s.call(e, t);
  }
  setAtomOpacityOverrides(t) {
    var e, s;
    (s = (e = this.atomRenderer) == null ? void 0 : e.setOpacityOverrides) == null || s.call(e, t);
  }
  clearAtomOverrides() {
    var t, e;
    (e = (t = this.atomRenderer) == null ? void 0 : t.clearOverrides) == null || e.call(t);
  }
  setBondScale(t) {
    var e;
    this.bondScale = t, (e = this.bondRenderer) != null && e.setScale && this.snapshot && this.bondRenderer.setScale(t, this.snapshot);
  }
  setBondOpacity(t) {
    var e, s;
    this.bondOpacity = t, (s = (e = this.bondRenderer) == null ? void 0 : e.setOpacity) == null || s.call(e, t);
  }
  setBondOpacityOverrides(t) {
    var e, s;
    (s = (e = this.bondRenderer) == null ? void 0 : e.setBondOpacityOverrides) == null || s.call(e, t);
  }
  clearBondOpacityOverrides() {
    var t, e;
    (e = (t = this.bondRenderer) == null ? void 0 : t.clearBondOpacityOverrides) == null || e.call(t);
  }
  setAtomsVisible(t) {
    this.atomRenderer && (this.atomRenderer.mesh.visible = t);
  }
  setBondsVisible(t) {
    this.bondRenderer && (this.bondRenderer.mesh.visible = t);
  }
  setCellVisible(t) {
    this.cellRenderer && this.cellRenderer.setVisible(t);
  }
  getPositions() {
    var t;
    return this.currentPositions ?? ((t = this.snapshot) == null ? void 0 : t.positions) ?? null;
  }
  dispose() {
    this.atomRenderer && (this.scene.remove(this.atomRenderer.mesh), this.atomRenderer.dispose(), this.atomRenderer = null), this.bondRenderer && (this.scene.remove(this.bondRenderer.mesh), this.bondRenderer.dispose(), this.bondRenderer = null), this.cellRenderer && (this.scene.remove(this.cellRenderer.mesh), this.cellRenderer.dispose(), this.cellRenderer = null), this.snapshot = null, this.currentPositions = null;
  }
}
const $r = new Je();
function Gb(n, t, e, s, a, o) {
  $r.set(t, e, s, 1), $r.applyMatrix4(n.matrixWorldInverse);
  const c = -$r.z;
  $r.applyMatrix4(n.projectionMatrix);
  const u = ($r.x / $r.w * 0.5 + 0.5) * a, d = (-$r.y / $r.w * 0.5 + 0.5) * o;
  return { sx: u, sy: d, depth: c };
}
function PL(n, t, e, s) {
  if (n instanceof ns) {
    const c = (n.top - n.bottom) / n.zoom, u = s / c;
    return t * u;
  }
  const a = n.fov * Math.PI / 180, o = s / (2 * e * Math.tan(a / 2));
  return t * o;
}
function IL(n, t, e, s, a, o, c) {
  const u = t.getBoundingClientRect(), d = o - u.left, h = c - u.top, m = u.width, p = u.height, g = s, _ = e.elements, x = e.nAtoms;
  let A = -1, b = 1 / 0;
  for (let D = 0; D < x; D++) {
    const { sx: T, sy: L, depth: z } = Gb(
      n,
      g[D * 3],
      g[D * 3 + 1],
      g[D * 3 + 2],
      m,
      p
    );
    if (z <= 0) continue;
    const R = ov(_[D]) * av * a, B = PL(n, R, z, p), H = d - T, U = h - L;
    H * H + U * U <= B * B && z < b && (A = D, b = z);
  }
  if (A >= 0) {
    const D = A, T = _[D];
    return {
      kind: "atom",
      atomIndex: D,
      elementSymbol: Wc(T),
      atomicNumber: T,
      position: [g[D * 3], g[D * 3 + 1], g[D * 3 + 2]],
      screenX: o,
      screenY: c
    };
  }
  const y = 8, E = e.bonds, w = e.nBonds, M = e.bondOrders;
  let O = -1, C = 1 / 0;
  for (let D = 0; D < w; D++) {
    const T = E[D * 2], L = E[D * 2 + 1], z = (g[T * 3] + g[L * 3]) * 0.5, R = (g[T * 3 + 1] + g[L * 3 + 1]) * 0.5, B = (g[T * 3 + 2] + g[L * 3 + 2]) * 0.5, { sx: H, sy: U, depth: V } = Gb(n, z, R, B, m, p);
    if (V <= 0) continue;
    const N = d - H, I = h - U;
    N * N + I * I <= y * y && V < C && (O = D, C = V);
  }
  if (O >= 0) {
    const D = E[O * 2], T = E[O * 2 + 1], L = g[T * 3] - g[D * 3], z = g[T * 3 + 1] - g[D * 3 + 1], R = g[T * 3 + 2] - g[D * 3 + 2], B = Math.sqrt(L * L + z * z + R * R), H = M ? M[O] : 1;
    return {
      kind: "bond",
      atomA: D,
      atomB: T,
      bondOrder: H,
      bondLength: B,
      screenX: o,
      screenY: c
    };
  }
  return null;
}
function BL(n, t, e) {
  const s = n[e * 3] - n[t * 3], a = n[e * 3 + 1] - n[t * 3 + 1], o = n[e * 3 + 2] - n[t * 3 + 2];
  return Math.sqrt(s * s + a * a + o * o);
}
function zL(n, t, e, s) {
  const a = n[t * 3] - n[e * 3], o = n[t * 3 + 1] - n[e * 3 + 1], c = n[t * 3 + 2] - n[e * 3 + 2], u = n[s * 3] - n[e * 3], d = n[s * 3 + 1] - n[e * 3 + 1], h = n[s * 3 + 2] - n[e * 3 + 2], m = a * u + o * d + c * h, p = Math.sqrt(a * a + o * o + c * c), g = Math.sqrt(u * u + d * d + h * h);
  return Math.acos(Math.max(-1, Math.min(1, m / (p * g)))) * (180 / Math.PI);
}
function FL(n, t, e, s, a) {
  const o = n[e * 3] - n[t * 3], c = n[e * 3 + 1] - n[t * 3 + 1], u = n[e * 3 + 2] - n[t * 3 + 2], d = n[s * 3] - n[e * 3], h = n[s * 3 + 1] - n[e * 3 + 1], m = n[s * 3 + 2] - n[e * 3 + 2], p = n[a * 3] - n[s * 3], g = n[a * 3 + 1] - n[s * 3 + 1], _ = n[a * 3 + 2] - n[s * 3 + 2], x = c * m - u * h, A = u * d - o * m, b = o * h - c * d, y = h * _ - m * g, E = m * p - d * _, w = d * g - h * p, M = Math.sqrt(d * d + h * h + m * m), O = d / M, C = h / M, D = m / M, T = A * D - b * C, L = b * O - x * D, z = x * C - A * O, R = x * y + A * E + b * w, B = T * y + L * E + z * w;
  return Math.atan2(B, R) * (180 / Math.PI);
}
function HL(n, t) {
  if (t.length < 2) return null;
  if (t.length === 2) {
    const e = BL(n, t[0], t[1]);
    return { atoms: [...t], type: "distance", value: e, label: `${e.toFixed(3)} Å` };
  }
  if (t.length === 3) {
    const e = zL(n, t[0], t[1], t[2]);
    return { atoms: [...t], type: "angle", value: e, label: `${e.toFixed(1)}°` };
  }
  if (t.length === 4) {
    const e = FL(n, t[0], t[1], t[2], t[3]);
    return { atoms: [...t], type: "dihedral", value: e, label: `${e.toFixed(1)}°` };
  }
  return null;
}
function VL(n) {
  const { positions: t, nAtoms: e } = n;
  let s = 0, a = 0, o = 0;
  for (let M = 0; M < e; M++)
    s += t[M * 3], a += t[M * 3 + 1], o += t[M * 3 + 2];
  let c, u, d, h = 1 / 0, m = 1 / 0, p = 1 / 0, g = -1 / 0, _ = -1 / 0, x = -1 / 0;
  if (n.box && n.box.some((M) => M !== 0)) {
    const M = n.box;
    c = (M[0] + M[3] + M[6]) / 2, u = (M[1] + M[4] + M[7]) / 2, d = (M[2] + M[5] + M[8]) / 2;
    const O = [M[0], M[1], M[2]], C = [M[3], M[4], M[5]], D = [M[6], M[7], M[8]];
    for (let T = 0; T <= 1; T++)
      for (let L = 0; L <= 1; L++)
        for (let z = 0; z <= 1; z++) {
          const R = T * O[0] + L * C[0] + z * D[0], B = T * O[1] + L * C[1] + z * D[1], H = T * O[2] + L * C[2] + z * D[2];
          h = Math.min(h, R), m = Math.min(m, B), p = Math.min(p, H), g = Math.max(g, R), _ = Math.max(_, B), x = Math.max(x, H);
        }
  } else {
    c = e > 0 ? s / e : 0, u = e > 0 ? a / e : 0, d = e > 0 ? o / e : 0;
    for (let M = 0; M < e; M++) {
      const O = t[M * 3], C = t[M * 3 + 1], D = t[M * 3 + 2];
      h = Math.min(h, O), m = Math.min(m, C), p = Math.min(p, D), g = Math.max(g, O), _ = Math.max(_, C), x = Math.max(x, D);
    }
  }
  const b = g - h, y = _ - m, E = x - p, w = Math.max(b, y, E);
  return {
    center: [c, u, d],
    extent: { maxExtent: w, extentX: b, extentY: y }
  };
}
function GL(n, t, e) {
  const { center: s, extent: a } = VL(e), [o, c, u] = s;
  t.target.set(o, c, u);
  const d = Math.max(a.maxExtent * 1.2, 0.1);
  return n.position.set(o, c - d, u), n instanceof ns ? (n.near = -d * 10, n.far = d * 10, n.zoom = 1) : (n.near = d * 0.01, n.far = d * 10, n.updateProjectionMatrix()), t.update(), a;
}
function kL(n, t, e, s, a, o) {
  if (t === 0 || e === 0) return;
  const c = Math.max(t * 0.3, 100), d = Math.max(t - s - a, c) / e, m = Math.max(o.extentY / 2, o.extentX / (2 * d)) * 1.2, p = Math.max(m * 2, 0.1), g = t / e, _ = p * g / 2;
  n.left = -_, n.right = _, n.top = p / 2, n.bottom = -p / 2;
  const x = 2 * _, A = (s - a) / (2 * t) * x;
  n.left -= A, n.right -= A, n.updateProjectionMatrix();
}
function XL(n, t, e, s) {
  const a = n.position.clone(), o = n.up.clone(), c = e / s;
  let u;
  return t ? u = new Ti(50, c, 0.1, 1e4) : u = new ns(
    -50 * c / 2,
    50 * c / 2,
    50 / 2,
    -50 / 2,
    0.1,
    1e4
  ), u.position.copy(a), u.up.copy(o), u;
}
class WL {
  constructor() {
    At(this, "container", null);
    At(this, "renderer");
    At(this, "scene");
    At(this, "camera");
    At(this, "controls");
    At(this, "perspectiveMode", !1);
    At(this, "atomRenderer", null);
    At(this, "bondRenderer", null);
    At(this, "cellRenderer", null);
    At(this, "cellAxesRenderer", null);
    At(this, "labelOverlay", null);
    At(this, "arrowRenderer", null);
    At(this, "polyhedronRenderer", null);
    At(this, "useImpostor", !1);
    At(this, "animationId", null);
    At(this, "snapshot", null);
    At(this, "lastExtent", { maxExtent: 1, extentX: 1, extentY: 1 });
    At(this, "currentPositions", null);
    /** Axes-inset drag state */
    At(this, "axesDragging", !1);
    At(this, "axesDragLastX", 0);
    At(this, "axesDragLastY", 0);
    At(this, "atomScale", 1);
    At(this, "atomOpacity", 1);
    At(this, "bondScale", 1);
    At(this, "bondOpacity", 1);
    At(this, "viewInsetLeft", 0);
    At(this, "viewInsetRight", 0);
    At(this, "dprMediaQuery", null);
    At(this, "dprChangeHandler", null);
    // Cached dimensions for frame-synchronous resize detection
    At(this, "lastContainerW", 0);
    At(this, "lastContainerH", 0);
    At(this, "lastDpr", 1);
    /** Structure layers for multi-structure overlay rendering. */
    At(this, "layers", /* @__PURE__ */ new Map());
    // (screen-space picking replaces Three.js raycasting)
    // Atom selection & measurement
    At(this, "selectedAtoms", []);
    At(this, "selectionGroup", new na());
    At(this, "animate", () => {
      if (this.animationId = requestAnimationFrame(this.animate), this.container) {
        const s = this.container.clientWidth, a = this.container.clientHeight, o = Math.min(window.devicePixelRatio, 2);
        (s !== this.lastContainerW || a !== this.lastContainerH || o !== this.lastDpr) && (this.lastContainerW = s, this.lastContainerH = a, this.lastDpr = o, this.onResize());
      }
      this.controls.update(), this.polyhedronRenderer && this.container && this.polyhedronRenderer.updateResolution(
        this.container.clientWidth,
        this.container.clientHeight
      ), this.renderer.render(this.scene, this.camera);
      const t = new ae();
      this.renderer.getSize(t);
      const e = this.renderer.getPixelRatio();
      if (this.cellAxesRenderer)
        try {
          this.cellAxesRenderer.render(this.renderer, this.camera, t.x, t.y);
        } catch (s) {
          console.warn("CellAxesRenderer render error:", s), this.cellAxesRenderer = null;
        }
      this.labelOverlay && this.labelOverlay.render(this.camera, t.x, t.y, e);
    });
  }
  /** Mount the viewer into a DOM element. */
  mount(t) {
    this.container = t, this.renderer = new WO({
      antialias: !0,
      alpha: !0,
      powerPreference: "high-performance",
      preserveDrawingBuffer: !0
    }), this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)), this.renderer.setSize(t.clientWidth, t.clientHeight, !1), this.renderer.setClearColor(16777215, 1);
    const e = this.renderer.domElement;
    e.style.display = "block", e.style.position = "absolute", e.style.top = "0", e.style.left = "0", e.style.width = "100%", e.style.height = "100%", t.appendChild(e), this.labelOverlay = new ML(), t.appendChild(this.labelOverlay.getCanvas()), this.labelOverlay.resize(
      t.clientWidth,
      t.clientHeight,
      Math.min(window.devicePixelRatio, 2)
    ), this.scene = new DM(), this.scene.background = new we(16777215);
    const s = t.clientWidth / t.clientHeight, a = 50;
    this.camera = new ns(
      -a * s / 2,
      a * s / 2,
      a / 2,
      -a / 2,
      0.1,
      1e4
    ), this.camera.position.set(0, -50, 0), this.camera.up.set(0, 0, 1), this.controls = new wb(this.camera, this.renderer.domElement), this.controls.enableDamping = !0, this.controls.dampingFactor = 0.1, this.controls.rotateSpeed = 0.8, this.controls.zoomSpeed = 1.2;
    const o = new V3(14544639, 10057540, 0.4);
    this.scene.add(o);
    const c = new md(16777215, 0.8);
    c.position.set(50, 50, 50), this.scene.add(c);
    const u = new md(16777215, 0.4);
    u.position.set(-30, 20, -20), this.scene.add(u);
    const d = new md(16777215, 0.3);
    d.position.set(0, -30, -50), this.scene.add(d), this.scene.add(this.selectionGroup), new ResizeObserver(() => this.onResize()).observe(t), this.setupDprListener(), this.animate();
  }
  /** Load a molecular snapshot (topology + positions). */
  loadSnapshot(t) {
    if (this.snapshot = t, this.currentPositions = new Float32Array(t.positions), (this.atomRenderer === null || !this.useImpostor) && this.swapRenderers(!0), this.atomRenderer.loadSnapshot(t), this.atomScale !== 1 && this.atomRenderer.setScale && this.atomRenderer.setScale(this.atomScale, t), this.labelOverlay && (this.labelOverlay.setAtomData(t.elements, t.nAtoms), this.labelOverlay.setPositions(t.positions)), this.arrowRenderer || (this.arrowRenderer = new RL(t.nAtoms), this.scene.add(this.arrowRenderer.mesh)), this.arrowRenderer.setAtomPositions(t.positions, t.nAtoms), t.box) {
      const e = t.box.some((s) => s !== 0);
      if (e && (this.cellRenderer || (this.cellRenderer = new qM(), this.scene.add(this.cellRenderer.mesh)), this.cellRenderer.loadBox(t.box)), e)
        try {
          this.cellAxesRenderer || (this.cellAxesRenderer = new xL()), this.cellAxesRenderer.loadBox(t.box);
        } catch (s) {
          console.warn("CellAxesRenderer init error:", s), this.cellAxesRenderer = null;
        }
    }
    this.fitToView(t);
  }
  /** Update positions from a trajectory frame. */
  updateFrame(t) {
    var e, s;
    !this.snapshot || !this.atomRenderer || !this.bondRenderer || ((!this.currentPositions || this.currentPositions.length < t.positions.length) && (this.currentPositions = new Float32Array(t.positions.length)), this.currentPositions.set(t.positions), this.atomRenderer.updatePositions(t.positions), (e = this.labelOverlay) == null || e.setPositions(t.positions), (s = this.arrowRenderer) == null || s.setAtomPositions(t.positions, t.nAtoms), this.bondRenderer.updatePositions(t.positions, this.snapshot.bonds, this.snapshot.nBonds), this.selectedAtoms.length > 0 && this.updateSelectionVisuals());
  }
  /**
   * Replace bond data and re-render bonds without resetting the camera.
   * Used for per-frame bond recalculation (e.g. distance-based bonds).
   */
  updateBonds(t, e) {
    if (!this.snapshot || !this.bondRenderer) return;
    const s = this.currentPositions ?? this.snapshot.positions, a = {
      ...this.snapshot,
      nBonds: t.length / 2,
      bonds: t,
      bondOrders: e
    };
    this.snapshot = a, this.bondRenderer.loadSnapshot({
      ...a,
      positions: s
    }), this.bondScale !== 1 && this.bondRenderer.setScale && this.bondRenderer.setScale(this.bondScale, a);
  }
  /**
   * Replace bond data with optional extended positions/elements (PBC ghost atoms).
   * When positions/elements are provided, they include ghost atoms appended to
   * the original arrays, and bond indices may reference those ghost atoms.
   */
  updateBondsExt(t, e, s, a, o) {
    if (!this.snapshot || !this.bondRenderer) return;
    const c = s ?? this.currentPositions ?? this.snapshot.positions, u = a ?? this.snapshot.elements, d = o || this.snapshot.nAtoms;
    this.bondRenderer.loadSnapshot({
      ...this.snapshot,
      nAtoms: d,
      nBonds: t.length / 2,
      bonds: t,
      bondOrders: e,
      positions: c,
      elements: u
    }), this.bondScale !== 1 && this.bondRenderer.setScale && this.bondRenderer.setScale(this.bondScale, this.snapshot);
  }
  /** Set per-atom labels for overlay display. */
  setLabels(t) {
    var e;
    (e = this.labelOverlay) == null || e.setLabels(t);
  }
  /** Set per-atom vector data for arrow display. */
  setVectors(t) {
    var e;
    (e = this.arrowRenderer) == null || e.setVectors(t);
  }
  /** Set arrow scale multiplier. */
  setVectorScale(t) {
    var e;
    (e = this.arrowRenderer) == null || e.setScale(t);
  }
  /** Load polyhedra mesh data for rendering. */
  loadPolyhedra(t) {
    this.polyhedronRenderer || (this.polyhedronRenderer = new LL(), this.scene.add(this.polyhedronRenderer.group)), this.polyhedronRenderer.loadMeshData(t);
  }
  /** Clear all polyhedra from the scene. */
  clearPolyhedra() {
    this.polyhedronRenderer && this.polyhedronRenderer.clear();
  }
  // ── Structure Layer Management ─────────────────────────────────
  /** Get or create a structure layer for a given node ID. */
  getOrCreateLayer(t) {
    let e = this.layers.get(t);
    return e || (e = new UL(t, this.scene), this.layers.set(t, e)), e;
  }
  /** Get an existing structure layer (or undefined). */
  getLayer(t) {
    return this.layers.get(t);
  }
  /** Remove a structure layer and dispose its resources. */
  removeLayer(t) {
    const e = this.layers.get(t);
    e && (e.dispose(), this.layers.delete(t));
  }
  /** Get all current layer IDs. */
  getLayerIds() {
    return Array.from(this.layers.keys());
  }
  /** Remove layers not in the given set of active IDs. */
  removeInactiveLayers(t) {
    for (const [e, s] of this.layers)
      t.has(e) || (s.dispose(), this.layers.delete(e));
  }
  /**
   * Fit camera to show all structures (from all layers + primary snapshot).
   * Call after loading snapshots into layers.
   */
  fitToViewAll() {
    const t = [];
    this.snapshot && t.push(this.snapshot);
    for (const e of this.layers.values())
      e.snapshot && t.push(e.snapshot);
    t.length !== 0 && this.fitToView(t[0]);
  }
  /** Set atom radius scale multiplier. */
  setAtomScale(t) {
    var e;
    this.atomScale = t, (e = this.atomRenderer) != null && e.setScale && this.snapshot && this.atomRenderer.setScale(t, this.snapshot);
  }
  /** Set atom opacity (independent of bonds). */
  setAtomOpacity(t) {
    var e, s;
    this.atomOpacity = t, (s = (e = this.atomRenderer) == null ? void 0 : e.setOpacity) == null || s.call(e, t);
  }
  /** Set per-atom scale overrides from selection pipeline. */
  setAtomScaleOverrides(t) {
    var e, s;
    (s = (e = this.atomRenderer) == null ? void 0 : e.setScaleOverrides) == null || s.call(e, t);
  }
  /** Set per-atom opacity overrides from selection pipeline. */
  setAtomOpacityOverrides(t) {
    var e, s;
    (s = (e = this.atomRenderer) == null ? void 0 : e.setOpacityOverrides) == null || s.call(e, t);
  }
  /** Clear all per-atom overrides, reverting to global uniforms. */
  clearAtomOverrides() {
    var t, e;
    (e = (t = this.atomRenderer) == null ? void 0 : t.clearOverrides) == null || e.call(t);
  }
  /** Set bond radius scale multiplier. */
  setBondScale(t) {
    var e;
    this.bondScale = t, (e = this.bondRenderer) != null && e.setScale && this.snapshot && this.bondRenderer.setScale(t, this.snapshot);
  }
  /** Set bond opacity (independent of atoms). */
  setBondOpacity(t) {
    var e, s;
    this.bondOpacity = t, (s = (e = this.bondRenderer) == null ? void 0 : e.setOpacity) == null || s.call(e, t);
  }
  /** Apply per-bond opacity overrides (one value per logical bond). */
  setBondOpacityOverrides(t) {
    var e, s;
    (s = (e = this.bondRenderer) == null ? void 0 : e.setBondOpacityOverrides) == null || s.call(e, t);
  }
  /** Clear per-bond opacity overrides, reverting to global opacity. */
  clearBondOpacityOverrides() {
    var t, e;
    (e = (t = this.bondRenderer) == null ? void 0 : t.clearBondOpacityOverrides) == null || e.call(t);
  }
  /** Toggle atom visibility. */
  setAtomsVisible(t) {
    this.atomRenderer && (this.atomRenderer.mesh.visible = t);
  }
  /** Toggle bond visibility. */
  setBondsVisible(t) {
    this.bondRenderer && (this.bondRenderer.mesh.visible = t);
  }
  /** Toggle simulation cell visibility. */
  setCellVisible(t) {
    this.cellRenderer && this.cellRenderer.setVisible(t);
  }
  /** Check if cell data exists. */
  hasCell() {
    return this.cellRenderer !== null && this.cellRenderer.mesh.visible;
  }
  /** Toggle cell axes indicator visibility. */
  setCellAxesVisible(t) {
    this.cellAxesRenderer && this.cellAxesRenderer.setVisible(t);
  }
  // ── Axes inset drag API ───────────────────────────────────
  /** Returns true if the CSS-pixel coordinate hits the axes inset. */
  hitTestAxesInset(t, e) {
    return !this.cellAxesRenderer || !this.container ? !1 : this.cellAxesRenderer.hitTest(t, e, this.container.clientHeight);
  }
  /** Begin an axes-inset drag at the given CSS coordinates. */
  startAxesDrag(t, e) {
    this.axesDragging = !0, this.axesDragLastX = t, this.axesDragLastY = e, this.controls.enabled = !1;
  }
  /** Continue an axes-inset drag. Returns true if currently dragging. */
  moveAxesDrag(t, e) {
    if (!this.axesDragging || !this.cellAxesRenderer || !this.container) return !1;
    const s = t - this.axesDragLastX, a = e - this.axesDragLastY;
    return this.axesDragLastX = t, this.axesDragLastY = e, this.cellAxesRenderer.moveBy(s, a, this.container.clientWidth, this.container.clientHeight), !0;
  }
  /** End the axes-inset drag. */
  endAxesDrag() {
    this.axesDragging && (this.axesDragging = !1, this.controls.enabled = !0);
  }
  /** Whether an axes drag is in progress. */
  isAxesDragging() {
    return this.axesDragging;
  }
  /** Check if cell axes data exists. */
  hasCellAxes() {
    return this.cellAxesRenderer !== null;
  }
  /** Swap between InstancedMesh and Impostor renderers. */
  swapRenderers(t) {
    var a, o, c, u;
    this.atomRenderer && (this.scene.remove(this.atomRenderer.mesh), this.atomRenderer.dispose()), this.bondRenderer && (this.scene.remove(this.bondRenderer.mesh), this.bondRenderer.dispose()), this.useImpostor = t;
    const e = new YM(), s = new jM();
    this.atomRenderer = e, this.bondRenderer = s, this.scene.add(this.atomRenderer.mesh), this.scene.add(this.bondRenderer.mesh), this.atomOpacity !== 1 && ((o = (a = this.atomRenderer).setOpacity) == null || o.call(a, this.atomOpacity)), this.bondOpacity !== 1 && ((u = (c = this.bondRenderer).setOpacity) == null || u.call(c, this.bondOpacity));
  }
  /** Fit camera to show all atoms (or simulation cell if present). */
  fitToView(t) {
    this.lastExtent = GL(this.camera, this.controls, t), this.camera instanceof ns && this.doApplyFrustumInsets();
  }
  /** Reset view to fit all atoms. */
  resetView() {
    this.snapshot && this.fitToView(this.snapshot);
  }
  /** Set the rotation center (orbit target) to the given world coordinates. */
  setRotationCenter(t, e, s) {
    this.controls.target.set(t, e, s), this.controls.update();
  }
  /** Set pixel insets for overlay panels that occlude viewport edges. */
  setViewInsets(t, e) {
    this.viewInsetLeft = t, this.viewInsetRight = e, this.doApplyFrustumInsets();
  }
  /** Recalculate the orthographic frustum accounting for overlay insets. */
  doApplyFrustumInsets() {
    this.camera instanceof ns && this.container && kL(
      this.camera,
      this.container.clientWidth,
      this.container.clientHeight,
      this.viewInsetLeft,
      this.viewInsetRight,
      this.lastExtent
    );
  }
  /** Switch between orthographic and perspective projection. */
  setPerspective(t) {
    if (this.perspectiveMode === t || (this.perspectiveMode = t, !this.container)) return;
    const e = this.controls.target.clone(), s = XL(
      this.camera,
      t,
      this.container.clientWidth,
      this.container.clientHeight
    ), a = this.controls.enableDamping, o = this.controls.dampingFactor, c = this.controls.rotateSpeed, u = this.controls.zoomSpeed;
    this.controls.dispose(), this.camera = s, this.controls = new wb(this.camera, this.renderer.domElement), this.controls.enableDamping = a, this.controls.dampingFactor = o, this.controls.rotateSpeed = c, this.controls.zoomSpeed = u, this.controls.target.copy(e), this.controls.update(), this.snapshot && this.fitToView(this.snapshot);
  }
  /** Get the canvas element for event listener attachment. */
  getCanvas() {
    var t;
    return ((t = this.renderer) == null ? void 0 : t.domElement) ?? null;
  }
  /** Get the Three.js scene. */
  getScene() {
    return this.scene;
  }
  /** Get the active camera. */
  getCamera() {
    return this.camera;
  }
  /** Get the WebGL renderer. */
  getRenderer() {
    return this.renderer;
  }
  /** Get the label overlay canvas. */
  getLabelOverlay() {
    return this.labelOverlay;
  }
  /**
   * Render a single frame synchronously at the current (or custom) size.
   * Used for image/video capture outside the rAF loop.
   */
  renderSingleFrame() {
    if (this.controls.update(), this.polyhedronRenderer && this.container) {
      const s = new ae();
      this.renderer.getSize(s), this.polyhedronRenderer.updateResolution(s.x, s.y);
    }
    this.renderer.render(this.scene, this.camera);
    const t = new ae();
    this.renderer.getSize(t);
    const e = this.renderer.getPixelRatio();
    if (this.cellAxesRenderer)
      try {
        this.cellAxesRenderer.render(this.renderer, this.camera, t.x, t.y);
      } catch (s) {
        console.warn("CellAxesRenderer render error:", s);
      }
    this.labelOverlay && this.labelOverlay.render(this.camera, t.x, t.y, e);
  }
  /**
   * Temporarily resize the renderer for capture, suppressing auto-resize.
   * Returns a restore function to call after capture is complete.
   */
  resizeForCapture(t, e) {
    var c;
    const s = this.lastContainerW, a = this.lastContainerH, o = this.lastDpr;
    if (this.renderer.setPixelRatio(1), this.renderer.setSize(t, e, !1), (c = this.labelOverlay) == null || c.resize(t, e, 1), this.camera instanceof ns) {
      const u = t / e, d = (this.camera.top - this.camera.bottom) / 2;
      this.camera.left = -d * u, this.camera.right = d * u, this.camera.updateProjectionMatrix();
    } else
      this.camera.aspect = t / e, this.camera.updateProjectionMatrix();
    return this.lastContainerW = t, this.lastContainerH = e, this.lastDpr = 1, () => {
      this.lastContainerW = s, this.lastContainerH = a, this.lastDpr = o, this.onResize();
    };
  }
  /** Get a copy of current atom positions (public, for external use). */
  getCurrentPositionsCopy() {
    return this.snapshot ? new Float32Array(this.currentPositions ?? this.snapshot.positions) : null;
  }
  /** Get current atom positions (may reflect trajectory frame). */
  getCurrentPositions() {
    return this.currentPositions ?? this.snapshot.positions;
  }
  // ---- Raycasting ----
  /** Perform a pick at the given screen coordinates using CPU screen-space projection. */
  raycastAtPixel(t, e) {
    return !this.container || !this.snapshot ? null : IL(
      this.camera,
      this.container,
      this.snapshot,
      this.getCurrentPositions(),
      this.atomScale,
      t,
      e
    );
  }
  // ---- Selection & Measurement ----
  /** Toggle atom selection (right-click). Returns new selection state. */
  toggleAtomSelection(t) {
    const e = this.selectedAtoms.indexOf(t);
    return e >= 0 ? this.selectedAtoms.splice(e, 1) : (this.selectedAtoms.length >= 4 && this.selectedAtoms.shift(), this.selectedAtoms.push(t)), this.updateSelectionVisuals(), { atoms: [...this.selectedAtoms] };
  }
  /** Set selected atoms directly (for external triggers). Returns new selection state. */
  setSelection(t) {
    return this.selectedAtoms = t.slice(0, 4), this.updateSelectionVisuals(), { atoms: [...this.selectedAtoms] };
  }
  /** Clear all selected atoms. */
  clearSelection() {
    this.selectedAtoms = [], this.updateSelectionVisuals();
  }
  /** Compute the current geometric measurement based on selected atoms. */
  getMeasurement() {
    return !this.snapshot || this.selectedAtoms.length < 2 ? null : HL(this.getCurrentPositions(), this.selectedAtoms);
  }
  updateSelectionVisuals() {
    for (; this.selectionGroup.children.length > 0; ) {
      const s = this.selectionGroup.children[0];
      this.selectionGroup.remove(s), (s instanceof Ln || s instanceof Gc) && (s.geometry.dispose(), Array.isArray(s.material) ? s.material.forEach((a) => a.dispose()) : s.material.dispose());
    }
    if (!this.snapshot || this.selectedAtoms.length === 0) return;
    const t = this.getCurrentPositions(), e = this.snapshot.elements;
    for (const s of this.selectedAtoms) {
      const a = ov(e[s]) * av * 1.6, o = new tv(a, 16, 16), c = new Yd({
        color: 4359668,
        transparent: !0,
        opacity: 0.35,
        depthWrite: !1
      }), u = new Ln(o, c);
      u.position.set(t[s * 3], t[s * 3 + 1], t[s * 3 + 2]), this.selectionGroup.add(u);
    }
    if (this.selectedAtoms.length >= 2) {
      const s = this.selectedAtoms.map(
        (u) => new st(t[u * 3], t[u * 3 + 1], t[u * 3 + 2])
      ), a = new In().setFromPoints(s), o = new jd({
        color: 4359668,
        depthTest: !1
      }), c = new Gc(a, o);
      c.renderOrder = 999, this.selectionGroup.add(c);
    }
  }
  setupDprListener() {
    const t = () => {
      var e;
      this.onResize(), (e = this.dprMediaQuery) == null || e.removeEventListener("change", t), this.dprMediaQuery = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`), this.dprChangeHandler = t, this.dprMediaQuery.addEventListener("change", t);
    };
    this.dprMediaQuery = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`), this.dprChangeHandler = t, this.dprMediaQuery.addEventListener("change", t);
  }
  onResize() {
    var a;
    if (!this.container) return;
    const t = this.container.clientWidth, e = this.container.clientHeight;
    if (t === 0 || e === 0) return;
    const s = Math.min(window.devicePixelRatio, 2);
    this.lastContainerW = t, this.lastContainerH = e, this.lastDpr = s, this.renderer.setPixelRatio(s), this.camera instanceof ns ? this.doApplyFrustumInsets() : (this.camera.aspect = t / e, this.camera.updateProjectionMatrix()), this.renderer.setSize(t, e, !1), (a = this.labelOverlay) == null || a.resize(t, e, s);
  }
  /** Clean up all resources. */
  dispose() {
    this.animationId !== null && cancelAnimationFrame(this.animationId), this.clearSelection(), this.atomRenderer && this.atomRenderer.dispose(), this.bondRenderer && this.bondRenderer.dispose(), this.cellRenderer && this.cellRenderer.dispose(), this.cellAxesRenderer && this.cellAxesRenderer.dispose(), this.arrowRenderer && this.arrowRenderer.dispose(), this.polyhedronRenderer && this.polyhedronRenderer.dispose(), this.labelOverlay && this.labelOverlay.dispose();
    for (const t of this.layers.values())
      t.dispose();
    this.layers.clear(), this.dprMediaQuery && this.dprChangeHandler && this.dprMediaQuery.removeEventListener("change", this.dprChangeHandler), this.controls.dispose(), this.renderer.dispose(), this.container && this.renderer.domElement.parentNode && this.container.removeChild(this.renderer.domElement);
  }
}
function KM({
  snapshot: n,
  frame: t,
  atomLabels: e,
  atomVectors: s,
  onRendererReady: a,
  onHover: o,
  onAtomRightClick: c,
  onFrameUpdated: u
}) {
  const d = vt.useRef(null), h = vt.useRef(null), m = vt.useRef(o), p = vt.useRef(c), g = vt.useRef(u);
  return m.current = o, p.current = c, g.current = u, vt.useEffect(() => {
    if (!d.current) return;
    const _ = new WL();
    return _.mount(d.current), h.current = _, a == null || a(_), () => {
      _.dispose(), h.current = null;
    };
  }, []), vt.useEffect(() => {
    const _ = h.current, x = _ == null ? void 0 : _.getCanvas();
    if (!x || !_) return;
    let A = null;
    const b = (L) => {
      A === null && (A = requestAnimationFrame(() => {
        var R;
        const z = _.raycastAtPixel(L.clientX, L.clientY);
        (R = m.current) == null || R.call(m, z), A = null;
      }));
    }, y = (L) => {
      var R;
      L.preventDefault();
      const z = _.raycastAtPixel(L.clientX, L.clientY);
      z && z.kind === "atom" && ((R = p.current) == null || R.call(p, z.atomIndex));
    }, E = () => {
      var L;
      (L = m.current) == null || L.call(m, null);
    }, w = (L) => {
      const z = _.raycastAtPixel(L.clientX, L.clientY);
      if (z && z.kind === "atom") {
        const R = _.getCurrentPositionsCopy();
        if (R) {
          const B = z.atomIndex;
          _.setRotationCenter(
            R[B * 3],
            R[B * 3 + 1],
            R[B * 3 + 2]
          );
        }
      }
    }, M = d.current, O = (L) => {
      const z = M.getBoundingClientRect();
      return { x: L.clientX - z.left, y: L.clientY - z.top };
    }, C = (L) => {
      var B, H;
      const { x: z, y: R } = O(L);
      _.hitTestAxesInset(z, R) && (L.preventDefault(), _.startAxesDrag(z, R), (H = (B = L.target) == null ? void 0 : B.setPointerCapture) == null || H.call(B, L.pointerId));
    }, D = (L) => {
      if (_.isAxesDragging()) {
        const { x: z, y: R } = O(L);
        _.moveAxesDrag(z, R);
      }
    }, T = (L) => {
      _.endAxesDrag();
    };
    return x.addEventListener("mousemove", b), x.addEventListener("contextmenu", y), x.addEventListener("mouseleave", E), x.addEventListener("dblclick", w), x.addEventListener("pointerdown", C), x.addEventListener("pointermove", D), x.addEventListener("pointerup", T), x.addEventListener("pointercancel", T), () => {
      x.removeEventListener("mousemove", b), x.removeEventListener("contextmenu", y), x.removeEventListener("mouseleave", E), x.removeEventListener("dblclick", w), x.removeEventListener("pointerdown", C), x.removeEventListener("pointermove", D), x.removeEventListener("pointerup", T), x.removeEventListener("pointercancel", T), A !== null && cancelAnimationFrame(A);
    };
  }, []), vt.useEffect(() => {
    n && h.current && h.current.loadSnapshot(n);
  }, [n]), vt.useEffect(() => {
    var _;
    t && h.current && (h.current.updateFrame(t), (_ = g.current) == null || _.call(g));
  }, [t]), vt.useEffect(() => {
    var _;
    (_ = h.current) == null || _.setLabels(e ?? null);
  }, [e]), vt.useEffect(() => {
    var _;
    (_ = h.current) == null || _.setVectors(s ?? null);
  }, [s]), /* @__PURE__ */ _t.jsx(
    "div",
    {
      ref: d,
      style: {
        width: "100%",
        height: "100%",
        position: "relative",
        background: "#ffffff"
      }
    }
  );
}
function QM({
  currentFrame: n,
  totalFrames: t,
  playing: e,
  fps: s,
  onSeek: a,
  onPlayPause: o,
  onFpsChange: c
}) {
  return t <= 1 ? null : /* @__PURE__ */ _t.jsxs(
    "div",
    {
      style: {
        position: "absolute",
        bottom: 0,
        left: 0,
        right: 0,
        padding: "10px 20px 14px",
        background: "rgba(255, 255, 255, 0.88)",
        backdropFilter: "blur(16px)",
        WebkitBackdropFilter: "blur(16px)",
        borderTop: "1px solid rgba(226,232,240,0.6)",
        boxShadow: "0 -1px 8px rgba(0,0,0,0.04)",
        display: "flex",
        alignItems: "center",
        gap: 12,
        zIndex: 10,
        fontSize: 13,
        color: "#64748b"
      },
      children: [
        /* @__PURE__ */ _t.jsx(
          "button",
          {
            onClick: o,
            style: {
              background: "none",
              border: "1px solid #e2e8f0",
              borderRadius: 8,
              width: 32,
              height: 32,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: 14,
              fontWeight: 500,
              color: "#64748b",
              flexShrink: 0,
              transition: "all 0.15s"
            },
            title: e ? "Pause" : "Play",
            children: e ? "⏸" : "▶"
          }
        ),
        /* @__PURE__ */ _t.jsxs(
          "span",
          {
            style: {
              minWidth: 80,
              textAlign: "center",
              fontVariantNumeric: "tabular-nums",
              fontWeight: 500,
              color: "#64748b",
              flexShrink: 0
            },
            children: [
              n + 1,
              " / ",
              t
            ]
          }
        ),
        /* @__PURE__ */ _t.jsx(
          "input",
          {
            type: "range",
            min: 0,
            max: t - 1,
            value: n,
            onChange: (u) => a(parseInt(u.target.value, 10)),
            style: {
              flex: 1,
              height: 4,
              cursor: "pointer",
              accentColor: "#3b82f6"
            }
          }
        ),
        /* @__PURE__ */ _t.jsxs(
          "select",
          {
            value: s,
            onChange: (u) => c(parseInt(u.target.value, 10)),
            style: {
              background: "rgba(255,255,255,0.8)",
              border: "1px solid #e2e8f0",
              borderRadius: 6,
              padding: "2px 6px",
              fontSize: 12,
              fontWeight: 500,
              color: "#64748b",
              cursor: "pointer",
              flexShrink: 0
            },
            children: [
              /* @__PURE__ */ _t.jsx("option", { value: 10, children: "10 fps" }),
              /* @__PURE__ */ _t.jsx("option", { value: 20, children: "20 fps" }),
              /* @__PURE__ */ _t.jsx("option", { value: 30, children: "30 fps" }),
              /* @__PURE__ */ _t.jsx("option", { value: 60, children: "60 fps" })
            ]
          }
        )
      ]
    }
  );
}
function lv(n) {
  const [t, e, s, a, o, c, u, d, h] = n, m = t * (o * h - c * d) - e * (a * h - c * u) + s * (a * d - o * u);
  if (Math.abs(m) < 1e-20) return null;
  const p = 1 / m;
  return new Float32Array([
    (o * h - c * d) * p,
    (s * d - e * h) * p,
    (e * c - s * o) * p,
    (c * u - a * h) * p,
    (t * h - s * u) * p,
    (s * a - t * c) * p,
    (a * d - o * u) * p,
    (e * u - t * d) * p,
    (t * o - e * a) * p
  ]);
}
const YL = 0.6, kb = 0.4, ir = 2;
function JM(n, t, e, s = YL, a = null) {
  if (e < 2) return new Uint32Array(0);
  const o = a !== null && a.some((y) => y !== 0), c = o ? lv(a) : null, u = o && c !== null;
  let d, h, m;
  if (u) {
    const y = Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]), E = Math.sqrt(a[3] * a[3] + a[4] * a[4] + a[5] * a[5]), w = Math.sqrt(a[6] * a[6] + a[7] * a[7] + a[8] * a[8]);
    d = Math.max(1, Math.floor(y / ir)), h = Math.max(1, Math.floor(E / ir)), m = Math.max(1, Math.floor(w / ir));
  } else {
    let y = 1 / 0, E = 1 / 0, w = 1 / 0, M = -1 / 0, O = -1 / 0, C = -1 / 0;
    for (let D = 0; D < e; D++) {
      const T = n[D * 3], L = n[D * 3 + 1], z = n[D * 3 + 2];
      T < y && (y = T), L < E && (E = L), z < w && (w = z), T > M && (M = T), L > O && (O = L), z > C && (C = z);
    }
    d = Math.max(1, Math.floor((M - y) / ir) + 1), h = Math.max(1, Math.floor((O - E) / ir) + 1), m = Math.max(1, Math.floor((C - w) / ir) + 1);
  }
  const p = d * h * m, g = new Array(p);
  for (let y = 0; y < p; y++) g[y] = [];
  if (u)
    for (let y = 0; y < e; y++) {
      const E = n[y * 3], w = n[y * 3 + 1], M = n[y * 3 + 2];
      let O = c[0] * E + c[3] * w + c[6] * M, C = c[1] * E + c[4] * w + c[7] * M, D = c[2] * E + c[5] * w + c[8] * M;
      O = O - Math.floor(O), C = C - Math.floor(C), D = D - Math.floor(D);
      const T = Math.min(Math.floor(O * d), d - 1), L = Math.min(Math.floor(C * h), h - 1), z = Math.min(Math.floor(D * m), m - 1);
      g[T * h * m + L * m + z].push(y);
    }
  else {
    let y = 1 / 0, E = 1 / 0, w = 1 / 0;
    for (let M = 0; M < e; M++)
      n[M * 3] < y && (y = n[M * 3]), n[M * 3 + 1] < E && (E = n[M * 3 + 1]), n[M * 3 + 2] < w && (w = n[M * 3 + 2]);
    for (let M = 0; M < e; M++) {
      const O = Math.min(Math.floor((n[M * 3] - y) / ir), d - 1), C = Math.min(Math.floor((n[M * 3 + 1] - E) / ir), h - 1), D = Math.min(Math.floor((n[M * 3 + 2] - w) / ir), m - 1);
      g[O * h * m + C * m + D].push(M);
    }
  }
  const _ = [
    [0, 0, 1],
    [0, 1, -1],
    [0, 1, 0],
    [0, 1, 1],
    [1, -1, -1],
    [1, -1, 0],
    [1, -1, 1],
    [1, 0, -1],
    [1, 0, 0],
    [1, 0, 1],
    [1, 1, -1],
    [1, 1, 0],
    [1, 1, 1]
  ], x = kb * kb, A = [];
  function b(y, E) {
    const w = x0[t[y]] ?? S0, M = x0[t[E]] ?? S0, O = (w + M) * s, C = O * O;
    let D = n[E * 3] - n[y * 3], T = n[E * 3 + 1] - n[y * 3 + 1], L = n[E * 3 + 2] - n[y * 3 + 2];
    if (u) {
      let R = c[0] * D + c[3] * T + c[6] * L, B = c[1] * D + c[4] * T + c[7] * L, H = c[2] * D + c[5] * T + c[8] * L;
      R -= Math.round(R), B -= Math.round(B), H -= Math.round(H), D = a[0] * R + a[3] * B + a[6] * H, T = a[1] * R + a[4] * B + a[7] * H, L = a[2] * R + a[5] * B + a[8] * H;
    }
    const z = D * D + T * T + L * L;
    if (z > x && z <= C) {
      const R = y < E ? y : E, B = y < E ? E : y;
      A.push(R, B);
    }
  }
  for (let y = 0; y < d; y++)
    for (let E = 0; E < h; E++)
      for (let w = 0; w < m; w++) {
        const M = y * h * m + E * m + w, O = g[M];
        for (let C = 0; C < O.length; C++)
          for (let D = C + 1; D < O.length; D++)
            b(O[C], O[D]);
        for (const [C, D, T] of _) {
          const L = y + C, z = E + D, R = w + T;
          if (u) {
            const B = (L % d + d) % d, H = (z % h + h) % h, U = (R % m + m) % m, V = B * h * m + H * m + U;
            if (V === M) continue;
            const N = g[V];
            for (const I of O)
              for (const k of N)
                b(I, k);
          } else {
            if (L < 0 || L >= d || z < 0 || z >= h || R < 0 || R >= m) continue;
            const B = L * h * m + z * m + R, H = g[B];
            for (const U of O)
              for (const V of H)
                b(U, V);
          }
        }
      }
  return new Uint32Array(A);
}
function b0(n, t, e, s, a, o) {
  if (!o || !o.some((T) => T !== 0))
    return {
      bondIndices: n,
      bondOrders: t,
      nBonds: n.length / 2,
      positions: null,
      elements: null,
      nAtoms: 0
    };
  const c = lv(o);
  if (!c)
    return {
      bondIndices: n,
      bondOrders: t,
      nBonds: n.length / 2,
      positions: null,
      elements: null,
      nAtoms: 0
    };
  const u = Math.sqrt(o[0] * o[0] + o[1] * o[1] + o[2] * o[2]), d = Math.sqrt(o[3] * o[3] + o[4] * o[4] + o[5] * o[5]), h = Math.sqrt(o[6] * o[6] + o[7] * o[7] + o[8] * o[8]), m = Math.min(u, d, h) / 2, p = m * m, g = n.length / 2;
  let _ = 0, x = 0;
  for (let T = 0; T < g; T++) {
    const L = n[T * 2], z = n[T * 2 + 1], R = e[z * 3] - e[L * 3], B = e[z * 3 + 1] - e[L * 3 + 1], H = e[z * 3 + 2] - e[L * 3 + 2];
    R * R + B * B + H * H > p ? x++ : _++;
  }
  if (x === 0)
    return {
      bondIndices: n,
      bondOrders: t,
      nBonds: g,
      positions: null,
      elements: null,
      nAtoms: 0
    };
  const A = _ + x * 2, b = new Uint32Array(A * 2), y = t ? new Uint8Array(A) : null, E = [], w = [];
  let M = a, O = 0;
  for (let T = 0; T < g; T++) {
    const L = n[T * 2], z = n[T * 2 + 1], R = e[z * 3] - e[L * 3], B = e[z * 3 + 1] - e[L * 3 + 1], H = e[z * 3 + 2] - e[L * 3 + 2];
    if (R * R + B * B + H * H <= p)
      b[O * 2] = L, b[O * 2 + 1] = z, y && t && (y[O] = t[T]), O++;
    else {
      let V = c[0] * R + c[3] * B + c[6] * H, N = c[1] * R + c[4] * B + c[7] * H, I = c[2] * R + c[5] * B + c[8] * H;
      V -= Math.round(V), N -= Math.round(N), I -= Math.round(I);
      const k = o[0] * V + o[3] * N + o[6] * I, X = o[1] * V + o[4] * N + o[7] * I, Q = o[2] * V + o[5] * N + o[8] * I;
      E.push(
        e[L * 3] + k,
        e[L * 3 + 1] + X,
        e[L * 3 + 2] + Q
      ), w.push(s[z]), b[O * 2] = L, b[O * 2 + 1] = M, y && t && (y[O] = t[T]), O++, M++, E.push(
        e[z * 3] - k,
        e[z * 3 + 1] - X,
        e[z * 3 + 2] - Q
      ), w.push(s[L]), b[O * 2] = z, b[O * 2 + 1] = M, y && t && (y[O] = t[T]), O++, M++;
    }
  }
  const C = new Float32Array(e.length + E.length);
  C.set(e), C.set(new Float32Array(E), e.length);
  const D = new Uint8Array(s.length + w.length);
  return D.set(s), D.set(new Uint8Array(w), s.length), {
    bondIndices: b,
    bondOrders: y,
    nBonds: A,
    positions: C,
    elements: D,
    nAtoms: M
  };
}
function jL(n, t) {
  var o;
  const e = /* @__PURE__ */ new Map(), s = (o = t.get("particle")) == null ? void 0 : o[0];
  if (!s) return e;
  const a = s.source;
  if (n.bondSource === "structure") {
    if (a.nFileBonds > 0) {
      let c = a.bonds, u = a.bondOrders, d = a.nBonds, h = null, m = null, p = 0;
      const g = b0(
        c,
        u,
        a.positions,
        a.elements,
        a.nAtoms,
        a.box
      );
      if (c = g.bondIndices, u = g.bondOrders, d = g.nBonds, h = g.positions, m = g.elements, p = g.nAtoms, d > 0) {
        const _ = {
          type: "bond",
          sourceNodeId: s.sourceNodeId,
          bondIndices: c,
          bondOrders: u,
          nBonds: d,
          scale: 1,
          opacity: 1,
          positions: h,
          elements: m,
          nAtoms: p,
          atomElements: a.elements,
          selectedBondIndices: null,
          bondOpacityOverrides: null
        };
        e.set("bond", _);
      }
    }
  } else if (n.bondSource === "distance") {
    let c = JM(
      a.positions,
      a.elements,
      a.nAtoms,
      0.6,
      a.box
    );
    if (c.length > 0) {
      let u = c.length / 2, d = null, h = null, m = 0;
      const p = b0(
        c,
        null,
        a.positions,
        a.elements,
        a.nAtoms,
        a.box
      );
      if (c = p.bondIndices, u = p.nBonds, d = p.positions, h = p.elements, m = p.nAtoms, u > 0) {
        const g = {
          type: "bond",
          sourceNodeId: s.sourceNodeId,
          bondIndices: c,
          bondOrders: null,
          nBonds: u,
          scale: 1,
          opacity: 1,
          positions: d,
          elements: h,
          nAtoms: m,
          atomElements: a.elements,
          selectedBondIndices: null,
          bondOpacityOverrides: null
        };
        e.set("bond", g);
      }
    }
  }
  return e;
}
const Xb = (n) => {
  let t;
  const e = /* @__PURE__ */ new Set(), s = (h, m) => {
    const p = typeof h == "function" ? h(t) : h;
    if (!Object.is(p, t)) {
      const g = t;
      t = m ?? (typeof p != "object" || p === null) ? p : Object.assign({}, t, p), e.forEach((_) => _(t, g));
    }
  }, a = () => t, u = { setState: s, getState: a, getInitialState: () => d, subscribe: (h) => (e.add(h), () => e.delete(h)) }, d = t = n(s, a, u);
  return u;
}, qL = ((n) => n ? Xb(n) : Xb), ZL = (n) => n;
function $L(n, t = ZL) {
  const e = Rc.useSyncExternalStore(
    n.subscribe,
    Rc.useCallback(() => t(n.getState()), [n, t]),
    Rc.useCallback(() => t(n.getInitialState()), [n, t])
  );
  return Rc.useDebugValue(e), e;
}
const Wb = (n) => {
  const t = qL(n), e = (s) => $L(t, s);
  return Object.assign(e, t), e;
}, KL = ((n) => n ? Wb(n) : Wb);
function Rn(n) {
  if (typeof n == "string" || typeof n == "number") return "" + n;
  let t = "";
  if (Array.isArray(n))
    for (let e = 0, s; e < n.length; e++)
      (s = Rn(n[e])) !== "" && (t += (t && " ") + s);
  else
    for (let e in n)
      n[e] && (t += (t && " ") + e);
  return t;
}
var QL = { value: () => {
} };
function Jd() {
  for (var n = 0, t = arguments.length, e = {}, s; n < t; ++n) {
    if (!(s = arguments[n] + "") || s in e || /[\s.]/.test(s)) throw new Error("illegal type: " + s);
    e[s] = [];
  }
  return new vd(e);
}
function vd(n) {
  this._ = n;
}
function JL(n, t) {
  return n.trim().split(/^|\s+/).map(function(e) {
    var s = "", a = e.indexOf(".");
    if (a >= 0 && (s = e.slice(a + 1), e = e.slice(0, a)), e && !t.hasOwnProperty(e)) throw new Error("unknown type: " + e);
    return { type: e, name: s };
  });
}
vd.prototype = Jd.prototype = {
  constructor: vd,
  on: function(n, t) {
    var e = this._, s = JL(n + "", e), a, o = -1, c = s.length;
    if (arguments.length < 2) {
      for (; ++o < c; ) if ((a = (n = s[o]).type) && (a = tU(e[a], n.name))) return a;
      return;
    }
    if (t != null && typeof t != "function") throw new Error("invalid callback: " + t);
    for (; ++o < c; )
      if (a = (n = s[o]).type) e[a] = Yb(e[a], n.name, t);
      else if (t == null) for (a in e) e[a] = Yb(e[a], n.name, null);
    return this;
  },
  copy: function() {
    var n = {}, t = this._;
    for (var e in t) n[e] = t[e].slice();
    return new vd(n);
  },
  call: function(n, t) {
    if ((a = arguments.length - 2) > 0) for (var e = new Array(a), s = 0, a, o; s < a; ++s) e[s] = arguments[s + 2];
    if (!this._.hasOwnProperty(n)) throw new Error("unknown type: " + n);
    for (o = this._[n], s = 0, a = o.length; s < a; ++s) o[s].value.apply(t, e);
  },
  apply: function(n, t, e) {
    if (!this._.hasOwnProperty(n)) throw new Error("unknown type: " + n);
    for (var s = this._[n], a = 0, o = s.length; a < o; ++a) s[a].value.apply(t, e);
  }
};
function tU(n, t) {
  for (var e = 0, s = n.length, a; e < s; ++e)
    if ((a = n[e]).name === t)
      return a.value;
}
function Yb(n, t, e) {
  for (var s = 0, a = n.length; s < a; ++s)
    if (n[s].name === t) {
      n[s] = QL, n = n.slice(0, s).concat(n.slice(s + 1));
      break;
    }
  return e != null && n.push({ name: t, value: e }), n;
}
var M0 = "http://www.w3.org/1999/xhtml";
const jb = {
  svg: "http://www.w3.org/2000/svg",
  xhtml: M0,
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
};
function th(n) {
  var t = n += "", e = t.indexOf(":");
  return e >= 0 && (t = n.slice(0, e)) !== "xmlns" && (n = n.slice(e + 1)), jb.hasOwnProperty(t) ? { space: jb[t], local: n } : n;
}
function eU(n) {
  return function() {
    var t = this.ownerDocument, e = this.namespaceURI;
    return e === M0 && t.documentElement.namespaceURI === M0 ? t.createElement(n) : t.createElementNS(e, n);
  };
}
function nU(n) {
  return function() {
    return this.ownerDocument.createElementNS(n.space, n.local);
  };
}
function tE(n) {
  var t = th(n);
  return (t.local ? nU : eU)(t);
}
function iU() {
}
function cv(n) {
  return n == null ? iU : function() {
    return this.querySelector(n);
  };
}
function sU(n) {
  typeof n != "function" && (n = cv(n));
  for (var t = this._groups, e = t.length, s = new Array(e), a = 0; a < e; ++a)
    for (var o = t[a], c = o.length, u = s[a] = new Array(c), d, h, m = 0; m < c; ++m)
      (d = o[m]) && (h = n.call(d, d.__data__, m, o)) && ("__data__" in d && (h.__data__ = d.__data__), u[m] = h);
  return new Oi(s, this._parents);
}
function rU(n) {
  return n == null ? [] : Array.isArray(n) ? n : Array.from(n);
}
function aU() {
  return [];
}
function eE(n) {
  return n == null ? aU : function() {
    return this.querySelectorAll(n);
  };
}
function oU(n) {
  return function() {
    return rU(n.apply(this, arguments));
  };
}
function lU(n) {
  typeof n == "function" ? n = oU(n) : n = eE(n);
  for (var t = this._groups, e = t.length, s = [], a = [], o = 0; o < e; ++o)
    for (var c = t[o], u = c.length, d, h = 0; h < u; ++h)
      (d = c[h]) && (s.push(n.call(d, d.__data__, h, c)), a.push(d));
  return new Oi(s, a);
}
function nE(n) {
  return function() {
    return this.matches(n);
  };
}
function iE(n) {
  return function(t) {
    return t.matches(n);
  };
}
var cU = Array.prototype.find;
function uU(n) {
  return function() {
    return cU.call(this.children, n);
  };
}
function fU() {
  return this.firstElementChild;
}
function dU(n) {
  return this.select(n == null ? fU : uU(typeof n == "function" ? n : iE(n)));
}
var hU = Array.prototype.filter;
function pU() {
  return Array.from(this.children);
}
function mU(n) {
  return function() {
    return hU.call(this.children, n);
  };
}
function gU(n) {
  return this.selectAll(n == null ? pU : mU(typeof n == "function" ? n : iE(n)));
}
function vU(n) {
  typeof n != "function" && (n = nE(n));
  for (var t = this._groups, e = t.length, s = new Array(e), a = 0; a < e; ++a)
    for (var o = t[a], c = o.length, u = s[a] = [], d, h = 0; h < c; ++h)
      (d = o[h]) && n.call(d, d.__data__, h, o) && u.push(d);
  return new Oi(s, this._parents);
}
function sE(n) {
  return new Array(n.length);
}
function _U() {
  return new Oi(this._enter || this._groups.map(sE), this._parents);
}
function Nd(n, t) {
  this.ownerDocument = n.ownerDocument, this.namespaceURI = n.namespaceURI, this._next = null, this._parent = n, this.__data__ = t;
}
Nd.prototype = {
  constructor: Nd,
  appendChild: function(n) {
    return this._parent.insertBefore(n, this._next);
  },
  insertBefore: function(n, t) {
    return this._parent.insertBefore(n, t);
  },
  querySelector: function(n) {
    return this._parent.querySelector(n);
  },
  querySelectorAll: function(n) {
    return this._parent.querySelectorAll(n);
  }
};
function yU(n) {
  return function() {
    return n;
  };
}
function xU(n, t, e, s, a, o) {
  for (var c = 0, u, d = t.length, h = o.length; c < h; ++c)
    (u = t[c]) ? (u.__data__ = o[c], s[c] = u) : e[c] = new Nd(n, o[c]);
  for (; c < d; ++c)
    (u = t[c]) && (a[c] = u);
}
function SU(n, t, e, s, a, o, c) {
  var u, d, h = /* @__PURE__ */ new Map(), m = t.length, p = o.length, g = new Array(m), _;
  for (u = 0; u < m; ++u)
    (d = t[u]) && (g[u] = _ = c.call(d, d.__data__, u, t) + "", h.has(_) ? a[u] = d : h.set(_, d));
  for (u = 0; u < p; ++u)
    _ = c.call(n, o[u], u, o) + "", (d = h.get(_)) ? (s[u] = d, d.__data__ = o[u], h.delete(_)) : e[u] = new Nd(n, o[u]);
  for (u = 0; u < m; ++u)
    (d = t[u]) && h.get(g[u]) === d && (a[u] = d);
}
function bU(n) {
  return n.__data__;
}
function MU(n, t) {
  if (!arguments.length) return Array.from(this, bU);
  var e = t ? SU : xU, s = this._parents, a = this._groups;
  typeof n != "function" && (n = yU(n));
  for (var o = a.length, c = new Array(o), u = new Array(o), d = new Array(o), h = 0; h < o; ++h) {
    var m = s[h], p = a[h], g = p.length, _ = EU(n.call(m, m && m.__data__, h, s)), x = _.length, A = u[h] = new Array(x), b = c[h] = new Array(x), y = d[h] = new Array(g);
    e(m, p, A, b, y, _, t);
    for (var E = 0, w = 0, M, O; E < x; ++E)
      if (M = A[E]) {
        for (E >= w && (w = E + 1); !(O = b[w]) && ++w < x; ) ;
        M._next = O || null;
      }
  }
  return c = new Oi(c, s), c._enter = u, c._exit = d, c;
}
function EU(n) {
  return typeof n == "object" && "length" in n ? n : Array.from(n);
}
function wU() {
  return new Oi(this._exit || this._groups.map(sE), this._parents);
}
function AU(n, t, e) {
  var s = this.enter(), a = this, o = this.exit();
  return typeof n == "function" ? (s = n(s), s && (s = s.selection())) : s = s.append(n + ""), t != null && (a = t(a), a && (a = a.selection())), e == null ? o.remove() : e(o), s && a ? s.merge(a).order() : a;
}
function TU(n) {
  for (var t = n.selection ? n.selection() : n, e = this._groups, s = t._groups, a = e.length, o = s.length, c = Math.min(a, o), u = new Array(a), d = 0; d < c; ++d)
    for (var h = e[d], m = s[d], p = h.length, g = u[d] = new Array(p), _, x = 0; x < p; ++x)
      (_ = h[x] || m[x]) && (g[x] = _);
  for (; d < a; ++d)
    u[d] = e[d];
  return new Oi(u, this._parents);
}
function CU() {
  for (var n = this._groups, t = -1, e = n.length; ++t < e; )
    for (var s = n[t], a = s.length - 1, o = s[a], c; --a >= 0; )
      (c = s[a]) && (o && c.compareDocumentPosition(o) ^ 4 && o.parentNode.insertBefore(c, o), o = c);
  return this;
}
function RU(n) {
  n || (n = DU);
  function t(p, g) {
    return p && g ? n(p.__data__, g.__data__) : !p - !g;
  }
  for (var e = this._groups, s = e.length, a = new Array(s), o = 0; o < s; ++o) {
    for (var c = e[o], u = c.length, d = a[o] = new Array(u), h, m = 0; m < u; ++m)
      (h = c[m]) && (d[m] = h);
    d.sort(t);
  }
  return new Oi(a, this._parents).order();
}
function DU(n, t) {
  return n < t ? -1 : n > t ? 1 : n >= t ? 0 : NaN;
}
function NU() {
  var n = arguments[0];
  return arguments[0] = this, n.apply(null, arguments), this;
}
function OU() {
  return Array.from(this);
}
function LU() {
  for (var n = this._groups, t = 0, e = n.length; t < e; ++t)
    for (var s = n[t], a = 0, o = s.length; a < o; ++a) {
      var c = s[a];
      if (c) return c;
    }
  return null;
}
function UU() {
  let n = 0;
  for (const t of this) ++n;
  return n;
}
function PU() {
  return !this.node();
}
function IU(n) {
  for (var t = this._groups, e = 0, s = t.length; e < s; ++e)
    for (var a = t[e], o = 0, c = a.length, u; o < c; ++o)
      (u = a[o]) && n.call(u, u.__data__, o, a);
  return this;
}
function BU(n) {
  return function() {
    this.removeAttribute(n);
  };
}
function zU(n) {
  return function() {
    this.removeAttributeNS(n.space, n.local);
  };
}
function FU(n, t) {
  return function() {
    this.setAttribute(n, t);
  };
}
function HU(n, t) {
  return function() {
    this.setAttributeNS(n.space, n.local, t);
  };
}
function VU(n, t) {
  return function() {
    var e = t.apply(this, arguments);
    e == null ? this.removeAttribute(n) : this.setAttribute(n, e);
  };
}
function GU(n, t) {
  return function() {
    var e = t.apply(this, arguments);
    e == null ? this.removeAttributeNS(n.space, n.local) : this.setAttributeNS(n.space, n.local, e);
  };
}
function kU(n, t) {
  var e = th(n);
  if (arguments.length < 2) {
    var s = this.node();
    return e.local ? s.getAttributeNS(e.space, e.local) : s.getAttribute(e);
  }
  return this.each((t == null ? e.local ? zU : BU : typeof t == "function" ? e.local ? GU : VU : e.local ? HU : FU)(e, t));
}
function rE(n) {
  return n.ownerDocument && n.ownerDocument.defaultView || n.document && n || n.defaultView;
}
function XU(n) {
  return function() {
    this.style.removeProperty(n);
  };
}
function WU(n, t, e) {
  return function() {
    this.style.setProperty(n, t, e);
  };
}
function YU(n, t, e) {
  return function() {
    var s = t.apply(this, arguments);
    s == null ? this.style.removeProperty(n) : this.style.setProperty(n, s, e);
  };
}
function jU(n, t, e) {
  return arguments.length > 1 ? this.each((t == null ? XU : typeof t == "function" ? YU : WU)(n, t, e ?? "")) : gl(this.node(), n);
}
function gl(n, t) {
  return n.style.getPropertyValue(t) || rE(n).getComputedStyle(n, null).getPropertyValue(t);
}
function qU(n) {
  return function() {
    delete this[n];
  };
}
function ZU(n, t) {
  return function() {
    this[n] = t;
  };
}
function $U(n, t) {
  return function() {
    var e = t.apply(this, arguments);
    e == null ? delete this[n] : this[n] = e;
  };
}
function KU(n, t) {
  return arguments.length > 1 ? this.each((t == null ? qU : typeof t == "function" ? $U : ZU)(n, t)) : this.node()[n];
}
function aE(n) {
  return n.trim().split(/^|\s+/);
}
function uv(n) {
  return n.classList || new oE(n);
}
function oE(n) {
  this._node = n, this._names = aE(n.getAttribute("class") || "");
}
oE.prototype = {
  add: function(n) {
    var t = this._names.indexOf(n);
    t < 0 && (this._names.push(n), this._node.setAttribute("class", this._names.join(" ")));
  },
  remove: function(n) {
    var t = this._names.indexOf(n);
    t >= 0 && (this._names.splice(t, 1), this._node.setAttribute("class", this._names.join(" ")));
  },
  contains: function(n) {
    return this._names.indexOf(n) >= 0;
  }
};
function lE(n, t) {
  for (var e = uv(n), s = -1, a = t.length; ++s < a; ) e.add(t[s]);
}
function cE(n, t) {
  for (var e = uv(n), s = -1, a = t.length; ++s < a; ) e.remove(t[s]);
}
function QU(n) {
  return function() {
    lE(this, n);
  };
}
function JU(n) {
  return function() {
    cE(this, n);
  };
}
function tP(n, t) {
  return function() {
    (t.apply(this, arguments) ? lE : cE)(this, n);
  };
}
function eP(n, t) {
  var e = aE(n + "");
  if (arguments.length < 2) {
    for (var s = uv(this.node()), a = -1, o = e.length; ++a < o; ) if (!s.contains(e[a])) return !1;
    return !0;
  }
  return this.each((typeof t == "function" ? tP : t ? QU : JU)(e, t));
}
function nP() {
  this.textContent = "";
}
function iP(n) {
  return function() {
    this.textContent = n;
  };
}
function sP(n) {
  return function() {
    var t = n.apply(this, arguments);
    this.textContent = t ?? "";
  };
}
function rP(n) {
  return arguments.length ? this.each(n == null ? nP : (typeof n == "function" ? sP : iP)(n)) : this.node().textContent;
}
function aP() {
  this.innerHTML = "";
}
function oP(n) {
  return function() {
    this.innerHTML = n;
  };
}
function lP(n) {
  return function() {
    var t = n.apply(this, arguments);
    this.innerHTML = t ?? "";
  };
}
function cP(n) {
  return arguments.length ? this.each(n == null ? aP : (typeof n == "function" ? lP : oP)(n)) : this.node().innerHTML;
}
function uP() {
  this.nextSibling && this.parentNode.appendChild(this);
}
function fP() {
  return this.each(uP);
}
function dP() {
  this.previousSibling && this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
function hP() {
  return this.each(dP);
}
function pP(n) {
  var t = typeof n == "function" ? n : tE(n);
  return this.select(function() {
    return this.appendChild(t.apply(this, arguments));
  });
}
function mP() {
  return null;
}
function gP(n, t) {
  var e = typeof n == "function" ? n : tE(n), s = t == null ? mP : typeof t == "function" ? t : cv(t);
  return this.select(function() {
    return this.insertBefore(e.apply(this, arguments), s.apply(this, arguments) || null);
  });
}
function vP() {
  var n = this.parentNode;
  n && n.removeChild(this);
}
function _P() {
  return this.each(vP);
}
function yP() {
  var n = this.cloneNode(!1), t = this.parentNode;
  return t ? t.insertBefore(n, this.nextSibling) : n;
}
function xP() {
  var n = this.cloneNode(!0), t = this.parentNode;
  return t ? t.insertBefore(n, this.nextSibling) : n;
}
function SP(n) {
  return this.select(n ? xP : yP);
}
function bP(n) {
  return arguments.length ? this.property("__data__", n) : this.node().__data__;
}
function MP(n) {
  return function(t) {
    n.call(this, t, this.__data__);
  };
}
function EP(n) {
  return n.trim().split(/^|\s+/).map(function(t) {
    var e = "", s = t.indexOf(".");
    return s >= 0 && (e = t.slice(s + 1), t = t.slice(0, s)), { type: t, name: e };
  });
}
function wP(n) {
  return function() {
    var t = this.__on;
    if (t) {
      for (var e = 0, s = -1, a = t.length, o; e < a; ++e)
        o = t[e], (!n.type || o.type === n.type) && o.name === n.name ? this.removeEventListener(o.type, o.listener, o.options) : t[++s] = o;
      ++s ? t.length = s : delete this.__on;
    }
  };
}
function AP(n, t, e) {
  return function() {
    var s = this.__on, a, o = MP(t);
    if (s) {
      for (var c = 0, u = s.length; c < u; ++c)
        if ((a = s[c]).type === n.type && a.name === n.name) {
          this.removeEventListener(a.type, a.listener, a.options), this.addEventListener(a.type, a.listener = o, a.options = e), a.value = t;
          return;
        }
    }
    this.addEventListener(n.type, o, e), a = { type: n.type, name: n.name, value: t, listener: o, options: e }, s ? s.push(a) : this.__on = [a];
  };
}
function TP(n, t, e) {
  var s = EP(n + ""), a, o = s.length, c;
  if (arguments.length < 2) {
    var u = this.node().__on;
    if (u) {
      for (var d = 0, h = u.length, m; d < h; ++d)
        for (a = 0, m = u[d]; a < o; ++a)
          if ((c = s[a]).type === m.type && c.name === m.name)
            return m.value;
    }
    return;
  }
  for (u = t ? AP : wP, a = 0; a < o; ++a) this.each(u(s[a], t, e));
  return this;
}
function uE(n, t, e) {
  var s = rE(n), a = s.CustomEvent;
  typeof a == "function" ? a = new a(t, e) : (a = s.document.createEvent("Event"), e ? (a.initEvent(t, e.bubbles, e.cancelable), a.detail = e.detail) : a.initEvent(t, !1, !1)), n.dispatchEvent(a);
}
function CP(n, t) {
  return function() {
    return uE(this, n, t);
  };
}
function RP(n, t) {
  return function() {
    return uE(this, n, t.apply(this, arguments));
  };
}
function DP(n, t) {
  return this.each((typeof t == "function" ? RP : CP)(n, t));
}
function* NP() {
  for (var n = this._groups, t = 0, e = n.length; t < e; ++t)
    for (var s = n[t], a = 0, o = s.length, c; a < o; ++a)
      (c = s[a]) && (yield c);
}
var fE = [null];
function Oi(n, t) {
  this._groups = n, this._parents = t;
}
function iu() {
  return new Oi([[document.documentElement]], fE);
}
function OP() {
  return this;
}
Oi.prototype = iu.prototype = {
  constructor: Oi,
  select: sU,
  selectAll: lU,
  selectChild: dU,
  selectChildren: gU,
  filter: vU,
  data: MU,
  enter: _U,
  exit: wU,
  join: AU,
  merge: TU,
  selection: OP,
  order: CU,
  sort: RU,
  call: NU,
  nodes: OU,
  node: LU,
  size: UU,
  empty: PU,
  each: IU,
  attr: kU,
  style: jU,
  property: KU,
  classed: eP,
  text: rP,
  html: cP,
  raise: fP,
  lower: hP,
  append: pP,
  insert: gP,
  remove: _P,
  clone: SP,
  datum: bP,
  on: TP,
  dispatch: DP,
  [Symbol.iterator]: NP
};
function Ri(n) {
  return typeof n == "string" ? new Oi([[document.querySelector(n)]], [document.documentElement]) : new Oi([[n]], fE);
}
function LP(n) {
  let t;
  for (; t = n.sourceEvent; ) n = t;
  return n;
}
function ts(n, t) {
  if (n = LP(n), t === void 0 && (t = n.currentTarget), t) {
    var e = t.ownerSVGElement || t;
    if (e.createSVGPoint) {
      var s = e.createSVGPoint();
      return s.x = n.clientX, s.y = n.clientY, s = s.matrixTransform(t.getScreenCTM().inverse()), [s.x, s.y];
    }
    if (t.getBoundingClientRect) {
      var a = t.getBoundingClientRect();
      return [n.clientX - a.left - t.clientLeft, n.clientY - a.top - t.clientTop];
    }
  }
  return [n.pageX, n.pageY];
}
const UP = { passive: !1 }, Yc = { capture: !0, passive: !1 };
function ug(n) {
  n.stopImmediatePropagation();
}
function cl(n) {
  n.preventDefault(), n.stopImmediatePropagation();
}
function dE(n) {
  var t = n.document.documentElement, e = Ri(n).on("dragstart.drag", cl, Yc);
  "onselectstart" in t ? e.on("selectstart.drag", cl, Yc) : (t.__noselect = t.style.MozUserSelect, t.style.MozUserSelect = "none");
}
function hE(n, t) {
  var e = n.document.documentElement, s = Ri(n).on("dragstart.drag", null);
  t && (s.on("click.drag", cl, Yc), setTimeout(function() {
    s.on("click.drag", null);
  }, 0)), "onselectstart" in e ? s.on("selectstart.drag", null) : (e.style.MozUserSelect = e.__noselect, delete e.__noselect);
}
const ed = (n) => () => n;
function E0(n, {
  sourceEvent: t,
  subject: e,
  target: s,
  identifier: a,
  active: o,
  x: c,
  y: u,
  dx: d,
  dy: h,
  dispatch: m
}) {
  Object.defineProperties(this, {
    type: { value: n, enumerable: !0, configurable: !0 },
    sourceEvent: { value: t, enumerable: !0, configurable: !0 },
    subject: { value: e, enumerable: !0, configurable: !0 },
    target: { value: s, enumerable: !0, configurable: !0 },
    identifier: { value: a, enumerable: !0, configurable: !0 },
    active: { value: o, enumerable: !0, configurable: !0 },
    x: { value: c, enumerable: !0, configurable: !0 },
    y: { value: u, enumerable: !0, configurable: !0 },
    dx: { value: d, enumerable: !0, configurable: !0 },
    dy: { value: h, enumerable: !0, configurable: !0 },
    _: { value: m }
  });
}
E0.prototype.on = function() {
  var n = this._.on.apply(this._, arguments);
  return n === this._ ? this : n;
};
function PP(n) {
  return !n.ctrlKey && !n.button;
}
function IP() {
  return this.parentNode;
}
function BP(n, t) {
  return t ?? { x: n.x, y: n.y };
}
function zP() {
  return navigator.maxTouchPoints || "ontouchstart" in this;
}
function pE() {
  var n = PP, t = IP, e = BP, s = zP, a = {}, o = Jd("start", "drag", "end"), c = 0, u, d, h, m, p = 0;
  function g(M) {
    M.on("mousedown.drag", _).filter(s).on("touchstart.drag", b).on("touchmove.drag", y, UP).on("touchend.drag touchcancel.drag", E).style("touch-action", "none").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }
  function _(M, O) {
    if (!(m || !n.call(this, M, O))) {
      var C = w(this, t.call(this, M, O), M, O, "mouse");
      C && (Ri(M.view).on("mousemove.drag", x, Yc).on("mouseup.drag", A, Yc), dE(M.view), ug(M), h = !1, u = M.clientX, d = M.clientY, C("start", M));
    }
  }
  function x(M) {
    if (cl(M), !h) {
      var O = M.clientX - u, C = M.clientY - d;
      h = O * O + C * C > p;
    }
    a.mouse("drag", M);
  }
  function A(M) {
    Ri(M.view).on("mousemove.drag mouseup.drag", null), hE(M.view, h), cl(M), a.mouse("end", M);
  }
  function b(M, O) {
    if (n.call(this, M, O)) {
      var C = M.changedTouches, D = t.call(this, M, O), T = C.length, L, z;
      for (L = 0; L < T; ++L)
        (z = w(this, D, M, O, C[L].identifier, C[L])) && (ug(M), z("start", M, C[L]));
    }
  }
  function y(M) {
    var O = M.changedTouches, C = O.length, D, T;
    for (D = 0; D < C; ++D)
      (T = a[O[D].identifier]) && (cl(M), T("drag", M, O[D]));
  }
  function E(M) {
    var O = M.changedTouches, C = O.length, D, T;
    for (m && clearTimeout(m), m = setTimeout(function() {
      m = null;
    }, 500), D = 0; D < C; ++D)
      (T = a[O[D].identifier]) && (ug(M), T("end", M, O[D]));
  }
  function w(M, O, C, D, T, L) {
    var z = o.copy(), R = ts(L || C, O), B, H, U;
    if ((U = e.call(M, new E0("beforestart", {
      sourceEvent: C,
      target: g,
      identifier: T,
      active: c,
      x: R[0],
      y: R[1],
      dx: 0,
      dy: 0,
      dispatch: z
    }), D)) != null)
      return B = U.x - R[0] || 0, H = U.y - R[1] || 0, function V(N, I, k) {
        var X = R, Q;
        switch (N) {
          case "start":
            a[T] = V, Q = c++;
            break;
          case "end":
            delete a[T], --c;
          // falls through
          case "drag":
            R = ts(k || I, O), Q = c;
            break;
        }
        z.call(
          N,
          M,
          new E0(N, {
            sourceEvent: I,
            subject: U,
            target: g,
            identifier: T,
            active: Q,
            x: R[0] + B,
            y: R[1] + H,
            dx: R[0] - X[0],
            dy: R[1] - X[1],
            dispatch: z
          }),
          D
        );
      };
  }
  return g.filter = function(M) {
    return arguments.length ? (n = typeof M == "function" ? M : ed(!!M), g) : n;
  }, g.container = function(M) {
    return arguments.length ? (t = typeof M == "function" ? M : ed(M), g) : t;
  }, g.subject = function(M) {
    return arguments.length ? (e = typeof M == "function" ? M : ed(M), g) : e;
  }, g.touchable = function(M) {
    return arguments.length ? (s = typeof M == "function" ? M : ed(!!M), g) : s;
  }, g.on = function() {
    var M = o.on.apply(o, arguments);
    return M === o ? g : M;
  }, g.clickDistance = function(M) {
    return arguments.length ? (p = (M = +M) * M, g) : Math.sqrt(p);
  }, g;
}
function fv(n, t, e) {
  n.prototype = t.prototype = e, e.constructor = n;
}
function mE(n, t) {
  var e = Object.create(n.prototype);
  for (var s in t) e[s] = t[s];
  return e;
}
function su() {
}
var jc = 0.7, Od = 1 / jc, ul = "\\s*([+-]?\\d+)\\s*", qc = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*", Ts = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*", FP = /^#([0-9a-f]{3,8})$/, HP = new RegExp(`^rgb\\(${ul},${ul},${ul}\\)$`), VP = new RegExp(`^rgb\\(${Ts},${Ts},${Ts}\\)$`), GP = new RegExp(`^rgba\\(${ul},${ul},${ul},${qc}\\)$`), kP = new RegExp(`^rgba\\(${Ts},${Ts},${Ts},${qc}\\)$`), XP = new RegExp(`^hsl\\(${qc},${Ts},${Ts}\\)$`), WP = new RegExp(`^hsla\\(${qc},${Ts},${Ts},${qc}\\)$`), qb = {
  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
};
fv(su, Xa, {
  copy(n) {
    return Object.assign(new this.constructor(), this, n);
  },
  displayable() {
    return this.rgb().displayable();
  },
  hex: Zb,
  // Deprecated! Use color.formatHex.
  formatHex: Zb,
  formatHex8: YP,
  formatHsl: jP,
  formatRgb: $b,
  toString: $b
});
function Zb() {
  return this.rgb().formatHex();
}
function YP() {
  return this.rgb().formatHex8();
}
function jP() {
  return gE(this).formatHsl();
}
function $b() {
  return this.rgb().formatRgb();
}
function Xa(n) {
  var t, e;
  return n = (n + "").trim().toLowerCase(), (t = FP.exec(n)) ? (e = t[1].length, t = parseInt(t[1], 16), e === 6 ? Kb(t) : e === 3 ? new hi(t >> 8 & 15 | t >> 4 & 240, t >> 4 & 15 | t & 240, (t & 15) << 4 | t & 15, 1) : e === 8 ? nd(t >> 24 & 255, t >> 16 & 255, t >> 8 & 255, (t & 255) / 255) : e === 4 ? nd(t >> 12 & 15 | t >> 8 & 240, t >> 8 & 15 | t >> 4 & 240, t >> 4 & 15 | t & 240, ((t & 15) << 4 | t & 15) / 255) : null) : (t = HP.exec(n)) ? new hi(t[1], t[2], t[3], 1) : (t = VP.exec(n)) ? new hi(t[1] * 255 / 100, t[2] * 255 / 100, t[3] * 255 / 100, 1) : (t = GP.exec(n)) ? nd(t[1], t[2], t[3], t[4]) : (t = kP.exec(n)) ? nd(t[1] * 255 / 100, t[2] * 255 / 100, t[3] * 255 / 100, t[4]) : (t = XP.exec(n)) ? t1(t[1], t[2] / 100, t[3] / 100, 1) : (t = WP.exec(n)) ? t1(t[1], t[2] / 100, t[3] / 100, t[4]) : qb.hasOwnProperty(n) ? Kb(qb[n]) : n === "transparent" ? new hi(NaN, NaN, NaN, 0) : null;
}
function Kb(n) {
  return new hi(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
}
function nd(n, t, e, s) {
  return s <= 0 && (n = t = e = NaN), new hi(n, t, e, s);
}
function qP(n) {
  return n instanceof su || (n = Xa(n)), n ? (n = n.rgb(), new hi(n.r, n.g, n.b, n.opacity)) : new hi();
}
function w0(n, t, e, s) {
  return arguments.length === 1 ? qP(n) : new hi(n, t, e, s ?? 1);
}
function hi(n, t, e, s) {
  this.r = +n, this.g = +t, this.b = +e, this.opacity = +s;
}
fv(hi, w0, mE(su, {
  brighter(n) {
    return n = n == null ? Od : Math.pow(Od, n), new hi(this.r * n, this.g * n, this.b * n, this.opacity);
  },
  darker(n) {
    return n = n == null ? jc : Math.pow(jc, n), new hi(this.r * n, this.g * n, this.b * n, this.opacity);
  },
  rgb() {
    return this;
  },
  clamp() {
    return new hi(Va(this.r), Va(this.g), Va(this.b), Ld(this.opacity));
  },
  displayable() {
    return -0.5 <= this.r && this.r < 255.5 && -0.5 <= this.g && this.g < 255.5 && -0.5 <= this.b && this.b < 255.5 && 0 <= this.opacity && this.opacity <= 1;
  },
  hex: Qb,
  // Deprecated! Use color.formatHex.
  formatHex: Qb,
  formatHex8: ZP,
  formatRgb: Jb,
  toString: Jb
}));
function Qb() {
  return `#${Fa(this.r)}${Fa(this.g)}${Fa(this.b)}`;
}
function ZP() {
  return `#${Fa(this.r)}${Fa(this.g)}${Fa(this.b)}${Fa((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}
function Jb() {
  const n = Ld(this.opacity);
  return `${n === 1 ? "rgb(" : "rgba("}${Va(this.r)}, ${Va(this.g)}, ${Va(this.b)}${n === 1 ? ")" : `, ${n})`}`;
}
function Ld(n) {
  return isNaN(n) ? 1 : Math.max(0, Math.min(1, n));
}
function Va(n) {
  return Math.max(0, Math.min(255, Math.round(n) || 0));
}
function Fa(n) {
  return n = Va(n), (n < 16 ? "0" : "") + n.toString(16);
}
function t1(n, t, e, s) {
  return s <= 0 ? n = t = e = NaN : e <= 0 || e >= 1 ? n = t = NaN : t <= 0 && (n = NaN), new is(n, t, e, s);
}
function gE(n) {
  if (n instanceof is) return new is(n.h, n.s, n.l, n.opacity);
  if (n instanceof su || (n = Xa(n)), !n) return new is();
  if (n instanceof is) return n;
  n = n.rgb();
  var t = n.r / 255, e = n.g / 255, s = n.b / 255, a = Math.min(t, e, s), o = Math.max(t, e, s), c = NaN, u = o - a, d = (o + a) / 2;
  return u ? (t === o ? c = (e - s) / u + (e < s) * 6 : e === o ? c = (s - t) / u + 2 : c = (t - e) / u + 4, u /= d < 0.5 ? o + a : 2 - o - a, c *= 60) : u = d > 0 && d < 1 ? 0 : c, new is(c, u, d, n.opacity);
}
function $P(n, t, e, s) {
  return arguments.length === 1 ? gE(n) : new is(n, t, e, s ?? 1);
}
function is(n, t, e, s) {
  this.h = +n, this.s = +t, this.l = +e, this.opacity = +s;
}
fv(is, $P, mE(su, {
  brighter(n) {
    return n = n == null ? Od : Math.pow(Od, n), new is(this.h, this.s, this.l * n, this.opacity);
  },
  darker(n) {
    return n = n == null ? jc : Math.pow(jc, n), new is(this.h, this.s, this.l * n, this.opacity);
  },
  rgb() {
    var n = this.h % 360 + (this.h < 0) * 360, t = isNaN(n) || isNaN(this.s) ? 0 : this.s, e = this.l, s = e + (e < 0.5 ? e : 1 - e) * t, a = 2 * e - s;
    return new hi(
      fg(n >= 240 ? n - 240 : n + 120, a, s),
      fg(n, a, s),
      fg(n < 120 ? n + 240 : n - 120, a, s),
      this.opacity
    );
  },
  clamp() {
    return new is(e1(this.h), id(this.s), id(this.l), Ld(this.opacity));
  },
  displayable() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && 0 <= this.l && this.l <= 1 && 0 <= this.opacity && this.opacity <= 1;
  },
  formatHsl() {
    const n = Ld(this.opacity);
    return `${n === 1 ? "hsl(" : "hsla("}${e1(this.h)}, ${id(this.s) * 100}%, ${id(this.l) * 100}%${n === 1 ? ")" : `, ${n})`}`;
  }
}));
function e1(n) {
  return n = (n || 0) % 360, n < 0 ? n + 360 : n;
}
function id(n) {
  return Math.max(0, Math.min(1, n || 0));
}
function fg(n, t, e) {
  return (n < 60 ? t + (e - t) * n / 60 : n < 180 ? e : n < 240 ? t + (e - t) * (240 - n) / 60 : t) * 255;
}
const dv = (n) => () => n;
function KP(n, t) {
  return function(e) {
    return n + e * t;
  };
}
function QP(n, t, e) {
  return n = Math.pow(n, e), t = Math.pow(t, e) - n, e = 1 / e, function(s) {
    return Math.pow(n + s * t, e);
  };
}
function JP(n) {
  return (n = +n) == 1 ? vE : function(t, e) {
    return e - t ? QP(t, e, n) : dv(isNaN(t) ? e : t);
  };
}
function vE(n, t) {
  var e = t - n;
  return e ? KP(n, e) : dv(isNaN(n) ? t : n);
}
const Ud = (function n(t) {
  var e = JP(t);
  function s(a, o) {
    var c = e((a = w0(a)).r, (o = w0(o)).r), u = e(a.g, o.g), d = e(a.b, o.b), h = vE(a.opacity, o.opacity);
    return function(m) {
      return a.r = c(m), a.g = u(m), a.b = d(m), a.opacity = h(m), a + "";
    };
  }
  return s.gamma = n, s;
})(1);
function tI(n, t) {
  t || (t = []);
  var e = n ? Math.min(t.length, n.length) : 0, s = t.slice(), a;
  return function(o) {
    for (a = 0; a < e; ++a) s[a] = n[a] * (1 - o) + t[a] * o;
    return s;
  };
}
function eI(n) {
  return ArrayBuffer.isView(n) && !(n instanceof DataView);
}
function nI(n, t) {
  var e = t ? t.length : 0, s = n ? Math.min(e, n.length) : 0, a = new Array(s), o = new Array(e), c;
  for (c = 0; c < s; ++c) a[c] = Ic(n[c], t[c]);
  for (; c < e; ++c) o[c] = t[c];
  return function(u) {
    for (c = 0; c < s; ++c) o[c] = a[c](u);
    return o;
  };
}
function iI(n, t) {
  var e = /* @__PURE__ */ new Date();
  return n = +n, t = +t, function(s) {
    return e.setTime(n * (1 - s) + t * s), e;
  };
}
function xs(n, t) {
  return n = +n, t = +t, function(e) {
    return n * (1 - e) + t * e;
  };
}
function sI(n, t) {
  var e = {}, s = {}, a;
  (n === null || typeof n != "object") && (n = {}), (t === null || typeof t != "object") && (t = {});
  for (a in t)
    a in n ? e[a] = Ic(n[a], t[a]) : s[a] = t[a];
  return function(o) {
    for (a in e) s[a] = e[a](o);
    return s;
  };
}
var A0 = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, dg = new RegExp(A0.source, "g");
function rI(n) {
  return function() {
    return n;
  };
}
function aI(n) {
  return function(t) {
    return n(t) + "";
  };
}
function _E(n, t) {
  var e = A0.lastIndex = dg.lastIndex = 0, s, a, o, c = -1, u = [], d = [];
  for (n = n + "", t = t + ""; (s = A0.exec(n)) && (a = dg.exec(t)); )
    (o = a.index) > e && (o = t.slice(e, o), u[c] ? u[c] += o : u[++c] = o), (s = s[0]) === (a = a[0]) ? u[c] ? u[c] += a : u[++c] = a : (u[++c] = null, d.push({ i: c, x: xs(s, a) })), e = dg.lastIndex;
  return e < t.length && (o = t.slice(e), u[c] ? u[c] += o : u[++c] = o), u.length < 2 ? d[0] ? aI(d[0].x) : rI(t) : (t = d.length, function(h) {
    for (var m = 0, p; m < t; ++m) u[(p = d[m]).i] = p.x(h);
    return u.join("");
  });
}
function Ic(n, t) {
  var e = typeof t, s;
  return t == null || e === "boolean" ? dv(t) : (e === "number" ? xs : e === "string" ? (s = Xa(t)) ? (t = s, Ud) : _E : t instanceof Xa ? Ud : t instanceof Date ? iI : eI(t) ? tI : Array.isArray(t) ? nI : typeof t.valueOf != "function" && typeof t.toString != "function" || isNaN(t) ? sI : xs)(n, t);
}
var n1 = 180 / Math.PI, T0 = {
  translateX: 0,
  translateY: 0,
  rotate: 0,
  skewX: 0,
  scaleX: 1,
  scaleY: 1
};
function yE(n, t, e, s, a, o) {
  var c, u, d;
  return (c = Math.sqrt(n * n + t * t)) && (n /= c, t /= c), (d = n * e + t * s) && (e -= n * d, s -= t * d), (u = Math.sqrt(e * e + s * s)) && (e /= u, s /= u, d /= u), n * s < t * e && (n = -n, t = -t, d = -d, c = -c), {
    translateX: a,
    translateY: o,
    rotate: Math.atan2(t, n) * n1,
    skewX: Math.atan(d) * n1,
    scaleX: c,
    scaleY: u
  };
}
var sd;
function oI(n) {
  const t = new (typeof DOMMatrix == "function" ? DOMMatrix : WebKitCSSMatrix)(n + "");
  return t.isIdentity ? T0 : yE(t.a, t.b, t.c, t.d, t.e, t.f);
}
function lI(n) {
  return n == null || (sd || (sd = document.createElementNS("http://www.w3.org/2000/svg", "g")), sd.setAttribute("transform", n), !(n = sd.transform.baseVal.consolidate())) ? T0 : (n = n.matrix, yE(n.a, n.b, n.c, n.d, n.e, n.f));
}
function xE(n, t, e, s) {
  function a(h) {
    return h.length ? h.pop() + " " : "";
  }
  function o(h, m, p, g, _, x) {
    if (h !== p || m !== g) {
      var A = _.push("translate(", null, t, null, e);
      x.push({ i: A - 4, x: xs(h, p) }, { i: A - 2, x: xs(m, g) });
    } else (p || g) && _.push("translate(" + p + t + g + e);
  }
  function c(h, m, p, g) {
    h !== m ? (h - m > 180 ? m += 360 : m - h > 180 && (h += 360), g.push({ i: p.push(a(p) + "rotate(", null, s) - 2, x: xs(h, m) })) : m && p.push(a(p) + "rotate(" + m + s);
  }
  function u(h, m, p, g) {
    h !== m ? g.push({ i: p.push(a(p) + "skewX(", null, s) - 2, x: xs(h, m) }) : m && p.push(a(p) + "skewX(" + m + s);
  }
  function d(h, m, p, g, _, x) {
    if (h !== p || m !== g) {
      var A = _.push(a(_) + "scale(", null, ",", null, ")");
      x.push({ i: A - 4, x: xs(h, p) }, { i: A - 2, x: xs(m, g) });
    } else (p !== 1 || g !== 1) && _.push(a(_) + "scale(" + p + "," + g + ")");
  }
  return function(h, m) {
    var p = [], g = [];
    return h = n(h), m = n(m), o(h.translateX, h.translateY, m.translateX, m.translateY, p, g), c(h.rotate, m.rotate, p, g), u(h.skewX, m.skewX, p, g), d(h.scaleX, h.scaleY, m.scaleX, m.scaleY, p, g), h = m = null, function(_) {
      for (var x = -1, A = g.length, b; ++x < A; ) p[(b = g[x]).i] = b.x(_);
      return p.join("");
    };
  };
}
var cI = xE(oI, "px, ", "px)", "deg)"), uI = xE(lI, ", ", ")", ")"), fI = 1e-12;
function i1(n) {
  return ((n = Math.exp(n)) + 1 / n) / 2;
}
function dI(n) {
  return ((n = Math.exp(n)) - 1 / n) / 2;
}
function hI(n) {
  return ((n = Math.exp(2 * n)) - 1) / (n + 1);
}
const _d = (function n(t, e, s) {
  function a(o, c) {
    var u = o[0], d = o[1], h = o[2], m = c[0], p = c[1], g = c[2], _ = m - u, x = p - d, A = _ * _ + x * x, b, y;
    if (A < fI)
      y = Math.log(g / h) / t, b = function(D) {
        return [
          u + D * _,
          d + D * x,
          h * Math.exp(t * D * y)
        ];
      };
    else {
      var E = Math.sqrt(A), w = (g * g - h * h + s * A) / (2 * h * e * E), M = (g * g - h * h - s * A) / (2 * g * e * E), O = Math.log(Math.sqrt(w * w + 1) - w), C = Math.log(Math.sqrt(M * M + 1) - M);
      y = (C - O) / t, b = function(D) {
        var T = D * y, L = i1(O), z = h / (e * E) * (L * hI(t * T + O) - dI(O));
        return [
          u + z * _,
          d + z * x,
          h * L / i1(t * T + O)
        ];
      };
    }
    return b.duration = y * 1e3 * t / Math.SQRT2, b;
  }
  return a.rho = function(o) {
    var c = Math.max(1e-3, +o), u = c * c, d = u * u;
    return n(c, u, d);
  }, a;
})(Math.SQRT2, 2, 4);
var vl = 0, Oc = 0, Ac = 0, SE = 1e3, Pd, Lc, Id = 0, Wa = 0, eh = 0, Zc = typeof performance == "object" && performance.now ? performance : Date, bE = typeof window == "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(n) {
  setTimeout(n, 17);
};
function hv() {
  return Wa || (bE(pI), Wa = Zc.now() + eh);
}
function pI() {
  Wa = 0;
}
function Bd() {
  this._call = this._time = this._next = null;
}
Bd.prototype = ME.prototype = {
  constructor: Bd,
  restart: function(n, t, e) {
    if (typeof n != "function") throw new TypeError("callback is not a function");
    e = (e == null ? hv() : +e) + (t == null ? 0 : +t), !this._next && Lc !== this && (Lc ? Lc._next = this : Pd = this, Lc = this), this._call = n, this._time = e, C0();
  },
  stop: function() {
    this._call && (this._call = null, this._time = 1 / 0, C0());
  }
};
function ME(n, t, e) {
  var s = new Bd();
  return s.restart(n, t, e), s;
}
function mI() {
  hv(), ++vl;
  for (var n = Pd, t; n; )
    (t = Wa - n._time) >= 0 && n._call.call(void 0, t), n = n._next;
  --vl;
}
function s1() {
  Wa = (Id = Zc.now()) + eh, vl = Oc = 0;
  try {
    mI();
  } finally {
    vl = 0, vI(), Wa = 0;
  }
}
function gI() {
  var n = Zc.now(), t = n - Id;
  t > SE && (eh -= t, Id = n);
}
function vI() {
  for (var n, t = Pd, e, s = 1 / 0; t; )
    t._call ? (s > t._time && (s = t._time), n = t, t = t._next) : (e = t._next, t._next = null, t = n ? n._next = e : Pd = e);
  Lc = n, C0(s);
}
function C0(n) {
  if (!vl) {
    Oc && (Oc = clearTimeout(Oc));
    var t = n - Wa;
    t > 24 ? (n < 1 / 0 && (Oc = setTimeout(s1, n - Zc.now() - eh)), Ac && (Ac = clearInterval(Ac))) : (Ac || (Id = Zc.now(), Ac = setInterval(gI, SE)), vl = 1, bE(s1));
  }
}
function r1(n, t, e) {
  var s = new Bd();
  return t = t == null ? 0 : +t, s.restart((a) => {
    s.stop(), n(a + t);
  }, t, e), s;
}
var _I = Jd("start", "end", "cancel", "interrupt"), yI = [], EE = 0, a1 = 1, R0 = 2, yd = 3, o1 = 4, D0 = 5, xd = 6;
function nh(n, t, e, s, a, o) {
  var c = n.__transition;
  if (!c) n.__transition = {};
  else if (e in c) return;
  xI(n, e, {
    name: t,
    index: s,
    // For context during callback.
    group: a,
    // For context during callback.
    on: _I,
    tween: yI,
    time: o.time,
    delay: o.delay,
    duration: o.duration,
    ease: o.ease,
    timer: null,
    state: EE
  });
}
function pv(n, t) {
  var e = ls(n, t);
  if (e.state > EE) throw new Error("too late; already scheduled");
  return e;
}
function Os(n, t) {
  var e = ls(n, t);
  if (e.state > yd) throw new Error("too late; already running");
  return e;
}
function ls(n, t) {
  var e = n.__transition;
  if (!e || !(e = e[t])) throw new Error("transition not found");
  return e;
}
function xI(n, t, e) {
  var s = n.__transition, a;
  s[t] = e, e.timer = ME(o, 0, e.time);
  function o(h) {
    e.state = a1, e.timer.restart(c, e.delay, e.time), e.delay <= h && c(h - e.delay);
  }
  function c(h) {
    var m, p, g, _;
    if (e.state !== a1) return d();
    for (m in s)
      if (_ = s[m], _.name === e.name) {
        if (_.state === yd) return r1(c);
        _.state === o1 ? (_.state = xd, _.timer.stop(), _.on.call("interrupt", n, n.__data__, _.index, _.group), delete s[m]) : +m < t && (_.state = xd, _.timer.stop(), _.on.call("cancel", n, n.__data__, _.index, _.group), delete s[m]);
      }
    if (r1(function() {
      e.state === yd && (e.state = o1, e.timer.restart(u, e.delay, e.time), u(h));
    }), e.state = R0, e.on.call("start", n, n.__data__, e.index, e.group), e.state === R0) {
      for (e.state = yd, a = new Array(g = e.tween.length), m = 0, p = -1; m < g; ++m)
        (_ = e.tween[m].value.call(n, n.__data__, e.index, e.group)) && (a[++p] = _);
      a.length = p + 1;
    }
  }
  function u(h) {
    for (var m = h < e.duration ? e.ease.call(null, h / e.duration) : (e.timer.restart(d), e.state = D0, 1), p = -1, g = a.length; ++p < g; )
      a[p].call(n, m);
    e.state === D0 && (e.on.call("end", n, n.__data__, e.index, e.group), d());
  }
  function d() {
    e.state = xd, e.timer.stop(), delete s[t];
    for (var h in s) return;
    delete n.__transition;
  }
}
function Sd(n, t) {
  var e = n.__transition, s, a, o = !0, c;
  if (e) {
    t = t == null ? null : t + "";
    for (c in e) {
      if ((s = e[c]).name !== t) {
        o = !1;
        continue;
      }
      a = s.state > R0 && s.state < D0, s.state = xd, s.timer.stop(), s.on.call(a ? "interrupt" : "cancel", n, n.__data__, s.index, s.group), delete e[c];
    }
    o && delete n.__transition;
  }
}
function SI(n) {
  return this.each(function() {
    Sd(this, n);
  });
}
function bI(n, t) {
  var e, s;
  return function() {
    var a = Os(this, n), o = a.tween;
    if (o !== e) {
      s = e = o;
      for (var c = 0, u = s.length; c < u; ++c)
        if (s[c].name === t) {
          s = s.slice(), s.splice(c, 1);
          break;
        }
    }
    a.tween = s;
  };
}
function MI(n, t, e) {
  var s, a;
  if (typeof e != "function") throw new Error();
  return function() {
    var o = Os(this, n), c = o.tween;
    if (c !== s) {
      a = (s = c).slice();
      for (var u = { name: t, value: e }, d = 0, h = a.length; d < h; ++d)
        if (a[d].name === t) {
          a[d] = u;
          break;
        }
      d === h && a.push(u);
    }
    o.tween = a;
  };
}
function EI(n, t) {
  var e = this._id;
  if (n += "", arguments.length < 2) {
    for (var s = ls(this.node(), e).tween, a = 0, o = s.length, c; a < o; ++a)
      if ((c = s[a]).name === n)
        return c.value;
    return null;
  }
  return this.each((t == null ? bI : MI)(e, n, t));
}
function mv(n, t, e) {
  var s = n._id;
  return n.each(function() {
    var a = Os(this, s);
    (a.value || (a.value = {}))[t] = e.apply(this, arguments);
  }), function(a) {
    return ls(a, s).value[t];
  };
}
function wE(n, t) {
  var e;
  return (typeof t == "number" ? xs : t instanceof Xa ? Ud : (e = Xa(t)) ? (t = e, Ud) : _E)(n, t);
}
function wI(n) {
  return function() {
    this.removeAttribute(n);
  };
}
function AI(n) {
  return function() {
    this.removeAttributeNS(n.space, n.local);
  };
}
function TI(n, t, e) {
  var s, a = e + "", o;
  return function() {
    var c = this.getAttribute(n);
    return c === a ? null : c === s ? o : o = t(s = c, e);
  };
}
function CI(n, t, e) {
  var s, a = e + "", o;
  return function() {
    var c = this.getAttributeNS(n.space, n.local);
    return c === a ? null : c === s ? o : o = t(s = c, e);
  };
}
function RI(n, t, e) {
  var s, a, o;
  return function() {
    var c, u = e(this), d;
    return u == null ? void this.removeAttribute(n) : (c = this.getAttribute(n), d = u + "", c === d ? null : c === s && d === a ? o : (a = d, o = t(s = c, u)));
  };
}
function DI(n, t, e) {
  var s, a, o;
  return function() {
    var c, u = e(this), d;
    return u == null ? void this.removeAttributeNS(n.space, n.local) : (c = this.getAttributeNS(n.space, n.local), d = u + "", c === d ? null : c === s && d === a ? o : (a = d, o = t(s = c, u)));
  };
}
function NI(n, t) {
  var e = th(n), s = e === "transform" ? uI : wE;
  return this.attrTween(n, typeof t == "function" ? (e.local ? DI : RI)(e, s, mv(this, "attr." + n, t)) : t == null ? (e.local ? AI : wI)(e) : (e.local ? CI : TI)(e, s, t));
}
function OI(n, t) {
  return function(e) {
    this.setAttribute(n, t.call(this, e));
  };
}
function LI(n, t) {
  return function(e) {
    this.setAttributeNS(n.space, n.local, t.call(this, e));
  };
}
function UI(n, t) {
  var e, s;
  function a() {
    var o = t.apply(this, arguments);
    return o !== s && (e = (s = o) && LI(n, o)), e;
  }
  return a._value = t, a;
}
function PI(n, t) {
  var e, s;
  function a() {
    var o = t.apply(this, arguments);
    return o !== s && (e = (s = o) && OI(n, o)), e;
  }
  return a._value = t, a;
}
function II(n, t) {
  var e = "attr." + n;
  if (arguments.length < 2) return (e = this.tween(e)) && e._value;
  if (t == null) return this.tween(e, null);
  if (typeof t != "function") throw new Error();
  var s = th(n);
  return this.tween(e, (s.local ? UI : PI)(s, t));
}
function BI(n, t) {
  return function() {
    pv(this, n).delay = +t.apply(this, arguments);
  };
}
function zI(n, t) {
  return t = +t, function() {
    pv(this, n).delay = t;
  };
}
function FI(n) {
  var t = this._id;
  return arguments.length ? this.each((typeof n == "function" ? BI : zI)(t, n)) : ls(this.node(), t).delay;
}
function HI(n, t) {
  return function() {
    Os(this, n).duration = +t.apply(this, arguments);
  };
}
function VI(n, t) {
  return t = +t, function() {
    Os(this, n).duration = t;
  };
}
function GI(n) {
  var t = this._id;
  return arguments.length ? this.each((typeof n == "function" ? HI : VI)(t, n)) : ls(this.node(), t).duration;
}
function kI(n, t) {
  if (typeof t != "function") throw new Error();
  return function() {
    Os(this, n).ease = t;
  };
}
function XI(n) {
  var t = this._id;
  return arguments.length ? this.each(kI(t, n)) : ls(this.node(), t).ease;
}
function WI(n, t) {
  return function() {
    var e = t.apply(this, arguments);
    if (typeof e != "function") throw new Error();
    Os(this, n).ease = e;
  };
}
function YI(n) {
  if (typeof n != "function") throw new Error();
  return this.each(WI(this._id, n));
}
function jI(n) {
  typeof n != "function" && (n = nE(n));
  for (var t = this._groups, e = t.length, s = new Array(e), a = 0; a < e; ++a)
    for (var o = t[a], c = o.length, u = s[a] = [], d, h = 0; h < c; ++h)
      (d = o[h]) && n.call(d, d.__data__, h, o) && u.push(d);
  return new mr(s, this._parents, this._name, this._id);
}
function qI(n) {
  if (n._id !== this._id) throw new Error();
  for (var t = this._groups, e = n._groups, s = t.length, a = e.length, o = Math.min(s, a), c = new Array(s), u = 0; u < o; ++u)
    for (var d = t[u], h = e[u], m = d.length, p = c[u] = new Array(m), g, _ = 0; _ < m; ++_)
      (g = d[_] || h[_]) && (p[_] = g);
  for (; u < s; ++u)
    c[u] = t[u];
  return new mr(c, this._parents, this._name, this._id);
}
function ZI(n) {
  return (n + "").trim().split(/^|\s+/).every(function(t) {
    var e = t.indexOf(".");
    return e >= 0 && (t = t.slice(0, e)), !t || t === "start";
  });
}
function $I(n, t, e) {
  var s, a, o = ZI(t) ? pv : Os;
  return function() {
    var c = o(this, n), u = c.on;
    u !== s && (a = (s = u).copy()).on(t, e), c.on = a;
  };
}
function KI(n, t) {
  var e = this._id;
  return arguments.length < 2 ? ls(this.node(), e).on.on(n) : this.each($I(e, n, t));
}
function QI(n) {
  return function() {
    var t = this.parentNode;
    for (var e in this.__transition) if (+e !== n) return;
    t && t.removeChild(this);
  };
}
function JI() {
  return this.on("end.remove", QI(this._id));
}
function tB(n) {
  var t = this._name, e = this._id;
  typeof n != "function" && (n = cv(n));
  for (var s = this._groups, a = s.length, o = new Array(a), c = 0; c < a; ++c)
    for (var u = s[c], d = u.length, h = o[c] = new Array(d), m, p, g = 0; g < d; ++g)
      (m = u[g]) && (p = n.call(m, m.__data__, g, u)) && ("__data__" in m && (p.__data__ = m.__data__), h[g] = p, nh(h[g], t, e, g, h, ls(m, e)));
  return new mr(o, this._parents, t, e);
}
function eB(n) {
  var t = this._name, e = this._id;
  typeof n != "function" && (n = eE(n));
  for (var s = this._groups, a = s.length, o = [], c = [], u = 0; u < a; ++u)
    for (var d = s[u], h = d.length, m, p = 0; p < h; ++p)
      if (m = d[p]) {
        for (var g = n.call(m, m.__data__, p, d), _, x = ls(m, e), A = 0, b = g.length; A < b; ++A)
          (_ = g[A]) && nh(_, t, e, A, g, x);
        o.push(g), c.push(m);
      }
  return new mr(o, c, t, e);
}
var nB = iu.prototype.constructor;
function iB() {
  return new nB(this._groups, this._parents);
}
function sB(n, t) {
  var e, s, a;
  return function() {
    var o = gl(this, n), c = (this.style.removeProperty(n), gl(this, n));
    return o === c ? null : o === e && c === s ? a : a = t(e = o, s = c);
  };
}
function AE(n) {
  return function() {
    this.style.removeProperty(n);
  };
}
function rB(n, t, e) {
  var s, a = e + "", o;
  return function() {
    var c = gl(this, n);
    return c === a ? null : c === s ? o : o = t(s = c, e);
  };
}
function aB(n, t, e) {
  var s, a, o;
  return function() {
    var c = gl(this, n), u = e(this), d = u + "";
    return u == null && (d = u = (this.style.removeProperty(n), gl(this, n))), c === d ? null : c === s && d === a ? o : (a = d, o = t(s = c, u));
  };
}
function oB(n, t) {
  var e, s, a, o = "style." + t, c = "end." + o, u;
  return function() {
    var d = Os(this, n), h = d.on, m = d.value[o] == null ? u || (u = AE(t)) : void 0;
    (h !== e || a !== m) && (s = (e = h).copy()).on(c, a = m), d.on = s;
  };
}
function lB(n, t, e) {
  var s = (n += "") == "transform" ? cI : wE;
  return t == null ? this.styleTween(n, sB(n, s)).on("end.style." + n, AE(n)) : typeof t == "function" ? this.styleTween(n, aB(n, s, mv(this, "style." + n, t))).each(oB(this._id, n)) : this.styleTween(n, rB(n, s, t), e).on("end.style." + n, null);
}
function cB(n, t, e) {
  return function(s) {
    this.style.setProperty(n, t.call(this, s), e);
  };
}
function uB(n, t, e) {
  var s, a;
  function o() {
    var c = t.apply(this, arguments);
    return c !== a && (s = (a = c) && cB(n, c, e)), s;
  }
  return o._value = t, o;
}
function fB(n, t, e) {
  var s = "style." + (n += "");
  if (arguments.length < 2) return (s = this.tween(s)) && s._value;
  if (t == null) return this.tween(s, null);
  if (typeof t != "function") throw new Error();
  return this.tween(s, uB(n, t, e ?? ""));
}
function dB(n) {
  return function() {
    this.textContent = n;
  };
}
function hB(n) {
  return function() {
    var t = n(this);
    this.textContent = t ?? "";
  };
}
function pB(n) {
  return this.tween("text", typeof n == "function" ? hB(mv(this, "text", n)) : dB(n == null ? "" : n + ""));
}
function mB(n) {
  return function(t) {
    this.textContent = n.call(this, t);
  };
}
function gB(n) {
  var t, e;
  function s() {
    var a = n.apply(this, arguments);
    return a !== e && (t = (e = a) && mB(a)), t;
  }
  return s._value = n, s;
}
function vB(n) {
  var t = "text";
  if (arguments.length < 1) return (t = this.tween(t)) && t._value;
  if (n == null) return this.tween(t, null);
  if (typeof n != "function") throw new Error();
  return this.tween(t, gB(n));
}
function _B() {
  for (var n = this._name, t = this._id, e = TE(), s = this._groups, a = s.length, o = 0; o < a; ++o)
    for (var c = s[o], u = c.length, d, h = 0; h < u; ++h)
      if (d = c[h]) {
        var m = ls(d, t);
        nh(d, n, e, h, c, {
          time: m.time + m.delay + m.duration,
          delay: 0,
          duration: m.duration,
          ease: m.ease
        });
      }
  return new mr(s, this._parents, n, e);
}
function yB() {
  var n, t, e = this, s = e._id, a = e.size();
  return new Promise(function(o, c) {
    var u = { value: c }, d = { value: function() {
      --a === 0 && o();
    } };
    e.each(function() {
      var h = Os(this, s), m = h.on;
      m !== n && (t = (n = m).copy(), t._.cancel.push(u), t._.interrupt.push(u), t._.end.push(d)), h.on = t;
    }), a === 0 && o();
  });
}
var xB = 0;
function mr(n, t, e, s) {
  this._groups = n, this._parents = t, this._name = e, this._id = s;
}
function TE() {
  return ++xB;
}
var sr = iu.prototype;
mr.prototype = {
  constructor: mr,
  select: tB,
  selectAll: eB,
  selectChild: sr.selectChild,
  selectChildren: sr.selectChildren,
  filter: jI,
  merge: qI,
  selection: iB,
  transition: _B,
  call: sr.call,
  nodes: sr.nodes,
  node: sr.node,
  size: sr.size,
  empty: sr.empty,
  each: sr.each,
  on: KI,
  attr: NI,
  attrTween: II,
  style: lB,
  styleTween: fB,
  text: pB,
  textTween: vB,
  remove: JI,
  tween: EI,
  delay: FI,
  duration: GI,
  ease: XI,
  easeVarying: YI,
  end: yB,
  [Symbol.iterator]: sr[Symbol.iterator]
};
function SB(n) {
  return ((n *= 2) <= 1 ? n * n * n : (n -= 2) * n * n + 2) / 2;
}
var bB = {
  time: null,
  // Set on use.
  delay: 0,
  duration: 250,
  ease: SB
};
function MB(n, t) {
  for (var e; !(e = n.__transition) || !(e = e[t]); )
    if (!(n = n.parentNode))
      throw new Error(`transition ${t} not found`);
  return e;
}
function EB(n) {
  var t, e;
  n instanceof mr ? (t = n._id, n = n._name) : (t = TE(), (e = bB).time = hv(), n = n == null ? null : n + "");
  for (var s = this._groups, a = s.length, o = 0; o < a; ++o)
    for (var c = s[o], u = c.length, d, h = 0; h < u; ++h)
      (d = c[h]) && nh(d, n, t, h, c, e || MB(d, t));
  return new mr(s, this._parents, n, t);
}
iu.prototype.interrupt = SI;
iu.prototype.transition = EB;
const rd = (n) => () => n;
function wB(n, {
  sourceEvent: t,
  target: e,
  transform: s,
  dispatch: a
}) {
  Object.defineProperties(this, {
    type: { value: n, enumerable: !0, configurable: !0 },
    sourceEvent: { value: t, enumerable: !0, configurable: !0 },
    target: { value: e, enumerable: !0, configurable: !0 },
    transform: { value: s, enumerable: !0, configurable: !0 },
    _: { value: a }
  });
}
function lr(n, t, e) {
  this.k = n, this.x = t, this.y = e;
}
lr.prototype = {
  constructor: lr,
  scale: function(n) {
    return n === 1 ? this : new lr(this.k * n, this.x, this.y);
  },
  translate: function(n, t) {
    return n === 0 & t === 0 ? this : new lr(this.k, this.x + this.k * n, this.y + this.k * t);
  },
  apply: function(n) {
    return [n[0] * this.k + this.x, n[1] * this.k + this.y];
  },
  applyX: function(n) {
    return n * this.k + this.x;
  },
  applyY: function(n) {
    return n * this.k + this.y;
  },
  invert: function(n) {
    return [(n[0] - this.x) / this.k, (n[1] - this.y) / this.k];
  },
  invertX: function(n) {
    return (n - this.x) / this.k;
  },
  invertY: function(n) {
    return (n - this.y) / this.k;
  },
  rescaleX: function(n) {
    return n.copy().domain(n.range().map(this.invertX, this).map(n.invert, n));
  },
  rescaleY: function(n) {
    return n.copy().domain(n.range().map(this.invertY, this).map(n.invert, n));
  },
  toString: function() {
    return "translate(" + this.x + "," + this.y + ") scale(" + this.k + ")";
  }
};
var ih = new lr(1, 0, 0);
CE.prototype = lr.prototype;
function CE(n) {
  for (; !n.__zoom; ) if (!(n = n.parentNode)) return ih;
  return n.__zoom;
}
function hg(n) {
  n.stopImmediatePropagation();
}
function Tc(n) {
  n.preventDefault(), n.stopImmediatePropagation();
}
function AB(n) {
  return (!n.ctrlKey || n.type === "wheel") && !n.button;
}
function TB() {
  var n = this;
  return n instanceof SVGElement ? (n = n.ownerSVGElement || n, n.hasAttribute("viewBox") ? (n = n.viewBox.baseVal, [[n.x, n.y], [n.x + n.width, n.y + n.height]]) : [[0, 0], [n.width.baseVal.value, n.height.baseVal.value]]) : [[0, 0], [n.clientWidth, n.clientHeight]];
}
function l1() {
  return this.__zoom || ih;
}
function CB(n) {
  return -n.deltaY * (n.deltaMode === 1 ? 0.05 : n.deltaMode ? 1 : 2e-3) * (n.ctrlKey ? 10 : 1);
}
function RB() {
  return navigator.maxTouchPoints || "ontouchstart" in this;
}
function DB(n, t, e) {
  var s = n.invertX(t[0][0]) - e[0][0], a = n.invertX(t[1][0]) - e[1][0], o = n.invertY(t[0][1]) - e[0][1], c = n.invertY(t[1][1]) - e[1][1];
  return n.translate(
    a > s ? (s + a) / 2 : Math.min(0, s) || Math.max(0, a),
    c > o ? (o + c) / 2 : Math.min(0, o) || Math.max(0, c)
  );
}
function RE() {
  var n = AB, t = TB, e = DB, s = CB, a = RB, o = [0, 1 / 0], c = [[-1 / 0, -1 / 0], [1 / 0, 1 / 0]], u = 250, d = _d, h = Jd("start", "zoom", "end"), m, p, g, _ = 500, x = 150, A = 0, b = 10;
  function y(U) {
    U.property("__zoom", l1).on("wheel.zoom", T, { passive: !1 }).on("mousedown.zoom", L).on("dblclick.zoom", z).filter(a).on("touchstart.zoom", R).on("touchmove.zoom", B).on("touchend.zoom touchcancel.zoom", H).style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }
  y.transform = function(U, V, N, I) {
    var k = U.selection ? U.selection() : U;
    k.property("__zoom", l1), U !== k ? O(U, V, N, I) : k.interrupt().each(function() {
      C(this, arguments).event(I).start().zoom(null, typeof V == "function" ? V.apply(this, arguments) : V).end();
    });
  }, y.scaleBy = function(U, V, N, I) {
    y.scaleTo(U, function() {
      var k = this.__zoom.k, X = typeof V == "function" ? V.apply(this, arguments) : V;
      return k * X;
    }, N, I);
  }, y.scaleTo = function(U, V, N, I) {
    y.transform(U, function() {
      var k = t.apply(this, arguments), X = this.__zoom, Q = N == null ? M(k) : typeof N == "function" ? N.apply(this, arguments) : N, F = X.invert(Q), W = typeof V == "function" ? V.apply(this, arguments) : V;
      return e(w(E(X, W), Q, F), k, c);
    }, N, I);
  }, y.translateBy = function(U, V, N, I) {
    y.transform(U, function() {
      return e(this.__zoom.translate(
        typeof V == "function" ? V.apply(this, arguments) : V,
        typeof N == "function" ? N.apply(this, arguments) : N
      ), t.apply(this, arguments), c);
    }, null, I);
  }, y.translateTo = function(U, V, N, I, k) {
    y.transform(U, function() {
      var X = t.apply(this, arguments), Q = this.__zoom, F = I == null ? M(X) : typeof I == "function" ? I.apply(this, arguments) : I;
      return e(ih.translate(F[0], F[1]).scale(Q.k).translate(
        typeof V == "function" ? -V.apply(this, arguments) : -V,
        typeof N == "function" ? -N.apply(this, arguments) : -N
      ), X, c);
    }, I, k);
  };
  function E(U, V) {
    return V = Math.max(o[0], Math.min(o[1], V)), V === U.k ? U : new lr(V, U.x, U.y);
  }
  function w(U, V, N) {
    var I = V[0] - N[0] * U.k, k = V[1] - N[1] * U.k;
    return I === U.x && k === U.y ? U : new lr(U.k, I, k);
  }
  function M(U) {
    return [(+U[0][0] + +U[1][0]) / 2, (+U[0][1] + +U[1][1]) / 2];
  }
  function O(U, V, N, I) {
    U.on("start.zoom", function() {
      C(this, arguments).event(I).start();
    }).on("interrupt.zoom end.zoom", function() {
      C(this, arguments).event(I).end();
    }).tween("zoom", function() {
      var k = this, X = arguments, Q = C(k, X).event(I), F = t.apply(k, X), W = N == null ? M(F) : typeof N == "function" ? N.apply(k, X) : N, et = Math.max(F[1][0] - F[0][0], F[1][1] - F[0][1]), $ = k.__zoom, j = typeof V == "function" ? V.apply(k, X) : V, Y = d($.invert(W).concat(et / $.k), j.invert(W).concat(et / j.k));
      return function(K) {
        if (K === 1) K = j;
        else {
          var J = Y(K), rt = et / J[2];
          K = new lr(rt, W[0] - J[0] * rt, W[1] - J[1] * rt);
        }
        Q.zoom(null, K);
      };
    });
  }
  function C(U, V, N) {
    return !N && U.__zooming || new D(U, V);
  }
  function D(U, V) {
    this.that = U, this.args = V, this.active = 0, this.sourceEvent = null, this.extent = t.apply(U, V), this.taps = 0;
  }
  D.prototype = {
    event: function(U) {
      return U && (this.sourceEvent = U), this;
    },
    start: function() {
      return ++this.active === 1 && (this.that.__zooming = this, this.emit("start")), this;
    },
    zoom: function(U, V) {
      return this.mouse && U !== "mouse" && (this.mouse[1] = V.invert(this.mouse[0])), this.touch0 && U !== "touch" && (this.touch0[1] = V.invert(this.touch0[0])), this.touch1 && U !== "touch" && (this.touch1[1] = V.invert(this.touch1[0])), this.that.__zoom = V, this.emit("zoom"), this;
    },
    end: function() {
      return --this.active === 0 && (delete this.that.__zooming, this.emit("end")), this;
    },
    emit: function(U) {
      var V = Ri(this.that).datum();
      h.call(
        U,
        this.that,
        new wB(U, {
          sourceEvent: this.sourceEvent,
          target: y,
          transform: this.that.__zoom,
          dispatch: h
        }),
        V
      );
    }
  };
  function T(U, ...V) {
    if (!n.apply(this, arguments)) return;
    var N = C(this, V).event(U), I = this.__zoom, k = Math.max(o[0], Math.min(o[1], I.k * Math.pow(2, s.apply(this, arguments)))), X = ts(U);
    if (N.wheel)
      (N.mouse[0][0] !== X[0] || N.mouse[0][1] !== X[1]) && (N.mouse[1] = I.invert(N.mouse[0] = X)), clearTimeout(N.wheel);
    else {
      if (I.k === k) return;
      N.mouse = [X, I.invert(X)], Sd(this), N.start();
    }
    Tc(U), N.wheel = setTimeout(Q, x), N.zoom("mouse", e(w(E(I, k), N.mouse[0], N.mouse[1]), N.extent, c));
    function Q() {
      N.wheel = null, N.end();
    }
  }
  function L(U, ...V) {
    if (g || !n.apply(this, arguments)) return;
    var N = U.currentTarget, I = C(this, V, !0).event(U), k = Ri(U.view).on("mousemove.zoom", W, !0).on("mouseup.zoom", et, !0), X = ts(U, N), Q = U.clientX, F = U.clientY;
    dE(U.view), hg(U), I.mouse = [X, this.__zoom.invert(X)], Sd(this), I.start();
    function W($) {
      if (Tc($), !I.moved) {
        var j = $.clientX - Q, Y = $.clientY - F;
        I.moved = j * j + Y * Y > A;
      }
      I.event($).zoom("mouse", e(w(I.that.__zoom, I.mouse[0] = ts($, N), I.mouse[1]), I.extent, c));
    }
    function et($) {
      k.on("mousemove.zoom mouseup.zoom", null), hE($.view, I.moved), Tc($), I.event($).end();
    }
  }
  function z(U, ...V) {
    if (n.apply(this, arguments)) {
      var N = this.__zoom, I = ts(U.changedTouches ? U.changedTouches[0] : U, this), k = N.invert(I), X = N.k * (U.shiftKey ? 0.5 : 2), Q = e(w(E(N, X), I, k), t.apply(this, V), c);
      Tc(U), u > 0 ? Ri(this).transition().duration(u).call(O, Q, I, U) : Ri(this).call(y.transform, Q, I, U);
    }
  }
  function R(U, ...V) {
    if (n.apply(this, arguments)) {
      var N = U.touches, I = N.length, k = C(this, V, U.changedTouches.length === I).event(U), X, Q, F, W;
      for (hg(U), Q = 0; Q < I; ++Q)
        F = N[Q], W = ts(F, this), W = [W, this.__zoom.invert(W), F.identifier], k.touch0 ? !k.touch1 && k.touch0[2] !== W[2] && (k.touch1 = W, k.taps = 0) : (k.touch0 = W, X = !0, k.taps = 1 + !!m);
      m && (m = clearTimeout(m)), X && (k.taps < 2 && (p = W[0], m = setTimeout(function() {
        m = null;
      }, _)), Sd(this), k.start());
    }
  }
  function B(U, ...V) {
    if (this.__zooming) {
      var N = C(this, V).event(U), I = U.changedTouches, k = I.length, X, Q, F, W;
      for (Tc(U), X = 0; X < k; ++X)
        Q = I[X], F = ts(Q, this), N.touch0 && N.touch0[2] === Q.identifier ? N.touch0[0] = F : N.touch1 && N.touch1[2] === Q.identifier && (N.touch1[0] = F);
      if (Q = N.that.__zoom, N.touch1) {
        var et = N.touch0[0], $ = N.touch0[1], j = N.touch1[0], Y = N.touch1[1], K = (K = j[0] - et[0]) * K + (K = j[1] - et[1]) * K, J = (J = Y[0] - $[0]) * J + (J = Y[1] - $[1]) * J;
        Q = E(Q, Math.sqrt(K / J)), F = [(et[0] + j[0]) / 2, (et[1] + j[1]) / 2], W = [($[0] + Y[0]) / 2, ($[1] + Y[1]) / 2];
      } else if (N.touch0) F = N.touch0[0], W = N.touch0[1];
      else return;
      N.zoom("touch", e(w(Q, F, W), N.extent, c));
    }
  }
  function H(U, ...V) {
    if (this.__zooming) {
      var N = C(this, V).event(U), I = U.changedTouches, k = I.length, X, Q;
      for (hg(U), g && clearTimeout(g), g = setTimeout(function() {
        g = null;
      }, _), X = 0; X < k; ++X)
        Q = I[X], N.touch0 && N.touch0[2] === Q.identifier ? delete N.touch0 : N.touch1 && N.touch1[2] === Q.identifier && delete N.touch1;
      if (N.touch1 && !N.touch0 && (N.touch0 = N.touch1, delete N.touch1), N.touch0) N.touch0[1] = this.__zoom.invert(N.touch0[0]);
      else if (N.end(), N.taps === 2 && (Q = ts(Q, this), Math.hypot(p[0] - Q[0], p[1] - Q[1]) < b)) {
        var F = Ri(this).on("dblclick.zoom");
        F && F.apply(this, arguments);
      }
    }
  }
  return y.wheelDelta = function(U) {
    return arguments.length ? (s = typeof U == "function" ? U : rd(+U), y) : s;
  }, y.filter = function(U) {
    return arguments.length ? (n = typeof U == "function" ? U : rd(!!U), y) : n;
  }, y.touchable = function(U) {
    return arguments.length ? (a = typeof U == "function" ? U : rd(!!U), y) : a;
  }, y.extent = function(U) {
    return arguments.length ? (t = typeof U == "function" ? U : rd([[+U[0][0], +U[0][1]], [+U[1][0], +U[1][1]]]), y) : t;
  }, y.scaleExtent = function(U) {
    return arguments.length ? (o[0] = +U[0], o[1] = +U[1], y) : [o[0], o[1]];
  }, y.translateExtent = function(U) {
    return arguments.length ? (c[0][0] = +U[0][0], c[1][0] = +U[1][0], c[0][1] = +U[0][1], c[1][1] = +U[1][1], y) : [[c[0][0], c[0][1]], [c[1][0], c[1][1]]];
  }, y.constrain = function(U) {
    return arguments.length ? (e = U, y) : e;
  }, y.duration = function(U) {
    return arguments.length ? (u = +U, y) : u;
  }, y.interpolate = function(U) {
    return arguments.length ? (d = U, y) : d;
  }, y.on = function() {
    var U = h.on.apply(h, arguments);
    return U === h ? y : U;
  }, y.clickDistance = function(U) {
    return arguments.length ? (A = (U = +U) * U, y) : Math.sqrt(A);
  }, y.tapDistance = function(U) {
    return arguments.length ? (b = +U, y) : b;
  }, y;
}
const Ds = {
  error001: () => "[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",
  error002: () => "It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",
  error003: (n) => `Node type "${n}" not found. Using fallback type "default".`,
  error004: () => "The React Flow parent container needs a width and a height to render the graph.",
  error005: () => "Only child nodes can use a parent extent.",
  error006: () => "Can't create edge. An edge needs a source and a target.",
  error007: (n) => `The old edge with id=${n} does not exist.`,
  error009: (n) => `Marker type "${n}" doesn't exist.`,
  error008: (n, { id: t, sourceHandle: e, targetHandle: s }) => `Couldn't create edge for ${n} handle id: "${n === "source" ? e : s}", edge id: ${t}.`,
  error010: () => "Handle: No node id found. Make sure to only use a Handle inside a custom Node.",
  error011: (n) => `Edge type "${n}" not found. Using fallback type "default".`,
  error012: (n) => `Node with id "${n}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,
  error013: (n = "react") => `It seems that you haven't loaded the styles. Please import '@xyflow/${n}/dist/style.css' or base.css to make sure everything is working properly.`,
  error014: () => "useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",
  error015: () => "It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."
}, $c = [
  [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY],
  [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]
], DE = ["Enter", " ", "Escape"], NE = {
  "node.a11yDescription.default": "Press enter or space to select a node. Press delete to remove it and escape to cancel.",
  "node.a11yDescription.keyboardDisabled": "Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.",
  "node.a11yDescription.ariaLiveMessage": ({ direction: n, x: t, y: e }) => `Moved selected node ${n}. New position, x: ${t}, y: ${e}`,
  "edge.a11yDescription.default": "Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.",
  // Control elements
  "controls.ariaLabel": "Control Panel",
  "controls.zoomIn.ariaLabel": "Zoom In",
  "controls.zoomOut.ariaLabel": "Zoom Out",
  "controls.fitView.ariaLabel": "Fit View",
  "controls.interactive.ariaLabel": "Toggle Interactivity",
  // Mini map
  "minimap.ariaLabel": "Mini Map",
  // Handle
  "handle.ariaLabel": "Handle"
};
var _l;
(function(n) {
  n.Strict = "strict", n.Loose = "loose";
})(_l || (_l = {}));
var Ga;
(function(n) {
  n.Free = "free", n.Vertical = "vertical", n.Horizontal = "horizontal";
})(Ga || (Ga = {}));
var Kc;
(function(n) {
  n.Partial = "partial", n.Full = "full";
})(Kc || (Kc = {}));
const OE = {
  inProgress: !1,
  isValid: null,
  from: null,
  fromHandle: null,
  fromPosition: null,
  fromNode: null,
  to: null,
  toHandle: null,
  toPosition: null,
  toNode: null,
  pointer: null
};
var ea;
(function(n) {
  n.Bezier = "default", n.Straight = "straight", n.Step = "step", n.SmoothStep = "smoothstep", n.SimpleBezier = "simplebezier";
})(ea || (ea = {}));
var zd;
(function(n) {
  n.Arrow = "arrow", n.ArrowClosed = "arrowclosed";
})(zd || (zd = {}));
var oe;
(function(n) {
  n.Left = "left", n.Top = "top", n.Right = "right", n.Bottom = "bottom";
})(oe || (oe = {}));
const c1 = {
  [oe.Left]: oe.Right,
  [oe.Right]: oe.Left,
  [oe.Top]: oe.Bottom,
  [oe.Bottom]: oe.Top
};
function LE(n) {
  return n === null ? null : n ? "valid" : "invalid";
}
const UE = (n) => "id" in n && "source" in n && "target" in n, NB = (n) => "id" in n && "position" in n && !("source" in n) && !("target" in n), gv = (n) => "id" in n && "internals" in n && !("source" in n) && !("target" in n), ru = (n, t = [0, 0]) => {
  const { width: e, height: s } = gr(n), a = n.origin ?? t, o = e * a[0], c = s * a[1];
  return {
    x: n.position.x - o,
    y: n.position.y - c
  };
}, OB = (n, t = { nodeOrigin: [0, 0] }) => {
  if (n.length === 0)
    return { x: 0, y: 0, width: 0, height: 0 };
  const e = n.reduce((s, a) => {
    const o = typeof a == "string";
    let c = !t.nodeLookup && !o ? a : void 0;
    t.nodeLookup && (c = o ? t.nodeLookup.get(a) : gv(a) ? a : t.nodeLookup.get(a.id));
    const u = c ? Fd(c, t.nodeOrigin) : { x: 0, y: 0, x2: 0, y2: 0 };
    return sh(s, u);
  }, { x: 1 / 0, y: 1 / 0, x2: -1 / 0, y2: -1 / 0 });
  return rh(e);
}, au = (n, t = {}) => {
  let e = { x: 1 / 0, y: 1 / 0, x2: -1 / 0, y2: -1 / 0 }, s = !1;
  return n.forEach((a) => {
    (t.filter === void 0 || t.filter(a)) && (e = sh(e, Fd(a)), s = !0);
  }), s ? rh(e) : { x: 0, y: 0, width: 0, height: 0 };
}, vv = (n, t, [e, s, a] = [0, 0, 1], o = !1, c = !1) => {
  const u = {
    ...lu(t, [e, s, a]),
    width: t.width / a,
    height: t.height / a
  }, d = [];
  for (const h of n.values()) {
    const { measured: m, selectable: p = !0, hidden: g = !1 } = h;
    if (c && !p || g)
      continue;
    const _ = m.width ?? h.width ?? h.initialWidth ?? null, x = m.height ?? h.height ?? h.initialHeight ?? null, A = Qc(u, xl(h)), b = (_ ?? 0) * (x ?? 0), y = o && A > 0;
    (!h.internals.handleBounds || y || A >= b || h.dragging) && d.push(h);
  }
  return d;
}, LB = (n, t) => {
  const e = /* @__PURE__ */ new Set();
  return n.forEach((s) => {
    e.add(s.id);
  }), t.filter((s) => e.has(s.source) || e.has(s.target));
};
function UB(n, t) {
  const e = /* @__PURE__ */ new Map(), s = t != null && t.nodes ? new Set(t.nodes.map((a) => a.id)) : null;
  return n.forEach((a) => {
    a.measured.width && a.measured.height && ((t == null ? void 0 : t.includeHiddenNodes) || !a.hidden) && (!s || s.has(a.id)) && e.set(a.id, a);
  }), e;
}
async function PB({ nodes: n, width: t, height: e, panZoom: s, minZoom: a, maxZoom: o }, c) {
  if (n.size === 0)
    return Promise.resolve(!0);
  const u = UB(n, c), d = au(u), h = _v(d, t, e, (c == null ? void 0 : c.minZoom) ?? a, (c == null ? void 0 : c.maxZoom) ?? o, (c == null ? void 0 : c.padding) ?? 0.1);
  return await s.setViewport(h, {
    duration: c == null ? void 0 : c.duration,
    ease: c == null ? void 0 : c.ease,
    interpolate: c == null ? void 0 : c.interpolate
  }), Promise.resolve(!0);
}
function PE({ nodeId: n, nextPosition: t, nodeLookup: e, nodeOrigin: s = [0, 0], nodeExtent: a, onError: o }) {
  const c = e.get(n), u = c.parentId ? e.get(c.parentId) : void 0, { x: d, y: h } = u ? u.internals.positionAbsolute : { x: 0, y: 0 }, m = c.origin ?? s;
  let p = c.extent || a;
  if (c.extent === "parent" && !c.expandParent)
    if (!u)
      o == null || o("005", Ds.error005());
    else {
      const _ = u.measured.width, x = u.measured.height;
      _ && x && (p = [
        [d, h],
        [d + _, h + x]
      ]);
    }
  else u && Sl(c.extent) && (p = [
    [c.extent[0][0] + d, c.extent[0][1] + h],
    [c.extent[1][0] + d, c.extent[1][1] + h]
  ]);
  const g = Sl(p) ? Ya(t, p, c.measured) : t;
  return (c.measured.width === void 0 || c.measured.height === void 0) && (o == null || o("015", Ds.error015())), {
    position: {
      x: g.x - d + (c.measured.width ?? 0) * m[0],
      y: g.y - h + (c.measured.height ?? 0) * m[1]
    },
    positionAbsolute: g
  };
}
async function IB({ nodesToRemove: n = [], edgesToRemove: t = [], nodes: e, edges: s, onBeforeDelete: a }) {
  const o = new Set(n.map((g) => g.id)), c = [];
  for (const g of e) {
    if (g.deletable === !1)
      continue;
    const _ = o.has(g.id), x = !_ && g.parentId && c.find((A) => A.id === g.parentId);
    (_ || x) && c.push(g);
  }
  const u = new Set(t.map((g) => g.id)), d = s.filter((g) => g.deletable !== !1), m = LB(c, d);
  for (const g of d)
    u.has(g.id) && !m.find((x) => x.id === g.id) && m.push(g);
  if (!a)
    return {
      edges: m,
      nodes: c
    };
  const p = await a({
    nodes: c,
    edges: m
  });
  return typeof p == "boolean" ? p ? { edges: m, nodes: c } : { edges: [], nodes: [] } : p;
}
const yl = (n, t = 0, e = 1) => Math.min(Math.max(n, t), e), Ya = (n = { x: 0, y: 0 }, t, e) => ({
  x: yl(n.x, t[0][0], t[1][0] - ((e == null ? void 0 : e.width) ?? 0)),
  y: yl(n.y, t[0][1], t[1][1] - ((e == null ? void 0 : e.height) ?? 0))
});
function IE(n, t, e) {
  const { width: s, height: a } = gr(e), { x: o, y: c } = e.internals.positionAbsolute;
  return Ya(n, [
    [o, c],
    [o + s, c + a]
  ], t);
}
const u1 = (n, t, e) => n < t ? yl(Math.abs(n - t), 1, t) / t : n > e ? -yl(Math.abs(n - e), 1, t) / t : 0, BE = (n, t, e = 15, s = 40) => {
  const a = u1(n.x, s, t.width - s) * e, o = u1(n.y, s, t.height - s) * e;
  return [a, o];
}, sh = (n, t) => ({
  x: Math.min(n.x, t.x),
  y: Math.min(n.y, t.y),
  x2: Math.max(n.x2, t.x2),
  y2: Math.max(n.y2, t.y2)
}), N0 = ({ x: n, y: t, width: e, height: s }) => ({
  x: n,
  y: t,
  x2: n + e,
  y2: t + s
}), rh = ({ x: n, y: t, x2: e, y2: s }) => ({
  x: n,
  y: t,
  width: e - n,
  height: s - t
}), xl = (n, t = [0, 0]) => {
  var a, o;
  const { x: e, y: s } = gv(n) ? n.internals.positionAbsolute : ru(n, t);
  return {
    x: e,
    y: s,
    width: ((a = n.measured) == null ? void 0 : a.width) ?? n.width ?? n.initialWidth ?? 0,
    height: ((o = n.measured) == null ? void 0 : o.height) ?? n.height ?? n.initialHeight ?? 0
  };
}, Fd = (n, t = [0, 0]) => {
  var a, o;
  const { x: e, y: s } = gv(n) ? n.internals.positionAbsolute : ru(n, t);
  return {
    x: e,
    y: s,
    x2: e + (((a = n.measured) == null ? void 0 : a.width) ?? n.width ?? n.initialWidth ?? 0),
    y2: s + (((o = n.measured) == null ? void 0 : o.height) ?? n.height ?? n.initialHeight ?? 0)
  };
}, zE = (n, t) => rh(sh(N0(n), N0(t))), Qc = (n, t) => {
  const e = Math.max(0, Math.min(n.x + n.width, t.x + t.width) - Math.max(n.x, t.x)), s = Math.max(0, Math.min(n.y + n.height, t.y + t.height) - Math.max(n.y, t.y));
  return Math.ceil(e * s);
}, f1 = (n) => ss(n.width) && ss(n.height) && ss(n.x) && ss(n.y), ss = (n) => !isNaN(n) && isFinite(n), BB = (n, t) => {
}, ou = (n, t = [1, 1]) => ({
  x: t[0] * Math.round(n.x / t[0]),
  y: t[1] * Math.round(n.y / t[1])
}), lu = ({ x: n, y: t }, [e, s, a], o = !1, c = [1, 1]) => {
  const u = {
    x: (n - e) / a,
    y: (t - s) / a
  };
  return o ? ou(u, c) : u;
}, Hd = ({ x: n, y: t }, [e, s, a]) => ({
  x: n * a + e,
  y: t * a + s
});
function tl(n, t) {
  if (typeof n == "number")
    return Math.floor((t - t / (1 + n)) * 0.5);
  if (typeof n == "string" && n.endsWith("px")) {
    const e = parseFloat(n);
    if (!Number.isNaN(e))
      return Math.floor(e);
  }
  if (typeof n == "string" && n.endsWith("%")) {
    const e = parseFloat(n);
    if (!Number.isNaN(e))
      return Math.floor(t * e * 0.01);
  }
  return console.error(`[React Flow] The padding value "${n}" is invalid. Please provide a number or a string with a valid unit (px or %).`), 0;
}
function zB(n, t, e) {
  if (typeof n == "string" || typeof n == "number") {
    const s = tl(n, e), a = tl(n, t);
    return {
      top: s,
      right: a,
      bottom: s,
      left: a,
      x: a * 2,
      y: s * 2
    };
  }
  if (typeof n == "object") {
    const s = tl(n.top ?? n.y ?? 0, e), a = tl(n.bottom ?? n.y ?? 0, e), o = tl(n.left ?? n.x ?? 0, t), c = tl(n.right ?? n.x ?? 0, t);
    return { top: s, right: c, bottom: a, left: o, x: o + c, y: s + a };
  }
  return { top: 0, right: 0, bottom: 0, left: 0, x: 0, y: 0 };
}
function FB(n, t, e, s, a, o) {
  const { x: c, y: u } = Hd(n, [t, e, s]), { x: d, y: h } = Hd({ x: n.x + n.width, y: n.y + n.height }, [t, e, s]), m = a - d, p = o - h;
  return {
    left: Math.floor(c),
    top: Math.floor(u),
    right: Math.floor(m),
    bottom: Math.floor(p)
  };
}
const _v = (n, t, e, s, a, o) => {
  const c = zB(o, t, e), u = (t - c.x) / n.width, d = (e - c.y) / n.height, h = Math.min(u, d), m = yl(h, s, a), p = n.x + n.width / 2, g = n.y + n.height / 2, _ = t / 2 - p * m, x = e / 2 - g * m, A = FB(n, _, x, m, t, e), b = {
    left: Math.min(A.left - c.left, 0),
    top: Math.min(A.top - c.top, 0),
    right: Math.min(A.right - c.right, 0),
    bottom: Math.min(A.bottom - c.bottom, 0)
  };
  return {
    x: _ - b.left + b.right,
    y: x - b.top + b.bottom,
    zoom: m
  };
}, Jc = () => {
  var n;
  return typeof navigator < "u" && ((n = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : n.indexOf("Mac")) >= 0;
};
function Sl(n) {
  return n != null && n !== "parent";
}
function gr(n) {
  var t, e;
  return {
    width: ((t = n.measured) == null ? void 0 : t.width) ?? n.width ?? n.initialWidth ?? 0,
    height: ((e = n.measured) == null ? void 0 : e.height) ?? n.height ?? n.initialHeight ?? 0
  };
}
function FE(n) {
  var t, e;
  return (((t = n.measured) == null ? void 0 : t.width) ?? n.width ?? n.initialWidth) !== void 0 && (((e = n.measured) == null ? void 0 : e.height) ?? n.height ?? n.initialHeight) !== void 0;
}
function HE(n, t = { width: 0, height: 0 }, e, s, a) {
  const o = { ...n }, c = s.get(e);
  if (c) {
    const u = c.origin || a;
    o.x += c.internals.positionAbsolute.x - (t.width ?? 0) * u[0], o.y += c.internals.positionAbsolute.y - (t.height ?? 0) * u[1];
  }
  return o;
}
function d1(n, t) {
  if (n.size !== t.size)
    return !1;
  for (const e of n)
    if (!t.has(e))
      return !1;
  return !0;
}
function HB() {
  let n, t;
  return { promise: new Promise((s, a) => {
    n = s, t = a;
  }), resolve: n, reject: t };
}
function VB(n) {
  return { ...NE, ...n || {} };
}
function Bc(n, { snapGrid: t = [0, 0], snapToGrid: e = !1, transform: s, containerBounds: a }) {
  const { x: o, y: c } = rs(n), u = lu({ x: o - ((a == null ? void 0 : a.left) ?? 0), y: c - ((a == null ? void 0 : a.top) ?? 0) }, s), { x: d, y: h } = e ? ou(u, t) : u;
  return {
    xSnapped: d,
    ySnapped: h,
    ...u
  };
}
const yv = (n) => ({
  width: n.offsetWidth,
  height: n.offsetHeight
}), VE = (n) => {
  var t;
  return ((t = n == null ? void 0 : n.getRootNode) == null ? void 0 : t.call(n)) || (window == null ? void 0 : window.document);
}, GB = ["INPUT", "SELECT", "TEXTAREA"];
function GE(n) {
  var s, a;
  const t = ((a = (s = n.composedPath) == null ? void 0 : s.call(n)) == null ? void 0 : a[0]) || n.target;
  return (t == null ? void 0 : t.nodeType) !== 1 ? !1 : GB.includes(t.nodeName) || t.hasAttribute("contenteditable") || !!t.closest(".nokey");
}
const kE = (n) => "clientX" in n, rs = (n, t) => {
  var o, c;
  const e = kE(n), s = e ? n.clientX : (o = n.touches) == null ? void 0 : o[0].clientX, a = e ? n.clientY : (c = n.touches) == null ? void 0 : c[0].clientY;
  return {
    x: s - ((t == null ? void 0 : t.left) ?? 0),
    y: a - ((t == null ? void 0 : t.top) ?? 0)
  };
}, h1 = (n, t, e, s, a) => {
  const o = t.querySelectorAll(`.${n}`);
  return !o || !o.length ? null : Array.from(o).map((c) => {
    const u = c.getBoundingClientRect();
    return {
      id: c.getAttribute("data-handleid"),
      type: n,
      nodeId: a,
      position: c.getAttribute("data-handlepos"),
      x: (u.left - e.left) / s,
      y: (u.top - e.top) / s,
      ...yv(c)
    };
  });
};
function XE({ sourceX: n, sourceY: t, targetX: e, targetY: s, sourceControlX: a, sourceControlY: o, targetControlX: c, targetControlY: u }) {
  const d = n * 0.125 + a * 0.375 + c * 0.375 + e * 0.125, h = t * 0.125 + o * 0.375 + u * 0.375 + s * 0.125, m = Math.abs(d - n), p = Math.abs(h - t);
  return [d, h, m, p];
}
function ad(n, t) {
  return n >= 0 ? 0.5 * n : t * 25 * Math.sqrt(-n);
}
function p1({ pos: n, x1: t, y1: e, x2: s, y2: a, c: o }) {
  switch (n) {
    case oe.Left:
      return [t - ad(t - s, o), e];
    case oe.Right:
      return [t + ad(s - t, o), e];
    case oe.Top:
      return [t, e - ad(e - a, o)];
    case oe.Bottom:
      return [t, e + ad(a - e, o)];
  }
}
function WE({ sourceX: n, sourceY: t, sourcePosition: e = oe.Bottom, targetX: s, targetY: a, targetPosition: o = oe.Top, curvature: c = 0.25 }) {
  const [u, d] = p1({
    pos: e,
    x1: n,
    y1: t,
    x2: s,
    y2: a,
    c
  }), [h, m] = p1({
    pos: o,
    x1: s,
    y1: a,
    x2: n,
    y2: t,
    c
  }), [p, g, _, x] = XE({
    sourceX: n,
    sourceY: t,
    targetX: s,
    targetY: a,
    sourceControlX: u,
    sourceControlY: d,
    targetControlX: h,
    targetControlY: m
  });
  return [
    `M${n},${t} C${u},${d} ${h},${m} ${s},${a}`,
    p,
    g,
    _,
    x
  ];
}
function YE({ sourceX: n, sourceY: t, targetX: e, targetY: s }) {
  const a = Math.abs(e - n) / 2, o = e < n ? e + a : e - a, c = Math.abs(s - t) / 2, u = s < t ? s + c : s - c;
  return [o, u, a, c];
}
function kB({ sourceNode: n, targetNode: t, selected: e = !1, zIndex: s = 0, elevateOnSelect: a = !1, zIndexMode: o = "basic" }) {
  if (o === "manual")
    return s;
  const c = a && e ? s + 1e3 : s, u = Math.max(n.parentId || a && n.selected ? n.internals.z : 0, t.parentId || a && t.selected ? t.internals.z : 0);
  return c + u;
}
function XB({ sourceNode: n, targetNode: t, width: e, height: s, transform: a }) {
  const o = sh(Fd(n), Fd(t));
  o.x === o.x2 && (o.x2 += 1), o.y === o.y2 && (o.y2 += 1);
  const c = {
    x: -a[0] / a[2],
    y: -a[1] / a[2],
    width: e / a[2],
    height: s / a[2]
  };
  return Qc(c, rh(o)) > 0;
}
const WB = ({ source: n, sourceHandle: t, target: e, targetHandle: s }) => `xy-edge__${n}${t || ""}-${e}${s || ""}`, YB = (n, t) => t.some((e) => e.source === n.source && e.target === n.target && (e.sourceHandle === n.sourceHandle || !e.sourceHandle && !n.sourceHandle) && (e.targetHandle === n.targetHandle || !e.targetHandle && !n.targetHandle)), jE = (n, t, e = {}) => {
  if (!n.source || !n.target)
    return t;
  const s = e.getEdgeId || WB;
  let a;
  return UE(n) ? a = { ...n } : a = {
    ...n,
    id: s(n)
  }, YB(a, t) ? t : (a.sourceHandle === null && delete a.sourceHandle, a.targetHandle === null && delete a.targetHandle, t.concat(a));
};
function qE({ sourceX: n, sourceY: t, targetX: e, targetY: s }) {
  const [a, o, c, u] = YE({
    sourceX: n,
    sourceY: t,
    targetX: e,
    targetY: s
  });
  return [`M ${n},${t}L ${e},${s}`, a, o, c, u];
}
const m1 = {
  [oe.Left]: { x: -1, y: 0 },
  [oe.Right]: { x: 1, y: 0 },
  [oe.Top]: { x: 0, y: -1 },
  [oe.Bottom]: { x: 0, y: 1 }
}, jB = ({ source: n, sourcePosition: t = oe.Bottom, target: e }) => t === oe.Left || t === oe.Right ? n.x < e.x ? { x: 1, y: 0 } : { x: -1, y: 0 } : n.y < e.y ? { x: 0, y: 1 } : { x: 0, y: -1 }, g1 = (n, t) => Math.sqrt(Math.pow(t.x - n.x, 2) + Math.pow(t.y - n.y, 2));
function qB({ source: n, sourcePosition: t = oe.Bottom, target: e, targetPosition: s = oe.Top, center: a, offset: o, stepPosition: c }) {
  const u = m1[t], d = m1[s], h = { x: n.x + u.x * o, y: n.y + u.y * o }, m = { x: e.x + d.x * o, y: e.y + d.y * o }, p = jB({
    source: h,
    sourcePosition: t,
    target: m
  }), g = p.x !== 0 ? "x" : "y", _ = p[g];
  let x = [], A, b;
  const y = { x: 0, y: 0 }, E = { x: 0, y: 0 }, [, , w, M] = YE({
    sourceX: n.x,
    sourceY: n.y,
    targetX: e.x,
    targetY: e.y
  });
  if (u[g] * d[g] === -1) {
    g === "x" ? (A = a.x ?? h.x + (m.x - h.x) * c, b = a.y ?? (h.y + m.y) / 2) : (A = a.x ?? (h.x + m.x) / 2, b = a.y ?? h.y + (m.y - h.y) * c);
    const C = [
      { x: A, y: h.y },
      { x: A, y: m.y }
    ], D = [
      { x: h.x, y: b },
      { x: m.x, y: b }
    ];
    u[g] === _ ? x = g === "x" ? C : D : x = g === "x" ? D : C;
  } else {
    const C = [{ x: h.x, y: m.y }], D = [{ x: m.x, y: h.y }];
    if (g === "x" ? x = u.x === _ ? D : C : x = u.y === _ ? C : D, t === s) {
      const B = Math.abs(n[g] - e[g]);
      if (B <= o) {
        const H = Math.min(o - 1, o - B);
        u[g] === _ ? y[g] = (h[g] > n[g] ? -1 : 1) * H : E[g] = (m[g] > e[g] ? -1 : 1) * H;
      }
    }
    if (t !== s) {
      const B = g === "x" ? "y" : "x", H = u[g] === d[B], U = h[B] > m[B], V = h[B] < m[B];
      (u[g] === 1 && (!H && U || H && V) || u[g] !== 1 && (!H && V || H && U)) && (x = g === "x" ? C : D);
    }
    const T = { x: h.x + y.x, y: h.y + y.y }, L = { x: m.x + E.x, y: m.y + E.y }, z = Math.max(Math.abs(T.x - x[0].x), Math.abs(L.x - x[0].x)), R = Math.max(Math.abs(T.y - x[0].y), Math.abs(L.y - x[0].y));
    z >= R ? (A = (T.x + L.x) / 2, b = x[0].y) : (A = x[0].x, b = (T.y + L.y) / 2);
  }
  return [[
    n,
    { x: h.x + y.x, y: h.y + y.y },
    ...x,
    { x: m.x + E.x, y: m.y + E.y },
    e
  ], A, b, w, M];
}
function ZB(n, t, e, s) {
  const a = Math.min(g1(n, t) / 2, g1(t, e) / 2, s), { x: o, y: c } = t;
  if (n.x === o && o === e.x || n.y === c && c === e.y)
    return `L${o} ${c}`;
  if (n.y === c) {
    const h = n.x < e.x ? -1 : 1, m = n.y < e.y ? 1 : -1;
    return `L ${o + a * h},${c}Q ${o},${c} ${o},${c + a * m}`;
  }
  const u = n.x < e.x ? 1 : -1, d = n.y < e.y ? -1 : 1;
  return `L ${o},${c + a * d}Q ${o},${c} ${o + a * u},${c}`;
}
function O0({ sourceX: n, sourceY: t, sourcePosition: e = oe.Bottom, targetX: s, targetY: a, targetPosition: o = oe.Top, borderRadius: c = 5, centerX: u, centerY: d, offset: h = 20, stepPosition: m = 0.5 }) {
  const [p, g, _, x, A] = qB({
    source: { x: n, y: t },
    sourcePosition: e,
    target: { x: s, y: a },
    targetPosition: o,
    center: { x: u, y: d },
    offset: h,
    stepPosition: m
  });
  return [p.reduce((y, E, w) => {
    let M = "";
    return w > 0 && w < p.length - 1 ? M = ZB(p[w - 1], E, p[w + 1], c) : M = `${w === 0 ? "M" : "L"}${E.x} ${E.y}`, y += M, y;
  }, ""), g, _, x, A];
}
function v1(n) {
  var t;
  return n && !!(n.internals.handleBounds || (t = n.handles) != null && t.length) && !!(n.measured.width || n.width || n.initialWidth);
}
function $B(n) {
  var p;
  const { sourceNode: t, targetNode: e } = n;
  if (!v1(t) || !v1(e))
    return null;
  const s = t.internals.handleBounds || _1(t.handles), a = e.internals.handleBounds || _1(e.handles), o = y1((s == null ? void 0 : s.source) ?? [], n.sourceHandle), c = y1(
    // when connection type is loose we can define all handles as sources and connect source -> source
    n.connectionMode === _l.Strict ? (a == null ? void 0 : a.target) ?? [] : ((a == null ? void 0 : a.target) ?? []).concat((a == null ? void 0 : a.source) ?? []),
    n.targetHandle
  );
  if (!o || !c)
    return (p = n.onError) == null || p.call(n, "008", Ds.error008(o ? "target" : "source", {
      id: n.id,
      sourceHandle: n.sourceHandle,
      targetHandle: n.targetHandle
    })), null;
  const u = (o == null ? void 0 : o.position) || oe.Bottom, d = (c == null ? void 0 : c.position) || oe.Top, h = ja(t, o, u), m = ja(e, c, d);
  return {
    sourceX: h.x,
    sourceY: h.y,
    targetX: m.x,
    targetY: m.y,
    sourcePosition: u,
    targetPosition: d
  };
}
function _1(n) {
  if (!n)
    return null;
  const t = [], e = [];
  for (const s of n)
    s.width = s.width ?? 1, s.height = s.height ?? 1, s.type === "source" ? t.push(s) : s.type === "target" && e.push(s);
  return {
    source: t,
    target: e
  };
}
function ja(n, t, e = oe.Left, s = !1) {
  const a = ((t == null ? void 0 : t.x) ?? 0) + n.internals.positionAbsolute.x, o = ((t == null ? void 0 : t.y) ?? 0) + n.internals.positionAbsolute.y, { width: c, height: u } = t ?? gr(n);
  if (s)
    return { x: a + c / 2, y: o + u / 2 };
  switch ((t == null ? void 0 : t.position) ?? e) {
    case oe.Top:
      return { x: a + c / 2, y: o };
    case oe.Right:
      return { x: a + c, y: o + u / 2 };
    case oe.Bottom:
      return { x: a + c / 2, y: o + u };
    case oe.Left:
      return { x: a, y: o + u / 2 };
  }
}
function y1(n, t) {
  return n && (t ? n.find((e) => e.id === t) : n[0]) || null;
}
function L0(n, t) {
  return n ? typeof n == "string" ? n : `${t ? `${t}__` : ""}${Object.keys(n).sort().map((s) => `${s}=${n[s]}`).join("&")}` : "";
}
function KB(n, { id: t, defaultColor: e, defaultMarkerStart: s, defaultMarkerEnd: a }) {
  const o = /* @__PURE__ */ new Set();
  return n.reduce((c, u) => ([u.markerStart || s, u.markerEnd || a].forEach((d) => {
    if (d && typeof d == "object") {
      const h = L0(d, t);
      o.has(h) || (c.push({ id: h, color: d.color || e, ...d }), o.add(h));
    }
  }), c), []).sort((c, u) => c.id.localeCompare(u.id));
}
const ZE = 1e3, QB = 10, xv = {
  nodeOrigin: [0, 0],
  nodeExtent: $c,
  elevateNodesOnSelect: !0,
  zIndexMode: "basic",
  defaults: {}
}, JB = {
  ...xv,
  checkEquality: !0
};
function Sv(n, t) {
  const e = { ...n };
  for (const s in t)
    t[s] !== void 0 && (e[s] = t[s]);
  return e;
}
function tz(n, t, e) {
  const s = Sv(xv, e);
  for (const a of n.values())
    if (a.parentId)
      Mv(a, n, t, s);
    else {
      const o = ru(a, s.nodeOrigin), c = Sl(a.extent) ? a.extent : s.nodeExtent, u = Ya(o, c, gr(a));
      a.internals.positionAbsolute = u;
    }
}
function ez(n, t) {
  if (!n.handles)
    return n.measured ? t == null ? void 0 : t.internals.handleBounds : void 0;
  const e = [], s = [];
  for (const a of n.handles) {
    const o = {
      id: a.id,
      width: a.width ?? 1,
      height: a.height ?? 1,
      nodeId: n.id,
      x: a.x,
      y: a.y,
      position: a.position,
      type: a.type
    };
    a.type === "source" ? e.push(o) : a.type === "target" && s.push(o);
  }
  return {
    source: e,
    target: s
  };
}
function bv(n) {
  return n === "manual";
}
function U0(n, t, e, s = {}) {
  var h, m;
  const a = Sv(JB, s), o = { i: 0 }, c = new Map(t), u = a != null && a.elevateNodesOnSelect && !bv(a.zIndexMode) ? ZE : 0;
  let d = n.length > 0;
  t.clear(), e.clear();
  for (const p of n) {
    let g = c.get(p.id);
    if (a.checkEquality && p === (g == null ? void 0 : g.internals.userNode))
      t.set(p.id, g);
    else {
      const _ = ru(p, a.nodeOrigin), x = Sl(p.extent) ? p.extent : a.nodeExtent, A = Ya(_, x, gr(p));
      g = {
        ...a.defaults,
        ...p,
        measured: {
          width: (h = p.measured) == null ? void 0 : h.width,
          height: (m = p.measured) == null ? void 0 : m.height
        },
        internals: {
          positionAbsolute: A,
          // if user re-initializes the node or removes `measured` for whatever reason, we reset the handleBounds so that the node gets re-measured
          handleBounds: ez(p, g),
          z: $E(p, u, a.zIndexMode),
          userNode: p
        }
      }, t.set(p.id, g);
    }
    (g.measured === void 0 || g.measured.width === void 0 || g.measured.height === void 0) && !g.hidden && (d = !1), p.parentId && Mv(g, t, e, s, o);
  }
  return d;
}
function nz(n, t) {
  if (!n.parentId)
    return;
  const e = t.get(n.parentId);
  e ? e.set(n.id, n) : t.set(n.parentId, /* @__PURE__ */ new Map([[n.id, n]]));
}
function Mv(n, t, e, s, a) {
  const { elevateNodesOnSelect: o, nodeOrigin: c, nodeExtent: u, zIndexMode: d } = Sv(xv, s), h = n.parentId, m = t.get(h);
  if (!m) {
    console.warn(`Parent node ${h} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);
    return;
  }
  nz(n, e), a && !m.parentId && m.internals.rootParentIndex === void 0 && d === "auto" && (m.internals.rootParentIndex = ++a.i, m.internals.z = m.internals.z + a.i * QB), a && m.internals.rootParentIndex !== void 0 && (a.i = m.internals.rootParentIndex);
  const p = o && !bv(d) ? ZE : 0, { x: g, y: _, z: x } = iz(n, m, c, u, p, d), { positionAbsolute: A } = n.internals, b = g !== A.x || _ !== A.y;
  (b || x !== n.internals.z) && t.set(n.id, {
    ...n,
    internals: {
      ...n.internals,
      positionAbsolute: b ? { x: g, y: _ } : A,
      z: x
    }
  });
}
function $E(n, t, e) {
  const s = ss(n.zIndex) ? n.zIndex : 0;
  return bv(e) ? s : s + (n.selected ? t : 0);
}
function iz(n, t, e, s, a, o) {
  const { x: c, y: u } = t.internals.positionAbsolute, d = gr(n), h = ru(n, e), m = Sl(n.extent) ? Ya(h, n.extent, d) : h;
  let p = Ya({ x: c + m.x, y: u + m.y }, s, d);
  n.extent === "parent" && (p = IE(p, d, t));
  const g = $E(n, a, o), _ = t.internals.z ?? 0;
  return {
    x: p.x,
    y: p.y,
    z: _ >= g ? _ + 1 : g
  };
}
function Ev(n, t, e, s = [0, 0]) {
  var c;
  const a = [], o = /* @__PURE__ */ new Map();
  for (const u of n) {
    const d = t.get(u.parentId);
    if (!d)
      continue;
    const h = ((c = o.get(u.parentId)) == null ? void 0 : c.expandedRect) ?? xl(d), m = zE(h, u.rect);
    o.set(u.parentId, { expandedRect: m, parent: d });
  }
  return o.size > 0 && o.forEach(({ expandedRect: u, parent: d }, h) => {
    var w;
    const m = d.internals.positionAbsolute, p = gr(d), g = d.origin ?? s, _ = u.x < m.x ? Math.round(Math.abs(m.x - u.x)) : 0, x = u.y < m.y ? Math.round(Math.abs(m.y - u.y)) : 0, A = Math.max(p.width, Math.round(u.width)), b = Math.max(p.height, Math.round(u.height)), y = (A - p.width) * g[0], E = (b - p.height) * g[1];
    (_ > 0 || x > 0 || y || E) && (a.push({
      id: h,
      type: "position",
      position: {
        x: d.position.x - _ + y,
        y: d.position.y - x + E
      }
    }), (w = e.get(h)) == null || w.forEach((M) => {
      n.some((O) => O.id === M.id) || a.push({
        id: M.id,
        type: "position",
        position: {
          x: M.position.x + _,
          y: M.position.y + x
        }
      });
    })), (p.width < u.width || p.height < u.height || _ || x) && a.push({
      id: h,
      type: "dimensions",
      setAttributes: !0,
      dimensions: {
        width: A + (_ ? g[0] * _ - y : 0),
        height: b + (x ? g[1] * x - E : 0)
      }
    });
  }), a;
}
function sz(n, t, e, s, a, o, c) {
  const u = s == null ? void 0 : s.querySelector(".xyflow__viewport");
  let d = !1;
  if (!u)
    return { changes: [], updatedInternals: d };
  const h = [], m = window.getComputedStyle(u), { m22: p } = new window.DOMMatrixReadOnly(m.transform), g = [];
  for (const _ of n.values()) {
    const x = t.get(_.id);
    if (!x)
      continue;
    if (x.hidden) {
      t.set(x.id, {
        ...x,
        internals: {
          ...x.internals,
          handleBounds: void 0
        }
      }), d = !0;
      continue;
    }
    const A = yv(_.nodeElement), b = x.measured.width !== A.width || x.measured.height !== A.height;
    if (!!(A.width && A.height && (b || !x.internals.handleBounds || _.force))) {
      const E = _.nodeElement.getBoundingClientRect(), w = Sl(x.extent) ? x.extent : o;
      let { positionAbsolute: M } = x.internals;
      x.parentId && x.extent === "parent" ? M = IE(M, A, t.get(x.parentId)) : w && (M = Ya(M, w, A));
      const O = {
        ...x,
        measured: A,
        internals: {
          ...x.internals,
          positionAbsolute: M,
          handleBounds: {
            source: h1("source", _.nodeElement, E, p, x.id),
            target: h1("target", _.nodeElement, E, p, x.id)
          }
        }
      };
      t.set(x.id, O), x.parentId && Mv(O, t, e, { nodeOrigin: a, zIndexMode: c }), d = !0, b && (h.push({
        id: x.id,
        type: "dimensions",
        dimensions: A
      }), x.expandParent && x.parentId && g.push({
        id: x.id,
        parentId: x.parentId,
        rect: xl(O, a)
      }));
    }
  }
  if (g.length > 0) {
    const _ = Ev(g, t, e, a);
    h.push(..._);
  }
  return { changes: h, updatedInternals: d };
}
async function rz({ delta: n, panZoom: t, transform: e, translateExtent: s, width: a, height: o }) {
  if (!t || !n.x && !n.y)
    return Promise.resolve(!1);
  const c = await t.setViewportConstrained({
    x: e[0] + n.x,
    y: e[1] + n.y,
    zoom: e[2]
  }, [
    [0, 0],
    [a, o]
  ], s), u = !!c && (c.x !== e[0] || c.y !== e[1] || c.k !== e[2]);
  return Promise.resolve(u);
}
function x1(n, t, e, s, a, o) {
  let c = a;
  const u = s.get(c) || /* @__PURE__ */ new Map();
  s.set(c, u.set(e, t)), c = `${a}-${n}`;
  const d = s.get(c) || /* @__PURE__ */ new Map();
  if (s.set(c, d.set(e, t)), o) {
    c = `${a}-${n}-${o}`;
    const h = s.get(c) || /* @__PURE__ */ new Map();
    s.set(c, h.set(e, t));
  }
}
function KE(n, t, e) {
  n.clear(), t.clear();
  for (const s of e) {
    const { source: a, target: o, sourceHandle: c = null, targetHandle: u = null } = s, d = { edgeId: s.id, source: a, target: o, sourceHandle: c, targetHandle: u }, h = `${a}-${c}--${o}-${u}`, m = `${o}-${u}--${a}-${c}`;
    x1("source", d, m, n, a, c), x1("target", d, h, n, o, u), t.set(s.id, s);
  }
}
function QE(n, t) {
  if (!n.parentId)
    return !1;
  const e = t.get(n.parentId);
  return e ? e.selected ? !0 : QE(e, t) : !1;
}
function S1(n, t, e) {
  var a;
  let s = n;
  do {
    if ((a = s == null ? void 0 : s.matches) != null && a.call(s, t))
      return !0;
    if (s === e)
      return !1;
    s = s == null ? void 0 : s.parentElement;
  } while (s);
  return !1;
}
function az(n, t, e, s) {
  const a = /* @__PURE__ */ new Map();
  for (const [o, c] of n)
    if ((c.selected || c.id === s) && (!c.parentId || !QE(c, n)) && (c.draggable || t && typeof c.draggable > "u")) {
      const u = n.get(o);
      u && a.set(o, {
        id: o,
        position: u.position || { x: 0, y: 0 },
        distance: {
          x: e.x - u.internals.positionAbsolute.x,
          y: e.y - u.internals.positionAbsolute.y
        },
        extent: u.extent,
        parentId: u.parentId,
        origin: u.origin,
        expandParent: u.expandParent,
        internals: {
          positionAbsolute: u.internals.positionAbsolute || { x: 0, y: 0 }
        },
        measured: {
          width: u.measured.width ?? 0,
          height: u.measured.height ?? 0
        }
      });
    }
  return a;
}
function pg({ nodeId: n, dragItems: t, nodeLookup: e, dragging: s = !0 }) {
  var c, u, d;
  const a = [];
  for (const [h, m] of t) {
    const p = (c = e.get(h)) == null ? void 0 : c.internals.userNode;
    p && a.push({
      ...p,
      position: m.position,
      dragging: s
    });
  }
  if (!n)
    return [a[0], a];
  const o = (u = e.get(n)) == null ? void 0 : u.internals.userNode;
  return [
    o ? {
      ...o,
      position: ((d = t.get(n)) == null ? void 0 : d.position) || o.position,
      dragging: s
    } : a[0],
    a
  ];
}
function oz({ dragItems: n, snapGrid: t, x: e, y: s }) {
  const a = n.values().next().value;
  if (!a)
    return null;
  const o = {
    x: e - a.distance.x,
    y: s - a.distance.y
  }, c = ou(o, t);
  return {
    x: c.x - o.x,
    y: c.y - o.y
  };
}
function lz({ onNodeMouseDown: n, getStoreItems: t, onDragStart: e, onDrag: s, onDragStop: a }) {
  let o = { x: null, y: null }, c = 0, u = /* @__PURE__ */ new Map(), d = !1, h = { x: 0, y: 0 }, m = null, p = !1, g = null, _ = !1, x = !1, A = null;
  function b({ noDragClassName: E, handleSelector: w, domNode: M, isSelectable: O, nodeId: C, nodeClickDistance: D = 0 }) {
    g = Ri(M);
    function T({ x: B, y: H }) {
      const { nodeLookup: U, nodeExtent: V, snapGrid: N, snapToGrid: I, nodeOrigin: k, onNodeDrag: X, onSelectionDrag: Q, onError: F, updateNodePositions: W } = t();
      o = { x: B, y: H };
      let et = !1;
      const $ = u.size > 1, j = $ && V ? N0(au(u)) : null, Y = $ && I ? oz({
        dragItems: u,
        snapGrid: N,
        x: B,
        y: H
      }) : null;
      for (const [K, J] of u) {
        if (!U.has(K))
          continue;
        let rt = { x: B - J.distance.x, y: H - J.distance.y };
        I && (rt = Y ? {
          x: Math.round(rt.x + Y.x),
          y: Math.round(rt.y + Y.y)
        } : ou(rt, N));
        let dt = null;
        if ($ && V && !J.extent && j) {
          const { positionAbsolute: Lt } = J.internals, zt = Lt.x - j.x + V[0][0], Xt = Lt.x + J.measured.width - j.x2 + V[1][0], Ft = Lt.y - j.y + V[0][1], ve = Lt.y + J.measured.height - j.y2 + V[1][1];
          dt = [
            [zt, Ft],
            [Xt, ve]
          ];
        }
        const { position: yt, positionAbsolute: Pt } = PE({
          nodeId: K,
          nextPosition: rt,
          nodeLookup: U,
          nodeExtent: dt || V,
          nodeOrigin: k,
          onError: F
        });
        et = et || J.position.x !== yt.x || J.position.y !== yt.y, J.position = yt, J.internals.positionAbsolute = Pt;
      }
      if (x = x || et, !!et && (W(u, !0), A && (s || X || !C && Q))) {
        const [K, J] = pg({
          nodeId: C,
          dragItems: u,
          nodeLookup: U
        });
        s == null || s(A, u, K, J), X == null || X(A, K, J), C || Q == null || Q(A, J);
      }
    }
    async function L() {
      if (!m)
        return;
      const { transform: B, panBy: H, autoPanSpeed: U, autoPanOnNodeDrag: V } = t();
      if (!V) {
        d = !1, cancelAnimationFrame(c);
        return;
      }
      const [N, I] = BE(h, m, U);
      (N !== 0 || I !== 0) && (o.x = (o.x ?? 0) - N / B[2], o.y = (o.y ?? 0) - I / B[2], await H({ x: N, y: I }) && T(o)), c = requestAnimationFrame(L);
    }
    function z(B) {
      var $;
      const { nodeLookup: H, multiSelectionActive: U, nodesDraggable: V, transform: N, snapGrid: I, snapToGrid: k, selectNodesOnDrag: X, onNodeDragStart: Q, onSelectionDragStart: F, unselectNodesAndEdges: W } = t();
      p = !0, (!X || !O) && !U && C && (($ = H.get(C)) != null && $.selected || W()), O && X && C && (n == null || n(C));
      const et = Bc(B.sourceEvent, { transform: N, snapGrid: I, snapToGrid: k, containerBounds: m });
      if (o = et, u = az(H, V, et, C), u.size > 0 && (e || Q || !C && F)) {
        const [j, Y] = pg({
          nodeId: C,
          dragItems: u,
          nodeLookup: H
        });
        e == null || e(B.sourceEvent, u, j, Y), Q == null || Q(B.sourceEvent, j, Y), C || F == null || F(B.sourceEvent, Y);
      }
    }
    const R = pE().clickDistance(D).on("start", (B) => {
      const { domNode: H, nodeDragThreshold: U, transform: V, snapGrid: N, snapToGrid: I } = t();
      m = (H == null ? void 0 : H.getBoundingClientRect()) || null, _ = !1, x = !1, A = B.sourceEvent, U === 0 && z(B), o = Bc(B.sourceEvent, { transform: V, snapGrid: N, snapToGrid: I, containerBounds: m }), h = rs(B.sourceEvent, m);
    }).on("drag", (B) => {
      const { autoPanOnNodeDrag: H, transform: U, snapGrid: V, snapToGrid: N, nodeDragThreshold: I, nodeLookup: k } = t(), X = Bc(B.sourceEvent, { transform: U, snapGrid: V, snapToGrid: N, containerBounds: m });
      if (A = B.sourceEvent, (B.sourceEvent.type === "touchmove" && B.sourceEvent.touches.length > 1 || // if user deletes a node while dragging, we need to abort the drag to prevent errors
      C && !k.has(C)) && (_ = !0), !_) {
        if (!d && H && p && (d = !0, L()), !p) {
          const Q = rs(B.sourceEvent, m), F = Q.x - h.x, W = Q.y - h.y;
          Math.sqrt(F * F + W * W) > I && z(B);
        }
        (o.x !== X.xSnapped || o.y !== X.ySnapped) && u && p && (h = rs(B.sourceEvent, m), T(X));
      }
    }).on("end", (B) => {
      if (!(!p || _) && (d = !1, p = !1, cancelAnimationFrame(c), u.size > 0)) {
        const { nodeLookup: H, updateNodePositions: U, onNodeDragStop: V, onSelectionDragStop: N } = t();
        if (x && (U(u, !1), x = !1), a || V || !C && N) {
          const [I, k] = pg({
            nodeId: C,
            dragItems: u,
            nodeLookup: H,
            dragging: !1
          });
          a == null || a(B.sourceEvent, u, I, k), V == null || V(B.sourceEvent, I, k), C || N == null || N(B.sourceEvent, k);
        }
      }
    }).filter((B) => {
      const H = B.target;
      return !B.button && (!E || !S1(H, `.${E}`, M)) && (!w || S1(H, w, M));
    });
    g.call(R);
  }
  function y() {
    g == null || g.on(".drag", null);
  }
  return {
    update: b,
    destroy: y
  };
}
function cz(n, t, e) {
  const s = [], a = {
    x: n.x - e,
    y: n.y - e,
    width: e * 2,
    height: e * 2
  };
  for (const o of t.values())
    Qc(a, xl(o)) > 0 && s.push(o);
  return s;
}
const uz = 250;
function fz(n, t, e, s) {
  var u, d;
  let a = [], o = 1 / 0;
  const c = cz(n, e, t + uz);
  for (const h of c) {
    const m = [...((u = h.internals.handleBounds) == null ? void 0 : u.source) ?? [], ...((d = h.internals.handleBounds) == null ? void 0 : d.target) ?? []];
    for (const p of m) {
      if (s.nodeId === p.nodeId && s.type === p.type && s.id === p.id)
        continue;
      const { x: g, y: _ } = ja(h, p, p.position, !0), x = Math.sqrt(Math.pow(g - n.x, 2) + Math.pow(_ - n.y, 2));
      x > t || (x < o ? (a = [{ ...p, x: g, y: _ }], o = x) : x === o && a.push({ ...p, x: g, y: _ }));
    }
  }
  if (!a.length)
    return null;
  if (a.length > 1) {
    const h = s.type === "source" ? "target" : "source";
    return a.find((m) => m.type === h) ?? a[0];
  }
  return a[0];
}
function JE(n, t, e, s, a, o = !1) {
  var h, m, p;
  const c = s.get(n);
  if (!c)
    return null;
  const u = a === "strict" ? (h = c.internals.handleBounds) == null ? void 0 : h[t] : [...((m = c.internals.handleBounds) == null ? void 0 : m.source) ?? [], ...((p = c.internals.handleBounds) == null ? void 0 : p.target) ?? []], d = (e ? u == null ? void 0 : u.find((g) => g.id === e) : u == null ? void 0 : u[0]) ?? null;
  return d && o ? { ...d, ...ja(c, d, d.position, !0) } : d;
}
function tw(n, t) {
  return n || (t != null && t.classList.contains("target") ? "target" : t != null && t.classList.contains("source") ? "source" : null);
}
function dz(n, t) {
  let e = null;
  return t ? e = !0 : n && !t && (e = !1), e;
}
const ew = () => !0;
function hz(n, { connectionMode: t, connectionRadius: e, handleId: s, nodeId: a, edgeUpdaterType: o, isTarget: c, domNode: u, nodeLookup: d, lib: h, autoPanOnConnect: m, flowId: p, panBy: g, cancelConnection: _, onConnectStart: x, onConnect: A, onConnectEnd: b, isValidConnection: y = ew, onReconnectEnd: E, updateConnection: w, getTransform: M, getFromHandle: O, autoPanSpeed: C, dragThreshold: D = 1, handleDomNode: T }) {
  const L = VE(n.target);
  let z = 0, R;
  const { x: B, y: H } = rs(n), U = tw(o, T), V = u == null ? void 0 : u.getBoundingClientRect();
  let N = !1;
  if (!V || !U)
    return;
  const I = JE(a, U, s, d, t);
  if (!I)
    return;
  let k = rs(n, V), X = !1, Q = null, F = !1, W = null;
  function et() {
    if (!m || !V)
      return;
    const [yt, Pt] = BE(k, V, C);
    g({ x: yt, y: Pt }), z = requestAnimationFrame(et);
  }
  const $ = {
    ...I,
    nodeId: a,
    type: U,
    position: I.position
  }, j = d.get(a);
  let K = {
    inProgress: !0,
    isValid: null,
    from: ja(j, $, oe.Left, !0),
    fromHandle: $,
    fromPosition: $.position,
    fromNode: j,
    to: k,
    toHandle: null,
    toPosition: c1[$.position],
    toNode: null,
    pointer: k
  };
  function J() {
    N = !0, w(K), x == null || x(n, { nodeId: a, handleId: s, handleType: U });
  }
  D === 0 && J();
  function rt(yt) {
    if (!N) {
      const { x: ve, y: it } = rs(yt), Ue = ve - B, xe = it - H;
      if (!(Ue * Ue + xe * xe > D * D))
        return;
      J();
    }
    if (!O() || !$) {
      dt(yt);
      return;
    }
    const Pt = M();
    k = rs(yt, V), R = fz(lu(k, Pt, !1, [1, 1]), e, d, $), X || (et(), X = !0);
    const Lt = nw(yt, {
      handle: R,
      connectionMode: t,
      fromNodeId: a,
      fromHandleId: s,
      fromType: c ? "target" : "source",
      isValidConnection: y,
      doc: L,
      lib: h,
      flowId: p,
      nodeLookup: d
    });
    W = Lt.handleDomNode, Q = Lt.connection, F = dz(!!R, Lt.isValid);
    const zt = d.get(a), Xt = zt ? ja(zt, $, oe.Left, !0) : K.from, Ft = {
      ...K,
      from: Xt,
      isValid: F,
      to: Lt.toHandle && F ? Hd({ x: Lt.toHandle.x, y: Lt.toHandle.y }, Pt) : k,
      toHandle: Lt.toHandle,
      toPosition: F && Lt.toHandle ? Lt.toHandle.position : c1[$.position],
      toNode: Lt.toHandle ? d.get(Lt.toHandle.nodeId) : null,
      pointer: k
    };
    w(Ft), K = Ft;
  }
  function dt(yt) {
    if (!("touches" in yt && yt.touches.length > 0)) {
      if (N) {
        (R || W) && Q && F && (A == null || A(Q));
        const { inProgress: Pt, ...Lt } = K, zt = {
          ...Lt,
          toPosition: K.toHandle ? K.toPosition : null
        };
        b == null || b(yt, zt), o && (E == null || E(yt, zt));
      }
      _(), cancelAnimationFrame(z), X = !1, F = !1, Q = null, W = null, L.removeEventListener("mousemove", rt), L.removeEventListener("mouseup", dt), L.removeEventListener("touchmove", rt), L.removeEventListener("touchend", dt);
    }
  }
  L.addEventListener("mousemove", rt), L.addEventListener("mouseup", dt), L.addEventListener("touchmove", rt), L.addEventListener("touchend", dt);
}
function nw(n, { handle: t, connectionMode: e, fromNodeId: s, fromHandleId: a, fromType: o, doc: c, lib: u, flowId: d, isValidConnection: h = ew, nodeLookup: m }) {
  const p = o === "target", g = t ? c.querySelector(`.${u}-flow__handle[data-id="${d}-${t == null ? void 0 : t.nodeId}-${t == null ? void 0 : t.id}-${t == null ? void 0 : t.type}"]`) : null, { x: _, y: x } = rs(n), A = c.elementFromPoint(_, x), b = A != null && A.classList.contains(`${u}-flow__handle`) ? A : g, y = {
    handleDomNode: b,
    isValid: !1,
    connection: null,
    toHandle: null
  };
  if (b) {
    const E = tw(void 0, b), w = b.getAttribute("data-nodeid"), M = b.getAttribute("data-handleid"), O = b.classList.contains("connectable"), C = b.classList.contains("connectableend");
    if (!w || !E)
      return y;
    const D = {
      source: p ? w : s,
      sourceHandle: p ? M : a,
      target: p ? s : w,
      targetHandle: p ? a : M
    };
    y.connection = D;
    const L = O && C && (e === _l.Strict ? p && E === "source" || !p && E === "target" : w !== s || M !== a);
    y.isValid = L && h(D), y.toHandle = JE(w, E, M, m, e, !0);
  }
  return y;
}
const P0 = {
  onPointerDown: hz,
  isValid: nw
};
function pz({ domNode: n, panZoom: t, getTransform: e, getViewScale: s }) {
  const a = Ri(n);
  function o({ translateExtent: u, width: d, height: h, zoomStep: m = 1, pannable: p = !0, zoomable: g = !0, inversePan: _ = !1 }) {
    const x = (w) => {
      if (w.sourceEvent.type !== "wheel" || !t)
        return;
      const M = e(), O = w.sourceEvent.ctrlKey && Jc() ? 10 : 1, C = -w.sourceEvent.deltaY * (w.sourceEvent.deltaMode === 1 ? 0.05 : w.sourceEvent.deltaMode ? 1 : 2e-3) * m, D = M[2] * Math.pow(2, C * O);
      t.scaleTo(D);
    };
    let A = [0, 0];
    const b = (w) => {
      (w.sourceEvent.type === "mousedown" || w.sourceEvent.type === "touchstart") && (A = [
        w.sourceEvent.clientX ?? w.sourceEvent.touches[0].clientX,
        w.sourceEvent.clientY ?? w.sourceEvent.touches[0].clientY
      ]);
    }, y = (w) => {
      const M = e();
      if (w.sourceEvent.type !== "mousemove" && w.sourceEvent.type !== "touchmove" || !t)
        return;
      const O = [
        w.sourceEvent.clientX ?? w.sourceEvent.touches[0].clientX,
        w.sourceEvent.clientY ?? w.sourceEvent.touches[0].clientY
      ], C = [O[0] - A[0], O[1] - A[1]];
      A = O;
      const D = s() * Math.max(M[2], Math.log(M[2])) * (_ ? -1 : 1), T = {
        x: M[0] - C[0] * D,
        y: M[1] - C[1] * D
      }, L = [
        [0, 0],
        [d, h]
      ];
      t.setViewportConstrained({
        x: T.x,
        y: T.y,
        zoom: M[2]
      }, L, u);
    }, E = RE().on("start", b).on("zoom", p ? y : null).on("zoom.wheel", g ? x : null);
    a.call(E, {});
  }
  function c() {
    a.on("zoom", null);
  }
  return {
    update: o,
    destroy: c,
    pointer: ts
  };
}
const ah = (n) => ({
  x: n.x,
  y: n.y,
  zoom: n.k
}), mg = ({ x: n, y: t, zoom: e }) => ih.translate(n, t).scale(e), sl = (n, t) => n.target.closest(`.${t}`), iw = (n, t) => t === 2 && Array.isArray(n) && n.includes(2), mz = (n) => ((n *= 2) <= 1 ? n * n * n : (n -= 2) * n * n + 2) / 2, gg = (n, t = 0, e = mz, s = () => {
}) => {
  const a = typeof t == "number" && t > 0;
  return a || s(), a ? n.transition().duration(t).ease(e).on("end", s) : n;
}, sw = (n) => {
  const t = n.ctrlKey && Jc() ? 10 : 1;
  return -n.deltaY * (n.deltaMode === 1 ? 0.05 : n.deltaMode ? 1 : 2e-3) * t;
};
function gz({ zoomPanValues: n, noWheelClassName: t, d3Selection: e, d3Zoom: s, panOnScrollMode: a, panOnScrollSpeed: o, zoomOnPinch: c, onPanZoomStart: u, onPanZoom: d, onPanZoomEnd: h }) {
  return (m) => {
    if (sl(m, t))
      return m.ctrlKey && m.preventDefault(), !1;
    m.preventDefault(), m.stopImmediatePropagation();
    const p = e.property("__zoom").k || 1;
    if (m.ctrlKey && c) {
      const b = ts(m), y = sw(m), E = p * Math.pow(2, y);
      s.scaleTo(e, E, b, m);
      return;
    }
    const g = m.deltaMode === 1 ? 20 : 1;
    let _ = a === Ga.Vertical ? 0 : m.deltaX * g, x = a === Ga.Horizontal ? 0 : m.deltaY * g;
    !Jc() && m.shiftKey && a !== Ga.Vertical && (_ = m.deltaY * g, x = 0), s.translateBy(
      e,
      -(_ / p) * o,
      -(x / p) * o,
      // @ts-ignore
      { internal: !0 }
    );
    const A = ah(e.property("__zoom"));
    clearTimeout(n.panScrollTimeout), n.isPanScrolling ? (d == null || d(m, A), n.panScrollTimeout = setTimeout(() => {
      h == null || h(m, A), n.isPanScrolling = !1;
    }, 150)) : (n.isPanScrolling = !0, u == null || u(m, A));
  };
}
function vz({ noWheelClassName: n, preventScrolling: t, d3ZoomHandler: e }) {
  return function(s, a) {
    const o = s.type === "wheel", c = !t && o && !s.ctrlKey, u = sl(s, n);
    if (s.ctrlKey && o && u && s.preventDefault(), c || u)
      return null;
    s.preventDefault(), e.call(this, s, a);
  };
}
function _z({ zoomPanValues: n, onDraggingChange: t, onPanZoomStart: e }) {
  return (s) => {
    var o, c, u;
    if ((o = s.sourceEvent) != null && o.internal)
      return;
    const a = ah(s.transform);
    n.mouseButton = ((c = s.sourceEvent) == null ? void 0 : c.button) || 0, n.isZoomingOrPanning = !0, n.prevViewport = a, ((u = s.sourceEvent) == null ? void 0 : u.type) === "mousedown" && t(!0), e && (e == null || e(s.sourceEvent, a));
  };
}
function yz({ zoomPanValues: n, panOnDrag: t, onPaneContextMenu: e, onTransformChange: s, onPanZoom: a }) {
  return (o) => {
    var c, u;
    n.usedRightMouseButton = !!(e && iw(t, n.mouseButton ?? 0)), (c = o.sourceEvent) != null && c.sync || s([o.transform.x, o.transform.y, o.transform.k]), a && !((u = o.sourceEvent) != null && u.internal) && (a == null || a(o.sourceEvent, ah(o.transform)));
  };
}
function xz({ zoomPanValues: n, panOnDrag: t, panOnScroll: e, onDraggingChange: s, onPanZoomEnd: a, onPaneContextMenu: o }) {
  return (c) => {
    var u;
    if (!((u = c.sourceEvent) != null && u.internal) && (n.isZoomingOrPanning = !1, o && iw(t, n.mouseButton ?? 0) && !n.usedRightMouseButton && c.sourceEvent && o(c.sourceEvent), n.usedRightMouseButton = !1, s(!1), a)) {
      const d = ah(c.transform);
      n.prevViewport = d, clearTimeout(n.timerId), n.timerId = setTimeout(
        () => {
          a == null || a(c.sourceEvent, d);
        },
        // we need a setTimeout for panOnScroll to supress multiple end events fired during scroll
        e ? 150 : 0
      );
    }
  };
}
function Sz({ zoomActivationKeyPressed: n, zoomOnScroll: t, zoomOnPinch: e, panOnDrag: s, panOnScroll: a, zoomOnDoubleClick: o, userSelectionActive: c, noWheelClassName: u, noPanClassName: d, lib: h, connectionInProgress: m }) {
  return (p) => {
    var b;
    const g = n || t, _ = e && p.ctrlKey, x = p.type === "wheel";
    if (p.button === 1 && p.type === "mousedown" && (sl(p, `${h}-flow__node`) || sl(p, `${h}-flow__edge`)))
      return !0;
    if (!s && !g && !a && !o && !e || c || m && !x || sl(p, u) && x || sl(p, d) && (!x || a && x && !n) || !e && p.ctrlKey && x)
      return !1;
    if (!e && p.type === "touchstart" && ((b = p.touches) == null ? void 0 : b.length) > 1)
      return p.preventDefault(), !1;
    if (!g && !a && !_ && x || !s && (p.type === "mousedown" || p.type === "touchstart") || Array.isArray(s) && !s.includes(p.button) && p.type === "mousedown")
      return !1;
    const A = Array.isArray(s) && s.includes(p.button) || !p.button || p.button <= 1;
    return (!p.ctrlKey || x) && A;
  };
}
function bz({ domNode: n, minZoom: t, maxZoom: e, translateExtent: s, viewport: a, onPanZoom: o, onPanZoomStart: c, onPanZoomEnd: u, onDraggingChange: d }) {
  const h = {
    isZoomingOrPanning: !1,
    usedRightMouseButton: !1,
    prevViewport: {},
    mouseButton: 0,
    timerId: void 0,
    panScrollTimeout: void 0,
    isPanScrolling: !1
  }, m = n.getBoundingClientRect(), p = RE().scaleExtent([t, e]).translateExtent(s), g = Ri(n).call(p);
  E({
    x: a.x,
    y: a.y,
    zoom: yl(a.zoom, t, e)
  }, [
    [0, 0],
    [m.width, m.height]
  ], s);
  const _ = g.on("wheel.zoom"), x = g.on("dblclick.zoom");
  p.wheelDelta(sw);
  function A(R, B) {
    return g ? new Promise((H) => {
      p == null || p.interpolate((B == null ? void 0 : B.interpolate) === "linear" ? Ic : _d).transform(gg(g, B == null ? void 0 : B.duration, B == null ? void 0 : B.ease, () => H(!0)), R);
    }) : Promise.resolve(!1);
  }
  function b({ noWheelClassName: R, noPanClassName: B, onPaneContextMenu: H, userSelectionActive: U, panOnScroll: V, panOnDrag: N, panOnScrollMode: I, panOnScrollSpeed: k, preventScrolling: X, zoomOnPinch: Q, zoomOnScroll: F, zoomOnDoubleClick: W, zoomActivationKeyPressed: et, lib: $, onTransformChange: j, connectionInProgress: Y, paneClickDistance: K, selectionOnDrag: J }) {
    U && !h.isZoomingOrPanning && y();
    const rt = V && !et && !U;
    p.clickDistance(J ? 1 / 0 : !ss(K) || K < 0 ? 0 : K);
    const dt = rt ? gz({
      zoomPanValues: h,
      noWheelClassName: R,
      d3Selection: g,
      d3Zoom: p,
      panOnScrollMode: I,
      panOnScrollSpeed: k,
      zoomOnPinch: Q,
      onPanZoomStart: c,
      onPanZoom: o,
      onPanZoomEnd: u
    }) : vz({
      noWheelClassName: R,
      preventScrolling: X,
      d3ZoomHandler: _
    });
    if (g.on("wheel.zoom", dt, { passive: !1 }), !U) {
      const Pt = _z({
        zoomPanValues: h,
        onDraggingChange: d,
        onPanZoomStart: c
      });
      p.on("start", Pt);
      const Lt = yz({
        zoomPanValues: h,
        panOnDrag: N,
        onPaneContextMenu: !!H,
        onPanZoom: o,
        onTransformChange: j
      });
      p.on("zoom", Lt);
      const zt = xz({
        zoomPanValues: h,
        panOnDrag: N,
        panOnScroll: V,
        onPaneContextMenu: H,
        onPanZoomEnd: u,
        onDraggingChange: d
      });
      p.on("end", zt);
    }
    const yt = Sz({
      zoomActivationKeyPressed: et,
      panOnDrag: N,
      zoomOnScroll: F,
      panOnScroll: V,
      zoomOnDoubleClick: W,
      zoomOnPinch: Q,
      userSelectionActive: U,
      noPanClassName: B,
      noWheelClassName: R,
      lib: $,
      connectionInProgress: Y
    });
    p.filter(yt), W ? g.on("dblclick.zoom", x) : g.on("dblclick.zoom", null);
  }
  function y() {
    p.on("zoom", null);
  }
  async function E(R, B, H) {
    const U = mg(R), V = p == null ? void 0 : p.constrain()(U, B, H);
    return V && await A(V), new Promise((N) => N(V));
  }
  async function w(R, B) {
    const H = mg(R);
    return await A(H, B), new Promise((U) => U(H));
  }
  function M(R) {
    if (g) {
      const B = mg(R), H = g.property("__zoom");
      (H.k !== R.zoom || H.x !== R.x || H.y !== R.y) && (p == null || p.transform(g, B, null, { sync: !0 }));
    }
  }
  function O() {
    const R = g ? CE(g.node()) : { x: 0, y: 0, k: 1 };
    return { x: R.x, y: R.y, zoom: R.k };
  }
  function C(R, B) {
    return g ? new Promise((H) => {
      p == null || p.interpolate((B == null ? void 0 : B.interpolate) === "linear" ? Ic : _d).scaleTo(gg(g, B == null ? void 0 : B.duration, B == null ? void 0 : B.ease, () => H(!0)), R);
    }) : Promise.resolve(!1);
  }
  function D(R, B) {
    return g ? new Promise((H) => {
      p == null || p.interpolate((B == null ? void 0 : B.interpolate) === "linear" ? Ic : _d).scaleBy(gg(g, B == null ? void 0 : B.duration, B == null ? void 0 : B.ease, () => H(!0)), R);
    }) : Promise.resolve(!1);
  }
  function T(R) {
    p == null || p.scaleExtent(R);
  }
  function L(R) {
    p == null || p.translateExtent(R);
  }
  function z(R) {
    const B = !ss(R) || R < 0 ? 0 : R;
    p == null || p.clickDistance(B);
  }
  return {
    update: b,
    destroy: y,
    setViewport: w,
    setViewportConstrained: E,
    getViewport: O,
    scaleTo: C,
    scaleBy: D,
    setScaleExtent: T,
    setTranslateExtent: L,
    syncViewport: M,
    setClickDistance: z
  };
}
var bl;
(function(n) {
  n.Line = "line", n.Handle = "handle";
})(bl || (bl = {}));
function Mz({ width: n, prevWidth: t, height: e, prevHeight: s, affectsX: a, affectsY: o }) {
  const c = n - t, u = e - s, d = [c > 0 ? 1 : c < 0 ? -1 : 0, u > 0 ? 1 : u < 0 ? -1 : 0];
  return c && a && (d[0] = d[0] * -1), u && o && (d[1] = d[1] * -1), d;
}
function b1(n) {
  const t = n.includes("right") || n.includes("left"), e = n.includes("bottom") || n.includes("top"), s = n.includes("left"), a = n.includes("top");
  return {
    isHorizontal: t,
    isVertical: e,
    affectsX: s,
    affectsY: a
  };
}
function Kr(n, t) {
  return Math.max(0, t - n);
}
function Qr(n, t) {
  return Math.max(0, n - t);
}
function od(n, t, e) {
  return Math.max(0, t - n, n - e);
}
function M1(n, t) {
  return n ? !t : t;
}
function Ez(n, t, e, s, a, o, c, u) {
  let { affectsX: d, affectsY: h } = t;
  const { isHorizontal: m, isVertical: p } = t, g = m && p, { xSnapped: _, ySnapped: x } = e, { minWidth: A, maxWidth: b, minHeight: y, maxHeight: E } = s, { x: w, y: M, width: O, height: C, aspectRatio: D } = n;
  let T = Math.floor(m ? _ - n.pointerX : 0), L = Math.floor(p ? x - n.pointerY : 0);
  const z = O + (d ? -T : T), R = C + (h ? -L : L), B = -o[0] * O, H = -o[1] * C;
  let U = od(z, A, b), V = od(R, y, E);
  if (c) {
    let k = 0, X = 0;
    d && T < 0 ? k = Kr(w + T + B, c[0][0]) : !d && T > 0 && (k = Qr(w + z + B, c[1][0])), h && L < 0 ? X = Kr(M + L + H, c[0][1]) : !h && L > 0 && (X = Qr(M + R + H, c[1][1])), U = Math.max(U, k), V = Math.max(V, X);
  }
  if (u) {
    let k = 0, X = 0;
    d && T > 0 ? k = Qr(w + T, u[0][0]) : !d && T < 0 && (k = Kr(w + z, u[1][0])), h && L > 0 ? X = Qr(M + L, u[0][1]) : !h && L < 0 && (X = Kr(M + R, u[1][1])), U = Math.max(U, k), V = Math.max(V, X);
  }
  if (a) {
    if (m) {
      const k = od(z / D, y, E) * D;
      if (U = Math.max(U, k), c) {
        let X = 0;
        !d && !h || d && !h && g ? X = Qr(M + H + z / D, c[1][1]) * D : X = Kr(M + H + (d ? T : -T) / D, c[0][1]) * D, U = Math.max(U, X);
      }
      if (u) {
        let X = 0;
        !d && !h || d && !h && g ? X = Kr(M + z / D, u[1][1]) * D : X = Qr(M + (d ? T : -T) / D, u[0][1]) * D, U = Math.max(U, X);
      }
    }
    if (p) {
      const k = od(R * D, A, b) / D;
      if (V = Math.max(V, k), c) {
        let X = 0;
        !d && !h || h && !d && g ? X = Qr(w + R * D + B, c[1][0]) / D : X = Kr(w + (h ? L : -L) * D + B, c[0][0]) / D, V = Math.max(V, X);
      }
      if (u) {
        let X = 0;
        !d && !h || h && !d && g ? X = Kr(w + R * D, u[1][0]) / D : X = Qr(w + (h ? L : -L) * D, u[0][0]) / D, V = Math.max(V, X);
      }
    }
  }
  L = L + (L < 0 ? V : -V), T = T + (T < 0 ? U : -U), a && (g ? z > R * D ? L = (M1(d, h) ? -T : T) / D : T = (M1(d, h) ? -L : L) * D : m ? (L = T / D, h = d) : (T = L * D, d = h));
  const N = d ? w + T : w, I = h ? M + L : M;
  return {
    width: O + (d ? -T : T),
    height: C + (h ? -L : L),
    x: o[0] * T * (d ? -1 : 1) + N,
    y: o[1] * L * (h ? -1 : 1) + I
  };
}
const rw = { width: 0, height: 0, x: 0, y: 0 }, wz = {
  ...rw,
  pointerX: 0,
  pointerY: 0,
  aspectRatio: 1
};
function Az(n) {
  return [
    [0, 0],
    [n.measured.width, n.measured.height]
  ];
}
function Tz(n, t, e) {
  const s = t.position.x + n.position.x, a = t.position.y + n.position.y, o = n.measured.width ?? 0, c = n.measured.height ?? 0, u = e[0] * o, d = e[1] * c;
  return [
    [s - u, a - d],
    [s + o - u, a + c - d]
  ];
}
function Cz({ domNode: n, nodeId: t, getStoreItems: e, onChange: s, onEnd: a }) {
  const o = Ri(n);
  let c = {
    controlDirection: b1("bottom-right"),
    boundaries: {
      minWidth: 0,
      minHeight: 0,
      maxWidth: Number.MAX_VALUE,
      maxHeight: Number.MAX_VALUE
    },
    resizeDirection: void 0,
    keepAspectRatio: !1
  };
  function u({ controlPosition: h, boundaries: m, keepAspectRatio: p, resizeDirection: g, onResizeStart: _, onResize: x, onResizeEnd: A, shouldResize: b }) {
    let y = { ...rw }, E = { ...wz };
    c = {
      boundaries: m,
      resizeDirection: g,
      keepAspectRatio: p,
      controlDirection: b1(h)
    };
    let w, M = null, O = [], C, D, T, L = !1;
    const z = pE().on("start", (R) => {
      const { nodeLookup: B, transform: H, snapGrid: U, snapToGrid: V, nodeOrigin: N, paneDomNode: I } = e();
      if (w = B.get(t), !w)
        return;
      M = (I == null ? void 0 : I.getBoundingClientRect()) ?? null;
      const { xSnapped: k, ySnapped: X } = Bc(R.sourceEvent, {
        transform: H,
        snapGrid: U,
        snapToGrid: V,
        containerBounds: M
      });
      y = {
        width: w.measured.width ?? 0,
        height: w.measured.height ?? 0,
        x: w.position.x ?? 0,
        y: w.position.y ?? 0
      }, E = {
        ...y,
        pointerX: k,
        pointerY: X,
        aspectRatio: y.width / y.height
      }, C = void 0, w.parentId && (w.extent === "parent" || w.expandParent) && (C = B.get(w.parentId), D = C && w.extent === "parent" ? Az(C) : void 0), O = [], T = void 0;
      for (const [Q, F] of B)
        if (F.parentId === t && (O.push({
          id: Q,
          position: { ...F.position },
          extent: F.extent
        }), F.extent === "parent" || F.expandParent)) {
          const W = Tz(F, w, F.origin ?? N);
          T ? T = [
            [Math.min(W[0][0], T[0][0]), Math.min(W[0][1], T[0][1])],
            [Math.max(W[1][0], T[1][0]), Math.max(W[1][1], T[1][1])]
          ] : T = W;
        }
      _ == null || _(R, { ...y });
    }).on("drag", (R) => {
      const { transform: B, snapGrid: H, snapToGrid: U, nodeOrigin: V } = e(), N = Bc(R.sourceEvent, {
        transform: B,
        snapGrid: H,
        snapToGrid: U,
        containerBounds: M
      }), I = [];
      if (!w)
        return;
      const { x: k, y: X, width: Q, height: F } = y, W = {}, et = w.origin ?? V, { width: $, height: j, x: Y, y: K } = Ez(E, c.controlDirection, N, c.boundaries, c.keepAspectRatio, et, D, T), J = $ !== Q, rt = j !== F, dt = Y !== k && J, yt = K !== X && rt;
      if (!dt && !yt && !J && !rt)
        return;
      if ((dt || yt || et[0] === 1 || et[1] === 1) && (W.x = dt ? Y : y.x, W.y = yt ? K : y.y, y.x = W.x, y.y = W.y, O.length > 0)) {
        const Xt = Y - k, Ft = K - X;
        for (const ve of O)
          ve.position = {
            x: ve.position.x - Xt + et[0] * ($ - Q),
            y: ve.position.y - Ft + et[1] * (j - F)
          }, I.push(ve);
      }
      if ((J || rt) && (W.width = J && (!c.resizeDirection || c.resizeDirection === "horizontal") ? $ : y.width, W.height = rt && (!c.resizeDirection || c.resizeDirection === "vertical") ? j : y.height, y.width = W.width, y.height = W.height), C && w.expandParent) {
        const Xt = et[0] * (W.width ?? 0);
        W.x && W.x < Xt && (y.x = Xt, E.x = E.x - (W.x - Xt));
        const Ft = et[1] * (W.height ?? 0);
        W.y && W.y < Ft && (y.y = Ft, E.y = E.y - (W.y - Ft));
      }
      const Pt = Mz({
        width: y.width,
        prevWidth: Q,
        height: y.height,
        prevHeight: F,
        affectsX: c.controlDirection.affectsX,
        affectsY: c.controlDirection.affectsY
      }), Lt = { ...y, direction: Pt };
      (b == null ? void 0 : b(R, Lt)) !== !1 && (L = !0, x == null || x(R, Lt), s(W, I));
    }).on("end", (R) => {
      L && (A == null || A(R, { ...y }), a == null || a({ ...y }), L = !1);
    });
    o.call(z);
  }
  function d() {
    o.on(".drag", null);
  }
  return {
    update: u,
    destroy: d
  };
}
var vg = { exports: {} }, _g = {}, yg = { exports: {} }, xg = {};
/**
 * @license React
 * use-sync-external-store-shim.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var E1;
function Rz() {
  if (E1) return xg;
  E1 = 1;
  var n = eu();
  function t(p, g) {
    return p === g && (p !== 0 || 1 / p === 1 / g) || p !== p && g !== g;
  }
  var e = typeof Object.is == "function" ? Object.is : t, s = n.useState, a = n.useEffect, o = n.useLayoutEffect, c = n.useDebugValue;
  function u(p, g) {
    var _ = g(), x = s({ inst: { value: _, getSnapshot: g } }), A = x[0].inst, b = x[1];
    return o(
      function() {
        A.value = _, A.getSnapshot = g, d(A) && b({ inst: A });
      },
      [p, _, g]
    ), a(
      function() {
        return d(A) && b({ inst: A }), p(function() {
          d(A) && b({ inst: A });
        });
      },
      [p]
    ), c(_), _;
  }
  function d(p) {
    var g = p.getSnapshot;
    p = p.value;
    try {
      var _ = g();
      return !e(p, _);
    } catch {
      return !0;
    }
  }
  function h(p, g) {
    return g();
  }
  var m = typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u" ? h : u;
  return xg.useSyncExternalStore = n.useSyncExternalStore !== void 0 ? n.useSyncExternalStore : m, xg;
}
var w1;
function Dz() {
  return w1 || (w1 = 1, yg.exports = Rz()), yg.exports;
}
/**
 * @license React
 * use-sync-external-store-shim/with-selector.production.js
 *
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var A1;
function Nz() {
  if (A1) return _g;
  A1 = 1;
  var n = eu(), t = Dz();
  function e(h, m) {
    return h === m && (h !== 0 || 1 / h === 1 / m) || h !== h && m !== m;
  }
  var s = typeof Object.is == "function" ? Object.is : e, a = t.useSyncExternalStore, o = n.useRef, c = n.useEffect, u = n.useMemo, d = n.useDebugValue;
  return _g.useSyncExternalStoreWithSelector = function(h, m, p, g, _) {
    var x = o(null);
    if (x.current === null) {
      var A = { hasValue: !1, value: null };
      x.current = A;
    } else A = x.current;
    x = u(
      function() {
        function y(C) {
          if (!E) {
            if (E = !0, w = C, C = g(C), _ !== void 0 && A.hasValue) {
              var D = A.value;
              if (_(D, C))
                return M = D;
            }
            return M = C;
          }
          if (D = M, s(w, C)) return D;
          var T = g(C);
          return _ !== void 0 && _(D, T) ? (w = C, D) : (w = C, M = T);
        }
        var E = !1, w, M, O = p === void 0 ? null : p;
        return [
          function() {
            return y(m());
          },
          O === null ? void 0 : function() {
            return y(O());
          }
        ];
      },
      [m, p, g, _]
    );
    var b = a(h, x[0], x[1]);
    return c(
      function() {
        A.hasValue = !0, A.value = b;
      },
      [b]
    ), d(b), b;
  }, _g;
}
var T1;
function Oz() {
  return T1 || (T1 = 1, vg.exports = Nz()), vg.exports;
}
var Lz = Oz();
const Uz = /* @__PURE__ */ lM(Lz), Pz = {}, C1 = (n) => {
  let t;
  const e = /* @__PURE__ */ new Set(), s = (m, p) => {
    const g = typeof m == "function" ? m(t) : m;
    if (!Object.is(g, t)) {
      const _ = t;
      t = p ?? (typeof g != "object" || g === null) ? g : Object.assign({}, t, g), e.forEach((x) => x(t, _));
    }
  }, a = () => t, d = { setState: s, getState: a, getInitialState: () => h, subscribe: (m) => (e.add(m), () => e.delete(m)), destroy: () => {
    (Pz ? "production" : void 0) !== "production" && console.warn(
      "[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."
    ), e.clear();
  } }, h = t = n(s, a, d);
  return d;
}, Iz = (n) => n ? C1(n) : C1, { useDebugValue: Bz } = Rc, { useSyncExternalStoreWithSelector: zz } = Uz, Fz = (n) => n;
function aw(n, t = Fz, e) {
  const s = zz(
    n.subscribe,
    n.getState,
    n.getServerState || n.getInitialState,
    t,
    e
  );
  return Bz(s), s;
}
const R1 = (n, t) => {
  const e = Iz(n), s = (a, o = t) => aw(e, a, o);
  return Object.assign(s, e), s;
}, Hz = (n, t) => n ? R1(n, t) : R1;
function on(n, t) {
  if (Object.is(n, t))
    return !0;
  if (typeof n != "object" || n === null || typeof t != "object" || t === null)
    return !1;
  if (n instanceof Map && t instanceof Map) {
    if (n.size !== t.size) return !1;
    for (const [s, a] of n)
      if (!Object.is(a, t.get(s)))
        return !1;
    return !0;
  }
  if (n instanceof Set && t instanceof Set) {
    if (n.size !== t.size) return !1;
    for (const s of n)
      if (!t.has(s))
        return !1;
    return !0;
  }
  const e = Object.keys(n);
  if (e.length !== Object.keys(t).length)
    return !1;
  for (const s of e)
    if (!Object.prototype.hasOwnProperty.call(t, s) || !Object.is(n[s], t[s]))
      return !1;
  return !0;
}
cM();
const oh = vt.createContext(null), Vz = oh.Provider, ow = Ds.error001();
function Pe(n, t) {
  const e = vt.useContext(oh);
  if (e === null)
    throw new Error(ow);
  return aw(e, n, t);
}
function ln() {
  const n = vt.useContext(oh);
  if (n === null)
    throw new Error(ow);
  return vt.useMemo(() => ({
    getState: n.getState,
    setState: n.setState,
    subscribe: n.subscribe
  }), [n]);
}
const D1 = { display: "none" }, Gz = {
  position: "absolute",
  width: 1,
  height: 1,
  margin: -1,
  border: 0,
  padding: 0,
  overflow: "hidden",
  clip: "rect(0px, 0px, 0px, 0px)",
  clipPath: "inset(100%)"
}, lw = "react-flow__node-desc", cw = "react-flow__edge-desc", kz = "react-flow__aria-live", Xz = (n) => n.ariaLiveMessage, Wz = (n) => n.ariaLabelConfig;
function Yz({ rfId: n }) {
  const t = Pe(Xz);
  return _t.jsx("div", { id: `${kz}-${n}`, "aria-live": "assertive", "aria-atomic": "true", style: Gz, children: t });
}
function jz({ rfId: n, disableKeyboardA11y: t }) {
  const e = Pe(Wz);
  return _t.jsxs(_t.Fragment, { children: [_t.jsx("div", { id: `${lw}-${n}`, style: D1, children: t ? e["node.a11yDescription.default"] : e["node.a11yDescription.keyboardDisabled"] }), _t.jsx("div", { id: `${cw}-${n}`, style: D1, children: e["edge.a11yDescription.default"] }), !t && _t.jsx(Yz, { rfId: n })] });
}
const lh = vt.forwardRef(({ position: n = "top-left", children: t, className: e, style: s, ...a }, o) => {
  const c = `${n}`.split("-");
  return _t.jsx("div", { className: Rn(["react-flow__panel", e, ...c]), style: s, ref: o, ...a, children: t });
});
lh.displayName = "Panel";
function qz({ proOptions: n, position: t = "bottom-right" }) {
  return n != null && n.hideAttribution ? null : _t.jsx(lh, { position: t, className: "react-flow__attribution", "data-message": "Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev", children: _t.jsx("a", { href: "https://reactflow.dev", target: "_blank", rel: "noopener noreferrer", "aria-label": "React Flow attribution", children: "React Flow" }) });
}
const Zz = (n) => {
  const t = [], e = [];
  for (const [, s] of n.nodeLookup)
    s.selected && t.push(s.internals.userNode);
  for (const [, s] of n.edgeLookup)
    s.selected && e.push(s);
  return { selectedNodes: t, selectedEdges: e };
}, ld = (n) => n.id;
function $z(n, t) {
  return on(n.selectedNodes.map(ld), t.selectedNodes.map(ld)) && on(n.selectedEdges.map(ld), t.selectedEdges.map(ld));
}
function Kz({ onSelectionChange: n }) {
  const t = ln(), { selectedNodes: e, selectedEdges: s } = Pe(Zz, $z);
  return vt.useEffect(() => {
    const a = { nodes: e, edges: s };
    n == null || n(a), t.getState().onSelectionChangeHandlers.forEach((o) => o(a));
  }, [e, s, n]), null;
}
const Qz = (n) => !!n.onSelectionChangeHandlers;
function Jz({ onSelectionChange: n }) {
  const t = Pe(Qz);
  return n || t ? _t.jsx(Kz, { onSelectionChange: n }) : null;
}
const uw = [0, 0], t4 = { x: 0, y: 0, zoom: 1 }, e4 = [
  "nodes",
  "edges",
  "defaultNodes",
  "defaultEdges",
  "onConnect",
  "onConnectStart",
  "onConnectEnd",
  "onClickConnectStart",
  "onClickConnectEnd",
  "nodesDraggable",
  "autoPanOnNodeFocus",
  "nodesConnectable",
  "nodesFocusable",
  "edgesFocusable",
  "edgesReconnectable",
  "elevateNodesOnSelect",
  "elevateEdgesOnSelect",
  "minZoom",
  "maxZoom",
  "nodeExtent",
  "onNodesChange",
  "onEdgesChange",
  "elementsSelectable",
  "connectionMode",
  "snapGrid",
  "snapToGrid",
  "translateExtent",
  "connectOnClick",
  "defaultEdgeOptions",
  "fitView",
  "fitViewOptions",
  "onNodesDelete",
  "onEdgesDelete",
  "onDelete",
  "onNodeDrag",
  "onNodeDragStart",
  "onNodeDragStop",
  "onSelectionDrag",
  "onSelectionDragStart",
  "onSelectionDragStop",
  "onMoveStart",
  "onMove",
  "onMoveEnd",
  "noPanClassName",
  "nodeOrigin",
  "autoPanOnConnect",
  "autoPanOnNodeDrag",
  "onError",
  "connectionRadius",
  "isValidConnection",
  "selectNodesOnDrag",
  "nodeDragThreshold",
  "connectionDragThreshold",
  "onBeforeDelete",
  "debug",
  "autoPanSpeed",
  "ariaLabelConfig",
  "zIndexMode"
], N1 = [...e4, "rfId"], n4 = (n) => ({
  setNodes: n.setNodes,
  setEdges: n.setEdges,
  setMinZoom: n.setMinZoom,
  setMaxZoom: n.setMaxZoom,
  setTranslateExtent: n.setTranslateExtent,
  setNodeExtent: n.setNodeExtent,
  reset: n.reset,
  setDefaultNodesAndEdges: n.setDefaultNodesAndEdges
}), O1 = {
  /*
   * these are values that are also passed directly to other components
   * than the StoreUpdater. We can reduce the number of setStore calls
   * by setting the same values here as prev fields.
   */
  translateExtent: $c,
  nodeOrigin: uw,
  minZoom: 0.5,
  maxZoom: 2,
  elementsSelectable: !0,
  noPanClassName: "nopan",
  rfId: "1"
};
function i4(n) {
  const { setNodes: t, setEdges: e, setMinZoom: s, setMaxZoom: a, setTranslateExtent: o, setNodeExtent: c, reset: u, setDefaultNodesAndEdges: d } = Pe(n4, on), h = ln();
  vt.useEffect(() => (d(n.defaultNodes, n.defaultEdges), () => {
    m.current = O1, u();
  }), []);
  const m = vt.useRef(O1);
  return vt.useEffect(
    () => {
      for (const p of N1) {
        const g = n[p], _ = m.current[p];
        g !== _ && (typeof n[p] > "u" || (p === "nodes" ? t(g) : p === "edges" ? e(g) : p === "minZoom" ? s(g) : p === "maxZoom" ? a(g) : p === "translateExtent" ? o(g) : p === "nodeExtent" ? c(g) : p === "ariaLabelConfig" ? h.setState({ ariaLabelConfig: VB(g) }) : p === "fitView" ? h.setState({ fitViewQueued: g }) : p === "fitViewOptions" ? h.setState({ fitViewOptions: g }) : h.setState({ [p]: g })));
      }
      m.current = n;
    },
    // Only re-run the effect if one of the fields we track changes
    N1.map((p) => n[p])
  ), null;
}
function L1() {
  return typeof window > "u" || !window.matchMedia ? null : window.matchMedia("(prefers-color-scheme: dark)");
}
function s4(n) {
  var s;
  const [t, e] = vt.useState(n === "system" ? null : n);
  return vt.useEffect(() => {
    if (n !== "system") {
      e(n);
      return;
    }
    const a = L1(), o = () => e(a != null && a.matches ? "dark" : "light");
    return o(), a == null || a.addEventListener("change", o), () => {
      a == null || a.removeEventListener("change", o);
    };
  }, [n]), t !== null ? t : (s = L1()) != null && s.matches ? "dark" : "light";
}
const U1 = typeof document < "u" ? document : null;
function tu(n = null, t = { target: U1, actInsideInputWithModifier: !0 }) {
  const [e, s] = vt.useState(!1), a = vt.useRef(!1), o = vt.useRef(/* @__PURE__ */ new Set([])), [c, u] = vt.useMemo(() => {
    if (n !== null) {
      const h = (Array.isArray(n) ? n : [n]).filter((p) => typeof p == "string").map((p) => p.replace("+", `
`).replace(`

`, `
+`).split(`
`)), m = h.reduce((p, g) => p.concat(...g), []);
      return [h, m];
    }
    return [[], []];
  }, [n]);
  return vt.useEffect(() => {
    const d = (t == null ? void 0 : t.target) ?? U1, h = (t == null ? void 0 : t.actInsideInputWithModifier) ?? !0;
    if (n !== null) {
      const m = (_) => {
        var b, y;
        if (a.current = _.ctrlKey || _.metaKey || _.shiftKey || _.altKey, (!a.current || a.current && !h) && GE(_))
          return !1;
        const A = I1(_.code, u);
        if (o.current.add(_[A]), P1(c, o.current, !1)) {
          const E = ((y = (b = _.composedPath) == null ? void 0 : b.call(_)) == null ? void 0 : y[0]) || _.target, w = (E == null ? void 0 : E.nodeName) === "BUTTON" || (E == null ? void 0 : E.nodeName) === "A";
          t.preventDefault !== !1 && (a.current || !w) && _.preventDefault(), s(!0);
        }
      }, p = (_) => {
        const x = I1(_.code, u);
        P1(c, o.current, !0) ? (s(!1), o.current.clear()) : o.current.delete(_[x]), _.key === "Meta" && o.current.clear(), a.current = !1;
      }, g = () => {
        o.current.clear(), s(!1);
      };
      return d == null || d.addEventListener("keydown", m), d == null || d.addEventListener("keyup", p), window.addEventListener("blur", g), window.addEventListener("contextmenu", g), () => {
        d == null || d.removeEventListener("keydown", m), d == null || d.removeEventListener("keyup", p), window.removeEventListener("blur", g), window.removeEventListener("contextmenu", g);
      };
    }
  }, [n, s]), e;
}
function P1(n, t, e) {
  return n.filter((s) => e || s.length === t.size).some((s) => s.every((a) => t.has(a)));
}
function I1(n, t) {
  return t.includes(n) ? "code" : "key";
}
const r4 = () => {
  const n = ln();
  return vt.useMemo(() => ({
    zoomIn: (t) => {
      const { panZoom: e } = n.getState();
      return e ? e.scaleBy(1.2, { duration: t == null ? void 0 : t.duration }) : Promise.resolve(!1);
    },
    zoomOut: (t) => {
      const { panZoom: e } = n.getState();
      return e ? e.scaleBy(1 / 1.2, { duration: t == null ? void 0 : t.duration }) : Promise.resolve(!1);
    },
    zoomTo: (t, e) => {
      const { panZoom: s } = n.getState();
      return s ? s.scaleTo(t, { duration: e == null ? void 0 : e.duration }) : Promise.resolve(!1);
    },
    getZoom: () => n.getState().transform[2],
    setViewport: async (t, e) => {
      const { transform: [s, a, o], panZoom: c } = n.getState();
      return c ? (await c.setViewport({
        x: t.x ?? s,
        y: t.y ?? a,
        zoom: t.zoom ?? o
      }, e), Promise.resolve(!0)) : Promise.resolve(!1);
    },
    getViewport: () => {
      const [t, e, s] = n.getState().transform;
      return { x: t, y: e, zoom: s };
    },
    setCenter: async (t, e, s) => n.getState().setCenter(t, e, s),
    fitBounds: async (t, e) => {
      const { width: s, height: a, minZoom: o, maxZoom: c, panZoom: u } = n.getState(), d = _v(t, s, a, o, c, (e == null ? void 0 : e.padding) ?? 0.1);
      return u ? (await u.setViewport(d, {
        duration: e == null ? void 0 : e.duration,
        ease: e == null ? void 0 : e.ease,
        interpolate: e == null ? void 0 : e.interpolate
      }), Promise.resolve(!0)) : Promise.resolve(!1);
    },
    screenToFlowPosition: (t, e = {}) => {
      const { transform: s, snapGrid: a, snapToGrid: o, domNode: c } = n.getState();
      if (!c)
        return t;
      const { x: u, y: d } = c.getBoundingClientRect(), h = {
        x: t.x - u,
        y: t.y - d
      }, m = e.snapGrid ?? a, p = e.snapToGrid ?? o;
      return lu(h, s, p, m);
    },
    flowToScreenPosition: (t) => {
      const { transform: e, domNode: s } = n.getState();
      if (!s)
        return t;
      const { x: a, y: o } = s.getBoundingClientRect(), c = Hd(t, e);
      return {
        x: c.x + a,
        y: c.y + o
      };
    }
  }), []);
};
function fw(n, t) {
  const e = [], s = /* @__PURE__ */ new Map(), a = [];
  for (const o of n)
    if (o.type === "add") {
      a.push(o);
      continue;
    } else if (o.type === "remove" || o.type === "replace")
      s.set(o.id, [o]);
    else {
      const c = s.get(o.id);
      c ? c.push(o) : s.set(o.id, [o]);
    }
  for (const o of t) {
    const c = s.get(o.id);
    if (!c) {
      e.push(o);
      continue;
    }
    if (c[0].type === "remove")
      continue;
    if (c[0].type === "replace") {
      e.push({ ...c[0].item });
      continue;
    }
    const u = { ...o };
    for (const d of c)
      a4(d, u);
    e.push(u);
  }
  return a.length && a.forEach((o) => {
    o.index !== void 0 ? e.splice(o.index, 0, { ...o.item }) : e.push({ ...o.item });
  }), e;
}
function a4(n, t) {
  switch (n.type) {
    case "select": {
      t.selected = n.selected;
      break;
    }
    case "position": {
      typeof n.position < "u" && (t.position = n.position), typeof n.dragging < "u" && (t.dragging = n.dragging);
      break;
    }
    case "dimensions": {
      typeof n.dimensions < "u" && (t.measured = {
        ...n.dimensions
      }, n.setAttributes && ((n.setAttributes === !0 || n.setAttributes === "width") && (t.width = n.dimensions.width), (n.setAttributes === !0 || n.setAttributes === "height") && (t.height = n.dimensions.height))), typeof n.resizing == "boolean" && (t.resizing = n.resizing);
      break;
    }
  }
}
function dw(n, t) {
  return fw(n, t);
}
function hw(n, t) {
  return fw(n, t);
}
function La(n, t) {
  return {
    id: n,
    type: "select",
    selected: t
  };
}
function rl(n, t = /* @__PURE__ */ new Set(), e = !1) {
  const s = [];
  for (const [a, o] of n) {
    const c = t.has(a);
    !(o.selected === void 0 && !c) && o.selected !== c && (e && (o.selected = c), s.push(La(o.id, c)));
  }
  return s;
}
function B1({ items: n = [], lookup: t }) {
  var a;
  const e = [], s = new Map(n.map((o) => [o.id, o]));
  for (const [o, c] of n.entries()) {
    const u = t.get(c.id), d = ((a = u == null ? void 0 : u.internals) == null ? void 0 : a.userNode) ?? u;
    d !== void 0 && d !== c && e.push({ id: c.id, item: c, type: "replace" }), d === void 0 && e.push({ item: c, type: "add", index: o });
  }
  for (const [o] of t)
    s.get(o) === void 0 && e.push({ id: o, type: "remove" });
  return e;
}
function z1(n) {
  return {
    id: n.id,
    type: "remove"
  };
}
const F1 = (n) => NB(n), o4 = (n) => UE(n);
function pw(n) {
  return vt.forwardRef(n);
}
const l4 = typeof window < "u" ? vt.useLayoutEffect : vt.useEffect;
function H1(n) {
  const [t, e] = vt.useState(BigInt(0)), [s] = vt.useState(() => c4(() => e((a) => a + BigInt(1))));
  return l4(() => {
    const a = s.get();
    a.length && (n(a), s.reset());
  }, [t]), s;
}
function c4(n) {
  let t = [];
  return {
    get: () => t,
    reset: () => {
      t = [];
    },
    push: (e) => {
      t.push(e), n();
    }
  };
}
const mw = vt.createContext(null);
function u4({ children: n }) {
  const t = ln(), e = vt.useCallback((u) => {
    const { nodes: d = [], setNodes: h, hasDefaultNodes: m, onNodesChange: p, nodeLookup: g, fitViewQueued: _, onNodesChangeMiddlewareMap: x } = t.getState();
    let A = d;
    for (const y of u)
      A = typeof y == "function" ? y(A) : y;
    let b = B1({
      items: A,
      lookup: g
    });
    for (const y of x.values())
      b = y(b);
    m && h(A), b.length > 0 ? p == null || p(b) : _ && window.requestAnimationFrame(() => {
      const { fitViewQueued: y, nodes: E, setNodes: w } = t.getState();
      y && w(E);
    });
  }, []), s = H1(e), a = vt.useCallback((u) => {
    const { edges: d = [], setEdges: h, hasDefaultEdges: m, onEdgesChange: p, edgeLookup: g } = t.getState();
    let _ = d;
    for (const x of u)
      _ = typeof x == "function" ? x(_) : x;
    m ? h(_) : p && p(B1({
      items: _,
      lookup: g
    }));
  }, []), o = H1(a), c = vt.useMemo(() => ({ nodeQueue: s, edgeQueue: o }), []);
  return _t.jsx(mw.Provider, { value: c, children: n });
}
function f4() {
  const n = vt.useContext(mw);
  if (!n)
    throw new Error("useBatchContext must be used within a BatchProvider");
  return n;
}
const d4 = (n) => !!n.panZoom;
function wv() {
  const n = r4(), t = ln(), e = f4(), s = Pe(d4), a = vt.useMemo(() => {
    const o = (p) => t.getState().nodeLookup.get(p), c = (p) => {
      e.nodeQueue.push(p);
    }, u = (p) => {
      e.edgeQueue.push(p);
    }, d = (p) => {
      var y, E;
      const { nodeLookup: g, nodeOrigin: _ } = t.getState(), x = F1(p) ? p : g.get(p.id), A = x.parentId ? HE(x.position, x.measured, x.parentId, g, _) : x.position, b = {
        ...x,
        position: A,
        width: ((y = x.measured) == null ? void 0 : y.width) ?? x.width,
        height: ((E = x.measured) == null ? void 0 : E.height) ?? x.height
      };
      return xl(b);
    }, h = (p, g, _ = { replace: !1 }) => {
      c((x) => x.map((A) => {
        if (A.id === p) {
          const b = typeof g == "function" ? g(A) : g;
          return _.replace && F1(b) ? b : { ...A, ...b };
        }
        return A;
      }));
    }, m = (p, g, _ = { replace: !1 }) => {
      u((x) => x.map((A) => {
        if (A.id === p) {
          const b = typeof g == "function" ? g(A) : g;
          return _.replace && o4(b) ? b : { ...A, ...b };
        }
        return A;
      }));
    };
    return {
      getNodes: () => t.getState().nodes.map((p) => ({ ...p })),
      getNode: (p) => {
        var g;
        return (g = o(p)) == null ? void 0 : g.internals.userNode;
      },
      getInternalNode: o,
      getEdges: () => {
        const { edges: p = [] } = t.getState();
        return p.map((g) => ({ ...g }));
      },
      getEdge: (p) => t.getState().edgeLookup.get(p),
      setNodes: c,
      setEdges: u,
      addNodes: (p) => {
        const g = Array.isArray(p) ? p : [p];
        e.nodeQueue.push((_) => [..._, ...g]);
      },
      addEdges: (p) => {
        const g = Array.isArray(p) ? p : [p];
        e.edgeQueue.push((_) => [..._, ...g]);
      },
      toObject: () => {
        const { nodes: p = [], edges: g = [], transform: _ } = t.getState(), [x, A, b] = _;
        return {
          nodes: p.map((y) => ({ ...y })),
          edges: g.map((y) => ({ ...y })),
          viewport: {
            x,
            y: A,
            zoom: b
          }
        };
      },
      deleteElements: async ({ nodes: p = [], edges: g = [] }) => {
        const { nodes: _, edges: x, onNodesDelete: A, onEdgesDelete: b, triggerNodeChanges: y, triggerEdgeChanges: E, onDelete: w, onBeforeDelete: M } = t.getState(), { nodes: O, edges: C } = await IB({
          nodesToRemove: p,
          edgesToRemove: g,
          nodes: _,
          edges: x,
          onBeforeDelete: M
        }), D = C.length > 0, T = O.length > 0;
        if (D) {
          const L = C.map(z1);
          b == null || b(C), E(L);
        }
        if (T) {
          const L = O.map(z1);
          A == null || A(O), y(L);
        }
        return (T || D) && (w == null || w({ nodes: O, edges: C })), { deletedNodes: O, deletedEdges: C };
      },
      /**
       * Partial is defined as "the 2 nodes/areas are intersecting partially".
       * If a is contained in b or b is contained in a, they are both
       * considered fully intersecting.
       */
      getIntersectingNodes: (p, g = !0, _) => {
        const x = f1(p), A = x ? p : d(p), b = _ !== void 0;
        return A ? (_ || t.getState().nodes).filter((y) => {
          const E = t.getState().nodeLookup.get(y.id);
          if (E && !x && (y.id === p.id || !E.internals.positionAbsolute))
            return !1;
          const w = xl(b ? y : E), M = Qc(w, A);
          return g && M > 0 || M >= w.width * w.height || M >= A.width * A.height;
        }) : [];
      },
      isNodeIntersecting: (p, g, _ = !0) => {
        const A = f1(p) ? p : d(p);
        if (!A)
          return !1;
        const b = Qc(A, g);
        return _ && b > 0 || b >= g.width * g.height || b >= A.width * A.height;
      },
      updateNode: h,
      updateNodeData: (p, g, _ = { replace: !1 }) => {
        h(p, (x) => {
          const A = typeof g == "function" ? g(x) : g;
          return _.replace ? { ...x, data: A } : { ...x, data: { ...x.data, ...A } };
        }, _);
      },
      updateEdge: m,
      updateEdgeData: (p, g, _ = { replace: !1 }) => {
        m(p, (x) => {
          const A = typeof g == "function" ? g(x) : g;
          return _.replace ? { ...x, data: A } : { ...x, data: { ...x.data, ...A } };
        }, _);
      },
      getNodesBounds: (p) => {
        const { nodeLookup: g, nodeOrigin: _ } = t.getState();
        return OB(p, { nodeLookup: g, nodeOrigin: _ });
      },
      getHandleConnections: ({ type: p, id: g, nodeId: _ }) => {
        var x;
        return Array.from(((x = t.getState().connectionLookup.get(`${_}-${p}${g ? `-${g}` : ""}`)) == null ? void 0 : x.values()) ?? []);
      },
      getNodeConnections: ({ type: p, handleId: g, nodeId: _ }) => {
        var x;
        return Array.from(((x = t.getState().connectionLookup.get(`${_}${p ? g ? `-${p}-${g}` : `-${p}` : ""}`)) == null ? void 0 : x.values()) ?? []);
      },
      fitView: async (p) => {
        const g = t.getState().fitViewResolver ?? HB();
        return t.setState({ fitViewQueued: !0, fitViewOptions: p, fitViewResolver: g }), e.nodeQueue.push((_) => [..._]), g.promise;
      }
    };
  }, []);
  return vt.useMemo(() => ({
    ...a,
    ...n,
    viewportInitialized: s
  }), [s]);
}
const V1 = (n) => n.selected, h4 = typeof window < "u" ? window : void 0;
function p4({ deleteKeyCode: n, multiSelectionKeyCode: t }) {
  const e = ln(), { deleteElements: s } = wv(), a = tu(n, { actInsideInputWithModifier: !1 }), o = tu(t, { target: h4 });
  vt.useEffect(() => {
    if (a) {
      const { edges: c, nodes: u } = e.getState();
      s({ nodes: u.filter(V1), edges: c.filter(V1) }), e.setState({ nodesSelectionActive: !1 });
    }
  }, [a]), vt.useEffect(() => {
    e.setState({ multiSelectionActive: o });
  }, [o]);
}
function m4(n) {
  const t = ln();
  vt.useEffect(() => {
    const e = () => {
      var a, o, c, u;
      if (!n.current || !(((o = (a = n.current).checkVisibility) == null ? void 0 : o.call(a)) ?? !0))
        return !1;
      const s = yv(n.current);
      (s.height === 0 || s.width === 0) && ((u = (c = t.getState()).onError) == null || u.call(c, "004", Ds.error004())), t.setState({ width: s.width || 500, height: s.height || 500 });
    };
    if (n.current) {
      e(), window.addEventListener("resize", e);
      const s = new ResizeObserver(() => e());
      return s.observe(n.current), () => {
        window.removeEventListener("resize", e), s && n.current && s.unobserve(n.current);
      };
    }
  }, []);
}
const ch = {
  position: "absolute",
  width: "100%",
  height: "100%",
  top: 0,
  left: 0
}, g4 = (n) => ({
  userSelectionActive: n.userSelectionActive,
  lib: n.lib,
  connectionInProgress: n.connection.inProgress
});
function v4({ onPaneContextMenu: n, zoomOnScroll: t = !0, zoomOnPinch: e = !0, panOnScroll: s = !1, panOnScrollSpeed: a = 0.5, panOnScrollMode: o = Ga.Free, zoomOnDoubleClick: c = !0, panOnDrag: u = !0, defaultViewport: d, translateExtent: h, minZoom: m, maxZoom: p, zoomActivationKeyCode: g, preventScrolling: _ = !0, children: x, noWheelClassName: A, noPanClassName: b, onViewportChange: y, isControlledViewport: E, paneClickDistance: w, selectionOnDrag: M }) {
  const O = ln(), C = vt.useRef(null), { userSelectionActive: D, lib: T, connectionInProgress: L } = Pe(g4, on), z = tu(g), R = vt.useRef();
  m4(C);
  const B = vt.useCallback((H) => {
    y == null || y({ x: H[0], y: H[1], zoom: H[2] }), E || O.setState({ transform: H });
  }, [y, E]);
  return vt.useEffect(() => {
    if (C.current) {
      R.current = bz({
        domNode: C.current,
        minZoom: m,
        maxZoom: p,
        translateExtent: h,
        viewport: d,
        onDraggingChange: (N) => O.setState((I) => I.paneDragging === N ? I : { paneDragging: N }),
        onPanZoomStart: (N, I) => {
          const { onViewportChangeStart: k, onMoveStart: X } = O.getState();
          X == null || X(N, I), k == null || k(I);
        },
        onPanZoom: (N, I) => {
          const { onViewportChange: k, onMove: X } = O.getState();
          X == null || X(N, I), k == null || k(I);
        },
        onPanZoomEnd: (N, I) => {
          const { onViewportChangeEnd: k, onMoveEnd: X } = O.getState();
          X == null || X(N, I), k == null || k(I);
        }
      });
      const { x: H, y: U, zoom: V } = R.current.getViewport();
      return O.setState({
        panZoom: R.current,
        transform: [H, U, V],
        domNode: C.current.closest(".react-flow")
      }), () => {
        var N;
        (N = R.current) == null || N.destroy();
      };
    }
  }, []), vt.useEffect(() => {
    var H;
    (H = R.current) == null || H.update({
      onPaneContextMenu: n,
      zoomOnScroll: t,
      zoomOnPinch: e,
      panOnScroll: s,
      panOnScrollSpeed: a,
      panOnScrollMode: o,
      zoomOnDoubleClick: c,
      panOnDrag: u,
      zoomActivationKeyPressed: z,
      preventScrolling: _,
      noPanClassName: b,
      userSelectionActive: D,
      noWheelClassName: A,
      lib: T,
      onTransformChange: B,
      connectionInProgress: L,
      selectionOnDrag: M,
      paneClickDistance: w
    });
  }, [
    n,
    t,
    e,
    s,
    a,
    o,
    c,
    u,
    z,
    _,
    b,
    D,
    A,
    T,
    B,
    L,
    M,
    w
  ]), _t.jsx("div", { className: "react-flow__renderer", ref: C, style: ch, children: x });
}
const _4 = (n) => ({
  userSelectionActive: n.userSelectionActive,
  userSelectionRect: n.userSelectionRect
});
function y4() {
  const { userSelectionActive: n, userSelectionRect: t } = Pe(_4, on);
  return n && t ? _t.jsx("div", { className: "react-flow__selection react-flow__container", style: {
    width: t.width,
    height: t.height,
    transform: `translate(${t.x}px, ${t.y}px)`
  } }) : null;
}
const Sg = (n, t) => (e) => {
  e.target === t.current && (n == null || n(e));
}, x4 = (n) => ({
  userSelectionActive: n.userSelectionActive,
  elementsSelectable: n.elementsSelectable,
  connectionInProgress: n.connection.inProgress,
  dragging: n.paneDragging
});
function S4({ isSelecting: n, selectionKeyPressed: t, selectionMode: e = Kc.Full, panOnDrag: s, paneClickDistance: a, selectionOnDrag: o, onSelectionStart: c, onSelectionEnd: u, onPaneClick: d, onPaneContextMenu: h, onPaneScroll: m, onPaneMouseEnter: p, onPaneMouseMove: g, onPaneMouseLeave: _, children: x }) {
  const A = ln(), { userSelectionActive: b, elementsSelectable: y, dragging: E, connectionInProgress: w } = Pe(x4, on), M = y && (n || b), O = vt.useRef(null), C = vt.useRef(), D = vt.useRef(/* @__PURE__ */ new Set()), T = vt.useRef(/* @__PURE__ */ new Set()), L = vt.useRef(!1), z = (k) => {
    if (L.current || w) {
      L.current = !1;
      return;
    }
    d == null || d(k), A.getState().resetSelectedElements(), A.setState({ nodesSelectionActive: !1 });
  }, R = (k) => {
    if (Array.isArray(s) && (s != null && s.includes(2))) {
      k.preventDefault();
      return;
    }
    h == null || h(k);
  }, B = m ? (k) => m(k) : void 0, H = (k) => {
    L.current && (k.stopPropagation(), L.current = !1);
  }, U = (k) => {
    var j, Y;
    const { domNode: X } = A.getState();
    if (C.current = X == null ? void 0 : X.getBoundingClientRect(), !C.current)
      return;
    const Q = k.target === O.current;
    if (!Q && !!k.target.closest(".nokey") || !n || !(o && Q || t) || k.button !== 0 || !k.isPrimary)
      return;
    (Y = (j = k.target) == null ? void 0 : j.setPointerCapture) == null || Y.call(j, k.pointerId), L.current = !1;
    const { x: et, y: $ } = rs(k.nativeEvent, C.current);
    A.setState({
      userSelectionRect: {
        width: 0,
        height: 0,
        startX: et,
        startY: $,
        x: et,
        y: $
      }
    }), Q || (k.stopPropagation(), k.preventDefault());
  }, V = (k) => {
    const { userSelectionRect: X, transform: Q, nodeLookup: F, edgeLookup: W, connectionLookup: et, triggerNodeChanges: $, triggerEdgeChanges: j, defaultEdgeOptions: Y, resetSelectedElements: K } = A.getState();
    if (!C.current || !X)
      return;
    const { x: J, y: rt } = rs(k.nativeEvent, C.current), { startX: dt, startY: yt } = X;
    if (!L.current) {
      const Ft = t ? 0 : a;
      if (Math.hypot(J - dt, rt - yt) <= Ft)
        return;
      K(), c == null || c(k);
    }
    L.current = !0;
    const Pt = {
      startX: dt,
      startY: yt,
      x: J < dt ? J : dt,
      y: rt < yt ? rt : yt,
      width: Math.abs(J - dt),
      height: Math.abs(rt - yt)
    }, Lt = D.current, zt = T.current;
    D.current = new Set(vv(F, Pt, Q, e === Kc.Partial, !0).map((Ft) => Ft.id)), T.current = /* @__PURE__ */ new Set();
    const Xt = (Y == null ? void 0 : Y.selectable) ?? !0;
    for (const Ft of D.current) {
      const ve = et.get(Ft);
      if (ve)
        for (const { edgeId: it } of ve.values()) {
          const Ue = W.get(it);
          Ue && (Ue.selectable ?? Xt) && T.current.add(it);
        }
    }
    if (!d1(Lt, D.current)) {
      const Ft = rl(F, D.current, !0);
      $(Ft);
    }
    if (!d1(zt, T.current)) {
      const Ft = rl(W, T.current);
      j(Ft);
    }
    A.setState({
      userSelectionRect: Pt,
      userSelectionActive: !0,
      nodesSelectionActive: !1
    });
  }, N = (k) => {
    var X, Q;
    k.button === 0 && ((Q = (X = k.target) == null ? void 0 : X.releasePointerCapture) == null || Q.call(X, k.pointerId), !b && k.target === O.current && A.getState().userSelectionRect && (z == null || z(k)), A.setState({
      userSelectionActive: !1,
      userSelectionRect: null
    }), L.current && (u == null || u(k), A.setState({
      nodesSelectionActive: D.current.size > 0
    })));
  }, I = s === !0 || Array.isArray(s) && s.includes(0);
  return _t.jsxs("div", { className: Rn(["react-flow__pane", { draggable: I, dragging: E, selection: n }]), onClick: M ? void 0 : Sg(z, O), onContextMenu: Sg(R, O), onWheel: Sg(B, O), onPointerEnter: M ? void 0 : p, onPointerMove: M ? V : g, onPointerUp: M ? N : void 0, onPointerDownCapture: M ? U : void 0, onClickCapture: M ? H : void 0, onPointerLeave: _, ref: O, style: ch, children: [x, _t.jsx(y4, {})] });
}
function I0({ id: n, store: t, unselect: e = !1, nodeRef: s }) {
  const { addSelectedNodes: a, unselectNodesAndEdges: o, multiSelectionActive: c, nodeLookup: u, onError: d } = t.getState(), h = u.get(n);
  if (!h) {
    d == null || d("012", Ds.error012(n));
    return;
  }
  t.setState({ nodesSelectionActive: !1 }), h.selected ? (e || h.selected && c) && (o({ nodes: [h], edges: [] }), requestAnimationFrame(() => {
    var m;
    return (m = s == null ? void 0 : s.current) == null ? void 0 : m.blur();
  })) : a([n]);
}
function gw({ nodeRef: n, disabled: t = !1, noDragClassName: e, handleSelector: s, nodeId: a, isSelectable: o, nodeClickDistance: c }) {
  const u = ln(), [d, h] = vt.useState(!1), m = vt.useRef();
  return vt.useEffect(() => {
    m.current = lz({
      getStoreItems: () => u.getState(),
      onNodeMouseDown: (p) => {
        I0({
          id: p,
          store: u,
          nodeRef: n
        });
      },
      onDragStart: () => {
        h(!0);
      },
      onDragStop: () => {
        h(!1);
      }
    });
  }, []), vt.useEffect(() => {
    if (!(t || !n.current || !m.current))
      return m.current.update({
        noDragClassName: e,
        handleSelector: s,
        domNode: n.current,
        isSelectable: o,
        nodeId: a,
        nodeClickDistance: c
      }), () => {
        var p;
        (p = m.current) == null || p.destroy();
      };
  }, [e, s, t, o, n, a, c]), d;
}
const b4 = (n) => (t) => t.selected && (t.draggable || n && typeof t.draggable > "u");
function vw() {
  const n = ln();
  return vt.useCallback((e) => {
    const { nodeExtent: s, snapToGrid: a, snapGrid: o, nodesDraggable: c, onError: u, updateNodePositions: d, nodeLookup: h, nodeOrigin: m } = n.getState(), p = /* @__PURE__ */ new Map(), g = b4(c), _ = a ? o[0] : 5, x = a ? o[1] : 5, A = e.direction.x * _ * e.factor, b = e.direction.y * x * e.factor;
    for (const [, y] of h) {
      if (!g(y))
        continue;
      let E = {
        x: y.internals.positionAbsolute.x + A,
        y: y.internals.positionAbsolute.y + b
      };
      a && (E = ou(E, o));
      const { position: w, positionAbsolute: M } = PE({
        nodeId: y.id,
        nextPosition: E,
        nodeLookup: h,
        nodeExtent: s,
        nodeOrigin: m,
        onError: u
      });
      y.position = w, y.internals.positionAbsolute = M, p.set(y.id, y);
    }
    d(p);
  }, []);
}
const Av = vt.createContext(null), M4 = Av.Provider;
Av.Consumer;
const _w = () => vt.useContext(Av), E4 = (n) => ({
  connectOnClick: n.connectOnClick,
  noPanClassName: n.noPanClassName,
  rfId: n.rfId
}), w4 = (n, t, e) => (s) => {
  const { connectionClickStartHandle: a, connectionMode: o, connection: c } = s, { fromHandle: u, toHandle: d, isValid: h } = c, m = (d == null ? void 0 : d.nodeId) === n && (d == null ? void 0 : d.id) === t && (d == null ? void 0 : d.type) === e;
  return {
    connectingFrom: (u == null ? void 0 : u.nodeId) === n && (u == null ? void 0 : u.id) === t && (u == null ? void 0 : u.type) === e,
    connectingTo: m,
    clickConnecting: (a == null ? void 0 : a.nodeId) === n && (a == null ? void 0 : a.id) === t && (a == null ? void 0 : a.type) === e,
    isPossibleEndHandle: o === _l.Strict ? (u == null ? void 0 : u.type) !== e : n !== (u == null ? void 0 : u.nodeId) || t !== (u == null ? void 0 : u.id),
    connectionInProcess: !!u,
    clickConnectionInProcess: !!a,
    valid: m && h
  };
};
function A4({ type: n = "source", position: t = oe.Top, isValidConnection: e, isConnectable: s = !0, isConnectableStart: a = !0, isConnectableEnd: o = !0, id: c, onConnect: u, children: d, className: h, onMouseDown: m, onTouchStart: p, ...g }, _) {
  var V, N;
  const x = c || null, A = n === "target", b = ln(), y = _w(), { connectOnClick: E, noPanClassName: w, rfId: M } = Pe(E4, on), { connectingFrom: O, connectingTo: C, clickConnecting: D, isPossibleEndHandle: T, connectionInProcess: L, clickConnectionInProcess: z, valid: R } = Pe(w4(y, x, n), on);
  y || (N = (V = b.getState()).onError) == null || N.call(V, "010", Ds.error010());
  const B = (I) => {
    const { defaultEdgeOptions: k, onConnect: X, hasDefaultEdges: Q } = b.getState(), F = {
      ...k,
      ...I
    };
    if (Q) {
      const { edges: W, setEdges: et } = b.getState();
      et(jE(F, W));
    }
    X == null || X(F), u == null || u(F);
  }, H = (I) => {
    if (!y)
      return;
    const k = kE(I.nativeEvent);
    if (a && (k && I.button === 0 || !k)) {
      const X = b.getState();
      P0.onPointerDown(I.nativeEvent, {
        handleDomNode: I.currentTarget,
        autoPanOnConnect: X.autoPanOnConnect,
        connectionMode: X.connectionMode,
        connectionRadius: X.connectionRadius,
        domNode: X.domNode,
        nodeLookup: X.nodeLookup,
        lib: X.lib,
        isTarget: A,
        handleId: x,
        nodeId: y,
        flowId: X.rfId,
        panBy: X.panBy,
        cancelConnection: X.cancelConnection,
        onConnectStart: X.onConnectStart,
        onConnectEnd: (...Q) => {
          var F, W;
          return (W = (F = b.getState()).onConnectEnd) == null ? void 0 : W.call(F, ...Q);
        },
        updateConnection: X.updateConnection,
        onConnect: B,
        isValidConnection: e || ((...Q) => {
          var F, W;
          return ((W = (F = b.getState()).isValidConnection) == null ? void 0 : W.call(F, ...Q)) ?? !0;
        }),
        getTransform: () => b.getState().transform,
        getFromHandle: () => b.getState().connection.fromHandle,
        autoPanSpeed: X.autoPanSpeed,
        dragThreshold: X.connectionDragThreshold
      });
    }
    k ? m == null || m(I) : p == null || p(I);
  }, U = (I) => {
    const { onClickConnectStart: k, onClickConnectEnd: X, connectionClickStartHandle: Q, connectionMode: F, isValidConnection: W, lib: et, rfId: $, nodeLookup: j, connection: Y } = b.getState();
    if (!y || !Q && !a)
      return;
    if (!Q) {
      k == null || k(I.nativeEvent, { nodeId: y, handleId: x, handleType: n }), b.setState({ connectionClickStartHandle: { nodeId: y, type: n, id: x } });
      return;
    }
    const K = VE(I.target), J = e || W, { connection: rt, isValid: dt } = P0.isValid(I.nativeEvent, {
      handle: {
        nodeId: y,
        id: x,
        type: n
      },
      connectionMode: F,
      fromNodeId: Q.nodeId,
      fromHandleId: Q.id || null,
      fromType: Q.type,
      isValidConnection: J,
      flowId: $,
      doc: K,
      lib: et,
      nodeLookup: j
    });
    dt && rt && B(rt);
    const yt = structuredClone(Y);
    delete yt.inProgress, yt.toPosition = yt.toHandle ? yt.toHandle.position : null, X == null || X(I, yt), b.setState({ connectionClickStartHandle: null });
  };
  return _t.jsx("div", { "data-handleid": x, "data-nodeid": y, "data-handlepos": t, "data-id": `${M}-${y}-${x}-${n}`, className: Rn([
    "react-flow__handle",
    `react-flow__handle-${t}`,
    "nodrag",
    w,
    h,
    {
      source: !A,
      target: A,
      connectable: s,
      connectablestart: a,
      connectableend: o,
      clickconnecting: D,
      connectingfrom: O,
      connectingto: C,
      valid: R,
      /*
       * shows where you can start a connection from
       * and where you can end it while connecting
       */
      connectionindicator: s && (!L || T) && (L || z ? o : a)
    }
  ]), onMouseDown: H, onTouchStart: H, onClick: E ? U : void 0, ref: _, ...g, children: d });
}
const Vd = vt.memo(pw(A4));
function T4({ data: n, isConnectable: t, sourcePosition: e = oe.Bottom }) {
  return _t.jsxs(_t.Fragment, { children: [n == null ? void 0 : n.label, _t.jsx(Vd, { type: "source", position: e, isConnectable: t })] });
}
function C4({ data: n, isConnectable: t, targetPosition: e = oe.Top, sourcePosition: s = oe.Bottom }) {
  return _t.jsxs(_t.Fragment, { children: [_t.jsx(Vd, { type: "target", position: e, isConnectable: t }), n == null ? void 0 : n.label, _t.jsx(Vd, { type: "source", position: s, isConnectable: t })] });
}
function R4() {
  return null;
}
function D4({ data: n, isConnectable: t, targetPosition: e = oe.Top }) {
  return _t.jsxs(_t.Fragment, { children: [_t.jsx(Vd, { type: "target", position: e, isConnectable: t }), n == null ? void 0 : n.label] });
}
const Gd = {
  ArrowUp: { x: 0, y: -1 },
  ArrowDown: { x: 0, y: 1 },
  ArrowLeft: { x: -1, y: 0 },
  ArrowRight: { x: 1, y: 0 }
}, G1 = {
  input: T4,
  default: C4,
  output: D4,
  group: R4
};
function N4(n) {
  var t, e, s, a;
  return n.internals.handleBounds === void 0 ? {
    width: n.width ?? n.initialWidth ?? ((t = n.style) == null ? void 0 : t.width),
    height: n.height ?? n.initialHeight ?? ((e = n.style) == null ? void 0 : e.height)
  } : {
    width: n.width ?? ((s = n.style) == null ? void 0 : s.width),
    height: n.height ?? ((a = n.style) == null ? void 0 : a.height)
  };
}
const O4 = (n) => {
  const { width: t, height: e, x: s, y: a } = au(n.nodeLookup, {
    filter: (o) => !!o.selected
  });
  return {
    width: ss(t) ? t : null,
    height: ss(e) ? e : null,
    userSelectionActive: n.userSelectionActive,
    transformString: `translate(${n.transform[0]}px,${n.transform[1]}px) scale(${n.transform[2]}) translate(${s}px,${a}px)`
  };
};
function L4({ onSelectionContextMenu: n, noPanClassName: t, disableKeyboardA11y: e }) {
  const s = ln(), { width: a, height: o, transformString: c, userSelectionActive: u } = Pe(O4, on), d = vw(), h = vt.useRef(null);
  vt.useEffect(() => {
    var _;
    e || (_ = h.current) == null || _.focus({
      preventScroll: !0
    });
  }, [e]);
  const m = !u && a !== null && o !== null;
  if (gw({
    nodeRef: h,
    disabled: !m
  }), !m)
    return null;
  const p = n ? (_) => {
    const x = s.getState().nodes.filter((A) => A.selected);
    n(_, x);
  } : void 0, g = (_) => {
    Object.prototype.hasOwnProperty.call(Gd, _.key) && (_.preventDefault(), d({
      direction: Gd[_.key],
      factor: _.shiftKey ? 4 : 1
    }));
  };
  return _t.jsx("div", { className: Rn(["react-flow__nodesselection", "react-flow__container", t]), style: {
    transform: c
  }, children: _t.jsx("div", { ref: h, className: "react-flow__nodesselection-rect", onContextMenu: p, tabIndex: e ? void 0 : -1, onKeyDown: e ? void 0 : g, style: {
    width: a,
    height: o
  } }) });
}
const k1 = typeof window < "u" ? window : void 0, U4 = (n) => ({ nodesSelectionActive: n.nodesSelectionActive, userSelectionActive: n.userSelectionActive });
function yw({ children: n, onPaneClick: t, onPaneMouseEnter: e, onPaneMouseMove: s, onPaneMouseLeave: a, onPaneContextMenu: o, onPaneScroll: c, paneClickDistance: u, deleteKeyCode: d, selectionKeyCode: h, selectionOnDrag: m, selectionMode: p, onSelectionStart: g, onSelectionEnd: _, multiSelectionKeyCode: x, panActivationKeyCode: A, zoomActivationKeyCode: b, elementsSelectable: y, zoomOnScroll: E, zoomOnPinch: w, panOnScroll: M, panOnScrollSpeed: O, panOnScrollMode: C, zoomOnDoubleClick: D, panOnDrag: T, defaultViewport: L, translateExtent: z, minZoom: R, maxZoom: B, preventScrolling: H, onSelectionContextMenu: U, noWheelClassName: V, noPanClassName: N, disableKeyboardA11y: I, onViewportChange: k, isControlledViewport: X }) {
  const { nodesSelectionActive: Q, userSelectionActive: F } = Pe(U4, on), W = tu(h, { target: k1 }), et = tu(A, { target: k1 }), $ = et || T, j = et || M, Y = m && $ !== !0, K = W || F || Y;
  return p4({ deleteKeyCode: d, multiSelectionKeyCode: x }), _t.jsx(v4, { onPaneContextMenu: o, elementsSelectable: y, zoomOnScroll: E, zoomOnPinch: w, panOnScroll: j, panOnScrollSpeed: O, panOnScrollMode: C, zoomOnDoubleClick: D, panOnDrag: !W && $, defaultViewport: L, translateExtent: z, minZoom: R, maxZoom: B, zoomActivationKeyCode: b, preventScrolling: H, noWheelClassName: V, noPanClassName: N, onViewportChange: k, isControlledViewport: X, paneClickDistance: u, selectionOnDrag: Y, children: _t.jsxs(S4, { onSelectionStart: g, onSelectionEnd: _, onPaneClick: t, onPaneMouseEnter: e, onPaneMouseMove: s, onPaneMouseLeave: a, onPaneContextMenu: o, onPaneScroll: c, panOnDrag: $, isSelecting: !!K, selectionMode: p, selectionKeyPressed: W, paneClickDistance: u, selectionOnDrag: Y, children: [n, Q && _t.jsx(L4, { onSelectionContextMenu: U, noPanClassName: N, disableKeyboardA11y: I })] }) });
}
yw.displayName = "FlowRenderer";
const P4 = vt.memo(yw), I4 = (n) => (t) => n ? vv(t.nodeLookup, { x: 0, y: 0, width: t.width, height: t.height }, t.transform, !0).map((e) => e.id) : Array.from(t.nodeLookup.keys());
function B4(n) {
  return Pe(vt.useCallback(I4(n), [n]), on);
}
const z4 = (n) => n.updateNodeInternals;
function F4() {
  const n = Pe(z4), [t] = vt.useState(() => typeof ResizeObserver > "u" ? null : new ResizeObserver((e) => {
    const s = /* @__PURE__ */ new Map();
    e.forEach((a) => {
      const o = a.target.getAttribute("data-id");
      s.set(o, {
        id: o,
        nodeElement: a.target,
        force: !0
      });
    }), n(s);
  }));
  return vt.useEffect(() => () => {
    t == null || t.disconnect();
  }, [t]), t;
}
function H4({ node: n, nodeType: t, hasDimensions: e, resizeObserver: s }) {
  const a = ln(), o = vt.useRef(null), c = vt.useRef(null), u = vt.useRef(n.sourcePosition), d = vt.useRef(n.targetPosition), h = vt.useRef(t), m = e && !!n.internals.handleBounds;
  return vt.useEffect(() => {
    o.current && !n.hidden && (!m || c.current !== o.current) && (c.current && (s == null || s.unobserve(c.current)), s == null || s.observe(o.current), c.current = o.current);
  }, [m, n.hidden]), vt.useEffect(() => () => {
    c.current && (s == null || s.unobserve(c.current), c.current = null);
  }, []), vt.useEffect(() => {
    if (o.current) {
      const p = h.current !== t, g = u.current !== n.sourcePosition, _ = d.current !== n.targetPosition;
      (p || g || _) && (h.current = t, u.current = n.sourcePosition, d.current = n.targetPosition, a.getState().updateNodeInternals(/* @__PURE__ */ new Map([[n.id, { id: n.id, nodeElement: o.current, force: !0 }]])));
    }
  }, [n.id, t, n.sourcePosition, n.targetPosition]), o;
}
function V4({ id: n, onClick: t, onMouseEnter: e, onMouseMove: s, onMouseLeave: a, onContextMenu: o, onDoubleClick: c, nodesDraggable: u, elementsSelectable: d, nodesConnectable: h, nodesFocusable: m, resizeObserver: p, noDragClassName: g, noPanClassName: _, disableKeyboardA11y: x, rfId: A, nodeTypes: b, nodeClickDistance: y, onError: E }) {
  const { node: w, internals: M, isParent: O } = Pe((J) => {
    const rt = J.nodeLookup.get(n), dt = J.parentLookup.has(n);
    return {
      node: rt,
      internals: rt.internals,
      isParent: dt
    };
  }, on);
  let C = w.type || "default", D = (b == null ? void 0 : b[C]) || G1[C];
  D === void 0 && (E == null || E("003", Ds.error003(C)), C = "default", D = (b == null ? void 0 : b.default) || G1.default);
  const T = !!(w.draggable || u && typeof w.draggable > "u"), L = !!(w.selectable || d && typeof w.selectable > "u"), z = !!(w.connectable || h && typeof w.connectable > "u"), R = !!(w.focusable || m && typeof w.focusable > "u"), B = ln(), H = FE(w), U = H4({ node: w, nodeType: C, hasDimensions: H, resizeObserver: p }), V = gw({
    nodeRef: U,
    disabled: w.hidden || !T,
    noDragClassName: g,
    handleSelector: w.dragHandle,
    nodeId: n,
    isSelectable: L,
    nodeClickDistance: y
  }), N = vw();
  if (w.hidden)
    return null;
  const I = gr(w), k = N4(w), X = L || T || t || e || s || a, Q = e ? (J) => e(J, { ...M.userNode }) : void 0, F = s ? (J) => s(J, { ...M.userNode }) : void 0, W = a ? (J) => a(J, { ...M.userNode }) : void 0, et = o ? (J) => o(J, { ...M.userNode }) : void 0, $ = c ? (J) => c(J, { ...M.userNode }) : void 0, j = (J) => {
    const { selectNodesOnDrag: rt, nodeDragThreshold: dt } = B.getState();
    L && (!rt || !T || dt > 0) && I0({
      id: n,
      store: B,
      nodeRef: U
    }), t && t(J, { ...M.userNode });
  }, Y = (J) => {
    if (!(GE(J.nativeEvent) || x)) {
      if (DE.includes(J.key) && L) {
        const rt = J.key === "Escape";
        I0({
          id: n,
          store: B,
          unselect: rt,
          nodeRef: U
        });
      } else if (T && w.selected && Object.prototype.hasOwnProperty.call(Gd, J.key)) {
        J.preventDefault();
        const { ariaLabelConfig: rt } = B.getState();
        B.setState({
          ariaLiveMessage: rt["node.a11yDescription.ariaLiveMessage"]({
            direction: J.key.replace("Arrow", "").toLowerCase(),
            x: ~~M.positionAbsolute.x,
            y: ~~M.positionAbsolute.y
          })
        }), N({
          direction: Gd[J.key],
          factor: J.shiftKey ? 4 : 1
        });
      }
    }
  }, K = () => {
    var zt;
    if (x || !((zt = U.current) != null && zt.matches(":focus-visible")))
      return;
    const { transform: J, width: rt, height: dt, autoPanOnNodeFocus: yt, setCenter: Pt } = B.getState();
    if (!yt)
      return;
    vv(/* @__PURE__ */ new Map([[n, w]]), { x: 0, y: 0, width: rt, height: dt }, J, !0).length > 0 || Pt(w.position.x + I.width / 2, w.position.y + I.height / 2, {
      zoom: J[2]
    });
  };
  return _t.jsx("div", { className: Rn([
    "react-flow__node",
    `react-flow__node-${C}`,
    {
      // this is overwritable by passing `nopan` as a class name
      [_]: T
    },
    w.className,
    {
      selected: w.selected,
      selectable: L,
      parent: O,
      draggable: T,
      dragging: V
    }
  ]), ref: U, style: {
    zIndex: M.z,
    transform: `translate(${M.positionAbsolute.x}px,${M.positionAbsolute.y}px)`,
    pointerEvents: X ? "all" : "none",
    visibility: H ? "visible" : "hidden",
    ...w.style,
    ...k
  }, "data-id": n, "data-testid": `rf__node-${n}`, onMouseEnter: Q, onMouseMove: F, onMouseLeave: W, onContextMenu: et, onClick: j, onDoubleClick: $, onKeyDown: R ? Y : void 0, tabIndex: R ? 0 : void 0, onFocus: R ? K : void 0, role: w.ariaRole ?? (R ? "group" : void 0), "aria-roledescription": "node", "aria-describedby": x ? void 0 : `${lw}-${A}`, "aria-label": w.ariaLabel, ...w.domAttributes, children: _t.jsx(M4, { value: n, children: _t.jsx(D, { id: n, data: w.data, type: C, positionAbsoluteX: M.positionAbsolute.x, positionAbsoluteY: M.positionAbsolute.y, selected: w.selected ?? !1, selectable: L, draggable: T, deletable: w.deletable ?? !0, isConnectable: z, sourcePosition: w.sourcePosition, targetPosition: w.targetPosition, dragging: V, dragHandle: w.dragHandle, zIndex: M.z, parentId: w.parentId, ...I }) }) });
}
var G4 = vt.memo(V4);
const k4 = (n) => ({
  nodesDraggable: n.nodesDraggable,
  nodesConnectable: n.nodesConnectable,
  nodesFocusable: n.nodesFocusable,
  elementsSelectable: n.elementsSelectable,
  onError: n.onError
});
function xw(n) {
  const { nodesDraggable: t, nodesConnectable: e, nodesFocusable: s, elementsSelectable: a, onError: o } = Pe(k4, on), c = B4(n.onlyRenderVisibleElements), u = F4();
  return _t.jsx("div", { className: "react-flow__nodes", style: ch, children: c.map((d) => (
    /*
     * The split of responsibilities between NodeRenderer and
     * NodeComponentWrapper may appear weird. However, it’s designed to
     * minimize the cost of updates when individual nodes change.
     *
     * For example, when you’re dragging a single node, that node gets
     * updated multiple times per second. If `NodeRenderer` were to update
     * every time, it would have to re-run the `nodes.map()` loop every
     * time. This gets pricey with hundreds of nodes, especially if every
     * loop cycle does more than just rendering a JSX element!
     *
     * As a result of this choice, we took the following implementation
     * decisions:
     * - NodeRenderer subscribes *only* to node IDs – and therefore
     *   rerender *only* when visible nodes are added or removed.
     * - NodeRenderer performs all operations the result of which can be
     *   shared between nodes (such as creating the `ResizeObserver`
     *   instance, or subscribing to `selector`). This means extra prop
     *   drilling into `NodeComponentWrapper`, but it means we need to run
     *   these operations only once – instead of once per node.
     * - Any operations that you’d normally write inside `nodes.map` are
     *   moved into `NodeComponentWrapper`. This ensures they are
     *   memorized – so if `NodeRenderer` *has* to rerender, it only
     *   needs to regenerate the list of nodes, nothing else.
     */
    _t.jsx(G4, { id: d, nodeTypes: n.nodeTypes, nodeExtent: n.nodeExtent, onClick: n.onNodeClick, onMouseEnter: n.onNodeMouseEnter, onMouseMove: n.onNodeMouseMove, onMouseLeave: n.onNodeMouseLeave, onContextMenu: n.onNodeContextMenu, onDoubleClick: n.onNodeDoubleClick, noDragClassName: n.noDragClassName, noPanClassName: n.noPanClassName, rfId: n.rfId, disableKeyboardA11y: n.disableKeyboardA11y, resizeObserver: u, nodesDraggable: t, nodesConnectable: e, nodesFocusable: s, elementsSelectable: a, nodeClickDistance: n.nodeClickDistance, onError: o }, d)
  )) });
}
xw.displayName = "NodeRenderer";
const X4 = vt.memo(xw);
function W4(n) {
  return Pe(vt.useCallback((e) => {
    if (!n)
      return e.edges.map((a) => a.id);
    const s = [];
    if (e.width && e.height)
      for (const a of e.edges) {
        const o = e.nodeLookup.get(a.source), c = e.nodeLookup.get(a.target);
        o && c && XB({
          sourceNode: o,
          targetNode: c,
          width: e.width,
          height: e.height,
          transform: e.transform
        }) && s.push(a.id);
      }
    return s;
  }, [n]), on);
}
const Y4 = ({ color: n = "none", strokeWidth: t = 1 }) => {
  const e = {
    strokeWidth: t,
    ...n && { stroke: n }
  };
  return _t.jsx("polyline", { className: "arrow", style: e, strokeLinecap: "round", fill: "none", strokeLinejoin: "round", points: "-5,-4 0,0 -5,4" });
}, j4 = ({ color: n = "none", strokeWidth: t = 1 }) => {
  const e = {
    strokeWidth: t,
    ...n && { stroke: n, fill: n }
  };
  return _t.jsx("polyline", { className: "arrowclosed", style: e, strokeLinecap: "round", strokeLinejoin: "round", points: "-5,-4 0,0 -5,4 -5,-4" });
}, X1 = {
  [zd.Arrow]: Y4,
  [zd.ArrowClosed]: j4
};
function q4(n) {
  const t = ln();
  return vt.useMemo(() => {
    var a, o;
    return Object.prototype.hasOwnProperty.call(X1, n) ? X1[n] : ((o = (a = t.getState()).onError) == null || o.call(a, "009", Ds.error009(n)), null);
  }, [n]);
}
const Z4 = ({ id: n, type: t, color: e, width: s = 12.5, height: a = 12.5, markerUnits: o = "strokeWidth", strokeWidth: c, orient: u = "auto-start-reverse" }) => {
  const d = q4(t);
  return d ? _t.jsx("marker", { className: "react-flow__arrowhead", id: n, markerWidth: `${s}`, markerHeight: `${a}`, viewBox: "-10 -10 20 20", markerUnits: o, orient: u, refX: "0", refY: "0", children: _t.jsx(d, { color: e, strokeWidth: c }) }) : null;
}, Sw = ({ defaultColor: n, rfId: t }) => {
  const e = Pe((o) => o.edges), s = Pe((o) => o.defaultEdgeOptions), a = vt.useMemo(() => KB(e, {
    id: t,
    defaultColor: n,
    defaultMarkerStart: s == null ? void 0 : s.markerStart,
    defaultMarkerEnd: s == null ? void 0 : s.markerEnd
  }), [e, s, t, n]);
  return a.length ? _t.jsx("svg", { className: "react-flow__marker", "aria-hidden": "true", children: _t.jsx("defs", { children: a.map((o) => _t.jsx(Z4, { id: o.id, type: o.type, color: o.color, width: o.width, height: o.height, markerUnits: o.markerUnits, strokeWidth: o.strokeWidth, orient: o.orient }, o.id)) }) }) : null;
};
Sw.displayName = "MarkerDefinitions";
var $4 = vt.memo(Sw);
function bw({ x: n, y: t, label: e, labelStyle: s, labelShowBg: a = !0, labelBgStyle: o, labelBgPadding: c = [2, 4], labelBgBorderRadius: u = 2, children: d, className: h, ...m }) {
  const [p, g] = vt.useState({ x: 1, y: 0, width: 0, height: 0 }), _ = Rn(["react-flow__edge-textwrapper", h]), x = vt.useRef(null);
  return vt.useEffect(() => {
    if (x.current) {
      const A = x.current.getBBox();
      g({
        x: A.x,
        y: A.y,
        width: A.width,
        height: A.height
      });
    }
  }, [e]), e ? _t.jsxs("g", { transform: `translate(${n - p.width / 2} ${t - p.height / 2})`, className: _, visibility: p.width ? "visible" : "hidden", ...m, children: [a && _t.jsx("rect", { width: p.width + 2 * c[0], x: -c[0], y: -c[1], height: p.height + 2 * c[1], className: "react-flow__edge-textbg", style: o, rx: u, ry: u }), _t.jsx("text", { className: "react-flow__edge-text", y: p.height / 2, dy: "0.3em", ref: x, style: s, children: e }), d] }) : null;
}
bw.displayName = "EdgeText";
const K4 = vt.memo(bw);
function uh({ path: n, labelX: t, labelY: e, label: s, labelStyle: a, labelShowBg: o, labelBgStyle: c, labelBgPadding: u, labelBgBorderRadius: d, interactionWidth: h = 20, ...m }) {
  return _t.jsxs(_t.Fragment, { children: [_t.jsx("path", { ...m, d: n, fill: "none", className: Rn(["react-flow__edge-path", m.className]) }), h ? _t.jsx("path", { d: n, fill: "none", strokeOpacity: 0, strokeWidth: h, className: "react-flow__edge-interaction" }) : null, s && ss(t) && ss(e) ? _t.jsx(K4, { x: t, y: e, label: s, labelStyle: a, labelShowBg: o, labelBgStyle: c, labelBgPadding: u, labelBgBorderRadius: d }) : null] });
}
function W1({ pos: n, x1: t, y1: e, x2: s, y2: a }) {
  return n === oe.Left || n === oe.Right ? [0.5 * (t + s), e] : [t, 0.5 * (e + a)];
}
function Mw({ sourceX: n, sourceY: t, sourcePosition: e = oe.Bottom, targetX: s, targetY: a, targetPosition: o = oe.Top }) {
  const [c, u] = W1({
    pos: e,
    x1: n,
    y1: t,
    x2: s,
    y2: a
  }), [d, h] = W1({
    pos: o,
    x1: s,
    y1: a,
    x2: n,
    y2: t
  }), [m, p, g, _] = XE({
    sourceX: n,
    sourceY: t,
    targetX: s,
    targetY: a,
    sourceControlX: c,
    sourceControlY: u,
    targetControlX: d,
    targetControlY: h
  });
  return [
    `M${n},${t} C${c},${u} ${d},${h} ${s},${a}`,
    m,
    p,
    g,
    _
  ];
}
function Ew(n) {
  return vt.memo(({ id: t, sourceX: e, sourceY: s, targetX: a, targetY: o, sourcePosition: c, targetPosition: u, label: d, labelStyle: h, labelShowBg: m, labelBgStyle: p, labelBgPadding: g, labelBgBorderRadius: _, style: x, markerEnd: A, markerStart: b, interactionWidth: y }) => {
    const [E, w, M] = Mw({
      sourceX: e,
      sourceY: s,
      sourcePosition: c,
      targetX: a,
      targetY: o,
      targetPosition: u
    }), O = n.isInternal ? void 0 : t;
    return _t.jsx(uh, { id: O, path: E, labelX: w, labelY: M, label: d, labelStyle: h, labelShowBg: m, labelBgStyle: p, labelBgPadding: g, labelBgBorderRadius: _, style: x, markerEnd: A, markerStart: b, interactionWidth: y });
  });
}
const Q4 = Ew({ isInternal: !1 }), ww = Ew({ isInternal: !0 });
Q4.displayName = "SimpleBezierEdge";
ww.displayName = "SimpleBezierEdgeInternal";
function Aw(n) {
  return vt.memo(({ id: t, sourceX: e, sourceY: s, targetX: a, targetY: o, label: c, labelStyle: u, labelShowBg: d, labelBgStyle: h, labelBgPadding: m, labelBgBorderRadius: p, style: g, sourcePosition: _ = oe.Bottom, targetPosition: x = oe.Top, markerEnd: A, markerStart: b, pathOptions: y, interactionWidth: E }) => {
    const [w, M, O] = O0({
      sourceX: e,
      sourceY: s,
      sourcePosition: _,
      targetX: a,
      targetY: o,
      targetPosition: x,
      borderRadius: y == null ? void 0 : y.borderRadius,
      offset: y == null ? void 0 : y.offset,
      stepPosition: y == null ? void 0 : y.stepPosition
    }), C = n.isInternal ? void 0 : t;
    return _t.jsx(uh, { id: C, path: w, labelX: M, labelY: O, label: c, labelStyle: u, labelShowBg: d, labelBgStyle: h, labelBgPadding: m, labelBgBorderRadius: p, style: g, markerEnd: A, markerStart: b, interactionWidth: E });
  });
}
const Tw = Aw({ isInternal: !1 }), Cw = Aw({ isInternal: !0 });
Tw.displayName = "SmoothStepEdge";
Cw.displayName = "SmoothStepEdgeInternal";
function Rw(n) {
  return vt.memo(({ id: t, ...e }) => {
    var a;
    const s = n.isInternal ? void 0 : t;
    return _t.jsx(Tw, { ...e, id: s, pathOptions: vt.useMemo(() => {
      var o;
      return { borderRadius: 0, offset: (o = e.pathOptions) == null ? void 0 : o.offset };
    }, [(a = e.pathOptions) == null ? void 0 : a.offset]) });
  });
}
const J4 = Rw({ isInternal: !1 }), Dw = Rw({ isInternal: !0 });
J4.displayName = "StepEdge";
Dw.displayName = "StepEdgeInternal";
function Nw(n) {
  return vt.memo(({ id: t, sourceX: e, sourceY: s, targetX: a, targetY: o, label: c, labelStyle: u, labelShowBg: d, labelBgStyle: h, labelBgPadding: m, labelBgBorderRadius: p, style: g, markerEnd: _, markerStart: x, interactionWidth: A }) => {
    const [b, y, E] = qE({ sourceX: e, sourceY: s, targetX: a, targetY: o }), w = n.isInternal ? void 0 : t;
    return _t.jsx(uh, { id: w, path: b, labelX: y, labelY: E, label: c, labelStyle: u, labelShowBg: d, labelBgStyle: h, labelBgPadding: m, labelBgBorderRadius: p, style: g, markerEnd: _, markerStart: x, interactionWidth: A });
  });
}
const tF = Nw({ isInternal: !1 }), Ow = Nw({ isInternal: !0 });
tF.displayName = "StraightEdge";
Ow.displayName = "StraightEdgeInternal";
function Lw(n) {
  return vt.memo(({ id: t, sourceX: e, sourceY: s, targetX: a, targetY: o, sourcePosition: c = oe.Bottom, targetPosition: u = oe.Top, label: d, labelStyle: h, labelShowBg: m, labelBgStyle: p, labelBgPadding: g, labelBgBorderRadius: _, style: x, markerEnd: A, markerStart: b, pathOptions: y, interactionWidth: E }) => {
    const [w, M, O] = WE({
      sourceX: e,
      sourceY: s,
      sourcePosition: c,
      targetX: a,
      targetY: o,
      targetPosition: u,
      curvature: y == null ? void 0 : y.curvature
    }), C = n.isInternal ? void 0 : t;
    return _t.jsx(uh, { id: C, path: w, labelX: M, labelY: O, label: d, labelStyle: h, labelShowBg: m, labelBgStyle: p, labelBgPadding: g, labelBgBorderRadius: _, style: x, markerEnd: A, markerStart: b, interactionWidth: E });
  });
}
const eF = Lw({ isInternal: !1 }), Uw = Lw({ isInternal: !0 });
eF.displayName = "BezierEdge";
Uw.displayName = "BezierEdgeInternal";
const Y1 = {
  default: Uw,
  straight: Ow,
  step: Dw,
  smoothstep: Cw,
  simplebezier: ww
}, j1 = {
  sourceX: null,
  sourceY: null,
  targetX: null,
  targetY: null,
  sourcePosition: null,
  targetPosition: null
}, nF = (n, t, e) => e === oe.Left ? n - t : e === oe.Right ? n + t : n, iF = (n, t, e) => e === oe.Top ? n - t : e === oe.Bottom ? n + t : n, q1 = "react-flow__edgeupdater";
function Z1({ position: n, centerX: t, centerY: e, radius: s = 10, onMouseDown: a, onMouseEnter: o, onMouseOut: c, type: u }) {
  return _t.jsx("circle", { onMouseDown: a, onMouseEnter: o, onMouseOut: c, className: Rn([q1, `${q1}-${u}`]), cx: nF(t, s, n), cy: iF(e, s, n), r: s, stroke: "transparent", fill: "transparent" });
}
function sF({ isReconnectable: n, reconnectRadius: t, edge: e, sourceX: s, sourceY: a, targetX: o, targetY: c, sourcePosition: u, targetPosition: d, onReconnect: h, onReconnectStart: m, onReconnectEnd: p, setReconnecting: g, setUpdateHover: _ }) {
  const x = ln(), A = (M, O) => {
    if (M.button !== 0)
      return;
    const { autoPanOnConnect: C, domNode: D, connectionMode: T, connectionRadius: L, lib: z, onConnectStart: R, cancelConnection: B, nodeLookup: H, rfId: U, panBy: V, updateConnection: N } = x.getState(), I = O.type === "target", k = (F, W) => {
      g(!1), p == null || p(F, e, O.type, W);
    }, X = (F) => h == null ? void 0 : h(e, F), Q = (F, W) => {
      g(!0), m == null || m(M, e, O.type), R == null || R(F, W);
    };
    P0.onPointerDown(M.nativeEvent, {
      autoPanOnConnect: C,
      connectionMode: T,
      connectionRadius: L,
      domNode: D,
      handleId: O.id,
      nodeId: O.nodeId,
      nodeLookup: H,
      isTarget: I,
      edgeUpdaterType: O.type,
      lib: z,
      flowId: U,
      cancelConnection: B,
      panBy: V,
      isValidConnection: (...F) => {
        var W, et;
        return ((et = (W = x.getState()).isValidConnection) == null ? void 0 : et.call(W, ...F)) ?? !0;
      },
      onConnect: X,
      onConnectStart: Q,
      onConnectEnd: (...F) => {
        var W, et;
        return (et = (W = x.getState()).onConnectEnd) == null ? void 0 : et.call(W, ...F);
      },
      onReconnectEnd: k,
      updateConnection: N,
      getTransform: () => x.getState().transform,
      getFromHandle: () => x.getState().connection.fromHandle,
      dragThreshold: x.getState().connectionDragThreshold,
      handleDomNode: M.currentTarget
    });
  }, b = (M) => A(M, { nodeId: e.target, id: e.targetHandle ?? null, type: "target" }), y = (M) => A(M, { nodeId: e.source, id: e.sourceHandle ?? null, type: "source" }), E = () => _(!0), w = () => _(!1);
  return _t.jsxs(_t.Fragment, { children: [(n === !0 || n === "source") && _t.jsx(Z1, { position: u, centerX: s, centerY: a, radius: t, onMouseDown: b, onMouseEnter: E, onMouseOut: w, type: "source" }), (n === !0 || n === "target") && _t.jsx(Z1, { position: d, centerX: o, centerY: c, radius: t, onMouseDown: y, onMouseEnter: E, onMouseOut: w, type: "target" })] });
}
function rF({ id: n, edgesFocusable: t, edgesReconnectable: e, elementsSelectable: s, onClick: a, onDoubleClick: o, onContextMenu: c, onMouseEnter: u, onMouseMove: d, onMouseLeave: h, reconnectRadius: m, onReconnect: p, onReconnectStart: g, onReconnectEnd: _, rfId: x, edgeTypes: A, noPanClassName: b, onError: y, disableKeyboardA11y: E }) {
  let w = Pe((Pt) => Pt.edgeLookup.get(n));
  const M = Pe((Pt) => Pt.defaultEdgeOptions);
  w = M ? { ...M, ...w } : w;
  let O = w.type || "default", C = (A == null ? void 0 : A[O]) || Y1[O];
  C === void 0 && (y == null || y("011", Ds.error011(O)), O = "default", C = (A == null ? void 0 : A.default) || Y1.default);
  const D = !!(w.focusable || t && typeof w.focusable > "u"), T = typeof p < "u" && (w.reconnectable || e && typeof w.reconnectable > "u"), L = !!(w.selectable || s && typeof w.selectable > "u"), z = vt.useRef(null), [R, B] = vt.useState(!1), [H, U] = vt.useState(!1), V = ln(), { zIndex: N, sourceX: I, sourceY: k, targetX: X, targetY: Q, sourcePosition: F, targetPosition: W } = Pe(vt.useCallback((Pt) => {
    const Lt = Pt.nodeLookup.get(w.source), zt = Pt.nodeLookup.get(w.target);
    if (!Lt || !zt)
      return {
        zIndex: w.zIndex,
        ...j1
      };
    const Xt = $B({
      id: n,
      sourceNode: Lt,
      targetNode: zt,
      sourceHandle: w.sourceHandle || null,
      targetHandle: w.targetHandle || null,
      connectionMode: Pt.connectionMode,
      onError: y
    });
    return {
      zIndex: kB({
        selected: w.selected,
        zIndex: w.zIndex,
        sourceNode: Lt,
        targetNode: zt,
        elevateOnSelect: Pt.elevateEdgesOnSelect,
        zIndexMode: Pt.zIndexMode
      }),
      ...Xt || j1
    };
  }, [w.source, w.target, w.sourceHandle, w.targetHandle, w.selected, w.zIndex]), on), et = vt.useMemo(() => w.markerStart ? `url('#${L0(w.markerStart, x)}')` : void 0, [w.markerStart, x]), $ = vt.useMemo(() => w.markerEnd ? `url('#${L0(w.markerEnd, x)}')` : void 0, [w.markerEnd, x]);
  if (w.hidden || I === null || k === null || X === null || Q === null)
    return null;
  const j = (Pt) => {
    var Ft;
    const { addSelectedEdges: Lt, unselectNodesAndEdges: zt, multiSelectionActive: Xt } = V.getState();
    L && (V.setState({ nodesSelectionActive: !1 }), w.selected && Xt ? (zt({ nodes: [], edges: [w] }), (Ft = z.current) == null || Ft.blur()) : Lt([n])), a && a(Pt, w);
  }, Y = o ? (Pt) => {
    o(Pt, { ...w });
  } : void 0, K = c ? (Pt) => {
    c(Pt, { ...w });
  } : void 0, J = u ? (Pt) => {
    u(Pt, { ...w });
  } : void 0, rt = d ? (Pt) => {
    d(Pt, { ...w });
  } : void 0, dt = h ? (Pt) => {
    h(Pt, { ...w });
  } : void 0, yt = (Pt) => {
    var Lt;
    if (!E && DE.includes(Pt.key) && L) {
      const { unselectNodesAndEdges: zt, addSelectedEdges: Xt } = V.getState();
      Pt.key === "Escape" ? ((Lt = z.current) == null || Lt.blur(), zt({ edges: [w] })) : Xt([n]);
    }
  };
  return _t.jsx("svg", { style: { zIndex: N }, children: _t.jsxs("g", { className: Rn([
    "react-flow__edge",
    `react-flow__edge-${O}`,
    w.className,
    b,
    {
      selected: w.selected,
      animated: w.animated,
      inactive: !L && !a,
      updating: R,
      selectable: L
    }
  ]), onClick: j, onDoubleClick: Y, onContextMenu: K, onMouseEnter: J, onMouseMove: rt, onMouseLeave: dt, onKeyDown: D ? yt : void 0, tabIndex: D ? 0 : void 0, role: w.ariaRole ?? (D ? "group" : "img"), "aria-roledescription": "edge", "data-id": n, "data-testid": `rf__edge-${n}`, "aria-label": w.ariaLabel === null ? void 0 : w.ariaLabel || `Edge from ${w.source} to ${w.target}`, "aria-describedby": D ? `${cw}-${x}` : void 0, ref: z, ...w.domAttributes, children: [!H && _t.jsx(C, { id: n, source: w.source, target: w.target, type: w.type, selected: w.selected, animated: w.animated, selectable: L, deletable: w.deletable ?? !0, label: w.label, labelStyle: w.labelStyle, labelShowBg: w.labelShowBg, labelBgStyle: w.labelBgStyle, labelBgPadding: w.labelBgPadding, labelBgBorderRadius: w.labelBgBorderRadius, sourceX: I, sourceY: k, targetX: X, targetY: Q, sourcePosition: F, targetPosition: W, data: w.data, style: w.style, sourceHandleId: w.sourceHandle, targetHandleId: w.targetHandle, markerStart: et, markerEnd: $, pathOptions: "pathOptions" in w ? w.pathOptions : void 0, interactionWidth: w.interactionWidth }), T && _t.jsx(sF, { edge: w, isReconnectable: T, reconnectRadius: m, onReconnect: p, onReconnectStart: g, onReconnectEnd: _, sourceX: I, sourceY: k, targetX: X, targetY: Q, sourcePosition: F, targetPosition: W, setUpdateHover: B, setReconnecting: U })] }) });
}
var aF = vt.memo(rF);
const oF = (n) => ({
  edgesFocusable: n.edgesFocusable,
  edgesReconnectable: n.edgesReconnectable,
  elementsSelectable: n.elementsSelectable,
  connectionMode: n.connectionMode,
  onError: n.onError
});
function Pw({ defaultMarkerColor: n, onlyRenderVisibleElements: t, rfId: e, edgeTypes: s, noPanClassName: a, onReconnect: o, onEdgeContextMenu: c, onEdgeMouseEnter: u, onEdgeMouseMove: d, onEdgeMouseLeave: h, onEdgeClick: m, reconnectRadius: p, onEdgeDoubleClick: g, onReconnectStart: _, onReconnectEnd: x, disableKeyboardA11y: A }) {
  const { edgesFocusable: b, edgesReconnectable: y, elementsSelectable: E, onError: w } = Pe(oF, on), M = W4(t);
  return _t.jsxs("div", { className: "react-flow__edges", children: [_t.jsx($4, { defaultColor: n, rfId: e }), M.map((O) => _t.jsx(aF, { id: O, edgesFocusable: b, edgesReconnectable: y, elementsSelectable: E, noPanClassName: a, onReconnect: o, onContextMenu: c, onMouseEnter: u, onMouseMove: d, onMouseLeave: h, onClick: m, reconnectRadius: p, onDoubleClick: g, onReconnectStart: _, onReconnectEnd: x, rfId: e, onError: w, edgeTypes: s, disableKeyboardA11y: A }, O))] });
}
Pw.displayName = "EdgeRenderer";
const lF = vt.memo(Pw), cF = (n) => `translate(${n.transform[0]}px,${n.transform[1]}px) scale(${n.transform[2]})`;
function uF({ children: n }) {
  const t = Pe(cF);
  return _t.jsx("div", { className: "react-flow__viewport xyflow__viewport react-flow__container", style: { transform: t }, children: n });
}
function fF(n) {
  const t = wv(), e = vt.useRef(!1);
  vt.useEffect(() => {
    !e.current && t.viewportInitialized && n && (setTimeout(() => n(t), 1), e.current = !0);
  }, [n, t.viewportInitialized]);
}
const dF = (n) => {
  var t;
  return (t = n.panZoom) == null ? void 0 : t.syncViewport;
};
function hF(n) {
  const t = Pe(dF), e = ln();
  return vt.useEffect(() => {
    n && (t == null || t(n), e.setState({ transform: [n.x, n.y, n.zoom] }));
  }, [n, t]), null;
}
function pF(n) {
  return n.connection.inProgress ? { ...n.connection, to: lu(n.connection.to, n.transform) } : { ...n.connection };
}
function mF(n) {
  return pF;
}
function gF(n) {
  const t = mF();
  return Pe(t, on);
}
const vF = (n) => ({
  nodesConnectable: n.nodesConnectable,
  isValid: n.connection.isValid,
  inProgress: n.connection.inProgress,
  width: n.width,
  height: n.height
});
function _F({ containerStyle: n, style: t, type: e, component: s }) {
  const { nodesConnectable: a, width: o, height: c, isValid: u, inProgress: d } = Pe(vF, on);
  return !(o && a && d) ? null : _t.jsx("svg", { style: n, width: o, height: c, className: "react-flow__connectionline react-flow__container", children: _t.jsx("g", { className: Rn(["react-flow__connection", LE(u)]), children: _t.jsx(Iw, { style: t, type: e, CustomComponent: s, isValid: u }) }) });
}
const Iw = ({ style: n, type: t = ea.Bezier, CustomComponent: e, isValid: s }) => {
  const { inProgress: a, from: o, fromNode: c, fromHandle: u, fromPosition: d, to: h, toNode: m, toHandle: p, toPosition: g, pointer: _ } = gF();
  if (!a)
    return;
  if (e)
    return _t.jsx(e, { connectionLineType: t, connectionLineStyle: n, fromNode: c, fromHandle: u, fromX: o.x, fromY: o.y, toX: h.x, toY: h.y, fromPosition: d, toPosition: g, connectionStatus: LE(s), toNode: m, toHandle: p, pointer: _ });
  let x = "";
  const A = {
    sourceX: o.x,
    sourceY: o.y,
    sourcePosition: d,
    targetX: h.x,
    targetY: h.y,
    targetPosition: g
  };
  switch (t) {
    case ea.Bezier:
      [x] = WE(A);
      break;
    case ea.SimpleBezier:
      [x] = Mw(A);
      break;
    case ea.Step:
      [x] = O0({
        ...A,
        borderRadius: 0
      });
      break;
    case ea.SmoothStep:
      [x] = O0(A);
      break;
    default:
      [x] = qE(A);
  }
  return _t.jsx("path", { d: x, fill: "none", className: "react-flow__connection-path", style: n });
};
Iw.displayName = "ConnectionLine";
const yF = {};
function $1(n = yF) {
  vt.useRef(n), ln(), vt.useEffect(() => {
  }, [n]);
}
function xF() {
  ln(), vt.useRef(!1), vt.useEffect(() => {
  }, []);
}
function Bw({ nodeTypes: n, edgeTypes: t, onInit: e, onNodeClick: s, onEdgeClick: a, onNodeDoubleClick: o, onEdgeDoubleClick: c, onNodeMouseEnter: u, onNodeMouseMove: d, onNodeMouseLeave: h, onNodeContextMenu: m, onSelectionContextMenu: p, onSelectionStart: g, onSelectionEnd: _, connectionLineType: x, connectionLineStyle: A, connectionLineComponent: b, connectionLineContainerStyle: y, selectionKeyCode: E, selectionOnDrag: w, selectionMode: M, multiSelectionKeyCode: O, panActivationKeyCode: C, zoomActivationKeyCode: D, deleteKeyCode: T, onlyRenderVisibleElements: L, elementsSelectable: z, defaultViewport: R, translateExtent: B, minZoom: H, maxZoom: U, preventScrolling: V, defaultMarkerColor: N, zoomOnScroll: I, zoomOnPinch: k, panOnScroll: X, panOnScrollSpeed: Q, panOnScrollMode: F, zoomOnDoubleClick: W, panOnDrag: et, onPaneClick: $, onPaneMouseEnter: j, onPaneMouseMove: Y, onPaneMouseLeave: K, onPaneScroll: J, onPaneContextMenu: rt, paneClickDistance: dt, nodeClickDistance: yt, onEdgeContextMenu: Pt, onEdgeMouseEnter: Lt, onEdgeMouseMove: zt, onEdgeMouseLeave: Xt, reconnectRadius: Ft, onReconnect: ve, onReconnectStart: it, onReconnectEnd: Ue, noDragClassName: xe, noWheelClassName: Re, noPanClassName: Kt, disableKeyboardA11y: tt, nodeExtent: G, rfId: ct, viewport: Et, onViewportChange: Rt }) {
  return $1(n), $1(t), xF(), fF(e), hF(Et), _t.jsx(P4, { onPaneClick: $, onPaneMouseEnter: j, onPaneMouseMove: Y, onPaneMouseLeave: K, onPaneContextMenu: rt, onPaneScroll: J, paneClickDistance: dt, deleteKeyCode: T, selectionKeyCode: E, selectionOnDrag: w, selectionMode: M, onSelectionStart: g, onSelectionEnd: _, multiSelectionKeyCode: O, panActivationKeyCode: C, zoomActivationKeyCode: D, elementsSelectable: z, zoomOnScroll: I, zoomOnPinch: k, zoomOnDoubleClick: W, panOnScroll: X, panOnScrollSpeed: Q, panOnScrollMode: F, panOnDrag: et, defaultViewport: R, translateExtent: B, minZoom: H, maxZoom: U, onSelectionContextMenu: p, preventScrolling: V, noDragClassName: xe, noWheelClassName: Re, noPanClassName: Kt, disableKeyboardA11y: tt, onViewportChange: Rt, isControlledViewport: !!Et, children: _t.jsxs(uF, { children: [_t.jsx(lF, { edgeTypes: t, onEdgeClick: a, onEdgeDoubleClick: c, onReconnect: ve, onReconnectStart: it, onReconnectEnd: Ue, onlyRenderVisibleElements: L, onEdgeContextMenu: Pt, onEdgeMouseEnter: Lt, onEdgeMouseMove: zt, onEdgeMouseLeave: Xt, reconnectRadius: Ft, defaultMarkerColor: N, noPanClassName: Kt, disableKeyboardA11y: tt, rfId: ct }), _t.jsx(_F, { style: A, type: x, component: b, containerStyle: y }), _t.jsx("div", { className: "react-flow__edgelabel-renderer" }), _t.jsx(X4, { nodeTypes: n, onNodeClick: s, onNodeDoubleClick: o, onNodeMouseEnter: u, onNodeMouseMove: d, onNodeMouseLeave: h, onNodeContextMenu: m, nodeClickDistance: yt, onlyRenderVisibleElements: L, noPanClassName: Kt, noDragClassName: xe, disableKeyboardA11y: tt, nodeExtent: G, rfId: ct }), _t.jsx("div", { className: "react-flow__viewport-portal" })] }) });
}
Bw.displayName = "GraphView";
const SF = vt.memo(Bw), K1 = ({ nodes: n, edges: t, defaultNodes: e, defaultEdges: s, width: a, height: o, fitView: c, fitViewOptions: u, minZoom: d = 0.5, maxZoom: h = 2, nodeOrigin: m, nodeExtent: p, zIndexMode: g = "basic" } = {}) => {
  const _ = /* @__PURE__ */ new Map(), x = /* @__PURE__ */ new Map(), A = /* @__PURE__ */ new Map(), b = /* @__PURE__ */ new Map(), y = s ?? t ?? [], E = e ?? n ?? [], w = m ?? [0, 0], M = p ?? $c;
  KE(A, b, y);
  const O = U0(E, _, x, {
    nodeOrigin: w,
    nodeExtent: M,
    zIndexMode: g
  });
  let C = [0, 0, 1];
  if (c && a && o) {
    const D = au(_, {
      filter: (R) => !!((R.width || R.initialWidth) && (R.height || R.initialHeight))
    }), { x: T, y: L, zoom: z } = _v(D, a, o, d, h, (u == null ? void 0 : u.padding) ?? 0.1);
    C = [T, L, z];
  }
  return {
    rfId: "1",
    width: a ?? 0,
    height: o ?? 0,
    transform: C,
    nodes: E,
    nodesInitialized: O,
    nodeLookup: _,
    parentLookup: x,
    edges: y,
    edgeLookup: b,
    connectionLookup: A,
    onNodesChange: null,
    onEdgesChange: null,
    hasDefaultNodes: e !== void 0,
    hasDefaultEdges: s !== void 0,
    panZoom: null,
    minZoom: d,
    maxZoom: h,
    translateExtent: $c,
    nodeExtent: M,
    nodesSelectionActive: !1,
    userSelectionActive: !1,
    userSelectionRect: null,
    connectionMode: _l.Strict,
    domNode: null,
    paneDragging: !1,
    noPanClassName: "nopan",
    nodeOrigin: w,
    nodeDragThreshold: 1,
    connectionDragThreshold: 1,
    snapGrid: [15, 15],
    snapToGrid: !1,
    nodesDraggable: !0,
    nodesConnectable: !0,
    nodesFocusable: !0,
    edgesFocusable: !0,
    edgesReconnectable: !0,
    elementsSelectable: !0,
    elevateNodesOnSelect: !0,
    elevateEdgesOnSelect: !0,
    selectNodesOnDrag: !0,
    multiSelectionActive: !1,
    fitViewQueued: c ?? !1,
    fitViewOptions: u,
    fitViewResolver: null,
    connection: { ...OE },
    connectionClickStartHandle: null,
    connectOnClick: !0,
    ariaLiveMessage: "",
    autoPanOnConnect: !0,
    autoPanOnNodeDrag: !0,
    autoPanOnNodeFocus: !0,
    autoPanSpeed: 15,
    connectionRadius: 20,
    onError: BB,
    isValidConnection: void 0,
    onSelectionChangeHandlers: [],
    lib: "react",
    debug: !1,
    ariaLabelConfig: NE,
    zIndexMode: g,
    onNodesChangeMiddlewareMap: /* @__PURE__ */ new Map(),
    onEdgesChangeMiddlewareMap: /* @__PURE__ */ new Map()
  };
}, bF = ({ nodes: n, edges: t, defaultNodes: e, defaultEdges: s, width: a, height: o, fitView: c, fitViewOptions: u, minZoom: d, maxZoom: h, nodeOrigin: m, nodeExtent: p, zIndexMode: g }) => Hz((_, x) => {
  async function A() {
    const { nodeLookup: b, panZoom: y, fitViewOptions: E, fitViewResolver: w, width: M, height: O, minZoom: C, maxZoom: D } = x();
    y && (await PB({
      nodes: b,
      width: M,
      height: O,
      panZoom: y,
      minZoom: C,
      maxZoom: D
    }, E), w == null || w.resolve(!0), _({ fitViewResolver: null }));
  }
  return {
    ...K1({
      nodes: n,
      edges: t,
      width: a,
      height: o,
      fitView: c,
      fitViewOptions: u,
      minZoom: d,
      maxZoom: h,
      nodeOrigin: m,
      nodeExtent: p,
      defaultNodes: e,
      defaultEdges: s,
      zIndexMode: g
    }),
    setNodes: (b) => {
      const { nodeLookup: y, parentLookup: E, nodeOrigin: w, elevateNodesOnSelect: M, fitViewQueued: O, zIndexMode: C } = x(), D = U0(b, y, E, {
        nodeOrigin: w,
        nodeExtent: p,
        elevateNodesOnSelect: M,
        checkEquality: !0,
        zIndexMode: C
      });
      O && D ? (A(), _({ nodes: b, nodesInitialized: D, fitViewQueued: !1, fitViewOptions: void 0 })) : _({ nodes: b, nodesInitialized: D });
    },
    setEdges: (b) => {
      const { connectionLookup: y, edgeLookup: E } = x();
      KE(y, E, b), _({ edges: b });
    },
    setDefaultNodesAndEdges: (b, y) => {
      if (b) {
        const { setNodes: E } = x();
        E(b), _({ hasDefaultNodes: !0 });
      }
      if (y) {
        const { setEdges: E } = x();
        E(y), _({ hasDefaultEdges: !0 });
      }
    },
    /*
     * Every node gets registerd at a ResizeObserver. Whenever a node
     * changes its dimensions, this function is called to measure the
     * new dimensions and update the nodes.
     */
    updateNodeInternals: (b) => {
      const { triggerNodeChanges: y, nodeLookup: E, parentLookup: w, domNode: M, nodeOrigin: O, nodeExtent: C, debug: D, fitViewQueued: T, zIndexMode: L } = x(), { changes: z, updatedInternals: R } = sz(b, E, w, M, O, C, L);
      R && (tz(E, w, { nodeOrigin: O, nodeExtent: C, zIndexMode: L }), T ? (A(), _({ fitViewQueued: !1, fitViewOptions: void 0 })) : _({}), (z == null ? void 0 : z.length) > 0 && (D && console.log("React Flow: trigger node changes", z), y == null || y(z)));
    },
    updateNodePositions: (b, y = !1) => {
      const E = [];
      let w = [];
      const { nodeLookup: M, triggerNodeChanges: O, connection: C, updateConnection: D, onNodesChangeMiddlewareMap: T } = x();
      for (const [L, z] of b) {
        const R = M.get(L), B = !!(R != null && R.expandParent && (R != null && R.parentId) && (z != null && z.position)), H = {
          id: L,
          type: "position",
          position: B ? {
            x: Math.max(0, z.position.x),
            y: Math.max(0, z.position.y)
          } : z.position,
          dragging: y
        };
        if (R && C.inProgress && C.fromNode.id === R.id) {
          const U = ja(R, C.fromHandle, oe.Left, !0);
          D({ ...C, from: U });
        }
        B && R.parentId && E.push({
          id: L,
          parentId: R.parentId,
          rect: {
            ...z.internals.positionAbsolute,
            width: z.measured.width ?? 0,
            height: z.measured.height ?? 0
          }
        }), w.push(H);
      }
      if (E.length > 0) {
        const { parentLookup: L, nodeOrigin: z } = x(), R = Ev(E, M, L, z);
        w.push(...R);
      }
      for (const L of T.values())
        w = L(w);
      O(w);
    },
    triggerNodeChanges: (b) => {
      const { onNodesChange: y, setNodes: E, nodes: w, hasDefaultNodes: M, debug: O } = x();
      if (b != null && b.length) {
        if (M) {
          const C = dw(b, w);
          E(C);
        }
        O && console.log("React Flow: trigger node changes", b), y == null || y(b);
      }
    },
    triggerEdgeChanges: (b) => {
      const { onEdgesChange: y, setEdges: E, edges: w, hasDefaultEdges: M, debug: O } = x();
      if (b != null && b.length) {
        if (M) {
          const C = hw(b, w);
          E(C);
        }
        O && console.log("React Flow: trigger edge changes", b), y == null || y(b);
      }
    },
    addSelectedNodes: (b) => {
      const { multiSelectionActive: y, edgeLookup: E, nodeLookup: w, triggerNodeChanges: M, triggerEdgeChanges: O } = x();
      if (y) {
        const C = b.map((D) => La(D, !0));
        M(C);
        return;
      }
      M(rl(w, /* @__PURE__ */ new Set([...b]), !0)), O(rl(E));
    },
    addSelectedEdges: (b) => {
      const { multiSelectionActive: y, edgeLookup: E, nodeLookup: w, triggerNodeChanges: M, triggerEdgeChanges: O } = x();
      if (y) {
        const C = b.map((D) => La(D, !0));
        O(C);
        return;
      }
      O(rl(E, /* @__PURE__ */ new Set([...b]))), M(rl(w, /* @__PURE__ */ new Set(), !0));
    },
    unselectNodesAndEdges: ({ nodes: b, edges: y } = {}) => {
      const { edges: E, nodes: w, nodeLookup: M, triggerNodeChanges: O, triggerEdgeChanges: C } = x(), D = b || w, T = y || E, L = [];
      for (const R of D) {
        if (!R.selected)
          continue;
        const B = M.get(R.id);
        B && (B.selected = !1), L.push(La(R.id, !1));
      }
      const z = [];
      for (const R of T)
        R.selected && z.push(La(R.id, !1));
      O(L), C(z);
    },
    setMinZoom: (b) => {
      const { panZoom: y, maxZoom: E } = x();
      y == null || y.setScaleExtent([b, E]), _({ minZoom: b });
    },
    setMaxZoom: (b) => {
      const { panZoom: y, minZoom: E } = x();
      y == null || y.setScaleExtent([E, b]), _({ maxZoom: b });
    },
    setTranslateExtent: (b) => {
      var y;
      (y = x().panZoom) == null || y.setTranslateExtent(b), _({ translateExtent: b });
    },
    resetSelectedElements: () => {
      const { edges: b, nodes: y, triggerNodeChanges: E, triggerEdgeChanges: w, elementsSelectable: M } = x();
      if (!M)
        return;
      const O = y.reduce((D, T) => T.selected ? [...D, La(T.id, !1)] : D, []), C = b.reduce((D, T) => T.selected ? [...D, La(T.id, !1)] : D, []);
      E(O), w(C);
    },
    setNodeExtent: (b) => {
      const { nodes: y, nodeLookup: E, parentLookup: w, nodeOrigin: M, elevateNodesOnSelect: O, nodeExtent: C, zIndexMode: D } = x();
      b[0][0] === C[0][0] && b[0][1] === C[0][1] && b[1][0] === C[1][0] && b[1][1] === C[1][1] || (U0(y, E, w, {
        nodeOrigin: M,
        nodeExtent: b,
        elevateNodesOnSelect: O,
        checkEquality: !1,
        zIndexMode: D
      }), _({ nodeExtent: b }));
    },
    panBy: (b) => {
      const { transform: y, width: E, height: w, panZoom: M, translateExtent: O } = x();
      return rz({ delta: b, panZoom: M, transform: y, translateExtent: O, width: E, height: w });
    },
    setCenter: async (b, y, E) => {
      const { width: w, height: M, maxZoom: O, panZoom: C } = x();
      if (!C)
        return Promise.resolve(!1);
      const D = typeof (E == null ? void 0 : E.zoom) < "u" ? E.zoom : O;
      return await C.setViewport({
        x: w / 2 - b * D,
        y: M / 2 - y * D,
        zoom: D
      }, { duration: E == null ? void 0 : E.duration, ease: E == null ? void 0 : E.ease, interpolate: E == null ? void 0 : E.interpolate }), Promise.resolve(!0);
    },
    cancelConnection: () => {
      _({
        connection: { ...OE }
      });
    },
    updateConnection: (b) => {
      _({ connection: b });
    },
    reset: () => _({ ...K1() })
  };
}, Object.is);
function MF({ initialNodes: n, initialEdges: t, defaultNodes: e, defaultEdges: s, initialWidth: a, initialHeight: o, initialMinZoom: c, initialMaxZoom: u, initialFitViewOptions: d, fitView: h, nodeOrigin: m, nodeExtent: p, zIndexMode: g, children: _ }) {
  const [x] = vt.useState(() => bF({
    nodes: n,
    edges: t,
    defaultNodes: e,
    defaultEdges: s,
    width: a,
    height: o,
    fitView: h,
    minZoom: c,
    maxZoom: u,
    fitViewOptions: d,
    nodeOrigin: m,
    nodeExtent: p,
    zIndexMode: g
  }));
  return _t.jsx(Vz, { value: x, children: _t.jsx(u4, { children: _ }) });
}
function EF({ children: n, nodes: t, edges: e, defaultNodes: s, defaultEdges: a, width: o, height: c, fitView: u, fitViewOptions: d, minZoom: h, maxZoom: m, nodeOrigin: p, nodeExtent: g, zIndexMode: _ }) {
  return vt.useContext(oh) ? _t.jsx(_t.Fragment, { children: n }) : _t.jsx(MF, { initialNodes: t, initialEdges: e, defaultNodes: s, defaultEdges: a, initialWidth: o, initialHeight: c, fitView: u, initialFitViewOptions: d, initialMinZoom: h, initialMaxZoom: m, nodeOrigin: p, nodeExtent: g, zIndexMode: _, children: n });
}
const wF = {
  width: "100%",
  height: "100%",
  overflow: "hidden",
  position: "relative",
  zIndex: 0
};
function AF({ nodes: n, edges: t, defaultNodes: e, defaultEdges: s, className: a, nodeTypes: o, edgeTypes: c, onNodeClick: u, onEdgeClick: d, onInit: h, onMove: m, onMoveStart: p, onMoveEnd: g, onConnect: _, onConnectStart: x, onConnectEnd: A, onClickConnectStart: b, onClickConnectEnd: y, onNodeMouseEnter: E, onNodeMouseMove: w, onNodeMouseLeave: M, onNodeContextMenu: O, onNodeDoubleClick: C, onNodeDragStart: D, onNodeDrag: T, onNodeDragStop: L, onNodesDelete: z, onEdgesDelete: R, onDelete: B, onSelectionChange: H, onSelectionDragStart: U, onSelectionDrag: V, onSelectionDragStop: N, onSelectionContextMenu: I, onSelectionStart: k, onSelectionEnd: X, onBeforeDelete: Q, connectionMode: F, connectionLineType: W = ea.Bezier, connectionLineStyle: et, connectionLineComponent: $, connectionLineContainerStyle: j, deleteKeyCode: Y = "Backspace", selectionKeyCode: K = "Shift", selectionOnDrag: J = !1, selectionMode: rt = Kc.Full, panActivationKeyCode: dt = "Space", multiSelectionKeyCode: yt = Jc() ? "Meta" : "Control", zoomActivationKeyCode: Pt = Jc() ? "Meta" : "Control", snapToGrid: Lt, snapGrid: zt, onlyRenderVisibleElements: Xt = !1, selectNodesOnDrag: Ft, nodesDraggable: ve, autoPanOnNodeFocus: it, nodesConnectable: Ue, nodesFocusable: xe, nodeOrigin: Re = uw, edgesFocusable: Kt, edgesReconnectable: tt, elementsSelectable: G = !0, defaultViewport: ct = t4, minZoom: Et = 0.5, maxZoom: Rt = 2, translateExtent: Mt = $c, preventScrolling: Jt = !0, nodeExtent: It, defaultMarkerColor: se = "#b1b1b7", zoomOnScroll: le = !0, zoomOnPinch: Ot = !0, panOnScroll: Dt = !1, panOnScrollSpeed: Wt = 0.5, panOnScrollMode: kt = Ga.Free, zoomOnDoubleClick: Yt = !0, panOnDrag: _e = !0, onPaneClick: lt, onPaneMouseEnter: Bt, onPaneMouseMove: Ut, onPaneMouseLeave: jt, onPaneScroll: Nt, onPaneContextMenu: bt, paneClickDistance: Zt = 1, nodeClickDistance: fe = 0, children: He, onReconnect: Oe, onReconnectStart: Fn, onReconnectEnd: mi, onEdgeContextMenu: oa, onEdgeDoubleClick: vr, onEdgeMouseEnter: $a, onEdgeMouseMove: _r, onEdgeMouseLeave: yr, reconnectRadius: Li = 10, onNodesChange: xr, onEdgesChange: gi, noDragClassName: cn = "nodrag", noWheelClassName: hn = "nowheel", noPanClassName: Ui = "nopan", fitView: Yi, fitViewOptions: la, connectOnClick: Ka, attributionPosition: Qa, proOptions: Ls, defaultEdgeOptions: ca, elevateNodesOnSelect: cs = !0, elevateEdgesOnSelect: us = !1, disableKeyboardA11y: fs = !1, autoPanOnConnect: Z, autoPanOnNodeDrag: ot, autoPanSpeed: xt, connectionRadius: mt, isValidConnection: ft, onError: Ht, style: qt, id: Vt, nodeDragThreshold: te, connectionDragThreshold: ne, viewport: ue, onViewportChange: pe, width: $t, height: ye, colorMode: en = "light", debug: nn, onScroll: Ae, ariaLabelConfig: pn, zIndexMode: Qt = "basic", ...Hn }, he) {
  const Dn = Vt || "1", ti = s4(en), vi = vt.useCallback((qn) => {
    qn.currentTarget.scrollTo({ top: 0, left: 0, behavior: "instant" }), Ae == null || Ae(qn);
  }, [Ae]);
  return _t.jsx("div", { "data-testid": "rf__wrapper", ...Hn, onScroll: vi, style: { ...qt, ...wF }, ref: he, className: Rn(["react-flow", a, ti]), id: Vt, role: "application", children: _t.jsxs(EF, { nodes: n, edges: t, width: $t, height: ye, fitView: Yi, fitViewOptions: la, minZoom: Et, maxZoom: Rt, nodeOrigin: Re, nodeExtent: It, zIndexMode: Qt, children: [_t.jsx(SF, { onInit: h, onNodeClick: u, onEdgeClick: d, onNodeMouseEnter: E, onNodeMouseMove: w, onNodeMouseLeave: M, onNodeContextMenu: O, onNodeDoubleClick: C, nodeTypes: o, edgeTypes: c, connectionLineType: W, connectionLineStyle: et, connectionLineComponent: $, connectionLineContainerStyle: j, selectionKeyCode: K, selectionOnDrag: J, selectionMode: rt, deleteKeyCode: Y, multiSelectionKeyCode: yt, panActivationKeyCode: dt, zoomActivationKeyCode: Pt, onlyRenderVisibleElements: Xt, defaultViewport: ct, translateExtent: Mt, minZoom: Et, maxZoom: Rt, preventScrolling: Jt, zoomOnScroll: le, zoomOnPinch: Ot, zoomOnDoubleClick: Yt, panOnScroll: Dt, panOnScrollSpeed: Wt, panOnScrollMode: kt, panOnDrag: _e, onPaneClick: lt, onPaneMouseEnter: Bt, onPaneMouseMove: Ut, onPaneMouseLeave: jt, onPaneScroll: Nt, onPaneContextMenu: bt, paneClickDistance: Zt, nodeClickDistance: fe, onSelectionContextMenu: I, onSelectionStart: k, onSelectionEnd: X, onReconnect: Oe, onReconnectStart: Fn, onReconnectEnd: mi, onEdgeContextMenu: oa, onEdgeDoubleClick: vr, onEdgeMouseEnter: $a, onEdgeMouseMove: _r, onEdgeMouseLeave: yr, reconnectRadius: Li, defaultMarkerColor: se, noDragClassName: cn, noWheelClassName: hn, noPanClassName: Ui, rfId: Dn, disableKeyboardA11y: fs, nodeExtent: It, viewport: ue, onViewportChange: pe }), _t.jsx(i4, { nodes: n, edges: t, defaultNodes: e, defaultEdges: s, onConnect: _, onConnectStart: x, onConnectEnd: A, onClickConnectStart: b, onClickConnectEnd: y, nodesDraggable: ve, autoPanOnNodeFocus: it, nodesConnectable: Ue, nodesFocusable: xe, edgesFocusable: Kt, edgesReconnectable: tt, elementsSelectable: G, elevateNodesOnSelect: cs, elevateEdgesOnSelect: us, minZoom: Et, maxZoom: Rt, nodeExtent: It, onNodesChange: xr, onEdgesChange: gi, snapToGrid: Lt, snapGrid: zt, connectionMode: F, translateExtent: Mt, connectOnClick: Ka, defaultEdgeOptions: ca, fitView: Yi, fitViewOptions: la, onNodesDelete: z, onEdgesDelete: R, onDelete: B, onNodeDragStart: D, onNodeDrag: T, onNodeDragStop: L, onSelectionDrag: V, onSelectionDragStart: U, onSelectionDragStop: N, onMove: m, onMoveStart: p, onMoveEnd: g, noPanClassName: Ui, nodeOrigin: Re, rfId: Dn, autoPanOnConnect: Z, autoPanOnNodeDrag: ot, autoPanSpeed: xt, onError: Ht, connectionRadius: mt, isValidConnection: ft, selectNodesOnDrag: Ft, nodeDragThreshold: te, connectionDragThreshold: ne, onBeforeDelete: Q, debug: nn, ariaLabelConfig: pn, zIndexMode: Qt }), _t.jsx(Jz, { onSelectionChange: H }), He, _t.jsx(qz, { proOptions: Ls, position: Qa }), _t.jsx(jz, { rfId: Dn, disableKeyboardA11y: fs })] }) });
}
pw(AF);
function TF({ dimensions: n, lineWidth: t, variant: e, className: s }) {
  return _t.jsx("path", { strokeWidth: t, d: `M${n[0] / 2} 0 V${n[1]} M0 ${n[1] / 2} H${n[0]}`, className: Rn(["react-flow__background-pattern", e, s]) });
}
function CF({ radius: n, className: t }) {
  return _t.jsx("circle", { cx: n, cy: n, r: n, className: Rn(["react-flow__background-pattern", "dots", t]) });
}
var sa;
(function(n) {
  n.Lines = "lines", n.Dots = "dots", n.Cross = "cross";
})(sa || (sa = {}));
const RF = {
  [sa.Dots]: 1,
  [sa.Lines]: 1,
  [sa.Cross]: 6
}, DF = (n) => ({ transform: n.transform, patternId: `pattern-${n.rfId}` });
function zw({
  id: n,
  variant: t = sa.Dots,
  // only used for dots and cross
  gap: e = 20,
  // only used for lines and cross
  size: s,
  lineWidth: a = 1,
  offset: o = 0,
  color: c,
  bgColor: u,
  style: d,
  className: h,
  patternClassName: m
}) {
  const p = vt.useRef(null), { transform: g, patternId: _ } = Pe(DF, on), x = s || RF[t], A = t === sa.Dots, b = t === sa.Cross, y = Array.isArray(e) ? e : [e, e], E = [y[0] * g[2] || 1, y[1] * g[2] || 1], w = x * g[2], M = Array.isArray(o) ? o : [o, o], O = b ? [w, w] : E, C = [
    M[0] * g[2] || 1 + O[0] / 2,
    M[1] * g[2] || 1 + O[1] / 2
  ], D = `${_}${n || ""}`;
  return _t.jsxs("svg", { className: Rn(["react-flow__background", h]), style: {
    ...d,
    ...ch,
    "--xy-background-color-props": u,
    "--xy-background-pattern-color-props": c
  }, ref: p, "data-testid": "rf__background", children: [_t.jsx("pattern", { id: D, x: g[0] % E[0], y: g[1] % E[1], width: E[0], height: E[1], patternUnits: "userSpaceOnUse", patternTransform: `translate(-${C[0]},-${C[1]})`, children: A ? _t.jsx(CF, { radius: w / 2, className: m }) : _t.jsx(TF, { dimensions: O, lineWidth: a, variant: t, className: m }) }), _t.jsx("rect", { x: "0", y: "0", width: "100%", height: "100%", fill: `url(#${D})` })] });
}
zw.displayName = "Background";
vt.memo(zw);
function NF() {
  return _t.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 32 32", children: _t.jsx("path", { d: "M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z" }) });
}
function OF() {
  return _t.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 32 5", children: _t.jsx("path", { d: "M0 0h32v4.2H0z" }) });
}
function LF() {
  return _t.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 32 30", children: _t.jsx("path", { d: "M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z" }) });
}
function UF() {
  return _t.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 25 32", children: _t.jsx("path", { d: "M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z" }) });
}
function PF() {
  return _t.jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 25 32", children: _t.jsx("path", { d: "M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z" }) });
}
function cd({ children: n, className: t, ...e }) {
  return _t.jsx("button", { type: "button", className: Rn(["react-flow__controls-button", t]), ...e, children: n });
}
const IF = (n) => ({
  isInteractive: n.nodesDraggable || n.nodesConnectable || n.elementsSelectable,
  minZoomReached: n.transform[2] <= n.minZoom,
  maxZoomReached: n.transform[2] >= n.maxZoom,
  ariaLabelConfig: n.ariaLabelConfig
});
function Fw({ style: n, showZoom: t = !0, showFitView: e = !0, showInteractive: s = !0, fitViewOptions: a, onZoomIn: o, onZoomOut: c, onFitView: u, onInteractiveChange: d, className: h, children: m, position: p = "bottom-left", orientation: g = "vertical", "aria-label": _ }) {
  const x = ln(), { isInteractive: A, minZoomReached: b, maxZoomReached: y, ariaLabelConfig: E } = Pe(IF, on), { zoomIn: w, zoomOut: M, fitView: O } = wv(), C = () => {
    w(), o == null || o();
  }, D = () => {
    M(), c == null || c();
  }, T = () => {
    O(a), u == null || u();
  }, L = () => {
    x.setState({
      nodesDraggable: !A,
      nodesConnectable: !A,
      elementsSelectable: !A
    }), d == null || d(!A);
  }, z = g === "horizontal" ? "horizontal" : "vertical";
  return _t.jsxs(lh, { className: Rn(["react-flow__controls", z, h]), position: p, style: n, "data-testid": "rf__controls", "aria-label": _ ?? E["controls.ariaLabel"], children: [t && _t.jsxs(_t.Fragment, { children: [_t.jsx(cd, { onClick: C, className: "react-flow__controls-zoomin", title: E["controls.zoomIn.ariaLabel"], "aria-label": E["controls.zoomIn.ariaLabel"], disabled: y, children: _t.jsx(NF, {}) }), _t.jsx(cd, { onClick: D, className: "react-flow__controls-zoomout", title: E["controls.zoomOut.ariaLabel"], "aria-label": E["controls.zoomOut.ariaLabel"], disabled: b, children: _t.jsx(OF, {}) })] }), e && _t.jsx(cd, { className: "react-flow__controls-fitview", onClick: T, title: E["controls.fitView.ariaLabel"], "aria-label": E["controls.fitView.ariaLabel"], children: _t.jsx(LF, {}) }), s && _t.jsx(cd, { className: "react-flow__controls-interactive", onClick: L, title: E["controls.interactive.ariaLabel"], "aria-label": E["controls.interactive.ariaLabel"], children: A ? _t.jsx(PF, {}) : _t.jsx(UF, {}) }), m] });
}
Fw.displayName = "Controls";
vt.memo(Fw);
function BF({ id: n, x: t, y: e, width: s, height: a, style: o, color: c, strokeColor: u, strokeWidth: d, className: h, borderRadius: m, shapeRendering: p, selected: g, onClick: _ }) {
  const { background: x, backgroundColor: A } = o || {}, b = c || x || A;
  return _t.jsx("rect", { className: Rn(["react-flow__minimap-node", { selected: g }, h]), x: t, y: e, rx: m, ry: m, width: s, height: a, style: {
    fill: b,
    stroke: u,
    strokeWidth: d
  }, shapeRendering: p, onClick: _ ? (y) => _(y, n) : void 0 });
}
const zF = vt.memo(BF), FF = (n) => n.nodes.map((t) => t.id), bg = (n) => n instanceof Function ? n : () => n;
function HF({
  nodeStrokeColor: n,
  nodeColor: t,
  nodeClassName: e = "",
  nodeBorderRadius: s = 5,
  nodeStrokeWidth: a,
  /*
   * We need to rename the prop to be `CapitalCase` so that JSX will render it as
   * a component properly.
   */
  nodeComponent: o = zF,
  onClick: c
}) {
  const u = Pe(FF, on), d = bg(t), h = bg(n), m = bg(e), p = typeof window > "u" || window.chrome ? "crispEdges" : "geometricPrecision";
  return _t.jsx(_t.Fragment, { children: u.map((g) => (
    /*
     * The split of responsibilities between MiniMapNodes and
     * NodeComponentWrapper may appear weird. However, it’s designed to
     * minimize the cost of updates when individual nodes change.
     *
     * For more details, see a similar commit in `NodeRenderer/index.tsx`.
     */
    _t.jsx(GF, { id: g, nodeColorFunc: d, nodeStrokeColorFunc: h, nodeClassNameFunc: m, nodeBorderRadius: s, nodeStrokeWidth: a, NodeComponent: o, onClick: c, shapeRendering: p }, g)
  )) });
}
function VF({ id: n, nodeColorFunc: t, nodeStrokeColorFunc: e, nodeClassNameFunc: s, nodeBorderRadius: a, nodeStrokeWidth: o, shapeRendering: c, NodeComponent: u, onClick: d }) {
  const { node: h, x: m, y: p, width: g, height: _ } = Pe((x) => {
    const A = x.nodeLookup.get(n);
    if (!A)
      return { node: void 0, x: 0, y: 0, width: 0, height: 0 };
    const b = A.internals.userNode, { x: y, y: E } = A.internals.positionAbsolute, { width: w, height: M } = gr(b);
    return {
      node: b,
      x: y,
      y: E,
      width: w,
      height: M
    };
  }, on);
  return !h || h.hidden || !FE(h) ? null : _t.jsx(u, { x: m, y: p, width: g, height: _, style: h.style, selected: !!h.selected, className: s(h), color: t(h), borderRadius: a, strokeColor: e(h), strokeWidth: o, shapeRendering: c, onClick: d, id: h.id });
}
const GF = vt.memo(VF);
var kF = vt.memo(HF);
const XF = 200, WF = 150, YF = (n) => !n.hidden, jF = (n) => {
  const t = {
    x: -n.transform[0] / n.transform[2],
    y: -n.transform[1] / n.transform[2],
    width: n.width / n.transform[2],
    height: n.height / n.transform[2]
  };
  return {
    viewBB: t,
    boundingRect: n.nodeLookup.size > 0 ? zE(au(n.nodeLookup, { filter: YF }), t) : t,
    rfId: n.rfId,
    panZoom: n.panZoom,
    translateExtent: n.translateExtent,
    flowWidth: n.width,
    flowHeight: n.height,
    ariaLabelConfig: n.ariaLabelConfig
  };
}, qF = "react-flow__minimap-desc";
function Hw({
  style: n,
  className: t,
  nodeStrokeColor: e,
  nodeColor: s,
  nodeClassName: a = "",
  nodeBorderRadius: o = 5,
  nodeStrokeWidth: c,
  /*
   * We need to rename the prop to be `CapitalCase` so that JSX will render it as
   * a component properly.
   */
  nodeComponent: u,
  bgColor: d,
  maskColor: h,
  maskStrokeColor: m,
  maskStrokeWidth: p,
  position: g = "bottom-right",
  onClick: _,
  onNodeClick: x,
  pannable: A = !1,
  zoomable: b = !1,
  ariaLabel: y,
  inversePan: E,
  zoomStep: w = 1,
  offsetScale: M = 5
}) {
  const O = ln(), C = vt.useRef(null), { boundingRect: D, viewBB: T, rfId: L, panZoom: z, translateExtent: R, flowWidth: B, flowHeight: H, ariaLabelConfig: U } = Pe(jF, on), V = (n == null ? void 0 : n.width) ?? XF, N = (n == null ? void 0 : n.height) ?? WF, I = D.width / V, k = D.height / N, X = Math.max(I, k), Q = X * V, F = X * N, W = M * X, et = D.x - (Q - D.width) / 2 - W, $ = D.y - (F - D.height) / 2 - W, j = Q + W * 2, Y = F + W * 2, K = `${qF}-${L}`, J = vt.useRef(0), rt = vt.useRef();
  J.current = X, vt.useEffect(() => {
    if (C.current && z)
      return rt.current = pz({
        domNode: C.current,
        panZoom: z,
        getTransform: () => O.getState().transform,
        getViewScale: () => J.current
      }), () => {
        var Lt;
        (Lt = rt.current) == null || Lt.destroy();
      };
  }, [z]), vt.useEffect(() => {
    var Lt;
    (Lt = rt.current) == null || Lt.update({
      translateExtent: R,
      width: B,
      height: H,
      inversePan: E,
      pannable: A,
      zoomStep: w,
      zoomable: b
    });
  }, [A, b, E, w, R, B, H]);
  const dt = _ ? (Lt) => {
    var Ft;
    const [zt, Xt] = ((Ft = rt.current) == null ? void 0 : Ft.pointer(Lt)) || [0, 0];
    _(Lt, { x: zt, y: Xt });
  } : void 0, yt = x ? vt.useCallback((Lt, zt) => {
    const Xt = O.getState().nodeLookup.get(zt).internals.userNode;
    x(Lt, Xt);
  }, []) : void 0, Pt = y ?? U["minimap.ariaLabel"];
  return _t.jsx(lh, { position: g, style: {
    ...n,
    "--xy-minimap-background-color-props": typeof d == "string" ? d : void 0,
    "--xy-minimap-mask-background-color-props": typeof h == "string" ? h : void 0,
    "--xy-minimap-mask-stroke-color-props": typeof m == "string" ? m : void 0,
    "--xy-minimap-mask-stroke-width-props": typeof p == "number" ? p * X : void 0,
    "--xy-minimap-node-background-color-props": typeof s == "string" ? s : void 0,
    "--xy-minimap-node-stroke-color-props": typeof e == "string" ? e : void 0,
    "--xy-minimap-node-stroke-width-props": typeof c == "number" ? c : void 0
  }, className: Rn(["react-flow__minimap", t]), "data-testid": "rf__minimap", children: _t.jsxs("svg", { width: V, height: N, viewBox: `${et} ${$} ${j} ${Y}`, className: "react-flow__minimap-svg", role: "img", "aria-labelledby": K, ref: C, onClick: dt, children: [Pt && _t.jsx("title", { id: K, children: Pt }), _t.jsx(kF, { onClick: yt, nodeColor: s, nodeStrokeColor: e, nodeBorderRadius: o, nodeClassName: a, nodeStrokeWidth: c, nodeComponent: u }), _t.jsx("path", { className: "react-flow__minimap-mask", d: `M${et - W},${$ - W}h${j + W * 2}v${Y + W * 2}h${-j - W * 2}z
        M${T.x},${T.y}h${T.width}v${T.height}h${-T.width}z`, fillRule: "evenodd", pointerEvents: "none" })] }) });
}
Hw.displayName = "MiniMap";
vt.memo(Hw);
const ZF = (n) => (t) => n ? `${Math.max(1 / t.transform[2], 1)}` : void 0, $F = {
  [bl.Line]: "right",
  [bl.Handle]: "bottom-right"
};
function KF({ nodeId: n, position: t, variant: e = bl.Handle, className: s, style: a = void 0, children: o, color: c, minWidth: u = 10, minHeight: d = 10, maxWidth: h = Number.MAX_VALUE, maxHeight: m = Number.MAX_VALUE, keepAspectRatio: p = !1, resizeDirection: g, autoScale: _ = !0, shouldResize: x, onResizeStart: A, onResize: b, onResizeEnd: y }) {
  const E = _w(), w = typeof n == "string" ? n : E, M = ln(), O = vt.useRef(null), C = e === bl.Handle, D = Pe(vt.useCallback(ZF(C && _), [C, _]), on), T = vt.useRef(null), L = t ?? $F[e];
  vt.useEffect(() => {
    if (!(!O.current || !w))
      return T.current || (T.current = Cz({
        domNode: O.current,
        nodeId: w,
        getStoreItems: () => {
          const { nodeLookup: R, transform: B, snapGrid: H, snapToGrid: U, nodeOrigin: V, domNode: N } = M.getState();
          return {
            nodeLookup: R,
            transform: B,
            snapGrid: H,
            snapToGrid: U,
            nodeOrigin: V,
            paneDomNode: N
          };
        },
        onChange: (R, B) => {
          const { triggerNodeChanges: H, nodeLookup: U, parentLookup: V, nodeOrigin: N } = M.getState(), I = [], k = { x: R.x, y: R.y }, X = U.get(w);
          if (X && X.expandParent && X.parentId) {
            const Q = X.origin ?? N, F = R.width ?? X.measured.width ?? 0, W = R.height ?? X.measured.height ?? 0, et = {
              id: X.id,
              parentId: X.parentId,
              rect: {
                width: F,
                height: W,
                ...HE({
                  x: R.x ?? X.position.x,
                  y: R.y ?? X.position.y
                }, { width: F, height: W }, X.parentId, U, Q)
              }
            }, $ = Ev([et], U, V, N);
            I.push(...$), k.x = R.x ? Math.max(Q[0] * F, R.x) : void 0, k.y = R.y ? Math.max(Q[1] * W, R.y) : void 0;
          }
          if (k.x !== void 0 && k.y !== void 0) {
            const Q = {
              id: w,
              type: "position",
              position: { ...k }
            };
            I.push(Q);
          }
          if (R.width !== void 0 && R.height !== void 0) {
            const F = {
              id: w,
              type: "dimensions",
              resizing: !0,
              setAttributes: g ? g === "horizontal" ? "width" : "height" : !0,
              dimensions: {
                width: R.width,
                height: R.height
              }
            };
            I.push(F);
          }
          for (const Q of B) {
            const F = {
              ...Q,
              type: "position"
            };
            I.push(F);
          }
          H(I);
        },
        onEnd: ({ width: R, height: B }) => {
          const H = {
            id: w,
            type: "dimensions",
            resizing: !1,
            dimensions: {
              width: R,
              height: B
            }
          };
          M.getState().triggerNodeChanges([H]);
        }
      })), T.current.update({
        controlPosition: L,
        boundaries: {
          minWidth: u,
          minHeight: d,
          maxWidth: h,
          maxHeight: m
        },
        keepAspectRatio: p,
        resizeDirection: g,
        onResizeStart: A,
        onResize: b,
        onResizeEnd: y,
        shouldResize: x
      }), () => {
        var R;
        (R = T.current) == null || R.destroy();
      };
  }, [
    L,
    u,
    d,
    h,
    m,
    p,
    A,
    b,
    y,
    x
  ]);
  const z = L.split("-");
  return _t.jsx("div", { className: Rn(["react-flow__resize-control", "nodrag", ...z, e, s]), ref: O, style: {
    ...a,
    scale: D,
    ...c && { [C ? "backgroundColor" : "borderColor"]: c }
  }, children: o });
}
vt.memo(KF);
class Vw {
  constructor(t, e, s) {
    At(this, "kind", "memory");
    At(this, "meta");
    At(this, "frames");
    At(this, "basePositions");
    this.frames = t, this.meta = e, this.basePositions = s ?? null;
  }
  getFrame(t) {
    return t === 0 && this.basePositions ? {
      frameId: 0,
      nAtoms: this.meta.nAtoms,
      positions: this.basePositions
    } : this.frames[t - (this.basePositions ? 1 : 0)] ?? null;
  }
}
const kd = {
  load_structure: {
    inputs: [],
    outputs: [
      { name: "particle", dataType: "particle", label: "Particle" },
      { name: "trajectory", dataType: "trajectory", label: "Trajectory" },
      { name: "cell", dataType: "cell", label: "Cell" }
    ]
  },
  load_trajectory: {
    inputs: [{ name: "particle", dataType: "particle", label: "Particle" }],
    outputs: [{ name: "trajectory", dataType: "trajectory", label: "Trajectory" }]
  },
  streaming: {
    inputs: [],
    outputs: [
      { name: "particle", dataType: "particle", label: "Particle" },
      { name: "bond", dataType: "bond", label: "Bond" },
      { name: "trajectory", dataType: "trajectory", label: "Trajectory" },
      { name: "cell", dataType: "cell", label: "Cell" }
    ]
  },
  load_vector: {
    inputs: [],
    outputs: [{ name: "vector", dataType: "vector", label: "Vector" }]
  },
  add_bond: {
    inputs: [{ name: "particle", dataType: "particle", label: "Particle" }],
    outputs: [{ name: "bond", dataType: "bond", label: "Bond" }]
  },
  viewport: {
    inputs: [
      { name: "particle", dataType: "particle", label: "Particle" },
      { name: "bond", dataType: "bond", label: "Bond" },
      { name: "cell", dataType: "cell", label: "Cell" },
      { name: "trajectory", dataType: "trajectory", label: "Trajectory" },
      { name: "label", dataType: "label", label: "Label" },
      { name: "mesh", dataType: "mesh", label: "Mesh" },
      { name: "vector", dataType: "vector", label: "Vector" }
    ],
    outputs: []
  },
  filter: {
    inputs: [{ name: "in", dataType: "particle", label: "In" }],
    outputs: [{ name: "out", dataType: "particle", label: "Out" }]
  },
  modify: {
    inputs: [{ name: "in", dataType: "particle", label: "In" }],
    outputs: [{ name: "out", dataType: "particle", label: "Out" }]
  },
  label_generator: {
    inputs: [{ name: "particle", dataType: "particle", label: "Particle" }],
    outputs: [{ name: "label", dataType: "label", label: "Label" }]
  },
  polyhedron_generator: {
    inputs: [{ name: "particle", dataType: "particle", label: "Particle" }],
    outputs: [{ name: "mesh", dataType: "mesh", label: "Mesh" }]
  },
  vector_overlay: {
    inputs: [{ name: "vector", dataType: "vector", label: "Vector" }],
    outputs: [{ name: "vector", dataType: "vector", label: "Vector" }]
  }
}, QF = {
  filter: ["particle", "bond"],
  modify: ["particle", "bond"]
};
function Gw(n) {
  switch (n) {
    case "load_structure":
      return { type: n, fileName: null, hasTrajectory: !1, hasCell: !1 };
    case "load_trajectory":
      return { type: n, fileName: null };
    case "streaming":
      return { type: n, connected: !1 };
    case "load_vector":
      return { type: n, fileName: null };
    case "add_bond":
      return { type: n, bondSource: "distance" };
    case "viewport":
      return { type: n, perspective: !1, cellAxesVisible: !0 };
    case "filter":
      return { type: n, query: "", bond_query: "" };
    case "modify":
      return { type: n, scale: 1, opacity: 1 };
    case "label_generator":
      return { type: n, source: "element" };
    case "polyhedron_generator":
      return {
        type: n,
        centerElements: [],
        ligandElements: [8],
        // oxygen by default
        maxDistance: 2.5,
        opacity: 0.5,
        showEdges: !1,
        edgeColor: "#dddddd",
        edgeWidth: 3
      };
    case "vector_overlay":
      return { type: n, scale: 1 };
  }
}
function JF(n, t, e, s) {
  if (!t || !s) return !1;
  const a = kd[n], o = kd[e], c = a.outputs.find((h) => h.name === t), u = o.inputs.find((h) => h.name === s);
  if (!c || !u) return !1;
  const d = QF[e];
  return d ? d.includes(c.dataType) : c.dataType === u.dataType;
}
const bd = {
  particles: [],
  bonds: [],
  cells: [],
  trajectories: [],
  labels: [],
  meshes: [],
  vectors: [],
  perspective: !1,
  cellAxesVisible: !0
};
function t5(n, t) {
  const e = /* @__PURE__ */ new Map();
  if (!t) return e;
  const { snapshot: s, streamProvider: a } = t, o = {
    type: "particle",
    source: s,
    sourceNodeId: n,
    indices: null,
    scaleOverrides: null,
    opacityOverrides: null
  };
  if (e.set("particle", o), s.nBonds > 0) {
    const c = {
      type: "bond",
      sourceNodeId: n,
      bondIndices: s.bonds,
      bondOrders: s.bondOrders,
      nBonds: s.nBonds,
      scale: 1,
      opacity: 1,
      positions: null,
      elements: null,
      nAtoms: s.nAtoms,
      atomElements: s.elements,
      selectedBondIndices: null,
      bondOpacityOverrides: null
    };
    e.set("bond", c);
  }
  if (a) {
    const c = {
      type: "trajectory",
      provider: a,
      meta: a.meta,
      source: "stream"
    };
    e.set("trajectory", c);
  }
  if (s.box) {
    const c = {
      type: "cell",
      sourceNodeId: n,
      box: s.box,
      visible: !0,
      axesVisible: !0
    };
    e.set("cell", c);
  }
  return e;
}
function kw(n, t) {
  var c;
  const e = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
  for (const u of n)
    e.set(u.id, 0), s.set(u.id, []);
  for (const u of t) {
    const d = e.get(u.target) ?? 0;
    e.set(u.target, d + 1), (c = s.get(u.source)) == null || c.push(u.target);
  }
  const a = [];
  for (const [u, d] of e)
    d === 0 && a.push(u);
  const o = [];
  for (; a.length > 0; ) {
    const u = a.shift();
    o.push(u);
    for (const d of s.get(u) ?? []) {
      const h = (e.get(d) ?? 1) - 1;
      e.set(d, h), h === 0 && a.push(d);
    }
  }
  return o;
}
function Q1(n, t, e) {
  const s = /* @__PURE__ */ new Map();
  for (const a of t) {
    if (a.target !== n) continue;
    const o = a.sourceHandle, c = a.targetHandle;
    if (!o || !c) continue;
    const u = e.get(a.source);
    if (!u) continue;
    const d = u.get(o);
    d && (s.has(c) || s.set(c, []), s.get(c).push(d));
  }
  return s;
}
function e5(n, t, e, s, a) {
  const o = /* @__PURE__ */ new Map();
  if (!t) return o;
  const c = {
    type: "particle",
    source: t,
    sourceNodeId: a,
    indices: null,
    scaleOverrides: null,
    opacityOverrides: null
  };
  if (o.set("particle", c), e && e.length > 0 && s) {
    const d = {
      type: "trajectory",
      provider: new Vw(e, s, t.positions),
      meta: s,
      source: "structure"
    };
    o.set("trajectory", d);
  }
  if (t.box) {
    const u = {
      type: "cell",
      sourceNodeId: a,
      box: t.box,
      visible: !0,
      axesVisible: !0
    };
    o.set("cell", u);
  }
  return o;
}
function n5(n, t, e, s) {
  const a = /* @__PURE__ */ new Map();
  if (e && e.length > 0 && s) {
    const c = {
      type: "trajectory",
      provider: new Vw(e, s),
      meta: s,
      source: "file"
    };
    a.set("trajectory", c);
  }
  return a;
}
const i5 = /* @__PURE__ */ new Set(["element", "index", "x", "y", "z", "resname", "mass"]);
function Xw(n) {
  const t = [];
  let e = 0;
  for (; e < n.length; ) {
    if (/\s/.test(n[e])) {
      e++;
      continue;
    }
    if (n[e] === "(") {
      t.push({ type: "lparen", value: "(" }), e++;
      continue;
    }
    if (n[e] === ")") {
      t.push({ type: "rparen", value: ")" }), e++;
      continue;
    }
    if (n.startsWith("==", e)) {
      t.push({ type: "op", value: "==" }), e += 2;
      continue;
    }
    if (n.startsWith("!=", e)) {
      t.push({ type: "op", value: "!=" }), e += 2;
      continue;
    }
    if (n.startsWith(">=", e)) {
      t.push({ type: "op", value: ">=" }), e += 2;
      continue;
    }
    if (n.startsWith("<=", e)) {
      t.push({ type: "op", value: "<=" }), e += 2;
      continue;
    }
    if (n[e] === ">") {
      t.push({ type: "op", value: ">" }), e++;
      continue;
    }
    if (n[e] === "<") {
      t.push({ type: "op", value: "<" }), e++;
      continue;
    }
    if (n[e] === '"' || n[e] === "'") {
      const s = n[e];
      let a = e + 1;
      for (; a < n.length && n[a] !== s; ) a++;
      if (a >= n.length) throw new Error(`Unterminated string at position ${e}`);
      t.push({ type: "string", value: n.slice(e + 1, a) }), e = a + 1;
      continue;
    }
    if (/[\d.]/.test(n[e]) || n[e] === "-" && e + 1 < n.length && /[\d.]/.test(n[e + 1])) {
      let s = e;
      for (n[s] === "-" && s++; s < n.length && /[\d.]/.test(n[s]); ) s++;
      t.push({ type: "number", value: n.slice(e, s) }), e = s;
      continue;
    }
    if (/[a-zA-Z_]/.test(n[e])) {
      let s = e;
      for (; s < n.length && /[a-zA-Z_0-9]/.test(n[s]); ) s++;
      const a = n.slice(e, s);
      if (a === "and") t.push({ type: "and", value: a });
      else if (a === "or") t.push({ type: "or", value: a });
      else if (a === "not") t.push({ type: "not", value: a });
      else if (a === "all") t.push({ type: "all", value: a });
      else if (a === "none") t.push({ type: "none", value: a });
      else if (i5.has(a)) t.push({ type: "field", value: a });
      else throw new Error(`Unknown identifier: "${a}"`);
      e = s;
      continue;
    }
    throw new Error(`Unexpected character: "${n[e]}" at position ${e}`);
  }
  return t.push({ type: "eof", value: "" }), t;
}
class Ww {
  constructor(t) {
    At(this, "tokens");
    At(this, "pos", 0);
    this.tokens = t;
  }
  peek() {
    return this.tokens[this.pos];
  }
  advance() {
    return this.tokens[this.pos++];
  }
  expect(t) {
    const e = this.peek();
    if (e.type !== t)
      throw new Error(`Expected ${t}, got ${e.type} ("${e.value}")`);
    return this.advance();
  }
  parse() {
    const t = this.parseOr();
    if (this.peek().type !== "eof")
      throw new Error(`Unexpected token: "${this.peek().value}"`);
    return t;
  }
  parseOr() {
    let t = this.parseAnd();
    for (; this.peek().type === "or"; ) {
      this.advance();
      const e = this.parseAnd();
      t = { kind: "or", left: t, right: e };
    }
    return t;
  }
  parseAnd() {
    let t = this.parseNot();
    for (; this.peek().type === "and"; ) {
      this.advance();
      const e = this.parseNot();
      t = { kind: "and", left: t, right: e };
    }
    return t;
  }
  parseNot() {
    return this.peek().type === "not" ? (this.advance(), { kind: "not", operand: this.parseNot() }) : this.parseAtom();
  }
  parseAtom() {
    const t = this.peek();
    if (t.type === "all")
      return this.advance(), { kind: "all" };
    if (t.type === "none")
      return this.advance(), { kind: "none" };
    if (t.type === "lparen") {
      this.advance();
      const e = this.parseOr();
      return this.expect("rparen"), e;
    }
    if (t.type === "field") {
      const e = this.advance().value, s = this.expect("op").value, a = this.peek();
      let o;
      if (a.type === "string")
        o = this.advance().value;
      else if (a.type === "number") {
        if (o = parseFloat(this.advance().value), isNaN(o)) throw new Error("Invalid number");
      } else
        throw new Error(`Expected value after operator, got ${a.type}`);
      return { kind: "comparison", field: e, op: s, value: o };
    }
    throw new Error(`Unexpected token: "${t.value}" (${t.type})`);
  }
}
function s5(n) {
  const t = n.match(/^([A-Za-z]+)/);
  return t ? t[1] : n;
}
function el(n, t, e) {
  switch (n.kind) {
    case "all":
      return () => !0;
    case "none":
      return () => !1;
    case "not": {
      const s = el(n.operand, t, e);
      return (a) => !s(a);
    }
    case "and": {
      const s = el(n.left, t, e), a = el(n.right, t, e);
      return (o) => s(o) && a(o);
    }
    case "or": {
      const s = el(n.left, t, e), a = el(n.right, t, e);
      return (o) => s(o) || a(o);
    }
    case "comparison": {
      const { field: s, op: a, value: o } = n;
      return (c) => {
        let u;
        switch (s) {
          case "element":
            u = Wc(t.elements[c]);
            break;
          case "index":
            u = c;
            break;
          case "x":
            u = t.positions[c * 3];
            break;
          case "y":
            u = t.positions[c * 3 + 1];
            break;
          case "z":
            u = t.positions[c * 3 + 2];
            break;
          case "resname":
            u = e != null && e[c] ? s5(e[c]) : "";
            break;
          case "mass":
            u = pL(t.elements[c]);
            break;
          default:
            return !1;
        }
        switch (a) {
          case "==":
            return u === o;
          case "!=":
            return u !== o;
          case ">":
            return u > o;
          case "<":
            return u < o;
          case ">=":
            return u >= o;
          case "<=":
            return u <= o;
          default:
            return !1;
        }
      };
    }
  }
}
function r5(n, t, e) {
  const s = n.trim();
  if (s === "" || s === "all") return null;
  const a = Xw(s), c = new Ww(a).parse();
  if (c.kind === "all") return null;
  if (c.kind === "none") return /* @__PURE__ */ new Set();
  const u = el(c, t, e), d = /* @__PURE__ */ new Set();
  for (let h = 0; h < t.nAtoms; h++)
    u(h) && d.add(h);
  return d;
}
function a5(n) {
  const t = n.trim();
  if (t === "" || t === "all" || t === "none")
    return { valid: !0 };
  try {
    const e = Xw(t);
    return new Ww(e).parse(), { valid: !0 };
  } catch (e) {
    return { valid: !1, error: e.message };
  }
}
const o5 = /* @__PURE__ */ new Set(["bond_index", "atom_index", "element"]);
function l5(n) {
  const t = [];
  let e = 0;
  for (; e < n.length; ) {
    if (/\s/.test(n[e])) {
      e++;
      continue;
    }
    if (n[e] === "(") {
      t.push({ type: "lparen", value: "(" }), e++;
      continue;
    }
    if (n[e] === ")") {
      t.push({ type: "rparen", value: ")" }), e++;
      continue;
    }
    if (n.startsWith("==", e)) {
      t.push({ type: "op", value: "==" }), e += 2;
      continue;
    }
    if (n.startsWith("!=", e)) {
      t.push({ type: "op", value: "!=" }), e += 2;
      continue;
    }
    if (n.startsWith(">=", e)) {
      t.push({ type: "op", value: ">=" }), e += 2;
      continue;
    }
    if (n.startsWith("<=", e)) {
      t.push({ type: "op", value: "<=" }), e += 2;
      continue;
    }
    if (n[e] === ">") {
      t.push({ type: "op", value: ">" }), e++;
      continue;
    }
    if (n[e] === "<") {
      t.push({ type: "op", value: "<" }), e++;
      continue;
    }
    if (n[e] === '"' || n[e] === "'") {
      const s = n[e];
      let a = e + 1;
      for (; a < n.length && n[a] !== s; ) a++;
      if (a >= n.length) throw new Error(`Unterminated string at position ${e}`);
      t.push({ type: "string", value: n.slice(e + 1, a) }), e = a + 1;
      continue;
    }
    if (/[\d.]/.test(n[e]) || n[e] === "-" && e + 1 < n.length && /[\d.]/.test(n[e + 1])) {
      let s = e;
      for (n[s] === "-" && s++; s < n.length && /[\d.]/.test(n[s]); ) s++;
      t.push({ type: "number", value: n.slice(e, s) }), e = s;
      continue;
    }
    if (/[a-zA-Z_]/.test(n[e])) {
      let s = e;
      for (; s < n.length && /[a-zA-Z_0-9]/.test(n[s]); ) s++;
      const a = n.slice(e, s);
      if (a === "and") t.push({ type: "and", value: a });
      else if (a === "or") t.push({ type: "or", value: a });
      else if (a === "not") t.push({ type: "not", value: a });
      else if (a === "all") t.push({ type: "all", value: a });
      else if (a === "none") t.push({ type: "none", value: a });
      else if (a === "both") t.push({ type: "both", value: a });
      else if (o5.has(a)) t.push({ type: "bond_field", value: a });
      else throw new Error(`Unknown identifier: "${a}"`);
      e = s;
      continue;
    }
    throw new Error(`Unexpected character: "${n[e]}" at position ${e}`);
  }
  return t.push({ type: "eof", value: "" }), t;
}
class c5 {
  constructor(t) {
    At(this, "tokens");
    At(this, "pos", 0);
    this.tokens = t;
  }
  peek() {
    return this.tokens[this.pos];
  }
  advance() {
    return this.tokens[this.pos++];
  }
  expect(t) {
    const e = this.peek();
    if (e.type !== t) throw new Error(`Expected ${t}, got ${e.type} ("${e.value}")`);
    return this.advance();
  }
  parse() {
    const t = this.parseOr();
    if (this.peek().type !== "eof") throw new Error(`Unexpected token: "${this.peek().value}"`);
    return t;
  }
  parseOr() {
    let t = this.parseAnd();
    for (; this.peek().type === "or"; )
      this.advance(), t = { kind: "or", left: t, right: this.parseAnd() };
    return t;
  }
  parseAnd() {
    let t = this.parseNot();
    for (; this.peek().type === "and"; )
      this.advance(), t = { kind: "and", left: t, right: this.parseNot() };
    return t;
  }
  parseNot() {
    return this.peek().type === "not" ? (this.advance(), { kind: "not", operand: this.parseNot() }) : this.parseAtom();
  }
  parseAtom() {
    const t = this.peek();
    if (t.type === "all")
      return this.advance(), { kind: "all" };
    if (t.type === "none")
      return this.advance(), { kind: "none" };
    if (t.type === "lparen") {
      this.advance();
      const e = this.parseOr();
      return this.expect("rparen"), e;
    }
    if (t.type === "both")
      return this.advance(), this.parseComparison(!0);
    if (t.type === "bond_field")
      return this.parseComparison(!1);
    throw new Error(`Unexpected token: "${t.value}" (${t.type})`);
  }
  parseComparison(t) {
    const e = this.expect("bond_field").value, s = this.expect("op").value, a = this.peek();
    let o;
    if (a.type === "string")
      o = this.advance().value;
    else if (a.type === "number") {
      if (o = parseFloat(this.advance().value), isNaN(o)) throw new Error("Invalid number");
    } else
      throw new Error(`Expected value after operator, got ${a.type}`);
    return { kind: "comparison", field: e, op: s, value: o, both: t };
  }
}
function rr(n, t, e) {
  switch (t) {
    case "==":
      return n === e;
    case "!=":
      return n !== e;
    case ">":
      return n > e;
    case "<":
      return n < e;
    case ">=":
      return n >= e;
    case "<=":
      return n <= e;
    default:
      return !1;
  }
}
function nl(n, t, e) {
  switch (n.kind) {
    case "all":
      return () => !0;
    case "none":
      return () => !1;
    case "not": {
      const s = nl(n.operand, t, e);
      return (a) => !s(a);
    }
    case "and": {
      const s = nl(n.left, t, e), a = nl(n.right, t, e);
      return (o) => s(o) && a(o);
    }
    case "or": {
      const s = nl(n.left, t, e), a = nl(n.right, t, e);
      return (o) => s(o) || a(o);
    }
    case "comparison": {
      const { field: s, op: a, value: o, both: c } = n;
      return (u) => {
        const d = t[u * 2], h = t[u * 2 + 1];
        switch (s) {
          case "bond_index":
            return rr(u, a, o);
          case "atom_index":
            return c ? rr(d, a, o) && rr(h, a, o) : rr(d, a, o) || rr(h, a, o);
          case "element": {
            const m = Wc(e[d] ?? 0), p = Wc(e[h] ?? 0);
            return c ? rr(m, a, o) && rr(p, a, o) : rr(m, a, o) || rr(p, a, o);
          }
          default:
            return !1;
        }
      };
    }
  }
}
function u5(n, t, e, s) {
  const a = n.trim();
  if (a === "" || a === "all") return null;
  const o = l5(a), u = new c5(o).parse();
  if (u.kind === "all") return null;
  if (u.kind === "none") return /* @__PURE__ */ new Set();
  const d = nl(u, t, e), h = /* @__PURE__ */ new Set();
  for (let m = 0; m < s; m++)
    d(m) && h.add(m);
  return h;
}
function f5(n, t, e) {
  var o, c;
  const s = /* @__PURE__ */ new Map(), a = (o = t.get("in")) == null ? void 0 : o[0];
  if (!a) return s;
  if (a.type === "particle") {
    const u = a;
    if (!n.query.trim())
      return s.set("out", u), s;
    try {
      const d = r5(n.query, u.source, e);
      if (d === null)
        s.set("out", u);
      else {
        let h;
        if (u.indices === null)
          h = new Uint32Array(d);
        else {
          const p = new Set(u.indices), g = [...d].filter((_) => p.has(_));
          h = new Uint32Array(g);
        }
        const m = {
          ...u,
          indices: h,
          scaleOverrides: u.scaleOverrides,
          opacityOverrides: u.opacityOverrides
        };
        s.set("out", m);
      }
    } catch {
      s.set("out", u);
    }
  } else if (a.type === "bond") {
    const u = a, d = ((c = n.bond_query) == null ? void 0 : c.trim()) ?? "";
    if (d && u.atomElements)
      try {
        const h = u5(
          d,
          u.bondIndices,
          u.atomElements,
          u.nBonds
        );
        if (h !== null)
          return s.set("out", {
            ...u,
            selectedBondIndices: new Uint32Array(h)
          }), s;
      } catch {
      }
    s.set("out", u);
  }
  return s;
}
function d5(n, t) {
  var a;
  const e = /* @__PURE__ */ new Map(), s = (a = t.get("in")) == null ? void 0 : a[0];
  if (!s) return e;
  if (s.type === "particle") {
    const o = s, c = o.source.nAtoms;
    let u = o.scaleOverrides;
    if (o.indices !== null && o.indices.length > 0) {
      u ? u = new Float32Array(u) : u = new Float32Array(c).fill(1);
      for (const m of o.indices)
        u[m] = n.scale;
    } else o.indices === null && n.scale !== 1 && (u = new Float32Array(c).fill(n.scale));
    let d = o.opacityOverrides;
    if (o.indices !== null && o.indices.length > 0) {
      d ? d = new Float32Array(d) : d = new Float32Array(c).fill(1);
      for (const m of o.indices)
        d[m] = n.opacity;
    } else o.indices === null && n.opacity !== 1 && (d = new Float32Array(c).fill(n.opacity));
    const h = {
      ...o,
      scaleOverrides: u,
      opacityOverrides: d
    };
    e.set("out", h);
  } else if (s.type === "bond") {
    const o = s;
    if (o.selectedBondIndices !== null) {
      const c = new Float32Array(o.nBonds).fill(1);
      for (const u of o.selectedBondIndices)
        c[u] = n.opacity;
      e.set("out", {
        ...o,
        scale: n.scale,
        bondOpacityOverrides: c
      });
    } else
      e.set("out", { ...o, scale: n.scale, opacity: n.opacity });
  }
  return e;
}
function h5(n, t, e) {
  var d;
  const s = /* @__PURE__ */ new Map(), a = (d = t.get("particle")) == null ? void 0 : d[0];
  if (!a) return s;
  const o = a.source;
  let c;
  switch (n.source) {
    case "element":
      c = Array.from(o.elements).map((h) => Wc(h));
      break;
    case "resname":
      c = (e == null ? void 0 : e.slice(0, o.nAtoms)) ?? [];
      break;
    case "index":
      c = Array.from({ length: o.nAtoms }, (h, m) => String(m));
      break;
    default:
      c = [];
  }
  if (a.indices !== null) {
    const h = new Array(o.nAtoms).fill("");
    for (const m of a.indices)
      h[m] = c[m];
    c = h;
  }
  const u = {
    type: "label",
    labels: c,
    particleRef: a
  };
  return s.set("label", u), s;
}
function Yw(n, t, e, s, a, o) {
  return [t * o - e * a, e * s - n * o, n * a - t * s];
}
function Cc(n, t, e, s, a) {
  const o = s[n * 3], c = s[n * 3 + 1], u = s[n * 3 + 2], d = s[t * 3], h = s[t * 3 + 1], m = s[t * 3 + 2], p = s[e * 3], g = s[e * 3 + 1], _ = s[e * 3 + 2], x = d - o, A = h - c, b = m - u, y = p - o, E = g - c, w = _ - u;
  let [M, O, C] = Yw(x, A, b, y, E, w);
  const D = Math.sqrt(M * M + O * O + C * C);
  if (D < 1e-12)
    return { a: n, b: t, c: e, nx: 0, ny: 0, nz: 0, d: 0 };
  M /= D, O /= D, C /= D;
  const T = -(M * o + O * c + C * u);
  return M * a[0] + O * a[1] + C * a[2] + T > 0 ? (M = -M, O = -O, C = -C, { a: n, b: e, c: t, nx: M, ny: O, nz: C, d: -T }) : { a: n, b: t, c: e, nx: M, ny: O, nz: C, d: T };
}
function p5(n, t, e, s) {
  return n.nx * t + n.ny * e + n.nz * s + n.d;
}
function m5(n, t) {
  if (t < 4) return null;
  let e = 0, s = 1, a = -1;
  for (let R = 0; R < t; R++)
    for (let B = R + 1; B < t; B++) {
      const H = n[B * 3] - n[R * 3], U = n[B * 3 + 1] - n[R * 3 + 1], V = n[B * 3 + 2] - n[R * 3 + 2], N = H * H + U * U + V * V;
      N > a && (a = N, e = R, s = B);
    }
  if (a < 1e-20) return null;
  const o = n[s * 3] - n[e * 3], c = n[s * 3 + 1] - n[e * 3 + 1], u = n[s * 3 + 2] - n[e * 3 + 2], d = Math.sqrt(o * o + c * c + u * u), h = o / d, m = c / d, p = u / d;
  let g = -1, _ = -1;
  for (let R = 0; R < t; R++) {
    if (R === e || R === s) continue;
    const B = n[R * 3] - n[e * 3], H = n[R * 3 + 1] - n[e * 3 + 1], U = n[R * 3 + 2] - n[e * 3 + 2], V = B * h + H * m + U * p, N = B - V * h, I = H - V * m, k = U - V * p, X = N * N + I * I + k * k;
    X > _ && (_ = X, g = R);
  }
  if (g < 0 || _ < 1e-20) return null;
  const x = n[s * 3] - n[e * 3], A = n[s * 3 + 1] - n[e * 3 + 1], b = n[s * 3 + 2] - n[e * 3 + 2], y = n[g * 3] - n[e * 3], E = n[g * 3 + 1] - n[e * 3 + 1], w = n[g * 3 + 2] - n[e * 3 + 2];
  let [M, O, C] = Yw(x, A, b, y, E, w);
  const D = Math.sqrt(M * M + O * O + C * C);
  if (D < 1e-12) return null;
  M /= D, O /= D, C /= D;
  const T = -(M * n[e * 3] + O * n[e * 3 + 1] + C * n[e * 3 + 2]);
  let L = -1, z = -1;
  for (let R = 0; R < t; R++) {
    if (R === e || R === s || R === g) continue;
    const B = Math.abs(M * n[R * 3] + O * n[R * 3 + 1] + C * n[R * 3 + 2] + T);
    B > z && (z = B, L = R);
  }
  return L < 0 || z < 1e-10 ? null : [e, s, g, L];
}
function g5(n, t) {
  if (t < 4) return null;
  const e = m5(n, t);
  if (!e) return null;
  const [s, a, o, c] = e, u = [
    (n[s * 3] + n[a * 3] + n[o * 3] + n[c * 3]) / 4,
    (n[s * 3 + 1] + n[a * 3 + 1] + n[o * 3 + 1] + n[c * 3 + 1]) / 4,
    (n[s * 3 + 2] + n[a * 3 + 2] + n[o * 3 + 2] + n[c * 3 + 2]) / 4
  ], d = [
    Cc(s, a, o, n, u),
    Cc(s, a, c, n, u),
    Cc(s, o, c, n, u),
    Cc(a, o, c, n, u)
  ], h = /* @__PURE__ */ new Set([s, a, o, c]);
  for (let y = 0; y < t; y++) {
    if (h.has(y)) continue;
    const E = n[y * 3], w = n[y * 3 + 1], M = n[y * 3 + 2], O = [];
    for (let L = 0; L < d.length; L++)
      p5(d[L], E, w, M) > 1e-10 && O.push(L);
    if (O.length === 0) continue;
    const C = [], D = new Set(O);
    for (const L of O) {
      const z = d[L], R = [
        [z.a, z.b],
        [z.b, z.c],
        [z.c, z.a]
      ];
      for (const [B, H] of R) {
        let U = !1;
        for (let V = 0; V < d.length; V++) {
          if (V === L || D.has(V)) continue;
          const N = d[V];
          if (N.a === H && N.b === B || N.b === H && N.c === B || N.c === H && N.a === B) {
            U = !0;
            break;
          }
        }
        U && C.push([B, H]);
      }
    }
    const T = [...O].sort((L, z) => z - L);
    for (const L of T)
      d.splice(L, 1);
    for (const [L, z] of C)
      d.push(Cc(L, z, y, n, u));
  }
  const m = d.length, p = new Uint32Array(m * 3), g = new Float32Array(t * 3), _ = new Float32Array(t);
  for (let y = 0; y < m; y++) {
    const E = d[y];
    p[y * 3] = E.a, p[y * 3 + 1] = E.b, p[y * 3 + 2] = E.c;
    for (const w of [E.a, E.b, E.c])
      g[w * 3] += E.nx, g[w * 3 + 1] += E.ny, g[w * 3 + 2] += E.nz, _[w]++;
  }
  for (let y = 0; y < t; y++)
    if (_[y] > 0) {
      const E = Math.sqrt(
        g[y * 3] ** 2 + g[y * 3 + 1] ** 2 + g[y * 3 + 2] ** 2
      );
      E > 1e-12 && (g[y * 3] /= E, g[y * 3 + 1] /= E, g[y * 3 + 2] /= E);
    }
  const x = /* @__PURE__ */ new Set(), A = [];
  for (let y = 0; y < m; y++) {
    const E = d[y], w = [
      [E.a, E.b],
      [E.b, E.c],
      [E.c, E.a]
    ];
    for (const [M, O] of w) {
      const C = M < O ? `${M}-${O}` : `${O}-${M}`;
      x.has(C) || (x.add(C), A.push(M, O));
    }
  }
  const b = new Float32Array(A.length * 3);
  for (let y = 0; y < A.length; y++) {
    const E = A[y];
    b[y * 3] = n[E * 3], b[y * 3 + 1] = n[E * 3 + 1], b[y * 3 + 2] = n[E * 3 + 2];
  }
  return {
    vertices: new Float32Array(n.buffer, n.byteOffset, t * 3),
    indices: p,
    normals: g,
    edges: b
  };
}
function v5(n, t, e, s, a) {
  let o = a[0] * n + a[3] * t + a[6] * e, c = a[1] * n + a[4] * t + a[7] * e, u = a[2] * n + a[5] * t + a[8] * e;
  return o -= Math.round(o), c -= Math.round(c), u -= Math.round(u), [
    s[0] * o + s[3] * c + s[6] * u,
    s[1] * o + s[4] * c + s[7] * u,
    s[2] * o + s[5] * c + s[8] * u
  ];
}
function _5(n, t) {
  var C;
  const e = /* @__PURE__ */ new Map(), s = (C = t.get("particle")) == null ? void 0 : C[0];
  if (!s) return e;
  const a = s.source, { positions: o, elements: c, nAtoms: u } = a, d = new Set(n.centerElements), h = new Set(n.ligandElements);
  if (d.size === 0 || h.size === 0) return e;
  const m = [], p = [];
  for (let D = 0; D < u; D++)
    d.has(c[D]) && m.push(D), h.has(c[D]) && p.push(D);
  if (m.length === 0 || p.length === 0) return e;
  const g = a.box;
  let _ = null;
  g && g.some((D) => D !== 0) && (_ = lv(g));
  const x = n.maxDistance * n.maxDistance, A = [], b = [], y = [], E = [], w = [];
  let M = 0;
  for (const D of m) {
    const T = o[D * 3], L = o[D * 3 + 1], z = o[D * 3 + 2], R = [];
    for (const X of p) {
      let Q = o[X * 3] - T, F = o[X * 3 + 1] - L, W = o[X * 3 + 2] - z;
      _ && g && ([Q, F, W] = v5(Q, F, W, g, _));
      const et = Q * Q + F * F + W * W;
      et <= x && et > 0.01 && R.push(T + Q, L + F, z + W);
    }
    const B = R.length / 3;
    if (B < 4) continue;
    const H = new Float32Array(R), U = g5(H, B);
    if (!U) continue;
    const [V, N, I] = Xc(c[D]), k = U.vertices.length / 3;
    for (let X = 0; X < k; X++)
      A.push(U.vertices[X * 3], U.vertices[X * 3 + 1], U.vertices[X * 3 + 2]), y.push(U.normals[X * 3], U.normals[X * 3 + 1], U.normals[X * 3 + 2]), E.push(V, N, I, n.opacity);
    for (let X = 0; X < U.indices.length; X++)
      b.push(U.indices[X] + M);
    for (let X = 0; X < U.edges.length; X++)
      w.push(U.edges[X]);
    M += k;
  }
  if (b.length === 0) return e;
  const O = {
    type: "mesh",
    positions: new Float32Array(A),
    indices: new Uint32Array(b),
    normals: new Float32Array(y),
    colors: new Float32Array(E),
    opacity: n.opacity,
    showEdges: n.showEdges,
    edgePositions: n.showEdges ? new Float32Array(w) : null,
    edgeColor: n.edgeColor,
    edgeWidth: n.edgeWidth
  };
  return e.set("mesh", O), e;
}
function y5(n, t) {
  const e = /* @__PURE__ */ new Map();
  if (!t || t.length === 0)
    return e;
  const s = t[0].vectors.length / 3, a = {
    type: "vector",
    frames: t,
    nAtoms: s,
    scale: 1
  };
  return e.set("vector", a), e;
}
function x5(n, t) {
  const e = /* @__PURE__ */ new Map(), s = t.get("vector");
  if (!s || s.length === 0) return e;
  const o = {
    ...s[0],
    scale: n.scale
  };
  return e.set("vector", o), e;
}
function S5(n, t) {
  const e = t.get("particle") ?? [], s = t.get("bond") ?? [], a = t.get("cell") ?? [], o = t.get("trajectory") ?? [], c = t.get("label") ?? [], u = t.get("mesh") ?? [], d = t.get("vector") ?? [], h = b5(s, e), m = [...o].sort((p, g) => p.source === "file" && g.source !== "file" ? -1 : p.source !== "file" && g.source === "file" ? 1 : 0);
  return {
    particles: e,
    bonds: h,
    cells: a,
    trajectories: m,
    labels: c,
    meshes: u,
    vectors: d,
    perspective: n.perspective,
    cellAxesVisible: n.cellAxesVisible
  };
}
function b5(n, t) {
  if (n.length === 0 || t.length === 0) return n;
  let e = null;
  for (const s of t) {
    if (s.indices === null)
      return n;
    if (!e)
      e = new Set(s.indices);
    else
      for (const a of s.indices)
        e.add(a);
  }
  return e ? n.map((s) => {
    const a = [], o = [];
    for (let c = 0; c < s.nBonds; c++) {
      const u = s.bondIndices[c * 2], d = s.bondIndices[c * 2 + 1];
      e.has(u) && e.has(d) && (a.push(u, d), s.bondOrders && o.push(s.bondOrders[c]));
    }
    return a.length === s.nBonds * 2 ? s : {
      ...s,
      bondIndices: new Uint32Array(a),
      bondOrders: s.bondOrders ? new Uint8Array(o) : null,
      nBonds: a.length / 2
    };
  }) : n;
}
function M5(n, t, e = {}) {
  var h, m, p, g, _, x, A, b, y;
  const s = kw(n, t), a = new Map(n.map((E) => [E.id, E])), o = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), u = (E, w) => {
    c.has(E) || c.set(E, []), c.get(E).push(w);
  };
  let d = { ...bd };
  for (const E of s) {
    const w = a.get(E);
    if (!w) continue;
    const M = w.data;
    if (!M.enabled) {
      const C = Q1(E, t, o), D = /* @__PURE__ */ new Map(), T = M.params.type, L = kd[T];
      for (const [z, R] of C)
        if (R.length > 0) {
          const B = L.outputs.find((H) => {
            const U = L.inputs.find((V) => V.name === z);
            return U && H.dataType === U.dataType;
          });
          B && D.set(B.name, R[0]);
        }
      o.set(E, D);
      continue;
    }
    const O = Q1(E, t, o);
    switch (M.params.type) {
      case "load_structure": {
        const C = (h = e.nodeSnapshots) == null ? void 0 : h[E], D = (C == null ? void 0 : C.snapshot) ?? e.snapshot ?? null, T = (C == null ? void 0 : C.frames) ?? e.structureFrames ?? null, L = (C == null ? void 0 : C.meta) ?? e.structureMeta ?? null, z = e5(
          M.params,
          D,
          T,
          L,
          E
        );
        o.set(E, z), D || u(E, { message: "No structure data available", severity: "warning" });
        break;
      }
      case "load_vector": {
        const C = y5(M.params, e.fileVectors ?? null);
        o.set(E, C);
        break;
      }
      case "load_trajectory": {
        const C = n5(
          M.params,
          O,
          e.fileFrames ?? null,
          e.fileMeta ?? null
        );
        o.set(E, C);
        break;
      }
      case "streaming": {
        const C = (m = e.nodeStreamingData) == null ? void 0 : m[E], D = t5(E, C);
        o.set(E, D), C != null && C.snapshot || u(E, { message: "No streaming data available", severity: "warning" });
        break;
      }
      case "add_bond": {
        const C = jL(M.params, O);
        o.set(E, C), (p = O.get("particle")) != null && p.length && !C.has("bond") ? u(E, { message: "No bonds found", severity: "warning" }) : (g = O.get("particle")) != null && g.length || u(E, { message: "No input data (check upstream nodes)", severity: "warning" });
        break;
      }
      case "filter": {
        const C = f5(M.params, O, e.atomLabels ?? null);
        o.set(E, C);
        const D = C.get("out");
        if (!((_ = O.get("in")) != null && _.length))
          u(E, { message: "No input data (check upstream nodes)", severity: "warning" });
        else if (D && D.type === "particle") {
          const T = D;
          T.indices !== null && T.indices.length === 0 && u(E, { message: "Filter returned 0 atoms", severity: "warning" });
        }
        break;
      }
      case "modify": {
        const C = d5(M.params, O);
        o.set(E, C), (x = O.get("in")) != null && x.length || u(E, { message: "No input data (check upstream nodes)", severity: "warning" });
        break;
      }
      case "label_generator": {
        const C = h5(
          M.params,
          O,
          e.atomLabels ?? null
        );
        o.set(E, C), (A = O.get("particle")) != null && A.length || u(E, { message: "No input data (check upstream nodes)", severity: "warning" });
        break;
      }
      case "polyhedron_generator": {
        const C = _5(
          M.params,
          O
        );
        o.set(E, C), (b = O.get("particle")) != null && b.length ? C.has("mesh") || u(E, { message: "No polyhedra matched the criteria", severity: "warning" }) : u(E, { message: "No input data (check upstream nodes)", severity: "warning" });
        break;
      }
      case "vector_overlay": {
        const C = x5(M.params, O);
        o.set(E, C), (y = O.get("vector")) != null && y.length || u(E, { message: "No input data (check upstream nodes)", severity: "warning" });
        break;
      }
      case "viewport": {
        d = S5(M.params, O);
        break;
      }
    }
  }
  return { viewportState: d, nodeErrors: c };
}
function E5(n, t) {
  var u, d, h, m;
  const e = /* @__PURE__ */ new Map(), s = (p, g) => {
    e.has(p) || e.set(p, []), e.get(p).push(g);
  };
  new Map(n.map((p) => [p.id, p]));
  const a = /* @__PURE__ */ new Map();
  for (const p of n)
    a.set(p.id, []);
  for (const p of t)
    (u = a.get(p.target)) == null || u.push(p);
  for (const p of n) {
    const g = p.type;
    if (!g) continue;
    const _ = kd[g];
    if (!_ || _.inputs.length === 0) continue;
    const x = new Set((a.get(p.id) ?? []).map((b) => b.targetHandle));
    _.inputs.some((b) => x.has(b.name)) || s(p.id, { message: "No input connected", severity: "error" });
  }
  const o = n.filter((p) => p.type === "viewport").map((p) => p.id);
  if (o.length > 0) {
    const p = /* @__PURE__ */ new Map();
    for (const b of n)
      p.set(b.id, /* @__PURE__ */ new Set());
    for (const b of t)
      (d = p.get(b.source)) == null || d.add(b.target);
    new Set(o);
    const g = /* @__PURE__ */ new Map();
    for (const b of n)
      g.set(b.id, /* @__PURE__ */ new Set());
    for (const b of t)
      (h = g.get(b.source)) == null || h.add(b.target);
    const _ = [...o], x = new Set(o), A = /* @__PURE__ */ new Map();
    for (const b of n)
      A.set(b.id, /* @__PURE__ */ new Set());
    for (const b of t)
      (m = A.get(b.target)) == null || m.add(b.source);
    for (; _.length > 0; ) {
      const b = _.shift();
      for (const y of A.get(b) ?? [])
        x.has(y) || (x.add(y), _.push(y));
    }
    for (const b of n)
      b.type !== "viewport" && (x.has(b.id) || s(b.id, {
        message: "Not connected to Viewport",
        severity: "warning"
      }));
  }
  const c = kw(n, t);
  if (c.length < n.length) {
    const p = new Set(c);
    for (const g of n)
      p.has(g.id) || s(g.id, { message: "Cycle detected", severity: "error" });
  }
  for (const p of n) {
    if (!p.data.enabled) continue;
    const g = p.data.params;
    switch (g.type) {
      case "load_structure": {
        g.fileName || s(p.id, {
          message: "No structure file loaded",
          severity: "warning"
        });
        break;
      }
      case "load_trajectory": {
        g.fileName || s(p.id, {
          message: "No trajectory file loaded",
          severity: "warning"
        });
        break;
      }
      case "streaming": {
        g.connected || s(p.id, {
          message: "Not connected to server",
          severity: "warning"
        });
        break;
      }
      case "load_vector": {
        g.fileName || s(p.id, {
          message: "No vector file loaded",
          severity: "warning"
        });
        break;
      }
      case "filter": {
        const _ = g;
        if (_.query.trim()) {
          const x = a5(_.query);
          x.valid || s(p.id, {
            message: `Query syntax error: ${x.error}`,
            severity: "error"
          });
        }
        break;
      }
      case "polyhedron_generator": {
        const _ = g;
        _.centerElements.length === 0 && s(p.id, {
          message: "No center elements selected",
          severity: "error"
        }), _.ligandElements.length === 0 && s(p.id, {
          message: "No ligand elements selected",
          severity: "error"
        });
        break;
      }
    }
  }
  return e;
}
const w5 = /* @__PURE__ */ new Set([
  "load_structure",
  "load_trajectory",
  "load_vector",
  "streaming",
  "add_bond",
  "viewport",
  "filter",
  "modify",
  "label_generator",
  "polyhedron_generator",
  "vector_overlay"
]);
function A5(n, t) {
  return {
    version: 3,
    nodes: n.map((e) => ({
      ...e.data.params,
      id: e.id,
      position: e.position,
      enabled: e.data.enabled
    })),
    edges: t.map((e) => ({
      source: e.source,
      target: e.target,
      sourceHandle: e.sourceHandle ?? "",
      targetHandle: e.targetHandle ?? ""
    }))
  };
}
function T5(n) {
  if (n.version !== 3)
    throw new Error(`Unsupported pipeline version: ${n.version}`);
  const t = n.nodes.map((s) => {
    if (!w5.has(s.type))
      throw new Error(`Unknown node type: ${s.type}`);
    const a = s.type, o = Gw(a), { id: c, position: u, enabled: d, ...h } = s, m = { ...o, ...h, type: a };
    return {
      id: c,
      type: a,
      position: u ?? { x: 0, y: 0 },
      data: {
        params: m,
        enabled: d !== !1
      }
    };
  }), e = (n.edges ?? []).map((s, a) => ({
    id: `e-${s.source}-${s.sourceHandle}-${s.target}-${s.targetHandle}-${a}`,
    source: s.source,
    target: s.target,
    sourceHandle: s.sourceHandle || null,
    targetHandle: s.targetHandle || null
  }));
  return { nodes: t, edges: e };
}
function C5() {
  return {
    nodes: [
      // Row 0: Source
      {
        id: "loader-1",
        type: "load_structure",
        position: { x: 425, y: 0 },
        data: {
          params: {
            type: "load_structure",
            fileName: "caffeine_water.pdb",
            hasTrajectory: !1,
            hasCell: !0
          },
          enabled: !0
        }
      },
      // Row 1: Data loading & filtering
      {
        id: "traj-1",
        type: "load_trajectory",
        position: { x: -85, y: 310 },
        data: {
          params: {
            type: "load_trajectory",
            fileName: "caffeine_water_vibration.xtc"
          },
          enabled: !0
        }
      },
      {
        id: "addbond-1",
        type: "add_bond",
        position: { x: 255, y: 310 },
        data: {
          params: {
            type: "add_bond",
            bondSource: "structure"
          },
          enabled: !0
        }
      },
      {
        id: "filter-caf",
        type: "filter",
        position: { x: 595, y: 310 },
        data: {
          params: {
            type: "filter",
            query: "index < 24"
          },
          enabled: !0
        }
      },
      {
        id: "filter-sol",
        type: "filter",
        position: { x: 935, y: 310 },
        data: {
          params: {
            type: "filter",
            query: "index >= 24"
          },
          enabled: !0
        }
      },
      // Row 2: Processing (labels, modify)
      {
        id: "labels-1",
        type: "label_generator",
        position: { x: 425, y: 615 },
        data: {
          params: {
            type: "label_generator",
            source: "element"
          },
          enabled: !0
        }
      },
      {
        id: "modify-caf",
        type: "modify",
        position: { x: 680, y: 615 },
        data: {
          params: {
            type: "modify",
            scale: 1.3,
            opacity: 1
          },
          enabled: !0
        }
      },
      {
        id: "modify-sol",
        type: "modify",
        position: { x: 970, y: 615 },
        data: {
          params: {
            type: "modify",
            scale: 1,
            opacity: 0.15
          },
          enabled: !0
        }
      },
      {
        id: "filter-bond-sol",
        type: "filter",
        position: { x: 255, y: 615 },
        data: {
          params: {
            type: "filter",
            query: "",
            bond_query: "both atom_index >= 24"
          },
          enabled: !0
        }
      },
      {
        id: "modify-bond-sol",
        type: "modify",
        position: { x: 255, y: 920 },
        data: {
          params: {
            type: "modify",
            scale: 1,
            opacity: 0.15
          },
          enabled: !0
        }
      },
      // Row 3: Sink
      {
        id: "viewport-1",
        type: "viewport",
        position: { x: 510, y: 920 },
        data: {
          params: {
            type: "viewport",
            perspective: !1,
            cellAxesVisible: !0
          },
          enabled: !0
        }
      }
    ],
    edges: [
      {
        id: "e1",
        source: "loader-1",
        target: "filter-caf",
        sourceHandle: "particle",
        targetHandle: "in"
      },
      {
        id: "e2",
        source: "loader-1",
        target: "filter-sol",
        sourceHandle: "particle",
        targetHandle: "in"
      },
      {
        id: "e3",
        source: "filter-caf",
        target: "modify-caf",
        sourceHandle: "out",
        targetHandle: "in"
      },
      {
        id: "e4",
        source: "filter-sol",
        target: "modify-sol",
        sourceHandle: "out",
        targetHandle: "in"
      },
      {
        id: "e5",
        source: "modify-sol",
        target: "viewport-1",
        sourceHandle: "out",
        targetHandle: "particle"
      },
      {
        id: "e6",
        source: "loader-1",
        target: "addbond-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e7",
        source: "addbond-1",
        target: "filter-bond-sol",
        sourceHandle: "bond",
        targetHandle: "in"
      },
      {
        id: "e7b",
        source: "filter-bond-sol",
        target: "modify-bond-sol",
        sourceHandle: "out",
        targetHandle: "in"
      },
      {
        id: "e7c",
        source: "modify-bond-sol",
        target: "viewport-1",
        sourceHandle: "out",
        targetHandle: "bond"
      },
      {
        id: "e8",
        source: "loader-1",
        target: "viewport-1",
        sourceHandle: "cell",
        targetHandle: "cell"
      },
      {
        id: "e9",
        source: "loader-1",
        target: "traj-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e10",
        source: "traj-1",
        target: "viewport-1",
        sourceHandle: "trajectory",
        targetHandle: "trajectory"
      },
      {
        id: "e11",
        source: "modify-caf",
        target: "viewport-1",
        sourceHandle: "out",
        targetHandle: "particle"
      },
      {
        id: "e12",
        source: "filter-caf",
        target: "labels-1",
        sourceHandle: "out",
        targetHandle: "particle"
      },
      {
        id: "e13",
        source: "labels-1",
        target: "viewport-1",
        sourceHandle: "label",
        targetHandle: "label"
      }
    ]
  };
}
function R5() {
  return {
    nodes: [
      {
        id: "loader-1",
        type: "load_structure",
        position: { x: 425, y: 0 },
        data: {
          params: {
            type: "load_structure",
            fileName: "",
            hasTrajectory: !1,
            hasCell: !1
          },
          enabled: !0
        }
      },
      {
        id: "addbond-1",
        type: "add_bond",
        position: { x: 425, y: 255 },
        data: {
          params: {
            type: "add_bond",
            bondSource: "structure"
          },
          enabled: !0
        }
      },
      {
        id: "viewport-1",
        type: "viewport",
        position: { x: 425, y: 510 },
        data: {
          params: {
            type: "viewport",
            perspective: !1,
            cellAxesVisible: !0
          },
          enabled: !0
        }
      }
    ],
    edges: [
      {
        id: "e1",
        source: "loader-1",
        target: "addbond-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e2",
        source: "addbond-1",
        target: "viewport-1",
        sourceHandle: "bond",
        targetHandle: "bond"
      },
      {
        id: "e3",
        source: "loader-1",
        target: "viewport-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e4",
        source: "loader-1",
        target: "viewport-1",
        sourceHandle: "cell",
        targetHandle: "cell"
      }
    ]
  };
}
function D5() {
  return {
    nodes: [
      {
        id: "loader-1",
        type: "load_structure",
        position: { x: 425, y: 0 },
        data: {
          params: {
            type: "load_structure",
            fileName: "protein.pdb",
            hasTrajectory: !1,
            hasCell: !1
          },
          enabled: !0
        }
      },
      {
        id: "addbond-1",
        type: "add_bond",
        position: { x: 425, y: 255 },
        data: {
          params: {
            type: "add_bond",
            bondSource: "structure"
          },
          enabled: !0
        }
      },
      {
        id: "filter-1",
        type: "filter",
        position: { x: 85, y: 425 },
        data: {
          params: {
            type: "filter",
            query: 'element == "C"'
          },
          enabled: !0
        }
      },
      {
        id: "modify-1",
        type: "modify",
        position: { x: 85, y: 765 },
        data: {
          params: {
            type: "modify",
            scale: 1.5,
            opacity: 0.8
          },
          enabled: !0
        }
      },
      {
        id: "filter-2",
        type: "filter",
        position: { x: 765, y: 425 },
        data: {
          params: {
            type: "filter",
            query: 'element == "N"'
          },
          enabled: !0
        }
      },
      {
        id: "modify-2",
        type: "modify",
        position: { x: 765, y: 765 },
        data: {
          params: {
            type: "modify",
            scale: 0.5,
            opacity: 0.6
          },
          enabled: !0
        }
      },
      {
        id: "viewport-1",
        type: "viewport",
        position: { x: 425, y: 1190 },
        data: {
          params: {
            type: "viewport",
            perspective: !1,
            cellAxesVisible: !0
          },
          enabled: !0
        }
      }
    ],
    edges: [
      {
        id: "e1",
        source: "loader-1",
        target: "filter-1",
        sourceHandle: "particle",
        targetHandle: "in"
      },
      { id: "e2", source: "filter-1", target: "modify-1", sourceHandle: "out", targetHandle: "in" },
      {
        id: "e3",
        source: "loader-1",
        target: "filter-2",
        sourceHandle: "particle",
        targetHandle: "in"
      },
      { id: "e4", source: "filter-2", target: "modify-2", sourceHandle: "out", targetHandle: "in" },
      {
        id: "e5",
        source: "modify-1",
        target: "viewport-1",
        sourceHandle: "out",
        targetHandle: "particle"
      },
      {
        id: "e6",
        source: "modify-2",
        target: "viewport-1",
        sourceHandle: "out",
        targetHandle: "particle"
      },
      {
        id: "e7",
        source: "loader-1",
        target: "addbond-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e8",
        source: "addbond-1",
        target: "viewport-1",
        sourceHandle: "bond",
        targetHandle: "bond"
      }
    ]
  };
}
function N5() {
  return {
    nodes: [
      {
        id: "loader-1",
        type: "load_structure",
        position: { x: 425, y: 0 },
        data: {
          params: {
            type: "load_structure",
            fileName: "caffeine_water.pdb",
            hasTrajectory: !1,
            hasCell: !0
          },
          enabled: !0
        }
      },
      {
        id: "traj-1",
        type: "load_trajectory",
        position: { x: 85, y: 310 },
        data: {
          params: {
            type: "load_trajectory",
            fileName: "caffeine_water_vibration.xtc"
          },
          enabled: !0
        }
      },
      {
        id: "addbond-1",
        type: "add_bond",
        position: { x: 425, y: 310 },
        data: {
          params: {
            type: "add_bond",
            bondSource: "structure"
          },
          enabled: !0
        }
      },
      {
        id: "viewport-1",
        type: "viewport",
        position: { x: 425, y: 615 },
        data: {
          params: {
            type: "viewport",
            perspective: !1,
            cellAxesVisible: !0
          },
          enabled: !0
        }
      }
    ],
    edges: [
      {
        id: "e1",
        source: "loader-1",
        target: "addbond-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e2",
        source: "loader-1",
        target: "traj-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e3",
        source: "loader-1",
        target: "viewport-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e4",
        source: "loader-1",
        target: "viewport-1",
        sourceHandle: "cell",
        targetHandle: "cell"
      },
      {
        id: "e5",
        source: "addbond-1",
        target: "viewport-1",
        sourceHandle: "bond",
        targetHandle: "bond"
      },
      {
        id: "e6",
        source: "traj-1",
        target: "viewport-1",
        sourceHandle: "trajectory",
        targetHandle: "trajectory"
      }
    ]
  };
}
function O5() {
  return {
    nodes: [
      {
        id: "loader-1",
        type: "load_structure",
        position: { x: 425, y: 0 },
        data: {
          params: {
            type: "load_structure",
            fileName: "perovskite_srtio3_3x3x3.xyz",
            hasTrajectory: !1,
            hasCell: !0
          },
          enabled: !0
        }
      },
      {
        id: "addbond-1",
        type: "add_bond",
        position: { x: 170, y: 310 },
        data: {
          params: {
            type: "add_bond",
            bondSource: "distance"
          },
          enabled: !0
        }
      },
      {
        id: "polyhedron-1",
        type: "polyhedron_generator",
        position: { x: 680, y: 310 },
        data: {
          params: {
            type: "polyhedron_generator",
            centerElements: [22],
            // Ti
            ligandElements: [8],
            // O
            maxDistance: 2.5,
            opacity: 0.5,
            showEdges: !1,
            edgeColor: "#dddddd",
            edgeWidth: 3
          },
          enabled: !0
        }
      },
      {
        id: "viewport-1",
        type: "viewport",
        position: { x: 425, y: 615 },
        data: {
          params: {
            type: "viewport",
            perspective: !1,
            cellAxesVisible: !0
          },
          enabled: !0
        }
      }
    ],
    edges: [
      {
        id: "e1",
        source: "loader-1",
        target: "addbond-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e2",
        source: "loader-1",
        target: "polyhedron-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e3",
        source: "loader-1",
        target: "viewport-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e4",
        source: "loader-1",
        target: "viewport-1",
        sourceHandle: "cell",
        targetHandle: "cell"
      },
      {
        id: "e5",
        source: "addbond-1",
        target: "viewport-1",
        sourceHandle: "bond",
        targetHandle: "bond"
      },
      {
        id: "e6",
        source: "polyhedron-1",
        target: "viewport-1",
        sourceHandle: "mesh",
        targetHandle: "mesh"
      }
    ]
  };
}
function L5() {
  return {
    nodes: [
      {
        id: "streaming-1",
        type: "streaming",
        position: { x: 425, y: 0 },
        data: {
          params: {
            type: "streaming",
            connected: !1
          },
          enabled: !0
        }
      },
      {
        id: "viewport-1",
        type: "viewport",
        position: { x: 425, y: 310 },
        data: {
          params: {
            type: "viewport",
            perspective: !1,
            cellAxesVisible: !0
          },
          enabled: !0
        }
      }
    ],
    edges: [
      {
        id: "e1",
        source: "streaming-1",
        target: "viewport-1",
        sourceHandle: "particle",
        targetHandle: "particle"
      },
      {
        id: "e2",
        source: "streaming-1",
        target: "viewport-1",
        sourceHandle: "bond",
        targetHandle: "bond"
      },
      {
        id: "e3",
        source: "streaming-1",
        target: "viewport-1",
        sourceHandle: "trajectory",
        targetHandle: "trajectory"
      },
      {
        id: "e4",
        source: "streaming-1",
        target: "viewport-1",
        sourceHandle: "cell",
        targetHandle: "cell"
      }
    ]
  };
}
const U5 = [
  {
    id: "molecule",
    label: "Molecule",
    description: "Caffeine with bonds and trajectory",
    create: N5
  },
  {
    id: "solid",
    label: "Solid",
    description: "Perovskite with coordination polyhedra",
    create: O5
  },
  {
    id: "streaming",
    label: "Streaming",
    description: "WebSocket streaming with bonds",
    create: L5
  }
];
var qe = (n, t) => () => (t || n((t = { exports: {} }).exports, t), t.exports), os = qe((n, t) => {
  var e = Object.defineProperty, s = (H, U, V) => U in H ? e(H, U, { enumerable: !0, configurable: !0, writable: !0, value: V }) : H[U] = V, a = (H, U) => () => (U || H((U = { exports: {} }).exports, U), U.exports), o = (H, U, V) => s(H, typeof U != "symbol" ? U + "" : U, V), c = a((H, U) => {
    var V = "\0", N = "\0", I = "", k = class {
      constructor($) {
        o(this, "_isDirected", !0), o(this, "_isMultigraph", !1), o(this, "_isCompound", !1), o(this, "_label"), o(this, "_defaultNodeLabelFn", () => {
        }), o(this, "_defaultEdgeLabelFn", () => {
        }), o(this, "_nodes", {}), o(this, "_in", {}), o(this, "_preds", {}), o(this, "_out", {}), o(this, "_sucs", {}), o(this, "_edgeObjs", {}), o(this, "_edgeLabels", {}), o(this, "_nodeCount", 0), o(this, "_edgeCount", 0), o(this, "_parent"), o(this, "_children"), $ && (this._isDirected = Object.hasOwn($, "directed") ? $.directed : !0, this._isMultigraph = Object.hasOwn($, "multigraph") ? $.multigraph : !1, this._isCompound = Object.hasOwn($, "compound") ? $.compound : !1), this._isCompound && (this._parent = {}, this._children = {}, this._children[N] = {});
      }
      isDirected() {
        return this._isDirected;
      }
      isMultigraph() {
        return this._isMultigraph;
      }
      isCompound() {
        return this._isCompound;
      }
      setGraph($) {
        return this._label = $, this;
      }
      graph() {
        return this._label;
      }
      setDefaultNodeLabel($) {
        return this._defaultNodeLabelFn = $, typeof $ != "function" && (this._defaultNodeLabelFn = () => $), this;
      }
      nodeCount() {
        return this._nodeCount;
      }
      nodes() {
        return Object.keys(this._nodes);
      }
      sources() {
        var $ = this;
        return this.nodes().filter((j) => Object.keys($._in[j]).length === 0);
      }
      sinks() {
        var $ = this;
        return this.nodes().filter((j) => Object.keys($._out[j]).length === 0);
      }
      setNodes($, j) {
        var Y = arguments, K = this;
        return $.forEach(function(J) {
          Y.length > 1 ? K.setNode(J, j) : K.setNode(J);
        }), this;
      }
      setNode($, j) {
        return Object.hasOwn(this._nodes, $) ? (arguments.length > 1 && (this._nodes[$] = j), this) : (this._nodes[$] = arguments.length > 1 ? j : this._defaultNodeLabelFn($), this._isCompound && (this._parent[$] = N, this._children[$] = {}, this._children[N][$] = !0), this._in[$] = {}, this._preds[$] = {}, this._out[$] = {}, this._sucs[$] = {}, ++this._nodeCount, this);
      }
      node($) {
        return this._nodes[$];
      }
      hasNode($) {
        return Object.hasOwn(this._nodes, $);
      }
      removeNode($) {
        var j = this;
        if (Object.hasOwn(this._nodes, $)) {
          var Y = (K) => j.removeEdge(j._edgeObjs[K]);
          delete this._nodes[$], this._isCompound && (this._removeFromParentsChildList($), delete this._parent[$], this.children($).forEach(function(K) {
            j.setParent(K);
          }), delete this._children[$]), Object.keys(this._in[$]).forEach(Y), delete this._in[$], delete this._preds[$], Object.keys(this._out[$]).forEach(Y), delete this._out[$], delete this._sucs[$], --this._nodeCount;
        }
        return this;
      }
      setParent($, j) {
        if (!this._isCompound) throw new Error("Cannot set parent in a non-compound graph");
        if (j === void 0) j = N;
        else {
          j += "";
          for (var Y = j; Y !== void 0; Y = this.parent(Y)) if (Y === $) throw new Error("Setting " + j + " as parent of " + $ + " would create a cycle");
          this.setNode(j);
        }
        return this.setNode($), this._removeFromParentsChildList($), this._parent[$] = j, this._children[j][$] = !0, this;
      }
      _removeFromParentsChildList($) {
        delete this._children[this._parent[$]][$];
      }
      parent($) {
        if (this._isCompound) {
          var j = this._parent[$];
          if (j !== N) return j;
        }
      }
      children($ = N) {
        if (this._isCompound) {
          var j = this._children[$];
          if (j) return Object.keys(j);
        } else {
          if ($ === N) return this.nodes();
          if (this.hasNode($)) return [];
        }
      }
      predecessors($) {
        var j = this._preds[$];
        if (j) return Object.keys(j);
      }
      successors($) {
        var j = this._sucs[$];
        if (j) return Object.keys(j);
      }
      neighbors($) {
        var j = this.predecessors($);
        if (j) {
          let K = new Set(j);
          for (var Y of this.successors($)) K.add(Y);
          return Array.from(K.values());
        }
      }
      isLeaf($) {
        var j;
        return this.isDirected() ? j = this.successors($) : j = this.neighbors($), j.length === 0;
      }
      filterNodes($) {
        var j = new this.constructor({ directed: this._isDirected, multigraph: this._isMultigraph, compound: this._isCompound });
        j.setGraph(this.graph());
        var Y = this;
        Object.entries(this._nodes).forEach(function([rt, dt]) {
          $(rt) && j.setNode(rt, dt);
        }), Object.values(this._edgeObjs).forEach(function(rt) {
          j.hasNode(rt.v) && j.hasNode(rt.w) && j.setEdge(rt, Y.edge(rt));
        });
        var K = {};
        function J(rt) {
          var dt = Y.parent(rt);
          return dt === void 0 || j.hasNode(dt) ? (K[rt] = dt, dt) : dt in K ? K[dt] : J(dt);
        }
        return this._isCompound && j.nodes().forEach((rt) => j.setParent(rt, J(rt))), j;
      }
      setDefaultEdgeLabel($) {
        return this._defaultEdgeLabelFn = $, typeof $ != "function" && (this._defaultEdgeLabelFn = () => $), this;
      }
      edgeCount() {
        return this._edgeCount;
      }
      edges() {
        return Object.values(this._edgeObjs);
      }
      setPath($, j) {
        var Y = this, K = arguments;
        return $.reduce(function(J, rt) {
          return K.length > 1 ? Y.setEdge(J, rt, j) : Y.setEdge(J, rt), rt;
        }), this;
      }
      setEdge() {
        var $, j, Y, K, J = !1, rt = arguments[0];
        typeof rt == "object" && rt !== null && "v" in rt ? ($ = rt.v, j = rt.w, Y = rt.name, arguments.length === 2 && (K = arguments[1], J = !0)) : ($ = rt, j = arguments[1], Y = arguments[3], arguments.length > 2 && (K = arguments[2], J = !0)), $ = "" + $, j = "" + j, Y !== void 0 && (Y = "" + Y);
        var dt = F(this._isDirected, $, j, Y);
        if (Object.hasOwn(this._edgeLabels, dt)) return J && (this._edgeLabels[dt] = K), this;
        if (Y !== void 0 && !this._isMultigraph) throw new Error("Cannot set a named edge when isMultigraph = false");
        this.setNode($), this.setNode(j), this._edgeLabels[dt] = J ? K : this._defaultEdgeLabelFn($, j, Y);
        var yt = W(this._isDirected, $, j, Y);
        return $ = yt.v, j = yt.w, Object.freeze(yt), this._edgeObjs[dt] = yt, X(this._preds[j], $), X(this._sucs[$], j), this._in[j][dt] = yt, this._out[$][dt] = yt, this._edgeCount++, this;
      }
      edge($, j, Y) {
        var K = arguments.length === 1 ? et(this._isDirected, arguments[0]) : F(this._isDirected, $, j, Y);
        return this._edgeLabels[K];
      }
      edgeAsObj() {
        let $ = this.edge(...arguments);
        return typeof $ != "object" ? { label: $ } : $;
      }
      hasEdge($, j, Y) {
        var K = arguments.length === 1 ? et(this._isDirected, arguments[0]) : F(this._isDirected, $, j, Y);
        return Object.hasOwn(this._edgeLabels, K);
      }
      removeEdge($, j, Y) {
        var K = arguments.length === 1 ? et(this._isDirected, arguments[0]) : F(this._isDirected, $, j, Y), J = this._edgeObjs[K];
        return J && ($ = J.v, j = J.w, delete this._edgeLabels[K], delete this._edgeObjs[K], Q(this._preds[j], $), Q(this._sucs[$], j), delete this._in[j][K], delete this._out[$][K], this._edgeCount--), this;
      }
      inEdges($, j) {
        return this.isDirected() ? this.filterEdges(this._in[$], $, j) : this.nodeEdges($, j);
      }
      outEdges($, j) {
        return this.isDirected() ? this.filterEdges(this._out[$], $, j) : this.nodeEdges($, j);
      }
      nodeEdges($, j) {
        if ($ in this._nodes) return this.filterEdges({ ...this._in[$], ...this._out[$] }, $, j);
      }
      filterEdges($, j, Y) {
        if ($) {
          var K = Object.values($);
          return Y ? K.filter(function(J) {
            return J.v === j && J.w === Y || J.v === Y && J.w === j;
          }) : K;
        }
      }
    };
    function X($, j) {
      $[j] ? $[j]++ : $[j] = 1;
    }
    function Q($, j) {
      --$[j] || delete $[j];
    }
    function F($, j, Y, K) {
      var J = "" + j, rt = "" + Y;
      if (!$ && J > rt) {
        var dt = J;
        J = rt, rt = dt;
      }
      return J + I + rt + I + (K === void 0 ? V : K);
    }
    function W($, j, Y, K) {
      var J = "" + j, rt = "" + Y;
      if (!$ && J > rt) {
        var dt = J;
        J = rt, rt = dt;
      }
      var yt = { v: J, w: rt };
      return K && (yt.name = K), yt;
    }
    function et($, j) {
      return F($, j.v, j.w, j.name);
    }
    U.exports = k;
  }), u = a((H, U) => {
    U.exports = "3.0.2";
  }), d = a((H, U) => {
    U.exports = { Graph: c(), version: u() };
  }), h = a((H, U) => {
    var V = c();
    U.exports = { write: N, read: X };
    function N(Q) {
      var F = { options: { directed: Q.isDirected(), multigraph: Q.isMultigraph(), compound: Q.isCompound() }, nodes: I(Q), edges: k(Q) };
      return Q.graph() !== void 0 && (F.value = structuredClone(Q.graph())), F;
    }
    function I(Q) {
      return Q.nodes().map(function(F) {
        var W = Q.node(F), et = Q.parent(F), $ = { v: F };
        return W !== void 0 && ($.value = W), et !== void 0 && ($.parent = et), $;
      });
    }
    function k(Q) {
      return Q.edges().map(function(F) {
        var W = Q.edge(F), et = { v: F.v, w: F.w };
        return F.name !== void 0 && (et.name = F.name), W !== void 0 && (et.value = W), et;
      });
    }
    function X(Q) {
      var F = new V(Q.options).setGraph(Q.value);
      return Q.nodes.forEach(function(W) {
        F.setNode(W.v, W.value), W.parent && F.setParent(W.v, W.parent);
      }), Q.edges.forEach(function(W) {
        F.setEdge({ v: W.v, w: W.w, name: W.name }, W.value);
      }), F;
    }
  }), m = a((H, U) => {
    U.exports = N;
    var V = () => 1;
    function N(k, X, Q, F) {
      return I(k, String(X), Q || V, F || function(W) {
        return k.outEdges(W);
      });
    }
    function I(k, X, Q, F) {
      var W = {}, et = !0, $ = 0, j = k.nodes(), Y = function(dt) {
        var yt = Q(dt);
        W[dt.v].distance + yt < W[dt.w].distance && (W[dt.w] = { distance: W[dt.v].distance + yt, predecessor: dt.v }, et = !0);
      }, K = function() {
        j.forEach(function(dt) {
          F(dt).forEach(function(yt) {
            var Pt = yt.v === dt ? yt.v : yt.w, Lt = Pt === yt.v ? yt.w : yt.v;
            Y({ v: Pt, w: Lt });
          });
        });
      };
      j.forEach(function(dt) {
        var yt = dt === X ? 0 : Number.POSITIVE_INFINITY;
        W[dt] = { distance: yt };
      });
      for (var J = j.length, rt = 1; rt < J && (et = !1, $++, K(), !!et); rt++) ;
      if ($ === J - 1 && (et = !1, K(), et)) throw new Error("The graph contains a negative weight cycle");
      return W;
    }
  }), p = a((H, U) => {
    U.exports = V;
    function V(N) {
      var I = {}, k = [], X;
      function Q(F) {
        Object.hasOwn(I, F) || (I[F] = !0, X.push(F), N.successors(F).forEach(Q), N.predecessors(F).forEach(Q));
      }
      return N.nodes().forEach(function(F) {
        X = [], Q(F), X.length && k.push(X);
      }), k;
    }
  }), g = a((H, U) => {
    var V = class {
      constructor() {
        o(this, "_arr", []), o(this, "_keyIndices", {});
      }
      size() {
        return this._arr.length;
      }
      keys() {
        return this._arr.map(function(N) {
          return N.key;
        });
      }
      has(N) {
        return Object.hasOwn(this._keyIndices, N);
      }
      priority(N) {
        var I = this._keyIndices[N];
        if (I !== void 0) return this._arr[I].priority;
      }
      min() {
        if (this.size() === 0) throw new Error("Queue underflow");
        return this._arr[0].key;
      }
      add(N, I) {
        var k = this._keyIndices;
        if (N = String(N), !Object.hasOwn(k, N)) {
          var X = this._arr, Q = X.length;
          return k[N] = Q, X.push({ key: N, priority: I }), this._decrease(Q), !0;
        }
        return !1;
      }
      removeMin() {
        this._swap(0, this._arr.length - 1);
        var N = this._arr.pop();
        return delete this._keyIndices[N.key], this._heapify(0), N.key;
      }
      decrease(N, I) {
        var k = this._keyIndices[N];
        if (I > this._arr[k].priority) throw new Error("New priority is greater than current priority. Key: " + N + " Old: " + this._arr[k].priority + " New: " + I);
        this._arr[k].priority = I, this._decrease(k);
      }
      _heapify(N) {
        var I = this._arr, k = 2 * N, X = k + 1, Q = N;
        k < I.length && (Q = I[k].priority < I[Q].priority ? k : Q, X < I.length && (Q = I[X].priority < I[Q].priority ? X : Q), Q !== N && (this._swap(N, Q), this._heapify(Q)));
      }
      _decrease(N) {
        for (var I = this._arr, k = I[N].priority, X; N !== 0 && (X = N >> 1, !(I[X].priority < k)); ) this._swap(N, X), N = X;
      }
      _swap(N, I) {
        var k = this._arr, X = this._keyIndices, Q = k[N], F = k[I];
        k[N] = F, k[I] = Q, X[F.key] = N, X[Q.key] = I;
      }
    };
    U.exports = V;
  }), _ = a((H, U) => {
    var V = g();
    U.exports = I;
    var N = () => 1;
    function I(X, Q, F, W) {
      var et = function($) {
        return X.outEdges($);
      };
      return k(X, String(Q), F || N, W || et);
    }
    function k(X, Q, F, W) {
      var et = {}, $ = new V(), j, Y, K = function(J) {
        var rt = J.v !== j ? J.v : J.w, dt = et[rt], yt = F(J), Pt = Y.distance + yt;
        if (yt < 0) throw new Error("dijkstra does not allow negative edge weights. Bad edge: " + J + " Weight: " + yt);
        Pt < dt.distance && (dt.distance = Pt, dt.predecessor = j, $.decrease(rt, Pt));
      };
      for (X.nodes().forEach(function(J) {
        var rt = J === Q ? 0 : Number.POSITIVE_INFINITY;
        et[J] = { distance: rt }, $.add(J, rt);
      }); $.size() > 0 && (j = $.removeMin(), Y = et[j], Y.distance !== Number.POSITIVE_INFINITY); ) W(j).forEach(K);
      return et;
    }
  }), x = a((H, U) => {
    var V = _();
    U.exports = N;
    function N(I, k, X) {
      return I.nodes().reduce(function(Q, F) {
        return Q[F] = V(I, F, k, X), Q;
      }, {});
    }
  }), A = a((H, U) => {
    U.exports = V;
    function V(I, k, X) {
      if (I[k].predecessor !== void 0) throw new Error("Invalid source vertex");
      if (I[X].predecessor === void 0 && X !== k) throw new Error("Invalid destination vertex");
      return { weight: I[X].distance, path: N(I, k, X) };
    }
    function N(I, k, X) {
      for (var Q = [], F = X; F !== k; ) Q.push(F), F = I[F].predecessor;
      return Q.push(k), Q.reverse();
    }
  }), b = a((H, U) => {
    U.exports = V;
    function V(N) {
      var I = 0, k = [], X = {}, Q = [];
      function F(W) {
        var et = X[W] = { onStack: !0, lowlink: I, index: I++ };
        if (k.push(W), N.successors(W).forEach(function(Y) {
          Object.hasOwn(X, Y) ? X[Y].onStack && (et.lowlink = Math.min(et.lowlink, X[Y].index)) : (F(Y), et.lowlink = Math.min(et.lowlink, X[Y].lowlink));
        }), et.lowlink === et.index) {
          var $ = [], j;
          do
            j = k.pop(), X[j].onStack = !1, $.push(j);
          while (W !== j);
          Q.push($);
        }
      }
      return N.nodes().forEach(function(W) {
        Object.hasOwn(X, W) || F(W);
      }), Q;
    }
  }), y = a((H, U) => {
    var V = b();
    U.exports = N;
    function N(I) {
      return V(I).filter(function(k) {
        return k.length > 1 || k.length === 1 && I.hasEdge(k[0], k[0]);
      });
    }
  }), E = a((H, U) => {
    U.exports = N;
    var V = () => 1;
    function N(k, X, Q) {
      return I(k, X || V, Q || function(F) {
        return k.outEdges(F);
      });
    }
    function I(k, X, Q) {
      var F = {}, W = k.nodes();
      return W.forEach(function(et) {
        F[et] = {}, F[et][et] = { distance: 0 }, W.forEach(function($) {
          et !== $ && (F[et][$] = { distance: Number.POSITIVE_INFINITY });
        }), Q(et).forEach(function($) {
          var j = $.v === et ? $.w : $.v, Y = X($);
          F[et][j] = { distance: Y, predecessor: et };
        });
      }), W.forEach(function(et) {
        var $ = F[et];
        W.forEach(function(j) {
          var Y = F[j];
          W.forEach(function(K) {
            var J = Y[et], rt = $[K], dt = Y[K], yt = J.distance + rt.distance;
            yt < dt.distance && (dt.distance = yt, dt.predecessor = rt.predecessor);
          });
        });
      }), F;
    }
  }), w = a((H, U) => {
    function V(I) {
      var k = {}, X = {}, Q = [];
      function F(W) {
        if (Object.hasOwn(X, W)) throw new N();
        Object.hasOwn(k, W) || (X[W] = !0, k[W] = !0, I.predecessors(W).forEach(F), delete X[W], Q.push(W));
      }
      if (I.sinks().forEach(F), Object.keys(k).length !== I.nodeCount()) throw new N();
      return Q;
    }
    var N = class extends Error {
      constructor() {
        super(...arguments);
      }
    };
    U.exports = V, V.CycleException = N;
  }), M = a((H, U) => {
    var V = w();
    U.exports = N;
    function N(I) {
      try {
        V(I);
      } catch (k) {
        if (k instanceof V.CycleException) return !1;
        throw k;
      }
      return !0;
    }
  }), O = a((H, U) => {
    U.exports = V;
    function V(I, k, X, Q, F) {
      Array.isArray(k) || (k = [k]);
      var W = (I.isDirected() ? I.successors : I.neighbors).bind(I), et = {};
      return k.forEach(function($) {
        if (!I.hasNode($)) throw new Error("Graph does not have node: " + $);
        F = N(I, $, X === "post", et, W, Q, F);
      }), F;
    }
    function N(I, k, X, Q, F, W, et) {
      return Object.hasOwn(Q, k) || (Q[k] = !0, X || (et = W(et, k)), F(k).forEach(function($) {
        et = N(I, $, X, Q, F, W, et);
      }), X && (et = W(et, k))), et;
    }
  }), C = a((H, U) => {
    var V = O();
    U.exports = N;
    function N(I, k, X) {
      return V(I, k, X, function(Q, F) {
        return Q.push(F), Q;
      }, []);
    }
  }), D = a((H, U) => {
    var V = C();
    U.exports = N;
    function N(I, k) {
      return V(I, k, "post");
    }
  }), T = a((H, U) => {
    var V = C();
    U.exports = N;
    function N(I, k) {
      return V(I, k, "pre");
    }
  }), L = a((H, U) => {
    var V = c(), N = g();
    U.exports = I;
    function I(k, X) {
      var Q = new V(), F = {}, W = new N(), et;
      function $(Y) {
        var K = Y.v === et ? Y.w : Y.v, J = W.priority(K);
        if (J !== void 0) {
          var rt = X(Y);
          rt < J && (F[K] = et, W.decrease(K, rt));
        }
      }
      if (k.nodeCount() === 0) return Q;
      k.nodes().forEach(function(Y) {
        W.add(Y, Number.POSITIVE_INFINITY), Q.setNode(Y);
      }), W.decrease(k.nodes()[0], 0);
      for (var j = !1; W.size() > 0; ) {
        if (et = W.removeMin(), Object.hasOwn(F, et)) Q.setEdge(et, F[et]);
        else {
          if (j) throw new Error("Input graph is not connected: " + k);
          j = !0;
        }
        k.nodeEdges(et).forEach($);
      }
      return Q;
    }
  }), z = a((H, U) => {
    var V = _(), N = m();
    U.exports = I;
    function I(X, Q, F, W) {
      return k(X, Q, F, W || function(et) {
        return X.outEdges(et);
      });
    }
    function k(X, Q, F, W) {
      if (F === void 0) return V(X, Q, F, W);
      for (var et = !1, $ = X.nodes(), j = 0; j < $.length; j++) {
        for (var Y = W($[j]), K = 0; K < Y.length; K++) {
          var J = Y[K], rt = J.v === $[j] ? J.v : J.w, dt = rt === J.v ? J.w : J.v;
          F({ v: rt, w: dt }) < 0 && (et = !0);
        }
        if (et) return N(X, Q, F, W);
      }
      return V(X, Q, F, W);
    }
  }), R = a((H, U) => {
    U.exports = { bellmanFord: m(), components: p(), dijkstra: _(), dijkstraAll: x(), extractPath: A(), findCycles: y(), floydWarshall: E(), isAcyclic: M(), postorder: D(), preorder: T(), prim: L(), shortestPaths: z(), reduce: O(), tarjan: b(), topsort: w() };
  }), B = d();
  t.exports = { Graph: B.Graph, json: h(), alg: R(), version: B.version };
}), P5 = qe((n, t) => {
  var e = class {
    constructor() {
      let o = {};
      o._next = o._prev = o, this._sentinel = o;
    }
    dequeue() {
      let o = this._sentinel, c = o._prev;
      if (c !== o) return s(c), c;
    }
    enqueue(o) {
      let c = this._sentinel;
      o._prev && o._next && s(o), o._next = c._next, c._next._prev = o, c._next = o, o._prev = c;
    }
    toString() {
      let o = [], c = this._sentinel, u = c._prev;
      for (; u !== c; ) o.push(JSON.stringify(u, a)), u = u._prev;
      return "[" + o.join(", ") + "]";
    }
  };
  function s(o) {
    o._prev._next = o._next, o._next._prev = o._prev, delete o._next, delete o._prev;
  }
  function a(o, c) {
    if (o !== "_next" && o !== "_prev") return c;
  }
  t.exports = e;
}), I5 = qe((n, t) => {
  var e = os().Graph, s = P5();
  t.exports = o;
  var a = () => 1;
  function o(p, g) {
    if (p.nodeCount() <= 1) return [];
    let _ = d(p, g || a);
    return c(_.graph, _.buckets, _.zeroIdx).flatMap((x) => p.outEdges(x.v, x.w));
  }
  function c(p, g, _) {
    let x = [], A = g[g.length - 1], b = g[0], y;
    for (; p.nodeCount(); ) {
      for (; y = b.dequeue(); ) u(p, g, _, y);
      for (; y = A.dequeue(); ) u(p, g, _, y);
      if (p.nodeCount()) {
        for (let E = g.length - 2; E > 0; --E) if (y = g[E].dequeue(), y) {
          x = x.concat(u(p, g, _, y, !0));
          break;
        }
      }
    }
    return x;
  }
  function u(p, g, _, x, A) {
    let b = A ? [] : void 0;
    return p.inEdges(x.v).forEach((y) => {
      let E = p.edge(y), w = p.node(y.v);
      A && b.push({ v: y.v, w: y.w }), w.out -= E, h(g, _, w);
    }), p.outEdges(x.v).forEach((y) => {
      let E = p.edge(y), w = y.w, M = p.node(w);
      M.in -= E, h(g, _, M);
    }), p.removeNode(x.v), b;
  }
  function d(p, g) {
    let _ = new e(), x = 0, A = 0;
    p.nodes().forEach((E) => {
      _.setNode(E, { v: E, in: 0, out: 0 });
    }), p.edges().forEach((E) => {
      let w = _.edge(E.v, E.w) || 0, M = g(E), O = w + M;
      _.setEdge(E.v, E.w, O), A = Math.max(A, _.node(E.v).out += M), x = Math.max(x, _.node(E.w).in += M);
    });
    let b = m(A + x + 3).map(() => new s()), y = x + 1;
    return _.nodes().forEach((E) => {
      h(b, y, _.node(E));
    }), { graph: _, buckets: b, zeroIdx: y };
  }
  function h(p, g, _) {
    _.out ? _.in ? p[_.out - _.in + g].enqueue(_) : p[p.length - 1].enqueue(_) : p[0].enqueue(_);
  }
  function m(p) {
    let g = [];
    for (let _ = 0; _ < p; _++) g.push(_);
    return g;
  }
}), Cn = qe((n, t) => {
  var e = os().Graph;
  t.exports = { addBorderNode: g, addDummyNode: s, applyWithChunking: A, asNonCompoundGraph: o, buildLayerMatrix: h, intersectRect: d, mapValues: T, maxRank: b, normalizeRanks: m, notime: w, partition: y, pick: D, predecessorWeights: u, range: C, removeEmptyRanks: p, simplify: a, successorWeights: c, time: E, uniqueId: O, zipObject: L };
  function s(z, R, B, H) {
    for (var U = H; z.hasNode(U); ) U = O(H);
    return B.dummy = R, z.setNode(U, B), U;
  }
  function a(z) {
    let R = new e().setGraph(z.graph());
    return z.nodes().forEach((B) => R.setNode(B, z.node(B))), z.edges().forEach((B) => {
      let H = R.edge(B.v, B.w) || { weight: 0, minlen: 1 }, U = z.edge(B);
      R.setEdge(B.v, B.w, { weight: H.weight + U.weight, minlen: Math.max(H.minlen, U.minlen) });
    }), R;
  }
  function o(z) {
    let R = new e({ multigraph: z.isMultigraph() }).setGraph(z.graph());
    return z.nodes().forEach((B) => {
      z.children(B).length || R.setNode(B, z.node(B));
    }), z.edges().forEach((B) => {
      R.setEdge(B, z.edge(B));
    }), R;
  }
  function c(z) {
    let R = z.nodes().map((B) => {
      let H = {};
      return z.outEdges(B).forEach((U) => {
        H[U.w] = (H[U.w] || 0) + z.edge(U).weight;
      }), H;
    });
    return L(z.nodes(), R);
  }
  function u(z) {
    let R = z.nodes().map((B) => {
      let H = {};
      return z.inEdges(B).forEach((U) => {
        H[U.v] = (H[U.v] || 0) + z.edge(U).weight;
      }), H;
    });
    return L(z.nodes(), R);
  }
  function d(z, R) {
    let B = z.x, H = z.y, U = R.x - B, V = R.y - H, N = z.width / 2, I = z.height / 2;
    if (!U && !V) throw new Error("Not possible to find intersection inside of the rectangle");
    let k, X;
    return Math.abs(V) * N > Math.abs(U) * I ? (V < 0 && (I = -I), k = I * U / V, X = I) : (U < 0 && (N = -N), k = N, X = N * V / U), { x: B + k, y: H + X };
  }
  function h(z) {
    let R = C(b(z) + 1).map(() => []);
    return z.nodes().forEach((B) => {
      let H = z.node(B), U = H.rank;
      U !== void 0 && (R[U][H.order] = B);
    }), R;
  }
  function m(z) {
    let R = z.nodes().map((H) => {
      let U = z.node(H).rank;
      return U === void 0 ? Number.MAX_VALUE : U;
    }), B = A(Math.min, R);
    z.nodes().forEach((H) => {
      let U = z.node(H);
      Object.hasOwn(U, "rank") && (U.rank -= B);
    });
  }
  function p(z) {
    let R = z.nodes().map((N) => z.node(N).rank).filter((N) => N !== void 0), B = A(Math.min, R), H = [];
    z.nodes().forEach((N) => {
      let I = z.node(N).rank - B;
      H[I] || (H[I] = []), H[I].push(N);
    });
    let U = 0, V = z.graph().nodeRankFactor;
    Array.from(H).forEach((N, I) => {
      N === void 0 && I % V !== 0 ? --U : N !== void 0 && U && N.forEach((k) => z.node(k).rank += U);
    });
  }
  function g(z, R, B, H) {
    let U = { width: 0, height: 0 };
    return arguments.length >= 4 && (U.rank = B, U.order = H), s(z, "border", U, R);
  }
  function _(z, R = x) {
    let B = [];
    for (let H = 0; H < z.length; H += R) {
      let U = z.slice(H, H + R);
      B.push(U);
    }
    return B;
  }
  var x = 65535;
  function A(z, R) {
    if (R.length > x) {
      let B = _(R);
      return z.apply(null, B.map((H) => z.apply(null, H)));
    } else return z.apply(null, R);
  }
  function b(z) {
    let R = z.nodes().map((B) => {
      let H = z.node(B).rank;
      return H === void 0 ? Number.MIN_VALUE : H;
    });
    return A(Math.max, R);
  }
  function y(z, R) {
    let B = { lhs: [], rhs: [] };
    return z.forEach((H) => {
      R(H) ? B.lhs.push(H) : B.rhs.push(H);
    }), B;
  }
  function E(z, R) {
    let B = Date.now();
    try {
      return R();
    } finally {
      console.log(z + " time: " + (Date.now() - B) + "ms");
    }
  }
  function w(z, R) {
    return R();
  }
  var M = 0;
  function O(z) {
    var R = ++M;
    return z + ("" + R);
  }
  function C(z, R, B = 1) {
    R == null && (R = z, z = 0);
    let H = (V) => V < R;
    B < 0 && (H = (V) => R < V);
    let U = [];
    for (let V = z; H(V); V += B) U.push(V);
    return U;
  }
  function D(z, R) {
    let B = {};
    for (let H of R) z[H] !== void 0 && (B[H] = z[H]);
    return B;
  }
  function T(z, R) {
    let B = R;
    return typeof R == "string" && (B = (H) => H[R]), Object.entries(z).reduce((H, [U, V]) => (H[U] = B(V, U), H), {});
  }
  function L(z, R) {
    return z.reduce((B, H, U) => (B[H] = R[U], B), {});
  }
}), B5 = qe((n, t) => {
  var e = I5(), s = Cn().uniqueId;
  t.exports = { run: a, undo: c };
  function a(u) {
    (u.graph().acyclicer === "greedy" ? e(u, d(u)) : o(u)).forEach((h) => {
      let m = u.edge(h);
      u.removeEdge(h), m.forwardName = h.name, m.reversed = !0, u.setEdge(h.w, h.v, m, s("rev"));
    });
    function d(h) {
      return (m) => h.edge(m).weight;
    }
  }
  function o(u) {
    let d = [], h = {}, m = {};
    function p(g) {
      Object.hasOwn(m, g) || (m[g] = !0, h[g] = !0, u.outEdges(g).forEach((_) => {
        Object.hasOwn(h, _.w) ? d.push(_) : p(_.w);
      }), delete h[g]);
    }
    return u.nodes().forEach(p), d;
  }
  function c(u) {
    u.edges().forEach((d) => {
      let h = u.edge(d);
      if (h.reversed) {
        u.removeEdge(d);
        let m = h.forwardName;
        delete h.reversed, delete h.forwardName, u.setEdge(d.w, d.v, h, m);
      }
    });
  }
}), z5 = qe((n, t) => {
  var e = Cn();
  t.exports = { run: s, undo: o };
  function s(c) {
    c.graph().dummyChains = [], c.edges().forEach((u) => a(c, u));
  }
  function a(c, u) {
    let d = u.v, h = c.node(d).rank, m = u.w, p = c.node(m).rank, g = u.name, _ = c.edge(u), x = _.labelRank;
    if (p === h + 1) return;
    c.removeEdge(u);
    let A, b, y;
    for (y = 0, ++h; h < p; ++y, ++h) _.points = [], b = { width: 0, height: 0, edgeLabel: _, edgeObj: u, rank: h }, A = e.addDummyNode(c, "edge", b, "_d"), h === x && (b.width = _.width, b.height = _.height, b.dummy = "edge-label", b.labelpos = _.labelpos), c.setEdge(d, A, { weight: _.weight }, g), y === 0 && c.graph().dummyChains.push(A), d = A;
    c.setEdge(d, m, { weight: _.weight }, g);
  }
  function o(c) {
    c.graph().dummyChains.forEach((u) => {
      let d = c.node(u), h = d.edgeLabel, m;
      for (c.setEdge(d.edgeObj, h); d.dummy; ) m = c.successors(u)[0], c.removeNode(u), h.points.push({ x: d.x, y: d.y }), d.dummy === "edge-label" && (h.x = d.x, h.y = d.y, h.width = d.width, h.height = d.height), u = m, d = c.node(u);
    });
  }
}), Xd = qe((n, t) => {
  var { applyWithChunking: e } = Cn();
  t.exports = { longestPath: s, slack: a };
  function s(o) {
    var c = {};
    function u(d) {
      var h = o.node(d);
      if (Object.hasOwn(c, d)) return h.rank;
      c[d] = !0;
      let m = o.outEdges(d).map((g) => g == null ? Number.POSITIVE_INFINITY : u(g.w) - o.edge(g).minlen);
      var p = e(Math.min, m);
      return p === Number.POSITIVE_INFINITY && (p = 0), h.rank = p;
    }
    o.sources().forEach(u);
  }
  function a(o, c) {
    return o.node(c.w).rank - o.node(c.v).rank - o.edge(c).minlen;
  }
}), jw = qe((n, t) => {
  var e = os().Graph, s = Xd().slack;
  t.exports = a;
  function a(d) {
    var h = new e({ directed: !1 }), m = d.nodes()[0], p = d.nodeCount();
    h.setNode(m, {});
    for (var g, _; o(h, d) < p; ) g = c(h, d), _ = h.hasNode(g.v) ? s(d, g) : -s(d, g), u(h, d, _);
    return h;
  }
  function o(d, h) {
    function m(p) {
      h.nodeEdges(p).forEach((g) => {
        var _ = g.v, x = p === _ ? g.w : _;
        !d.hasNode(x) && !s(h, g) && (d.setNode(x, {}), d.setEdge(p, x, {}), m(x));
      });
    }
    return d.nodes().forEach(m), d.nodeCount();
  }
  function c(d, h) {
    return h.edges().reduce((m, p) => {
      let g = Number.POSITIVE_INFINITY;
      return d.hasNode(p.v) !== d.hasNode(p.w) && (g = s(h, p)), g < m[0] ? [g, p] : m;
    }, [Number.POSITIVE_INFINITY, null])[1];
  }
  function u(d, h, m) {
    d.nodes().forEach((p) => h.node(p).rank += m);
  }
}), F5 = qe((n, t) => {
  var e = jw(), s = Xd().slack, a = Xd().longestPath, o = os().alg.preorder, c = os().alg.postorder, u = Cn().simplify;
  t.exports = d, d.initLowLimValues = g, d.initCutValues = h, d.calcCutValue = p, d.leaveEdge = x, d.enterEdge = A, d.exchangeEdges = b;
  function d(M) {
    M = u(M), a(M);
    var O = e(M);
    g(O), h(O, M);
    for (var C, D; C = x(O); ) D = A(O, M, C), b(O, M, C, D);
  }
  function h(M, O) {
    var C = c(M, M.nodes());
    C = C.slice(0, C.length - 1), C.forEach((D) => m(M, O, D));
  }
  function m(M, O, C) {
    var D = M.node(C), T = D.parent;
    M.edge(C, T).cutvalue = p(M, O, C);
  }
  function p(M, O, C) {
    var D = M.node(C), T = D.parent, L = !0, z = O.edge(C, T), R = 0;
    return z || (L = !1, z = O.edge(T, C)), R = z.weight, O.nodeEdges(C).forEach((B) => {
      var H = B.v === C, U = H ? B.w : B.v;
      if (U !== T) {
        var V = H === L, N = O.edge(B).weight;
        if (R += V ? N : -N, E(M, C, U)) {
          var I = M.edge(C, U).cutvalue;
          R += V ? -I : I;
        }
      }
    }), R;
  }
  function g(M, O) {
    arguments.length < 2 && (O = M.nodes()[0]), _(M, {}, 1, O);
  }
  function _(M, O, C, D, T) {
    var L = C, z = M.node(D);
    return O[D] = !0, M.neighbors(D).forEach((R) => {
      Object.hasOwn(O, R) || (C = _(M, O, C, R, D));
    }), z.low = L, z.lim = C++, T ? z.parent = T : delete z.parent, C;
  }
  function x(M) {
    return M.edges().find((O) => M.edge(O).cutvalue < 0);
  }
  function A(M, O, C) {
    var D = C.v, T = C.w;
    O.hasEdge(D, T) || (D = C.w, T = C.v);
    var L = M.node(D), z = M.node(T), R = L, B = !1;
    L.lim > z.lim && (R = z, B = !0);
    var H = O.edges().filter((U) => B === w(M, M.node(U.v), R) && B !== w(M, M.node(U.w), R));
    return H.reduce((U, V) => s(O, V) < s(O, U) ? V : U);
  }
  function b(M, O, C, D) {
    var T = C.v, L = C.w;
    M.removeEdge(T, L), M.setEdge(D.v, D.w, {}), g(M), h(M, O), y(M, O);
  }
  function y(M, O) {
    var C = M.nodes().find((T) => !O.node(T).parent), D = o(M, C);
    D = D.slice(1), D.forEach((T) => {
      var L = M.node(T).parent, z = O.edge(T, L), R = !1;
      z || (z = O.edge(L, T), R = !0), O.node(T).rank = O.node(L).rank + (R ? z.minlen : -z.minlen);
    });
  }
  function E(M, O, C) {
    return M.hasEdge(O, C);
  }
  function w(M, O, C) {
    return C.low <= O.lim && O.lim <= C.lim;
  }
}), H5 = qe((n, t) => {
  var e = Xd(), s = e.longestPath, a = jw(), o = F5();
  t.exports = c;
  function c(m) {
    var p = m.graph().ranker;
    if (p instanceof Function) return p(m);
    switch (m.graph().ranker) {
      case "network-simplex":
        h(m);
        break;
      case "tight-tree":
        d(m);
        break;
      case "longest-path":
        u(m);
        break;
      case "none":
        break;
      default:
        h(m);
    }
  }
  var u = s;
  function d(m) {
    s(m), a(m);
  }
  function h(m) {
    o(m);
  }
}), V5 = qe((n, t) => {
  t.exports = e;
  function e(o) {
    let c = a(o);
    o.graph().dummyChains.forEach((u) => {
      let d = o.node(u), h = d.edgeObj, m = s(o, c, h.v, h.w), p = m.path, g = m.lca, _ = 0, x = p[_], A = !0;
      for (; u !== h.w; ) {
        if (d = o.node(u), A) {
          for (; (x = p[_]) !== g && o.node(x).maxRank < d.rank; ) _++;
          x === g && (A = !1);
        }
        if (!A) {
          for (; _ < p.length - 1 && o.node(x = p[_ + 1]).minRank <= d.rank; ) _++;
          x = p[_];
        }
        o.setParent(u, x), u = o.successors(u)[0];
      }
    });
  }
  function s(o, c, u, d) {
    let h = [], m = [], p = Math.min(c[u].low, c[d].low), g = Math.max(c[u].lim, c[d].lim), _, x;
    _ = u;
    do
      _ = o.parent(_), h.push(_);
    while (_ && (c[_].low > p || g > c[_].lim));
    for (x = _, _ = d; (_ = o.parent(_)) !== x; ) m.push(_);
    return { path: h.concat(m.reverse()), lca: x };
  }
  function a(o) {
    let c = {}, u = 0;
    function d(h) {
      let m = u;
      o.children(h).forEach(d), c[h] = { low: m, lim: u++ };
    }
    return o.children().forEach(d), c;
  }
}), G5 = qe((n, t) => {
  var e = Cn();
  t.exports = { run: s, cleanup: u };
  function s(d) {
    let h = e.addDummyNode(d, "root", {}, "_root"), m = o(d), p = Object.values(m), g = e.applyWithChunking(Math.max, p) - 1, _ = 2 * g + 1;
    d.graph().nestingRoot = h, d.edges().forEach((A) => d.edge(A).minlen *= _);
    let x = c(d) + 1;
    d.children().forEach((A) => a(d, h, _, x, g, m, A)), d.graph().nodeRankFactor = _;
  }
  function a(d, h, m, p, g, _, x) {
    let A = d.children(x);
    if (!A.length) {
      x !== h && d.setEdge(h, x, { weight: 0, minlen: m });
      return;
    }
    let b = e.addBorderNode(d, "_bt"), y = e.addBorderNode(d, "_bb"), E = d.node(x);
    d.setParent(b, x), E.borderTop = b, d.setParent(y, x), E.borderBottom = y, A.forEach((w) => {
      a(d, h, m, p, g, _, w);
      let M = d.node(w), O = M.borderTop ? M.borderTop : w, C = M.borderBottom ? M.borderBottom : w, D = M.borderTop ? p : 2 * p, T = O !== C ? 1 : g - _[x] + 1;
      d.setEdge(b, O, { weight: D, minlen: T, nestingEdge: !0 }), d.setEdge(C, y, { weight: D, minlen: T, nestingEdge: !0 });
    }), d.parent(x) || d.setEdge(h, b, { weight: 0, minlen: g + _[x] });
  }
  function o(d) {
    var h = {};
    function m(p, g) {
      var _ = d.children(p);
      _ && _.length && _.forEach((x) => m(x, g + 1)), h[p] = g;
    }
    return d.children().forEach((p) => m(p, 1)), h;
  }
  function c(d) {
    return d.edges().reduce((h, m) => h + d.edge(m).weight, 0);
  }
  function u(d) {
    var h = d.graph();
    d.removeNode(h.nestingRoot), delete h.nestingRoot, d.edges().forEach((m) => {
      var p = d.edge(m);
      p.nestingEdge && d.removeEdge(m);
    });
  }
}), k5 = qe((n, t) => {
  var e = Cn();
  t.exports = s;
  function s(o) {
    function c(u) {
      let d = o.children(u), h = o.node(u);
      if (d.length && d.forEach(c), Object.hasOwn(h, "minRank")) {
        h.borderLeft = [], h.borderRight = [];
        for (let m = h.minRank, p = h.maxRank + 1; m < p; ++m) a(o, "borderLeft", "_bl", u, h, m), a(o, "borderRight", "_br", u, h, m);
      }
    }
    o.children().forEach(c);
  }
  function a(o, c, u, d, h, m) {
    let p = { width: 0, height: 0, rank: m, borderType: c }, g = h[c][m - 1], _ = e.addDummyNode(o, "border", p, u);
    h[c][m] = _, o.setParent(_, d), g && o.setEdge(g, _, { weight: 1 });
  }
}), X5 = qe((n, t) => {
  t.exports = { adjust: e, undo: s };
  function e(m) {
    let p = m.graph().rankdir.toLowerCase();
    (p === "lr" || p === "rl") && a(m);
  }
  function s(m) {
    let p = m.graph().rankdir.toLowerCase();
    (p === "bt" || p === "rl") && c(m), (p === "lr" || p === "rl") && (d(m), a(m));
  }
  function a(m) {
    m.nodes().forEach((p) => o(m.node(p))), m.edges().forEach((p) => o(m.edge(p)));
  }
  function o(m) {
    let p = m.width;
    m.width = m.height, m.height = p;
  }
  function c(m) {
    m.nodes().forEach((p) => u(m.node(p))), m.edges().forEach((p) => {
      let g = m.edge(p);
      g.points.forEach(u), Object.hasOwn(g, "y") && u(g);
    });
  }
  function u(m) {
    m.y = -m.y;
  }
  function d(m) {
    m.nodes().forEach((p) => h(m.node(p))), m.edges().forEach((p) => {
      let g = m.edge(p);
      g.points.forEach(h), Object.hasOwn(g, "x") && h(g);
    });
  }
  function h(m) {
    let p = m.x;
    m.x = m.y, m.y = p;
  }
}), W5 = qe((n, t) => {
  var e = Cn();
  t.exports = s;
  function s(a) {
    let o = {}, c = a.nodes().filter((p) => !a.children(p).length), u = c.map((p) => a.node(p).rank), d = e.applyWithChunking(Math.max, u), h = e.range(d + 1).map(() => []);
    function m(p) {
      if (o[p]) return;
      o[p] = !0;
      let g = a.node(p);
      h[g.rank].push(p), a.successors(p).forEach(m);
    }
    return c.sort((p, g) => a.node(p).rank - a.node(g).rank).forEach(m), h;
  }
}), Y5 = qe((n, t) => {
  var e = Cn().zipObject;
  t.exports = s;
  function s(o, c) {
    let u = 0;
    for (let d = 1; d < c.length; ++d) u += a(o, c[d - 1], c[d]);
    return u;
  }
  function a(o, c, u) {
    let d = e(u, u.map((x, A) => A)), h = c.flatMap((x) => o.outEdges(x).map((A) => ({ pos: d[A.w], weight: o.edge(A).weight })).sort((A, b) => A.pos - b.pos)), m = 1;
    for (; m < u.length; ) m <<= 1;
    let p = 2 * m - 1;
    m -= 1;
    let g = new Array(p).fill(0), _ = 0;
    return h.forEach((x) => {
      let A = x.pos + m;
      g[A] += x.weight;
      let b = 0;
      for (; A > 0; ) A % 2 && (b += g[A + 1]), A = A - 1 >> 1, g[A] += x.weight;
      _ += x.weight * b;
    }), _;
  }
}), j5 = qe((n, t) => {
  t.exports = e;
  function e(s, a = []) {
    return a.map((o) => {
      let c = s.inEdges(o);
      if (c.length) {
        let u = c.reduce((d, h) => {
          let m = s.edge(h), p = s.node(h.v);
          return { sum: d.sum + m.weight * p.order, weight: d.weight + m.weight };
        }, { sum: 0, weight: 0 });
        return { v: o, barycenter: u.sum / u.weight, weight: u.weight };
      } else return { v: o };
    });
  }
}), q5 = qe((n, t) => {
  var e = Cn();
  t.exports = s;
  function s(c, u) {
    let d = {};
    c.forEach((m, p) => {
      let g = d[m.v] = { indegree: 0, in: [], out: [], vs: [m.v], i: p };
      m.barycenter !== void 0 && (g.barycenter = m.barycenter, g.weight = m.weight);
    }), u.edges().forEach((m) => {
      let p = d[m.v], g = d[m.w];
      p !== void 0 && g !== void 0 && (g.indegree++, p.out.push(d[m.w]));
    });
    let h = Object.values(d).filter((m) => !m.indegree);
    return a(h);
  }
  function a(c) {
    let u = [];
    function d(m) {
      return (p) => {
        p.merged || (p.barycenter === void 0 || m.barycenter === void 0 || p.barycenter >= m.barycenter) && o(m, p);
      };
    }
    function h(m) {
      return (p) => {
        p.in.push(m), --p.indegree === 0 && c.push(p);
      };
    }
    for (; c.length; ) {
      let m = c.pop();
      u.push(m), m.in.reverse().forEach(d(m)), m.out.forEach(h(m));
    }
    return u.filter((m) => !m.merged).map((m) => e.pick(m, ["vs", "i", "barycenter", "weight"]));
  }
  function o(c, u) {
    let d = 0, h = 0;
    c.weight && (d += c.barycenter * c.weight, h += c.weight), u.weight && (d += u.barycenter * u.weight, h += u.weight), c.vs = u.vs.concat(c.vs), c.barycenter = d / h, c.weight = h, c.i = Math.min(u.i, c.i), u.merged = !0;
  }
}), Z5 = qe((n, t) => {
  var e = Cn();
  t.exports = s;
  function s(c, u) {
    let d = e.partition(c, (b) => Object.hasOwn(b, "barycenter")), h = d.lhs, m = d.rhs.sort((b, y) => y.i - b.i), p = [], g = 0, _ = 0, x = 0;
    h.sort(o(!!u)), x = a(p, m, x), h.forEach((b) => {
      x += b.vs.length, p.push(b.vs), g += b.barycenter * b.weight, _ += b.weight, x = a(p, m, x);
    });
    let A = { vs: p.flat(!0) };
    return _ && (A.barycenter = g / _, A.weight = _), A;
  }
  function a(c, u, d) {
    let h;
    for (; u.length && (h = u[u.length - 1]).i <= d; ) u.pop(), c.push(h.vs), d++;
    return d;
  }
  function o(c) {
    return (u, d) => u.barycenter < d.barycenter ? -1 : u.barycenter > d.barycenter ? 1 : c ? d.i - u.i : u.i - d.i;
  }
}), $5 = qe((n, t) => {
  var e = j5(), s = q5(), a = Z5();
  t.exports = o;
  function o(d, h, m, p) {
    let g = d.children(h), _ = d.node(h), x = _ ? _.borderLeft : void 0, A = _ ? _.borderRight : void 0, b = {};
    x && (g = g.filter((M) => M !== x && M !== A));
    let y = e(d, g);
    y.forEach((M) => {
      if (d.children(M.v).length) {
        let O = o(d, M.v, m, p);
        b[M.v] = O, Object.hasOwn(O, "barycenter") && u(M, O);
      }
    });
    let E = s(y, m);
    c(E, b);
    let w = a(E, p);
    if (x && (w.vs = [x, w.vs, A].flat(!0), d.predecessors(x).length)) {
      let M = d.node(d.predecessors(x)[0]), O = d.node(d.predecessors(A)[0]);
      Object.hasOwn(w, "barycenter") || (w.barycenter = 0, w.weight = 0), w.barycenter = (w.barycenter * w.weight + M.order + O.order) / (w.weight + 2), w.weight += 2;
    }
    return w;
  }
  function c(d, h) {
    d.forEach((m) => {
      m.vs = m.vs.flatMap((p) => h[p] ? h[p].vs : p);
    });
  }
  function u(d, h) {
    d.barycenter !== void 0 ? (d.barycenter = (d.barycenter * d.weight + h.barycenter * h.weight) / (d.weight + h.weight), d.weight += h.weight) : (d.barycenter = h.barycenter, d.weight = h.weight);
  }
}), K5 = qe((n, t) => {
  var e = os().Graph, s = Cn();
  t.exports = a;
  function a(c, u, d, h) {
    h || (h = c.nodes());
    let m = o(c), p = new e({ compound: !0 }).setGraph({ root: m }).setDefaultNodeLabel((g) => c.node(g));
    return h.forEach((g) => {
      let _ = c.node(g), x = c.parent(g);
      (_.rank === u || _.minRank <= u && u <= _.maxRank) && (p.setNode(g), p.setParent(g, x || m), c[d](g).forEach((A) => {
        let b = A.v === g ? A.w : A.v, y = p.edge(b, g), E = y !== void 0 ? y.weight : 0;
        p.setEdge(b, g, { weight: c.edge(A).weight + E });
      }), Object.hasOwn(_, "minRank") && p.setNode(g, { borderLeft: _.borderLeft[u], borderRight: _.borderRight[u] }));
    }), p;
  }
  function o(c) {
    for (var u; c.hasNode(u = s.uniqueId("_root")); ) ;
    return u;
  }
}), Q5 = qe((n, t) => {
  t.exports = e;
  function e(s, a, o) {
    let c = {}, u;
    o.forEach((d) => {
      let h = s.parent(d), m, p;
      for (; h; ) {
        if (m = s.parent(h), m ? (p = c[m], c[m] = h) : (p = u, u = h), p && p !== h) {
          a.setEdge(p, h);
          return;
        }
        h = m;
      }
    });
  }
}), J5 = qe((n, t) => {
  var e = W5(), s = Y5(), a = $5(), o = K5(), c = Q5(), u = os().Graph, d = Cn();
  t.exports = h;
  function h(_, x = {}) {
    if (typeof x.customOrder == "function") {
      x.customOrder(_, h);
      return;
    }
    let A = d.maxRank(_), b = m(_, d.range(1, A + 1), "inEdges"), y = m(_, d.range(A - 1, -1, -1), "outEdges"), E = e(_);
    if (g(_, E), x.disableOptimalOrderHeuristic) return;
    let w = Number.POSITIVE_INFINITY, M, O = x.constraints || [];
    for (let C = 0, D = 0; D < 4; ++C, ++D) {
      p(C % 2 ? b : y, C % 4 >= 2, O), E = d.buildLayerMatrix(_);
      let T = s(_, E);
      T < w ? (D = 0, M = Object.assign({}, E), w = T) : T === w && (M = structuredClone(E));
    }
    g(_, M);
  }
  function m(_, x, A) {
    let b = /* @__PURE__ */ new Map(), y = (E, w) => {
      b.has(E) || b.set(E, []), b.get(E).push(w);
    };
    for (let E of _.nodes()) {
      let w = _.node(E);
      if (typeof w.rank == "number" && y(w.rank, E), typeof w.minRank == "number" && typeof w.maxRank == "number") for (let M = w.minRank; M <= w.maxRank; M++) M !== w.rank && y(M, E);
    }
    return x.map(function(E) {
      return o(_, E, A, b.get(E) || []);
    });
  }
  function p(_, x, A) {
    let b = new u();
    _.forEach(function(y) {
      A.forEach((M) => b.setEdge(M.left, M.right));
      let E = y.graph().root, w = a(y, E, b, x);
      w.vs.forEach((M, O) => y.node(M).order = O), c(y, b, w.vs);
    });
  }
  function g(_, x) {
    Object.values(x).forEach((A) => A.forEach((b, y) => _.node(b).order = y));
  }
}), tH = qe((n, t) => {
  var e = os().Graph, s = Cn();
  t.exports = { positionX: A, findType1Conflicts: a, findType2Conflicts: o, addConflict: u, hasConflict: d, verticalAlignment: h, horizontalCompaction: m, alignCoordinates: _, findSmallestWidthAlignment: g, balance: x };
  function a(E, w) {
    let M = {};
    function O(C, D) {
      let T = 0, L = 0, z = C.length, R = D[D.length - 1];
      return D.forEach((B, H) => {
        let U = c(E, B), V = U ? E.node(U).order : z;
        (U || B === R) && (D.slice(L, H + 1).forEach((N) => {
          E.predecessors(N).forEach((I) => {
            let k = E.node(I), X = k.order;
            (X < T || V < X) && !(k.dummy && E.node(N).dummy) && u(M, I, N);
          });
        }), L = H + 1, T = V);
      }), D;
    }
    return w.length && w.reduce(O), M;
  }
  function o(E, w) {
    let M = {};
    function O(D, T, L, z, R) {
      let B;
      s.range(T, L).forEach((H) => {
        B = D[H], E.node(B).dummy && E.predecessors(B).forEach((U) => {
          let V = E.node(U);
          V.dummy && (V.order < z || V.order > R) && u(M, U, B);
        });
      });
    }
    function C(D, T) {
      let L = -1, z, R = 0;
      return T.forEach((B, H) => {
        if (E.node(B).dummy === "border") {
          let U = E.predecessors(B);
          U.length && (z = E.node(U[0]).order, O(T, R, H, L, z), R = H, L = z);
        }
        O(T, R, T.length, z, D.length);
      }), T;
    }
    return w.length && w.reduce(C), M;
  }
  function c(E, w) {
    if (E.node(w).dummy) return E.predecessors(w).find((M) => E.node(M).dummy);
  }
  function u(E, w, M) {
    if (w > M) {
      let C = w;
      w = M, M = C;
    }
    let O = E[w];
    O || (E[w] = O = {}), O[M] = !0;
  }
  function d(E, w, M) {
    if (w > M) {
      let O = w;
      w = M, M = O;
    }
    return !!E[w] && Object.hasOwn(E[w], M);
  }
  function h(E, w, M, O) {
    let C = {}, D = {}, T = {};
    return w.forEach((L) => {
      L.forEach((z, R) => {
        C[z] = z, D[z] = z, T[z] = R;
      });
    }), w.forEach((L) => {
      let z = -1;
      L.forEach((R) => {
        let B = O(R);
        if (B.length) {
          B = B.sort((U, V) => T[U] - T[V]);
          let H = (B.length - 1) / 2;
          for (let U = Math.floor(H), V = Math.ceil(H); U <= V; ++U) {
            let N = B[U];
            D[R] === R && z < T[N] && !d(M, R, N) && (D[N] = R, D[R] = C[R] = C[N], z = T[N]);
          }
        }
      });
    }), { root: C, align: D };
  }
  function m(E, w, M, O, C) {
    let D = {}, T = p(E, w, M, C), L = C ? "borderLeft" : "borderRight";
    function z(H, U) {
      let V = T.nodes().slice(), N = {}, I = V.pop();
      for (; I; ) {
        if (N[I]) H(I);
        else {
          N[I] = !0, V.push(I);
          for (let k of U(I)) V.push(k);
        }
        I = V.pop();
      }
    }
    function R(H) {
      D[H] = T.inEdges(H).reduce((U, V) => Math.max(U, D[V.v] + T.edge(V)), 0);
    }
    function B(H) {
      let U = T.outEdges(H).reduce((N, I) => Math.min(N, D[I.w] - T.edge(I)), Number.POSITIVE_INFINITY), V = E.node(H);
      U !== Number.POSITIVE_INFINITY && V.borderType !== L && (D[H] = Math.max(D[H], U));
    }
    return z(R, T.predecessors.bind(T)), z(B, T.successors.bind(T)), Object.keys(O).forEach((H) => D[H] = D[M[H]]), D;
  }
  function p(E, w, M, O) {
    let C = new e(), D = E.graph(), T = b(D.nodesep, D.edgesep, O);
    return w.forEach((L) => {
      let z;
      L.forEach((R) => {
        let B = M[R];
        if (C.setNode(B), z) {
          var H = M[z], U = C.edge(H, B);
          C.setEdge(H, B, Math.max(T(E, R, z), U || 0));
        }
        z = R;
      });
    }), C;
  }
  function g(E, w) {
    return Object.values(w).reduce((M, O) => {
      let C = Number.NEGATIVE_INFINITY, D = Number.POSITIVE_INFINITY;
      Object.entries(O).forEach(([L, z]) => {
        let R = y(E, L) / 2;
        C = Math.max(z + R, C), D = Math.min(z - R, D);
      });
      let T = C - D;
      return T < M[0] && (M = [T, O]), M;
    }, [Number.POSITIVE_INFINITY, null])[1];
  }
  function _(E, w) {
    let M = Object.values(w), O = s.applyWithChunking(Math.min, M), C = s.applyWithChunking(Math.max, M);
    ["u", "d"].forEach((D) => {
      ["l", "r"].forEach((T) => {
        let L = D + T, z = E[L];
        if (z === w) return;
        let R = Object.values(z), B = O - s.applyWithChunking(Math.min, R);
        T !== "l" && (B = C - s.applyWithChunking(Math.max, R)), B && (E[L] = s.mapValues(z, (H) => H + B));
      });
    });
  }
  function x(E, w) {
    return s.mapValues(E.ul, (M, O) => {
      if (w) return E[w.toLowerCase()][O];
      {
        let C = Object.values(E).map((D) => D[O]).sort((D, T) => D - T);
        return (C[1] + C[2]) / 2;
      }
    });
  }
  function A(E) {
    let w = s.buildLayerMatrix(E), M = Object.assign(a(E, w), o(E, w)), O = {}, C;
    ["u", "d"].forEach((T) => {
      C = T === "u" ? w : Object.values(w).reverse(), ["l", "r"].forEach((L) => {
        L === "r" && (C = C.map((H) => Object.values(H).reverse()));
        let z = (T === "u" ? E.predecessors : E.successors).bind(E), R = h(E, C, M, z), B = m(E, C, R.root, R.align, L === "r");
        L === "r" && (B = s.mapValues(B, (H) => -H)), O[T + L] = B;
      });
    });
    let D = g(E, O);
    return _(O, D), x(O, E.graph().align);
  }
  function b(E, w, M) {
    return (O, C, D) => {
      let T = O.node(C), L = O.node(D), z = 0, R;
      if (z += T.width / 2, Object.hasOwn(T, "labelpos")) switch (T.labelpos.toLowerCase()) {
        case "l":
          R = -T.width / 2;
          break;
        case "r":
          R = T.width / 2;
          break;
      }
      if (R && (z += M ? R : -R), R = 0, z += (T.dummy ? w : E) / 2, z += (L.dummy ? w : E) / 2, z += L.width / 2, Object.hasOwn(L, "labelpos")) switch (L.labelpos.toLowerCase()) {
        case "l":
          R = L.width / 2;
          break;
        case "r":
          R = -L.width / 2;
          break;
      }
      return R && (z += M ? R : -R), R = 0, z;
    };
  }
  function y(E, w) {
    return E.node(w).width;
  }
}), eH = qe((n, t) => {
  var e = Cn(), s = tH().positionX;
  t.exports = a;
  function a(c) {
    c = e.asNonCompoundGraph(c), o(c), Object.entries(s(c)).forEach(([u, d]) => c.node(u).x = d);
  }
  function o(c) {
    let u = e.buildLayerMatrix(c), d = c.graph().ranksep, h = c.graph().rankalign, m = 0;
    u.forEach((p) => {
      let g = p.reduce((_, x) => {
        let A = c.node(x).height;
        return _ > A ? _ : A;
      }, 0);
      p.forEach((_) => {
        let x = c.node(_);
        h === "top" ? x.y = m + x.height / 2 : h === "bottom" ? x.y = m + g - x.height / 2 : x.y = m + g / 2;
      }), m += g + d;
    });
  }
}), nH = qe((n, t) => {
  var e = B5(), s = z5(), a = H5(), o = Cn().normalizeRanks, c = V5(), u = Cn().removeEmptyRanks, d = G5(), h = k5(), m = X5(), p = J5(), g = eH(), _ = Cn(), x = os().Graph;
  t.exports = A;
  function A(j, Y = {}) {
    let K = Y.debugTiming ? _.time : _.notime;
    return K("layout", () => {
      let J = K("  buildLayoutGraph", () => z(j));
      return K("  runLayout", () => b(J, K, Y)), K("  updateInputGraph", () => y(j, J)), J;
    });
  }
  function b(j, Y, K) {
    Y("    makeSpaceForEdgeLabels", () => R(j)), Y("    removeSelfEdges", () => Q(j)), Y("    acyclic", () => e.run(j)), Y("    nestingGraph.run", () => d.run(j)), Y("    rank", () => a(_.asNonCompoundGraph(j))), Y("    injectEdgeLabelProxies", () => B(j)), Y("    removeEmptyRanks", () => u(j)), Y("    nestingGraph.cleanup", () => d.cleanup(j)), Y("    normalizeRanks", () => o(j)), Y("    assignRankMinMax", () => H(j)), Y("    removeEdgeLabelProxies", () => U(j)), Y("    normalize.run", () => s.run(j)), Y("    parentDummyChains", () => c(j)), Y("    addBorderSegments", () => h(j)), Y("    order", () => p(j, K)), Y("    insertSelfEdges", () => F(j)), Y("    adjustCoordinateSystem", () => m.adjust(j)), Y("    position", () => g(j)), Y("    positionSelfEdges", () => W(j)), Y("    removeBorderNodes", () => X(j)), Y("    normalize.undo", () => s.undo(j)), Y("    fixupEdgeLabelCoords", () => I(j)), Y("    undoCoordinateSystem", () => m.undo(j)), Y("    translateGraph", () => V(j)), Y("    assignNodeIntersects", () => N(j)), Y("    reversePoints", () => k(j)), Y("    acyclic.undo", () => e.undo(j));
  }
  function y(j, Y) {
    j.nodes().forEach((K) => {
      let J = j.node(K), rt = Y.node(K);
      J && (J.x = rt.x, J.y = rt.y, J.order = rt.order, J.rank = rt.rank, Y.children(K).length && (J.width = rt.width, J.height = rt.height));
    }), j.edges().forEach((K) => {
      let J = j.edge(K), rt = Y.edge(K);
      J.points = rt.points, Object.hasOwn(rt, "x") && (J.x = rt.x, J.y = rt.y);
    }), j.graph().width = Y.graph().width, j.graph().height = Y.graph().height;
  }
  var E = ["nodesep", "edgesep", "ranksep", "marginx", "marginy"], w = { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: "tb", rankalign: "center" }, M = ["acyclicer", "ranker", "rankdir", "align", "rankalign"], O = ["width", "height", "rank"], C = { width: 0, height: 0 }, D = ["minlen", "weight", "width", "height", "labeloffset"], T = { minlen: 1, weight: 1, width: 0, height: 0, labeloffset: 10, labelpos: "r" }, L = ["labelpos"];
  function z(j) {
    let Y = new x({ multigraph: !0, compound: !0 }), K = $(j.graph());
    return Y.setGraph(Object.assign({}, w, et(K, E), _.pick(K, M))), j.nodes().forEach((J) => {
      let rt = $(j.node(J)), dt = et(rt, O);
      Object.keys(C).forEach((yt) => {
        dt[yt] === void 0 && (dt[yt] = C[yt]);
      }), Y.setNode(J, dt), Y.setParent(J, j.parent(J));
    }), j.edges().forEach((J) => {
      let rt = $(j.edge(J));
      Y.setEdge(J, Object.assign({}, T, et(rt, D), _.pick(rt, L)));
    }), Y;
  }
  function R(j) {
    let Y = j.graph();
    Y.ranksep /= 2, j.edges().forEach((K) => {
      let J = j.edge(K);
      J.minlen *= 2, J.labelpos.toLowerCase() !== "c" && (Y.rankdir === "TB" || Y.rankdir === "BT" ? J.width += J.labeloffset : J.height += J.labeloffset);
    });
  }
  function B(j) {
    j.edges().forEach((Y) => {
      let K = j.edge(Y);
      if (K.width && K.height) {
        let J = j.node(Y.v), rt = { rank: (j.node(Y.w).rank - J.rank) / 2 + J.rank, e: Y };
        _.addDummyNode(j, "edge-proxy", rt, "_ep");
      }
    });
  }
  function H(j) {
    let Y = 0;
    j.nodes().forEach((K) => {
      let J = j.node(K);
      J.borderTop && (J.minRank = j.node(J.borderTop).rank, J.maxRank = j.node(J.borderBottom).rank, Y = Math.max(Y, J.maxRank));
    }), j.graph().maxRank = Y;
  }
  function U(j) {
    j.nodes().forEach((Y) => {
      let K = j.node(Y);
      K.dummy === "edge-proxy" && (j.edge(K.e).labelRank = K.rank, j.removeNode(Y));
    });
  }
  function V(j) {
    let Y = Number.POSITIVE_INFINITY, K = 0, J = Number.POSITIVE_INFINITY, rt = 0, dt = j.graph(), yt = dt.marginx || 0, Pt = dt.marginy || 0;
    function Lt(zt) {
      let Xt = zt.x, Ft = zt.y, ve = zt.width, it = zt.height;
      Y = Math.min(Y, Xt - ve / 2), K = Math.max(K, Xt + ve / 2), J = Math.min(J, Ft - it / 2), rt = Math.max(rt, Ft + it / 2);
    }
    j.nodes().forEach((zt) => Lt(j.node(zt))), j.edges().forEach((zt) => {
      let Xt = j.edge(zt);
      Object.hasOwn(Xt, "x") && Lt(Xt);
    }), Y -= yt, J -= Pt, j.nodes().forEach((zt) => {
      let Xt = j.node(zt);
      Xt.x -= Y, Xt.y -= J;
    }), j.edges().forEach((zt) => {
      let Xt = j.edge(zt);
      Xt.points.forEach((Ft) => {
        Ft.x -= Y, Ft.y -= J;
      }), Object.hasOwn(Xt, "x") && (Xt.x -= Y), Object.hasOwn(Xt, "y") && (Xt.y -= J);
    }), dt.width = K - Y + yt, dt.height = rt - J + Pt;
  }
  function N(j) {
    j.edges().forEach((Y) => {
      let K = j.edge(Y), J = j.node(Y.v), rt = j.node(Y.w), dt, yt;
      K.points ? (dt = K.points[0], yt = K.points[K.points.length - 1]) : (K.points = [], dt = rt, yt = J), K.points.unshift(_.intersectRect(J, dt)), K.points.push(_.intersectRect(rt, yt));
    });
  }
  function I(j) {
    j.edges().forEach((Y) => {
      let K = j.edge(Y);
      if (Object.hasOwn(K, "x")) switch ((K.labelpos === "l" || K.labelpos === "r") && (K.width -= K.labeloffset), K.labelpos) {
        case "l":
          K.x -= K.width / 2 + K.labeloffset;
          break;
        case "r":
          K.x += K.width / 2 + K.labeloffset;
          break;
      }
    });
  }
  function k(j) {
    j.edges().forEach((Y) => {
      let K = j.edge(Y);
      K.reversed && K.points.reverse();
    });
  }
  function X(j) {
    j.nodes().forEach((Y) => {
      if (j.children(Y).length) {
        let K = j.node(Y), J = j.node(K.borderTop), rt = j.node(K.borderBottom), dt = j.node(K.borderLeft[K.borderLeft.length - 1]), yt = j.node(K.borderRight[K.borderRight.length - 1]);
        K.width = Math.abs(yt.x - dt.x), K.height = Math.abs(rt.y - J.y), K.x = dt.x + K.width / 2, K.y = J.y + K.height / 2;
      }
    }), j.nodes().forEach((Y) => {
      j.node(Y).dummy === "border" && j.removeNode(Y);
    });
  }
  function Q(j) {
    j.edges().forEach((Y) => {
      if (Y.v === Y.w) {
        var K = j.node(Y.v);
        K.selfEdges || (K.selfEdges = []), K.selfEdges.push({ e: Y, label: j.edge(Y) }), j.removeEdge(Y);
      }
    });
  }
  function F(j) {
    var Y = _.buildLayerMatrix(j);
    Y.forEach((K) => {
      var J = 0;
      K.forEach((rt, dt) => {
        var yt = j.node(rt);
        yt.order = dt + J, (yt.selfEdges || []).forEach((Pt) => {
          _.addDummyNode(j, "selfedge", { width: Pt.label.width, height: Pt.label.height, rank: yt.rank, order: dt + ++J, e: Pt.e, label: Pt.label }, "_se");
        }), delete yt.selfEdges;
      });
    });
  }
  function W(j) {
    j.nodes().forEach((Y) => {
      var K = j.node(Y);
      if (K.dummy === "selfedge") {
        var J = j.node(K.e.v), rt = J.x + J.width / 2, dt = J.y, yt = K.x - rt, Pt = J.height / 2;
        j.setEdge(K.e, K.label), j.removeNode(Y), K.label.points = [{ x: rt + 2 * yt / 3, y: dt - Pt }, { x: rt + 5 * yt / 6, y: dt - Pt }, { x: rt + yt, y: dt }, { x: rt + 5 * yt / 6, y: dt + Pt }, { x: rt + 2 * yt / 3, y: dt + Pt }], K.label.x = K.x, K.label.y = K.y;
      }
    });
  }
  function et(j, Y) {
    return _.mapValues(_.pick(j, Y), Number);
  }
  function $(j) {
    var Y = {};
    return j && Object.entries(j).forEach(([K, J]) => {
      typeof K == "string" && (K = K.toLowerCase()), Y[K] = J;
    }), Y;
  }
}), iH = qe((n, t) => {
  var e = Cn(), s = os().Graph;
  t.exports = { debugOrdering: a };
  function a(o) {
    let c = e.buildLayerMatrix(o), u = new s({ compound: !0, multigraph: !0 }).setGraph({});
    return o.nodes().forEach((d) => {
      u.setNode(d, { label: d }), u.setParent(d, "layer" + o.node(d).rank);
    }), o.edges().forEach((d) => u.setEdge(d.v, d.w, {}, d.name)), c.forEach((d, h) => {
      let m = "layer" + h;
      u.setNode(m, { rank: "same" }), d.reduce((p, g) => (u.setEdge(p, g, { style: "invis" }), g));
    }), u;
  }
}), sH = qe((n, t) => {
  t.exports = "2.0.4";
}), rH = qe((n, t) => {
  t.exports = { graphlib: os(), layout: nH(), debug: iH(), util: { time: Cn().time, notime: Cn().notime }, version: sH() };
});
const J1 = rH();
/*! For license information please see dagre.esm.js.LEGAL.txt */
const Mg = 380, tM = 280, eM = 30, aH = 80, nM = 2;
function B0(n, t) {
  if (n.length === 0) return { nodes: n, edges: t };
  const e = new J1.graphlib.Graph().setDefaultEdgeLabel(() => ({}));
  e.setGraph({ rankdir: "TB", nodesep: 30, ranksep: 80 });
  for (const d of n)
    e.setNode(d.id, { width: Mg, height: tM });
  for (const d of t)
    e.setEdge(d.source, d.target);
  J1.layout(e);
  const s = /* @__PURE__ */ new Map();
  for (const d of n) {
    const h = e.node(d.id), m = Math.round(h.y);
    s.has(m) || s.set(m, []), s.get(m).push(d.id);
  }
  const a = [...s.entries()].sort(([d], [h]) => d - h).map(([, d]) => d.sort((h, m) => e.node(h).x - e.node(m).x)), o = /* @__PURE__ */ new Map();
  let c = 0;
  for (const d of a)
    for (let h = 0; h < d.length; h += nM) {
      const m = d.slice(h, h + nM), g = -(m.length * Mg + (m.length - 1) * eM) / 2;
      for (let _ = 0; _ < m.length; _++)
        o.set(m[_], {
          x: g + _ * (Mg + eM),
          y: c
        });
      c += tM + aH;
    }
  return { nodes: n.map((d) => ({
    ...d,
    position: o.get(d.id) ?? d.position
  })), edges: t };
}
let oH = 1;
function lH() {
  return `node-${oH++}`;
}
function qw() {
  var t;
  return new URLSearchParams(((t = globalThis.location) == null ? void 0 : t.search) ?? "").has("demo") ? D5() : globalThis.__MEGANE_CONTEXT__ === "vscode" ? R5() : C5();
}
const iM = qw(), sM = B0(iM.nodes, iM.edges), rM = {
  snapshot: null,
  atomLabels: null,
  structureFrames: null,
  structureMeta: null,
  fileFrames: null,
  fileMeta: null,
  fileVectors: null,
  nodeSnapshots: {},
  nodeParseErrors: {},
  nodeStreamingData: {}
}, ar = KL((n, t) => ({
  nodes: sM.nodes,
  edges: sM.edges,
  viewportState: { ...bd },
  nodeErrors: {},
  snapshot: null,
  atomLabels: null,
  structureFrames: null,
  structureMeta: null,
  fileFrames: null,
  fileMeta: null,
  fileVectors: null,
  nodeSnapshots: {},
  nodeParseErrors: {},
  nodeStreamingData: {},
  setSnapshot: (e) => {
    n({ snapshot: e }), t().execute();
  },
  setAtomLabels: (e) => {
    n({ atomLabels: e }), t().execute();
  },
  setStructureFrames: (e, s) => {
    n({ structureFrames: e, structureMeta: s }), t().execute();
  },
  setFileFrames: (e, s) => {
    n({ fileFrames: e, fileMeta: s }), t().execute();
  },
  setFileVectors: (e) => {
    n({ fileVectors: e }), t().execute();
  },
  setNodeSnapshot: (e, s) => {
    n((a) => ({
      nodeSnapshots: { ...a.nodeSnapshots, [e]: s }
    })), t().execute();
  },
  removeNodeSnapshot: (e) => {
    n((s) => {
      const { [e]: a, ...o } = s.nodeSnapshots, { [e]: c, ...u } = s.nodeParseErrors;
      return { nodeSnapshots: o, nodeParseErrors: u };
    }), t().execute();
  },
  setNodeParseError: (e, s) => {
    n((a) => ({
      nodeParseErrors: { ...a.nodeParseErrors, [e]: s }
    })), t().execute();
  },
  clearNodeParseError: (e) => {
    n((s) => {
      const { [e]: a, ...o } = s.nodeParseErrors;
      return { nodeParseErrors: o };
    });
  },
  setNodeStreamingData: (e, s) => {
    n((a) => ({
      nodeStreamingData: { ...a.nodeStreamingData, [e]: s }
    })), t().execute();
  },
  removeNodeStreamingData: (e) => {
    n((s) => {
      const { [e]: a, ...o } = s.nodeStreamingData;
      return { nodeStreamingData: o };
    }), t().execute();
  },
  onNodesChange: (e) => {
    const { nodes: s } = t(), a = e.filter((o) => {
      if (o.type === "remove") {
        const c = s.find((u) => u.id === o.id);
        if ((c == null ? void 0 : c.type) === "viewport") return !1;
      }
      return !0;
    });
    a.length !== 0 && (n((o) => ({
      nodes: dw(a, o.nodes)
    })), a.some((o) => o.type === "remove") && t().execute());
  },
  onEdgesChange: (e) => {
    n((s) => ({
      edges: hw(e, s.edges)
    })), t().execute();
  },
  onConnect: (e) => {
    const { nodes: s } = t(), a = s.find((c) => c.id === e.source), o = s.find((c) => c.id === e.target);
    !(a != null && a.type) || !(o != null && o.type) || JF(
      a.type,
      e.sourceHandle ?? null,
      o.type,
      e.targetHandle ?? null
    ) && (n((c) => ({
      edges: jE(
        {
          ...e,
          id: `e-${e.source}-${e.sourceHandle}-${e.target}-${e.targetHandle}`
        },
        c.edges
      )
    })), t().execute());
  },
  addNode: (e, s) => {
    const a = lH();
    let o = { x: 425, y: 50 };
    if (!s) {
      const u = t().nodes;
      u.length > 0 && (o = { x: 425, y: Math.max(...u.map((h) => h.position.y)) + 200 });
    }
    const c = {
      id: a,
      type: e,
      position: s ?? o,
      data: {
        params: Gw(e),
        enabled: !0
      }
    };
    return n((u) => ({
      nodes: [...u.nodes, c]
    })), a;
  },
  removeNode: (e) => {
    n((s) => {
      const { [e]: a, ...o } = s.nodeSnapshots, { [e]: c, ...u } = s.nodeParseErrors, { [e]: d, ...h } = s.nodeStreamingData;
      return {
        nodes: s.nodes.filter((m) => m.id !== e),
        edges: s.edges.filter((m) => m.source !== e && m.target !== e),
        nodeSnapshots: o,
        nodeParseErrors: u,
        nodeStreamingData: h
      };
    }), t().execute();
  },
  updateNodeParams: (e, s) => {
    n((a) => ({
      nodes: a.nodes.map((o) => o.id !== e ? o : {
        ...o,
        data: {
          ...o.data,
          params: { ...o.data.params, ...s }
        }
      })
    })), t().execute();
  },
  toggleNode: (e) => {
    n((s) => ({
      nodes: s.nodes.map((a) => a.id !== e ? a : {
        ...a,
        data: { ...a.data, enabled: !a.data.enabled }
      })
    })), t().execute();
  },
  execute: () => {
    const {
      nodes: e,
      edges: s,
      snapshot: a,
      atomLabels: o,
      structureFrames: c,
      structureMeta: u,
      fileFrames: d,
      fileMeta: h,
      fileVectors: m,
      nodeSnapshots: p,
      nodeParseErrors: g,
      nodeStreamingData: _
    } = t(), x = {
      snapshot: a,
      atomLabels: o,
      structureFrames: c,
      structureMeta: u,
      fileFrames: d,
      fileMeta: h,
      fileVectors: m,
      nodeSnapshots: p,
      nodeStreamingData: _
    }, A = E5(e, s), { viewportState: b, nodeErrors: y } = M5(e, s, x), E = {};
    for (const [w, M] of A)
      E[w] = [...M];
    for (const [w, M] of y)
      E[w] || (E[w] = []), E[w].push(...M);
    for (const [w, M] of Object.entries(g))
      E[w] || (E[w] = []), E[w].push({ message: M, severity: "error" });
    n({ viewportState: b, nodeErrors: E });
  },
  serialize: () => {
    const { nodes: e, edges: s } = t();
    return A5(e, s);
  },
  deserialize: (e) => {
    const { nodes: s, edges: a } = T5(e);
    n({ nodes: s, edges: a }), t().execute();
  },
  pendingTemplateId: null,
  applyTemplate: (e) => {
    const s = U5.find((u) => u.id === e);
    if (!s) return;
    const a = s.create(), { nodes: o, edges: c } = B0(a.nodes, a.edges);
    n({
      nodes: o,
      edges: c,
      viewportState: { ...bd },
      pendingTemplateId: e,
      ...rM
    }), t().execute();
  },
  clearPendingTemplate: () => {
    n({ pendingTemplateId: null });
  },
  autoLayout: () => {
    const { nodes: e, edges: s } = t(), { nodes: a } = B0(e, s);
    n({ nodes: a });
  },
  reset: () => {
    const e = qw();
    n({
      nodes: e.nodes,
      edges: e.edges,
      viewportState: { ...bd },
      ...rM
    });
  }
}));
function cH(n, t) {
  if (!n.fileVectors || n.fileVectors.length === 0) return null;
  if (n.fileVectors.length === 1) return n.fileVectors[0].vectors;
  const e = n.fileVectors.find((s) => s.frame === t);
  return (e == null ? void 0 : e.vectors) ?? null;
}
function Eg(n, t, e, s) {
  const o = uH(t)[0] ?? null, c = t.particles.filter((R) => R.sourceNodeId === o), u = t.particles.filter((R) => R.sourceNodeId !== o), d = t.bonds.filter((R) => R.sourceNodeId === o), h = t.bonds.filter((R) => R.sourceNodeId !== o), m = t.cells.filter((R) => R.sourceNodeId === o), p = t.cells.filter((R) => R.sourceNodeId !== o), g = (e == null ? void 0 : e.particles.filter((R) => R.sourceNodeId === o)) ?? null, _ = (e == null ? void 0 : e.bonds.filter((R) => R.sourceNodeId === o)) ?? null, x = c.length > 0, A = ((g == null ? void 0 : g.length) ?? 0) > 0;
  (!e || x !== A) && n.setAtomsVisible(x), fH(n, c, g), hH(n, d, _);
  const b = m.length > 0, y = (e ? e.cells.filter((R) => R.sourceNodeId === o).length : 0) > 0, E = b && m.some((R) => R.visible), w = y && ((e == null ? void 0 : e.cells.filter((R) => R.sourceNodeId === o).some((R) => R.visible)) ?? !1);
  (!e || E !== w) && n.setCellVisible(E);
  const M = b && m.some((R) => R.axesVisible);
  (!e || M !== ((e == null ? void 0 : e.cellAxesVisible) ?? !0)) && n.setCellAxesVisible(M);
  const O = d.length > 0, C = ((_ == null ? void 0 : _.length) ?? 0) > 0;
  (!e || O !== C) && n.setBondsVisible(O);
  const D = /* @__PURE__ */ new Set(), T = wg(u, (R) => R.sourceNodeId), L = wg(h, (R) => R.sourceNodeId), z = wg(p, (R) => R.sourceNodeId);
  for (const [R, B] of T) {
    D.add(R);
    const H = n.getOrCreateLayer(R), U = B[0];
    U && H.snapshot !== U.source && H.loadSnapshot(U.source), dH(H, B);
    const V = L.get(R);
    if (V && V.length > 0) {
      const I = V[0];
      H.updateBondsExt(
        I.bondIndices,
        I.bondOrders,
        I.positions,
        I.elements,
        I.nAtoms
      ), H.setBondScale(I.scale), I.bondOpacityOverrides ? H.setBondOpacityOverrides(I.bondOpacityOverrides) : (H.clearBondOpacityOverrides(), H.setBondOpacity(I.opacity)), H.setBondsVisible(!0);
    } else
      H.setBondsVisible(!1);
    const N = z.get(R);
    N && N.length > 0 ? H.setCellVisible(N.some((I) => I.visible)) : H.setCellVisible(!1), H.setAtomsVisible(!0);
  }
  n.removeInactiveLayers(D), (!e || t.perspective !== e.perspective) && n.setPerspective(t.perspective), (!e || t.cellAxesVisible !== e.cellAxesVisible) && n.setCellAxesVisible(t.cellAxesVisible), pH(n, t.labels, (e == null ? void 0 : e.labels) ?? null), mH(n, t.meshes, (e == null ? void 0 : e.meshes) ?? null), gH(n, t.vectors, (e == null ? void 0 : e.vectors) ?? null);
}
function uH(n) {
  const t = /* @__PURE__ */ new Set();
  for (const e of n.particles) t.add(e.sourceNodeId);
  for (const e of n.bonds) t.add(e.sourceNodeId);
  for (const e of n.cells) t.add(e.sourceNodeId);
  return Array.from(t);
}
function wg(n, t) {
  const e = /* @__PURE__ */ new Map();
  for (const s of n) {
    const a = t(s);
    let o = e.get(a);
    o || (o = [], e.set(a, o)), o.push(s);
  }
  return e;
}
function fH(n, t, e) {
  if (t.length === 0) {
    e && e.length > 0 && (n.clearAtomOverrides(), n.setAtomScale(1), n.setAtomOpacity(1));
    return;
  }
  let s = null, a = null;
  for (const o of t) {
    if (o.scaleOverrides)
      if (!s)
        s = new Float32Array(o.scaleOverrides);
      else
        for (let c = 0; c < s.length; c++)
          o.scaleOverrides[c] !== 1 && (s[c] = o.scaleOverrides[c]);
    if (o.opacityOverrides)
      if (!a)
        a = new Float32Array(o.opacityOverrides);
      else
        for (let c = 0; c < a.length; c++)
          o.opacityOverrides[c] !== 1 && (a[c] = o.opacityOverrides[c]);
  }
  s ? (n.setAtomScale(1), n.setAtomScaleOverrides(s)) : (n.clearAtomOverrides(), n.setAtomScale(1)), a ? (n.setAtomOpacity(1), n.setAtomOpacityOverrides(a)) : n.setAtomOpacity(1);
}
function dH(n, t) {
  let e = null, s = null;
  for (const a of t) {
    if (a.scaleOverrides)
      if (!e)
        e = new Float32Array(a.scaleOverrides);
      else
        for (let o = 0; o < e.length; o++)
          a.scaleOverrides[o] !== 1 && (e[o] = a.scaleOverrides[o]);
    if (a.opacityOverrides)
      if (!s)
        s = new Float32Array(a.opacityOverrides);
      else
        for (let o = 0; o < s.length; o++)
          a.opacityOverrides[o] !== 1 && (s[o] = a.opacityOverrides[o]);
  }
  e ? (n.setAtomScale(1), n.setAtomScaleOverrides(e)) : (n.clearAtomOverrides(), n.setAtomScale(1)), s ? (n.setAtomOpacity(1), n.setAtomOpacityOverrides(s)) : n.setAtomOpacity(1);
}
function hH(n, t, e) {
  if (t.length === 0) return;
  const s = t[0], a = e == null ? void 0 : e[0];
  (!a || s.bondIndices !== a.bondIndices) && n.updateBondsExt(
    s.bondIndices,
    s.bondOrders,
    s.positions,
    s.elements,
    s.nAtoms
  ), (!a || s.scale !== a.scale) && n.setBondScale(s.scale), !a || s.bondOpacityOverrides !== (a == null ? void 0 : a.bondOpacityOverrides) ? s.bondOpacityOverrides ? n.setBondOpacityOverrides(s.bondOpacityOverrides) : (n.clearBondOpacityOverrides(), (!a || s.opacity !== a.opacity) && n.setBondOpacity(s.opacity)) : (!a || s.opacity !== a.opacity) && n.setBondOpacity(s.opacity);
}
function pH(n, t, e) {
  t.length > 0 ? n.setLabels(t[0].labels) : e && e.length > 0 && n.setLabels(null);
}
function mH(n, t, e) {
  t.length > 0 ? n.loadPolyhedra(t[0]) : e && e.length > 0 && n.clearPolyhedra();
}
function gH(n, t, e) {
  if (t.length > 0) {
    const s = t[0], a = cH({ fileVectors: s.frames }, 0);
    n.setVectors(a), n.setVectorScale(s.scale);
  } else e && e.length > 0 && n.setVectors(null);
}
const aM = 1313293645, Zw = 0, vH = 1, _H = 1, yH = 2;
function z0(n) {
  const t = new DataView(n), e = t.getUint32(0, !0);
  if (e !== aM)
    throw new Error(`Invalid magic: 0x${e.toString(16)}, expected 0x${aM.toString(16)}`);
  return {
    msgType: t.getUint8(4),
    flags: t.getUint8(5)
  };
}
function $w(n) {
  const t = new DataView(n), e = t.getUint8(5);
  let s = 8;
  const a = t.getUint32(s, !0);
  s += 4;
  const o = t.getUint32(s, !0);
  s += 4;
  const c = new Float32Array(n, s, a * 3);
  s += a * 3 * 4;
  const u = new Uint8Array(n, s, a);
  s += a, s += (4 - s % 4) % 4;
  const d = new Uint32Array(n, s, o * 2);
  s += o * 2 * 4;
  let h = null;
  e & _H && (h = new Uint8Array(n, s, o), s += o, s += (4 - s % 4) % 4);
  let m = null;
  return e & yH && (m = new Float32Array(n, s, 9), s += 36), { nAtoms: a, nBonds: o, nFileBonds: o, positions: c, elements: u, bonds: d, bondOrders: h, box: m };
}
function xH(n) {
  const t = new DataView(n);
  let e = 8;
  const s = t.getUint32(e, !0);
  e += 4;
  const a = t.getUint32(e, !0);
  e += 4;
  const o = new Float32Array(n, e, a * 3);
  return { frameId: s, nAtoms: a, positions: o };
}
function SH(n) {
  return n.pipeline ? /* @__PURE__ */ _t.jsx(bH, { ...n }) : /* @__PURE__ */ _t.jsx(MH, { ...n });
}
function oM(n) {
  if (!n || n.byteLength === 0) return null;
  const t = new ArrayBuffer(n.byteLength);
  new Uint8Array(t).set(new Uint8Array(n.buffer, n.byteOffset, n.byteLength));
  const { msgType: e } = z0(t);
  return e === Zw ? $w(t) : null;
}
function bH({
  snapshot: n,
  frame: t,
  currentFrame: e,
  totalFrames: s,
  onSeek: a,
  pipelineJson: o,
  nodeSnapshotsData: c
}) {
  const u = vt.useRef(null), d = vt.useRef(null), [h, m] = vt.useState(!1), [p, g] = vt.useState(30), _ = vt.useRef(null), x = ar((C) => C.viewportState), A = ar((C) => C.snapshot), b = ar((C) => C.setSnapshot);
  vt.useEffect(() => {
    if (!c || Object.keys(c).length === 0)
      b(n);
    else {
      const D = ar.getState();
      for (const [L, z] of Object.entries(c)) {
        const R = oM(z);
        R && D.setNodeSnapshot(L, {
          snapshot: R,
          frames: null,
          meta: null,
          labels: null
        });
      }
      const T = Object.values(c)[0];
      if (T) {
        const L = oM(T);
        b(L);
      }
    }
    const C = u.current;
    if (C) {
      const D = ar.getState().viewportState;
      Eg(C, D, null), _.current = D;
    }
  }, [n, c, b]), vt.useEffect(() => {
    const C = u.current;
    C && (Eg(C, x, _.current), _.current = x);
  }, [x]), vt.useEffect(() => {
    const D = ar.getState().nodes.find((B) => B.type === "add_bond");
    if (!D) return;
    const T = D.data.params;
    if (T.type !== "add_bond" || T.bondSource !== "distance" || !n || !t) return;
    const L = u.current;
    if (!L) return;
    const z = JM(
      t.positions,
      n.elements,
      n.nAtoms,
      0.6,
      n.box
    ), R = b0(
      z,
      null,
      t.positions,
      n.elements,
      n.nAtoms,
      n.box
    );
    L.updateBondsExt(
      R.bondIndices,
      R.bondOrders,
      R.positions,
      R.elements,
      R.nAtoms
    );
  }, [t, n]);
  const y = vt.useRef("");
  vt.useEffect(() => {
    if (!(!o || o === y.current)) {
      y.current = o;
      try {
        const C = JSON.parse(o);
        ar.getState().deserialize(C);
      } catch {
      }
    }
  }, [o]);
  const E = vt.useCallback((C) => {
    u.current = C, Eg(C, ar.getState().viewportState, null), _.current = ar.getState().viewportState;
  }, []), w = vt.useCallback(() => {
    m((C) => C ? (d.current && (clearInterval(d.current), d.current = null), !1) : (d.current = setInterval(() => {
      a(-1);
    }, 1e3 / p), !0));
  }, [p, a]), M = vt.useCallback(
    (C) => {
      g(C), d.current && (clearInterval(d.current), d.current = setInterval(() => {
        a(-1);
      }, 1e3 / C));
    },
    [a]
  ), O = vt.useCallback(
    (C) => {
      h && (m(!1), d.current && (clearInterval(d.current), d.current = null)), a(C);
    },
    [a, h]
  );
  return /* @__PURE__ */ _t.jsxs(
    "div",
    {
      style: {
        width: "100%",
        height: "100%",
        position: "relative",
        overflow: "hidden"
      },
      children: [
        /* @__PURE__ */ _t.jsx(
          KM,
          {
            snapshot: A ?? n,
            frame: t,
            onRendererReady: E,
            onHover: () => {
            },
            onAtomRightClick: () => {
            },
            onFrameUpdated: () => {
            }
          }
        ),
        s > 1 && /* @__PURE__ */ _t.jsx(
          QM,
          {
            currentFrame: e,
            totalFrames: s,
            playing: h,
            fps: p,
            onSeek: O,
            onPlayPause: w,
            onFpsChange: M
          }
        )
      ]
    }
  );
}
function MH({
  snapshot: n,
  frame: t,
  currentFrame: e,
  totalFrames: s,
  onSeek: a
}) {
  const o = vt.useRef(null), c = vt.useRef(null), [u, d] = vt.useState(!1), [h, m] = vt.useState(30), p = vt.useCallback((A) => {
    o.current = A;
  }, []), g = vt.useCallback(() => {
    d((A) => A ? (c.current && (clearInterval(c.current), c.current = null), !1) : (c.current = setInterval(() => {
      a(-1);
    }, 1e3 / h), !0));
  }, [h, a]), _ = vt.useCallback(
    (A) => {
      m(A), c.current && (clearInterval(c.current), c.current = setInterval(() => {
        a(-1);
      }, 1e3 / A));
    },
    [a]
  ), x = vt.useCallback(
    (A) => {
      u && (d(!1), c.current && (clearInterval(c.current), c.current = null)), a(A);
    },
    [a, u]
  );
  return /* @__PURE__ */ _t.jsxs(
    "div",
    {
      style: {
        width: "100%",
        height: "100%",
        position: "relative",
        overflow: "hidden"
      },
      children: [
        /* @__PURE__ */ _t.jsx(
          KM,
          {
            snapshot: n,
            frame: t,
            onRendererReady: p,
            onHover: () => {
            },
            onAtomRightClick: () => {
            },
            onFrameUpdated: () => {
            }
          }
        ),
        s > 1 && /* @__PURE__ */ _t.jsx(
          QM,
          {
            currentFrame: e,
            totalFrames: s,
            playing: u,
            fps: h,
            onSeek: x,
            onPlayPause: g,
            onFpsChange: _
          }
        )
      ]
    }
  );
}
function EH({ model: n, el: t }) {
  const e = document.createElement("div");
  e.style.width = "100%", e.style.height = "500px", e.style.position = "relative", e.style.background = "#ffffff", e.style.borderRadius = "8px", e.style.overflow = "hidden", t.appendChild(e);
  let s = null, a = null, o = null, c = !1;
  function u() {
    const A = n.get("_snapshot_data");
    if (!A || A.byteLength === 0) return null;
    const b = new ArrayBuffer(A.byteLength);
    new Uint8Array(b).set(new Uint8Array(A.buffer, A.byteOffset, A.byteLength));
    const { msgType: y } = z0(b);
    return y === Zw ? $w(b) : null;
  }
  function d() {
    const A = n.get("_frame_data");
    if (!A || A.byteLength === 0) return null;
    const b = new ArrayBuffer(A.byteLength);
    new Uint8Array(b).set(new Uint8Array(A.buffer, A.byteOffset, A.byteLength));
    const { msgType: y } = z0(b);
    return y === vH ? xH(b) : null;
  }
  function h(A) {
    const b = n.get("total_frames") || 0;
    if (A === -1) {
      const E = ((n.get("frame_index") || 0) + 1) % b;
      n.set("frame_index", E);
    } else
      n.set("frame_index", A);
    n.save_changes();
  }
  function m(A) {
    const b = A ? JSON.stringify(A) : "";
    n.set("_measurement_json", b), n.save_changes();
  }
  function p(A) {
    n.set("_pipeline_json", A), n.save_changes();
  }
  function g() {
    if (!s || c) return;
    const A = n.get("frame_index") || 0, b = n.get("total_frames") || 0, y = n.get("selected_atoms") || [], E = n.get("_pipeline_enabled") || !1, w = n.get("_pipeline_json") || "", M = n.get("_node_snapshots_data") || {};
    s.render(
      vt.createElement(SH, {
        snapshot: a,
        frame: o,
        currentFrame: A,
        totalFrames: b,
        onSeek: h,
        selectedAtoms: y,
        onMeasurementChange: m,
        pipeline: E,
        pipelineJson: w,
        nodeSnapshotsData: M,
        onPipelineChange: p
      })
    );
  }
  function _() {
    return s || c ? !!s : e.clientWidth === 0 || e.clientHeight === 0 ? !1 : (s = c2.createRoot(e), a = u(), o = d(), g(), !0);
  }
  const x = new ResizeObserver(() => {
    !s && !c && _();
  });
  return x.observe(e), _(), n.on("change:_snapshot_data", () => {
    a = u(), s ? g() : _();
  }), n.on("change:_frame_data", () => {
    o = d(), g();
  }), n.on("change:frame_index", () => {
    g();
  }), n.on("change:total_frames", () => {
    g();
  }), n.on("change:selected_atoms", () => {
    g();
  }), n.on("change:_pipeline_enabled", () => {
    g();
  }), n.on("change:_node_snapshots_data", () => {
    g();
  }), n.on("change:_pipeline_json", () => {
    g();
  }), () => {
    c = !0, x.disconnect(), s == null || s.unmount(), s = null;
  };
}
const TH = { render: EH };
export {
  TH as default
};
