import {
  ACESFilmicToneMapping,
  AddEquation,
  AddOperation,
  AdditiveBlending,
  AgXToneMapping,
  AmbientLight,
  AnimationClip,
  AnimationMixer,
  BackSide,
  Bone,
  BooleanKeyframeTrack,
  Box2,
  Box3,
  Box3Helper,
  BoxGeometry,
  BufferAttribute,
  BufferGeometry,
  BufferGeometryLoader,
  Camera,
  CanvasTexture,
  CineonToneMapping,
  ClampToEdgeWrapping,
  Clock,
  Color,
  ColorKeyframeTrack,
  ColorManagement,
  CompressedArrayTexture,
  CompressedCubeTexture,
  CompressedTexture,
  CompressedTextureLoader,
  ConeGeometry,
  Controls,
  CubeTexture,
  Curve,
  CustomBlending,
  CustomToneMapping,
  CylinderGeometry,
  Data3DTexture,
  DataTexture,
  DataTextureLoader,
  DataUtils,
  DefaultLoadingManager,
  DepthStencilFormat,
  DepthTexture,
  DirectionalLight,
  DoubleSide,
  DstAlphaFactor,
  DstColorFactor,
  DynamicDrawUsage,
  EllipseCurve,
  EqualStencilFunc,
  EquirectangularReflectionMapping,
  EquirectangularRefractionMapping,
  Euler,
  ExtrudeGeometry,
  FileLoader,
  Float32BufferAttribute,
  FloatType,
  FramebufferTexture,
  FrontSide,
  Frustum,
  GridHelper,
  Group,
  HalfFloatType,
  ImageBitmapLoader,
  ImageUtils,
  IncrementStencilOp,
  InstancedBufferAttribute,
  InstancedBufferGeometry,
  InstancedInterleavedBuffer,
  InstancedMesh,
  Int32BufferAttribute,
  InterleavedBuffer,
  InterleavedBufferAttribute,
  Interpolant,
  InterpolateDiscrete,
  InterpolateLinear,
  Layers,
  LightProbe,
  Line,
  Line3,
  LineBasicMaterial,
  LineLoop,
  LineSegments,
  LinearFilter,
  LinearMipMapLinearFilter,
  LinearMipmapLinearFilter,
  LinearMipmapNearestFilter,
  LinearSRGBColorSpace,
  LinearToneMapping,
  Loader,
  LoaderUtils,
  LoadingManager,
  MOUSE,
  Material,
  MathUtils,
  Matrix3,
  Matrix4,
  Mesh,
  MeshBasicMaterial,
  MeshDepthMaterial,
  MeshLambertMaterial,
  MeshNormalMaterial,
  MeshPhongMaterial,
  MeshPhysicalMaterial,
  MeshStandardMaterial,
  MirroredRepeatWrapping,
  MultiplyOperation,
  NearestFilter,
  NearestMipmapLinearFilter,
  NearestMipmapNearestFilter,
  NeutralToneMapping,
  NoBlending,
  NoColorSpace,
  NormalBlending,
  NumberKeyframeTrack,
  Object3D,
  OctahedronGeometry,
  OneMinusSrcAlphaFactor,
  OrthographicCamera,
  Path,
  PerspectiveCamera,
  Plane,
  PlaneGeometry,
  PointLight,
  Points,
  PointsMaterial,
  PropertyBinding,
  Quaternion,
  QuaternionKeyframeTrack,
  REVISION,
  RGBADepthPacking,
  RGBAFormat,
  RGBA_ASTC_4x4_Format,
  RGBA_ASTC_6x6_Format,
  RGBA_BPTC_Format,
  RGBA_ETC2_EAC_Format,
  RGBA_PVRTC_2BPPV1_Format,
  RGBA_PVRTC_4BPPV1_Format,
  RGBA_S3TC_DXT1_Format,
  RGBA_S3TC_DXT3_Format,
  RGBA_S3TC_DXT5_Format,
  RGB_BPTC_SIGNED_Format,
  RGB_BPTC_UNSIGNED_Format,
  RGB_ETC1_Format,
  RGB_ETC2_Format,
  RGB_PVRTC_2BPPV1_Format,
  RGB_PVRTC_4BPPV1_Format,
  RGB_S3TC_DXT1_Format,
  RGFormat,
  RGIntegerFormat,
  RawShaderMaterial,
  Ray,
  Raycaster,
  RectAreaLight,
  RedFormat,
  RedIntegerFormat,
  ReinhardToneMapping,
  RepeatWrapping,
  SRGBColorSpace,
  SRGBTransfer,
  Scene,
  ShaderChunk,
  ShaderLib,
  ShaderMaterial,
  Shape,
  ShapePath as ShapePath2,
  ShapeUtils,
  Skeleton,
  SkeletonHelper,
  SkinnedMesh,
  Source,
  Sphere,
  SphereGeometry,
  Spherical,
  SphericalHarmonics3,
  SpotLight,
  Sprite,
  SpriteMaterial,
  SrcAlphaFactor,
  StereoCamera,
  TOUCH,
  Texture,
  TextureLoader,
  TorusGeometry,
  Triangle,
  TriangleFanDrawMode,
  TriangleStripDrawMode,
  TrianglesDrawMode,
  UVMapping,
  Uint16BufferAttribute,
  Uniform,
  UniformsLib,
  UniformsUtils,
  UnsignedByteType,
  UnsignedInt248Type,
  UnsignedShortType,
  Vector2,
  Vector3,
  Vector4,
  VectorKeyframeTrack,
  WebGLCoordinateSystem,
  WebGLCubeRenderTarget,
  WebGLRenderTarget,
  WebGLRenderer,
  WireframeGeometry,
  ZeroFactor,
  __export
} from "./chunk-CCI6HYBR.js";

// node_modules/three/examples/jsm/animation/AnimationClipCreator.js
var AnimationClipCreator = class {
  /**
   * Creates an animation clip that rotates a 3D object 360 degrees
   * in the given period of time around the given axis.
   *
   * @param {number} period - The duration of the animation.
   * @param {('x'|'y'|'z')} [axis='x'] - The axis of rotation.
   * @return {AnimationClip} The created animation clip.
   */
  static CreateRotationAnimation(period, axis = "x") {
    const times = [0, period], values2 = [0, 360];
    const trackName = ".rotation[" + axis + "]";
    const track = new NumberKeyframeTrack(trackName, times, values2);
    return new AnimationClip("", period, [track]);
  }
  /**
   * Creates an animation clip that scales a 3D object from `0` to `1`
   * in the given period of time along the given axis.
   *
   * @param {number} period - The duration of the animation.
   * @param {('x'|'y'|'z')} [axis='x'] - The axis to scale the 3D object along.
   * @return {AnimationClip} The created animation clip.
   */
  static CreateScaleAxisAnimation(period, axis = "x") {
    const times = [0, period], values2 = [0, 1];
    const trackName = ".scale[" + axis + "]";
    const track = new NumberKeyframeTrack(trackName, times, values2);
    return new AnimationClip("", period, [track]);
  }
  /**
   * Creates an animation clip that translates a 3D object in a shake pattern
   * in the given period.
   *
   * @param {number} duration - The duration of the animation.
   * @param {Vector3} shakeScale - The scale of the shake.
   * @return {AnimationClip} The created animation clip.
   */
  static CreateShakeAnimation(duration, shakeScale) {
    const times = [], values2 = [], tmp = new Vector3();
    for (let i = 0; i < duration * 10; i++) {
      times.push(i / 10);
      tmp.set(Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1).multiply(shakeScale).toArray(values2, values2.length);
    }
    const trackName = ".position";
    const track = new VectorKeyframeTrack(trackName, times, values2);
    return new AnimationClip("", duration, [track]);
  }
  /**
   * Creates an animation clip that scales a 3D object in a pulse pattern
   * in the given period.
   *
   * @param {number} duration - The duration of the animation.
   * @param {number} pulseScale - The scale of the pulse.
   * @return {AnimationClip} The created animation clip.
   */
  static CreatePulsationAnimation(duration, pulseScale) {
    const times = [], values2 = [], tmp = new Vector3();
    for (let i = 0; i < duration * 10; i++) {
      times.push(i / 10);
      const scaleFactor = Math.random() * pulseScale;
      tmp.set(scaleFactor, scaleFactor, scaleFactor).toArray(values2, values2.length);
    }
    const trackName = ".scale";
    const track = new VectorKeyframeTrack(trackName, times, values2);
    return new AnimationClip("", duration, [track]);
  }
  /**
   * Creates an animation clip that toggles the visibility of a 3D object.
   *
   * @param {number} duration - The duration of the animation.
   * @return {AnimationClip} The created animation clip.
   */
  static CreateVisibilityAnimation(duration) {
    const times = [0, duration / 2, duration], values2 = [true, false, true];
    const trackName = ".visible";
    const track = new BooleanKeyframeTrack(trackName, times, values2);
    return new AnimationClip("", duration, [track]);
  }
  /**
   * Creates an animation clip that animates the `color` property of a 3D object's
   * material.
   *
   * @param {number} duration - The duration of the animation.
   * @param {Array<Color>} colors - An array of colors that should be sequentially animated.
   * @return {AnimationClip} The created animation clip.
   */
  static CreateMaterialColorAnimation(duration, colors) {
    const times = [], values2 = [], timeStep = colors.length > 1 ? duration / (colors.length - 1) : 0;
    for (let i = 0; i < colors.length; i++) {
      times.push(i * timeStep);
      const color = colors[i];
      values2.push(color.r, color.g, color.b);
    }
    const trackName = ".material.color";
    const track = new ColorKeyframeTrack(trackName, times, values2);
    return new AnimationClip("", duration, [track]);
  }
};

// node_modules/three/examples/jsm/animation/CCDIKSolver.js
var _quaternion = new Quaternion();
var _targetPos = new Vector3();
var _targetVec = new Vector3();
var _effectorPos = new Vector3();
var _effectorVec = new Vector3();
var _linkPos = new Vector3();
var _invLinkQ = new Quaternion();
var _linkScale = new Vector3();
var _axis = new Vector3();
var _vector = new Vector3();
var _matrix = new Matrix4();
var CCDIKSolver = class {
  /**
   * @param {SkinnedMesh} mesh - The skinned mesh.
   * @param {Array<CCDIKSolver~IK>} [iks=[]] - The IK objects.
   */
  constructor(mesh, iks = []) {
    this.mesh = mesh;
    this.iks = iks;
    this._initialQuaternions = [];
    this._workingQuaternion = new Quaternion();
    for (const ik of iks) {
      const chainQuats = [];
      for (let i = 0; i < ik.links.length; i++) {
        chainQuats.push(new Quaternion());
      }
      this._initialQuaternions.push(chainQuats);
    }
    this._valid();
  }
  /**
   * Updates all IK bones by solving the CCD algorithm.
   *
   * @param {number} [globalBlendFactor=1.0] - Blend factor applied if an IK chain doesn't have its own .blendFactor.
   * @return {CCDIKSolver} A reference to this instance.
   */
  update(globalBlendFactor = 1) {
    const iks = this.iks;
    for (let i = 0, il = iks.length; i < il; i++) {
      this.updateOne(iks[i], globalBlendFactor);
    }
    return this;
  }
  /**
   * Updates one IK bone solving the CCD algorithm.
   *
   * @param {CCDIKSolver~IK} ik - The IK to update.
   * @param {number} [overrideBlend=1.0] - If the IK object does not define `blendFactor`, this value is used.
   * @return {CCDIKSolver} A reference to this instance.
   */
  updateOne(ik, overrideBlend = 1) {
    const chainBlend = ik.blendFactor !== void 0 ? ik.blendFactor : overrideBlend;
    const bones = this.mesh.skeleton.bones;
    const chainIndex = this.iks.indexOf(ik);
    const initialQuaternions = this._initialQuaternions[chainIndex];
    const math = Math;
    const effector = bones[ik.effector];
    const target = bones[ik.target];
    _targetPos.setFromMatrixPosition(target.matrixWorld);
    const links = ik.links;
    const iteration = ik.iteration !== void 0 ? ik.iteration : 1;
    if (chainBlend < 1) {
      for (let j2 = 0; j2 < links.length; j2++) {
        const linkIndex = links[j2].index;
        initialQuaternions[j2].copy(bones[linkIndex].quaternion);
      }
    }
    for (let i = 0; i < iteration; i++) {
      let rotated = false;
      for (let j2 = 0, jl = links.length; j2 < jl; j2++) {
        const link = bones[links[j2].index];
        if (links[j2].enabled === false) break;
        const limitation = links[j2].limitation;
        const rotationMin = links[j2].rotationMin;
        const rotationMax = links[j2].rotationMax;
        link.matrixWorld.decompose(_linkPos, _invLinkQ, _linkScale);
        _invLinkQ.invert();
        _effectorPos.setFromMatrixPosition(effector.matrixWorld);
        _effectorVec.subVectors(_effectorPos, _linkPos);
        _effectorVec.applyQuaternion(_invLinkQ);
        _effectorVec.normalize();
        _targetVec.subVectors(_targetPos, _linkPos);
        _targetVec.applyQuaternion(_invLinkQ);
        _targetVec.normalize();
        let angle = _targetVec.dot(_effectorVec);
        if (angle > 1) {
          angle = 1;
        } else if (angle < -1) {
          angle = -1;
        }
        angle = math.acos(angle);
        if (angle < 1e-5) continue;
        if (ik.minAngle !== void 0 && angle < ik.minAngle) {
          angle = ik.minAngle;
        }
        if (ik.maxAngle !== void 0 && angle > ik.maxAngle) {
          angle = ik.maxAngle;
        }
        _axis.crossVectors(_effectorVec, _targetVec);
        _axis.normalize();
        _quaternion.setFromAxisAngle(_axis, angle);
        link.quaternion.multiply(_quaternion);
        if (limitation !== void 0) {
          let c2 = link.quaternion.w;
          if (c2 > 1) c2 = 1;
          const c22 = math.sqrt(1 - c2 * c2);
          link.quaternion.set(
            limitation.x * c22,
            limitation.y * c22,
            limitation.z * c22,
            c2
          );
        }
        if (rotationMin !== void 0) {
          link.rotation.setFromVector3(_vector.setFromEuler(link.rotation).max(rotationMin));
        }
        if (rotationMax !== void 0) {
          link.rotation.setFromVector3(_vector.setFromEuler(link.rotation).min(rotationMax));
        }
        link.updateMatrixWorld(true);
        rotated = true;
      }
      if (!rotated) break;
    }
    if (chainBlend < 1) {
      for (let j2 = 0; j2 < links.length; j2++) {
        const linkIndex = links[j2].index;
        const link = bones[linkIndex];
        this._workingQuaternion.copy(initialQuaternions[j2]).slerp(link.quaternion, chainBlend);
        link.quaternion.copy(this._workingQuaternion);
        link.updateMatrixWorld(true);
      }
    }
    return this;
  }
  /**
   * Creates a helper for visualizing the CCDIK.
   *
   * @param {number} sphereSize - The sphere size.
   * @return {CCDIKHelper} The created helper.
   */
  createHelper(sphereSize) {
    return new CCDIKHelper(this.mesh, this.iks, sphereSize);
  }
  // private methods
  _valid() {
    const iks = this.iks;
    const bones = this.mesh.skeleton.bones;
    for (let i = 0, il = iks.length; i < il; i++) {
      const ik = iks[i];
      const effector = bones[ik.effector];
      const links = ik.links;
      let link0, link1;
      link0 = effector;
      for (let j2 = 0, jl = links.length; j2 < jl; j2++) {
        link1 = bones[links[j2].index];
        if (link0.parent !== link1) {
          console.warn("THREE.CCDIKSolver: bone " + link0.name + " is not the child of bone " + link1.name);
        }
        link0 = link1;
      }
    }
  }
};
function getPosition(bone, matrixWorldInv) {
  return _vector.setFromMatrixPosition(bone.matrixWorld).applyMatrix4(matrixWorldInv);
}
function setPositionOfBoneToAttributeArray(array, index2, bone, matrixWorldInv) {
  const v = getPosition(bone, matrixWorldInv);
  array[index2 * 3 + 0] = v.x;
  array[index2 * 3 + 1] = v.y;
  array[index2 * 3 + 2] = v.z;
}
var CCDIKHelper = class extends Object3D {
  /**
   * @param {SkinnedMesh} mesh - The skinned mesh.
  	 * @param {Array<CCDIKSolver~IK>} [iks=[]] - The IK objects.
  	 * @param {number} [sphereSize=0.25] - The sphere size.
   */
  constructor(mesh, iks = [], sphereSize = 0.25) {
    super();
    this.root = mesh;
    this.iks = iks;
    this.matrix.copy(mesh.matrixWorld);
    this.matrixAutoUpdate = false;
    this.sphereGeometry = new SphereGeometry(sphereSize, 16, 8);
    this.targetSphereMaterial = new MeshBasicMaterial({
      color: new Color(16746632),
      depthTest: false,
      depthWrite: false,
      transparent: true
    });
    this.effectorSphereMaterial = new MeshBasicMaterial({
      color: new Color(8978312),
      depthTest: false,
      depthWrite: false,
      transparent: true
    });
    this.linkSphereMaterial = new MeshBasicMaterial({
      color: new Color(8947967),
      depthTest: false,
      depthWrite: false,
      transparent: true
    });
    this.lineMaterial = new LineBasicMaterial({
      color: new Color(16711680),
      depthTest: false,
      depthWrite: false,
      transparent: true
    });
    this._init();
  }
  updateMatrixWorld(force) {
    const mesh = this.root;
    if (this.visible) {
      let offset = 0;
      const iks = this.iks;
      const bones = mesh.skeleton.bones;
      _matrix.copy(mesh.matrixWorld).invert();
      for (let i = 0, il = iks.length; i < il; i++) {
        const ik = iks[i];
        const targetBone = bones[ik.target];
        const effectorBone = bones[ik.effector];
        const targetMesh = this.children[offset++];
        const effectorMesh = this.children[offset++];
        targetMesh.position.copy(getPosition(targetBone, _matrix));
        effectorMesh.position.copy(getPosition(effectorBone, _matrix));
        for (let j2 = 0, jl = ik.links.length; j2 < jl; j2++) {
          const link = ik.links[j2];
          const linkBone = bones[link.index];
          const linkMesh = this.children[offset++];
          linkMesh.position.copy(getPosition(linkBone, _matrix));
        }
        const line2 = this.children[offset++];
        const array = line2.geometry.attributes.position.array;
        setPositionOfBoneToAttributeArray(array, 0, targetBone, _matrix);
        setPositionOfBoneToAttributeArray(array, 1, effectorBone, _matrix);
        for (let j2 = 0, jl = ik.links.length; j2 < jl; j2++) {
          const link = ik.links[j2];
          const linkBone = bones[link.index];
          setPositionOfBoneToAttributeArray(array, j2 + 2, linkBone, _matrix);
        }
        line2.geometry.attributes.position.needsUpdate = true;
      }
    }
    this.matrix.copy(mesh.matrixWorld);
    super.updateMatrixWorld(force);
  }
  /**
   * Frees the GPU-related resources allocated by this instance.
   * Call this method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.sphereGeometry.dispose();
    this.targetSphereMaterial.dispose();
    this.effectorSphereMaterial.dispose();
    this.linkSphereMaterial.dispose();
    this.lineMaterial.dispose();
    const children = this.children;
    for (let i = 0; i < children.length; i++) {
      const child = children[i];
      if (child.isLine) child.geometry.dispose();
    }
  }
  // private method
  _init() {
    const scope = this;
    const iks = this.iks;
    function createLineGeometry(ik) {
      const geometry = new BufferGeometry();
      const vertices = new Float32Array((2 + ik.links.length) * 3);
      geometry.setAttribute("position", new BufferAttribute(vertices, 3));
      return geometry;
    }
    function createTargetMesh() {
      return new Mesh(scope.sphereGeometry, scope.targetSphereMaterial);
    }
    function createEffectorMesh() {
      return new Mesh(scope.sphereGeometry, scope.effectorSphereMaterial);
    }
    function createLinkMesh() {
      return new Mesh(scope.sphereGeometry, scope.linkSphereMaterial);
    }
    function createLine(ik) {
      return new Line(createLineGeometry(ik), scope.lineMaterial);
    }
    for (let i = 0, il = iks.length; i < il; i++) {
      const ik = iks[i];
      this.add(createTargetMesh());
      this.add(createEffectorMesh());
      for (let j2 = 0, jl = ik.links.length; j2 < jl; j2++) {
        this.add(createLinkMesh());
      }
      this.add(createLine(ik));
    }
  }
};

// node_modules/three/examples/jsm/capabilities/WebGL.js
var WebGL = class {
  /**
   * Returns `true` if WebGL 2 is available.
   *
   * @return {boolean} Whether WebGL 2 is available or not.
   */
  static isWebGL2Available() {
    try {
      const canvas = document.createElement("canvas");
      return !!(window.WebGL2RenderingContext && canvas.getContext("webgl2"));
    } catch (e) {
      return false;
    }
  }
  /**
   * Returns `true` if the given color space is available. This method can only be used
   * if WebGL 2 is supported.
   *
   * @param {string} colorSpace - The color space to test.
   * @return {boolean} Whether the given color space is available or not.
   */
  static isColorSpaceAvailable(colorSpace) {
    try {
      const canvas = document.createElement("canvas");
      const ctx = window.WebGL2RenderingContext && canvas.getContext("webgl2");
      ctx.drawingBufferColorSpace = colorSpace;
      return ctx.drawingBufferColorSpace === colorSpace;
    } catch (e) {
      return false;
    }
  }
  /**
   * Returns a `div` element representing a formatted error message that can be appended in
   * web sites if WebGL 2 isn't supported.
   *
   * @return {HTMLDivElement} A `div` element representing a formatted error message that WebGL 2 isn't supported.
   */
  static getWebGL2ErrorMessage() {
    return this._getErrorMessage(2);
  }
  // private
  static _getErrorMessage(version) {
    const names = {
      1: "WebGL",
      2: "WebGL 2"
    };
    const contexts = {
      1: window.WebGLRenderingContext,
      2: window.WebGL2RenderingContext
    };
    let message = 'Your $0 does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">$1</a>';
    const element = document.createElement("div");
    element.id = "webglmessage";
    element.style.fontFamily = "monospace";
    element.style.fontSize = "13px";
    element.style.fontWeight = "normal";
    element.style.textAlign = "center";
    element.style.background = "#fff";
    element.style.color = "#000";
    element.style.padding = "1.5em";
    element.style.width = "400px";
    element.style.margin = "5em auto 0";
    if (contexts[version]) {
      message = message.replace("$0", "graphics card");
    } else {
      message = message.replace("$0", "browser");
    }
    message = message.replace("$1", names[version]);
    element.innerHTML = message;
    return element;
  }
};
var WebGL_default = WebGL;

// node_modules/three/examples/jsm/controls/ArcballControls.js
var STATE = {
  IDLE: Symbol(),
  ROTATE: Symbol(),
  PAN: Symbol(),
  SCALE: Symbol(),
  FOV: Symbol(),
  FOCUS: Symbol(),
  ZROTATE: Symbol(),
  TOUCH_MULTI: Symbol(),
  ANIMATION_FOCUS: Symbol(),
  ANIMATION_ROTATE: Symbol()
};
var INPUT = {
  NONE: Symbol(),
  ONE_FINGER: Symbol(),
  ONE_FINGER_SWITCHED: Symbol(),
  TWO_FINGER: Symbol(),
  MULT_FINGER: Symbol(),
  CURSOR: Symbol()
};
var _center = {
  x: 0,
  y: 0
};
var _transformation = {
  camera: new Matrix4(),
  gizmos: new Matrix4()
};
var _changeEvent = { type: "change" };
var _startEvent = { type: "start" };
var _endEvent = { type: "end" };
var _raycaster = new Raycaster();
var _offset = new Vector3();
var _gizmoMatrixStateTemp = new Matrix4();
var _cameraMatrixStateTemp = new Matrix4();
var _scalePointTemp = new Vector3();
var _EPS = 1e-6;
var ArcballControls = class extends Controls {
  /**
   * Constructs a new controls instance.
   *
   * @param {Camera} camera - The camera to be controlled. The camera must not be a child of another object, unless that object is the scene itself.
   * @param {?HTMLDOMElement} [domElement=null] - The HTML element used for event listeners.
   * @param {?Scene} [scene=null] The scene rendered by the camera. If not given, gizmos cannot be shown.
   */
  constructor(camera, domElement = null, scene = null) {
    super(camera, domElement);
    this.scene = scene;
    this.target = new Vector3();
    this._currentTarget = new Vector3();
    this.radiusFactor = 0.67;
    this.mouseActions = [];
    this._mouseOp = null;
    this._v2_1 = new Vector2();
    this._v3_1 = new Vector3();
    this._v3_2 = new Vector3();
    this._m4_1 = new Matrix4();
    this._m4_2 = new Matrix4();
    this._quat = new Quaternion();
    this._translationMatrix = new Matrix4();
    this._rotationMatrix = new Matrix4();
    this._scaleMatrix = new Matrix4();
    this._rotationAxis = new Vector3();
    this._cameraMatrixState = new Matrix4();
    this._cameraProjectionState = new Matrix4();
    this._fovState = 1;
    this._upState = new Vector3();
    this._zoomState = 1;
    this._nearPos = 0;
    this._farPos = 0;
    this._gizmoMatrixState = new Matrix4();
    this._up0 = new Vector3();
    this._zoom0 = 1;
    this._fov0 = 0;
    this._initialNear = 0;
    this._nearPos0 = 0;
    this._initialFar = 0;
    this._farPos0 = 0;
    this._cameraMatrixState0 = new Matrix4();
    this._gizmoMatrixState0 = new Matrix4();
    this._target0 = new Vector3();
    this._button = -1;
    this._touchStart = [];
    this._touchCurrent = [];
    this._input = INPUT.NONE;
    this._switchSensibility = 32;
    this._startFingerDistance = 0;
    this._currentFingerDistance = 0;
    this._startFingerRotation = 0;
    this._currentFingerRotation = 0;
    this._devPxRatio = 0;
    this._downValid = true;
    this._nclicks = 0;
    this._downEvents = [];
    this._downStart = 0;
    this._clickStart = 0;
    this._maxDownTime = 250;
    this._maxInterval = 300;
    this._posThreshold = 24;
    this._movementThreshold = 24;
    this._currentCursorPosition = new Vector3();
    this._startCursorPosition = new Vector3();
    this._grid = null;
    this._gridPosition = new Vector3();
    this._gizmos = new Group();
    this._curvePts = 128;
    this._timeStart = -1;
    this._animationId = -1;
    this.focusAnimationTime = 500;
    this._timePrev = 0;
    this._timeCurrent = 0;
    this._anglePrev = 0;
    this._angleCurrent = 0;
    this._cursorPosPrev = new Vector3();
    this._cursorPosCurr = new Vector3();
    this._wPrev = 0;
    this._wCurr = 0;
    this.adjustNearFar = false;
    this.scaleFactor = 1.1;
    this.dampingFactor = 25;
    this.wMax = 20;
    this.enableAnimations = true;
    this.enableGrid = false;
    this.cursorZoom = false;
    this.minFov = 5;
    this.maxFov = 90;
    this.rotateSpeed = 1;
    this.enablePan = true;
    this.enableRotate = true;
    this.enableZoom = true;
    this.enableGizmos = true;
    this.enableFocus = true;
    this.minDistance = 0;
    this.maxDistance = Infinity;
    this.minZoom = 0;
    this.maxZoom = Infinity;
    this._tbRadius = 1;
    this._state = STATE.IDLE;
    this.setCamera(camera);
    if (this.scene != null) {
      this.scene.add(this._gizmos);
    }
    this.initializeMouseActions();
    this._onContextMenu = onContextMenu.bind(this);
    this._onWheel = onWheel.bind(this);
    this._onPointerUp = onPointerUp.bind(this);
    this._onPointerMove = onPointerMove.bind(this);
    this._onPointerDown = onPointerDown.bind(this);
    this._onPointerCancel = onPointerCancel.bind(this);
    this._onWindowResize = onWindowResize.bind(this);
    if (domElement !== null) {
      this.connect(domElement);
    }
  }
  connect(element) {
    super.connect(element);
    this.domElement.style.touchAction = "none";
    this._devPxRatio = window.devicePixelRatio;
    this.domElement.addEventListener("contextmenu", this._onContextMenu);
    this.domElement.addEventListener("wheel", this._onWheel, { passive: false });
    this.domElement.addEventListener("pointerdown", this._onPointerDown);
    this.domElement.addEventListener("pointercancel", this._onPointerCancel);
    window.addEventListener("resize", this._onWindowResize);
  }
  disconnect() {
    this.domElement.removeEventListener("pointerdown", this._onPointerDown);
    this.domElement.removeEventListener("pointercancel", this._onPointerCancel);
    this.domElement.removeEventListener("wheel", this._onWheel);
    this.domElement.removeEventListener("contextmenu", this._onContextMenu);
    window.removeEventListener("pointermove", this._onPointerMove);
    window.removeEventListener("pointerup", this._onPointerUp);
    window.removeEventListener("resize", this._onWindowResize);
  }
  onSinglePanStart(event, operation) {
    if (this.enabled) {
      this.dispatchEvent(_startEvent);
      this.setCenter(event.clientX, event.clientY);
      switch (operation) {
        case "PAN":
          if (!this.enablePan) {
            return;
          }
          if (this._animationId != -1) {
            cancelAnimationFrame(this._animationId);
            this._animationId = -1;
            this._timeStart = -1;
            this.activateGizmos(false);
            this.dispatchEvent(_changeEvent);
          }
          this.updateTbState(STATE.PAN, true);
          this._startCursorPosition.copy(this.unprojectOnTbPlane(this.object, _center.x, _center.y, this.domElement));
          if (this.enableGrid) {
            this.drawGrid();
            this.dispatchEvent(_changeEvent);
          }
          break;
        case "ROTATE":
          if (!this.enableRotate) {
            return;
          }
          if (this._animationId != -1) {
            cancelAnimationFrame(this._animationId);
            this._animationId = -1;
            this._timeStart = -1;
          }
          this.updateTbState(STATE.ROTATE, true);
          this._startCursorPosition.copy(this.unprojectOnTbSurface(this.object, _center.x, _center.y, this.domElement, this._tbRadius));
          this.activateGizmos(true);
          if (this.enableAnimations) {
            this._timePrev = this._timeCurrent = performance.now();
            this._angleCurrent = this._anglePrev = 0;
            this._cursorPosPrev.copy(this._startCursorPosition);
            this._cursorPosCurr.copy(this._cursorPosPrev);
            this._wCurr = 0;
            this._wPrev = this._wCurr;
          }
          this.dispatchEvent(_changeEvent);
          break;
        case "FOV":
          if (!this.object.isPerspectiveCamera || !this.enableZoom) {
            return;
          }
          if (this._animationId != -1) {
            cancelAnimationFrame(this._animationId);
            this._animationId = -1;
            this._timeStart = -1;
            this.activateGizmos(false);
            this.dispatchEvent(_changeEvent);
          }
          this.updateTbState(STATE.FOV, true);
          this._startCursorPosition.setY(this.getCursorNDC(_center.x, _center.y, this.domElement).y * 0.5);
          this._currentCursorPosition.copy(this._startCursorPosition);
          break;
        case "ZOOM":
          if (!this.enableZoom) {
            return;
          }
          if (this._animationId != -1) {
            cancelAnimationFrame(this._animationId);
            this._animationId = -1;
            this._timeStart = -1;
            this.activateGizmos(false);
            this.dispatchEvent(_changeEvent);
          }
          this.updateTbState(STATE.SCALE, true);
          this._startCursorPosition.setY(this.getCursorNDC(_center.x, _center.y, this.domElement).y * 0.5);
          this._currentCursorPosition.copy(this._startCursorPosition);
          break;
      }
    }
  }
  onSinglePanMove(event, opState) {
    if (this.enabled) {
      const restart = opState != this._state;
      this.setCenter(event.clientX, event.clientY);
      switch (opState) {
        case STATE.PAN:
          if (this.enablePan) {
            if (restart) {
              this.dispatchEvent(_endEvent);
              this.dispatchEvent(_startEvent);
              this.updateTbState(opState, true);
              this._startCursorPosition.copy(this.unprojectOnTbPlane(this.object, _center.x, _center.y, this.domElement));
              if (this.enableGrid) {
                this.drawGrid();
              }
              this.activateGizmos(false);
            } else {
              this._currentCursorPosition.copy(this.unprojectOnTbPlane(this.object, _center.x, _center.y, this.domElement));
              this.applyTransformMatrix(this.pan(this._startCursorPosition, this._currentCursorPosition));
            }
          }
          break;
        case STATE.ROTATE:
          if (this.enableRotate) {
            if (restart) {
              this.dispatchEvent(_endEvent);
              this.dispatchEvent(_startEvent);
              this.updateTbState(opState, true);
              this._startCursorPosition.copy(this.unprojectOnTbSurface(this.object, _center.x, _center.y, this.domElement, this._tbRadius));
              if (this.enableGrid) {
                this.disposeGrid();
              }
              this.activateGizmos(true);
            } else {
              this._currentCursorPosition.copy(this.unprojectOnTbSurface(this.object, _center.x, _center.y, this.domElement, this._tbRadius));
              const distance = this._startCursorPosition.distanceTo(this._currentCursorPosition);
              const angle = this._startCursorPosition.angleTo(this._currentCursorPosition);
              const amount = Math.max(distance / this._tbRadius, angle) * this.rotateSpeed;
              this.applyTransformMatrix(this.rotate(this.calculateRotationAxis(this._startCursorPosition, this._currentCursorPosition), amount));
              if (this.enableAnimations) {
                this._timePrev = this._timeCurrent;
                this._timeCurrent = performance.now();
                this._anglePrev = this._angleCurrent;
                this._angleCurrent = amount;
                this._cursorPosPrev.copy(this._cursorPosCurr);
                this._cursorPosCurr.copy(this._currentCursorPosition);
                this._wPrev = this._wCurr;
                this._wCurr = this.calculateAngularSpeed(this._anglePrev, this._angleCurrent, this._timePrev, this._timeCurrent);
              }
            }
          }
          break;
        case STATE.SCALE:
          if (this.enableZoom) {
            if (restart) {
              this.dispatchEvent(_endEvent);
              this.dispatchEvent(_startEvent);
              this.updateTbState(opState, true);
              this._startCursorPosition.setY(this.getCursorNDC(_center.x, _center.y, this.domElement).y * 0.5);
              this._currentCursorPosition.copy(this._startCursorPosition);
              if (this.enableGrid) {
                this.disposeGrid();
              }
              this.activateGizmos(false);
            } else {
              const screenNotches = 8;
              this._currentCursorPosition.setY(this.getCursorNDC(_center.x, _center.y, this.domElement).y * 0.5);
              const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
              let size2 = 1;
              if (movement < 0) {
                size2 = 1 / Math.pow(this.scaleFactor, -movement * screenNotches);
              } else if (movement > 0) {
                size2 = Math.pow(this.scaleFactor, movement * screenNotches);
              }
              this._v3_1.setFromMatrixPosition(this._gizmoMatrixState);
              this.applyTransformMatrix(this.scale(size2, this._v3_1));
            }
          }
          break;
        case STATE.FOV:
          if (this.enableZoom && this.object.isPerspectiveCamera) {
            if (restart) {
              this.dispatchEvent(_endEvent);
              this.dispatchEvent(_startEvent);
              this.updateTbState(opState, true);
              this._startCursorPosition.setY(this.getCursorNDC(_center.x, _center.y, this.domElement).y * 0.5);
              this._currentCursorPosition.copy(this._startCursorPosition);
              if (this.enableGrid) {
                this.disposeGrid();
              }
              this.activateGizmos(false);
            } else {
              const screenNotches = 8;
              this._currentCursorPosition.setY(this.getCursorNDC(_center.x, _center.y, this.domElement).y * 0.5);
              const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
              let size2 = 1;
              if (movement < 0) {
                size2 = 1 / Math.pow(this.scaleFactor, -movement * screenNotches);
              } else if (movement > 0) {
                size2 = Math.pow(this.scaleFactor, movement * screenNotches);
              }
              this._v3_1.setFromMatrixPosition(this._cameraMatrixState);
              const x2 = this._v3_1.distanceTo(this._gizmos.position);
              let xNew = x2 / size2;
              xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance);
              const y = x2 * Math.tan(MathUtils.DEG2RAD * this._fovState * 0.5);
              let newFov = MathUtils.RAD2DEG * (Math.atan(y / xNew) * 2);
              newFov = MathUtils.clamp(newFov, this.minFov, this.maxFov);
              const newDistance = y / Math.tan(MathUtils.DEG2RAD * (newFov / 2));
              size2 = x2 / newDistance;
              this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);
              this.setFov(newFov);
              this.applyTransformMatrix(this.scale(size2, this._v3_2, false));
              _offset.copy(this._gizmos.position).sub(this.object.position).normalize().multiplyScalar(newDistance / x2);
              this._m4_1.makeTranslation(_offset.x, _offset.y, _offset.z);
            }
          }
          break;
      }
      this.dispatchEvent(_changeEvent);
    }
  }
  onSinglePanEnd() {
    if (this._state == STATE.ROTATE) {
      if (!this.enableRotate) {
        return;
      }
      if (this.enableAnimations) {
        const deltaTime = performance.now() - this._timeCurrent;
        if (deltaTime < 120) {
          const w = Math.abs((this._wPrev + this._wCurr) / 2);
          const self2 = this;
          this._animationId = window.requestAnimationFrame(function(t3) {
            self2.updateTbState(STATE.ANIMATION_ROTATE, true);
            const rotationAxis = self2.calculateRotationAxis(self2._cursorPosPrev, self2._cursorPosCurr);
            self2.onRotationAnim(t3, rotationAxis, Math.min(w, self2.wMax));
          });
        } else {
          this.updateTbState(STATE.IDLE, false);
          this.activateGizmos(false);
          this.dispatchEvent(_changeEvent);
        }
      } else {
        this.updateTbState(STATE.IDLE, false);
        this.activateGizmos(false);
        this.dispatchEvent(_changeEvent);
      }
    } else if (this._state == STATE.PAN || this._state == STATE.IDLE) {
      this.updateTbState(STATE.IDLE, false);
      if (this.enableGrid) {
        this.disposeGrid();
      }
      this.activateGizmos(false);
      this.dispatchEvent(_changeEvent);
    }
    this.dispatchEvent(_endEvent);
  }
  onDoubleTap(event) {
    if (this.enabled && this.enablePan && this.enableFocus && this.scene != null) {
      this.dispatchEvent(_startEvent);
      this.setCenter(event.clientX, event.clientY);
      const hitP = this.unprojectOnObj(this.getCursorNDC(_center.x, _center.y, this.domElement), this.object);
      if (hitP != null && this.enableAnimations) {
        const self2 = this;
        if (this._animationId != -1) {
          window.cancelAnimationFrame(this._animationId);
        }
        this._timeStart = -1;
        this._animationId = window.requestAnimationFrame(function(t3) {
          self2.updateTbState(STATE.ANIMATION_FOCUS, true);
          self2.onFocusAnim(t3, hitP, self2._cameraMatrixState, self2._gizmoMatrixState);
        });
      } else if (hitP != null && !this.enableAnimations) {
        this.updateTbState(STATE.FOCUS, true);
        this.focus(hitP, this.scaleFactor);
        this.updateTbState(STATE.IDLE, false);
        this.dispatchEvent(_changeEvent);
      }
    }
    this.dispatchEvent(_endEvent);
  }
  onDoublePanStart() {
    if (this.enabled && this.enablePan) {
      this.dispatchEvent(_startEvent);
      this.updateTbState(STATE.PAN, true);
      this.setCenter((this._touchCurrent[0].clientX + this._touchCurrent[1].clientX) / 2, (this._touchCurrent[0].clientY + this._touchCurrent[1].clientY) / 2);
      this._startCursorPosition.copy(this.unprojectOnTbPlane(this.object, _center.x, _center.y, this.domElement, true));
      this._currentCursorPosition.copy(this._startCursorPosition);
      this.activateGizmos(false);
    }
  }
  onDoublePanMove() {
    if (this.enabled && this.enablePan) {
      this.setCenter((this._touchCurrent[0].clientX + this._touchCurrent[1].clientX) / 2, (this._touchCurrent[0].clientY + this._touchCurrent[1].clientY) / 2);
      if (this._state != STATE.PAN) {
        this.updateTbState(STATE.PAN, true);
        this._startCursorPosition.copy(this._currentCursorPosition);
      }
      this._currentCursorPosition.copy(this.unprojectOnTbPlane(this.object, _center.x, _center.y, this.domElement, true));
      this.applyTransformMatrix(this.pan(this._startCursorPosition, this._currentCursorPosition, true));
      this.dispatchEvent(_changeEvent);
    }
  }
  onDoublePanEnd() {
    this.updateTbState(STATE.IDLE, false);
    this.dispatchEvent(_endEvent);
  }
  onRotateStart() {
    if (this.enabled && this.enableRotate) {
      this.dispatchEvent(_startEvent);
      this.updateTbState(STATE.ZROTATE, true);
      this._startFingerRotation = this.getAngle(this._touchCurrent[1], this._touchCurrent[0]) + this.getAngle(this._touchStart[1], this._touchStart[0]);
      this._currentFingerRotation = this._startFingerRotation;
      this.object.getWorldDirection(this._rotationAxis);
      if (!this.enablePan && !this.enableZoom) {
        this.activateGizmos(true);
      }
    }
  }
  onRotateMove() {
    if (this.enabled && this.enableRotate) {
      this.setCenter((this._touchCurrent[0].clientX + this._touchCurrent[1].clientX) / 2, (this._touchCurrent[0].clientY + this._touchCurrent[1].clientY) / 2);
      let rotationPoint;
      if (this._state != STATE.ZROTATE) {
        this.updateTbState(STATE.ZROTATE, true);
        this._startFingerRotation = this._currentFingerRotation;
      }
      this._currentFingerRotation = this.getAngle(this._touchCurrent[1], this._touchCurrent[0]) + this.getAngle(this._touchStart[1], this._touchStart[0]);
      if (!this.enablePan) {
        rotationPoint = new Vector3().setFromMatrixPosition(this._gizmoMatrixState);
      } else {
        this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);
        rotationPoint = this.unprojectOnTbPlane(this.object, _center.x, _center.y, this.domElement).applyQuaternion(this.object.quaternion).multiplyScalar(1 / this.object.zoom).add(this._v3_2);
      }
      const amount = MathUtils.DEG2RAD * (this._startFingerRotation - this._currentFingerRotation);
      this.applyTransformMatrix(this.zRotate(rotationPoint, amount));
      this.dispatchEvent(_changeEvent);
    }
  }
  onRotateEnd() {
    this.updateTbState(STATE.IDLE, false);
    this.activateGizmos(false);
    this.dispatchEvent(_endEvent);
  }
  onPinchStart() {
    if (this.enabled && this.enableZoom) {
      this.dispatchEvent(_startEvent);
      this.updateTbState(STATE.SCALE, true);
      this._startFingerDistance = this.calculatePointersDistance(this._touchCurrent[0], this._touchCurrent[1]);
      this._currentFingerDistance = this._startFingerDistance;
      this.activateGizmos(false);
    }
  }
  onPinchMove() {
    if (this.enabled && this.enableZoom) {
      this.setCenter((this._touchCurrent[0].clientX + this._touchCurrent[1].clientX) / 2, (this._touchCurrent[0].clientY + this._touchCurrent[1].clientY) / 2);
      const minDistance = 12;
      if (this._state != STATE.SCALE) {
        this._startFingerDistance = this._currentFingerDistance;
        this.updateTbState(STATE.SCALE, true);
      }
      this._currentFingerDistance = Math.max(this.calculatePointersDistance(this._touchCurrent[0], this._touchCurrent[1]), minDistance * this._devPxRatio);
      const amount = this._currentFingerDistance / this._startFingerDistance;
      let scalePoint;
      if (!this.enablePan) {
        scalePoint = this._gizmos.position;
      } else {
        if (this.object.isOrthographicCamera) {
          scalePoint = this.unprojectOnTbPlane(this.object, _center.x, _center.y, this.domElement).applyQuaternion(this.object.quaternion).multiplyScalar(1 / this.object.zoom).add(this._gizmos.position);
        } else if (this.object.isPerspectiveCamera) {
          scalePoint = this.unprojectOnTbPlane(this.object, _center.x, _center.y, this.domElement).applyQuaternion(this.object.quaternion).add(this._gizmos.position);
        }
      }
      this.applyTransformMatrix(this.scale(amount, scalePoint));
      this.dispatchEvent(_changeEvent);
    }
  }
  onPinchEnd() {
    this.updateTbState(STATE.IDLE, false);
    this.dispatchEvent(_endEvent);
  }
  onTriplePanStart() {
    if (this.enabled && this.enableZoom) {
      this.dispatchEvent(_startEvent);
      this.updateTbState(STATE.SCALE, true);
      let clientX = 0;
      let clientY = 0;
      const nFingers = this._touchCurrent.length;
      for (let i = 0; i < nFingers; i++) {
        clientX += this._touchCurrent[i].clientX;
        clientY += this._touchCurrent[i].clientY;
      }
      this.setCenter(clientX / nFingers, clientY / nFingers);
      this._startCursorPosition.setY(this.getCursorNDC(_center.x, _center.y, this.domElement).y * 0.5);
      this._currentCursorPosition.copy(this._startCursorPosition);
    }
  }
  onTriplePanMove() {
    if (this.enabled && this.enableZoom) {
      let clientX = 0;
      let clientY = 0;
      const nFingers = this._touchCurrent.length;
      for (let i = 0; i < nFingers; i++) {
        clientX += this._touchCurrent[i].clientX;
        clientY += this._touchCurrent[i].clientY;
      }
      this.setCenter(clientX / nFingers, clientY / nFingers);
      const screenNotches = 8;
      this._currentCursorPosition.setY(this.getCursorNDC(_center.x, _center.y, this.domElement).y * 0.5);
      const movement = this._currentCursorPosition.y - this._startCursorPosition.y;
      let size2 = 1;
      if (movement < 0) {
        size2 = 1 / Math.pow(this.scaleFactor, -movement * screenNotches);
      } else if (movement > 0) {
        size2 = Math.pow(this.scaleFactor, movement * screenNotches);
      }
      this._v3_1.setFromMatrixPosition(this._cameraMatrixState);
      const x2 = this._v3_1.distanceTo(this._gizmos.position);
      let xNew = x2 / size2;
      xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance);
      const y = x2 * Math.tan(MathUtils.DEG2RAD * this._fovState * 0.5);
      let newFov = MathUtils.RAD2DEG * (Math.atan(y / xNew) * 2);
      newFov = MathUtils.clamp(newFov, this.minFov, this.maxFov);
      const newDistance = y / Math.tan(MathUtils.DEG2RAD * (newFov / 2));
      size2 = x2 / newDistance;
      this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);
      this.setFov(newFov);
      this.applyTransformMatrix(this.scale(size2, this._v3_2, false));
      _offset.copy(this._gizmos.position).sub(this.object.position).normalize().multiplyScalar(newDistance / x2);
      this._m4_1.makeTranslation(_offset.x, _offset.y, _offset.z);
      this.dispatchEvent(_changeEvent);
    }
  }
  onTriplePanEnd() {
    this.updateTbState(STATE.IDLE, false);
    this.dispatchEvent(_endEvent);
  }
  /**
   * Set _center's x/y coordinates.
   *
   * @private
   * @param {number} clientX - The x coordinate.
   * @param {number} clientY - The y coordinate.
   */
  setCenter(clientX, clientY) {
    _center.x = clientX;
    _center.y = clientY;
  }
  /**
   * Set default mouse actions.
   *
   * @private
   */
  initializeMouseActions() {
    this.setMouseAction("PAN", 0, "CTRL");
    this.setMouseAction("PAN", 2);
    this.setMouseAction("ROTATE", 0);
    this.setMouseAction("ZOOM", "WHEEL");
    this.setMouseAction("ZOOM", 1);
    this.setMouseAction("FOV", "WHEEL", "SHIFT");
    this.setMouseAction("FOV", 1, "SHIFT");
  }
  /**
   * Compare two mouse actions.
   *
   * @private
   * @param {Object} action1 - The first mouse action.
   * @param {Object} action2 - The second mouse action.
   * @returns {boolean} `true` if action1 and action 2 are the same mouse action, `false` otherwise.
   */
  compareMouseAction(action1, action2) {
    if (action1.operation == action2.operation) {
      if (action1.mouse == action2.mouse && action1.key == action2.key) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  /**
   * Set a new mouse action by specifying the operation to be performed and a mouse/key combination. In case of conflict, replaces the existing one.
   *
   * @param {'PAN'|'ROTATE'|'ZOOM'|'FOV'} operation - The operation to be performed ('PAN', 'ROTATE', 'ZOOM', 'FOV').
   * @param {0|1|2|'WHEEL'} mouse - A mouse button (0, 1, 2) or 'WHEEL' for wheel notches.
   * @param {'CTRL'|'SHIFT'|null} [key=null] - The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed.
   * @returns {boolean} `true` if the mouse action has been successfully added, `false` otherwise.
   */
  setMouseAction(operation, mouse, key2 = null) {
    const operationInput = ["PAN", "ROTATE", "ZOOM", "FOV"];
    const mouseInput = [0, 1, 2, "WHEEL"];
    const keyInput = ["CTRL", "SHIFT", null];
    let state;
    if (!operationInput.includes(operation) || !mouseInput.includes(mouse) || !keyInput.includes(key2)) {
      return false;
    }
    if (mouse == "WHEEL") {
      if (operation != "ZOOM" && operation != "FOV") {
        return false;
      }
    }
    switch (operation) {
      case "PAN":
        state = STATE.PAN;
        break;
      case "ROTATE":
        state = STATE.ROTATE;
        break;
      case "ZOOM":
        state = STATE.SCALE;
        break;
      case "FOV":
        state = STATE.FOV;
        break;
    }
    const action = {
      operation,
      mouse,
      key: key2,
      state
    };
    for (let i = 0; i < this.mouseActions.length; i++) {
      if (this.mouseActions[i].mouse == action.mouse && this.mouseActions[i].key == action.key) {
        this.mouseActions.splice(i, 1, action);
        return true;
      }
    }
    this.mouseActions.push(action);
    return true;
  }
  /**
   * Remove a mouse action by specifying its mouse/key combination.
   *
   * @param {0|1|2|'WHEEL'} mouse - A mouse button (0, 1, 2) or 'WHEEL' for wheel notches.
   * @param {'CTRL'|'SHIFT'|null} key - The keyboard modifier ('CTRL', 'SHIFT') or null if key is not needed.
   * @returns {boolean} `true` if the operation has been successfully removed, `false` otherwise.
   */
  unsetMouseAction(mouse, key2 = null) {
    for (let i = 0; i < this.mouseActions.length; i++) {
      if (this.mouseActions[i].mouse == mouse && this.mouseActions[i].key == key2) {
        this.mouseActions.splice(i, 1);
        return true;
      }
    }
    return false;
  }
  /**
   * Return the operation associated to a mouse/keyboard combination.
   *
   * @private
   * @param {0|1|2|'WHEEL'} mouse - Mouse button index (0, 1, 2) or 'WHEEL' for wheel notches.
   * @param {'CTRL'|'SHIFT'|null} key - Keyboard modifier.
   * @returns {'PAN'|'ROTATE'|'ZOOM'|'FOV'|null} The operation if it has been found, `null` otherwise.
   */
  getOpFromAction(mouse, key2) {
    let action;
    for (let i = 0; i < this.mouseActions.length; i++) {
      action = this.mouseActions[i];
      if (action.mouse == mouse && action.key == key2) {
        return action.operation;
      }
    }
    if (key2 != null) {
      for (let i = 0; i < this.mouseActions.length; i++) {
        action = this.mouseActions[i];
        if (action.mouse == mouse && action.key == null) {
          return action.operation;
        }
      }
    }
    return null;
  }
  /**
   * Get the operation associated to mouse and key combination and returns the corresponding FSA state.
   *
   * @private
   * @param {0|1|2} mouse - Mouse button index (0, 1, 2)
   * @param {'CTRL'|'SHIFT'|null} key - Keyboard modifier
   * @returns {?STATE} The FSA state obtained from the operation associated to mouse/keyboard combination.
   */
  getOpStateFromAction(mouse, key2) {
    let action;
    for (let i = 0; i < this.mouseActions.length; i++) {
      action = this.mouseActions[i];
      if (action.mouse == mouse && action.key == key2) {
        return action.state;
      }
    }
    if (key2 != null) {
      for (let i = 0; i < this.mouseActions.length; i++) {
        action = this.mouseActions[i];
        if (action.mouse == mouse && action.key == null) {
          return action.state;
        }
      }
    }
    return null;
  }
  /**
   * Calculate the angle between two pointers.
   *
   * @private
   * @param {PointerEvent} p1 - The first pointer event.
   * @param {PointerEvent} p2 - The second pointer event.
   * @returns {number} The angle between two pointers in degrees.
   */
  getAngle(p1, p2) {
    return Math.atan2(p2.clientY - p1.clientY, p2.clientX - p1.clientX) * 180 / Math.PI;
  }
  /**
   * Updates a PointerEvent inside current pointerevents array.
   *
   * @private
   * @param {PointerEvent} event - The pointer event.
   */
  updateTouchEvent(event) {
    for (let i = 0; i < this._touchCurrent.length; i++) {
      if (this._touchCurrent[i].pointerId == event.pointerId) {
        this._touchCurrent.splice(i, 1, event);
        break;
      }
    }
  }
  /**
   * Applies a transformation matrix, to the camera and gizmos.
   *
   * @private
   * @param {Object} transformation - Object containing matrices to apply to camera and gizmos.
   */
  applyTransformMatrix(transformation) {
    if (transformation.camera != null) {
      this._m4_1.copy(this._cameraMatrixState).premultiply(transformation.camera);
      this._m4_1.decompose(this.object.position, this.object.quaternion, this.object.scale);
      this.object.updateMatrix();
      if (this._state == STATE.ROTATE || this._state == STATE.ZROTATE || this._state == STATE.ANIMATION_ROTATE) {
        this.object.up.copy(this._upState).applyQuaternion(this.object.quaternion);
      }
    }
    if (transformation.gizmos != null) {
      this._m4_1.copy(this._gizmoMatrixState).premultiply(transformation.gizmos);
      this._m4_1.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale);
      this._gizmos.updateMatrix();
    }
    if (this._state == STATE.SCALE || this._state == STATE.FOCUS || this._state == STATE.ANIMATION_FOCUS) {
      this._tbRadius = this.calculateTbRadius(this.object);
      if (this.adjustNearFar) {
        const cameraDistance = this.object.position.distanceTo(this._gizmos.position);
        const bb = new Box3();
        bb.setFromObject(this._gizmos);
        const sphere = new Sphere();
        bb.getBoundingSphere(sphere);
        const adjustedNearPosition = Math.max(this._nearPos0, sphere.radius + sphere.center.length());
        const regularNearPosition = cameraDistance - this._initialNear;
        const minNearPos = Math.min(adjustedNearPosition, regularNearPosition);
        this.object.near = cameraDistance - minNearPos;
        const adjustedFarPosition = Math.min(this._farPos0, -sphere.radius + sphere.center.length());
        const regularFarPosition = cameraDistance - this._initialFar;
        const minFarPos = Math.min(adjustedFarPosition, regularFarPosition);
        this.object.far = cameraDistance - minFarPos;
        this.object.updateProjectionMatrix();
      } else {
        let update = false;
        if (this.object.near != this._initialNear) {
          this.object.near = this._initialNear;
          update = true;
        }
        if (this.object.far != this._initialFar) {
          this.object.far = this._initialFar;
          update = true;
        }
        if (update) {
          this.object.updateProjectionMatrix();
        }
      }
    }
  }
  /**
   * Calculates the angular speed.
   *
   * @private
   * @param {number} p0 - Position at t0.
   * @param {number} p1 - Position at t1.
   * @param {number} t0 - Initial time in milliseconds.
   * @param {number} t1 - Ending time in milliseconds.
   * @returns {number} The angular speed.
   */
  calculateAngularSpeed(p0, p1, t0, t1) {
    const s = p1 - p0;
    const t3 = (t1 - t0) / 1e3;
    if (t3 == 0) {
      return 0;
    }
    return s / t3;
  }
  /**
   * Calculates the distance between two pointers.
   *
   * @private
   * @param {PointerEvent} p0 - The first pointer.
   * @param {PointerEvent} p1 - The second pointer.
   * @returns {number} The distance between the two pointers.
   */
  calculatePointersDistance(p0, p1) {
    return Math.sqrt(Math.pow(p1.clientX - p0.clientX, 2) + Math.pow(p1.clientY - p0.clientY, 2));
  }
  /**
   * Calculates the rotation axis as the vector perpendicular between two vectors.
   *
   * @private
   * @param {Vector3} vec1 - The first vector.
   * @param {Vector3} vec2 - The second vector.
   * @returns {Vector3} The normalized rotation axis.
   */
  calculateRotationAxis(vec1, vec2) {
    this._rotationMatrix.extractRotation(this._cameraMatrixState);
    this._quat.setFromRotationMatrix(this._rotationMatrix);
    this._rotationAxis.crossVectors(vec1, vec2).applyQuaternion(this._quat);
    return this._rotationAxis.normalize().clone();
  }
  /**
   * Calculates the trackball radius so that gizmo's diameter will be 2/3 of the minimum side of the camera frustum.
   *
   * @private
   * @param {Camera} camera - The camera.
   * @returns {number} The trackball radius.
   */
  calculateTbRadius(camera) {
    const distance = camera.position.distanceTo(this._gizmos.position);
    if (camera.type == "PerspectiveCamera") {
      const halfFovV = MathUtils.DEG2RAD * camera.fov * 0.5;
      const halfFovH = Math.atan(camera.aspect * Math.tan(halfFovV));
      return Math.tan(Math.min(halfFovV, halfFovH)) * distance * this.radiusFactor;
    } else if (camera.type == "OrthographicCamera") {
      return Math.min(camera.top, camera.right) * this.radiusFactor;
    }
  }
  /**
   * Focus operation consist of positioning the point of interest in front of the camera and a slightly zoom in.
   *
   * @private
   * @param {Vector3} point - The point of interest.
   * @param {number} size - Scale factor.
   * @param {number} [amount=1] - Amount of operation to be completed (used for focus animations, default is complete full operation).
   */
  focus(point, size2, amount = 1) {
    _offset.copy(point).sub(this._gizmos.position).multiplyScalar(amount);
    this._translationMatrix.makeTranslation(_offset.x, _offset.y, _offset.z);
    _gizmoMatrixStateTemp.copy(this._gizmoMatrixState);
    this._gizmoMatrixState.premultiply(this._translationMatrix);
    this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale);
    _cameraMatrixStateTemp.copy(this._cameraMatrixState);
    this._cameraMatrixState.premultiply(this._translationMatrix);
    this._cameraMatrixState.decompose(this.object.position, this.object.quaternion, this.object.scale);
    if (this.enableZoom) {
      this.applyTransformMatrix(this.scale(size2, this._gizmos.position));
    }
    this._gizmoMatrixState.copy(_gizmoMatrixStateTemp);
    this._cameraMatrixState.copy(_cameraMatrixStateTemp);
  }
  /**
   * Creates a grid if necessary and adds it to the scene.
   *
   * @private
   */
  drawGrid() {
    if (this.scene != null) {
      const color = 8947848;
      const multiplier = 3;
      let size2, divisions, maxLength, tick;
      if (this.object.isOrthographicCamera) {
        const width2 = this.object.right - this.object.left;
        const height2 = this.object.bottom - this.object.top;
        maxLength = Math.max(width2, height2);
        tick = maxLength / 20;
        size2 = maxLength / this.object.zoom * multiplier;
        divisions = size2 / tick * this.object.zoom;
      } else if (this.object.isPerspectiveCamera) {
        const distance = this.object.position.distanceTo(this._gizmos.position);
        const halfFovV = MathUtils.DEG2RAD * this.object.fov * 0.5;
        const halfFovH = Math.atan(this.object.aspect * Math.tan(halfFovV));
        maxLength = Math.tan(Math.max(halfFovV, halfFovH)) * distance * 2;
        tick = maxLength / 20;
        size2 = maxLength * multiplier;
        divisions = size2 / tick;
      }
      if (this._grid == null) {
        this._grid = new GridHelper(size2, divisions, color, color);
        this._grid.position.copy(this._gizmos.position);
        this._gridPosition.copy(this._grid.position);
        this._grid.quaternion.copy(this.object.quaternion);
        this._grid.rotateX(Math.PI * 0.5);
        this.scene.add(this._grid);
      }
    }
  }
  dispose() {
    if (this._animationId != -1) {
      window.cancelAnimationFrame(this._animationId);
    }
    this.disconnect();
    if (this.scene !== null) this.scene.remove(this._gizmos);
    this.disposeGrid();
  }
  /**
   * Removes the grid from the scene.
   */
  disposeGrid() {
    if (this._grid != null && this.scene != null) {
      this.scene.remove(this._grid);
      this._grid = null;
    }
  }
  /**
   * Computes the easing out cubic function for ease out effect in animation.
   *
   * @private
   * @param {number} t - The absolute progress of the animation in the bound of `0` (beginning of the) and `1` (ending of animation).
   * @returns {number} Result of easing out cubic at time `t`.
   */
  easeOutCubic(t3) {
    return 1 - Math.pow(1 - t3, 3);
  }
  /**
   * Makes rotation gizmos more or less visible.
   *
   * @param {boolean} isActive - If set to `true`, gizmos are more visible.
   */
  activateGizmos(isActive) {
    const gizmoX = this._gizmos.children[0];
    const gizmoY = this._gizmos.children[1];
    const gizmoZ = this._gizmos.children[2];
    if (isActive) {
      gizmoX.material.setValues({ opacity: 1 });
      gizmoY.material.setValues({ opacity: 1 });
      gizmoZ.material.setValues({ opacity: 1 });
    } else {
      gizmoX.material.setValues({ opacity: 0.6 });
      gizmoY.material.setValues({ opacity: 0.6 });
      gizmoZ.material.setValues({ opacity: 0.6 });
    }
  }
  /**
   * Calculates the cursor position in NDC.
   *
   * @private
   * @param {number} cursorX - Cursor horizontal coordinate within the canvas.
   * @param {number} cursorY - Cursor vertical coordinate within the canvas.
   * @param {HTMLElement} canvas - The canvas where the renderer draws its output.
   * @returns {Vector2} Cursor normalized position inside the canvas.
   */
  getCursorNDC(cursorX, cursorY, canvas) {
    const canvasRect = canvas.getBoundingClientRect();
    this._v2_1.setX((cursorX - canvasRect.left) / canvasRect.width * 2 - 1);
    this._v2_1.setY((canvasRect.bottom - cursorY) / canvasRect.height * 2 - 1);
    return this._v2_1.clone();
  }
  /**
   * Calculates the cursor position inside the canvas x/y coordinates with the origin being in the center of the canvas.
   *
   * @private
   * @param {number} cursorX - Cursor horizontal coordinate within the canvas.
   * @param {number} cursorY - Cursor vertical coordinate within the canvas.
   * @param {HTMLElement} canvas - The canvas where the renderer draws its output.
   * @returns {Vector2} Cursor position inside the canvas.
   */
  getCursorPosition(cursorX, cursorY, canvas) {
    this._v2_1.copy(this.getCursorNDC(cursorX, cursorY, canvas));
    this._v2_1.x *= (this.object.right - this.object.left) * 0.5;
    this._v2_1.y *= (this.object.top - this.object.bottom) * 0.5;
    return this._v2_1.clone();
  }
  /**
   * Sets the camera to be controlled.  Must be called in order to set a new camera to be controlled.
   *
   * @param {Camera} camera - The camera to be controlled.
   */
  setCamera(camera) {
    camera.lookAt(this.target);
    camera.updateMatrix();
    if (camera.type == "PerspectiveCamera") {
      this._fov0 = camera.fov;
      this._fovState = camera.fov;
    }
    this._cameraMatrixState0.copy(camera.matrix);
    this._cameraMatrixState.copy(this._cameraMatrixState0);
    this._cameraProjectionState.copy(camera.projectionMatrix);
    this._zoom0 = camera.zoom;
    this._zoomState = this._zoom0;
    this._initialNear = camera.near;
    this._nearPos0 = camera.position.distanceTo(this.target) - camera.near;
    this._nearPos = this._initialNear;
    this._initialFar = camera.far;
    this._farPos0 = camera.position.distanceTo(this.target) - camera.far;
    this._farPos = this._initialFar;
    this._up0.copy(camera.up);
    this._upState.copy(camera.up);
    this.object = camera;
    this.object.updateProjectionMatrix();
    this._tbRadius = this.calculateTbRadius(camera);
    this.makeGizmos(this.target, this._tbRadius);
  }
  /**
   * Sets gizmos visibility.
   *
   * @param {boolean} value - Value of gizmos visibility.
   */
  setGizmosVisible(value2) {
    this._gizmos.visible = value2;
    this.dispatchEvent(_changeEvent);
  }
  /**
   * Sets gizmos radius factor and redraws gizmos.
   *
   * @param {number} value - Value of radius factor.
   */
  setTbRadius(value2) {
    this.radiusFactor = value2;
    this._tbRadius = this.calculateTbRadius(this.object);
    const curve = new EllipseCurve(0, 0, this._tbRadius, this._tbRadius);
    const points = curve.getPoints(this._curvePts);
    const curveGeometry = new BufferGeometry().setFromPoints(points);
    for (const gizmo in this._gizmos.children) {
      this._gizmos.children[gizmo].geometry = curveGeometry;
    }
    this.dispatchEvent(_changeEvent);
  }
  /**
   * Creates the rotation gizmos matching trackball center and radius.
   *
   * @private
   * @param {Vector3} tbCenter - The trackball center.
   * @param {number} tbRadius - The trackball radius.
   */
  makeGizmos(tbCenter, tbRadius) {
    const curve = new EllipseCurve(0, 0, tbRadius, tbRadius);
    const points = curve.getPoints(this._curvePts);
    const curveGeometry = new BufferGeometry().setFromPoints(points);
    const curveMaterialX = new LineBasicMaterial({ color: 16744576, fog: false, transparent: true, opacity: 0.6 });
    const curveMaterialY = new LineBasicMaterial({ color: 8454016, fog: false, transparent: true, opacity: 0.6 });
    const curveMaterialZ = new LineBasicMaterial({ color: 8421631, fog: false, transparent: true, opacity: 0.6 });
    const gizmoX = new Line(curveGeometry, curveMaterialX);
    const gizmoY = new Line(curveGeometry, curveMaterialY);
    const gizmoZ = new Line(curveGeometry, curveMaterialZ);
    const rotation2 = Math.PI * 0.5;
    gizmoX.rotation.x = rotation2;
    gizmoY.rotation.y = rotation2;
    this._gizmoMatrixState0.identity().setPosition(tbCenter);
    this._gizmoMatrixState.copy(this._gizmoMatrixState0);
    if (this.object.zoom !== 1) {
      const size2 = 1 / this.object.zoom;
      this._scaleMatrix.makeScale(size2, size2, size2);
      this._translationMatrix.makeTranslation(-tbCenter.x, -tbCenter.y, -tbCenter.z);
      this._gizmoMatrixState.premultiply(this._translationMatrix).premultiply(this._scaleMatrix);
      this._translationMatrix.makeTranslation(tbCenter.x, tbCenter.y, tbCenter.z);
      this._gizmoMatrixState.premultiply(this._translationMatrix);
    }
    this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale);
    this._gizmos.traverse(function(object) {
      if (object.isLine) {
        object.geometry.dispose();
        object.material.dispose();
      }
    });
    this._gizmos.clear();
    this._gizmos.add(gizmoX);
    this._gizmos.add(gizmoY);
    this._gizmos.add(gizmoZ);
  }
  /**
   * Performs animation for focus operation.
   *
   * @private
   * @param {number} time - Instant in which this function is called as performance.now().
   * @param {Vector3} point - Point of interest for focus operation.
   * @param {Matrix4} cameraMatrix - Camera matrix.
   * @param {Matrix4} gizmoMatrix - Gizmos matrix.
   */
  onFocusAnim(time2, point, cameraMatrix, gizmoMatrix) {
    if (this._timeStart == -1) {
      this._timeStart = time2;
    }
    if (this._state == STATE.ANIMATION_FOCUS) {
      const deltaTime = time2 - this._timeStart;
      const animTime = deltaTime / this.focusAnimationTime;
      this._gizmoMatrixState.copy(gizmoMatrix);
      if (animTime >= 1) {
        this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale);
        this.focus(point, this.scaleFactor);
        this._timeStart = -1;
        this.updateTbState(STATE.IDLE, false);
        this.activateGizmos(false);
        this.dispatchEvent(_changeEvent);
      } else {
        const amount = this.easeOutCubic(animTime);
        const size2 = 1 - amount + this.scaleFactor * amount;
        this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale);
        this.focus(point, size2, amount);
        this.dispatchEvent(_changeEvent);
        const self2 = this;
        this._animationId = window.requestAnimationFrame(function(t3) {
          self2.onFocusAnim(t3, point, cameraMatrix, gizmoMatrix.clone());
        });
      }
    } else {
      this._animationId = -1;
      this._timeStart = -1;
    }
  }
  /**
   * Performs animation for rotation operation.
   *
   * @private
   * @param {number} time - Instant in which this function is called as performance.now().
   * @param {Vector3} rotationAxis - Rotation axis.
   * @param {number} w0 - Initial angular velocity.
   */
  onRotationAnim(time2, rotationAxis, w0) {
    if (this._timeStart == -1) {
      this._anglePrev = 0;
      this._angleCurrent = 0;
      this._timeStart = time2;
    }
    if (this._state == STATE.ANIMATION_ROTATE) {
      const deltaTime = (time2 - this._timeStart) / 1e3;
      const w = w0 + -this.dampingFactor * deltaTime;
      if (w > 0) {
        this._angleCurrent = 0.5 * -this.dampingFactor * Math.pow(deltaTime, 2) + w0 * deltaTime + 0;
        this.applyTransformMatrix(this.rotate(rotationAxis, this._angleCurrent));
        this.dispatchEvent(_changeEvent);
        const self2 = this;
        this._animationId = window.requestAnimationFrame(function(t3) {
          self2.onRotationAnim(t3, rotationAxis, w0);
        });
      } else {
        this._animationId = -1;
        this._timeStart = -1;
        this.updateTbState(STATE.IDLE, false);
        this.activateGizmos(false);
        this.dispatchEvent(_changeEvent);
      }
    } else {
      this._animationId = -1;
      this._timeStart = -1;
      if (this._state != STATE.ROTATE) {
        this.activateGizmos(false);
        this.dispatchEvent(_changeEvent);
      }
    }
  }
  /**
   * Performs pan operation moving camera between two points.
   *
   * @private
   * @param {Vector3} p0 - Initial point.
   * @param {Vector3} p1 - Ending point.
   * @param {boolean} [adjust=false] - If movement should be adjusted considering camera distance (Perspective only).
   * @returns {Object}
   */
  pan(p0, p1, adjust = false) {
    const movement = p0.clone().sub(p1);
    if (this.object.isOrthographicCamera) {
      movement.multiplyScalar(1 / this.object.zoom);
    } else if (this.object.isPerspectiveCamera && adjust) {
      this._v3_1.setFromMatrixPosition(this._cameraMatrixState0);
      this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0);
      const distanceFactor = this._v3_1.distanceTo(this._v3_2) / this.object.position.distanceTo(this._gizmos.position);
      movement.multiplyScalar(1 / distanceFactor);
    }
    this._v3_1.set(movement.x, movement.y, 0).applyQuaternion(this.object.quaternion);
    this._m4_1.makeTranslation(this._v3_1.x, this._v3_1.y, this._v3_1.z);
    this.setTransformationMatrices(this._m4_1, this._m4_1);
    return _transformation;
  }
  /**
   * Resets the controls.
   */
  reset() {
    this.target.copy(this._target0);
    this.object.zoom = this._zoom0;
    if (this.object.isPerspectiveCamera) {
      this.object.fov = this._fov0;
    }
    this.object.near = this._nearPos;
    this.object.far = this._farPos;
    this._cameraMatrixState.copy(this._cameraMatrixState0);
    this._cameraMatrixState.decompose(this.object.position, this.object.quaternion, this.object.scale);
    this.object.up.copy(this._up0);
    this.object.updateMatrix();
    this.object.updateProjectionMatrix();
    this._gizmoMatrixState.copy(this._gizmoMatrixState0);
    this._gizmoMatrixState0.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale);
    this._gizmos.updateMatrix();
    this._tbRadius = this.calculateTbRadius(this.object);
    this.makeGizmos(this._gizmos.position, this._tbRadius);
    this.object.lookAt(this._gizmos.position);
    this.updateTbState(STATE.IDLE, false);
    this.dispatchEvent(_changeEvent);
  }
  /**
   * Rotates the camera around an axis passing by trackball's center.
   *
   * @private
   * @param {Vector3} axis - Rotation axis.
   * @param {number} angle - Angle in radians.
   * @returns {Object} Object with 'camera' field containing transformation matrix resulting from the operation to be applied to the camera.
   */
  rotate(axis, angle) {
    const point = this._gizmos.position;
    this._translationMatrix.makeTranslation(-point.x, -point.y, -point.z);
    this._rotationMatrix.makeRotationAxis(axis, -angle);
    this._m4_1.makeTranslation(point.x, point.y, point.z);
    this._m4_1.multiply(this._rotationMatrix);
    this._m4_1.multiply(this._translationMatrix);
    this.setTransformationMatrices(this._m4_1);
    return _transformation;
  }
  /**
   * Copy the current state to clipboard (as a readable JSON text).
   */
  copyState() {
    let state;
    if (this.object.isOrthographicCamera) {
      state = JSON.stringify({
        arcballState: {
          cameraFar: this.object.far,
          cameraMatrix: this.object.matrix,
          cameraNear: this.object.near,
          cameraUp: this.object.up,
          cameraZoom: this.object.zoom,
          gizmoMatrix: this._gizmos.matrix,
          target: this.target
        }
      });
    } else if (this.object.isPerspectiveCamera) {
      state = JSON.stringify({
        arcballState: {
          cameraFar: this.object.far,
          cameraFov: this.object.fov,
          cameraMatrix: this.object.matrix,
          cameraNear: this.object.near,
          cameraUp: this.object.up,
          cameraZoom: this.object.zoom,
          gizmoMatrix: this._gizmos.matrix,
          target: this.target
        }
      });
    }
    navigator.clipboard.writeText(state);
  }
  /**
   * Set the controls state from the clipboard, assumes that the clipboard stores a JSON
   * text as saved from `copyState()`.
   */
  pasteState() {
    const self2 = this;
    navigator.clipboard.readText().then(function resolved(value2) {
      self2.setStateFromJSON(value2);
    });
  }
  /**
   * Saves the current state of the control. This can later be recover with `reset()`.
   */
  saveState() {
    this.object.updateMatrix();
    this._gizmos.updateMatrix();
    this._target0.copy(this.target);
    this._cameraMatrixState0.copy(this.object.matrix);
    this._gizmoMatrixState0.copy(this._gizmos.matrix);
    this._nearPos = this.object.near;
    this._farPos = this.object.far;
    this._zoom0 = this.object.zoom;
    this._up0.copy(this.object.up);
    if (this.object.isPerspectiveCamera) {
      this._fov0 = this.object.fov;
    }
  }
  /**
   * Performs uniform scale operation around a given point.
   *
   * @private
   * @param {number} size - Scale factor.
   * @param {Vector3} point - Point around which scale.
   * @param {boolean} scaleGizmos - If gizmos should be scaled (Perspective only).
   * @returns {Object} Object with 'camera' and 'gizmo' fields containing transformation matrices resulting from the operation to be applied to the camera and gizmos.
   */
  scale(size2, point, scaleGizmos = true) {
    _scalePointTemp.copy(point);
    let sizeInverse = 1 / size2;
    if (this.object.isOrthographicCamera) {
      this.object.zoom = this._zoomState;
      this.object.zoom *= size2;
      if (this.object.zoom > this.maxZoom) {
        this.object.zoom = this.maxZoom;
        sizeInverse = this._zoomState / this.maxZoom;
      } else if (this.object.zoom < this.minZoom) {
        this.object.zoom = this.minZoom;
        sizeInverse = this._zoomState / this.minZoom;
      }
      this.object.updateProjectionMatrix();
      this._v3_1.setFromMatrixPosition(this._gizmoMatrixState);
      this._scaleMatrix.makeScale(sizeInverse, sizeInverse, sizeInverse);
      this._translationMatrix.makeTranslation(-this._v3_1.x, -this._v3_1.y, -this._v3_1.z);
      this._m4_2.makeTranslation(this._v3_1.x, this._v3_1.y, this._v3_1.z).multiply(this._scaleMatrix);
      this._m4_2.multiply(this._translationMatrix);
      _scalePointTemp.sub(this._v3_1);
      const amount = _scalePointTemp.clone().multiplyScalar(sizeInverse);
      _scalePointTemp.sub(amount);
      this._m4_1.makeTranslation(_scalePointTemp.x, _scalePointTemp.y, _scalePointTemp.z);
      this._m4_2.premultiply(this._m4_1);
      this.setTransformationMatrices(this._m4_1, this._m4_2);
      return _transformation;
    } else if (this.object.isPerspectiveCamera) {
      this._v3_1.setFromMatrixPosition(this._cameraMatrixState);
      this._v3_2.setFromMatrixPosition(this._gizmoMatrixState);
      let distance = this._v3_1.distanceTo(_scalePointTemp);
      let amount = distance - distance * sizeInverse;
      const newDistance = distance - amount;
      if (newDistance < this.minDistance) {
        sizeInverse = this.minDistance / distance;
        amount = distance - distance * sizeInverse;
      } else if (newDistance > this.maxDistance) {
        sizeInverse = this.maxDistance / distance;
        amount = distance - distance * sizeInverse;
      }
      _offset.copy(_scalePointTemp).sub(this._v3_1).normalize().multiplyScalar(amount);
      this._m4_1.makeTranslation(_offset.x, _offset.y, _offset.z);
      if (scaleGizmos) {
        const pos = this._v3_2;
        distance = pos.distanceTo(_scalePointTemp);
        amount = distance - distance * sizeInverse;
        _offset.copy(_scalePointTemp).sub(this._v3_2).normalize().multiplyScalar(amount);
        this._translationMatrix.makeTranslation(pos.x, pos.y, pos.z);
        this._scaleMatrix.makeScale(sizeInverse, sizeInverse, sizeInverse);
        this._m4_2.makeTranslation(_offset.x, _offset.y, _offset.z).multiply(this._translationMatrix);
        this._m4_2.multiply(this._scaleMatrix);
        this._translationMatrix.makeTranslation(-pos.x, -pos.y, -pos.z);
        this._m4_2.multiply(this._translationMatrix);
        this.setTransformationMatrices(this._m4_1, this._m4_2);
      } else {
        this.setTransformationMatrices(this._m4_1);
      }
      return _transformation;
    }
  }
  /**
   * Sets camera fov.
   *
   * @private
   * @param {number} value - The FOV to be set.
   */
  setFov(value2) {
    if (this.object.isPerspectiveCamera) {
      this.object.fov = MathUtils.clamp(value2, this.minFov, this.maxFov);
      this.object.updateProjectionMatrix();
    }
  }
  /**
   * Sets values in transformation object.
   *
   * @private
   * @param {Matrix4} [camera=null] - Transformation to be applied to the camera.
   * @param {Matrix4} [gizmos=null] - Transformation to be applied to gizmos.
   */
  setTransformationMatrices(camera = null, gizmos = null) {
    if (camera != null) {
      if (_transformation.camera != null) {
        _transformation.camera.copy(camera);
      } else {
        _transformation.camera = camera.clone();
      }
    } else {
      _transformation.camera = null;
    }
    if (gizmos != null) {
      if (_transformation.gizmos != null) {
        _transformation.gizmos.copy(gizmos);
      } else {
        _transformation.gizmos = gizmos.clone();
      }
    } else {
      _transformation.gizmos = null;
    }
  }
  /**
   * Rotates camera around its direction axis passing by a given point by a given angle.
   *
   * @private
   * @param {Vector3} point - The point where the rotation axis is passing trough.
   * @param {number} angle - Angle in radians.
   * @returns {Object} The computed transformation matrix.
   */
  zRotate(point, angle) {
    this._rotationMatrix.makeRotationAxis(this._rotationAxis, angle);
    this._translationMatrix.makeTranslation(-point.x, -point.y, -point.z);
    this._m4_1.makeTranslation(point.x, point.y, point.z);
    this._m4_1.multiply(this._rotationMatrix);
    this._m4_1.multiply(this._translationMatrix);
    this._v3_1.setFromMatrixPosition(this._gizmoMatrixState).sub(point);
    this._v3_2.copy(this._v3_1).applyAxisAngle(this._rotationAxis, angle);
    this._v3_2.sub(this._v3_1);
    this._m4_2.makeTranslation(this._v3_2.x, this._v3_2.y, this._v3_2.z);
    this.setTransformationMatrices(this._m4_1, this._m4_2);
    return _transformation;
  }
  /**
   * Returns the raycaster that is used for user interaction. This object is shared between all
   * instances of `ArcballControls`.
   *
   * @returns {Raycaster} The internal raycaster.
   */
  getRaycaster() {
    return _raycaster;
  }
  /**
   * Unprojects the cursor on the 3D object surface.
   *
   * @private
   * @param {Vector2} cursor - Cursor coordinates in NDC.
   * @param {Camera} camera - Virtual camera.
   * @returns {?Vector3} The point of intersection with the model, if exist, null otherwise.
   */
  unprojectOnObj(cursor, camera) {
    const raycaster = this.getRaycaster();
    raycaster.near = camera.near;
    raycaster.far = camera.far;
    raycaster.setFromCamera(cursor, camera);
    const intersect = raycaster.intersectObjects(this.scene.children, true);
    for (let i = 0; i < intersect.length; i++) {
      if (intersect[i].object.uuid != this._gizmos.uuid && intersect[i].face != null) {
        return intersect[i].point.clone();
      }
    }
    return null;
  }
  /**
   * Unproject the cursor on the trackball surface.
   *
   * @private
   * @param {Camera} camera - The virtual camera.
   * @param {number} cursorX - Cursor horizontal coordinate on screen.
   * @param {number} cursorY - Cursor vertical coordinate on screen.
   * @param {HTMLElement} canvas - The canvas where the renderer draws its output.
   * @param {number} tbRadius - The trackball radius.
   * @returns {Vector3} The unprojected point on the trackball surface.
   */
  unprojectOnTbSurface(camera, cursorX, cursorY, canvas, tbRadius) {
    if (camera.type == "OrthographicCamera") {
      this._v2_1.copy(this.getCursorPosition(cursorX, cursorY, canvas));
      this._v3_1.set(this._v2_1.x, this._v2_1.y, 0);
      const x2 = Math.pow(this._v2_1.x, 2);
      const y2 = Math.pow(this._v2_1.y, 2);
      const r2 = Math.pow(this._tbRadius, 2);
      if (x2 + y2 <= r2 * 0.5) {
        this._v3_1.setZ(Math.sqrt(r2 - (x2 + y2)));
      } else {
        this._v3_1.setZ(r2 * 0.5 / Math.sqrt(x2 + y2));
      }
      return this._v3_1;
    } else if (camera.type == "PerspectiveCamera") {
      this._v2_1.copy(this.getCursorNDC(cursorX, cursorY, canvas));
      this._v3_1.set(this._v2_1.x, this._v2_1.y, -1);
      this._v3_1.applyMatrix4(camera.projectionMatrixInverse);
      const rayDir = this._v3_1.clone().normalize();
      const cameraGizmoDistance = camera.position.distanceTo(this._gizmos.position);
      const radius2 = Math.pow(tbRadius, 2);
      const h = this._v3_1.z;
      const l2 = Math.sqrt(Math.pow(this._v3_1.x, 2) + Math.pow(this._v3_1.y, 2));
      if (l2 == 0) {
        rayDir.set(this._v3_1.x, this._v3_1.y, tbRadius);
        return rayDir;
      }
      const m = h / l2;
      const q2 = cameraGizmoDistance;
      let a2 = Math.pow(m, 2) + 1;
      let b3 = 2 * m * q2;
      let c2 = Math.pow(q2, 2) - radius2;
      let delta = Math.pow(b3, 2) - 4 * a2 * c2;
      if (delta >= 0) {
        this._v2_1.setX((-b3 - Math.sqrt(delta)) / (2 * a2));
        this._v2_1.setY(m * this._v2_1.x + q2);
        const angle = MathUtils.RAD2DEG * this._v2_1.angle();
        if (angle >= 45) {
          const rayLength2 = Math.sqrt(Math.pow(this._v2_1.x, 2) + Math.pow(cameraGizmoDistance - this._v2_1.y, 2));
          rayDir.multiplyScalar(rayLength2);
          rayDir.z += cameraGizmoDistance;
          return rayDir;
        }
      }
      a2 = m;
      b3 = q2;
      c2 = -radius2 * 0.5;
      delta = Math.pow(b3, 2) - 4 * a2 * c2;
      this._v2_1.setX((-b3 - Math.sqrt(delta)) / (2 * a2));
      this._v2_1.setY(m * this._v2_1.x + q2);
      const rayLength = Math.sqrt(Math.pow(this._v2_1.x, 2) + Math.pow(cameraGizmoDistance - this._v2_1.y, 2));
      rayDir.multiplyScalar(rayLength);
      rayDir.z += cameraGizmoDistance;
      return rayDir;
    }
  }
  /**
   * Unprojects the cursor on the plane passing through the center of the trackball orthogonal to the camera.
   *
   * @private
   * @param {Camera} camera - The virtual camera.
   * @param {number} cursorX - Cursor horizontal coordinate on screen.
   * @param {number} cursorY - Cursor vertical coordinate on screen.
   * @param {HTMLElement} canvas - The canvas where the renderer draws its output.
   * @param {boolean} [initialDistance=false] - If initial distance between camera and gizmos should be used for calculations instead of current (Perspective only).
   * @returns {Vector3} The unprojected point on the trackball plane.
   */
  unprojectOnTbPlane(camera, cursorX, cursorY, canvas, initialDistance = false) {
    if (camera.type == "OrthographicCamera") {
      this._v2_1.copy(this.getCursorPosition(cursorX, cursorY, canvas));
      this._v3_1.set(this._v2_1.x, this._v2_1.y, 0);
      return this._v3_1.clone();
    } else if (camera.type == "PerspectiveCamera") {
      this._v2_1.copy(this.getCursorNDC(cursorX, cursorY, canvas));
      this._v3_1.set(this._v2_1.x, this._v2_1.y, -1);
      this._v3_1.applyMatrix4(camera.projectionMatrixInverse);
      const rayDir = this._v3_1.clone().normalize();
      const h = this._v3_1.z;
      const l2 = Math.sqrt(Math.pow(this._v3_1.x, 2) + Math.pow(this._v3_1.y, 2));
      let cameraGizmoDistance;
      if (initialDistance) {
        cameraGizmoDistance = this._v3_1.setFromMatrixPosition(this._cameraMatrixState0).distanceTo(this._v3_2.setFromMatrixPosition(this._gizmoMatrixState0));
      } else {
        cameraGizmoDistance = camera.position.distanceTo(this._gizmos.position);
      }
      if (l2 == 0) {
        rayDir.set(0, 0, 0);
        return rayDir;
      }
      const m = h / l2;
      const q2 = cameraGizmoDistance;
      const x2 = -q2 / m;
      const rayLength = Math.sqrt(Math.pow(q2, 2) + Math.pow(x2, 2));
      rayDir.multiplyScalar(rayLength);
      rayDir.z = 0;
      return rayDir;
    }
  }
  /**
   * Updates camera and gizmos state.
   *
   * @private
   */
  updateMatrixState() {
    this._cameraMatrixState.copy(this.object.matrix);
    this._gizmoMatrixState.copy(this._gizmos.matrix);
    if (this.object.isOrthographicCamera) {
      this._cameraProjectionState.copy(this.object.projectionMatrix);
      this.object.updateProjectionMatrix();
      this._zoomState = this.object.zoom;
    } else if (this.object.isPerspectiveCamera) {
      this._fovState = this.object.fov;
    }
  }
  /**
   * Updates the trackball FSA.
   *
   * @private
   * @param {STATE} newState - New state of the FSA.
   * @param {boolean} updateMatrices - If matrices state should be updated.
   */
  updateTbState(newState, updateMatrices) {
    this._state = newState;
    if (updateMatrices) {
      this.updateMatrixState();
    }
  }
  update() {
    if (this.target.equals(this._currentTarget) === false) {
      this._gizmos.position.copy(this.target);
      this._tbRadius = this.calculateTbRadius(this.object);
      this.makeGizmos(this.target, this._tbRadius);
      this._currentTarget.copy(this.target);
    }
    if (this.object.isOrthographicCamera) {
      if (this.object.zoom > this.maxZoom || this.object.zoom < this.minZoom) {
        const newZoom = MathUtils.clamp(this.object.zoom, this.minZoom, this.maxZoom);
        this.applyTransformMatrix(this.scale(newZoom / this.object.zoom, this._gizmos.position, true));
      }
    } else if (this.object.isPerspectiveCamera) {
      const distance = this.object.position.distanceTo(this._gizmos.position);
      if (distance > this.maxDistance + _EPS || distance < this.minDistance - _EPS) {
        const newDistance = MathUtils.clamp(distance, this.minDistance, this.maxDistance);
        this.applyTransformMatrix(this.scale(newDistance / distance, this._gizmos.position));
        this.updateMatrixState();
      }
      if (this.object.fov < this.minFov || this.object.fov > this.maxFov) {
        this.object.fov = MathUtils.clamp(this.object.fov, this.minFov, this.maxFov);
        this.object.updateProjectionMatrix();
      }
      const oldRadius = this._tbRadius;
      this._tbRadius = this.calculateTbRadius(this.object);
      if (oldRadius < this._tbRadius - _EPS || oldRadius > this._tbRadius + _EPS) {
        const scale2 = (this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z) / 3;
        const newRadius = this._tbRadius / scale2;
        const curve = new EllipseCurve(0, 0, newRadius, newRadius);
        const points = curve.getPoints(this._curvePts);
        const curveGeometry = new BufferGeometry().setFromPoints(points);
        for (const gizmo in this._gizmos.children) {
          this._gizmos.children[gizmo].geometry = curveGeometry;
        }
      }
    }
    this.object.lookAt(this._gizmos.position);
  }
  setStateFromJSON(json) {
    const state = JSON.parse(json);
    if (state.arcballState != void 0) {
      this.target.fromArray(state.arcballState.target);
      this._cameraMatrixState.fromArray(state.arcballState.cameraMatrix.elements);
      this._cameraMatrixState.decompose(this.object.position, this.object.quaternion, this.object.scale);
      this.object.up.copy(state.arcballState.cameraUp);
      this.object.near = state.arcballState.cameraNear;
      this.object.far = state.arcballState.cameraFar;
      this.object.zoom = state.arcballState.cameraZoom;
      if (this.object.isPerspectiveCamera) {
        this.object.fov = state.arcballState.cameraFov;
      }
      this._gizmoMatrixState.fromArray(state.arcballState.gizmoMatrix.elements);
      this._gizmoMatrixState.decompose(this._gizmos.position, this._gizmos.quaternion, this._gizmos.scale);
      this.object.updateMatrix();
      this.object.updateProjectionMatrix();
      this._gizmos.updateMatrix();
      this._tbRadius = this.calculateTbRadius(this.object);
      const gizmoTmp = new Matrix4().copy(this._gizmoMatrixState0);
      this.makeGizmos(this._gizmos.position, this._tbRadius);
      this._gizmoMatrixState0.copy(gizmoTmp);
      this.object.lookAt(this._gizmos.position);
      this.updateTbState(STATE.IDLE, false);
      this.dispatchEvent(_changeEvent);
    }
  }
};
function onWindowResize() {
  const scale2 = (this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z) / 3;
  this._tbRadius = this.calculateTbRadius(this.object);
  const newRadius = this._tbRadius / scale2;
  const curve = new EllipseCurve(0, 0, newRadius, newRadius);
  const points = curve.getPoints(this._curvePts);
  const curveGeometry = new BufferGeometry().setFromPoints(points);
  for (const gizmo in this._gizmos.children) {
    this._gizmos.children[gizmo].geometry = curveGeometry;
  }
  this.dispatchEvent(_changeEvent);
}
function onContextMenu(event) {
  if (!this.enabled) {
    return;
  }
  for (let i = 0; i < this.mouseActions.length; i++) {
    if (this.mouseActions[i].mouse == 2) {
      event.preventDefault();
      break;
    }
  }
}
function onPointerCancel() {
  this._touchStart.splice(0, this._touchStart.length);
  this._touchCurrent.splice(0, this._touchCurrent.length);
  this._input = INPUT.NONE;
}
function onPointerDown(event) {
  if (event.button == 0 && event.isPrimary) {
    this._downValid = true;
    this._downEvents.push(event);
    this._downStart = performance.now();
  } else {
    this._downValid = false;
  }
  if (event.pointerType == "touch" && this._input != INPUT.CURSOR) {
    this._touchStart.push(event);
    this._touchCurrent.push(event);
    switch (this._input) {
      case INPUT.NONE:
        this._input = INPUT.ONE_FINGER;
        this.onSinglePanStart(event, "ROTATE");
        window.addEventListener("pointermove", this._onPointerMove);
        window.addEventListener("pointerup", this._onPointerUp);
        break;
      case INPUT.ONE_FINGER:
      case INPUT.ONE_FINGER_SWITCHED:
        this._input = INPUT.TWO_FINGER;
        this.onRotateStart();
        this.onPinchStart();
        this.onDoublePanStart();
        break;
      case INPUT.TWO_FINGER:
        this._input = INPUT.MULT_FINGER;
        this.onTriplePanStart(event);
        break;
    }
  } else if (event.pointerType != "touch" && this._input == INPUT.NONE) {
    let modifier = null;
    if (event.ctrlKey || event.metaKey) {
      modifier = "CTRL";
    } else if (event.shiftKey) {
      modifier = "SHIFT";
    }
    this._mouseOp = this.getOpFromAction(event.button, modifier);
    if (this._mouseOp != null) {
      window.addEventListener("pointermove", this._onPointerMove);
      window.addEventListener("pointerup", this._onPointerUp);
      this._input = INPUT.CURSOR;
      this._button = event.button;
      this.onSinglePanStart(event, this._mouseOp);
    }
  }
}
function onPointerMove(event) {
  if (event.pointerType == "touch" && this._input != INPUT.CURSOR) {
    switch (this._input) {
      case INPUT.ONE_FINGER:
        this.updateTouchEvent(event);
        this.onSinglePanMove(event, STATE.ROTATE);
        break;
      case INPUT.ONE_FINGER_SWITCHED:
        const movement = this.calculatePointersDistance(this._touchCurrent[0], event) * this._devPxRatio;
        if (movement >= this._switchSensibility) {
          this._input = INPUT.ONE_FINGER;
          this.updateTouchEvent(event);
          this.onSinglePanStart(event, "ROTATE");
          break;
        }
        break;
      case INPUT.TWO_FINGER:
        this.updateTouchEvent(event);
        this.onRotateMove();
        this.onPinchMove();
        this.onDoublePanMove();
        break;
      case INPUT.MULT_FINGER:
        this.updateTouchEvent(event);
        this.onTriplePanMove(event);
        break;
    }
  } else if (event.pointerType != "touch" && this._input == INPUT.CURSOR) {
    let modifier = null;
    if (event.ctrlKey || event.metaKey) {
      modifier = "CTRL";
    } else if (event.shiftKey) {
      modifier = "SHIFT";
    }
    const mouseOpState = this.getOpStateFromAction(this._button, modifier);
    if (mouseOpState != null) {
      this.onSinglePanMove(event, mouseOpState);
    }
  }
  if (this._downValid) {
    const movement = this.calculatePointersDistance(this._downEvents[this._downEvents.length - 1], event) * this._devPxRatio;
    if (movement > this._movementThreshold) {
      this._downValid = false;
    }
  }
}
function onPointerUp(event) {
  if (event.pointerType == "touch" && this._input != INPUT.CURSOR) {
    const nTouch = this._touchCurrent.length;
    for (let i = 0; i < nTouch; i++) {
      if (this._touchCurrent[i].pointerId == event.pointerId) {
        this._touchCurrent.splice(i, 1);
        this._touchStart.splice(i, 1);
        break;
      }
    }
    switch (this._input) {
      case INPUT.ONE_FINGER:
      case INPUT.ONE_FINGER_SWITCHED:
        window.removeEventListener("pointermove", this._onPointerMove);
        window.removeEventListener("pointerup", this._onPointerUp);
        this._input = INPUT.NONE;
        this.onSinglePanEnd();
        break;
      case INPUT.TWO_FINGER:
        this.onDoublePanEnd(event);
        this.onPinchEnd(event);
        this.onRotateEnd(event);
        this._input = INPUT.ONE_FINGER_SWITCHED;
        break;
      case INPUT.MULT_FINGER:
        if (this._touchCurrent.length == 0) {
          window.removeEventListener("pointermove", this._onPointerMove);
          window.removeEventListener("pointerup", this._onPointerUp);
          this._input = INPUT.NONE;
          this.onTriplePanEnd();
        }
        break;
    }
  } else if (event.pointerType != "touch" && this._input == INPUT.CURSOR) {
    window.removeEventListener("pointermove", this._onPointerMove);
    window.removeEventListener("pointerup", this._onPointerUp);
    this._input = INPUT.NONE;
    this.onSinglePanEnd();
    this._button = -1;
  }
  if (event.isPrimary) {
    if (this._downValid) {
      const downTime = event.timeStamp - this._downEvents[this._downEvents.length - 1].timeStamp;
      if (downTime <= this._maxDownTime) {
        if (this._nclicks == 0) {
          this._nclicks = 1;
          this._clickStart = performance.now();
        } else {
          const clickInterval = event.timeStamp - this._clickStart;
          const movement = this.calculatePointersDistance(this._downEvents[1], this._downEvents[0]) * this._devPxRatio;
          if (clickInterval <= this._maxInterval && movement <= this._posThreshold) {
            this._nclicks = 0;
            this._downEvents.splice(0, this._downEvents.length);
            this.onDoubleTap(event);
          } else {
            this._nclicks = 1;
            this._downEvents.shift();
            this._clickStart = performance.now();
          }
        }
      } else {
        this._downValid = false;
        this._nclicks = 0;
        this._downEvents.splice(0, this._downEvents.length);
      }
    } else {
      this._nclicks = 0;
      this._downEvents.splice(0, this._downEvents.length);
    }
  }
}
function onWheel(event) {
  if (this.enabled && this.enableZoom) {
    let modifier = null;
    if (event.ctrlKey || event.metaKey) {
      modifier = "CTRL";
    } else if (event.shiftKey) {
      modifier = "SHIFT";
    }
    const mouseOp = this.getOpFromAction("WHEEL", modifier);
    if (mouseOp != null) {
      event.preventDefault();
      this.dispatchEvent(_startEvent);
      const notchDeltaY = 125;
      let sgn = event.deltaY / notchDeltaY;
      let size2 = 1;
      if (sgn > 0) {
        size2 = 1 / this.scaleFactor;
      } else if (sgn < 0) {
        size2 = this.scaleFactor;
      }
      switch (mouseOp) {
        case "ZOOM":
          this.updateTbState(STATE.SCALE, true);
          if (sgn > 0) {
            size2 = 1 / Math.pow(this.scaleFactor, sgn);
          } else if (sgn < 0) {
            size2 = Math.pow(this.scaleFactor, -sgn);
          }
          if (this.cursorZoom && this.enablePan) {
            let scalePoint;
            if (this.object.isOrthographicCamera) {
              scalePoint = this.unprojectOnTbPlane(this.object, event.clientX, event.clientY, this.domElement).applyQuaternion(this.object.quaternion).multiplyScalar(1 / this.object.zoom).add(this._gizmos.position);
            } else if (this.object.isPerspectiveCamera) {
              scalePoint = this.unprojectOnTbPlane(this.object, event.clientX, event.clientY, this.domElement).applyQuaternion(this.object.quaternion).add(this._gizmos.position);
            }
            this.applyTransformMatrix(this.scale(size2, scalePoint));
          } else {
            this.applyTransformMatrix(this.scale(size2, this._gizmos.position));
          }
          if (this._grid != null) {
            this.disposeGrid();
            this.drawGrid();
          }
          this.updateTbState(STATE.IDLE, false);
          this.dispatchEvent(_changeEvent);
          this.dispatchEvent(_endEvent);
          break;
        case "FOV":
          if (this.object.isPerspectiveCamera) {
            this.updateTbState(STATE.FOV, true);
            if (event.deltaX != 0) {
              sgn = event.deltaX / notchDeltaY;
              size2 = 1;
              if (sgn > 0) {
                size2 = 1 / Math.pow(this.scaleFactor, sgn);
              } else if (sgn < 0) {
                size2 = Math.pow(this.scaleFactor, -sgn);
              }
            }
            this._v3_1.setFromMatrixPosition(this._cameraMatrixState);
            const x2 = this._v3_1.distanceTo(this._gizmos.position);
            let xNew = x2 / size2;
            xNew = MathUtils.clamp(xNew, this.minDistance, this.maxDistance);
            const y = x2 * Math.tan(MathUtils.DEG2RAD * this.object.fov * 0.5);
            let newFov = MathUtils.RAD2DEG * (Math.atan(y / xNew) * 2);
            if (newFov > this.maxFov) {
              newFov = this.maxFov;
            } else if (newFov < this.minFov) {
              newFov = this.minFov;
            }
            const newDistance = y / Math.tan(MathUtils.DEG2RAD * (newFov / 2));
            size2 = x2 / newDistance;
            this.setFov(newFov);
            this.applyTransformMatrix(this.scale(size2, this._gizmos.position, false));
          }
          if (this._grid != null) {
            this.disposeGrid();
            this.drawGrid();
          }
          this.updateTbState(STATE.IDLE, false);
          this.dispatchEvent(_changeEvent);
          this.dispatchEvent(_endEvent);
          break;
      }
    }
  }
}

// node_modules/three/examples/jsm/controls/DragControls.js
var _plane = new Plane();
var _pointer = new Vector2();
var _offset2 = new Vector3();
var _diff = new Vector2();
var _previousPointer = new Vector2();
var _intersection = new Vector3();
var _worldPosition = new Vector3();
var _inverseMatrix = new Matrix4();
var _up = new Vector3();
var _right = new Vector3();
var _selected = null;
var _hovered = null;
var _intersections = [];
var STATE2 = {
  NONE: -1,
  PAN: 0,
  ROTATE: 1
};
var DragControls = class extends Controls {
  /**
   * Constructs a new controls instance.
   *
   * @param {Array<Object3D>} objects - An array of draggable 3D objects.
   * @param {Camera} camera - The camera of the rendered scene.
   * @param {?HTMLDOMElement} [domElement=null] - The HTML DOM element used for event listeners.
   */
  constructor(objects, camera, domElement = null) {
    super(camera, domElement);
    this.objects = objects;
    this.recursive = true;
    this.transformGroup = false;
    this.rotateSpeed = 1;
    this.raycaster = new Raycaster();
    this.mouseButtons = { LEFT: MOUSE.PAN, MIDDLE: MOUSE.PAN, RIGHT: MOUSE.ROTATE };
    this.touches = { ONE: TOUCH.PAN };
    this._onPointerMove = onPointerMove2.bind(this);
    this._onPointerDown = onPointerDown2.bind(this);
    this._onPointerCancel = onPointerCancel2.bind(this);
    this._onContextMenu = onContextMenu2.bind(this);
    if (domElement !== null) {
      this.connect(domElement);
    }
  }
  connect(element) {
    super.connect(element);
    this.domElement.addEventListener("pointermove", this._onPointerMove);
    this.domElement.addEventListener("pointerdown", this._onPointerDown);
    this.domElement.addEventListener("pointerup", this._onPointerCancel);
    this.domElement.addEventListener("pointerleave", this._onPointerCancel);
    this.domElement.addEventListener("contextmenu", this._onContextMenu);
    this.domElement.style.touchAction = "none";
  }
  disconnect() {
    this.domElement.removeEventListener("pointermove", this._onPointerMove);
    this.domElement.removeEventListener("pointerdown", this._onPointerDown);
    this.domElement.removeEventListener("pointerup", this._onPointerCancel);
    this.domElement.removeEventListener("pointerleave", this._onPointerCancel);
    this.domElement.removeEventListener("contextmenu", this._onContextMenu);
    this.domElement.style.touchAction = "auto";
    this.domElement.style.cursor = "";
  }
  dispose() {
    this.disconnect();
  }
  _updatePointer(event) {
    const rect = this.domElement.getBoundingClientRect();
    _pointer.x = (event.clientX - rect.left) / rect.width * 2 - 1;
    _pointer.y = -(event.clientY - rect.top) / rect.height * 2 + 1;
  }
  _updateState(event) {
    let action;
    if (event.pointerType === "touch") {
      action = this.touches.ONE;
    } else {
      switch (event.button) {
        case 0:
          action = this.mouseButtons.LEFT;
          break;
        case 1:
          action = this.mouseButtons.MIDDLE;
          break;
        case 2:
          action = this.mouseButtons.RIGHT;
          break;
        default:
          action = null;
      }
    }
    switch (action) {
      case MOUSE.PAN:
      case TOUCH.PAN:
        this.state = STATE2.PAN;
        break;
      case MOUSE.ROTATE:
      case TOUCH.ROTATE:
        this.state = STATE2.ROTATE;
        break;
      default:
        this.state = STATE2.NONE;
    }
  }
  getRaycaster() {
    console.warn("THREE.DragControls: getRaycaster() has been deprecated. Use controls.raycaster instead.");
    return this.raycaster;
  }
  setObjects(objects) {
    console.warn("THREE.DragControls: setObjects() has been deprecated. Use controls.objects instead.");
    this.objects = objects;
  }
  getObjects() {
    console.warn("THREE.DragControls: getObjects() has been deprecated. Use controls.objects instead.");
    return this.objects;
  }
  activate() {
    console.warn("THREE.DragControls: activate() has been renamed to connect().");
    this.connect();
  }
  deactivate() {
    console.warn("THREE.DragControls: deactivate() has been renamed to disconnect().");
    this.disconnect();
  }
  set mode(value2) {
    console.warn("THREE.DragControls: The .mode property has been removed. Define the type of transformation via the .mouseButtons or .touches properties.");
  }
  get mode() {
    console.warn("THREE.DragControls: The .mode property has been removed. Define the type of transformation via the .mouseButtons or .touches properties.");
  }
};
function onPointerMove2(event) {
  const camera = this.object;
  const domElement = this.domElement;
  const raycaster = this.raycaster;
  if (this.enabled === false) return;
  this._updatePointer(event);
  raycaster.setFromCamera(_pointer, camera);
  if (_selected) {
    if (this.state === STATE2.PAN) {
      if (raycaster.ray.intersectPlane(_plane, _intersection)) {
        _selected.position.copy(_intersection.sub(_offset2).applyMatrix4(_inverseMatrix));
      }
    } else if (this.state === STATE2.ROTATE) {
      _diff.subVectors(_pointer, _previousPointer).multiplyScalar(this.rotateSpeed);
      _selected.rotateOnWorldAxis(_up, _diff.x);
      _selected.rotateOnWorldAxis(_right.normalize(), -_diff.y);
    }
    this.dispatchEvent({ type: "drag", object: _selected });
    _previousPointer.copy(_pointer);
  } else {
    if (event.pointerType === "mouse" || event.pointerType === "pen") {
      _intersections.length = 0;
      raycaster.setFromCamera(_pointer, camera);
      raycaster.intersectObjects(this.objects, this.recursive, _intersections);
      if (_intersections.length > 0) {
        const object = _intersections[0].object;
        _plane.setFromNormalAndCoplanarPoint(camera.getWorldDirection(_plane.normal), _worldPosition.setFromMatrixPosition(object.matrixWorld));
        if (_hovered !== object && _hovered !== null) {
          this.dispatchEvent({ type: "hoveroff", object: _hovered });
          domElement.style.cursor = "auto";
          _hovered = null;
        }
        if (_hovered !== object) {
          this.dispatchEvent({ type: "hoveron", object });
          domElement.style.cursor = "pointer";
          _hovered = object;
        }
      } else {
        if (_hovered !== null) {
          this.dispatchEvent({ type: "hoveroff", object: _hovered });
          domElement.style.cursor = "auto";
          _hovered = null;
        }
      }
    }
  }
  _previousPointer.copy(_pointer);
}
function onPointerDown2(event) {
  const camera = this.object;
  const domElement = this.domElement;
  const raycaster = this.raycaster;
  if (this.enabled === false) return;
  this._updatePointer(event);
  this._updateState(event);
  _intersections.length = 0;
  raycaster.setFromCamera(_pointer, camera);
  raycaster.intersectObjects(this.objects, this.recursive, _intersections);
  if (_intersections.length > 0) {
    if (this.transformGroup === true) {
      _selected = findGroup(_intersections[0].object);
    } else {
      _selected = _intersections[0].object;
    }
    _plane.setFromNormalAndCoplanarPoint(camera.getWorldDirection(_plane.normal), _worldPosition.setFromMatrixPosition(_selected.matrixWorld));
    if (raycaster.ray.intersectPlane(_plane, _intersection)) {
      if (this.state === STATE2.PAN) {
        _inverseMatrix.copy(_selected.parent.matrixWorld).invert();
        _offset2.copy(_intersection).sub(_worldPosition.setFromMatrixPosition(_selected.matrixWorld));
      } else if (this.state === STATE2.ROTATE) {
        _up.set(0, 1, 0).applyQuaternion(camera.quaternion).normalize();
        _right.set(1, 0, 0).applyQuaternion(camera.quaternion).normalize();
      }
    }
    domElement.style.cursor = "move";
    this.dispatchEvent({ type: "dragstart", object: _selected });
  }
  _previousPointer.copy(_pointer);
}
function onPointerCancel2() {
  if (this.enabled === false) return;
  if (_selected) {
    this.dispatchEvent({ type: "dragend", object: _selected });
    _selected = null;
  }
  this.domElement.style.cursor = _hovered ? "pointer" : "auto";
  this.state = STATE2.NONE;
}
function onContextMenu2(event) {
  if (this.enabled === false) return;
  event.preventDefault();
}
function findGroup(obj, group = null) {
  if (obj.isGroup) group = obj;
  if (obj.parent === null) return group;
  return findGroup(obj.parent, group);
}

// node_modules/three/examples/jsm/controls/FirstPersonControls.js
var _lookDirection = new Vector3();
var _spherical = new Spherical();
var _target = new Vector3();
var _targetPosition = new Vector3();
var FirstPersonControls = class extends Controls {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(object, domElement = null) {
    super(object, domElement);
    this.movementSpeed = 1;
    this.lookSpeed = 5e-3;
    this.lookVertical = true;
    this.autoForward = false;
    this.activeLook = true;
    this.heightSpeed = false;
    this.heightCoef = 1;
    this.heightMin = 0;
    this.heightMax = 1;
    this.constrainVertical = false;
    this.verticalMin = 0;
    this.verticalMax = Math.PI;
    this.mouseDragOn = false;
    this._autoSpeedFactor = 0;
    this._pointerX = 0;
    this._pointerY = 0;
    this._moveForward = false;
    this._moveBackward = false;
    this._moveLeft = false;
    this._moveRight = false;
    this._viewHalfX = 0;
    this._viewHalfY = 0;
    this._lat = 0;
    this._lon = 0;
    this._onPointerMove = onPointerMove3.bind(this);
    this._onPointerDown = onPointerDown3.bind(this);
    this._onPointerUp = onPointerUp2.bind(this);
    this._onContextMenu = onContextMenu3.bind(this);
    this._onKeyDown = onKeyDown.bind(this);
    this._onKeyUp = onKeyUp.bind(this);
    if (domElement !== null) {
      this.connect(domElement);
      this.handleResize();
    }
    this._setOrientation();
  }
  connect(element) {
    super.connect(element);
    window.addEventListener("keydown", this._onKeyDown);
    window.addEventListener("keyup", this._onKeyUp);
    this.domElement.addEventListener("pointermove", this._onPointerMove);
    this.domElement.addEventListener("pointerdown", this._onPointerDown);
    this.domElement.addEventListener("pointerup", this._onPointerUp);
    this.domElement.addEventListener("contextmenu", this._onContextMenu);
  }
  disconnect() {
    window.removeEventListener("keydown", this._onKeyDown);
    window.removeEventListener("keyup", this._onKeyUp);
    this.domElement.removeEventListener("pointerdown", this._onPointerMove);
    this.domElement.removeEventListener("pointermove", this._onPointerDown);
    this.domElement.removeEventListener("pointerup", this._onPointerUp);
    this.domElement.removeEventListener("contextmenu", this._onContextMenu);
  }
  dispose() {
    this.disconnect();
  }
  /**
   * Must be called if the application window is resized.
   */
  handleResize() {
    if (this.domElement === document) {
      this._viewHalfX = window.innerWidth / 2;
      this._viewHalfY = window.innerHeight / 2;
    } else {
      this._viewHalfX = this.domElement.offsetWidth / 2;
      this._viewHalfY = this.domElement.offsetHeight / 2;
    }
  }
  /**
   * Rotates the camera towards the defined target position.
   *
   * @param {number|Vector3} x - The x coordinate of the target position or alternatively a vector representing the target position.
   * @param {number} y - The y coordinate of the target position.
   * @param {number} z - The z coordinate of the target position.
   * @return {FirstPersonControls} A reference to this controls.
   */
  lookAt(x2, y, z) {
    if (x2.isVector3) {
      _target.copy(x2);
    } else {
      _target.set(x2, y, z);
    }
    this.object.lookAt(_target);
    this._setOrientation();
    return this;
  }
  update(delta) {
    if (this.enabled === false) return;
    if (this.heightSpeed) {
      const y = MathUtils.clamp(this.object.position.y, this.heightMin, this.heightMax);
      const heightDelta = y - this.heightMin;
      this._autoSpeedFactor = delta * (heightDelta * this.heightCoef);
    } else {
      this._autoSpeedFactor = 0;
    }
    const actualMoveSpeed = delta * this.movementSpeed;
    if (this._moveForward || this.autoForward && !this._moveBackward) this.object.translateZ(-(actualMoveSpeed + this._autoSpeedFactor));
    if (this._moveBackward) this.object.translateZ(actualMoveSpeed);
    if (this._moveLeft) this.object.translateX(-actualMoveSpeed);
    if (this._moveRight) this.object.translateX(actualMoveSpeed);
    if (this._moveUp) this.object.translateY(actualMoveSpeed);
    if (this._moveDown) this.object.translateY(-actualMoveSpeed);
    let actualLookSpeed = delta * this.lookSpeed;
    if (!this.activeLook) {
      actualLookSpeed = 0;
    }
    let verticalLookRatio = 1;
    if (this.constrainVertical) {
      verticalLookRatio = Math.PI / (this.verticalMax - this.verticalMin);
    }
    this._lon -= this._pointerX * actualLookSpeed;
    if (this.lookVertical) this._lat -= this._pointerY * actualLookSpeed * verticalLookRatio;
    this._lat = Math.max(-85, Math.min(85, this._lat));
    let phi = MathUtils.degToRad(90 - this._lat);
    const theta = MathUtils.degToRad(this._lon);
    if (this.constrainVertical) {
      phi = MathUtils.mapLinear(phi, 0, Math.PI, this.verticalMin, this.verticalMax);
    }
    const position2 = this.object.position;
    _targetPosition.setFromSphericalCoords(1, phi, theta).add(position2);
    this.object.lookAt(_targetPosition);
  }
  _setOrientation() {
    const quaternion = this.object.quaternion;
    _lookDirection.set(0, 0, -1).applyQuaternion(quaternion);
    _spherical.setFromVector3(_lookDirection);
    this._lat = 90 - MathUtils.radToDeg(_spherical.phi);
    this._lon = MathUtils.radToDeg(_spherical.theta);
  }
};
function onPointerDown3(event) {
  if (this.domElement !== document) {
    this.domElement.focus();
  }
  if (this.activeLook) {
    switch (event.button) {
      case 0:
        this._moveForward = true;
        break;
      case 2:
        this._moveBackward = true;
        break;
    }
  }
  this.mouseDragOn = true;
}
function onPointerUp2(event) {
  if (this.activeLook) {
    switch (event.button) {
      case 0:
        this._moveForward = false;
        break;
      case 2:
        this._moveBackward = false;
        break;
    }
  }
  this.mouseDragOn = false;
}
function onPointerMove3(event) {
  if (this.domElement === document) {
    this._pointerX = event.pageX - this._viewHalfX;
    this._pointerY = event.pageY - this._viewHalfY;
  } else {
    this._pointerX = event.pageX - this.domElement.offsetLeft - this._viewHalfX;
    this._pointerY = event.pageY - this.domElement.offsetTop - this._viewHalfY;
  }
}
function onKeyDown(event) {
  switch (event.code) {
    case "ArrowUp":
    case "KeyW":
      this._moveForward = true;
      break;
    case "ArrowLeft":
    case "KeyA":
      this._moveLeft = true;
      break;
    case "ArrowDown":
    case "KeyS":
      this._moveBackward = true;
      break;
    case "ArrowRight":
    case "KeyD":
      this._moveRight = true;
      break;
    case "KeyR":
      this._moveUp = true;
      break;
    case "KeyF":
      this._moveDown = true;
      break;
  }
}
function onKeyUp(event) {
  switch (event.code) {
    case "ArrowUp":
    case "KeyW":
      this._moveForward = false;
      break;
    case "ArrowLeft":
    case "KeyA":
      this._moveLeft = false;
      break;
    case "ArrowDown":
    case "KeyS":
      this._moveBackward = false;
      break;
    case "ArrowRight":
    case "KeyD":
      this._moveRight = false;
      break;
    case "KeyR":
      this._moveUp = false;
      break;
    case "KeyF":
      this._moveDown = false;
      break;
  }
}
function onContextMenu3(event) {
  if (this.enabled === false) return;
  event.preventDefault();
}

// node_modules/three/examples/jsm/controls/FlyControls.js
var _changeEvent2 = { type: "change" };
var _EPS2 = 1e-6;
var _tmpQuaternion = new Quaternion();
var FlyControls = class extends Controls {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(object, domElement = null) {
    super(object, domElement);
    this.movementSpeed = 1;
    this.rollSpeed = 5e-3;
    this.dragToLook = false;
    this.autoForward = false;
    this._moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
    this._moveVector = new Vector3(0, 0, 0);
    this._rotationVector = new Vector3(0, 0, 0);
    this._lastQuaternion = new Quaternion();
    this._lastPosition = new Vector3();
    this._status = 0;
    this._onKeyDown = onKeyDown2.bind(this);
    this._onKeyUp = onKeyUp2.bind(this);
    this._onPointerMove = onPointerMove4.bind(this);
    this._onPointerDown = onPointerDown4.bind(this);
    this._onPointerUp = onPointerUp3.bind(this);
    this._onPointerCancel = onPointerCancel3.bind(this);
    this._onContextMenu = onContextMenu4.bind(this);
    if (domElement !== null) {
      this.connect(domElement);
    }
  }
  connect(element) {
    super.connect(element);
    window.addEventListener("keydown", this._onKeyDown);
    window.addEventListener("keyup", this._onKeyUp);
    this.domElement.addEventListener("pointermove", this._onPointerMove);
    this.domElement.addEventListener("pointerdown", this._onPointerDown);
    this.domElement.addEventListener("pointerup", this._onPointerUp);
    this.domElement.addEventListener("pointercancel", this._onPointerCancel);
    this.domElement.addEventListener("contextmenu", this._onContextMenu);
  }
  disconnect() {
    window.removeEventListener("keydown", this._onKeyDown);
    window.removeEventListener("keyup", this._onKeyUp);
    this.domElement.removeEventListener("pointermove", this._onPointerMove);
    this.domElement.removeEventListener("pointerdown", this._onPointerDown);
    this.domElement.removeEventListener("pointerup", this._onPointerUp);
    this.domElement.removeEventListener("pointercancel", this._onPointerCancel);
    this.domElement.removeEventListener("contextmenu", this._onContextMenu);
  }
  dispose() {
    this.disconnect();
  }
  update(delta) {
    if (this.enabled === false) return;
    const object = this.object;
    const moveMult = delta * this.movementSpeed;
    const rotMult = delta * this.rollSpeed;
    object.translateX(this._moveVector.x * moveMult);
    object.translateY(this._moveVector.y * moveMult);
    object.translateZ(this._moveVector.z * moveMult);
    _tmpQuaternion.set(this._rotationVector.x * rotMult, this._rotationVector.y * rotMult, this._rotationVector.z * rotMult, 1).normalize();
    object.quaternion.multiply(_tmpQuaternion);
    if (this._lastPosition.distanceToSquared(object.position) > _EPS2 || 8 * (1 - this._lastQuaternion.dot(object.quaternion)) > _EPS2) {
      this.dispatchEvent(_changeEvent2);
      this._lastQuaternion.copy(object.quaternion);
      this._lastPosition.copy(object.position);
    }
  }
  // private
  _updateMovementVector() {
    const forward = this._moveState.forward || this.autoForward && !this._moveState.back ? 1 : 0;
    this._moveVector.x = -this._moveState.left + this._moveState.right;
    this._moveVector.y = -this._moveState.down + this._moveState.up;
    this._moveVector.z = -forward + this._moveState.back;
  }
  _updateRotationVector() {
    this._rotationVector.x = -this._moveState.pitchDown + this._moveState.pitchUp;
    this._rotationVector.y = -this._moveState.yawRight + this._moveState.yawLeft;
    this._rotationVector.z = -this._moveState.rollRight + this._moveState.rollLeft;
  }
  _getContainerDimensions() {
    if (this.domElement != document) {
      return {
        size: [this.domElement.offsetWidth, this.domElement.offsetHeight],
        offset: [this.domElement.offsetLeft, this.domElement.offsetTop]
      };
    } else {
      return {
        size: [window.innerWidth, window.innerHeight],
        offset: [0, 0]
      };
    }
  }
};
function onKeyDown2(event) {
  if (event.altKey || this.enabled === false) {
    return;
  }
  switch (event.code) {
    case "ShiftLeft":
    case "ShiftRight":
      this.movementSpeedMultiplier = 0.1;
      break;
    case "KeyW":
      this._moveState.forward = 1;
      break;
    case "KeyS":
      this._moveState.back = 1;
      break;
    case "KeyA":
      this._moveState.left = 1;
      break;
    case "KeyD":
      this._moveState.right = 1;
      break;
    case "KeyR":
      this._moveState.up = 1;
      break;
    case "KeyF":
      this._moveState.down = 1;
      break;
    case "ArrowUp":
      this._moveState.pitchUp = 1;
      break;
    case "ArrowDown":
      this._moveState.pitchDown = 1;
      break;
    case "ArrowLeft":
      this._moveState.yawLeft = 1;
      break;
    case "ArrowRight":
      this._moveState.yawRight = 1;
      break;
    case "KeyQ":
      this._moveState.rollLeft = 1;
      break;
    case "KeyE":
      this._moveState.rollRight = 1;
      break;
  }
  this._updateMovementVector();
  this._updateRotationVector();
}
function onKeyUp2(event) {
  if (this.enabled === false) return;
  switch (event.code) {
    case "ShiftLeft":
    case "ShiftRight":
      this.movementSpeedMultiplier = 1;
      break;
    case "KeyW":
      this._moveState.forward = 0;
      break;
    case "KeyS":
      this._moveState.back = 0;
      break;
    case "KeyA":
      this._moveState.left = 0;
      break;
    case "KeyD":
      this._moveState.right = 0;
      break;
    case "KeyR":
      this._moveState.up = 0;
      break;
    case "KeyF":
      this._moveState.down = 0;
      break;
    case "ArrowUp":
      this._moveState.pitchUp = 0;
      break;
    case "ArrowDown":
      this._moveState.pitchDown = 0;
      break;
    case "ArrowLeft":
      this._moveState.yawLeft = 0;
      break;
    case "ArrowRight":
      this._moveState.yawRight = 0;
      break;
    case "KeyQ":
      this._moveState.rollLeft = 0;
      break;
    case "KeyE":
      this._moveState.rollRight = 0;
      break;
  }
  this._updateMovementVector();
  this._updateRotationVector();
}
function onPointerDown4(event) {
  if (this.enabled === false) return;
  if (this.dragToLook) {
    this._status++;
  } else {
    switch (event.button) {
      case 0:
        this._moveState.forward = 1;
        break;
      case 2:
        this._moveState.back = 1;
        break;
    }
    this._updateMovementVector();
  }
}
function onPointerMove4(event) {
  if (this.enabled === false) return;
  if (!this.dragToLook || this._status > 0) {
    const container = this._getContainerDimensions();
    const halfWidth = container.size[0] / 2;
    const halfHeight = container.size[1] / 2;
    this._moveState.yawLeft = -(event.pageX - container.offset[0] - halfWidth) / halfWidth;
    this._moveState.pitchDown = (event.pageY - container.offset[1] - halfHeight) / halfHeight;
    this._updateRotationVector();
  }
}
function onPointerUp3(event) {
  if (this.enabled === false) return;
  if (this.dragToLook) {
    this._status--;
    this._moveState.yawLeft = this._moveState.pitchDown = 0;
  } else {
    switch (event.button) {
      case 0:
        this._moveState.forward = 0;
        break;
      case 2:
        this._moveState.back = 0;
        break;
    }
    this._updateMovementVector();
  }
  this._updateRotationVector();
}
function onPointerCancel3() {
  if (this.enabled === false) return;
  if (this.dragToLook) {
    this._status = 0;
    this._moveState.yawLeft = this._moveState.pitchDown = 0;
  } else {
    this._moveState.forward = 0;
    this._moveState.back = 0;
    this._updateMovementVector();
  }
  this._updateRotationVector();
}
function onContextMenu4(event) {
  if (this.enabled === false) return;
  event.preventDefault();
}

// node_modules/three/examples/jsm/controls/OrbitControls.js
var _changeEvent3 = { type: "change" };
var _startEvent2 = { type: "start" };
var _endEvent2 = { type: "end" };
var _ray = new Ray();
var _plane2 = new Plane();
var _TILT_LIMIT = Math.cos(70 * MathUtils.DEG2RAD);
var _v = new Vector3();
var _twoPI = 2 * Math.PI;
var _STATE = {
  NONE: -1,
  ROTATE: 0,
  DOLLY: 1,
  PAN: 2,
  TOUCH_ROTATE: 3,
  TOUCH_PAN: 4,
  TOUCH_DOLLY_PAN: 5,
  TOUCH_DOLLY_ROTATE: 6
};
var _EPS3 = 1e-6;
var OrbitControls = class extends Controls {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(object, domElement = null) {
    super(object, domElement);
    this.state = _STATE.NONE;
    this.target = new Vector3();
    this.cursor = new Vector3();
    this.minDistance = 0;
    this.maxDistance = Infinity;
    this.minZoom = 0;
    this.maxZoom = Infinity;
    this.minTargetRadius = 0;
    this.maxTargetRadius = Infinity;
    this.minPolarAngle = 0;
    this.maxPolarAngle = Math.PI;
    this.minAzimuthAngle = -Infinity;
    this.maxAzimuthAngle = Infinity;
    this.enableDamping = false;
    this.dampingFactor = 0.05;
    this.enableZoom = true;
    this.zoomSpeed = 1;
    this.enableRotate = true;
    this.rotateSpeed = 1;
    this.keyRotateSpeed = 1;
    this.enablePan = true;
    this.panSpeed = 1;
    this.screenSpacePanning = true;
    this.keyPanSpeed = 7;
    this.zoomToCursor = false;
    this.autoRotate = false;
    this.autoRotateSpeed = 2;
    this.keys = { LEFT: "ArrowLeft", UP: "ArrowUp", RIGHT: "ArrowRight", BOTTOM: "ArrowDown" };
    this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
    this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
    this.target0 = this.target.clone();
    this.position0 = this.object.position.clone();
    this.zoom0 = this.object.zoom;
    this._domElementKeyEvents = null;
    this._lastPosition = new Vector3();
    this._lastQuaternion = new Quaternion();
    this._lastTargetPosition = new Vector3();
    this._quat = new Quaternion().setFromUnitVectors(object.up, new Vector3(0, 1, 0));
    this._quatInverse = this._quat.clone().invert();
    this._spherical = new Spherical();
    this._sphericalDelta = new Spherical();
    this._scale = 1;
    this._panOffset = new Vector3();
    this._rotateStart = new Vector2();
    this._rotateEnd = new Vector2();
    this._rotateDelta = new Vector2();
    this._panStart = new Vector2();
    this._panEnd = new Vector2();
    this._panDelta = new Vector2();
    this._dollyStart = new Vector2();
    this._dollyEnd = new Vector2();
    this._dollyDelta = new Vector2();
    this._dollyDirection = new Vector3();
    this._mouse = new Vector2();
    this._performCursorZoom = false;
    this._pointers = [];
    this._pointerPositions = {};
    this._controlActive = false;
    this._onPointerMove = onPointerMove5.bind(this);
    this._onPointerDown = onPointerDown5.bind(this);
    this._onPointerUp = onPointerUp4.bind(this);
    this._onContextMenu = onContextMenu5.bind(this);
    this._onMouseWheel = onMouseWheel.bind(this);
    this._onKeyDown = onKeyDown3.bind(this);
    this._onTouchStart = onTouchStart.bind(this);
    this._onTouchMove = onTouchMove.bind(this);
    this._onMouseDown = onMouseDown.bind(this);
    this._onMouseMove = onMouseMove.bind(this);
    this._interceptControlDown = interceptControlDown.bind(this);
    this._interceptControlUp = interceptControlUp.bind(this);
    if (this.domElement !== null) {
      this.connect(this.domElement);
    }
    this.update();
  }
  connect(element) {
    super.connect(element);
    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: false });
    const document2 = this.domElement.getRootNode();
    document2.addEventListener("keydown", this._interceptControlDown, { passive: true, capture: true });
    this.domElement.style.touchAction = "none";
  }
  disconnect() {
    this.domElement.removeEventListener("pointerdown", this._onPointerDown);
    this.domElement.removeEventListener("pointermove", this._onPointerMove);
    this.domElement.removeEventListener("pointerup", this._onPointerUp);
    this.domElement.removeEventListener("pointercancel", this._onPointerUp);
    this.domElement.removeEventListener("wheel", this._onMouseWheel);
    this.domElement.removeEventListener("contextmenu", this._onContextMenu);
    this.stopListenToKeyEvents();
    const document2 = this.domElement.getRootNode();
    document2.removeEventListener("keydown", this._interceptControlDown, { capture: true });
    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 {HTMLDOMElement} domElement - The DOM element
   */
  listenToKeyEvents(domElement) {
    domElement.addEventListener("keydown", this._onKeyDown);
    this._domElementKeyEvents = domElement;
  }
  /**
   * Removes the key event listener previously defined with `listenToKeyEvents()`.
   */
  stopListenToKeyEvents() {
    if (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(_changeEvent3);
    this.update();
    this.state = _STATE.NONE;
  }
  update(deltaTime = null) {
    const position2 = this.object.position;
    _v.copy(position2).sub(this.target);
    _v.applyQuaternion(this._quat);
    this._spherical.setFromVector3(_v);
    if (this.autoRotate && this.state === _STATE.NONE) {
      this._rotateLeft(this._getAutoRotationAngle(deltaTime));
    }
    if (this.enableDamping) {
      this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor;
      this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor;
    } else {
      this._spherical.theta += this._sphericalDelta.theta;
      this._spherical.phi += this._sphericalDelta.phi;
    }
    let min = this.minAzimuthAngle;
    let max2 = this.maxAzimuthAngle;
    if (isFinite(min) && isFinite(max2)) {
      if (min < -Math.PI) min += _twoPI;
      else if (min > Math.PI) min -= _twoPI;
      if (max2 < -Math.PI) max2 += _twoPI;
      else if (max2 > Math.PI) max2 -= _twoPI;
      if (min <= max2) {
        this._spherical.theta = Math.max(min, Math.min(max2, this._spherical.theta));
      } else {
        this._spherical.theta = this._spherical.theta > (min + max2) / 2 ? Math.max(min, this._spherical.theta) : Math.min(max2, this._spherical.theta);
      }
    }
    this._spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this._spherical.phi));
    this._spherical.makeSafe();
    if (this.enableDamping === true) {
      this.target.addScaledVector(this._panOffset, this.dampingFactor);
    } else {
      this.target.add(this._panOffset);
    }
    this.target.sub(this.cursor);
    this.target.clampLength(this.minTargetRadius, this.maxTargetRadius);
    this.target.add(this.cursor);
    let zoomChanged = false;
    if (this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera) {
      this._spherical.radius = this._clampDistance(this._spherical.radius);
    } else {
      const prevRadius = this._spherical.radius;
      this._spherical.radius = this._clampDistance(this._spherical.radius * this._scale);
      zoomChanged = prevRadius != this._spherical.radius;
    }
    _v.setFromSpherical(this._spherical);
    _v.applyQuaternion(this._quatInverse);
    position2.copy(this.target).add(_v);
    this.object.lookAt(this.target);
    if (this.enableDamping === true) {
      this._sphericalDelta.theta *= 1 - this.dampingFactor;
      this._sphericalDelta.phi *= 1 - this.dampingFactor;
      this._panOffset.multiplyScalar(1 - this.dampingFactor);
    } else {
      this._sphericalDelta.set(0, 0, 0);
      this._panOffset.set(0, 0, 0);
    }
    if (this.zoomToCursor && this._performCursorZoom) {
      let newRadius = null;
      if (this.object.isPerspectiveCamera) {
        const prevRadius = _v.length();
        newRadius = this._clampDistance(prevRadius * this._scale);
        const radiusDelta = prevRadius - newRadius;
        this.object.position.addScaledVector(this._dollyDirection, radiusDelta);
        this.object.updateMatrixWorld();
        zoomChanged = !!radiusDelta;
      } else if (this.object.isOrthographicCamera) {
        const mouseBefore = new Vector3(this._mouse.x, this._mouse.y, 0);
        mouseBefore.unproject(this.object);
        const prevZoom = this.object.zoom;
        this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale));
        this.object.updateProjectionMatrix();
        zoomChanged = prevZoom !== this.object.zoom;
        const mouseAfter = new Vector3(this._mouse.x, this._mouse.y, 0);
        mouseAfter.unproject(this.object);
        this.object.position.sub(mouseAfter).add(mouseBefore);
        this.object.updateMatrixWorld();
        newRadius = _v.length();
      } else {
        console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.");
        this.zoomToCursor = false;
      }
      if (newRadius !== null) {
        if (this.screenSpacePanning) {
          this.target.set(0, 0, -1).transformDirection(this.object.matrix).multiplyScalar(newRadius).add(this.object.position);
        } else {
          _ray.origin.copy(this.object.position);
          _ray.direction.set(0, 0, -1).transformDirection(this.object.matrix);
          if (Math.abs(this.object.up.dot(_ray.direction)) < _TILT_LIMIT) {
            this.object.lookAt(this.target);
          } else {
            _plane2.setFromNormalAndCoplanarPoint(this.object.up, this.target);
            _ray.intersectPlane(_plane2, this.target);
          }
        }
      }
    } else if (this.object.isOrthographicCamera) {
      const prevZoom = this.object.zoom;
      this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale));
      if (prevZoom !== this.object.zoom) {
        this.object.updateProjectionMatrix();
        zoomChanged = true;
      }
    }
    this._scale = 1;
    this._performCursorZoom = false;
    if (zoomChanged || this._lastPosition.distanceToSquared(this.object.position) > _EPS3 || 8 * (1 - this._lastQuaternion.dot(this.object.quaternion)) > _EPS3 || this._lastTargetPosition.distanceToSquared(this.target) > _EPS3) {
      this.dispatchEvent(_changeEvent3);
      this._lastPosition.copy(this.object.position);
      this._lastQuaternion.copy(this.object.quaternion);
      this._lastTargetPosition.copy(this.target);
      return true;
    }
    return false;
  }
  _getAutoRotationAngle(deltaTime) {
    if (deltaTime !== null) {
      return _twoPI / 60 * this.autoRotateSpeed * deltaTime;
    } else {
      return _twoPI / 60 / 60 * this.autoRotateSpeed;
    }
  }
  _getZoomScale(delta) {
    const normalizedDelta = Math.abs(delta * 0.01);
    return Math.pow(0.95, this.zoomSpeed * normalizedDelta);
  }
  _rotateLeft(angle) {
    this._sphericalDelta.theta -= angle;
  }
  _rotateUp(angle) {
    this._sphericalDelta.phi -= angle;
  }
  _panLeft(distance, objectMatrix) {
    _v.setFromMatrixColumn(objectMatrix, 0);
    _v.multiplyScalar(-distance);
    this._panOffset.add(_v);
  }
  _panUp(distance, objectMatrix) {
    if (this.screenSpacePanning === true) {
      _v.setFromMatrixColumn(objectMatrix, 1);
    } else {
      _v.setFromMatrixColumn(objectMatrix, 0);
      _v.crossVectors(this.object.up, _v);
    }
    _v.multiplyScalar(distance);
    this._panOffset.add(_v);
  }
  // deltaX and deltaY are in pixels; right and down are positive
  _pan(deltaX, deltaY) {
    const element = this.domElement;
    if (this.object.isPerspectiveCamera) {
      const position2 = this.object.position;
      _v.copy(position2).sub(this.target);
      let targetDistance = _v.length();
      targetDistance *= Math.tan(this.object.fov / 2 * Math.PI / 180);
      this._panLeft(2 * deltaX * targetDistance / element.clientHeight, this.object.matrix);
      this._panUp(2 * deltaY * targetDistance / element.clientHeight, this.object.matrix);
    } else if (this.object.isOrthographicCamera) {
      this._panLeft(deltaX * (this.object.right - this.object.left) / this.object.zoom / element.clientWidth, this.object.matrix);
      this._panUp(deltaY * (this.object.top - this.object.bottom) / this.object.zoom / element.clientHeight, this.object.matrix);
    } else {
      console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");
      this.enablePan = false;
    }
  }
  _dollyOut(dollyScale) {
    if (this.object.isPerspectiveCamera || this.object.isOrthographicCamera) {
      this._scale /= dollyScale;
    } else {
      console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
      this.enableZoom = false;
    }
  }
  _dollyIn(dollyScale) {
    if (this.object.isPerspectiveCamera || this.object.isOrthographicCamera) {
      this._scale *= dollyScale;
    } else {
      console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
      this.enableZoom = false;
    }
  }
  _updateZoomParameters(x2, y) {
    if (!this.zoomToCursor) {
      return;
    }
    this._performCursorZoom = true;
    const rect = this.domElement.getBoundingClientRect();
    const dx = x2 - rect.left;
    const dy = y - rect.top;
    const w = rect.width;
    const h = rect.height;
    this._mouse.x = dx / w * 2 - 1;
    this._mouse.y = -(dy / h) * 2 + 1;
    this._dollyDirection.set(this._mouse.x, this._mouse.y, 1).unproject(this.object).sub(this.object.position).normalize();
  }
  _clampDistance(dist) {
    return Math.max(this.minDistance, Math.min(this.maxDistance, dist));
  }
  //
  // event callbacks - update the object state
  //
  _handleMouseDownRotate(event) {
    this._rotateStart.set(event.clientX, event.clientY);
  }
  _handleMouseDownDolly(event) {
    this._updateZoomParameters(event.clientX, event.clientX);
    this._dollyStart.set(event.clientX, event.clientY);
  }
  _handleMouseDownPan(event) {
    this._panStart.set(event.clientX, event.clientY);
  }
  _handleMouseMoveRotate(event) {
    this._rotateEnd.set(event.clientX, event.clientY);
    this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed);
    const element = this.domElement;
    this._rotateLeft(_twoPI * this._rotateDelta.x / element.clientHeight);
    this._rotateUp(_twoPI * this._rotateDelta.y / element.clientHeight);
    this._rotateStart.copy(this._rotateEnd);
    this.update();
  }
  _handleMouseMoveDolly(event) {
    this._dollyEnd.set(event.clientX, event.clientY);
    this._dollyDelta.subVectors(this._dollyEnd, this._dollyStart);
    if (this._dollyDelta.y > 0) {
      this._dollyOut(this._getZoomScale(this._dollyDelta.y));
    } else if (this._dollyDelta.y < 0) {
      this._dollyIn(this._getZoomScale(this._dollyDelta.y));
    }
    this._dollyStart.copy(this._dollyEnd);
    this.update();
  }
  _handleMouseMovePan(event) {
    this._panEnd.set(event.clientX, event.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(event) {
    this._updateZoomParameters(event.clientX, event.clientY);
    if (event.deltaY < 0) {
      this._dollyIn(this._getZoomScale(event.deltaY));
    } else if (event.deltaY > 0) {
      this._dollyOut(this._getZoomScale(event.deltaY));
    }
    this.update();
  }
  _handleKeyDown(event) {
    let needsUpdate = false;
    switch (event.code) {
      case this.keys.UP:
        if (event.ctrlKey || event.metaKey || event.shiftKey) {
          if (this.enableRotate) {
            this._rotateUp(_twoPI * this.keyRotateSpeed / this.domElement.clientHeight);
          }
        } else {
          if (this.enablePan) {
            this._pan(0, this.keyPanSpeed);
          }
        }
        needsUpdate = true;
        break;
      case this.keys.BOTTOM:
        if (event.ctrlKey || event.metaKey || event.shiftKey) {
          if (this.enableRotate) {
            this._rotateUp(-_twoPI * this.keyRotateSpeed / this.domElement.clientHeight);
          }
        } else {
          if (this.enablePan) {
            this._pan(0, -this.keyPanSpeed);
          }
        }
        needsUpdate = true;
        break;
      case this.keys.LEFT:
        if (event.ctrlKey || event.metaKey || event.shiftKey) {
          if (this.enableRotate) {
            this._rotateLeft(_twoPI * this.keyRotateSpeed / this.domElement.clientHeight);
          }
        } else {
          if (this.enablePan) {
            this._pan(this.keyPanSpeed, 0);
          }
        }
        needsUpdate = true;
        break;
      case this.keys.RIGHT:
        if (event.ctrlKey || event.metaKey || event.shiftKey) {
          if (this.enableRotate) {
            this._rotateLeft(-_twoPI * this.keyRotateSpeed / this.domElement.clientHeight);
          }
        } else {
          if (this.enablePan) {
            this._pan(-this.keyPanSpeed, 0);
          }
        }
        needsUpdate = true;
        break;
    }
    if (needsUpdate) {
      event.preventDefault();
      this.update();
    }
  }
  _handleTouchStartRotate(event) {
    if (this._pointers.length === 1) {
      this._rotateStart.set(event.pageX, event.pageY);
    } else {
      const position2 = this._getSecondPointerPosition(event);
      const x2 = 0.5 * (event.pageX + position2.x);
      const y = 0.5 * (event.pageY + position2.y);
      this._rotateStart.set(x2, y);
    }
  }
  _handleTouchStartPan(event) {
    if (this._pointers.length === 1) {
      this._panStart.set(event.pageX, event.pageY);
    } else {
      const position2 = this._getSecondPointerPosition(event);
      const x2 = 0.5 * (event.pageX + position2.x);
      const y = 0.5 * (event.pageY + position2.y);
      this._panStart.set(x2, y);
    }
  }
  _handleTouchStartDolly(event) {
    const position2 = this._getSecondPointerPosition(event);
    const dx = event.pageX - position2.x;
    const dy = event.pageY - position2.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    this._dollyStart.set(0, distance);
  }
  _handleTouchStartDollyPan(event) {
    if (this.enableZoom) this._handleTouchStartDolly(event);
    if (this.enablePan) this._handleTouchStartPan(event);
  }
  _handleTouchStartDollyRotate(event) {
    if (this.enableZoom) this._handleTouchStartDolly(event);
    if (this.enableRotate) this._handleTouchStartRotate(event);
  }
  _handleTouchMoveRotate(event) {
    if (this._pointers.length == 1) {
      this._rotateEnd.set(event.pageX, event.pageY);
    } else {
      const position2 = this._getSecondPointerPosition(event);
      const x2 = 0.5 * (event.pageX + position2.x);
      const y = 0.5 * (event.pageY + position2.y);
      this._rotateEnd.set(x2, y);
    }
    this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed);
    const element = this.domElement;
    this._rotateLeft(_twoPI * this._rotateDelta.x / element.clientHeight);
    this._rotateUp(_twoPI * this._rotateDelta.y / element.clientHeight);
    this._rotateStart.copy(this._rotateEnd);
  }
  _handleTouchMovePan(event) {
    if (this._pointers.length === 1) {
      this._panEnd.set(event.pageX, event.pageY);
    } else {
      const position2 = this._getSecondPointerPosition(event);
      const x2 = 0.5 * (event.pageX + position2.x);
      const y = 0.5 * (event.pageY + position2.y);
      this._panEnd.set(x2, y);
    }
    this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed);
    this._pan(this._panDelta.x, this._panDelta.y);
    this._panStart.copy(this._panEnd);
  }
  _handleTouchMoveDolly(event) {
    const position2 = this._getSecondPointerPosition(event);
    const dx = event.pageX - position2.x;
    const dy = event.pageY - position2.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    this._dollyEnd.set(0, distance);
    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 centerX = (event.pageX + position2.x) * 0.5;
    const centerY = (event.pageY + position2.y) * 0.5;
    this._updateZoomParameters(centerX, centerY);
  }
  _handleTouchMoveDollyPan(event) {
    if (this.enableZoom) this._handleTouchMoveDolly(event);
    if (this.enablePan) this._handleTouchMovePan(event);
  }
  _handleTouchMoveDollyRotate(event) {
    if (this.enableZoom) this._handleTouchMoveDolly(event);
    if (this.enableRotate) this._handleTouchMoveRotate(event);
  }
  // pointers
  _addPointer(event) {
    this._pointers.push(event.pointerId);
  }
  _removePointer(event) {
    delete this._pointerPositions[event.pointerId];
    for (let i = 0; i < this._pointers.length; i++) {
      if (this._pointers[i] == event.pointerId) {
        this._pointers.splice(i, 1);
        return;
      }
    }
  }
  _isTrackingPointer(event) {
    for (let i = 0; i < this._pointers.length; i++) {
      if (this._pointers[i] == event.pointerId) return true;
    }
    return false;
  }
  _trackPointer(event) {
    let position2 = this._pointerPositions[event.pointerId];
    if (position2 === void 0) {
      position2 = new Vector2();
      this._pointerPositions[event.pointerId] = position2;
    }
    position2.set(event.pageX, event.pageY);
  }
  _getSecondPointerPosition(event) {
    const pointerId = event.pointerId === this._pointers[0] ? this._pointers[1] : this._pointers[0];
    return this._pointerPositions[pointerId];
  }
  //
  _customWheelEvent(event) {
    const mode = event.deltaMode;
    const newEvent = {
      clientX: event.clientX,
      clientY: event.clientY,
      deltaY: event.deltaY
    };
    switch (mode) {
      case 1:
        newEvent.deltaY *= 16;
        break;
      case 2:
        newEvent.deltaY *= 100;
        break;
    }
    if (event.ctrlKey && !this._controlActive) {
      newEvent.deltaY *= 10;
    }
    return newEvent;
  }
};
function onPointerDown5(event) {
  if (this.enabled === false) return;
  if (this._pointers.length === 0) {
    this.domElement.setPointerCapture(event.pointerId);
    this.domElement.addEventListener("pointermove", this._onPointerMove);
    this.domElement.addEventListener("pointerup", this._onPointerUp);
  }
  if (this._isTrackingPointer(event)) return;
  this._addPointer(event);
  if (event.pointerType === "touch") {
    this._onTouchStart(event);
  } else {
    this._onMouseDown(event);
  }
}
function onPointerMove5(event) {
  if (this.enabled === false) return;
  if (event.pointerType === "touch") {
    this._onTouchMove(event);
  } else {
    this._onMouseMove(event);
  }
}
function onPointerUp4(event) {
  this._removePointer(event);
  switch (this._pointers.length) {
    case 0:
      this.domElement.releasePointerCapture(event.pointerId);
      this.domElement.removeEventListener("pointermove", this._onPointerMove);
      this.domElement.removeEventListener("pointerup", this._onPointerUp);
      this.dispatchEvent(_endEvent2);
      this.state = _STATE.NONE;
      break;
    case 1:
      const pointerId = this._pointers[0];
      const position2 = this._pointerPositions[pointerId];
      this._onTouchStart({ pointerId, pageX: position2.x, pageY: position2.y });
      break;
  }
}
function onMouseDown(event) {
  let mouseAction;
  switch (event.button) {
    case 0:
      mouseAction = this.mouseButtons.LEFT;
      break;
    case 1:
      mouseAction = this.mouseButtons.MIDDLE;
      break;
    case 2:
      mouseAction = this.mouseButtons.RIGHT;
      break;
    default:
      mouseAction = -1;
  }
  switch (mouseAction) {
    case MOUSE.DOLLY:
      if (this.enableZoom === false) return;
      this._handleMouseDownDolly(event);
      this.state = _STATE.DOLLY;
      break;
    case MOUSE.ROTATE:
      if (event.ctrlKey || event.metaKey || event.shiftKey) {
        if (this.enablePan === false) return;
        this._handleMouseDownPan(event);
        this.state = _STATE.PAN;
      } else {
        if (this.enableRotate === false) return;
        this._handleMouseDownRotate(event);
        this.state = _STATE.ROTATE;
      }
      break;
    case MOUSE.PAN:
      if (event.ctrlKey || event.metaKey || event.shiftKey) {
        if (this.enableRotate === false) return;
        this._handleMouseDownRotate(event);
        this.state = _STATE.ROTATE;
      } else {
        if (this.enablePan === false) return;
        this._handleMouseDownPan(event);
        this.state = _STATE.PAN;
      }
      break;
    default:
      this.state = _STATE.NONE;
  }
  if (this.state !== _STATE.NONE) {
    this.dispatchEvent(_startEvent2);
  }
}
function onMouseMove(event) {
  switch (this.state) {
    case _STATE.ROTATE:
      if (this.enableRotate === false) return;
      this._handleMouseMoveRotate(event);
      break;
    case _STATE.DOLLY:
      if (this.enableZoom === false) return;
      this._handleMouseMoveDolly(event);
      break;
    case _STATE.PAN:
      if (this.enablePan === false) return;
      this._handleMouseMovePan(event);
      break;
  }
}
function onMouseWheel(event) {
  if (this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE) return;
  event.preventDefault();
  this.dispatchEvent(_startEvent2);
  this._handleMouseWheel(this._customWheelEvent(event));
  this.dispatchEvent(_endEvent2);
}
function onKeyDown3(event) {
  if (this.enabled === false) return;
  this._handleKeyDown(event);
}
function onTouchStart(event) {
  this._trackPointer(event);
  switch (this._pointers.length) {
    case 1:
      switch (this.touches.ONE) {
        case TOUCH.ROTATE:
          if (this.enableRotate === false) return;
          this._handleTouchStartRotate(event);
          this.state = _STATE.TOUCH_ROTATE;
          break;
        case TOUCH.PAN:
          if (this.enablePan === false) return;
          this._handleTouchStartPan(event);
          this.state = _STATE.TOUCH_PAN;
          break;
        default:
          this.state = _STATE.NONE;
      }
      break;
    case 2:
      switch (this.touches.TWO) {
        case TOUCH.DOLLY_PAN:
          if (this.enableZoom === false && this.enablePan === false) return;
          this._handleTouchStartDollyPan(event);
          this.state = _STATE.TOUCH_DOLLY_PAN;
          break;
        case TOUCH.DOLLY_ROTATE:
          if (this.enableZoom === false && this.enableRotate === false) return;
          this._handleTouchStartDollyRotate(event);
          this.state = _STATE.TOUCH_DOLLY_ROTATE;
          break;
        default:
          this.state = _STATE.NONE;
      }
      break;
    default:
      this.state = _STATE.NONE;
  }
  if (this.state !== _STATE.NONE) {
    this.dispatchEvent(_startEvent2);
  }
}
function onTouchMove(event) {
  this._trackPointer(event);
  switch (this.state) {
    case _STATE.TOUCH_ROTATE:
      if (this.enableRotate === false) return;
      this._handleTouchMoveRotate(event);
      this.update();
      break;
    case _STATE.TOUCH_PAN:
      if (this.enablePan === false) return;
      this._handleTouchMovePan(event);
      this.update();
      break;
    case _STATE.TOUCH_DOLLY_PAN:
      if (this.enableZoom === false && this.enablePan === false) return;
      this._handleTouchMoveDollyPan(event);
      this.update();
      break;
    case _STATE.TOUCH_DOLLY_ROTATE:
      if (this.enableZoom === false && this.enableRotate === false) return;
      this._handleTouchMoveDollyRotate(event);
      this.update();
      break;
    default:
      this.state = _STATE.NONE;
  }
}
function onContextMenu5(event) {
  if (this.enabled === false) return;
  event.preventDefault();
}
function interceptControlDown(event) {
  if (event.key === "Control") {
    this._controlActive = true;
    const document2 = this.domElement.getRootNode();
    document2.addEventListener("keyup", this._interceptControlUp, { passive: true, capture: true });
  }
}
function interceptControlUp(event) {
  if (event.key === "Control") {
    this._controlActive = false;
    const document2 = this.domElement.getRootNode();
    document2.removeEventListener("keyup", this._interceptControlUp, { passive: true, capture: true });
  }
}

// node_modules/three/examples/jsm/controls/MapControls.js
var MapControls = class extends OrbitControls {
  constructor(object, domElement) {
    super(object, domElement);
    this.screenSpacePanning = false;
    this.mouseButtons = { LEFT: MOUSE.PAN, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.ROTATE };
    this.touches = { ONE: TOUCH.PAN, TWO: TOUCH.DOLLY_ROTATE };
  }
};

// node_modules/three/examples/jsm/controls/PointerLockControls.js
var _euler = new Euler(0, 0, 0, "YXZ");
var _vector2 = new Vector3();
var _changeEvent4 = { type: "change" };
var _lockEvent = { type: "lock" };
var _unlockEvent = { type: "unlock" };
var _MOUSE_SENSITIVITY = 2e-3;
var _PI_2 = Math.PI / 2;
var PointerLockControls = class extends Controls {
  /**
   * Constructs a new controls instance.
   *
   * @param {Camera} camera - The camera that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(camera, domElement = null) {
    super(camera, domElement);
    this.isLocked = false;
    this.minPolarAngle = 0;
    this.maxPolarAngle = Math.PI;
    this.pointerSpeed = 1;
    this._onMouseMove = onMouseMove2.bind(this);
    this._onPointerlockChange = onPointerlockChange.bind(this);
    this._onPointerlockError = onPointerlockError.bind(this);
    if (this.domElement !== null) {
      this.connect(this.domElement);
    }
  }
  connect(element) {
    super.connect(element);
    this.domElement.ownerDocument.addEventListener("mousemove", this._onMouseMove);
    this.domElement.ownerDocument.addEventListener("pointerlockchange", this._onPointerlockChange);
    this.domElement.ownerDocument.addEventListener("pointerlockerror", this._onPointerlockError);
  }
  disconnect() {
    this.domElement.ownerDocument.removeEventListener("mousemove", this._onMouseMove);
    this.domElement.ownerDocument.removeEventListener("pointerlockchange", this._onPointerlockChange);
    this.domElement.ownerDocument.removeEventListener("pointerlockerror", this._onPointerlockError);
  }
  dispose() {
    this.disconnect();
  }
  getObject() {
    console.warn("THREE.PointerLockControls: getObject() has been deprecated. Use controls.object instead.");
    return this.object;
  }
  /**
   * Returns the look direction of the camera.
   *
   * @param {Vector3} v - The target vector that is used to store the method's result.
   * @return {Vector3} The normalized direction vector.
   */
  getDirection(v) {
    return v.set(0, 0, -1).applyQuaternion(this.object.quaternion);
  }
  /**
   * Moves the camera forward parallel to the xz-plane. Assumes camera.up is y-up.
   *
   * @param {number} distance - The signed distance.
   */
  moveForward(distance) {
    if (this.enabled === false) return;
    const camera = this.object;
    _vector2.setFromMatrixColumn(camera.matrix, 0);
    _vector2.crossVectors(camera.up, _vector2);
    camera.position.addScaledVector(_vector2, distance);
  }
  /**
   * Moves the camera sidewards parallel to the xz-plane.
   *
   * @param {number} distance - The signed distance.
   */
  moveRight(distance) {
    if (this.enabled === false) return;
    const camera = this.object;
    _vector2.setFromMatrixColumn(camera.matrix, 0);
    camera.position.addScaledVector(_vector2, distance);
  }
  /**
   * Activates the pointer lock.
   *
   * @param {boolean} [unadjustedMovement=false] - Disables OS-level adjustment for mouse acceleration, and accesses raw mouse input instead.
   * Setting it to true will disable mouse acceleration.
   */
  lock(unadjustedMovement = false) {
    this.domElement.requestPointerLock({
      unadjustedMovement
    });
  }
  /**
   * Exits the pointer lock.
   */
  unlock() {
    this.domElement.ownerDocument.exitPointerLock();
  }
};
function onMouseMove2(event) {
  if (this.enabled === false || this.isLocked === false) return;
  const camera = this.object;
  _euler.setFromQuaternion(camera.quaternion);
  _euler.y -= event.movementX * _MOUSE_SENSITIVITY * this.pointerSpeed;
  _euler.x -= event.movementY * _MOUSE_SENSITIVITY * this.pointerSpeed;
  _euler.x = Math.max(_PI_2 - this.maxPolarAngle, Math.min(_PI_2 - this.minPolarAngle, _euler.x));
  camera.quaternion.setFromEuler(_euler);
  this.dispatchEvent(_changeEvent4);
}
function onPointerlockChange() {
  if (this.domElement.ownerDocument.pointerLockElement === this.domElement) {
    this.dispatchEvent(_lockEvent);
    this.isLocked = true;
  } else {
    this.dispatchEvent(_unlockEvent);
    this.isLocked = false;
  }
}
function onPointerlockError() {
  console.error("THREE.PointerLockControls: Unable to use Pointer Lock API");
}

// node_modules/three/examples/jsm/controls/TrackballControls.js
var _changeEvent5 = { type: "change" };
var _startEvent3 = { type: "start" };
var _endEvent3 = { type: "end" };
var _EPS4 = 1e-6;
var _STATE2 = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 };
var _v2 = new Vector2();
var _mouseChange = new Vector2();
var _objectUp = new Vector3();
var _pan = new Vector3();
var _axis2 = new Vector3();
var _quaternion2 = new Quaternion();
var _eyeDirection = new Vector3();
var _objectUpDirection = new Vector3();
var _objectSidewaysDirection = new Vector3();
var _moveDirection = new Vector3();
var TrackballControls = class extends Controls {
  /**
   * Constructs a new controls instance.
   *
   * @param {Object3D} object - The object that is managed by the controls.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(object, domElement = null) {
    super(object, domElement);
    this.screen = { left: 0, top: 0, width: 0, height: 0 };
    this.rotateSpeed = 1;
    this.zoomSpeed = 1.2;
    this.panSpeed = 0.3;
    this.noRotate = false;
    this.noZoom = false;
    this.noPan = false;
    this.staticMoving = false;
    this.dynamicDampingFactor = 0.2;
    this.minDistance = 0;
    this.maxDistance = Infinity;
    this.minZoom = 0;
    this.maxZoom = Infinity;
    this.keys = [
      "KeyA",
      "KeyS",
      "KeyD"
      /*D*/
    ];
    this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
    this.target = new Vector3();
    this.state = _STATE2.NONE;
    this.keyState = _STATE2.NONE;
    this._lastPosition = new Vector3();
    this._lastZoom = 1;
    this._touchZoomDistanceStart = 0;
    this._touchZoomDistanceEnd = 0;
    this._lastAngle = 0;
    this._eye = new Vector3();
    this._movePrev = new Vector2();
    this._moveCurr = new Vector2();
    this._lastAxis = new Vector3();
    this._zoomStart = new Vector2();
    this._zoomEnd = new Vector2();
    this._panStart = new Vector2();
    this._panEnd = new Vector2();
    this._pointers = [];
    this._pointerPositions = {};
    this._onPointerMove = onPointerMove6.bind(this);
    this._onPointerDown = onPointerDown6.bind(this);
    this._onPointerUp = onPointerUp5.bind(this);
    this._onPointerCancel = onPointerCancel4.bind(this);
    this._onContextMenu = onContextMenu6.bind(this);
    this._onMouseWheel = onMouseWheel2.bind(this);
    this._onKeyDown = onKeyDown4.bind(this);
    this._onKeyUp = onKeyUp3.bind(this);
    this._onTouchStart = onTouchStart2.bind(this);
    this._onTouchMove = onTouchMove2.bind(this);
    this._onTouchEnd = onTouchEnd.bind(this);
    this._onMouseDown = onMouseDown2.bind(this);
    this._onMouseMove = onMouseMove3.bind(this);
    this._onMouseUp = onMouseUp.bind(this);
    this._target0 = this.target.clone();
    this._position0 = this.object.position.clone();
    this._up0 = this.object.up.clone();
    this._zoom0 = this.object.zoom;
    if (domElement !== null) {
      this.connect(domElement);
      this.handleResize();
    }
    this.update();
  }
  connect(element) {
    super.connect(element);
    window.addEventListener("keydown", this._onKeyDown);
    window.addEventListener("keyup", this._onKeyUp);
    this.domElement.addEventListener("pointerdown", this._onPointerDown);
    this.domElement.addEventListener("pointercancel", this._onPointerCancel);
    this.domElement.addEventListener("wheel", this._onMouseWheel, { passive: false });
    this.domElement.addEventListener("contextmenu", this._onContextMenu);
    this.domElement.style.touchAction = "none";
  }
  disconnect() {
    window.removeEventListener("keydown", this._onKeyDown);
    window.removeEventListener("keyup", this._onKeyUp);
    this.domElement.removeEventListener("pointerdown", this._onPointerDown);
    this.domElement.removeEventListener("pointermove", this._onPointerMove);
    this.domElement.removeEventListener("pointerup", this._onPointerUp);
    this.domElement.removeEventListener("pointercancel", this._onPointerCancel);
    this.domElement.removeEventListener("wheel", this._onMouseWheel);
    this.domElement.removeEventListener("contextmenu", this._onContextMenu);
    this.domElement.style.touchAction = "auto";
  }
  dispose() {
    this.disconnect();
  }
  /**
   * Must be called if the application window is resized.
   */
  handleResize() {
    const box = this.domElement.getBoundingClientRect();
    const d = this.domElement.ownerDocument.documentElement;
    this.screen.left = box.left + window.pageXOffset - d.clientLeft;
    this.screen.top = box.top + window.pageYOffset - d.clientTop;
    this.screen.width = box.width;
    this.screen.height = box.height;
  }
  update() {
    this._eye.subVectors(this.object.position, this.target);
    if (!this.noRotate) {
      this._rotateCamera();
    }
    if (!this.noZoom) {
      this._zoomCamera();
    }
    if (!this.noPan) {
      this._panCamera();
    }
    this.object.position.addVectors(this.target, this._eye);
    if (this.object.isPerspectiveCamera) {
      this._checkDistances();
      this.object.lookAt(this.target);
      if (this._lastPosition.distanceToSquared(this.object.position) > _EPS4) {
        this.dispatchEvent(_changeEvent5);
        this._lastPosition.copy(this.object.position);
      }
    } else if (this.object.isOrthographicCamera) {
      this.object.lookAt(this.target);
      if (this._lastPosition.distanceToSquared(this.object.position) > _EPS4 || this._lastZoom !== this.object.zoom) {
        this.dispatchEvent(_changeEvent5);
        this._lastPosition.copy(this.object.position);
        this._lastZoom = this.object.zoom;
      }
    } else {
      console.warn("THREE.TrackballControls: Unsupported camera type.");
    }
  }
  /**
   * Resets the controls to its initial state.
   */
  reset() {
    this.state = _STATE2.NONE;
    this.keyState = _STATE2.NONE;
    this.target.copy(this._target0);
    this.object.position.copy(this._position0);
    this.object.up.copy(this._up0);
    this.object.zoom = this._zoom0;
    this.object.updateProjectionMatrix();
    this._eye.subVectors(this.object.position, this.target);
    this.object.lookAt(this.target);
    this.dispatchEvent(_changeEvent5);
    this._lastPosition.copy(this.object.position);
    this._lastZoom = this.object.zoom;
  }
  _panCamera() {
    _mouseChange.copy(this._panEnd).sub(this._panStart);
    if (_mouseChange.lengthSq()) {
      if (this.object.isOrthographicCamera) {
        const scale_x = (this.object.right - this.object.left) / this.object.zoom / this.domElement.clientWidth;
        const scale_y = (this.object.top - this.object.bottom) / this.object.zoom / this.domElement.clientWidth;
        _mouseChange.x *= scale_x;
        _mouseChange.y *= scale_y;
      }
      _mouseChange.multiplyScalar(this._eye.length() * this.panSpeed);
      _pan.copy(this._eye).cross(this.object.up).setLength(_mouseChange.x);
      _pan.add(_objectUp.copy(this.object.up).setLength(_mouseChange.y));
      this.object.position.add(_pan);
      this.target.add(_pan);
      if (this.staticMoving) {
        this._panStart.copy(this._panEnd);
      } else {
        this._panStart.add(_mouseChange.subVectors(this._panEnd, this._panStart).multiplyScalar(this.dynamicDampingFactor));
      }
    }
  }
  _rotateCamera() {
    _moveDirection.set(this._moveCurr.x - this._movePrev.x, this._moveCurr.y - this._movePrev.y, 0);
    let angle = _moveDirection.length();
    if (angle) {
      this._eye.copy(this.object.position).sub(this.target);
      _eyeDirection.copy(this._eye).normalize();
      _objectUpDirection.copy(this.object.up).normalize();
      _objectSidewaysDirection.crossVectors(_objectUpDirection, _eyeDirection).normalize();
      _objectUpDirection.setLength(this._moveCurr.y - this._movePrev.y);
      _objectSidewaysDirection.setLength(this._moveCurr.x - this._movePrev.x);
      _moveDirection.copy(_objectUpDirection.add(_objectSidewaysDirection));
      _axis2.crossVectors(_moveDirection, this._eye).normalize();
      angle *= this.rotateSpeed;
      _quaternion2.setFromAxisAngle(_axis2, angle);
      this._eye.applyQuaternion(_quaternion2);
      this.object.up.applyQuaternion(_quaternion2);
      this._lastAxis.copy(_axis2);
      this._lastAngle = angle;
    } else if (!this.staticMoving && this._lastAngle) {
      this._lastAngle *= Math.sqrt(1 - this.dynamicDampingFactor);
      this._eye.copy(this.object.position).sub(this.target);
      _quaternion2.setFromAxisAngle(this._lastAxis, this._lastAngle);
      this._eye.applyQuaternion(_quaternion2);
      this.object.up.applyQuaternion(_quaternion2);
    }
    this._movePrev.copy(this._moveCurr);
  }
  _zoomCamera() {
    let factor;
    if (this.state === _STATE2.TOUCH_ZOOM_PAN) {
      factor = this._touchZoomDistanceStart / this._touchZoomDistanceEnd;
      this._touchZoomDistanceStart = this._touchZoomDistanceEnd;
      if (this.object.isPerspectiveCamera) {
        this._eye.multiplyScalar(factor);
      } else if (this.object.isOrthographicCamera) {
        this.object.zoom = MathUtils.clamp(this.object.zoom / factor, this.minZoom, this.maxZoom);
        if (this._lastZoom !== this.object.zoom) {
          this.object.updateProjectionMatrix();
        }
      } else {
        console.warn("THREE.TrackballControls: Unsupported camera type");
      }
    } else {
      factor = 1 + (this._zoomEnd.y - this._zoomStart.y) * this.zoomSpeed;
      if (factor !== 1 && factor > 0) {
        if (this.object.isPerspectiveCamera) {
          this._eye.multiplyScalar(factor);
        } else if (this.object.isOrthographicCamera) {
          this.object.zoom = MathUtils.clamp(this.object.zoom / factor, this.minZoom, this.maxZoom);
          if (this._lastZoom !== this.object.zoom) {
            this.object.updateProjectionMatrix();
          }
        } else {
          console.warn("THREE.TrackballControls: Unsupported camera type");
        }
      }
      if (this.staticMoving) {
        this._zoomStart.copy(this._zoomEnd);
      } else {
        this._zoomStart.y += (this._zoomEnd.y - this._zoomStart.y) * this.dynamicDampingFactor;
      }
    }
  }
  _getMouseOnScreen(pageX, pageY) {
    _v2.set(
      (pageX - this.screen.left) / this.screen.width,
      (pageY - this.screen.top) / this.screen.height
    );
    return _v2;
  }
  _getMouseOnCircle(pageX, pageY) {
    _v2.set(
      (pageX - this.screen.width * 0.5 - this.screen.left) / (this.screen.width * 0.5),
      (this.screen.height + 2 * (this.screen.top - pageY)) / this.screen.width
      // screen.width intentional
    );
    return _v2;
  }
  _addPointer(event) {
    this._pointers.push(event);
  }
  _removePointer(event) {
    delete this._pointerPositions[event.pointerId];
    for (let i = 0; i < this._pointers.length; i++) {
      if (this._pointers[i].pointerId == event.pointerId) {
        this._pointers.splice(i, 1);
        return;
      }
    }
  }
  _trackPointer(event) {
    let position2 = this._pointerPositions[event.pointerId];
    if (position2 === void 0) {
      position2 = new Vector2();
      this._pointerPositions[event.pointerId] = position2;
    }
    position2.set(event.pageX, event.pageY);
  }
  _getSecondPointerPosition(event) {
    const pointer = event.pointerId === this._pointers[0].pointerId ? this._pointers[1] : this._pointers[0];
    return this._pointerPositions[pointer.pointerId];
  }
  _checkDistances() {
    if (!this.noZoom || !this.noPan) {
      if (this._eye.lengthSq() > this.maxDistance * this.maxDistance) {
        this.object.position.addVectors(this.target, this._eye.setLength(this.maxDistance));
        this._zoomStart.copy(this._zoomEnd);
      }
      if (this._eye.lengthSq() < this.minDistance * this.minDistance) {
        this.object.position.addVectors(this.target, this._eye.setLength(this.minDistance));
        this._zoomStart.copy(this._zoomEnd);
      }
    }
  }
};
function onPointerDown6(event) {
  if (this.enabled === false) return;
  if (this._pointers.length === 0) {
    this.domElement.setPointerCapture(event.pointerId);
    this.domElement.addEventListener("pointermove", this._onPointerMove);
    this.domElement.addEventListener("pointerup", this._onPointerUp);
  }
  this._addPointer(event);
  if (event.pointerType === "touch") {
    this._onTouchStart(event);
  } else {
    this._onMouseDown(event);
  }
}
function onPointerMove6(event) {
  if (this.enabled === false) return;
  if (event.pointerType === "touch") {
    this._onTouchMove(event);
  } else {
    this._onMouseMove(event);
  }
}
function onPointerUp5(event) {
  if (this.enabled === false) return;
  if (event.pointerType === "touch") {
    this._onTouchEnd(event);
  } else {
    this._onMouseUp();
  }
  this._removePointer(event);
  if (this._pointers.length === 0) {
    this.domElement.releasePointerCapture(event.pointerId);
    this.domElement.removeEventListener("pointermove", this._onPointerMove);
    this.domElement.removeEventListener("pointerup", this._onPointerUp);
  }
}
function onPointerCancel4(event) {
  this._removePointer(event);
}
function onKeyUp3() {
  if (this.enabled === false) return;
  this.keyState = _STATE2.NONE;
  window.addEventListener("keydown", this._onKeyDown);
}
function onKeyDown4(event) {
  if (this.enabled === false) return;
  window.removeEventListener("keydown", this._onKeyDown);
  if (this.keyState !== _STATE2.NONE) {
    return;
  } else if (event.code === this.keys[_STATE2.ROTATE] && !this.noRotate) {
    this.keyState = _STATE2.ROTATE;
  } else if (event.code === this.keys[_STATE2.ZOOM] && !this.noZoom) {
    this.keyState = _STATE2.ZOOM;
  } else if (event.code === this.keys[_STATE2.PAN] && !this.noPan) {
    this.keyState = _STATE2.PAN;
  }
}
function onMouseDown2(event) {
  let mouseAction;
  switch (event.button) {
    case 0:
      mouseAction = this.mouseButtons.LEFT;
      break;
    case 1:
      mouseAction = this.mouseButtons.MIDDLE;
      break;
    case 2:
      mouseAction = this.mouseButtons.RIGHT;
      break;
    default:
      mouseAction = -1;
  }
  switch (mouseAction) {
    case MOUSE.DOLLY:
      this.state = _STATE2.ZOOM;
      break;
    case MOUSE.ROTATE:
      this.state = _STATE2.ROTATE;
      break;
    case MOUSE.PAN:
      this.state = _STATE2.PAN;
      break;
    default:
      this.state = _STATE2.NONE;
  }
  const state = this.keyState !== _STATE2.NONE ? this.keyState : this.state;
  if (state === _STATE2.ROTATE && !this.noRotate) {
    this._moveCurr.copy(this._getMouseOnCircle(event.pageX, event.pageY));
    this._movePrev.copy(this._moveCurr);
  } else if (state === _STATE2.ZOOM && !this.noZoom) {
    this._zoomStart.copy(this._getMouseOnScreen(event.pageX, event.pageY));
    this._zoomEnd.copy(this._zoomStart);
  } else if (state === _STATE2.PAN && !this.noPan) {
    this._panStart.copy(this._getMouseOnScreen(event.pageX, event.pageY));
    this._panEnd.copy(this._panStart);
  }
  this.dispatchEvent(_startEvent3);
}
function onMouseMove3(event) {
  const state = this.keyState !== _STATE2.NONE ? this.keyState : this.state;
  if (state === _STATE2.ROTATE && !this.noRotate) {
    this._movePrev.copy(this._moveCurr);
    this._moveCurr.copy(this._getMouseOnCircle(event.pageX, event.pageY));
  } else if (state === _STATE2.ZOOM && !this.noZoom) {
    this._zoomEnd.copy(this._getMouseOnScreen(event.pageX, event.pageY));
  } else if (state === _STATE2.PAN && !this.noPan) {
    this._panEnd.copy(this._getMouseOnScreen(event.pageX, event.pageY));
  }
}
function onMouseUp() {
  this.state = _STATE2.NONE;
  this.dispatchEvent(_endEvent3);
}
function onMouseWheel2(event) {
  if (this.enabled === false) return;
  if (this.noZoom === true) return;
  event.preventDefault();
  switch (event.deltaMode) {
    case 2:
      this._zoomStart.y -= event.deltaY * 0.025;
      break;
    case 1:
      this._zoomStart.y -= event.deltaY * 0.01;
      break;
    default:
      this._zoomStart.y -= event.deltaY * 25e-5;
      break;
  }
  this.dispatchEvent(_startEvent3);
  this.dispatchEvent(_endEvent3);
}
function onContextMenu6(event) {
  if (this.enabled === false) return;
  event.preventDefault();
}
function onTouchStart2(event) {
  this._trackPointer(event);
  switch (this._pointers.length) {
    case 1:
      this.state = _STATE2.TOUCH_ROTATE;
      this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX, this._pointers[0].pageY));
      this._movePrev.copy(this._moveCurr);
      break;
    default:
      this.state = _STATE2.TOUCH_ZOOM_PAN;
      const dx = this._pointers[0].pageX - this._pointers[1].pageX;
      const dy = this._pointers[0].pageY - this._pointers[1].pageY;
      this._touchZoomDistanceEnd = this._touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy);
      const x2 = (this._pointers[0].pageX + this._pointers[1].pageX) / 2;
      const y = (this._pointers[0].pageY + this._pointers[1].pageY) / 2;
      this._panStart.copy(this._getMouseOnScreen(x2, y));
      this._panEnd.copy(this._panStart);
      break;
  }
  this.dispatchEvent(_startEvent3);
}
function onTouchMove2(event) {
  this._trackPointer(event);
  switch (this._pointers.length) {
    case 1:
      this._movePrev.copy(this._moveCurr);
      this._moveCurr.copy(this._getMouseOnCircle(event.pageX, event.pageY));
      break;
    default:
      const position2 = this._getSecondPointerPosition(event);
      const dx = event.pageX - position2.x;
      const dy = event.pageY - position2.y;
      this._touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy);
      const x2 = (event.pageX + position2.x) / 2;
      const y = (event.pageY + position2.y) / 2;
      this._panEnd.copy(this._getMouseOnScreen(x2, y));
      break;
  }
}
function onTouchEnd(event) {
  switch (this._pointers.length) {
    case 0:
      this.state = _STATE2.NONE;
      break;
    case 1:
      this.state = _STATE2.TOUCH_ROTATE;
      this._moveCurr.copy(this._getMouseOnCircle(event.pageX, event.pageY));
      this._movePrev.copy(this._moveCurr);
      break;
    case 2:
      this.state = _STATE2.TOUCH_ZOOM_PAN;
      for (let i = 0; i < this._pointers.length; i++) {
        if (this._pointers[i].pointerId !== event.pointerId) {
          const position2 = this._pointerPositions[this._pointers[i].pointerId];
          this._moveCurr.copy(this._getMouseOnCircle(position2.x, position2.y));
          this._movePrev.copy(this._moveCurr);
          break;
        }
      }
      break;
  }
  this.dispatchEvent(_endEvent3);
}

// node_modules/three/examples/jsm/controls/TransformControls.js
var _raycaster2 = new Raycaster();
var _tempVector = new Vector3();
var _tempVector2 = new Vector3();
var _tempQuaternion = new Quaternion();
var _unit = {
  X: new Vector3(1, 0, 0),
  Y: new Vector3(0, 1, 0),
  Z: new Vector3(0, 0, 1)
};
var _changeEvent6 = { type: "change" };
var _mouseDownEvent = { type: "mouseDown", mode: null };
var _mouseUpEvent = { type: "mouseUp", mode: null };
var _objectChangeEvent = { type: "objectChange" };
var TransformControls = class extends Controls {
  /**
   * Constructs a new controls instance.
   *
   * @param {Camera} camera - The camera of the rendered scene.
   * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
   */
  constructor(camera, domElement = null) {
    super(void 0, domElement);
    const root = new TransformControlsRoot(this);
    this._root = root;
    const gizmo = new TransformControlsGizmo();
    this._gizmo = gizmo;
    root.add(gizmo);
    const plane2 = new TransformControlsPlane();
    this._plane = plane2;
    root.add(plane2);
    const scope = this;
    function defineProperty(propName, defaultValue) {
      let propValue = defaultValue;
      Object.defineProperty(scope, propName, {
        get: function() {
          return propValue !== void 0 ? propValue : defaultValue;
        },
        set: function(value2) {
          if (propValue !== value2) {
            propValue = value2;
            plane2[propName] = value2;
            gizmo[propName] = value2;
            scope.dispatchEvent({ type: propName + "-changed", value: value2 });
            scope.dispatchEvent(_changeEvent6);
          }
        }
      });
      scope[propName] = defaultValue;
      plane2[propName] = defaultValue;
      gizmo[propName] = defaultValue;
    }
    defineProperty("camera", camera);
    defineProperty("object", void 0);
    defineProperty("enabled", true);
    defineProperty("axis", null);
    defineProperty("mode", "translate");
    defineProperty("translationSnap", null);
    defineProperty("rotationSnap", null);
    defineProperty("scaleSnap", null);
    defineProperty("space", "world");
    defineProperty("size", 1);
    defineProperty("dragging", false);
    defineProperty("showX", true);
    defineProperty("showY", true);
    defineProperty("showZ", true);
    defineProperty("minX", -Infinity);
    defineProperty("maxX", Infinity);
    defineProperty("minY", -Infinity);
    defineProperty("maxY", Infinity);
    defineProperty("minZ", -Infinity);
    defineProperty("maxZ", Infinity);
    const worldPosition = new Vector3();
    const worldPositionStart = new Vector3();
    const worldQuaternion = new Quaternion();
    const worldQuaternionStart = new Quaternion();
    const cameraPosition = new Vector3();
    const cameraQuaternion = new Quaternion();
    const pointStart = new Vector3();
    const pointEnd = new Vector3();
    const rotationAxis = new Vector3();
    const rotationAngle = 0;
    const eye = new Vector3();
    defineProperty("worldPosition", worldPosition);
    defineProperty("worldPositionStart", worldPositionStart);
    defineProperty("worldQuaternion", worldQuaternion);
    defineProperty("worldQuaternionStart", worldQuaternionStart);
    defineProperty("cameraPosition", cameraPosition);
    defineProperty("cameraQuaternion", cameraQuaternion);
    defineProperty("pointStart", pointStart);
    defineProperty("pointEnd", pointEnd);
    defineProperty("rotationAxis", rotationAxis);
    defineProperty("rotationAngle", rotationAngle);
    defineProperty("eye", eye);
    this._offset = new Vector3();
    this._startNorm = new Vector3();
    this._endNorm = new Vector3();
    this._cameraScale = new Vector3();
    this._parentPosition = new Vector3();
    this._parentQuaternion = new Quaternion();
    this._parentQuaternionInv = new Quaternion();
    this._parentScale = new Vector3();
    this._worldScaleStart = new Vector3();
    this._worldQuaternionInv = new Quaternion();
    this._worldScale = new Vector3();
    this._positionStart = new Vector3();
    this._quaternionStart = new Quaternion();
    this._scaleStart = new Vector3();
    this._getPointer = getPointer.bind(this);
    this._onPointerDown = onPointerDown7.bind(this);
    this._onPointerHover = onPointerHover.bind(this);
    this._onPointerMove = onPointerMove7.bind(this);
    this._onPointerUp = onPointerUp6.bind(this);
    if (domElement !== null) {
      this.connect(domElement);
    }
  }
  connect(element) {
    super.connect(element);
    this.domElement.addEventListener("pointerdown", this._onPointerDown);
    this.domElement.addEventListener("pointermove", this._onPointerHover);
    this.domElement.addEventListener("pointerup", this._onPointerUp);
    this.domElement.style.touchAction = "none";
  }
  disconnect() {
    this.domElement.removeEventListener("pointerdown", this._onPointerDown);
    this.domElement.removeEventListener("pointermove", this._onPointerHover);
    this.domElement.removeEventListener("pointermove", this._onPointerMove);
    this.domElement.removeEventListener("pointerup", this._onPointerUp);
    this.domElement.style.touchAction = "auto";
  }
  /**
   * Returns the visual representation of the controls. Add the helper to your scene to
   * visually transform the attached  3D object.
   *
   * @return {TransformControlsRoot} The helper.
   */
  getHelper() {
    return this._root;
  }
  pointerHover(pointer) {
    if (this.object === void 0 || this.dragging === true) return;
    if (pointer !== null) _raycaster2.setFromCamera(pointer, this.camera);
    const intersect = intersectObjectWithRay(this._gizmo.picker[this.mode], _raycaster2);
    if (intersect) {
      this.axis = intersect.object.name;
    } else {
      this.axis = null;
    }
  }
  pointerDown(pointer) {
    if (this.object === void 0 || this.dragging === true || pointer != null && pointer.button !== 0) return;
    if (this.axis !== null) {
      if (pointer !== null) _raycaster2.setFromCamera(pointer, this.camera);
      const planeIntersect = intersectObjectWithRay(this._plane, _raycaster2, true);
      if (planeIntersect) {
        this.object.updateMatrixWorld();
        this.object.parent.updateMatrixWorld();
        this._positionStart.copy(this.object.position);
        this._quaternionStart.copy(this.object.quaternion);
        this._scaleStart.copy(this.object.scale);
        this.object.matrixWorld.decompose(this.worldPositionStart, this.worldQuaternionStart, this._worldScaleStart);
        this.pointStart.copy(planeIntersect.point).sub(this.worldPositionStart);
      }
      this.dragging = true;
      _mouseDownEvent.mode = this.mode;
      this.dispatchEvent(_mouseDownEvent);
    }
  }
  pointerMove(pointer) {
    const axis = this.axis;
    const mode = this.mode;
    const object = this.object;
    let space = this.space;
    if (mode === "scale") {
      space = "local";
    } else if (axis === "E" || axis === "XYZE" || axis === "XYZ") {
      space = "world";
    }
    if (object === void 0 || axis === null || this.dragging === false || pointer !== null && pointer.button !== -1) return;
    if (pointer !== null) _raycaster2.setFromCamera(pointer, this.camera);
    const planeIntersect = intersectObjectWithRay(this._plane, _raycaster2, true);
    if (!planeIntersect) return;
    this.pointEnd.copy(planeIntersect.point).sub(this.worldPositionStart);
    if (mode === "translate") {
      this._offset.copy(this.pointEnd).sub(this.pointStart);
      if (space === "local" && axis !== "XYZ") {
        this._offset.applyQuaternion(this._worldQuaternionInv);
      }
      if (axis.indexOf("X") === -1) this._offset.x = 0;
      if (axis.indexOf("Y") === -1) this._offset.y = 0;
      if (axis.indexOf("Z") === -1) this._offset.z = 0;
      if (space === "local" && axis !== "XYZ") {
        this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale);
      } else {
        this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale);
      }
      object.position.copy(this._offset).add(this._positionStart);
      if (this.translationSnap) {
        if (space === "local") {
          object.position.applyQuaternion(_tempQuaternion.copy(this._quaternionStart).invert());
          if (axis.search("X") !== -1) {
            object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap;
          }
          if (axis.search("Y") !== -1) {
            object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap;
          }
          if (axis.search("Z") !== -1) {
            object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap;
          }
          object.position.applyQuaternion(this._quaternionStart);
        }
        if (space === "world") {
          if (object.parent) {
            object.position.add(_tempVector.setFromMatrixPosition(object.parent.matrixWorld));
          }
          if (axis.search("X") !== -1) {
            object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap;
          }
          if (axis.search("Y") !== -1) {
            object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap;
          }
          if (axis.search("Z") !== -1) {
            object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap;
          }
          if (object.parent) {
            object.position.sub(_tempVector.setFromMatrixPosition(object.parent.matrixWorld));
          }
        }
      }
      object.position.x = Math.max(this.minX, Math.min(this.maxX, object.position.x));
      object.position.y = Math.max(this.minY, Math.min(this.maxY, object.position.y));
      object.position.z = Math.max(this.minZ, Math.min(this.maxZ, object.position.z));
    } else if (mode === "scale") {
      if (axis.search("XYZ") !== -1) {
        let d = this.pointEnd.length() / this.pointStart.length();
        if (this.pointEnd.dot(this.pointStart) < 0) d *= -1;
        _tempVector2.set(d, d, d);
      } else {
        _tempVector.copy(this.pointStart);
        _tempVector2.copy(this.pointEnd);
        _tempVector.applyQuaternion(this._worldQuaternionInv);
        _tempVector2.applyQuaternion(this._worldQuaternionInv);
        _tempVector2.divide(_tempVector);
        if (axis.search("X") === -1) {
          _tempVector2.x = 1;
        }
        if (axis.search("Y") === -1) {
          _tempVector2.y = 1;
        }
        if (axis.search("Z") === -1) {
          _tempVector2.z = 1;
        }
      }
      object.scale.copy(this._scaleStart).multiply(_tempVector2);
      if (this.scaleSnap) {
        if (axis.search("X") !== -1) {
          object.scale.x = Math.round(object.scale.x / this.scaleSnap) * this.scaleSnap || this.scaleSnap;
        }
        if (axis.search("Y") !== -1) {
          object.scale.y = Math.round(object.scale.y / this.scaleSnap) * this.scaleSnap || this.scaleSnap;
        }
        if (axis.search("Z") !== -1) {
          object.scale.z = Math.round(object.scale.z / this.scaleSnap) * this.scaleSnap || this.scaleSnap;
        }
      }
    } else if (mode === "rotate") {
      this._offset.copy(this.pointEnd).sub(this.pointStart);
      const ROTATION_SPEED = 20 / this.worldPosition.distanceTo(_tempVector.setFromMatrixPosition(this.camera.matrixWorld));
      let _inPlaneRotation = false;
      if (axis === "XYZE") {
        this.rotationAxis.copy(this._offset).cross(this.eye).normalize();
        this.rotationAngle = this._offset.dot(_tempVector.copy(this.rotationAxis).cross(this.eye)) * ROTATION_SPEED;
      } else if (axis === "X" || axis === "Y" || axis === "Z") {
        this.rotationAxis.copy(_unit[axis]);
        _tempVector.copy(_unit[axis]);
        if (space === "local") {
          _tempVector.applyQuaternion(this.worldQuaternion);
        }
        _tempVector.cross(this.eye);
        if (_tempVector.length() === 0) {
          _inPlaneRotation = true;
        } else {
          this.rotationAngle = this._offset.dot(_tempVector.normalize()) * ROTATION_SPEED;
        }
      }
      if (axis === "E" || _inPlaneRotation) {
        this.rotationAxis.copy(this.eye);
        this.rotationAngle = this.pointEnd.angleTo(this.pointStart);
        this._startNorm.copy(this.pointStart).normalize();
        this._endNorm.copy(this.pointEnd).normalize();
        this.rotationAngle *= this._endNorm.cross(this._startNorm).dot(this.eye) < 0 ? 1 : -1;
      }
      if (this.rotationSnap) this.rotationAngle = Math.round(this.rotationAngle / this.rotationSnap) * this.rotationSnap;
      if (space === "local" && axis !== "E" && axis !== "XYZE") {
        object.quaternion.copy(this._quaternionStart);
        object.quaternion.multiply(_tempQuaternion.setFromAxisAngle(this.rotationAxis, this.rotationAngle)).normalize();
      } else {
        this.rotationAxis.applyQuaternion(this._parentQuaternionInv);
        object.quaternion.copy(_tempQuaternion.setFromAxisAngle(this.rotationAxis, this.rotationAngle));
        object.quaternion.multiply(this._quaternionStart).normalize();
      }
    }
    this.dispatchEvent(_changeEvent6);
    this.dispatchEvent(_objectChangeEvent);
  }
  pointerUp(pointer) {
    if (pointer !== null && pointer.button !== 0) return;
    if (this.dragging && this.axis !== null) {
      _mouseUpEvent.mode = this.mode;
      this.dispatchEvent(_mouseUpEvent);
    }
    this.dragging = false;
    this.axis = null;
  }
  dispose() {
    this.disconnect();
    this._root.dispose();
  }
  /**
   * Sets the 3D object that should be transformed and ensures the controls UI is visible.
   *
   * @param {Object3D} object -  The 3D object that should be transformed.
   * @return {TransformControls} A reference to this controls.
   */
  attach(object) {
    this.object = object;
    this._root.visible = true;
    return this;
  }
  /**
   * Removes the current 3D object from the controls and makes the helper UI invisible.
   *
   * @return {TransformControls} A reference to this controls.
   */
  detach() {
    this.object = void 0;
    this.axis = null;
    this._root.visible = false;
    return this;
  }
  /**
   * Resets the object's position, rotation and scale to when the current transform began.
   */
  reset() {
    if (!this.enabled) return;
    if (this.dragging) {
      this.object.position.copy(this._positionStart);
      this.object.quaternion.copy(this._quaternionStart);
      this.object.scale.copy(this._scaleStart);
      this.dispatchEvent(_changeEvent6);
      this.dispatchEvent(_objectChangeEvent);
      this.pointStart.copy(this.pointEnd);
    }
  }
  /**
   * Returns the raycaster that is used for user interaction. This object is shared between all
   * instances of `TransformControls`.
   *
   * @returns {Raycaster} The internal raycaster.
   */
  getRaycaster() {
    return _raycaster2;
  }
  /**
   * Returns the transformation mode.
   *
   * @returns {'translate'|'rotate'|'scale'} The transformation mode.
   */
  getMode() {
    return this.mode;
  }
  /**
   * Sets the given transformation mode.
   *
   * @param {'translate'|'rotate'|'scale'} mode - The transformation mode to set.
   */
  setMode(mode) {
    this.mode = mode;
  }
  /**
   * Sets the translation snap.
   *
   * @param {?number} translationSnap - The translation snap to set.
   */
  setTranslationSnap(translationSnap) {
    this.translationSnap = translationSnap;
  }
  /**
   * Sets the rotation snap.
   *
   * @param {?number} rotationSnap - The rotation snap to set.
   */
  setRotationSnap(rotationSnap) {
    this.rotationSnap = rotationSnap;
  }
  /**
   * Sets the scale snap.
   *
   * @param {?number} scaleSnap - The scale snap to set.
   */
  setScaleSnap(scaleSnap) {
    this.scaleSnap = scaleSnap;
  }
  /**
   * Sets the size of the helper UI.
   *
   * @param {number} size - The size to set.
   */
  setSize(size2) {
    this.size = size2;
  }
  /**
   * Sets the coordinate space in which transformations are applied.
   *
   * @param {'world'|'local'} space - The space to set.
   */
  setSpace(space) {
    this.space = space;
  }
  /**
   * Sets the colors of the control's gizmo.
   *
   * @param {number|Color|string} xAxis - The x-axis color.
   * @param {number|Color|string} yAxis - The y-axis color.
   * @param {number|Color|string} zAxis - The z-axis color.
   * @param {number|Color|string} active - The color for active elements.
   */
  setColors(xAxis2, yAxis2, zAxis2, active2) {
    const materialLib = this._gizmo.materialLib;
    materialLib.xAxis.color.set(xAxis2);
    materialLib.yAxis.color.set(yAxis2);
    materialLib.zAxis.color.set(zAxis2);
    materialLib.active.color.set(active2);
    materialLib.xAxisTransparent.color.set(xAxis2);
    materialLib.yAxisTransparent.color.set(yAxis2);
    materialLib.zAxisTransparent.color.set(zAxis2);
    materialLib.activeTransparent.color.set(active2);
    if (materialLib.xAxis._color) materialLib.xAxis._color.set(xAxis2);
    if (materialLib.yAxis._color) materialLib.yAxis._color.set(yAxis2);
    if (materialLib.zAxis._color) materialLib.zAxis._color.set(zAxis2);
    if (materialLib.active._color) materialLib.active._color.set(active2);
    if (materialLib.xAxisTransparent._color) materialLib.xAxisTransparent._color.set(xAxis2);
    if (materialLib.yAxisTransparent._color) materialLib.yAxisTransparent._color.set(yAxis2);
    if (materialLib.zAxisTransparent._color) materialLib.zAxisTransparent._color.set(zAxis2);
    if (materialLib.activeTransparent._color) materialLib.activeTransparent._color.set(active2);
  }
};
function getPointer(event) {
  if (this.domElement.ownerDocument.pointerLockElement) {
    return {
      x: 0,
      y: 0,
      button: event.button
    };
  } else {
    const rect = this.domElement.getBoundingClientRect();
    return {
      x: (event.clientX - rect.left) / rect.width * 2 - 1,
      y: -(event.clientY - rect.top) / rect.height * 2 + 1,
      button: event.button
    };
  }
}
function onPointerHover(event) {
  if (!this.enabled) return;
  switch (event.pointerType) {
    case "mouse":
    case "pen":
      this.pointerHover(this._getPointer(event));
      break;
  }
}
function onPointerDown7(event) {
  if (!this.enabled) return;
  if (!document.pointerLockElement) {
    this.domElement.setPointerCapture(event.pointerId);
  }
  this.domElement.addEventListener("pointermove", this._onPointerMove);
  this.pointerHover(this._getPointer(event));
  this.pointerDown(this._getPointer(event));
}
function onPointerMove7(event) {
  if (!this.enabled) return;
  this.pointerMove(this._getPointer(event));
}
function onPointerUp6(event) {
  if (!this.enabled) return;
  this.domElement.releasePointerCapture(event.pointerId);
  this.domElement.removeEventListener("pointermove", this._onPointerMove);
  this.pointerUp(this._getPointer(event));
}
function intersectObjectWithRay(object, raycaster, includeInvisible) {
  const allIntersections = raycaster.intersectObject(object, true);
  for (let i = 0; i < allIntersections.length; i++) {
    if (allIntersections[i].object.visible || includeInvisible) {
      return allIntersections[i];
    }
  }
  return false;
}
var _tempEuler = new Euler();
var _alignVector = new Vector3(0, 1, 0);
var _zeroVector = new Vector3(0, 0, 0);
var _lookAtMatrix = new Matrix4();
var _tempQuaternion2 = new Quaternion();
var _identityQuaternion = new Quaternion();
var _dirVector = new Vector3();
var _tempMatrix = new Matrix4();
var _unitX = new Vector3(1, 0, 0);
var _unitY = new Vector3(0, 1, 0);
var _unitZ = new Vector3(0, 0, 1);
var _v1 = new Vector3();
var _v22 = new Vector3();
var _v3 = new Vector3();
var TransformControlsRoot = class extends Object3D {
  constructor(controls) {
    super();
    this.isTransformControlsRoot = true;
    this.controls = controls;
    this.visible = false;
  }
  // updateMatrixWorld updates key transformation variables
  updateMatrixWorld(force) {
    const controls = this.controls;
    if (controls.object !== void 0) {
      controls.object.updateMatrixWorld();
      if (controls.object.parent === null) {
        console.error("TransformControls: The attached 3D object must be a part of the scene graph.");
      } else {
        controls.object.parent.matrixWorld.decompose(controls._parentPosition, controls._parentQuaternion, controls._parentScale);
      }
      controls.object.matrixWorld.decompose(controls.worldPosition, controls.worldQuaternion, controls._worldScale);
      controls._parentQuaternionInv.copy(controls._parentQuaternion).invert();
      controls._worldQuaternionInv.copy(controls.worldQuaternion).invert();
    }
    controls.camera.updateMatrixWorld();
    controls.camera.matrixWorld.decompose(controls.cameraPosition, controls.cameraQuaternion, controls._cameraScale);
    if (controls.camera.isOrthographicCamera) {
      controls.camera.getWorldDirection(controls.eye).negate();
    } else {
      controls.eye.copy(controls.cameraPosition).sub(controls.worldPosition).normalize();
    }
    super.updateMatrixWorld(force);
  }
  dispose() {
    this.traverse(function(child) {
      if (child.geometry) child.geometry.dispose();
      if (child.material) child.material.dispose();
    });
  }
};
var TransformControlsGizmo = class extends Object3D {
  constructor() {
    super();
    this.isTransformControlsGizmo = true;
    this.type = "TransformControlsGizmo";
    const gizmoMaterial = new MeshBasicMaterial({
      depthTest: false,
      depthWrite: false,
      fog: false,
      toneMapped: false,
      transparent: true
    });
    const gizmoLineMaterial = new LineBasicMaterial({
      depthTest: false,
      depthWrite: false,
      fog: false,
      toneMapped: false,
      transparent: true
    });
    const matInvisible = gizmoMaterial.clone();
    matInvisible.opacity = 0.15;
    const matHelper = gizmoLineMaterial.clone();
    matHelper.opacity = 0.5;
    const matRed = gizmoMaterial.clone();
    matRed.color.setHex(16711680);
    const matGreen = gizmoMaterial.clone();
    matGreen.color.setHex(65280);
    const matBlue = gizmoMaterial.clone();
    matBlue.color.setHex(255);
    const matRedTransparent = gizmoMaterial.clone();
    matRedTransparent.color.setHex(16711680);
    matRedTransparent.opacity = 0.5;
    const matGreenTransparent = gizmoMaterial.clone();
    matGreenTransparent.color.setHex(65280);
    matGreenTransparent.opacity = 0.5;
    const matBlueTransparent = gizmoMaterial.clone();
    matBlueTransparent.color.setHex(255);
    matBlueTransparent.opacity = 0.5;
    const matWhiteTransparent = gizmoMaterial.clone();
    matWhiteTransparent.opacity = 0.25;
    const matYellowTransparent = gizmoMaterial.clone();
    matYellowTransparent.color.setHex(16776960);
    matYellowTransparent.opacity = 0.25;
    const matYellow = gizmoMaterial.clone();
    matYellow.color.setHex(16776960);
    const matGray = gizmoMaterial.clone();
    matGray.color.setHex(7895160);
    this.materialLib = {
      xAxis: matRed,
      yAxis: matGreen,
      zAxis: matBlue,
      active: matYellow,
      xAxisTransparent: matRedTransparent,
      yAxisTransparent: matGreenTransparent,
      zAxisTransparent: matBlueTransparent,
      activeTransparent: matYellowTransparent
    };
    const arrowGeometry = new CylinderGeometry(0, 0.04, 0.1, 12);
    arrowGeometry.translate(0, 0.05, 0);
    const scaleHandleGeometry = new BoxGeometry(0.08, 0.08, 0.08);
    scaleHandleGeometry.translate(0, 0.04, 0);
    const lineGeometry = new BufferGeometry();
    lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 1, 0, 0], 3));
    const lineGeometry2 = new CylinderGeometry(75e-4, 75e-4, 0.5, 3);
    lineGeometry2.translate(0, 0.25, 0);
    function CircleGeometry(radius, arc) {
      const geometry = new TorusGeometry(radius, 75e-4, 3, 64, arc * Math.PI * 2);
      geometry.rotateY(Math.PI / 2);
      geometry.rotateX(Math.PI / 2);
      return geometry;
    }
    function TranslateHelperGeometry() {
      const geometry = new BufferGeometry();
      geometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 1, 1, 1], 3));
      return geometry;
    }
    const gizmoTranslate = {
      X: [
        [new Mesh(arrowGeometry, matRed), [0.5, 0, 0], [0, 0, -Math.PI / 2]],
        [new Mesh(arrowGeometry, matRed), [-0.5, 0, 0], [0, 0, Math.PI / 2]],
        [new Mesh(lineGeometry2, matRed), [0, 0, 0], [0, 0, -Math.PI / 2]]
      ],
      Y: [
        [new Mesh(arrowGeometry, matGreen), [0, 0.5, 0]],
        [new Mesh(arrowGeometry, matGreen), [0, -0.5, 0], [Math.PI, 0, 0]],
        [new Mesh(lineGeometry2, matGreen)]
      ],
      Z: [
        [new Mesh(arrowGeometry, matBlue), [0, 0, 0.5], [Math.PI / 2, 0, 0]],
        [new Mesh(arrowGeometry, matBlue), [0, 0, -0.5], [-Math.PI / 2, 0, 0]],
        [new Mesh(lineGeometry2, matBlue), null, [Math.PI / 2, 0, 0]]
      ],
      XYZ: [
        [new Mesh(new OctahedronGeometry(0.1, 0), matWhiteTransparent), [0, 0, 0]]
      ],
      XY: [
        [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matBlueTransparent), [0.15, 0.15, 0]]
      ],
      YZ: [
        [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matRedTransparent), [0, 0.15, 0.15], [0, Math.PI / 2, 0]]
      ],
      XZ: [
        [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matGreenTransparent), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]]
      ]
    };
    const pickerTranslate = {
      X: [
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0.3, 0, 0], [0, 0, -Math.PI / 2]],
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [-0.3, 0, 0], [0, 0, Math.PI / 2]]
      ],
      Y: [
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0.3, 0]],
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, -0.3, 0], [0, 0, Math.PI]]
      ],
      Z: [
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, 0.3], [Math.PI / 2, 0, 0]],
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, -0.3], [-Math.PI / 2, 0, 0]]
      ],
      XYZ: [
        [new Mesh(new OctahedronGeometry(0.2, 0), matInvisible)]
      ],
      XY: [
        [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0.15, 0]]
      ],
      YZ: [
        [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0, 0.15, 0.15], [0, Math.PI / 2, 0]]
      ],
      XZ: [
        [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]]
      ]
    };
    const helperTranslate = {
      START: [
        [new Mesh(new OctahedronGeometry(0.01, 2), matHelper), null, null, null, "helper"]
      ],
      END: [
        [new Mesh(new OctahedronGeometry(0.01, 2), matHelper), null, null, null, "helper"]
      ],
      DELTA: [
        [new Line(TranslateHelperGeometry(), matHelper), null, null, null, "helper"]
      ],
      X: [
        [new Line(lineGeometry, matHelper), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"]
      ],
      Y: [
        [new Line(lineGeometry, matHelper), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], "helper"]
      ],
      Z: [
        [new Line(lineGeometry, matHelper), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], "helper"]
      ]
    };
    const gizmoRotate = {
      XYZE: [
        [new Mesh(CircleGeometry(0.5, 1), matGray), null, [0, Math.PI / 2, 0]]
      ],
      X: [
        [new Mesh(CircleGeometry(0.5, 0.5), matRed)]
      ],
      Y: [
        [new Mesh(CircleGeometry(0.5, 0.5), matGreen), null, [0, 0, -Math.PI / 2]]
      ],
      Z: [
        [new Mesh(CircleGeometry(0.5, 0.5), matBlue), null, [0, Math.PI / 2, 0]]
      ],
      E: [
        [new Mesh(CircleGeometry(0.75, 1), matYellowTransparent), null, [0, Math.PI / 2, 0]]
      ]
    };
    const helperRotate = {
      AXIS: [
        [new Line(lineGeometry, matHelper), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"]
      ]
    };
    const pickerRotate = {
      XYZE: [
        [new Mesh(new SphereGeometry(0.25, 10, 8), matInvisible)]
      ],
      X: [
        [new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, -Math.PI / 2, -Math.PI / 2]]
      ],
      Y: [
        [new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [Math.PI / 2, 0, 0]]
      ],
      Z: [
        [new Mesh(new TorusGeometry(0.5, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, 0, -Math.PI / 2]]
      ],
      E: [
        [new Mesh(new TorusGeometry(0.75, 0.1, 2, 24), matInvisible)]
      ]
    };
    const gizmoScale = {
      X: [
        [new Mesh(scaleHandleGeometry, matRed), [0.5, 0, 0], [0, 0, -Math.PI / 2]],
        [new Mesh(lineGeometry2, matRed), [0, 0, 0], [0, 0, -Math.PI / 2]],
        [new Mesh(scaleHandleGeometry, matRed), [-0.5, 0, 0], [0, 0, Math.PI / 2]]
      ],
      Y: [
        [new Mesh(scaleHandleGeometry, matGreen), [0, 0.5, 0]],
        [new Mesh(lineGeometry2, matGreen)],
        [new Mesh(scaleHandleGeometry, matGreen), [0, -0.5, 0], [0, 0, Math.PI]]
      ],
      Z: [
        [new Mesh(scaleHandleGeometry, matBlue), [0, 0, 0.5], [Math.PI / 2, 0, 0]],
        [new Mesh(lineGeometry2, matBlue), [0, 0, 0], [Math.PI / 2, 0, 0]],
        [new Mesh(scaleHandleGeometry, matBlue), [0, 0, -0.5], [-Math.PI / 2, 0, 0]]
      ],
      XY: [
        [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matBlueTransparent), [0.15, 0.15, 0]]
      ],
      YZ: [
        [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matRedTransparent), [0, 0.15, 0.15], [0, Math.PI / 2, 0]]
      ],
      XZ: [
        [new Mesh(new BoxGeometry(0.15, 0.15, 0.01), matGreenTransparent), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]]
      ],
      XYZ: [
        [new Mesh(new BoxGeometry(0.1, 0.1, 0.1), matWhiteTransparent)]
      ]
    };
    const pickerScale = {
      X: [
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0.3, 0, 0], [0, 0, -Math.PI / 2]],
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [-0.3, 0, 0], [0, 0, Math.PI / 2]]
      ],
      Y: [
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0.3, 0]],
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, -0.3, 0], [0, 0, Math.PI]]
      ],
      Z: [
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, 0.3], [Math.PI / 2, 0, 0]],
        [new Mesh(new CylinderGeometry(0.2, 0, 0.6, 4), matInvisible), [0, 0, -0.3], [-Math.PI / 2, 0, 0]]
      ],
      XY: [
        [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0.15, 0]]
      ],
      YZ: [
        [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0, 0.15, 0.15], [0, Math.PI / 2, 0]]
      ],
      XZ: [
        [new Mesh(new BoxGeometry(0.2, 0.2, 0.01), matInvisible), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]]
      ],
      XYZ: [
        [new Mesh(new BoxGeometry(0.2, 0.2, 0.2), matInvisible), [0, 0, 0]]
      ]
    };
    const helperScale = {
      X: [
        [new Line(lineGeometry, matHelper), [-1e3, 0, 0], null, [1e6, 1, 1], "helper"]
      ],
      Y: [
        [new Line(lineGeometry, matHelper), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], "helper"]
      ],
      Z: [
        [new Line(lineGeometry, matHelper), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], "helper"]
      ]
    };
    function setupGizmo(gizmoMap) {
      const gizmo = new Object3D();
      for (const name2 in gizmoMap) {
        for (let i = gizmoMap[name2].length; i--; ) {
          const object = gizmoMap[name2][i][0].clone();
          const position2 = gizmoMap[name2][i][1];
          const rotation2 = gizmoMap[name2][i][2];
          const scale2 = gizmoMap[name2][i][3];
          const tag = gizmoMap[name2][i][4];
          object.name = name2;
          object.tag = tag;
          if (position2) {
            object.position.set(position2[0], position2[1], position2[2]);
          }
          if (rotation2) {
            object.rotation.set(rotation2[0], rotation2[1], rotation2[2]);
          }
          if (scale2) {
            object.scale.set(scale2[0], scale2[1], scale2[2]);
          }
          object.updateMatrix();
          const tempGeometry = object.geometry.clone();
          tempGeometry.applyMatrix4(object.matrix);
          object.geometry = tempGeometry;
          object.renderOrder = Infinity;
          object.position.set(0, 0, 0);
          object.rotation.set(0, 0, 0);
          object.scale.set(1, 1, 1);
          gizmo.add(object);
        }
      }
      return gizmo;
    }
    this.gizmo = {};
    this.picker = {};
    this.helper = {};
    this.add(this.gizmo["translate"] = setupGizmo(gizmoTranslate));
    this.add(this.gizmo["rotate"] = setupGizmo(gizmoRotate));
    this.add(this.gizmo["scale"] = setupGizmo(gizmoScale));
    this.add(this.picker["translate"] = setupGizmo(pickerTranslate));
    this.add(this.picker["rotate"] = setupGizmo(pickerRotate));
    this.add(this.picker["scale"] = setupGizmo(pickerScale));
    this.add(this.helper["translate"] = setupGizmo(helperTranslate));
    this.add(this.helper["rotate"] = setupGizmo(helperRotate));
    this.add(this.helper["scale"] = setupGizmo(helperScale));
    this.picker["translate"].visible = false;
    this.picker["rotate"].visible = false;
    this.picker["scale"].visible = false;
  }
  // updateMatrixWorld will update transformations and appearance of individual handles
  updateMatrixWorld(force) {
    const space = this.mode === "scale" ? "local" : this.space;
    const quaternion = space === "local" ? this.worldQuaternion : _identityQuaternion;
    this.gizmo["translate"].visible = this.mode === "translate";
    this.gizmo["rotate"].visible = this.mode === "rotate";
    this.gizmo["scale"].visible = this.mode === "scale";
    this.helper["translate"].visible = this.mode === "translate";
    this.helper["rotate"].visible = this.mode === "rotate";
    this.helper["scale"].visible = this.mode === "scale";
    let handles = [];
    handles = handles.concat(this.picker[this.mode].children);
    handles = handles.concat(this.gizmo[this.mode].children);
    handles = handles.concat(this.helper[this.mode].children);
    for (let i = 0; i < handles.length; i++) {
      const handle = handles[i];
      handle.visible = true;
      handle.rotation.set(0, 0, 0);
      handle.position.copy(this.worldPosition);
      let factor;
      if (this.camera.isOrthographicCamera) {
        factor = (this.camera.top - this.camera.bottom) / this.camera.zoom;
      } else {
        factor = this.worldPosition.distanceTo(this.cameraPosition) * Math.min(1.9 * Math.tan(Math.PI * this.camera.fov / 360) / this.camera.zoom, 7);
      }
      handle.scale.set(1, 1, 1).multiplyScalar(factor * this.size / 4);
      if (handle.tag === "helper") {
        handle.visible = false;
        if (handle.name === "AXIS") {
          handle.visible = !!this.axis;
          if (this.axis === "X") {
            _tempQuaternion.setFromEuler(_tempEuler.set(0, 0, 0));
            handle.quaternion.copy(quaternion).multiply(_tempQuaternion);
            if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) > 0.9) {
              handle.visible = false;
            }
          }
          if (this.axis === "Y") {
            _tempQuaternion.setFromEuler(_tempEuler.set(0, 0, Math.PI / 2));
            handle.quaternion.copy(quaternion).multiply(_tempQuaternion);
            if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) > 0.9) {
              handle.visible = false;
            }
          }
          if (this.axis === "Z") {
            _tempQuaternion.setFromEuler(_tempEuler.set(0, Math.PI / 2, 0));
            handle.quaternion.copy(quaternion).multiply(_tempQuaternion);
            if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) > 0.9) {
              handle.visible = false;
            }
          }
          if (this.axis === "XYZE") {
            _tempQuaternion.setFromEuler(_tempEuler.set(0, Math.PI / 2, 0));
            _alignVector.copy(this.rotationAxis);
            handle.quaternion.setFromRotationMatrix(_lookAtMatrix.lookAt(_zeroVector, _alignVector, _unitY));
            handle.quaternion.multiply(_tempQuaternion);
            handle.visible = this.dragging;
          }
          if (this.axis === "E") {
            handle.visible = false;
          }
        } else if (handle.name === "START") {
          handle.position.copy(this.worldPositionStart);
          handle.visible = this.dragging;
        } else if (handle.name === "END") {
          handle.position.copy(this.worldPosition);
          handle.visible = this.dragging;
        } else if (handle.name === "DELTA") {
          handle.position.copy(this.worldPositionStart);
          handle.quaternion.copy(this.worldQuaternionStart);
          _tempVector.set(1e-10, 1e-10, 1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1);
          _tempVector.applyQuaternion(this.worldQuaternionStart.clone().invert());
          handle.scale.copy(_tempVector);
          handle.visible = this.dragging;
        } else {
          handle.quaternion.copy(quaternion);
          if (this.dragging) {
            handle.position.copy(this.worldPositionStart);
          } else {
            handle.position.copy(this.worldPosition);
          }
          if (this.axis) {
            handle.visible = this.axis.search(handle.name) !== -1;
          }
        }
        continue;
      }
      handle.quaternion.copy(quaternion);
      if (this.mode === "translate" || this.mode === "scale") {
        const AXIS_HIDE_THRESHOLD = 0.99;
        const PLANE_HIDE_THRESHOLD = 0.2;
        if (handle.name === "X") {
          if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) {
            handle.scale.set(1e-10, 1e-10, 1e-10);
            handle.visible = false;
          }
        }
        if (handle.name === "Y") {
          if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) {
            handle.scale.set(1e-10, 1e-10, 1e-10);
            handle.visible = false;
          }
        }
        if (handle.name === "Z") {
          if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_THRESHOLD) {
            handle.scale.set(1e-10, 1e-10, 1e-10);
            handle.visible = false;
          }
        }
        if (handle.name === "XY") {
          if (Math.abs(_alignVector.copy(_unitZ).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) {
            handle.scale.set(1e-10, 1e-10, 1e-10);
            handle.visible = false;
          }
        }
        if (handle.name === "YZ") {
          if (Math.abs(_alignVector.copy(_unitX).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) {
            handle.scale.set(1e-10, 1e-10, 1e-10);
            handle.visible = false;
          }
        }
        if (handle.name === "XZ") {
          if (Math.abs(_alignVector.copy(_unitY).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_THRESHOLD) {
            handle.scale.set(1e-10, 1e-10, 1e-10);
            handle.visible = false;
          }
        }
      } else if (this.mode === "rotate") {
        _tempQuaternion2.copy(quaternion);
        _alignVector.copy(this.eye).applyQuaternion(_tempQuaternion.copy(quaternion).invert());
        if (handle.name.search("E") !== -1) {
          handle.quaternion.setFromRotationMatrix(_lookAtMatrix.lookAt(this.eye, _zeroVector, _unitY));
        }
        if (handle.name === "X") {
          _tempQuaternion.setFromAxisAngle(_unitX, Math.atan2(-_alignVector.y, _alignVector.z));
          _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion);
          handle.quaternion.copy(_tempQuaternion);
        }
        if (handle.name === "Y") {
          _tempQuaternion.setFromAxisAngle(_unitY, Math.atan2(_alignVector.x, _alignVector.z));
          _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion);
          handle.quaternion.copy(_tempQuaternion);
        }
        if (handle.name === "Z") {
          _tempQuaternion.setFromAxisAngle(_unitZ, Math.atan2(_alignVector.y, _alignVector.x));
          _tempQuaternion.multiplyQuaternions(_tempQuaternion2, _tempQuaternion);
          handle.quaternion.copy(_tempQuaternion);
        }
      }
      handle.visible = handle.visible && (handle.name.indexOf("X") === -1 || this.showX);
      handle.visible = handle.visible && (handle.name.indexOf("Y") === -1 || this.showY);
      handle.visible = handle.visible && (handle.name.indexOf("Z") === -1 || this.showZ);
      handle.visible = handle.visible && (handle.name.indexOf("E") === -1 || this.showX && this.showY && this.showZ);
      handle.material._color = handle.material._color || handle.material.color.clone();
      handle.material._opacity = handle.material._opacity || handle.material.opacity;
      handle.material.color.copy(handle.material._color);
      handle.material.opacity = handle.material._opacity;
      if (this.enabled && this.axis) {
        if (handle.name === this.axis) {
          handle.material.color.copy(this.materialLib.active.color);
          handle.material.opacity = 1;
        } else if (this.axis.split("").some(function(a2) {
          return handle.name === a2;
        })) {
          handle.material.color.copy(this.materialLib.active.color);
          handle.material.opacity = 1;
        }
      }
    }
    super.updateMatrixWorld(force);
  }
};
var TransformControlsPlane = class extends Mesh {
  constructor() {
    super(
      new PlaneGeometry(1e5, 1e5, 2, 2),
      new MeshBasicMaterial({ visible: false, wireframe: true, side: DoubleSide, transparent: true, opacity: 0.1, toneMapped: false })
    );
    this.isTransformControlsPlane = true;
    this.type = "TransformControlsPlane";
  }
  updateMatrixWorld(force) {
    let space = this.space;
    this.position.copy(this.worldPosition);
    if (this.mode === "scale") space = "local";
    _v1.copy(_unitX).applyQuaternion(space === "local" ? this.worldQuaternion : _identityQuaternion);
    _v22.copy(_unitY).applyQuaternion(space === "local" ? this.worldQuaternion : _identityQuaternion);
    _v3.copy(_unitZ).applyQuaternion(space === "local" ? this.worldQuaternion : _identityQuaternion);
    _alignVector.copy(_v22);
    switch (this.mode) {
      case "translate":
      case "scale":
        switch (this.axis) {
          case "X":
            _alignVector.copy(this.eye).cross(_v1);
            _dirVector.copy(_v1).cross(_alignVector);
            break;
          case "Y":
            _alignVector.copy(this.eye).cross(_v22);
            _dirVector.copy(_v22).cross(_alignVector);
            break;
          case "Z":
            _alignVector.copy(this.eye).cross(_v3);
            _dirVector.copy(_v3).cross(_alignVector);
            break;
          case "XY":
            _dirVector.copy(_v3);
            break;
          case "YZ":
            _dirVector.copy(_v1);
            break;
          case "XZ":
            _alignVector.copy(_v3);
            _dirVector.copy(_v22);
            break;
          case "XYZ":
          case "E":
            _dirVector.set(0, 0, 0);
            break;
        }
        break;
      case "rotate":
      default:
        _dirVector.set(0, 0, 0);
    }
    if (_dirVector.length() === 0) {
      this.quaternion.copy(this.cameraQuaternion);
    } else {
      _tempMatrix.lookAt(_tempVector.set(0, 0, 0), _dirVector, _alignVector);
      this.quaternion.setFromRotationMatrix(_tempMatrix);
    }
    super.updateMatrixWorld(force);
  }
};

// node_modules/three/examples/jsm/csm/CSMFrustum.js
var inverseProjectionMatrix = new Matrix4();
var CSMFrustum = class _CSMFrustum {
  /**
   * Constructs a new CSM frustum.
   *
   * @param {CSMFrustum~Data} [data] - The CSM data.
   */
  constructor(data2) {
    data2 = data2 || {};
    this.zNear = data2.webGL === true ? -1 : 0;
    this.vertices = {
      near: [
        new Vector3(),
        new Vector3(),
        new Vector3(),
        new Vector3()
      ],
      far: [
        new Vector3(),
        new Vector3(),
        new Vector3(),
        new Vector3()
      ]
    };
    if (data2.projectionMatrix !== void 0) {
      this.setFromProjectionMatrix(data2.projectionMatrix, data2.maxFar || 1e4);
    }
  }
  /**
   * Setups this CSM frustum from the given projection matrix and max far value.
   *
   * @param {Matrix4} projectionMatrix - The projection matrix, usually of the scene's camera.
   * @param {number} maxFar - The maximum far value.
   * @returns {Object} An object representing the vertices of the near and far plane in view space.
   */
  setFromProjectionMatrix(projectionMatrix, maxFar) {
    const zNear = this.zNear;
    const isOrthographic = projectionMatrix.elements[2 * 4 + 3] === 0;
    inverseProjectionMatrix.copy(projectionMatrix).invert();
    this.vertices.near[0].set(1, 1, zNear);
    this.vertices.near[1].set(1, -1, zNear);
    this.vertices.near[2].set(-1, -1, zNear);
    this.vertices.near[3].set(-1, 1, zNear);
    this.vertices.near.forEach(function(v) {
      v.applyMatrix4(inverseProjectionMatrix);
    });
    this.vertices.far[0].set(1, 1, 1);
    this.vertices.far[1].set(1, -1, 1);
    this.vertices.far[2].set(-1, -1, 1);
    this.vertices.far[3].set(-1, 1, 1);
    this.vertices.far.forEach(function(v) {
      v.applyMatrix4(inverseProjectionMatrix);
      const absZ = Math.abs(v.z);
      if (isOrthographic) {
        v.z *= Math.min(maxFar / absZ, 1);
      } else {
        v.multiplyScalar(Math.min(maxFar / absZ, 1));
      }
    });
    return this.vertices;
  }
  /**
   * Splits the CSM frustum by the given array. The new CSM frustum are pushed into the given
   * target array.
   *
   * @param {Array<number>} breaks - An array of numbers in the range `[0,1]` the defines how the
   * CSM frustum should be split up.
   * @param {Array<CSMFrustum>} target - The target array that holds the new CSM frustums.
   */
  split(breaks, target) {
    while (breaks.length > target.length) {
      target.push(new _CSMFrustum());
    }
    target.length = breaks.length;
    for (let i = 0; i < breaks.length; i++) {
      const cascade = target[i];
      if (i === 0) {
        for (let j2 = 0; j2 < 4; j2++) {
          cascade.vertices.near[j2].copy(this.vertices.near[j2]);
        }
      } else {
        for (let j2 = 0; j2 < 4; j2++) {
          cascade.vertices.near[j2].lerpVectors(this.vertices.near[j2], this.vertices.far[j2], breaks[i - 1]);
        }
      }
      if (i === breaks.length - 1) {
        for (let j2 = 0; j2 < 4; j2++) {
          cascade.vertices.far[j2].copy(this.vertices.far[j2]);
        }
      } else {
        for (let j2 = 0; j2 < 4; j2++) {
          cascade.vertices.far[j2].lerpVectors(this.vertices.near[j2], this.vertices.far[j2], breaks[i]);
        }
      }
    }
  }
  /**
   * Transforms the given target CSM frustum into the different coordinate system defined by the
   * given camera matrix.
   *
   * @param {Matrix4} cameraMatrix - The matrix that defines the new coordinate system.
   * @param {CSMFrustum} target - The CSM to convert.
   */
  toSpace(cameraMatrix, target) {
    for (let i = 0; i < 4; i++) {
      target.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(cameraMatrix);
      target.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(cameraMatrix);
    }
  }
};

// node_modules/three/examples/jsm/csm/CSMShader.js
var CSMShader = {
  lights_fragment_begin: (
    /* glsl */
    `
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );

vec3 geometryClearcoatNormal = vec3( 0.0 );

#ifdef USE_CLEARCOAT

	geometryClearcoatNormal = clearcoatNormal;

#endif

#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		// Iridescence F0 approximation
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif

IncidentLight directLight;

#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )

	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif

	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {

		pointLight = pointLights[ i ];

		getPointLightInfo( pointLight, geometryPosition, directLight );

		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;

		#endif

		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

	}
	#pragma unroll_loop_end

#endif

#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )

	SpotLight spotLight;
 	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;

	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif

	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {

		spotLight = spotLights[ i ];

		getSpotLightInfo( spotLight, geometryPosition, directLight );

  		// spot lights are ordered [shadows with maps, shadows without maps, maps without shadows, none]
		#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 ) && defined( USE_CSM ) && defined( CSM_CASCADES )

	DirectionalLight directionalLight;
	float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear);
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif

	#if defined( USE_SHADOWMAP ) && defined( CSM_FADE )
		vec2 cascade;
		float cascadeCenter;
		float closestEdge;
		float margin;
		float csmx;
		float csmy;

		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];
			getDirectionalLightInfo( directionalLight, directLight );

			#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
				// NOTE: Depth gets larger away from the camera.
				// cascade.x is closer, cascade.y is further
				cascade = CSM_cascades[ i ];
				cascadeCenter = ( cascade.x + cascade.y ) / 2.0;
				closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y;
				margin = 0.25 * pow( closestEdge, 2.0 );
				csmx = cascade.x - margin / 2.0;
				csmy = cascade.y + margin / 2.0;
				if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) {

					float dist = min( linearDepth - csmx, csmy - linearDepth );
					float ratio = clamp( dist / margin, 0.0, 1.0 );

					vec3 prevColor = directLight.color;
					directionalLightShadow = directionalLightShadows[ i ];
					directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;

					bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter;
					directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 );

					ReflectedLight prevLight = reflectedLight;
					RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

					bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter;
					float blendRatio = shouldBlend ? ratio : 1.0;

					reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio );
					reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio );
					reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio );
					reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio );

				}
			#endif

		}
		#pragma unroll_loop_end
	#elif defined (USE_SHADOWMAP)

		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];
			getDirectionalLightInfo( directionalLight, directLight );

			#if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )

				directionalLightShadow = directionalLightShadows[ i ];
				if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;

				if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

			#endif

		}
		#pragma unroll_loop_end

	#elif ( NUM_DIR_LIGHT_SHADOWS > 0 )
		// note: no loop here - all CSM lights are in fact one light only
		getDirectionalLightInfo( directionalLights[0], directLight );
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

	#endif

	#if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS)
		// compute the lights not casting shadows (if any)

		#pragma unroll_loop_start
		for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) {

			directionalLight = directionalLights[ i ];

			getDirectionalLightInfo( directionalLight, directLight );

			RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );

		}
		#pragma unroll_loop_end

	#endif

#endif


#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES )

	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
`
  ),
  lights_pars_begin: (
    /* glsl */
    `
#if defined( USE_CSM ) && defined( CSM_CASCADES )
uniform vec2 CSM_cascades[CSM_CASCADES];
uniform float cameraNear;
uniform float shadowFar;
#endif
	` + ShaderChunk.lights_pars_begin
  )
};

// node_modules/three/examples/jsm/csm/CSM.js
var _cameraToLightMatrix = new Matrix4();
var _lightSpaceFrustum = new CSMFrustum({ webGL: true });
var _center2 = new Vector3();
var _bbox = new Box3();
var _uniformArray = [];
var _logArray = [];
var _lightOrientationMatrix = new Matrix4();
var _lightOrientationMatrixInverse = new Matrix4();
var _up2 = new Vector3(0, 1, 0);
var CSM = class {
  /**
   * Constructs a new CSM instance.
   *
   * @param {CSM~Data} data - The CSM data.
   */
  constructor(data2) {
    this.camera = data2.camera;
    this.parent = data2.parent;
    this.cascades = data2.cascades || 3;
    this.maxFar = data2.maxFar || 1e5;
    this.mode = data2.mode || "practical";
    this.shadowMapSize = data2.shadowMapSize || 2048;
    this.shadowBias = data2.shadowBias || 1e-6;
    this.lightDirection = data2.lightDirection || new Vector3(1, -1, 1).normalize();
    this.lightIntensity = data2.lightIntensity || 3;
    this.lightNear = data2.lightNear || 1;
    this.lightFar = data2.lightFar || 2e3;
    this.lightMargin = data2.lightMargin || 200;
    this.customSplitsCallback = data2.customSplitsCallback;
    this.fade = false;
    this.mainFrustum = new CSMFrustum({ webGL: true });
    this.frustums = [];
    this.breaks = [];
    this.lights = [];
    this.shaders = /* @__PURE__ */ new Map();
    this._createLights();
    this.updateFrustums();
    this._injectInclude();
  }
  /**
   * Creates the directional lights of this CSM instance.
   *
   * @private
   */
  _createLights() {
    for (let i = 0; i < this.cascades; i++) {
      const light = new DirectionalLight(16777215, this.lightIntensity);
      light.castShadow = true;
      light.shadow.mapSize.width = this.shadowMapSize;
      light.shadow.mapSize.height = this.shadowMapSize;
      light.shadow.camera.near = this.lightNear;
      light.shadow.camera.far = this.lightFar;
      light.shadow.bias = this.shadowBias;
      this.parent.add(light);
      this.parent.add(light.target);
      this.lights.push(light);
    }
  }
  /**
   * Inits the cascades according to the scene's camera and breaks configuration.
   *
   * @private
   */
  _initCascades() {
    const camera = this.camera;
    camera.updateProjectionMatrix();
    this.mainFrustum.setFromProjectionMatrix(camera.projectionMatrix, this.maxFar);
    this.mainFrustum.split(this.breaks, this.frustums);
  }
  /**
   * Updates the shadow bounds of this CSM instance.
   *
   * @private
   */
  _updateShadowBounds() {
    const frustums = this.frustums;
    for (let i = 0; i < frustums.length; i++) {
      const light = this.lights[i];
      const shadowCam = light.shadow.camera;
      const frustum = this.frustums[i];
      const nearVerts = frustum.vertices.near;
      const farVerts = frustum.vertices.far;
      const point1 = farVerts[0];
      let point2;
      if (point1.distanceTo(farVerts[2]) > point1.distanceTo(nearVerts[2])) {
        point2 = farVerts[2];
      } else {
        point2 = nearVerts[2];
      }
      let squaredBBWidth = point1.distanceTo(point2);
      if (this.fade) {
        const camera = this.camera;
        const far = Math.max(camera.far, this.maxFar);
        const linearDepth = frustum.vertices.far[0].z / (far - camera.near);
        const margin = 0.25 * Math.pow(linearDepth, 2) * (far - camera.near);
        squaredBBWidth += margin;
      }
      shadowCam.left = -squaredBBWidth / 2;
      shadowCam.right = squaredBBWidth / 2;
      shadowCam.top = squaredBBWidth / 2;
      shadowCam.bottom = -squaredBBWidth / 2;
      shadowCam.updateProjectionMatrix();
    }
  }
  /**
   * Computes the breaks of this CSM instance based on the scene's camera, number of cascades
   * and the selected split mode.
   *
   * @private
   */
  _getBreaks() {
    const camera = this.camera;
    const far = Math.min(camera.far, this.maxFar);
    this.breaks.length = 0;
    switch (this.mode) {
      case "uniform":
        uniformSplit(this.cascades, camera.near, far, this.breaks);
        break;
      case "logarithmic":
        logarithmicSplit(this.cascades, camera.near, far, this.breaks);
        break;
      case "practical":
        practicalSplit(this.cascades, camera.near, far, 0.5, this.breaks);
        break;
      case "custom":
        if (this.customSplitsCallback === void 0) console.error("CSM: Custom split scheme callback not defined.");
        this.customSplitsCallback(this.cascades, camera.near, far, this.breaks);
        break;
    }
    function uniformSplit(amount, near, far2, target) {
      for (let i = 1; i < amount; i++) {
        target.push((near + (far2 - near) * i / amount) / far2);
      }
      target.push(1);
    }
    function logarithmicSplit(amount, near, far2, target) {
      for (let i = 1; i < amount; i++) {
        target.push(near * (far2 / near) ** (i / amount) / far2);
      }
      target.push(1);
    }
    function practicalSplit(amount, near, far2, lambda, target) {
      _uniformArray.length = 0;
      _logArray.length = 0;
      logarithmicSplit(amount, near, far2, _logArray);
      uniformSplit(amount, near, far2, _uniformArray);
      for (let i = 1; i < amount; i++) {
        target.push(MathUtils.lerp(_uniformArray[i - 1], _logArray[i - 1], lambda));
      }
      target.push(1);
    }
  }
  /**
   * Updates the CSM. This method must be called in your animation loop before
   * calling `renderer.render()`.
   */
  update() {
    const camera = this.camera;
    const frustums = this.frustums;
    _lightOrientationMatrix.lookAt(new Vector3(), this.lightDirection, _up2);
    _lightOrientationMatrixInverse.copy(_lightOrientationMatrix).invert();
    for (let i = 0; i < frustums.length; i++) {
      const light = this.lights[i];
      const shadowCam = light.shadow.camera;
      const texelWidth = (shadowCam.right - shadowCam.left) / this.shadowMapSize;
      const texelHeight = (shadowCam.top - shadowCam.bottom) / this.shadowMapSize;
      _cameraToLightMatrix.multiplyMatrices(_lightOrientationMatrixInverse, camera.matrixWorld);
      frustums[i].toSpace(_cameraToLightMatrix, _lightSpaceFrustum);
      const nearVerts = _lightSpaceFrustum.vertices.near;
      const farVerts = _lightSpaceFrustum.vertices.far;
      _bbox.makeEmpty();
      for (let j2 = 0; j2 < 4; j2++) {
        _bbox.expandByPoint(nearVerts[j2]);
        _bbox.expandByPoint(farVerts[j2]);
      }
      _bbox.getCenter(_center2);
      _center2.z = _bbox.max.z + this.lightMargin;
      _center2.x = Math.floor(_center2.x / texelWidth) * texelWidth;
      _center2.y = Math.floor(_center2.y / texelHeight) * texelHeight;
      _center2.applyMatrix4(_lightOrientationMatrix);
      light.position.copy(_center2);
      light.target.position.copy(_center2);
      light.target.position.x += this.lightDirection.x;
      light.target.position.y += this.lightDirection.y;
      light.target.position.z += this.lightDirection.z;
    }
  }
  /**
   * Injects the CSM shader enhancements into the built-in materials.
   *
   * @private
   */
  _injectInclude() {
    ShaderChunk.lights_fragment_begin = CSMShader.lights_fragment_begin;
    ShaderChunk.lights_pars_begin = CSMShader.lights_pars_begin;
  }
  /**
   * Applications must call this method for all materials that should be affected by CSM.
   *
   * @param {Material} material - The material to setup for CSM support.
   */
  setupMaterial(material) {
    material.defines = material.defines || {};
    material.defines.USE_CSM = 1;
    material.defines.CSM_CASCADES = this.cascades;
    if (this.fade) {
      material.defines.CSM_FADE = "";
    }
    const breaksVec2 = [];
    const scope = this;
    const shaders = this.shaders;
    material.onBeforeCompile = function(shader) {
      const far = Math.min(scope.camera.far, scope.maxFar);
      scope._getExtendedBreaks(breaksVec2);
      shader.uniforms.CSM_cascades = { value: breaksVec2 };
      shader.uniforms.cameraNear = { value: scope.camera.near };
      shader.uniforms.shadowFar = { value: far };
      shaders.set(material, shader);
    };
    shaders.set(material, null);
  }
  /**
   * Updates the CSM uniforms.
   *
   * @private
   */
  _updateUniforms() {
    const far = Math.min(this.camera.far, this.maxFar);
    const shaders = this.shaders;
    shaders.forEach(function(shader, material) {
      if (shader !== null) {
        const uniforms = shader.uniforms;
        this._getExtendedBreaks(uniforms.CSM_cascades.value);
        uniforms.cameraNear.value = this.camera.near;
        uniforms.shadowFar.value = far;
      }
      if (!this.fade && "CSM_FADE" in material.defines) {
        delete material.defines.CSM_FADE;
        material.needsUpdate = true;
      } else if (this.fade && !("CSM_FADE" in material.defines)) {
        material.defines.CSM_FADE = "";
        material.needsUpdate = true;
      }
    }, this);
  }
  /**
   * Computes the extended breaks for the CSM uniforms.
   *
   * @private
   * @param {Array<Vector2>} target - The target array that holds the extended breaks.
   */
  _getExtendedBreaks(target) {
    while (target.length < this.breaks.length) {
      target.push(new Vector2());
    }
    target.length = this.breaks.length;
    for (let i = 0; i < this.cascades; i++) {
      const amount = this.breaks[i];
      const prev = this.breaks[i - 1] || 0;
      target[i].x = prev;
      target[i].y = amount;
    }
  }
  /**
   * Applications must call this method every time they change camera or CSM settings.
   */
  updateFrustums() {
    this._getBreaks();
    this._initCascades();
    this._updateShadowBounds();
    this._updateUniforms();
  }
  /**
   * Applications must call this method when they remove the CSM usage from their scene.
   */
  remove() {
    for (let i = 0; i < this.lights.length; i++) {
      this.parent.remove(this.lights[i].target);
      this.parent.remove(this.lights[i]);
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    const shaders = this.shaders;
    shaders.forEach(function(shader, material) {
      delete material.onBeforeCompile;
      delete material.defines.USE_CSM;
      delete material.defines.CSM_CASCADES;
      delete material.defines.CSM_FADE;
      if (shader !== null) {
        delete shader.uniforms.CSM_cascades;
        delete shader.uniforms.cameraNear;
        delete shader.uniforms.shadowFar;
      }
      material.needsUpdate = true;
    });
    shaders.clear();
  }
};

// node_modules/three/examples/jsm/csm/CSMHelper.js
var CSMHelper = class extends Group {
  /**
   * Constructs a new CSM helper.
   *
   * @param {CSM|CSMShadowNode} csm - The CSM instance to visualize.
   */
  constructor(csm) {
    super();
    this.csm = csm;
    this.displayFrustum = true;
    this.displayPlanes = true;
    this.displayShadowBounds = true;
    const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
    const positions = new Float32Array(24);
    const frustumGeometry = new BufferGeometry();
    frustumGeometry.setIndex(new BufferAttribute(indices, 1));
    frustumGeometry.setAttribute("position", new BufferAttribute(positions, 3, false));
    const frustumLines = new LineSegments(frustumGeometry, new LineBasicMaterial());
    this.add(frustumLines);
    this.frustumLines = frustumLines;
    this.cascadeLines = [];
    this.cascadePlanes = [];
    this.shadowLines = [];
  }
  /**
   * This method must be called if one of the `display*` properties is changed at runtime.
   */
  updateVisibility() {
    const displayFrustum = this.displayFrustum;
    const displayPlanes = this.displayPlanes;
    const displayShadowBounds = this.displayShadowBounds;
    const frustumLines = this.frustumLines;
    const cascadeLines = this.cascadeLines;
    const cascadePlanes = this.cascadePlanes;
    const shadowLines = this.shadowLines;
    for (let i = 0, l2 = cascadeLines.length; i < l2; i++) {
      const cascadeLine = cascadeLines[i];
      const cascadePlane = cascadePlanes[i];
      const shadowLineGroup = shadowLines[i];
      cascadeLine.visible = displayFrustum;
      cascadePlane.visible = displayFrustum && displayPlanes;
      shadowLineGroup.visible = displayShadowBounds;
    }
    frustumLines.visible = displayFrustum;
  }
  /**
   * Updates the helper. This method should be called in the app's animation loop.
   */
  update() {
    const csm = this.csm;
    const camera = csm.camera;
    const cascades = csm.cascades;
    const mainFrustum = csm.mainFrustum;
    const frustums = csm.frustums;
    const lights = csm.lights;
    const frustumLines = this.frustumLines;
    const frustumLinePositions = frustumLines.geometry.getAttribute("position");
    const cascadeLines = this.cascadeLines;
    const cascadePlanes = this.cascadePlanes;
    const shadowLines = this.shadowLines;
    if (camera === null) return;
    this.position.copy(camera.position);
    this.quaternion.copy(camera.quaternion);
    this.scale.copy(camera.scale);
    this.updateMatrixWorld(true);
    while (cascadeLines.length > cascades) {
      this.remove(cascadeLines.pop());
      this.remove(cascadePlanes.pop());
      this.remove(shadowLines.pop());
    }
    while (cascadeLines.length < cascades) {
      const cascadeLine = new Box3Helper(new Box3(), 16777215);
      const planeMat = new MeshBasicMaterial({ transparent: true, opacity: 0.1, depthWrite: false, side: DoubleSide });
      const cascadePlane = new Mesh(new PlaneGeometry(), planeMat);
      const shadowLineGroup = new Group();
      const shadowLine = new Box3Helper(new Box3(), 16776960);
      shadowLineGroup.add(shadowLine);
      this.add(cascadeLine);
      this.add(cascadePlane);
      this.add(shadowLineGroup);
      cascadeLines.push(cascadeLine);
      cascadePlanes.push(cascadePlane);
      shadowLines.push(shadowLineGroup);
    }
    for (let i = 0; i < cascades; i++) {
      const frustum = frustums[i];
      const light = lights[i];
      const shadowCam = light.shadow.camera;
      const farVerts2 = frustum.vertices.far;
      const cascadeLine = cascadeLines[i];
      const cascadePlane = cascadePlanes[i];
      const shadowLineGroup = shadowLines[i];
      const shadowLine = shadowLineGroup.children[0];
      cascadeLine.box.min.copy(farVerts2[2]);
      cascadeLine.box.max.copy(farVerts2[0]);
      cascadeLine.box.max.z += 1e-4;
      cascadePlane.position.addVectors(farVerts2[0], farVerts2[2]);
      cascadePlane.position.multiplyScalar(0.5);
      cascadePlane.scale.subVectors(farVerts2[0], farVerts2[2]);
      cascadePlane.scale.z = 1e-4;
      this.remove(shadowLineGroup);
      shadowLineGroup.position.copy(shadowCam.position);
      shadowLineGroup.quaternion.copy(shadowCam.quaternion);
      shadowLineGroup.scale.copy(shadowCam.scale);
      shadowLineGroup.updateMatrixWorld(true);
      this.attach(shadowLineGroup);
      shadowLine.box.min.set(shadowCam.bottom, shadowCam.left, -shadowCam.far);
      shadowLine.box.max.set(shadowCam.top, shadowCam.right, -shadowCam.near);
    }
    const nearVerts = mainFrustum.vertices.near;
    const farVerts = mainFrustum.vertices.far;
    frustumLinePositions.setXYZ(0, farVerts[0].x, farVerts[0].y, farVerts[0].z);
    frustumLinePositions.setXYZ(1, farVerts[3].x, farVerts[3].y, farVerts[3].z);
    frustumLinePositions.setXYZ(2, farVerts[2].x, farVerts[2].y, farVerts[2].z);
    frustumLinePositions.setXYZ(3, farVerts[1].x, farVerts[1].y, farVerts[1].z);
    frustumLinePositions.setXYZ(4, nearVerts[0].x, nearVerts[0].y, nearVerts[0].z);
    frustumLinePositions.setXYZ(5, nearVerts[3].x, nearVerts[3].y, nearVerts[3].z);
    frustumLinePositions.setXYZ(6, nearVerts[2].x, nearVerts[2].y, nearVerts[2].z);
    frustumLinePositions.setXYZ(7, nearVerts[1].x, nearVerts[1].y, nearVerts[1].z);
    frustumLinePositions.needsUpdate = true;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    const frustumLines = this.frustumLines;
    const cascadeLines = this.cascadeLines;
    const cascadePlanes = this.cascadePlanes;
    const shadowLines = this.shadowLines;
    frustumLines.geometry.dispose();
    frustumLines.material.dispose();
    const cascades = this.csm.cascades;
    for (let i = 0; i < cascades; i++) {
      const cascadeLine = cascadeLines[i];
      const cascadePlane = cascadePlanes[i];
      const shadowLineGroup = shadowLines[i];
      const shadowLine = shadowLineGroup.children[0];
      cascadeLine.dispose();
      cascadePlane.geometry.dispose();
      cascadePlane.material.dispose();
      shadowLine.dispose();
    }
  }
};

// node_modules/three/examples/jsm/curves/CurveExtras.js
var CurveExtras_exports = {};
__export(CurveExtras_exports, {
  CinquefoilKnot: () => CinquefoilKnot,
  DecoratedTorusKnot4a: () => DecoratedTorusKnot4a,
  DecoratedTorusKnot4b: () => DecoratedTorusKnot4b,
  DecoratedTorusKnot5a: () => DecoratedTorusKnot5a,
  DecoratedTorusKnot5c: () => DecoratedTorusKnot5c,
  FigureEightPolynomialKnot: () => FigureEightPolynomialKnot,
  GrannyKnot: () => GrannyKnot,
  HeartCurve: () => HeartCurve,
  HelixCurve: () => HelixCurve,
  KnotCurve: () => KnotCurve,
  TorusKnot: () => TorusKnot,
  TrefoilKnot: () => TrefoilKnot,
  TrefoilPolynomialKnot: () => TrefoilPolynomialKnot,
  VivianiCurve: () => VivianiCurve
});
var GrannyKnot = class extends Curve {
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    t3 = 2 * Math.PI * t3;
    const x2 = -0.22 * Math.cos(t3) - 1.28 * Math.sin(t3) - 0.44 * Math.cos(3 * t3) - 0.78 * Math.sin(3 * t3);
    const y = -0.1 * Math.cos(2 * t3) - 0.27 * Math.sin(2 * t3) + 0.38 * Math.cos(4 * t3) + 0.46 * Math.sin(4 * t3);
    const z = 0.7 * Math.cos(3 * t3) - 0.4 * Math.sin(3 * t3);
    return point.set(x2, y, z).multiplyScalar(20);
  }
};
var HeartCurve = class extends Curve {
  /**
   * Constructs a new heart curve.
   *
   * @param {number} [scale=5] - The curve's scale.
   */
  constructor(scale2 = 5) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    t3 *= 2 * Math.PI;
    const x2 = 16 * Math.pow(Math.sin(t3), 3);
    const y = 13 * Math.cos(t3) - 5 * Math.cos(2 * t3) - 2 * Math.cos(3 * t3) - Math.cos(4 * t3);
    const z = 0;
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
var VivianiCurve = class extends Curve {
  /**
   * Constructs a new Viviani curve.
   *
   * @param {number} [scale=70] - The curve's scale.
   */
  constructor(scale2 = 70) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    t3 = t3 * 4 * Math.PI;
    const a2 = this.scale / 2;
    const x2 = a2 * (1 + Math.cos(t3));
    const y = a2 * Math.sin(t3);
    const z = 2 * a2 * Math.sin(t3 / 2);
    return point.set(x2, y, z);
  }
};
var KnotCurve = class extends Curve {
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    t3 *= 2 * Math.PI;
    const R4 = 10;
    const s = 50;
    const x2 = s * Math.sin(t3);
    const y = Math.cos(t3) * (R4 + s * Math.cos(t3));
    const z = Math.sin(t3) * (R4 + s * Math.cos(t3));
    return point.set(x2, y, z);
  }
};
var HelixCurve = class extends Curve {
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const a2 = 30;
    const b3 = 150;
    const t22 = 2 * Math.PI * t3 * b3 / 30;
    const x2 = Math.cos(t22) * a2;
    const y = Math.sin(t22) * a2;
    const z = b3 * t3;
    return point.set(x2, y, z);
  }
};
var TrefoilKnot = class extends Curve {
  /**
   * Constructs a new Trefoil Knot.
   *
   * @param {number} [scale=10] - The curve's scale.
   */
  constructor(scale2 = 10) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    t3 *= Math.PI * 2;
    const x2 = (2 + Math.cos(3 * t3)) * Math.cos(2 * t3);
    const y = (2 + Math.cos(3 * t3)) * Math.sin(2 * t3);
    const z = Math.sin(3 * t3);
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
var TorusKnot = class extends Curve {
  /**
   * Constructs a new torus knot.
   *
   * @param {number} [scale=10] - The curve's scale.
   */
  constructor(scale2 = 10) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const p = 3;
    const q2 = 4;
    t3 *= Math.PI * 2;
    const x2 = (2 + Math.cos(q2 * t3)) * Math.cos(p * t3);
    const y = (2 + Math.cos(q2 * t3)) * Math.sin(p * t3);
    const z = Math.sin(q2 * t3);
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
var CinquefoilKnot = class extends Curve {
  /**
   * Constructs a new Cinquefoil Knot.
   *
   * @param {number} [scale=10] - The curve's scale.
   */
  constructor(scale2 = 10) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const p = 2;
    const q2 = 5;
    t3 *= Math.PI * 2;
    const x2 = (2 + Math.cos(q2 * t3)) * Math.cos(p * t3);
    const y = (2 + Math.cos(q2 * t3)) * Math.sin(p * t3);
    const z = Math.sin(q2 * t3);
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
var TrefoilPolynomialKnot = class extends Curve {
  /**
   * Constructs a new Trefoil Polynomial Knot.
   *
   * @param {number} [scale=10] - The curve's scale.
   */
  constructor(scale2 = 10) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    t3 = t3 * 4 - 2;
    const x2 = Math.pow(t3, 3) - 3 * t3;
    const y = Math.pow(t3, 4) - 4 * t3 * t3;
    const z = 1 / 5 * Math.pow(t3, 5) - 2 * t3;
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
function scaleTo(x2, y, t3) {
  const r = y - x2;
  return t3 * r + x2;
}
var FigureEightPolynomialKnot = class extends Curve {
  /**
   * Constructs a new Figure Eight Polynomial Knot.
   *
   * @param {number} [scale=1] - The curve's scale.
   */
  constructor(scale2 = 1) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    t3 = scaleTo(-4, 4, t3);
    const x2 = 2 / 5 * t3 * (t3 * t3 - 7) * (t3 * t3 - 10);
    const y = Math.pow(t3, 4) - 13 * t3 * t3;
    const z = 1 / 10 * t3 * (t3 * t3 - 4) * (t3 * t3 - 9) * (t3 * t3 - 12);
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
var DecoratedTorusKnot4a = class extends Curve {
  /**
   * Constructs a new Decorated Torus Knot 4a.
   *
   * @param {number} [scale=1] - The curve's scale.
   */
  constructor(scale2 = 40) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    t3 *= Math.PI * 2;
    const x2 = Math.cos(2 * t3) * (1 + 0.6 * (Math.cos(5 * t3) + 0.75 * Math.cos(10 * t3)));
    const y = Math.sin(2 * t3) * (1 + 0.6 * (Math.cos(5 * t3) + 0.75 * Math.cos(10 * t3)));
    const z = 0.35 * Math.sin(5 * t3);
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
var DecoratedTorusKnot4b = class extends Curve {
  /**
   * Constructs a new Decorated Torus Knot 4b.
   *
   * @param {number} [scale=1] - The curve's scale.
   */
  constructor(scale2 = 40) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const fi = t3 * Math.PI * 2;
    const x2 = Math.cos(2 * fi) * (1 + 0.45 * Math.cos(3 * fi) + 0.4 * Math.cos(9 * fi));
    const y = Math.sin(2 * fi) * (1 + 0.45 * Math.cos(3 * fi) + 0.4 * Math.cos(9 * fi));
    const z = 0.2 * Math.sin(9 * fi);
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
var DecoratedTorusKnot5a = class extends Curve {
  /**
   * Constructs a new Decorated Torus Knot 5a.
   *
   * @param {number} [scale=1] - The curve's scale.
   */
  constructor(scale2 = 40) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const fi = t3 * Math.PI * 2;
    const x2 = Math.cos(3 * fi) * (1 + 0.3 * Math.cos(5 * fi) + 0.5 * Math.cos(10 * fi));
    const y = Math.sin(3 * fi) * (1 + 0.3 * Math.cos(5 * fi) + 0.5 * Math.cos(10 * fi));
    const z = 0.2 * Math.sin(20 * fi);
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};
var DecoratedTorusKnot5c = class extends Curve {
  /**
   * Constructs a new Decorated Torus Knot 5c.
   *
   * @param {number} [scale=1] - The curve's scale.
   */
  constructor(scale2 = 40) {
    super();
    this.scale = scale2;
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const fi = t3 * Math.PI * 2;
    const x2 = Math.cos(4 * fi) * (1 + 0.5 * (Math.cos(5 * fi) + 0.4 * Math.cos(20 * fi)));
    const y = Math.sin(4 * fi) * (1 + 0.5 * (Math.cos(5 * fi) + 0.4 * Math.cos(20 * fi)));
    const z = 0.35 * Math.sin(15 * fi);
    return point.set(x2, y, z).multiplyScalar(this.scale);
  }
};

// node_modules/three/examples/jsm/curves/NURBSUtils.js
var NURBSUtils_exports = {};
__export(NURBSUtils_exports, {
  calcBSplineDerivatives: () => calcBSplineDerivatives,
  calcBSplinePoint: () => calcBSplinePoint,
  calcBasisFunctionDerivatives: () => calcBasisFunctionDerivatives,
  calcBasisFunctions: () => calcBasisFunctions,
  calcKoverI: () => calcKoverI,
  calcNURBSDerivatives: () => calcNURBSDerivatives,
  calcRationalCurveDerivatives: () => calcRationalCurveDerivatives,
  calcSurfacePoint: () => calcSurfacePoint,
  calcVolumePoint: () => calcVolumePoint,
  findSpan: () => findSpan
});
function findSpan(p, u2, U) {
  const n2 = U.length - p - 1;
  if (u2 >= U[n2]) {
    return n2 - 1;
  }
  if (u2 <= U[p]) {
    return p;
  }
  let low = p;
  let high = n2;
  let mid = Math.floor((low + high) / 2);
  while (u2 < U[mid] || u2 >= U[mid + 1]) {
    if (u2 < U[mid]) {
      high = mid;
    } else {
      low = mid;
    }
    mid = Math.floor((low + high) / 2);
  }
  return mid;
}
function calcBasisFunctions(span, u2, p, U) {
  const N = [];
  const left = [];
  const right = [];
  N[0] = 1;
  for (let j2 = 1; j2 <= p; ++j2) {
    left[j2] = u2 - U[span + 1 - j2];
    right[j2] = U[span + j2] - u2;
    let saved = 0;
    for (let r = 0; r < j2; ++r) {
      const rv = right[r + 1];
      const lv = left[j2 - r];
      const temp = N[r] / (rv + lv);
      N[r] = saved + rv * temp;
      saved = lv * temp;
    }
    N[j2] = saved;
  }
  return N;
}
function calcBSplinePoint(p, U, P, u2) {
  const span = findSpan(p, u2, U);
  const N = calcBasisFunctions(span, u2, p, U);
  const C3 = new Vector4(0, 0, 0, 0);
  for (let j2 = 0; j2 <= p; ++j2) {
    const point = P[span - p + j2];
    const Nj = N[j2];
    const wNj = point.w * Nj;
    C3.x += point.x * wNj;
    C3.y += point.y * wNj;
    C3.z += point.z * wNj;
    C3.w += point.w * Nj;
  }
  return C3;
}
function calcBasisFunctionDerivatives(span, u2, p, n2, U) {
  const zeroArr = [];
  for (let i = 0; i <= p; ++i)
    zeroArr[i] = 0;
  const ders = [];
  for (let i = 0; i <= n2; ++i)
    ders[i] = zeroArr.slice(0);
  const ndu = [];
  for (let i = 0; i <= p; ++i)
    ndu[i] = zeroArr.slice(0);
  ndu[0][0] = 1;
  const left = zeroArr.slice(0);
  const right = zeroArr.slice(0);
  for (let j2 = 1; j2 <= p; ++j2) {
    left[j2] = u2 - U[span + 1 - j2];
    right[j2] = U[span + j2] - u2;
    let saved = 0;
    for (let r2 = 0; r2 < j2; ++r2) {
      const rv = right[r2 + 1];
      const lv = left[j2 - r2];
      ndu[j2][r2] = rv + lv;
      const temp = ndu[r2][j2 - 1] / ndu[j2][r2];
      ndu[r2][j2] = saved + rv * temp;
      saved = lv * temp;
    }
    ndu[j2][j2] = saved;
  }
  for (let j2 = 0; j2 <= p; ++j2) {
    ders[0][j2] = ndu[j2][p];
  }
  for (let r2 = 0; r2 <= p; ++r2) {
    let s1 = 0;
    let s2 = 1;
    const a2 = [];
    for (let i = 0; i <= p; ++i) {
      a2[i] = zeroArr.slice(0);
    }
    a2[0][0] = 1;
    for (let k2 = 1; k2 <= n2; ++k2) {
      let d = 0;
      const rk = r2 - k2;
      const pk = p - k2;
      if (r2 >= k2) {
        a2[s2][0] = a2[s1][0] / ndu[pk + 1][rk];
        d = a2[s2][0] * ndu[rk][pk];
      }
      const j1 = rk >= -1 ? 1 : -rk;
      const j2 = r2 - 1 <= pk ? k2 - 1 : p - r2;
      for (let j4 = j1; j4 <= j2; ++j4) {
        a2[s2][j4] = (a2[s1][j4] - a2[s1][j4 - 1]) / ndu[pk + 1][rk + j4];
        d += a2[s2][j4] * ndu[rk + j4][pk];
      }
      if (r2 <= pk) {
        a2[s2][k2] = -a2[s1][k2 - 1] / ndu[pk + 1][r2];
        d += a2[s2][k2] * ndu[r2][pk];
      }
      ders[k2][r2] = d;
      const j3 = s1;
      s1 = s2;
      s2 = j3;
    }
  }
  let r = p;
  for (let k2 = 1; k2 <= n2; ++k2) {
    for (let j2 = 0; j2 <= p; ++j2) {
      ders[k2][j2] *= r;
    }
    r *= p - k2;
  }
  return ders;
}
function calcBSplineDerivatives(p, U, P, u2, nd) {
  const du = nd < p ? nd : p;
  const CK = [];
  const span = findSpan(p, u2, U);
  const nders = calcBasisFunctionDerivatives(span, u2, p, du, U);
  const Pw = [];
  for (let i = 0; i < P.length; ++i) {
    const point = P[i].clone();
    const w = point.w;
    point.x *= w;
    point.y *= w;
    point.z *= w;
    Pw[i] = point;
  }
  for (let k2 = 0; k2 <= du; ++k2) {
    const point = Pw[span - p].clone().multiplyScalar(nders[k2][0]);
    for (let j2 = 1; j2 <= p; ++j2) {
      point.add(Pw[span - p + j2].clone().multiplyScalar(nders[k2][j2]));
    }
    CK[k2] = point;
  }
  for (let k2 = du + 1; k2 <= nd + 1; ++k2) {
    CK[k2] = new Vector4(0, 0, 0);
  }
  return CK;
}
function calcKoverI(k2, i) {
  let nom = 1;
  for (let j2 = 2; j2 <= k2; ++j2) {
    nom *= j2;
  }
  let denom = 1;
  for (let j2 = 2; j2 <= i; ++j2) {
    denom *= j2;
  }
  for (let j2 = 2; j2 <= k2 - i; ++j2) {
    denom *= j2;
  }
  return nom / denom;
}
function calcRationalCurveDerivatives(Pders) {
  const nd = Pders.length;
  const Aders = [];
  const wders = [];
  for (let i = 0; i < nd; ++i) {
    const point = Pders[i];
    Aders[i] = new Vector3(point.x, point.y, point.z);
    wders[i] = point.w;
  }
  const CK = [];
  for (let k2 = 0; k2 < nd; ++k2) {
    const v = Aders[k2].clone();
    for (let i = 1; i <= k2; ++i) {
      v.sub(CK[k2 - i].clone().multiplyScalar(calcKoverI(k2, i) * wders[i]));
    }
    CK[k2] = v.divideScalar(wders[0]);
  }
  return CK;
}
function calcNURBSDerivatives(p, U, P, u2, nd) {
  const Pders = calcBSplineDerivatives(p, U, P, u2, nd);
  return calcRationalCurveDerivatives(Pders);
}
function calcSurfacePoint(p, q2, U, V, P, u2, v, target) {
  const uspan = findSpan(p, u2, U);
  const vspan = findSpan(q2, v, V);
  const Nu = calcBasisFunctions(uspan, u2, p, U);
  const Nv = calcBasisFunctions(vspan, v, q2, V);
  const temp = [];
  for (let l2 = 0; l2 <= q2; ++l2) {
    temp[l2] = new Vector4(0, 0, 0, 0);
    for (let k2 = 0; k2 <= p; ++k2) {
      const point = P[uspan - p + k2][vspan - q2 + l2].clone();
      const w = point.w;
      point.x *= w;
      point.y *= w;
      point.z *= w;
      temp[l2].add(point.multiplyScalar(Nu[k2]));
    }
  }
  const Sw = new Vector4(0, 0, 0, 0);
  for (let l2 = 0; l2 <= q2; ++l2) {
    Sw.add(temp[l2].multiplyScalar(Nv[l2]));
  }
  Sw.divideScalar(Sw.w);
  target.set(Sw.x, Sw.y, Sw.z);
}
function calcVolumePoint(p, q2, r, U, V, W, P, u2, v, w, target) {
  const uspan = findSpan(p, u2, U);
  const vspan = findSpan(q2, v, V);
  const wspan = findSpan(r, w, W);
  const Nu = calcBasisFunctions(uspan, u2, p, U);
  const Nv = calcBasisFunctions(vspan, v, q2, V);
  const Nw = calcBasisFunctions(wspan, w, r, W);
  const temp = [];
  for (let m = 0; m <= r; ++m) {
    temp[m] = [];
    for (let l2 = 0; l2 <= q2; ++l2) {
      temp[m][l2] = new Vector4(0, 0, 0, 0);
      for (let k2 = 0; k2 <= p; ++k2) {
        const point = P[uspan - p + k2][vspan - q2 + l2][wspan - r + m].clone();
        const w2 = point.w;
        point.x *= w2;
        point.y *= w2;
        point.z *= w2;
        temp[m][l2].add(point.multiplyScalar(Nu[k2]));
      }
    }
  }
  const Sw = new Vector4(0, 0, 0, 0);
  for (let m = 0; m <= r; ++m) {
    for (let l2 = 0; l2 <= q2; ++l2) {
      Sw.add(temp[m][l2].multiplyScalar(Nw[m]).multiplyScalar(Nv[l2]));
    }
  }
  Sw.divideScalar(Sw.w);
  target.set(Sw.x, Sw.y, Sw.z);
}

// node_modules/three/examples/jsm/curves/NURBSCurve.js
var NURBSCurve = class extends Curve {
  /**
   * Constructs a new NURBS curve.
   *
   * @param {number} degree - The NURBS degree.
   * @param {Array<number>} knots - The knots as a flat array of numbers.
   * @param {Array<Vector2|Vector3|Vector4>} controlPoints - An array holding control points.
   * @param {number} [startKnot] - Index of the start knot into the `knots` array.
   * @param {number} [endKnot] - Index of the end knot into the `knots` array.
   */
  constructor(degree, knots, controlPoints, startKnot, endKnot) {
    super();
    const knotsLength = knots ? knots.length - 1 : 0;
    const pointsLength = controlPoints ? controlPoints.length : 0;
    this.degree = degree;
    this.knots = knots;
    this.controlPoints = [];
    this.startKnot = startKnot || 0;
    this.endKnot = endKnot || knotsLength;
    for (let i = 0; i < pointsLength; ++i) {
      const point = controlPoints[i];
      this.controlPoints[i] = new Vector4(point.x, point.y, point.z, point.w);
    }
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor.
   *
   * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The position on the curve.
   */
  getPoint(t3, optionalTarget = new Vector3()) {
    const point = optionalTarget;
    const u2 = this.knots[this.startKnot] + t3 * (this.knots[this.endKnot] - this.knots[this.startKnot]);
    const hpoint = calcBSplinePoint(this.degree, this.knots, this.controlPoints, u2);
    if (hpoint.w !== 1) {
      hpoint.divideScalar(hpoint.w);
    }
    return point.set(hpoint.x, hpoint.y, hpoint.z);
  }
  /**
   * Returns a unit vector tangent for the given interpolation factor.
   *
   * @param {number} t - The interpolation factor.
   * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
   * @return {Vector3} The tangent vector.
   */
  getTangent(t3, optionalTarget = new Vector3()) {
    const tangent = optionalTarget;
    const u2 = this.knots[0] + t3 * (this.knots[this.knots.length - 1] - this.knots[0]);
    const ders = calcNURBSDerivatives(this.degree, this.knots, this.controlPoints, u2, 1);
    tangent.copy(ders[1]).normalize();
    return tangent;
  }
  toJSON() {
    const data2 = super.toJSON();
    data2.degree = this.degree;
    data2.knots = [...this.knots];
    data2.controlPoints = this.controlPoints.map((p) => p.toArray());
    data2.startKnot = this.startKnot;
    data2.endKnot = this.endKnot;
    return data2;
  }
  fromJSON(json) {
    super.fromJSON(json);
    this.degree = json.degree;
    this.knots = [...json.knots];
    this.controlPoints = json.controlPoints.map((p) => new Vector4(p[0], p[1], p[2], p[3]));
    this.startKnot = json.startKnot;
    this.endKnot = json.endKnot;
    return this;
  }
};

// node_modules/three/examples/jsm/curves/NURBSSurface.js
var NURBSSurface = class {
  /**
   * Constructs a new NURBS surface.
   *
   * @param {number} degree1 - The first NURBS degree.
   * @param {number} degree2 - The second NURBS degree.
   * @param {Array<number>} knots1 - The first knots as a flat array of numbers.
   * @param {Array<number>} knots2 - The second knots as a flat array of numbers.
   * @param {Array<Array<Vector2|Vector3|Vector4>>} controlPoints - An array^2 holding control points.
   */
  constructor(degree1, degree2, knots1, knots2, controlPoints) {
    this.degree1 = degree1;
    this.degree2 = degree2;
    this.knots1 = knots1;
    this.knots2 = knots2;
    this.controlPoints = [];
    const len1 = knots1.length - degree1 - 1;
    const len2 = knots2.length - degree2 - 1;
    for (let i = 0; i < len1; ++i) {
      this.controlPoints[i] = [];
      for (let j2 = 0; j2 < len2; ++j2) {
        const point = controlPoints[i][j2];
        this.controlPoints[i][j2] = new Vector4(point.x, point.y, point.z, point.w);
      }
    }
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor. This vector lies on the NURBS surface.
   *
   * @param {number} t1 - The first interpolation factor representing the `u` position on the surface. Must be in the range `[0,1]`.
   * @param {number} t2 - The second interpolation factor representing the `v` position on the surface. Must be in the range `[0,1]`.
   * @param {Vector3} target - The target vector the result is written to.
   */
  getPoint(t1, t22, target) {
    const u2 = this.knots1[0] + t1 * (this.knots1[this.knots1.length - 1] - this.knots1[0]);
    const v = this.knots2[0] + t22 * (this.knots2[this.knots2.length - 1] - this.knots2[0]);
    calcSurfacePoint(this.degree1, this.degree2, this.knots1, this.knots2, this.controlPoints, u2, v, target);
  }
};

// node_modules/three/examples/jsm/curves/NURBSVolume.js
var NURBSVolume = class {
  /**
   * Constructs a new NURBS surface.
   *
   * @param {number} degree1 - The first NURBS degree.
   * @param {number} degree2 - The second NURBS degree.
   * @param {number} degree3 - The third NURBS degree.
   * @param {Array<number>} knots1 - The first knots as a flat array of numbers.
   * @param {Array<number>} knots2 - The second knots as a flat array of numbers.
   * @param {Array<number>} knots3 - The third knots as a flat array of numbers.
   * @param {Array<Array<Array<Vector2|Vector3|Vector4>>>} controlPoints - An array^3 holding control points.
   */
  constructor(degree1, degree2, degree3, knots1, knots2, knots3, controlPoints) {
    this.degree1 = degree1;
    this.degree2 = degree2;
    this.degree3 = degree3;
    this.knots1 = knots1;
    this.knots2 = knots2;
    this.knots3 = knots3;
    this.controlPoints = [];
    const len1 = knots1.length - degree1 - 1;
    const len2 = knots2.length - degree2 - 1;
    const len3 = knots3.length - degree3 - 1;
    for (let i = 0; i < len1; ++i) {
      this.controlPoints[i] = [];
      for (let j2 = 0; j2 < len2; ++j2) {
        this.controlPoints[i][j2] = [];
        for (let k2 = 0; k2 < len3; ++k2) {
          const point = controlPoints[i][j2][k2];
          this.controlPoints[i][j2][k2] = new Vector4(point.x, point.y, point.z, point.w);
        }
      }
    }
  }
  /**
   * This method returns a vector in 3D space for the given interpolation factor. This vector lies within the NURBS volume.
   *
   * @param {number} t1 - The first interpolation factor representing the `u` position within the volume. Must be in the range `[0,1]`.
   * @param {number} t2 - The second interpolation factor representing the `v` position within the volume. Must be in the range `[0,1]`.
   * @param {number} t3 - The third interpolation factor representing the `w` position within the volume. Must be in the range `[0,1]`.
   * @param {Vector3} target - The target vector the result is written to.
   */
  getPoint(t1, t22, t3, target) {
    const u2 = this.knots1[0] + t1 * (this.knots1[this.knots1.length - 1] - this.knots1[0]);
    const v = this.knots2[0] + t22 * (this.knots2[this.knots2.length - 1] - this.knots2[0]);
    const w = this.knots3[0] + t3 * (this.knots3[this.knots3.length - 1] - this.knots3[0]);
    calcVolumePoint(this.degree1, this.degree2, this.degree3, this.knots1, this.knots2, this.knots3, this.controlPoints, u2, v, w, target);
  }
};

// node_modules/three/examples/jsm/postprocessing/Pass.js
var Pass = class {
  /**
   * Constructs a new pass.
   */
  constructor() {
    this.isPass = true;
    this.enabled = true;
    this.needsSwap = true;
    this.clear = false;
    this.renderToScreen = false;
  }
  /**
   * Sets the size of the pass.
   *
   * @abstract
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize() {
  }
  /**
   * This method holds the render logic of a pass. It must be implemented in all derived classes.
   *
   * @abstract
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render() {
    console.error("THREE.Pass: .render() must be implemented in derived pass.");
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   *
   * @abstract
   */
  dispose() {
  }
};
var _camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
var FullscreenTriangleGeometry = class extends BufferGeometry {
  constructor() {
    super();
    this.setAttribute("position", new Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3));
    this.setAttribute("uv", new Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2));
  }
};
var _geometry = new FullscreenTriangleGeometry();
var FullScreenQuad = class {
  /**
   * Constructs a new full screen quad.
   *
   * @param {?Material} material - The material to render te full screen quad with.
   */
  constructor(material) {
    this._mesh = new Mesh(_geometry, material);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the instance is no longer used in your app.
   */
  dispose() {
    this._mesh.geometry.dispose();
  }
  /**
   * Renders the full screen quad.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   */
  render(renderer2) {
    renderer2.render(this._mesh, _camera);
  }
  /**
   * The quad's material.
   *
   * @type {?Material}
   */
  get material() {
    return this._mesh.material;
  }
  set material(value2) {
    this._mesh.material = value2;
  }
};

// node_modules/three/examples/jsm/effects/AnaglyphEffect.js
var AnaglyphEffect = class {
  /**
   * Constructs a new anaglyph effect.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {number} width - The width of the effect in physical pixels.
   * @param {number} height - The height of the effect in physical pixels.
   */
  constructor(renderer2, width2 = 512, height2 = 512) {
    this.colorMatrixLeft = new Matrix3().fromArray([
      0.4561,
      -0.0400822,
      -0.0152161,
      0.500484,
      -0.0378246,
      -0.0205971,
      0.176381,
      -0.0157589,
      -546856e-8
    ]);
    this.colorMatrixRight = new Matrix3().fromArray([
      -0.0434706,
      0.378476,
      -0.0721527,
      -0.0879388,
      0.73364,
      -0.112961,
      -155529e-8,
      -0.0184503,
      1.2264
    ]);
    const _stereo = new StereoCamera();
    const _params = { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat };
    const _renderTargetL = new WebGLRenderTarget(width2, height2, _params);
    const _renderTargetR = new WebGLRenderTarget(width2, height2, _params);
    const _material = new ShaderMaterial({
      uniforms: {
        "mapLeft": { value: _renderTargetL.texture },
        "mapRight": { value: _renderTargetR.texture },
        "colorMatrixLeft": { value: this.colorMatrixLeft },
        "colorMatrixRight": { value: this.colorMatrixRight }
      },
      vertexShader: [
        "varying vec2 vUv;",
        "void main() {",
        "	vUv = vec2( uv.x, uv.y );",
        "	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
        "}"
      ].join("\n"),
      fragmentShader: [
        "uniform sampler2D mapLeft;",
        "uniform sampler2D mapRight;",
        "varying vec2 vUv;",
        "uniform mat3 colorMatrixLeft;",
        "uniform mat3 colorMatrixRight;",
        "void main() {",
        "	vec2 uv = vUv;",
        "	vec4 colorL = texture2D( mapLeft, uv );",
        "	vec4 colorR = texture2D( mapRight, uv );",
        "	vec3 color = clamp(",
        "			colorMatrixLeft * colorL.rgb +",
        "			colorMatrixRight * colorR.rgb, 0., 1. );",
        "	gl_FragColor = vec4(",
        "			color.r, color.g, color.b,",
        "			max( colorL.a, colorR.a ) );",
        "	#include <tonemapping_fragment>",
        "	#include <colorspace_fragment>",
        "}"
      ].join("\n")
    });
    const _quad = new FullScreenQuad(_material);
    this.setSize = function(width3, height3) {
      renderer2.setSize(width3, height3);
      const pixelRatio = renderer2.getPixelRatio();
      _renderTargetL.setSize(width3 * pixelRatio, height3 * pixelRatio);
      _renderTargetR.setSize(width3 * pixelRatio, height3 * pixelRatio);
    };
    this.render = function(scene, camera) {
      const currentRenderTarget = renderer2.getRenderTarget();
      if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
      if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
      _stereo.update(camera);
      renderer2.setRenderTarget(_renderTargetL);
      renderer2.clear();
      renderer2.render(scene, _stereo.cameraL);
      renderer2.setRenderTarget(_renderTargetR);
      renderer2.clear();
      renderer2.render(scene, _stereo.cameraR);
      renderer2.setRenderTarget(null);
      _quad.render(renderer2);
      renderer2.setRenderTarget(currentRenderTarget);
    };
    this.dispose = function() {
      _renderTargetL.dispose();
      _renderTargetR.dispose();
      _material.dispose();
      _quad.dispose();
    };
  }
};

// node_modules/three/examples/jsm/effects/AsciiEffect.js
var AsciiEffect = class {
  /**
   * Constructs a new ASCII effect.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {string} [charSet=' .:-=+*#%@'] - The char set.
   * @param {AsciiEffect~Options} [options] - The configuration parameter.
   */
  constructor(renderer2, charSet = " .:-=+*#%@", options = {}) {
    const fResolution = options["resolution"] || 0.15;
    const iScale = options["scale"] || 1;
    const bColor = options["color"] || false;
    const bAlpha = options["alpha"] || false;
    const bBlock = options["block"] || false;
    const bInvert = options["invert"] || false;
    const strResolution = options["strResolution"] || "low";
    let width2, height2;
    const domElement = document.createElement("div");
    domElement.style.cursor = "default";
    const oAscii = document.createElement("table");
    domElement.appendChild(oAscii);
    let iWidth, iHeight;
    let oImg;
    this.setSize = function(w, h) {
      width2 = w;
      height2 = h;
      renderer2.setSize(w, h);
      initAsciiSize();
    };
    this.render = function(scene, camera) {
      renderer2.render(scene, camera);
      asciifyImage(oAscii);
    };
    this.domElement = domElement;
    function initAsciiSize() {
      iWidth = Math.floor(width2 * fResolution);
      iHeight = Math.floor(height2 * fResolution);
      oCanvas.width = iWidth;
      oCanvas.height = iHeight;
      oImg = renderer2.domElement;
      if (oImg.style.backgroundColor) {
        oAscii.rows[0].cells[0].style.backgroundColor = oImg.style.backgroundColor;
        oAscii.rows[0].cells[0].style.color = oImg.style.color;
      }
      oAscii.cellSpacing = "0";
      oAscii.cellPadding = "0";
      const oStyle = oAscii.style;
      oStyle.whiteSpace = "pre";
      oStyle.margin = "0px";
      oStyle.padding = "0px";
      oStyle.letterSpacing = fLetterSpacing + "px";
      oStyle.fontFamily = strFont;
      oStyle.fontSize = fFontSize + "px";
      oStyle.lineHeight = fLineHeight + "px";
      oStyle.textAlign = "left";
      oStyle.textDecoration = "none";
    }
    const strFont = "courier new, monospace";
    const oCanvasImg = renderer2.domElement;
    const oCanvas = document.createElement("canvas");
    if (!oCanvas.getContext) {
      return;
    }
    const oCtx = oCanvas.getContext("2d");
    if (!oCtx.getImageData) {
      return;
    }
    let aCharList;
    if (charSet) {
      aCharList = charSet.split("");
    } else {
      const aDefaultCharList = " .,:;i1tfLCG08@".split("");
      const aDefaultColorCharList = " CGO08@".split("");
      aCharList = bColor ? aDefaultColorCharList : aDefaultCharList;
    }
    const fFontSize = 2 / fResolution * iScale;
    const fLineHeight = 2 / fResolution * iScale;
    let fLetterSpacing = 0;
    if (strResolution == "low") {
      switch (iScale) {
        case 1:
          fLetterSpacing = -1;
          break;
        case 2:
        case 3:
          fLetterSpacing = -2.1;
          break;
        case 4:
          fLetterSpacing = -3.1;
          break;
        case 5:
          fLetterSpacing = -4.15;
          break;
      }
    }
    if (strResolution == "medium") {
      switch (iScale) {
        case 1:
          fLetterSpacing = 0;
          break;
        case 2:
          fLetterSpacing = -1;
          break;
        case 3:
          fLetterSpacing = -1.04;
          break;
        case 4:
        case 5:
          fLetterSpacing = -2.1;
          break;
      }
    }
    if (strResolution == "high") {
      switch (iScale) {
        case 1:
        case 2:
          fLetterSpacing = 0;
          break;
        case 3:
        case 4:
        case 5:
          fLetterSpacing = -1;
          break;
      }
    }
    function asciifyImage(oAscii2) {
      oCtx.clearRect(0, 0, iWidth, iHeight);
      oCtx.drawImage(oCanvasImg, 0, 0, iWidth, iHeight);
      const oImgData = oCtx.getImageData(0, 0, iWidth, iHeight).data;
      let strChars = "";
      for (let y = 0; y < iHeight; y += 2) {
        for (let x2 = 0; x2 < iWidth; x2++) {
          const iOffset = (y * iWidth + x2) * 4;
          const iRed = oImgData[iOffset];
          const iGreen = oImgData[iOffset + 1];
          const iBlue = oImgData[iOffset + 2];
          const iAlpha = oImgData[iOffset + 3];
          let iCharIdx;
          let fBrightness;
          fBrightness = (0.3 * iRed + 0.59 * iGreen + 0.11 * iBlue) / 255;
          if (iAlpha == 0) {
            fBrightness = 1;
          }
          iCharIdx = Math.floor((1 - fBrightness) * (aCharList.length - 1));
          if (bInvert) {
            iCharIdx = aCharList.length - iCharIdx - 1;
          }
          let strThisChar = aCharList[iCharIdx];
          if (strThisChar === void 0 || strThisChar == " ")
            strThisChar = "&nbsp;";
          if (bColor) {
            strChars += "<span style='color:rgb(" + iRed + "," + iGreen + "," + iBlue + ");" + (bBlock ? "background-color:rgb(" + iRed + "," + iGreen + "," + iBlue + ");" : "") + (bAlpha ? "opacity:" + iAlpha / 255 + ";" : "") + "'>" + strThisChar + "</span>";
          } else {
            strChars += strThisChar;
          }
        }
        strChars += "<br/>";
      }
      oAscii2.innerHTML = `<tr><td style="display:block;width:${width2}px;height:${height2}px;overflow:hidden">${strChars}</td></tr>`;
    }
  }
};

// node_modules/three/examples/jsm/effects/OutlineEffect.js
var OutlineEffect = class {
  /**
   * Constructs a new outline effect.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {OutlineEffect~Options} [parameters] - The configuration parameter.
   */
  constructor(renderer2, parameters = {}) {
    this.enabled = true;
    const defaultThickness = parameters.defaultThickness !== void 0 ? parameters.defaultThickness : 3e-3;
    const defaultColor = new Color().fromArray(parameters.defaultColor !== void 0 ? parameters.defaultColor : [0, 0, 0]);
    const defaultAlpha = parameters.defaultAlpha !== void 0 ? parameters.defaultAlpha : 1;
    const defaultKeepAlive = parameters.defaultKeepAlive !== void 0 ? parameters.defaultKeepAlive : false;
    const cache = {};
    const removeThresholdCount = 60;
    const originalMaterials = {};
    const originalOnBeforeRenders = {};
    const uniformsOutline = {
      outlineThickness: { value: defaultThickness },
      outlineColor: { value: defaultColor },
      outlineAlpha: { value: defaultAlpha }
    };
    const vertexShader = [
      "#include <common>",
      "#include <uv_pars_vertex>",
      "#include <displacementmap_pars_vertex>",
      "#include <fog_pars_vertex>",
      "#include <morphtarget_pars_vertex>",
      "#include <skinning_pars_vertex>",
      "#include <logdepthbuf_pars_vertex>",
      "#include <clipping_planes_pars_vertex>",
      "uniform float outlineThickness;",
      "vec4 calculateOutline( vec4 pos, vec3 normal, vec4 skinned ) {",
      "	float thickness = outlineThickness;",
      "	const float ratio = 1.0;",
      // TODO: support outline thickness ratio for each vertex
      "	vec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + normal, 1.0 );",
      // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
      "	vec4 norm = normalize( pos - pos2 );",
      "	return pos + norm * thickness * pos.w * ratio;",
      "}",
      "void main() {",
      "	#include <uv_vertex>",
      "	#include <beginnormal_vertex>",
      "	#include <morphnormal_vertex>",
      "	#include <skinbase_vertex>",
      "	#include <skinnormal_vertex>",
      "	#include <begin_vertex>",
      "	#include <morphtarget_vertex>",
      "	#include <skinning_vertex>",
      "	#include <displacementmap_vertex>",
      "	#include <project_vertex>",
      "	vec3 outlineNormal = - objectNormal;",
      // the outline material is always rendered with BackSide
      "	gl_Position = calculateOutline( gl_Position, outlineNormal, vec4( transformed, 1.0 ) );",
      "	#include <logdepthbuf_vertex>",
      "	#include <clipping_planes_vertex>",
      "	#include <fog_vertex>",
      "}"
    ].join("\n");
    const fragmentShader = [
      "#include <common>",
      "#include <fog_pars_fragment>",
      "#include <logdepthbuf_pars_fragment>",
      "#include <clipping_planes_pars_fragment>",
      "uniform vec3 outlineColor;",
      "uniform float outlineAlpha;",
      "void main() {",
      "	#include <clipping_planes_fragment>",
      "	#include <logdepthbuf_fragment>",
      "	gl_FragColor = vec4( outlineColor, outlineAlpha );",
      "	#include <tonemapping_fragment>",
      "	#include <colorspace_fragment>",
      "	#include <fog_fragment>",
      "	#include <premultiplied_alpha_fragment>",
      "}"
    ].join("\n");
    function createMaterial() {
      return new ShaderMaterial({
        type: "OutlineEffect",
        uniforms: UniformsUtils.merge([
          UniformsLib["fog"],
          UniformsLib["displacementmap"],
          uniformsOutline
        ]),
        vertexShader,
        fragmentShader,
        side: BackSide
      });
    }
    function getOutlineMaterialFromCache(originalMaterial) {
      let data2 = cache[originalMaterial.uuid];
      if (data2 === void 0) {
        data2 = {
          material: createMaterial(),
          used: true,
          keepAlive: defaultKeepAlive,
          count: 0
        };
        cache[originalMaterial.uuid] = data2;
      }
      data2.used = true;
      return data2.material;
    }
    function getOutlineMaterial(originalMaterial) {
      const outlineMaterial = getOutlineMaterialFromCache(originalMaterial);
      originalMaterials[outlineMaterial.uuid] = originalMaterial;
      updateOutlineMaterial(outlineMaterial, originalMaterial);
      return outlineMaterial;
    }
    function isCompatible(object) {
      const geometry = object.geometry;
      const hasNormals = geometry !== void 0 && geometry.attributes.normal !== void 0;
      return object.isMesh === true && object.material !== void 0 && hasNormals === true;
    }
    function setOutlineMaterial(object) {
      if (isCompatible(object) === false) return;
      if (Array.isArray(object.material)) {
        for (let i = 0, il = object.material.length; i < il; i++) {
          object.material[i] = getOutlineMaterial(object.material[i]);
        }
      } else {
        object.material = getOutlineMaterial(object.material);
      }
      originalOnBeforeRenders[object.uuid] = object.onBeforeRender;
      object.onBeforeRender = onBeforeRender;
    }
    function restoreOriginalMaterial(object) {
      if (isCompatible(object) === false) return;
      if (Array.isArray(object.material)) {
        for (let i = 0, il = object.material.length; i < il; i++) {
          object.material[i] = originalMaterials[object.material[i].uuid];
        }
      } else {
        object.material = originalMaterials[object.material.uuid];
      }
      object.onBeforeRender = originalOnBeforeRenders[object.uuid];
    }
    function onBeforeRender(renderer3, scene, camera, geometry, material) {
      const originalMaterial = originalMaterials[material.uuid];
      if (originalMaterial === void 0) return;
      updateUniforms(material, originalMaterial);
    }
    function updateUniforms(material, originalMaterial) {
      const outlineParameters = originalMaterial.userData.outlineParameters;
      material.uniforms.outlineAlpha.value = originalMaterial.opacity;
      if (outlineParameters !== void 0) {
        if (outlineParameters.thickness !== void 0) material.uniforms.outlineThickness.value = outlineParameters.thickness;
        if (outlineParameters.color !== void 0) material.uniforms.outlineColor.value.fromArray(outlineParameters.color);
        if (outlineParameters.alpha !== void 0) material.uniforms.outlineAlpha.value = outlineParameters.alpha;
      }
      if (originalMaterial.displacementMap) {
        material.uniforms.displacementMap.value = originalMaterial.displacementMap;
        material.uniforms.displacementScale.value = originalMaterial.displacementScale;
        material.uniforms.displacementBias.value = originalMaterial.displacementBias;
      }
    }
    function updateOutlineMaterial(material, originalMaterial) {
      if (material.name === "invisible") return;
      const outlineParameters = originalMaterial.userData.outlineParameters;
      material.fog = originalMaterial.fog;
      material.toneMapped = originalMaterial.toneMapped;
      material.premultipliedAlpha = originalMaterial.premultipliedAlpha;
      material.displacementMap = originalMaterial.displacementMap;
      if (outlineParameters !== void 0) {
        if (originalMaterial.visible === false) {
          material.visible = false;
        } else {
          material.visible = outlineParameters.visible !== void 0 ? outlineParameters.visible : true;
        }
        material.transparent = outlineParameters.alpha !== void 0 && outlineParameters.alpha < 1 ? true : originalMaterial.transparent;
        if (outlineParameters.keepAlive !== void 0) cache[originalMaterial.uuid].keepAlive = outlineParameters.keepAlive;
      } else {
        material.transparent = originalMaterial.transparent;
        material.visible = originalMaterial.visible;
      }
      if (originalMaterial.wireframe === true || originalMaterial.depthTest === false) material.visible = false;
      if (originalMaterial.clippingPlanes) {
        material.clipping = true;
        material.clippingPlanes = originalMaterial.clippingPlanes;
        material.clipIntersection = originalMaterial.clipIntersection;
        material.clipShadows = originalMaterial.clipShadows;
      }
      material.version = originalMaterial.version;
    }
    function cleanupCache() {
      let keys2;
      keys2 = Object.keys(originalMaterials);
      for (let i = 0, il = keys2.length; i < il; i++) {
        originalMaterials[keys2[i]] = void 0;
      }
      keys2 = Object.keys(originalOnBeforeRenders);
      for (let i = 0, il = keys2.length; i < il; i++) {
        originalOnBeforeRenders[keys2[i]] = void 0;
      }
      keys2 = Object.keys(cache);
      for (let i = 0, il = keys2.length; i < il; i++) {
        const key2 = keys2[i];
        if (cache[key2].used === false) {
          cache[key2].count++;
          if (cache[key2].keepAlive === false && cache[key2].count > removeThresholdCount) {
            delete cache[key2];
          }
        } else {
          cache[key2].used = false;
          cache[key2].count = 0;
        }
      }
    }
    this.render = function(scene, camera) {
      if (this.enabled === false) {
        renderer2.render(scene, camera);
        return;
      }
      const currentAutoClear = renderer2.autoClear;
      renderer2.autoClear = this.autoClear;
      renderer2.render(scene, camera);
      renderer2.autoClear = currentAutoClear;
      this.renderOutline(scene, camera);
    };
    this.renderOutline = function(scene, camera) {
      const currentAutoClear = renderer2.autoClear;
      const currentSceneAutoUpdate = scene.matrixWorldAutoUpdate;
      const currentSceneBackground = scene.background;
      const currentShadowMapEnabled = renderer2.shadowMap.enabled;
      scene.matrixWorldAutoUpdate = false;
      scene.background = null;
      renderer2.autoClear = false;
      renderer2.shadowMap.enabled = false;
      scene.traverse(setOutlineMaterial);
      renderer2.render(scene, camera);
      scene.traverse(restoreOriginalMaterial);
      cleanupCache();
      scene.matrixWorldAutoUpdate = currentSceneAutoUpdate;
      scene.background = currentSceneBackground;
      renderer2.autoClear = currentAutoClear;
      renderer2.shadowMap.enabled = currentShadowMapEnabled;
    };
    this.setSize = function(width2, height2) {
      renderer2.setSize(width2, height2);
    };
  }
};

// node_modules/three/examples/jsm/effects/ParallaxBarrierEffect.js
var ParallaxBarrierEffect = class {
  /**
   * Constructs a new parallax barrier effect.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   */
  constructor(renderer2) {
    const _stereo = new StereoCamera();
    const _params = { minFilter: LinearFilter, magFilter: NearestFilter, format: RGBAFormat };
    const _renderTargetL = new WebGLRenderTarget(512, 512, _params);
    const _renderTargetR = new WebGLRenderTarget(512, 512, _params);
    const _material = new ShaderMaterial({
      uniforms: {
        "mapLeft": { value: _renderTargetL.texture },
        "mapRight": { value: _renderTargetR.texture }
      },
      vertexShader: [
        "varying vec2 vUv;",
        "void main() {",
        "	vUv = vec2( uv.x, uv.y );",
        "	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
        "}"
      ].join("\n"),
      fragmentShader: [
        "uniform sampler2D mapLeft;",
        "uniform sampler2D mapRight;",
        "varying vec2 vUv;",
        "void main() {",
        "	vec2 uv = vUv;",
        "	if ( ( mod( gl_FragCoord.y, 2.0 ) ) > 1.00 ) {",
        "		gl_FragColor = texture2D( mapLeft, uv );",
        "	} else {",
        "		gl_FragColor = texture2D( mapRight, uv );",
        "	}",
        "	#include <tonemapping_fragment>",
        "	#include <colorspace_fragment>",
        "}"
      ].join("\n")
    });
    const _quad = new FullScreenQuad(_material);
    this.setSize = function(width2, height2) {
      renderer2.setSize(width2, height2);
      const pixelRatio = renderer2.getPixelRatio();
      _renderTargetL.setSize(width2 * pixelRatio, height2 * pixelRatio);
      _renderTargetR.setSize(width2 * pixelRatio, height2 * pixelRatio);
    };
    this.render = function(scene, camera) {
      const currentRenderTarget = renderer2.getRenderTarget();
      if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
      if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
      _stereo.update(camera);
      renderer2.setRenderTarget(_renderTargetL);
      renderer2.clear();
      renderer2.render(scene, _stereo.cameraL);
      renderer2.setRenderTarget(_renderTargetR);
      renderer2.clear();
      renderer2.render(scene, _stereo.cameraR);
      renderer2.setRenderTarget(null);
      _quad.render(renderer2);
      renderer2.setRenderTarget(currentRenderTarget);
    };
    this.dispose = function() {
      _renderTargetL.dispose();
      _renderTargetR.dispose();
      _material.dispose();
      _quad.dispose();
    };
  }
};

// node_modules/three/examples/jsm/effects/StereoEffect.js
var StereoEffect = class {
  /**
   * Constructs a new stereo effect.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   */
  constructor(renderer2) {
    const _stereo = new StereoCamera();
    _stereo.aspect = 0.5;
    const size2 = new Vector2();
    this.setEyeSeparation = function(eyeSep) {
      _stereo.eyeSep = eyeSep;
    };
    this.setSize = function(width2, height2) {
      renderer2.setSize(width2, height2);
    };
    this.render = function(scene, camera) {
      if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
      if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
      _stereo.update(camera);
      const currentAutoClear = renderer2.autoClear;
      renderer2.getSize(size2);
      renderer2.autoClear = false;
      renderer2.clear();
      renderer2.setScissorTest(true);
      renderer2.setScissor(0, 0, size2.width / 2, size2.height);
      renderer2.setViewport(0, 0, size2.width / 2, size2.height);
      renderer2.render(scene, _stereo.cameraL);
      renderer2.setScissor(size2.width / 2, 0, size2.width / 2, size2.height);
      renderer2.setViewport(size2.width / 2, 0, size2.width / 2, size2.height);
      renderer2.render(scene, _stereo.cameraR);
      renderer2.setScissorTest(false);
      renderer2.autoClear = currentAutoClear;
    };
  }
};

// node_modules/three/examples/jsm/environments/DebugEnvironment.js
var DebugEnvironment = class extends Scene {
  /**
   * Constructs a new debug environment.
   */
  constructor() {
    super();
    const geometry = new BoxGeometry();
    geometry.deleteAttribute("uv");
    const roomMaterial = new MeshStandardMaterial({ metalness: 0, side: BackSide });
    const room = new Mesh(geometry, roomMaterial);
    room.scale.setScalar(10);
    this.add(room);
    const mainLight = new PointLight(16777215, 50, 0, 2);
    this.add(mainLight);
    const material1 = new MeshLambertMaterial({ color: 16711680, emissive: 16777215, emissiveIntensity: 10 });
    const light1 = new Mesh(geometry, material1);
    light1.position.set(-5, 2, 0);
    light1.scale.set(0.1, 1, 1);
    this.add(light1);
    const material2 = new MeshLambertMaterial({ color: 65280, emissive: 16777215, emissiveIntensity: 10 });
    const light2 = new Mesh(geometry, material2);
    light2.position.set(0, 5, 0);
    light2.scale.set(1, 0.1, 1);
    this.add(light2);
    const material3 = new MeshLambertMaterial({ color: 255, emissive: 16777215, emissiveIntensity: 10 });
    const light3 = new Mesh(geometry, material3);
    light3.position.set(2, 1, 5);
    light3.scale.set(1.5, 2, 0.1);
    this.add(light3);
  }
  /**
   * Frees internal resources. This method should be called
   * when the environment is no longer required.
   */
  dispose() {
    const resources = /* @__PURE__ */ new Set();
    this.traverse((object) => {
      if (object.isMesh) {
        resources.add(object.geometry);
        resources.add(object.material);
      }
    });
    for (const resource of resources) {
      resource.dispose();
    }
  }
};

// node_modules/three/examples/jsm/environments/RoomEnvironment.js
var RoomEnvironment = class extends Scene {
  constructor() {
    super();
    const geometry = new BoxGeometry();
    geometry.deleteAttribute("uv");
    const roomMaterial = new MeshStandardMaterial({ side: BackSide });
    const boxMaterial = new MeshStandardMaterial();
    const mainLight = new PointLight(16777215, 900, 28, 2);
    mainLight.position.set(0.418, 16.199, 0.3);
    this.add(mainLight);
    const room = new Mesh(geometry, roomMaterial);
    room.position.set(-0.757, 13.219, 0.717);
    room.scale.set(31.713, 28.305, 28.591);
    this.add(room);
    const boxes = new InstancedMesh(geometry, boxMaterial, 6);
    const transform2 = new Object3D();
    transform2.position.set(-10.906, 2.009, 1.846);
    transform2.rotation.set(0, -0.195, 0);
    transform2.scale.set(2.328, 7.905, 4.651);
    transform2.updateMatrix();
    boxes.setMatrixAt(0, transform2.matrix);
    transform2.position.set(-5.607, -0.754, -0.758);
    transform2.rotation.set(0, 0.994, 0);
    transform2.scale.set(1.97, 1.534, 3.955);
    transform2.updateMatrix();
    boxes.setMatrixAt(1, transform2.matrix);
    transform2.position.set(6.167, 0.857, 7.803);
    transform2.rotation.set(0, 0.561, 0);
    transform2.scale.set(3.927, 6.285, 3.687);
    transform2.updateMatrix();
    boxes.setMatrixAt(2, transform2.matrix);
    transform2.position.set(-2.017, 0.018, 6.124);
    transform2.rotation.set(0, 0.333, 0);
    transform2.scale.set(2.002, 4.566, 2.064);
    transform2.updateMatrix();
    boxes.setMatrixAt(3, transform2.matrix);
    transform2.position.set(2.291, -0.756, -2.621);
    transform2.rotation.set(0, -0.286, 0);
    transform2.scale.set(1.546, 1.552, 1.496);
    transform2.updateMatrix();
    boxes.setMatrixAt(4, transform2.matrix);
    transform2.position.set(-2.193, -0.369, -5.547);
    transform2.rotation.set(0, 0.516, 0);
    transform2.scale.set(3.875, 3.487, 2.986);
    transform2.updateMatrix();
    boxes.setMatrixAt(5, transform2.matrix);
    this.add(boxes);
    const light1 = new Mesh(geometry, createAreaLightMaterial(50));
    light1.position.set(-16.116, 14.37, 8.208);
    light1.scale.set(0.1, 2.428, 2.739);
    this.add(light1);
    const light2 = new Mesh(geometry, createAreaLightMaterial(50));
    light2.position.set(-16.109, 18.021, -8.207);
    light2.scale.set(0.1, 2.425, 2.751);
    this.add(light2);
    const light3 = new Mesh(geometry, createAreaLightMaterial(17));
    light3.position.set(14.904, 12.198, -1.832);
    light3.scale.set(0.15, 4.265, 6.331);
    this.add(light3);
    const light4 = new Mesh(geometry, createAreaLightMaterial(43));
    light4.position.set(-0.462, 8.89, 14.52);
    light4.scale.set(4.38, 5.441, 0.088);
    this.add(light4);
    const light5 = new Mesh(geometry, createAreaLightMaterial(20));
    light5.position.set(3.235, 11.486, -12.541);
    light5.scale.set(2.5, 2, 0.1);
    this.add(light5);
    const light6 = new Mesh(geometry, createAreaLightMaterial(100));
    light6.position.set(0, 20, 0);
    light6.scale.set(1, 0.1, 1);
    this.add(light6);
  }
  /**
   * Frees internal resources. This method should be called
   * when the environment is no longer required.
   */
  dispose() {
    const resources = /* @__PURE__ */ new Set();
    this.traverse((object) => {
      if (object.isMesh) {
        resources.add(object.geometry);
        resources.add(object.material);
      }
    });
    for (const resource of resources) {
      resource.dispose();
    }
  }
};
function createAreaLightMaterial(intensity) {
  const material = new MeshBasicMaterial();
  material.color.setScalar(intensity);
  return material;
}

// node_modules/three/examples/jsm/exporters/DRACOExporter.js
var DRACOExporter = class _DRACOExporter {
  /**
   * Parses the given mesh or point cloud and generates the Draco output.
   *
   * @param {(Mesh|Points)} object - The mesh or point cloud to export.
   * @param {DRACOExporter~Options} options - The export options.
   * @return {Int8Array} The exported Draco.
   */
  parse(object, options = {}) {
    options = Object.assign({
      decodeSpeed: 5,
      encodeSpeed: 5,
      encoderMethod: _DRACOExporter.MESH_EDGEBREAKER_ENCODING,
      quantization: [16, 8, 8, 8, 8],
      exportUvs: true,
      exportNormals: true,
      exportColor: false
    }, options);
    if (DracoEncoderModule === void 0) {
      throw new Error("THREE.DRACOExporter: required the draco_encoder to work.");
    }
    const geometry = object.geometry;
    const dracoEncoder = DracoEncoderModule();
    const encoder = new dracoEncoder.Encoder();
    let builder;
    let dracoObject;
    if (object.isMesh === true) {
      builder = new dracoEncoder.MeshBuilder();
      dracoObject = new dracoEncoder.Mesh();
      const vertices = geometry.getAttribute("position");
      builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array);
      const faces = geometry.getIndex();
      if (faces !== null) {
        builder.AddFacesToMesh(dracoObject, faces.count / 3, faces.array);
      } else {
        const faces2 = new (vertices.count > 65535 ? Uint32Array : Uint16Array)(vertices.count);
        for (let i = 0; i < faces2.length; i++) {
          faces2[i] = i;
        }
        builder.AddFacesToMesh(dracoObject, vertices.count, faces2);
      }
      if (options.exportNormals === true) {
        const normals = geometry.getAttribute("normal");
        if (normals !== void 0) {
          builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array);
        }
      }
      if (options.exportUvs === true) {
        const uvs = geometry.getAttribute("uv");
        if (uvs !== void 0) {
          builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array);
        }
      }
      if (options.exportColor === true) {
        const colors = geometry.getAttribute("color");
        if (colors !== void 0) {
          const array = createVertexColorSRGBArray(colors);
          builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, array);
        }
      }
    } else if (object.isPoints === true) {
      builder = new dracoEncoder.PointCloudBuilder();
      dracoObject = new dracoEncoder.PointCloud();
      const vertices = geometry.getAttribute("position");
      builder.AddFloatAttribute(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array);
      if (options.exportColor === true) {
        const colors = geometry.getAttribute("color");
        if (colors !== void 0) {
          const array = createVertexColorSRGBArray(colors);
          builder.AddFloatAttribute(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, array);
        }
      }
    } else {
      throw new Error("DRACOExporter: Unsupported object type.");
    }
    const encodedData = new dracoEncoder.DracoInt8Array();
    const encodeSpeed = options.encodeSpeed !== void 0 ? options.encodeSpeed : 5;
    const decodeSpeed = options.decodeSpeed !== void 0 ? options.decodeSpeed : 5;
    encoder.SetSpeedOptions(encodeSpeed, decodeSpeed);
    if (options.encoderMethod !== void 0) {
      encoder.SetEncodingMethod(options.encoderMethod);
    }
    if (options.quantization !== void 0) {
      for (let i = 0; i < 5; i++) {
        if (options.quantization[i] !== void 0) {
          encoder.SetAttributeQuantization(i, options.quantization[i]);
        }
      }
    }
    let length2;
    if (object.isMesh === true) {
      length2 = encoder.EncodeMeshToDracoBuffer(dracoObject, encodedData);
    } else {
      length2 = encoder.EncodePointCloudToDracoBuffer(dracoObject, true, encodedData);
    }
    dracoEncoder.destroy(dracoObject);
    if (length2 === 0) {
      throw new Error("THREE.DRACOExporter: Draco encoding failed.");
    }
    const outputData = new Int8Array(new ArrayBuffer(length2));
    for (let i = 0; i < length2; i++) {
      outputData[i] = encodedData.GetValue(i);
    }
    dracoEncoder.destroy(encodedData);
    dracoEncoder.destroy(encoder);
    dracoEncoder.destroy(builder);
    return outputData;
  }
};
function createVertexColorSRGBArray(attribute) {
  const _color5 = new Color();
  const count = attribute.count;
  const itemSize = attribute.itemSize;
  const array = new Float32Array(count * itemSize);
  for (let i = 0, il = count; i < il; i++) {
    _color5.fromBufferAttribute(attribute, i);
    ColorManagement.workingToColorSpace(_color5, SRGBColorSpace);
    array[i * itemSize] = _color5.r;
    array[i * itemSize + 1] = _color5.g;
    array[i * itemSize + 2] = _color5.b;
    if (itemSize === 4) {
      array[i * itemSize + 3] = attribute.getW(i);
    }
  }
  return array;
}
DRACOExporter.MESH_EDGEBREAKER_ENCODING = 1;
DRACOExporter.MESH_SEQUENTIAL_ENCODING = 0;
DRACOExporter.POINT_CLOUD = 0;
DRACOExporter.TRIANGULAR_MESH = 1;
DRACOExporter.INVALID = -1;
DRACOExporter.POSITION = 0;
DRACOExporter.NORMAL = 1;
DRACOExporter.COLOR = 2;
DRACOExporter.TEX_COORD = 3;
DRACOExporter.GENERIC = 4;

// node_modules/three/examples/jsm/libs/fflate.module.js
var ch2 = {};
var wk = function(c2, id, msg, transfer, cb) {
  var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([
    c2 + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'
  ], { type: "text/javascript" }))));
  w.onmessage = function(e) {
    var d = e.data, ed = d.$e$;
    if (ed) {
      var err2 = new Error(ed[0]);
      err2["code"] = ed[1];
      err2.stack = ed[2];
      cb(err2, null);
    } else
      cb(null, d);
  };
  w.postMessage(msg, transfer);
  return w;
};
var u8 = Uint8Array;
var u16 = Uint16Array;
var i32 = Int32Array;
var fleb = new u8([
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  1,
  1,
  1,
  1,
  2,
  2,
  2,
  2,
  3,
  3,
  3,
  3,
  4,
  4,
  4,
  4,
  5,
  5,
  5,
  5,
  0,
  /* unused */
  0,
  0,
  /* impossible */
  0
]);
var fdeb = new u8([
  0,
  0,
  0,
  0,
  1,
  1,
  2,
  2,
  3,
  3,
  4,
  4,
  5,
  5,
  6,
  6,
  7,
  7,
  8,
  8,
  9,
  9,
  10,
  10,
  11,
  11,
  12,
  12,
  13,
  13,
  /* unused */
  0,
  0
]);
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
var freb = function(eb, start) {
  var b3 = new u16(31);
  for (var i = 0; i < 31; ++i) {
    b3[i] = start += 1 << eb[i - 1];
  }
  var r = new i32(b3[30]);
  for (var i = 1; i < 30; ++i) {
    for (var j2 = b3[i]; j2 < b3[i + 1]; ++j2) {
      r[j2] = j2 - b3[i] << 5 | i;
    }
  }
  return { b: b3, r };
};
var _a = freb(fleb, 2);
var fl = _a.b;
var revfl = _a.r;
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0);
var fd = _b.b;
var revfd = _b.r;
var rev = new u16(32768);
for (i = 0; i < 32768; ++i) {
  x2 = (i & 43690) >> 1 | (i & 21845) << 1;
  x2 = (x2 & 52428) >> 2 | (x2 & 13107) << 2;
  x2 = (x2 & 61680) >> 4 | (x2 & 3855) << 4;
  rev[i] = ((x2 & 65280) >> 8 | (x2 & 255) << 8) >> 1;
}
var x2;
var i;
var hMap = function(cd, mb, r) {
  var s = cd.length;
  var i = 0;
  var l2 = new u16(mb);
  for (; i < s; ++i) {
    if (cd[i])
      ++l2[cd[i] - 1];
  }
  var le = new u16(mb);
  for (i = 1; i < mb; ++i) {
    le[i] = le[i - 1] + l2[i - 1] << 1;
  }
  var co;
  if (r) {
    co = new u16(1 << mb);
    var rvb = 15 - mb;
    for (i = 0; i < s; ++i) {
      if (cd[i]) {
        var sv = i << 4 | cd[i];
        var r_1 = mb - cd[i];
        var v = le[cd[i] - 1]++ << r_1;
        for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
          co[rev[v] >> rvb] = sv;
        }
      }
    }
  } else {
    co = new u16(s);
    for (i = 0; i < s; ++i) {
      if (cd[i]) {
        co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
      }
    }
  }
  return co;
};
var flt = new u8(288);
for (i = 0; i < 144; ++i)
  flt[i] = 8;
var i;
for (i = 144; i < 256; ++i)
  flt[i] = 9;
var i;
for (i = 256; i < 280; ++i)
  flt[i] = 7;
var i;
for (i = 280; i < 288; ++i)
  flt[i] = 8;
var i;
var fdt = new u8(32);
for (i = 0; i < 32; ++i)
  fdt[i] = 5;
var i;
var flm = hMap(flt, 9, 0);
var flrm = hMap(flt, 9, 1);
var fdm = hMap(fdt, 5, 0);
var fdrm = hMap(fdt, 5, 1);
var max = function(a2) {
  var m = a2[0];
  for (var i = 1; i < a2.length; ++i) {
    if (a2[i] > m)
      m = a2[i];
  }
  return m;
};
var bits = function(d, p, m) {
  var o = p / 8 | 0;
  return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
};
var bits16 = function(d, p) {
  var o = p / 8 | 0;
  return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
};
var shft = function(p) {
  return (p + 7) / 8 | 0;
};
var slc = function(v, s, e) {
  if (s == null || s < 0)
    s = 0;
  if (e == null || e > v.length)
    e = v.length;
  return new u8(v.subarray(s, e));
};
var ec = [
  "unexpected EOF",
  "invalid block type",
  "invalid length/literal",
  "invalid distance",
  "stream finished",
  "no stream handler",
  ,
  "no callback",
  "invalid UTF-8 data",
  "extra field too long",
  "date not in range 1980-2099",
  "filename too long",
  "stream finishing",
  "invalid zip data"
  // determined by unknown compression method
];
var err = function(ind, msg, nt2) {
  var e = new Error(msg || ec[ind]);
  e.code = ind;
  if (Error.captureStackTrace)
    Error.captureStackTrace(e, err);
  if (!nt2)
    throw e;
  return e;
};
var inflt = function(dat, st, buf, dict) {
  var sl = dat.length, dl = dict ? dict.length : 0;
  if (!sl || st.f && !st.l)
    return buf || new u8(0);
  var noBuf = !buf;
  var resize = noBuf || st.i != 2;
  var noSt = st.i;
  if (noBuf)
    buf = new u8(sl * 3);
  var cbuf = function(l3) {
    var bl = buf.length;
    if (l3 > bl) {
      var nbuf = new u8(Math.max(bl * 2, l3));
      nbuf.set(buf);
      buf = nbuf;
    }
  };
  var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
  var tbts = sl * 8;
  do {
    if (!lm) {
      final = bits(dat, pos, 1);
      var type = bits(dat, pos + 1, 3);
      pos += 3;
      if (!type) {
        var s = shft(pos) + 4, l2 = dat[s - 4] | dat[s - 3] << 8, t3 = s + l2;
        if (t3 > sl) {
          if (noSt)
            err(0);
          break;
        }
        if (resize)
          cbuf(bt + l2);
        buf.set(dat.subarray(s, t3), bt);
        st.b = bt += l2, st.p = pos = t3 * 8, st.f = final;
        continue;
      } else if (type == 1)
        lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
      else if (type == 2) {
        var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
        var tl = hLit + bits(dat, pos + 5, 31) + 1;
        pos += 14;
        var ldt = new u8(tl);
        var clt = new u8(19);
        for (var i = 0; i < hcLen; ++i) {
          clt[clim[i]] = bits(dat, pos + i * 3, 7);
        }
        pos += hcLen * 3;
        var clb = max(clt), clbmsk = (1 << clb) - 1;
        var clm = hMap(clt, clb, 1);
        for (var i = 0; i < tl; ) {
          var r = clm[bits(dat, pos, clbmsk)];
          pos += r & 15;
          var s = r >> 4;
          if (s < 16) {
            ldt[i++] = s;
          } else {
            var c2 = 0, n2 = 0;
            if (s == 16)
              n2 = 3 + bits(dat, pos, 3), pos += 2, c2 = ldt[i - 1];
            else if (s == 17)
              n2 = 3 + bits(dat, pos, 7), pos += 3;
            else if (s == 18)
              n2 = 11 + bits(dat, pos, 127), pos += 7;
            while (n2--)
              ldt[i++] = c2;
          }
        }
        var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
        lbt = max(lt);
        dbt = max(dt);
        lm = hMap(lt, lbt, 1);
        dm = hMap(dt, dbt, 1);
      } else
        err(1);
      if (pos > tbts) {
        if (noSt)
          err(0);
        break;
      }
    }
    if (resize)
      cbuf(bt + 131072);
    var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
    var lpos = pos;
    for (; ; lpos = pos) {
      var c2 = lm[bits16(dat, pos) & lms], sym = c2 >> 4;
      pos += c2 & 15;
      if (pos > tbts) {
        if (noSt)
          err(0);
        break;
      }
      if (!c2)
        err(2);
      if (sym < 256)
        buf[bt++] = sym;
      else if (sym == 256) {
        lpos = pos, lm = null;
        break;
      } else {
        var add2 = sym - 254;
        if (sym > 264) {
          var i = sym - 257, b3 = fleb[i];
          add2 = bits(dat, pos, (1 << b3) - 1) + fl[i];
          pos += b3;
        }
        var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
        if (!d)
          err(3);
        pos += d & 15;
        var dt = fd[dsym];
        if (dsym > 3) {
          var b3 = fdeb[dsym];
          dt += bits16(dat, pos) & (1 << b3) - 1, pos += b3;
        }
        if (pos > tbts) {
          if (noSt)
            err(0);
          break;
        }
        if (resize)
          cbuf(bt + 131072);
        var end = bt + add2;
        if (bt < dt) {
          var shift = dl - dt, dend = Math.min(dt, end);
          if (shift + bt < 0)
            err(3);
          for (; bt < dend; ++bt)
            buf[bt] = dict[shift + bt];
        }
        for (; bt < end; ++bt)
          buf[bt] = buf[bt - dt];
      }
    }
    st.l = lm, st.p = lpos, st.b = bt, st.f = final;
    if (lm)
      final = 1, st.m = lbt, st.d = dm, st.n = dbt;
  } while (!final);
  return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
var wbits = function(d, p, v) {
  v <<= p & 7;
  var o = p / 8 | 0;
  d[o] |= v;
  d[o + 1] |= v >> 8;
};
var wbits16 = function(d, p, v) {
  v <<= p & 7;
  var o = p / 8 | 0;
  d[o] |= v;
  d[o + 1] |= v >> 8;
  d[o + 2] |= v >> 16;
};
var hTree = function(d, mb) {
  var t3 = [];
  for (var i = 0; i < d.length; ++i) {
    if (d[i])
      t3.push({ s: i, f: d[i] });
  }
  var s = t3.length;
  var t22 = t3.slice();
  if (!s)
    return { t: et, l: 0 };
  if (s == 1) {
    var v = new u8(t3[0].s + 1);
    v[t3[0].s] = 1;
    return { t: v, l: 1 };
  }
  t3.sort(function(a2, b3) {
    return a2.f - b3.f;
  });
  t3.push({ s: -1, f: 25001 });
  var l2 = t3[0], r = t3[1], i0 = 0, i1 = 1, i2 = 2;
  t3[0] = { s: -1, f: l2.f + r.f, l: l2, r };
  while (i1 != s - 1) {
    l2 = t3[t3[i0].f < t3[i2].f ? i0++ : i2++];
    r = t3[i0 != i1 && t3[i0].f < t3[i2].f ? i0++ : i2++];
    t3[i1++] = { s: -1, f: l2.f + r.f, l: l2, r };
  }
  var maxSym = t22[0].s;
  for (var i = 1; i < s; ++i) {
    if (t22[i].s > maxSym)
      maxSym = t22[i].s;
  }
  var tr = new u16(maxSym + 1);
  var mbt = ln(t3[i1 - 1], tr, 0);
  if (mbt > mb) {
    var i = 0, dt = 0;
    var lft = mbt - mb, cst = 1 << lft;
    t22.sort(function(a2, b3) {
      return tr[b3.s] - tr[a2.s] || a2.f - b3.f;
    });
    for (; i < s; ++i) {
      var i2_1 = t22[i].s;
      if (tr[i2_1] > mb) {
        dt += cst - (1 << mbt - tr[i2_1]);
        tr[i2_1] = mb;
      } else
        break;
    }
    dt >>= lft;
    while (dt > 0) {
      var i2_2 = t22[i].s;
      if (tr[i2_2] < mb)
        dt -= 1 << mb - tr[i2_2]++ - 1;
      else
        ++i;
    }
    for (; i >= 0 && dt; --i) {
      var i2_3 = t22[i].s;
      if (tr[i2_3] == mb) {
        --tr[i2_3];
        ++dt;
      }
    }
    mbt = mb;
  }
  return { t: new u8(tr), l: mbt };
};
var ln = function(n2, l2, d) {
  return n2.s == -1 ? Math.max(ln(n2.l, l2, d + 1), ln(n2.r, l2, d + 1)) : l2[n2.s] = d;
};
var lc = function(c2) {
  var s = c2.length;
  while (s && !c2[--s])
    ;
  var cl = new u16(++s);
  var cli = 0, cln = c2[0], cls = 1;
  var w = function(v) {
    cl[cli++] = v;
  };
  for (var i = 1; i <= s; ++i) {
    if (c2[i] == cln && i != s)
      ++cls;
    else {
      if (!cln && cls > 2) {
        for (; cls > 138; cls -= 138)
          w(32754);
        if (cls > 2) {
          w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
          cls = 0;
        }
      } else if (cls > 3) {
        w(cln), --cls;
        for (; cls > 6; cls -= 6)
          w(8304);
        if (cls > 2)
          w(cls - 3 << 5 | 8208), cls = 0;
      }
      while (cls--)
        w(cln);
      cls = 1;
      cln = c2[i];
    }
  }
  return { c: cl.subarray(0, cli), n: s };
};
var clen = function(cf, cl) {
  var l2 = 0;
  for (var i = 0; i < cl.length; ++i)
    l2 += cf[i] * cl[i];
  return l2;
};
var wfblk = function(out, pos, dat) {
  var s = dat.length;
  var o = shft(pos + 2);
  out[o] = s & 255;
  out[o + 1] = s >> 8;
  out[o + 2] = out[o] ^ 255;
  out[o + 3] = out[o + 1] ^ 255;
  for (var i = 0; i < s; ++i)
    out[o + i + 4] = dat[i];
  return (o + 4 + s) * 8;
};
var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
  wbits(out, p++, final);
  ++lf[256];
  var _a3 = hTree(lf, 15), dlt = _a3.t, mlb = _a3.l;
  var _b3 = hTree(df, 15), ddt = _b3.t, mdb = _b3.l;
  var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
  var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
  var lcfreq = new u16(19);
  for (var i = 0; i < lclt.length; ++i)
    ++lcfreq[lclt[i] & 31];
  for (var i = 0; i < lcdt.length; ++i)
    ++lcfreq[lcdt[i] & 31];
  var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
  var nlcc = 19;
  for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
    ;
  var flen = bl + 5 << 3;
  var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
  var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
  if (bs >= 0 && flen <= ftlen && flen <= dtlen)
    return wfblk(out, p, dat.subarray(bs, bs + bl));
  var lm, ll, dm, dl;
  wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
  if (dtlen < ftlen) {
    lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
    var llm = hMap(lct, mlcb, 0);
    wbits(out, p, nlc - 257);
    wbits(out, p + 5, ndc - 1);
    wbits(out, p + 10, nlcc - 4);
    p += 14;
    for (var i = 0; i < nlcc; ++i)
      wbits(out, p + 3 * i, lct[clim[i]]);
    p += 3 * nlcc;
    var lcts = [lclt, lcdt];
    for (var it2 = 0; it2 < 2; ++it2) {
      var clct = lcts[it2];
      for (var i = 0; i < clct.length; ++i) {
        var len = clct[i] & 31;
        wbits(out, p, llm[len]), p += lct[len];
        if (len > 15)
          wbits(out, p, clct[i] >> 5 & 127), p += clct[i] >> 12;
      }
    }
  } else {
    lm = flm, ll = flt, dm = fdm, dl = fdt;
  }
  for (var i = 0; i < li; ++i) {
    var sym = syms[i];
    if (sym > 255) {
      var len = sym >> 18 & 31;
      wbits16(out, p, lm[len + 257]), p += ll[len + 257];
      if (len > 7)
        wbits(out, p, sym >> 23 & 31), p += fleb[len];
      var dst = sym & 31;
      wbits16(out, p, dm[dst]), p += dl[dst];
      if (dst > 3)
        wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
    } else {
      wbits16(out, p, lm[sym]), p += ll[sym];
    }
  }
  wbits16(out, p, lm[256]);
  return p + ll[256];
};
var deo = new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
var et = new u8(0);
var dflt = function(dat, lvl, plvl, pre, post2, st) {
  var s = st.z || dat.length;
  var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post2);
  var w = o.subarray(pre, o.length - post2);
  var lst = st.l;
  var pos = (st.r || 0) & 7;
  if (lvl) {
    if (pos)
      w[0] = st.r >> 3;
    var opt = deo[lvl - 1];
    var n2 = opt >> 13, c2 = opt & 8191;
    var msk_1 = (1 << plvl) - 1;
    var prev = st.p || new u16(32768), head2 = st.h || new u16(msk_1 + 1);
    var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
    var hsh = function(i2) {
      return (dat[i2] ^ dat[i2 + 1] << bs1_1 ^ dat[i2 + 2] << bs2_1) & msk_1;
    };
    var syms = new i32(25e3);
    var lf = new u16(288), df = new u16(32);
    var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
    for (; i + 2 < s; ++i) {
      var hv = hsh(i);
      var imod = i & 32767, pimod = head2[hv];
      prev[imod] = pimod;
      head2[hv] = imod;
      if (wi <= i) {
        var rem = s - i;
        if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
          pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
          li = lc_1 = eb = 0, bs = i;
          for (var j2 = 0; j2 < 286; ++j2)
            lf[j2] = 0;
          for (var j2 = 0; j2 < 30; ++j2)
            df[j2] = 0;
        }
        var l2 = 2, d = 0, ch_1 = c2, dif = imod - pimod & 32767;
        if (rem > 2 && hv == hsh(i - dif)) {
          var maxn = Math.min(n2, rem) - 1;
          var maxd = Math.min(32767, i);
          var ml = Math.min(258, rem);
          while (dif <= maxd && --ch_1 && imod != pimod) {
            if (dat[i + l2] == dat[i + l2 - dif]) {
              var nl = 0;
              for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
                ;
              if (nl > l2) {
                l2 = nl, d = dif;
                if (nl > maxn)
                  break;
                var mmd = Math.min(dif, nl - 2);
                var md = 0;
                for (var j2 = 0; j2 < mmd; ++j2) {
                  var ti = i - dif + j2 & 32767;
                  var pti = prev[ti];
                  var cd = ti - pti & 32767;
                  if (cd > md)
                    md = cd, pimod = ti;
                }
              }
            }
            imod = pimod, pimod = prev[imod];
            dif += imod - pimod & 32767;
          }
        }
        if (d) {
          syms[li++] = 268435456 | revfl[l2] << 18 | revfd[d];
          var lin = revfl[l2] & 31, din = revfd[d] & 31;
          eb += fleb[lin] + fdeb[din];
          ++lf[257 + lin];
          ++df[din];
          wi = i + l2;
          ++lc_1;
        } else {
          syms[li++] = dat[i];
          ++lf[dat[i]];
        }
      }
    }
    for (i = Math.max(i, wi); i < s; ++i) {
      syms[li++] = dat[i];
      ++lf[dat[i]];
    }
    pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
    if (!lst) {
      st.r = pos & 7 | w[pos / 8 | 0] << 3;
      pos -= 7;
      st.h = head2, st.p = prev, st.i = i, st.w = wi;
    }
  } else {
    for (var i = st.w || 0; i < s + lst; i += 65535) {
      var e = i + 65535;
      if (e >= s) {
        w[pos / 8 | 0] = lst;
        e = s;
      }
      pos = wfblk(w, pos + 1, dat.subarray(i, e));
    }
    st.i = s;
  }
  return slc(o, 0, pre + shft(pos) + post2);
};
var crct = function() {
  var t3 = new Int32Array(256);
  for (var i = 0; i < 256; ++i) {
    var c2 = i, k2 = 9;
    while (--k2)
      c2 = (c2 & 1 && -306674912) ^ c2 >>> 1;
    t3[i] = c2;
  }
  return t3;
}();
var crc = function() {
  var c2 = -1;
  return {
    p: function(d) {
      var cr = c2;
      for (var i = 0; i < d.length; ++i)
        cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8;
      c2 = cr;
    },
    d: function() {
      return ~c2;
    }
  };
};
var adler = function() {
  var a2 = 1, b3 = 0;
  return {
    p: function(d) {
      var n2 = a2, m = b3;
      var l2 = d.length | 0;
      for (var i = 0; i != l2; ) {
        var e = Math.min(i + 2655, l2);
        for (; i < e; ++i)
          m += n2 += d[i];
        n2 = (n2 & 65535) + 15 * (n2 >> 16), m = (m & 65535) + 15 * (m >> 16);
      }
      a2 = n2, b3 = m;
    },
    d: function() {
      a2 %= 65521, b3 %= 65521;
      return (a2 & 255) << 24 | (a2 & 65280) << 8 | (b3 & 255) << 8 | b3 >> 8;
    }
  };
};
var dopt = function(dat, opt, pre, post2, st) {
  if (!st) {
    st = { l: 1 };
    if (opt.dictionary) {
      var dict = opt.dictionary.subarray(-32768);
      var newDat = new u8(dict.length + dat.length);
      newDat.set(dict);
      newDat.set(dat, dict.length);
      dat = newDat;
      st.w = dict.length;
    }
  }
  return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post2, st);
};
var mrg = function(a2, b3) {
  var o = {};
  for (var k2 in a2)
    o[k2] = a2[k2];
  for (var k2 in b3)
    o[k2] = b3[k2];
  return o;
};
var wcln = function(fn, fnStr, td2) {
  var dt = fn();
  var st = fn.toString();
  var ks = st.slice(st.indexOf("[") + 1, st.lastIndexOf("]")).replace(/\s+/g, "").split(",");
  for (var i = 0; i < dt.length; ++i) {
    var v = dt[i], k2 = ks[i];
    if (typeof v == "function") {
      fnStr += ";" + k2 + "=";
      var st_1 = v.toString();
      if (v.prototype) {
        if (st_1.indexOf("[native code]") != -1) {
          var spInd = st_1.indexOf(" ", 8) + 1;
          fnStr += st_1.slice(spInd, st_1.indexOf("(", spInd));
        } else {
          fnStr += st_1;
          for (var t3 in v.prototype)
            fnStr += ";" + k2 + ".prototype." + t3 + "=" + v.prototype[t3].toString();
        }
      } else
        fnStr += st_1;
    } else
      td2[k2] = v;
  }
  return fnStr;
};
var ch = [];
var cbfs = function(v) {
  var tl = [];
  for (var k2 in v) {
    if (v[k2].buffer) {
      tl.push((v[k2] = new v[k2].constructor(v[k2])).buffer);
    }
  }
  return tl;
};
var wrkr = function(fns, init, id, cb) {
  if (!ch[id]) {
    var fnStr = "", td_1 = {}, m = fns.length - 1;
    for (var i = 0; i < m; ++i)
      fnStr = wcln(fns[i], fnStr, td_1);
    ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };
  }
  var td2 = mrg({}, ch[id].e);
  return wk(ch[id].c + ";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=" + init.toString() + "}", id, td2, cbfs(td2), cb);
};
var bInflt = function() {
  return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt];
};
var bDflt = function() {
  return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf];
};
var guze = function() {
  return [gzs, gzl];
};
var zule = function() {
  return [zls];
};
var pbf = function(msg) {
  return postMessage(msg, [msg.buffer]);
};
var gopt = function(o) {
  return o && {
    out: o.size && new u8(o.size),
    dictionary: o.dictionary
  };
};
var astrm = function(strm) {
  strm.ondata = function(dat, final) {
    return postMessage([dat, final], [dat.buffer]);
  };
  return function(ev) {
    if (ev.data.length) {
      strm.push(ev.data[0], ev.data[1]);
      postMessage([ev.data[0].length]);
    } else
      strm.flush();
  };
};
var astrmify = function(fns, strm, opts, init, id, flush, ext) {
  var t3;
  var w = wrkr(fns, init, id, function(err2, dat) {
    if (err2)
      w.terminate(), strm.ondata.call(strm, err2);
    else if (!Array.isArray(dat))
      ext(dat);
    else if (dat.length == 1) {
      strm.queuedSize -= dat[0];
      if (strm.ondrain)
        strm.ondrain(dat[0]);
    } else {
      if (dat[1])
        w.terminate();
      strm.ondata.call(strm, err2, dat[0], dat[1]);
    }
  });
  w.postMessage(opts);
  strm.queuedSize = 0;
  strm.push = function(d, f) {
    if (!strm.ondata)
      err(5);
    if (t3)
      strm.ondata(err(4, 0, 1), null, !!f);
    strm.queuedSize += d.length;
    w.postMessage([d, t3 = f], [d.buffer]);
  };
  strm.terminate = function() {
    w.terminate();
  };
  if (flush) {
    strm.flush = function() {
      w.postMessage([]);
    };
  }
};
var b2 = function(d, b3) {
  return d[b3] | d[b3 + 1] << 8;
};
var b4 = function(d, b3) {
  return (d[b3] | d[b3 + 1] << 8 | d[b3 + 2] << 16 | d[b3 + 3] << 24) >>> 0;
};
var b8 = function(d, b3) {
  return b4(d, b3) + b4(d, b3 + 4) * 4294967296;
};
var wbytes = function(d, b3, v) {
  for (; v; ++b3)
    d[b3] = v, v >>>= 8;
};
var gzh = function(c2, o) {
  var fn = o.filename;
  c2[0] = 31, c2[1] = 139, c2[2] = 8, c2[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c2[9] = 3;
  if (o.mtime != 0)
    wbytes(c2, 4, Math.floor(new Date(o.mtime || Date.now()) / 1e3));
  if (fn) {
    c2[3] = 8;
    for (var i = 0; i <= fn.length; ++i)
      c2[i + 10] = fn.charCodeAt(i);
  }
};
var gzs = function(d) {
  if (d[0] != 31 || d[1] != 139 || d[2] != 8)
    err(6, "invalid gzip data");
  var flg = d[3];
  var st = 10;
  if (flg & 4)
    st += (d[10] | d[11] << 8) + 2;
  for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
    ;
  return st + (flg & 2);
};
var gzl = function(d) {
  var l2 = d.length;
  return (d[l2 - 4] | d[l2 - 3] << 8 | d[l2 - 2] << 16 | d[l2 - 1] << 24) >>> 0;
};
var gzhl = function(o) {
  return 10 + (o.filename ? o.filename.length + 1 : 0);
};
var zlh = function(c2, o) {
  var lv = o.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
  c2[0] = 120, c2[1] = fl2 << 6 | (o.dictionary && 32);
  c2[1] |= 31 - (c2[0] << 8 | c2[1]) % 31;
  if (o.dictionary) {
    var h = adler();
    h.p(o.dictionary);
    wbytes(c2, 2, h.d());
  }
};
var zls = function(d, dict) {
  if ((d[0] & 15) != 8 || d[0] >> 4 > 7 || (d[0] << 8 | d[1]) % 31)
    err(6, "invalid zlib data");
  if ((d[1] >> 5 & 1) == +!dict)
    err(6, "invalid zlib data: " + (d[1] & 32 ? "need" : "unexpected") + " dictionary");
  return (d[1] >> 3 & 4) + 2;
};
function StrmOpt(opts, cb) {
  if (typeof opts == "function")
    cb = opts, opts = {};
  this.ondata = cb;
  return opts;
}
var Deflate = function() {
  function Deflate2(opts, cb) {
    if (typeof opts == "function")
      cb = opts, opts = {};
    this.ondata = cb;
    this.o = opts || {};
    this.s = { l: 0, i: 32768, w: 32768, z: 32768 };
    this.b = new u8(98304);
    if (this.o.dictionary) {
      var dict = this.o.dictionary.subarray(-32768);
      this.b.set(dict, 32768 - dict.length);
      this.s.i = 32768 - dict.length;
    }
  }
  Deflate2.prototype.p = function(c2, f) {
    this.ondata(dopt(c2, this.o, 0, 0, this.s), f);
  };
  Deflate2.prototype.push = function(chunk, final) {
    if (!this.ondata)
      err(5);
    if (this.s.l)
      err(4);
    var endLen = chunk.length + this.s.z;
    if (endLen > this.b.length) {
      if (endLen > 2 * this.b.length - 32768) {
        var newBuf = new u8(endLen & -32768);
        newBuf.set(this.b.subarray(0, this.s.z));
        this.b = newBuf;
      }
      var split = this.b.length - this.s.z;
      this.b.set(chunk.subarray(0, split), this.s.z);
      this.s.z = this.b.length;
      this.p(this.b, false);
      this.b.set(this.b.subarray(-32768));
      this.b.set(chunk.subarray(split), 32768);
      this.s.z = chunk.length - split + 32768;
      this.s.i = 32766, this.s.w = 32768;
    } else {
      this.b.set(chunk, this.s.z);
      this.s.z += chunk.length;
    }
    this.s.l = final & 1;
    if (this.s.z > this.s.w + 8191 || final) {
      this.p(this.b, final || false);
      this.s.w = this.s.i, this.s.i -= 2;
    }
  };
  Deflate2.prototype.flush = function() {
    if (!this.ondata)
      err(5);
    if (this.s.l)
      err(4);
    this.p(this.b, false);
    this.s.w = this.s.i, this.s.i -= 2;
  };
  return Deflate2;
}();
var AsyncDeflate = /* @__PURE__ */ function() {
  function AsyncDeflate2(opts, cb) {
    astrmify([
      bDflt,
      function() {
        return [astrm, Deflate];
      }
    ], this, StrmOpt.call(this, opts, cb), function(ev) {
      var strm = new Deflate(ev.data);
      onmessage = astrm(strm);
    }, 6, 1);
  }
  return AsyncDeflate2;
}();
function deflateSync(data2, opts) {
  return dopt(data2, opts || {}, 0, 0);
}
var Inflate = function() {
  function Inflate2(opts, cb) {
    if (typeof opts == "function")
      cb = opts, opts = {};
    this.ondata = cb;
    var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
    this.s = { i: 0, b: dict ? dict.length : 0 };
    this.o = new u8(32768);
    this.p = new u8(0);
    if (dict)
      this.o.set(dict);
  }
  Inflate2.prototype.e = function(c2) {
    if (!this.ondata)
      err(5);
    if (this.d)
      err(4);
    if (!this.p.length)
      this.p = c2;
    else if (c2.length) {
      var n2 = new u8(this.p.length + c2.length);
      n2.set(this.p), n2.set(c2, this.p.length), this.p = n2;
    }
  };
  Inflate2.prototype.c = function(final) {
    this.s.i = +(this.d = final || false);
    var bts = this.s.b;
    var dt = inflt(this.p, this.s, this.o);
    this.ondata(slc(dt, bts, this.s.b), this.d);
    this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
    this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7;
  };
  Inflate2.prototype.push = function(chunk, final) {
    this.e(chunk), this.c(final);
  };
  return Inflate2;
}();
var AsyncInflate = /* @__PURE__ */ function() {
  function AsyncInflate2(opts, cb) {
    astrmify([
      bInflt,
      function() {
        return [astrm, Inflate];
      }
    ], this, StrmOpt.call(this, opts, cb), function(ev) {
      var strm = new Inflate(ev.data);
      onmessage = astrm(strm);
    }, 7, 0);
  }
  return AsyncInflate2;
}();
function inflateSync(data2, opts) {
  return inflt(data2, { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
var Gzip = function() {
  function Gzip2(opts, cb) {
    this.c = crc();
    this.l = 0;
    this.v = 1;
    Deflate.call(this, opts, cb);
  }
  Gzip2.prototype.push = function(chunk, final) {
    this.c.p(chunk);
    this.l += chunk.length;
    Deflate.prototype.push.call(this, chunk, final);
  };
  Gzip2.prototype.p = function(c2, f) {
    var raw = dopt(c2, this.o, this.v && gzhl(this.o), f && 8, this.s);
    if (this.v)
      gzh(raw, this.o), this.v = 0;
    if (f)
      wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
    this.ondata(raw, f);
  };
  Gzip2.prototype.flush = function() {
    Deflate.prototype.flush.call(this);
  };
  return Gzip2;
}();
var Gunzip = function() {
  function Gunzip2(opts, cb) {
    this.v = 1;
    this.r = 0;
    Inflate.call(this, opts, cb);
  }
  Gunzip2.prototype.push = function(chunk, final) {
    Inflate.prototype.e.call(this, chunk);
    this.r += chunk.length;
    if (this.v) {
      var p = this.p.subarray(this.v - 1);
      var s = p.length > 3 ? gzs(p) : 4;
      if (s > p.length) {
        if (!final)
          return;
      } else if (this.v > 1 && this.onmember) {
        this.onmember(this.r - p.length);
      }
      this.p = p.subarray(s), this.v = 0;
    }
    Inflate.prototype.c.call(this, final);
    if (this.s.f && !this.s.l && !final) {
      this.v = shft(this.s.p) + 9;
      this.s = { i: 0 };
      this.o = new u8(0);
      this.push(new u8(0), final);
    }
  };
  return Gunzip2;
}();
var AsyncGunzip = /* @__PURE__ */ function() {
  function AsyncGunzip2(opts, cb) {
    var _this = this;
    astrmify([
      bInflt,
      guze,
      function() {
        return [astrm, Inflate, Gunzip];
      }
    ], this, StrmOpt.call(this, opts, cb), function(ev) {
      var strm = new Gunzip(ev.data);
      strm.onmember = function(offset) {
        return postMessage(offset);
      };
      onmessage = astrm(strm);
    }, 9, 0, function(offset) {
      return _this.onmember && _this.onmember(offset);
    });
  }
  return AsyncGunzip2;
}();
function gunzipSync(data2, opts) {
  var st = gzs(data2);
  if (st + 8 > data2.length)
    err(6, "invalid gzip data");
  return inflt(data2.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data2)), opts && opts.dictionary);
}
var Zlib = function() {
  function Zlib2(opts, cb) {
    this.c = adler();
    this.v = 1;
    Deflate.call(this, opts, cb);
  }
  Zlib2.prototype.push = function(chunk, final) {
    this.c.p(chunk);
    Deflate.prototype.push.call(this, chunk, final);
  };
  Zlib2.prototype.p = function(c2, f) {
    var raw = dopt(c2, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);
    if (this.v)
      zlh(raw, this.o), this.v = 0;
    if (f)
      wbytes(raw, raw.length - 4, this.c.d());
    this.ondata(raw, f);
  };
  Zlib2.prototype.flush = function() {
    Deflate.prototype.flush.call(this);
  };
  return Zlib2;
}();
function zlibSync(data2, opts) {
  if (!opts)
    opts = {};
  var a2 = adler();
  a2.p(data2);
  var d = dopt(data2, opts, opts.dictionary ? 6 : 2, 4);
  return zlh(d, opts), wbytes(d, d.length - 4, a2.d()), d;
}
var Unzlib = function() {
  function Unzlib2(opts, cb) {
    Inflate.call(this, opts, cb);
    this.v = opts && opts.dictionary ? 2 : 1;
  }
  Unzlib2.prototype.push = function(chunk, final) {
    Inflate.prototype.e.call(this, chunk);
    if (this.v) {
      if (this.p.length < 6 && !final)
        return;
      this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
    }
    if (final) {
      if (this.p.length < 4)
        err(6, "invalid zlib data");
      this.p = this.p.subarray(0, -4);
    }
    Inflate.prototype.c.call(this, final);
  };
  return Unzlib2;
}();
var AsyncUnzlib = /* @__PURE__ */ function() {
  function AsyncUnzlib2(opts, cb) {
    astrmify([
      bInflt,
      zule,
      function() {
        return [astrm, Inflate, Unzlib];
      }
    ], this, StrmOpt.call(this, opts, cb), function(ev) {
      var strm = new Unzlib(ev.data);
      onmessage = astrm(strm);
    }, 11, 0);
  }
  return AsyncUnzlib2;
}();
function unzlibSync(data2, opts) {
  return inflt(data2.subarray(zls(data2, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
var Decompress = function() {
  function Decompress2(opts, cb) {
    this.o = StrmOpt.call(this, opts, cb) || {};
    this.G = Gunzip;
    this.I = Inflate;
    this.Z = Unzlib;
  }
  Decompress2.prototype.i = function() {
    var _this = this;
    this.s.ondata = function(dat, final) {
      _this.ondata(dat, final);
    };
  };
  Decompress2.prototype.push = function(chunk, final) {
    if (!this.ondata)
      err(5);
    if (!this.s) {
      if (this.p && this.p.length) {
        var n2 = new u8(this.p.length + chunk.length);
        n2.set(this.p), n2.set(chunk, this.p.length);
      } else
        this.p = chunk;
      if (this.p.length > 2) {
        this.s = this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8 ? new this.G(this.o) : (this.p[0] & 15) != 8 || this.p[0] >> 4 > 7 || (this.p[0] << 8 | this.p[1]) % 31 ? new this.I(this.o) : new this.Z(this.o);
        this.i();
        this.s.push(this.p, final);
        this.p = null;
      }
    } else
      this.s.push(chunk, final);
  };
  return Decompress2;
}();
var AsyncDecompress = function() {
  function AsyncDecompress2(opts, cb) {
    Decompress.call(this, opts, cb);
    this.queuedSize = 0;
    this.G = AsyncGunzip;
    this.I = AsyncInflate;
    this.Z = AsyncUnzlib;
  }
  AsyncDecompress2.prototype.i = function() {
    var _this = this;
    this.s.ondata = function(err2, dat, final) {
      _this.ondata(err2, dat, final);
    };
    this.s.ondrain = function(size2) {
      _this.queuedSize -= size2;
      if (_this.ondrain)
        _this.ondrain(size2);
    };
  };
  AsyncDecompress2.prototype.push = function(chunk, final) {
    this.queuedSize += chunk.length;
    Decompress.prototype.push.call(this, chunk, final);
  };
  return AsyncDecompress2;
}();
var fltn = function(d, p, t3, o) {
  for (var k2 in d) {
    var val2 = d[k2], n2 = p + k2, op = o;
    if (Array.isArray(val2))
      op = mrg(o, val2[1]), val2 = val2[0];
    if (val2 instanceof u8)
      t3[n2] = [val2, op];
    else {
      t3[n2 += "/"] = [new u8(0), op];
      fltn(val2, n2, t3, o);
    }
  }
};
var te = typeof TextEncoder != "undefined" && new TextEncoder();
var td = typeof TextDecoder != "undefined" && new TextDecoder();
var tds = 0;
try {
  td.decode(et, { stream: true });
  tds = 1;
} catch (e) {
}
var dutf8 = function(d) {
  for (var r = "", i = 0; ; ) {
    var c2 = d[i++];
    var eb = (c2 > 127) + (c2 > 223) + (c2 > 239);
    if (i + eb > d.length)
      return { s: r, r: slc(d, i - 1) };
    if (!eb)
      r += String.fromCharCode(c2);
    else if (eb == 3) {
      c2 = ((c2 & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | d[i++] & 63) - 65536, r += String.fromCharCode(55296 | c2 >> 10, 56320 | c2 & 1023);
    } else if (eb & 1)
      r += String.fromCharCode((c2 & 31) << 6 | d[i++] & 63);
    else
      r += String.fromCharCode((c2 & 15) << 12 | (d[i++] & 63) << 6 | d[i++] & 63);
  }
};
var DecodeUTF8 = function() {
  function DecodeUTF82(cb) {
    this.ondata = cb;
    if (tds)
      this.t = new TextDecoder();
    else
      this.p = et;
  }
  DecodeUTF82.prototype.push = function(chunk, final) {
    if (!this.ondata)
      err(5);
    final = !!final;
    if (this.t) {
      this.ondata(this.t.decode(chunk, { stream: true }), final);
      if (final) {
        if (this.t.decode().length)
          err(8);
        this.t = null;
      }
      return;
    }
    if (!this.p)
      err(4);
    var dat = new u8(this.p.length + chunk.length);
    dat.set(this.p);
    dat.set(chunk, this.p.length);
    var _a3 = dutf8(dat), s = _a3.s, r = _a3.r;
    if (final) {
      if (r.length)
        err(8);
      this.p = null;
    } else
      this.p = r;
    this.ondata(s, final);
  };
  return DecodeUTF82;
}();
var EncodeUTF8 = function() {
  function EncodeUTF82(cb) {
    this.ondata = cb;
  }
  EncodeUTF82.prototype.push = function(chunk, final) {
    if (!this.ondata)
      err(5);
    if (this.d)
      err(4);
    this.ondata(strToU8(chunk), this.d = final || false);
  };
  return EncodeUTF82;
}();
function strToU8(str, latin1) {
  if (latin1) {
    var ar_1 = new u8(str.length);
    for (var i = 0; i < str.length; ++i)
      ar_1[i] = str.charCodeAt(i);
    return ar_1;
  }
  if (te)
    return te.encode(str);
  var l2 = str.length;
  var ar = new u8(str.length + (str.length >> 1));
  var ai = 0;
  var w = function(v) {
    ar[ai++] = v;
  };
  for (var i = 0; i < l2; ++i) {
    if (ai + 5 > ar.length) {
      var n2 = new u8(ai + 8 + (l2 - i << 1));
      n2.set(ar);
      ar = n2;
    }
    var c2 = str.charCodeAt(i);
    if (c2 < 128 || latin1)
      w(c2);
    else if (c2 < 2048)
      w(192 | c2 >> 6), w(128 | c2 & 63);
    else if (c2 > 55295 && c2 < 57344)
      c2 = 65536 + (c2 & 1023 << 10) | str.charCodeAt(++i) & 1023, w(240 | c2 >> 18), w(128 | c2 >> 12 & 63), w(128 | c2 >> 6 & 63), w(128 | c2 & 63);
    else
      w(224 | c2 >> 12), w(128 | c2 >> 6 & 63), w(128 | c2 & 63);
  }
  return slc(ar, 0, ai);
}
function strFromU8(dat, latin1) {
  if (latin1) {
    var r = "";
    for (var i = 0; i < dat.length; i += 16384)
      r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
    return r;
  } else if (td) {
    return td.decode(dat);
  } else {
    var _a3 = dutf8(dat), s = _a3.s, r = _a3.r;
    if (r.length)
      err(8);
    return s;
  }
}
var dbf = function(l2) {
  return l2 == 1 ? 3 : l2 < 6 ? 2 : l2 == 9 ? 1 : 0;
};
var slzh = function(d, b3) {
  return b3 + 30 + b2(d, b3 + 26) + b2(d, b3 + 28);
};
var zh = function(d, b3, z) {
  var fnl = b2(d, b3 + 28), fn = strFromU8(d.subarray(b3 + 46, b3 + 46 + fnl), !(b2(d, b3 + 8) & 2048)), es = b3 + 46 + fnl, bs = b4(d, b3 + 20);
  var _a3 = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b3 + 24), b4(d, b3 + 42)], sc = _a3[0], su = _a3[1], off = _a3[2];
  return [b2(d, b3 + 10), sc, su, fn, es + b2(d, b3 + 30) + b2(d, b3 + 32), off];
};
var z64e = function(d, b3) {
  for (; b2(d, b3) != 1; b3 += 4 + b2(d, b3 + 2))
    ;
  return [b8(d, b3 + 12), b8(d, b3 + 4), b8(d, b3 + 20)];
};
var exfl = function(ex) {
  var le = 0;
  if (ex) {
    for (var k2 in ex) {
      var l2 = ex[k2].length;
      if (l2 > 65535)
        err(9);
      le += l2 + 4;
    }
  }
  return le;
};
var wzh = function(d, b3, f, fn, u2, c2, ce2, co) {
  var fl2 = fn.length, ex = f.extra, col = co && co.length;
  var exl = exfl(ex);
  wbytes(d, b3, ce2 != null ? 33639248 : 67324752), b3 += 4;
  if (ce2 != null)
    d[b3++] = 20, d[b3++] = f.os;
  d[b3] = 20, b3 += 2;
  d[b3++] = f.flag << 1 | (c2 < 0 && 8), d[b3++] = u2 && 8;
  d[b3++] = f.compression & 255, d[b3++] = f.compression >> 8;
  var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
  if (y < 0 || y > 119)
    err(10);
  wbytes(d, b3, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b3 += 4;
  if (c2 != -1) {
    wbytes(d, b3, f.crc);
    wbytes(d, b3 + 4, c2 < 0 ? -c2 - 2 : c2);
    wbytes(d, b3 + 8, f.size);
  }
  wbytes(d, b3 + 12, fl2);
  wbytes(d, b3 + 14, exl), b3 += 16;
  if (ce2 != null) {
    wbytes(d, b3, col);
    wbytes(d, b3 + 6, f.attrs);
    wbytes(d, b3 + 10, ce2), b3 += 14;
  }
  d.set(fn, b3);
  b3 += fl2;
  if (exl) {
    for (var k2 in ex) {
      var exf = ex[k2], l2 = exf.length;
      wbytes(d, b3, +k2);
      wbytes(d, b3 + 2, l2);
      d.set(exf, b3 + 4), b3 += 4 + l2;
    }
  }
  if (col)
    d.set(co, b3), b3 += col;
  return b3;
};
var wzf = function(o, b3, c2, d, e) {
  wbytes(o, b3, 101010256);
  wbytes(o, b3 + 8, c2);
  wbytes(o, b3 + 10, c2);
  wbytes(o, b3 + 12, d);
  wbytes(o, b3 + 16, e);
};
var ZipPassThrough = function() {
  function ZipPassThrough2(filename) {
    this.filename = filename;
    this.c = crc();
    this.size = 0;
    this.compression = 0;
  }
  ZipPassThrough2.prototype.process = function(chunk, final) {
    this.ondata(null, chunk, final);
  };
  ZipPassThrough2.prototype.push = function(chunk, final) {
    if (!this.ondata)
      err(5);
    this.c.p(chunk);
    this.size += chunk.length;
    if (final)
      this.crc = this.c.d();
    this.process(chunk, final || false);
  };
  return ZipPassThrough2;
}();
var ZipDeflate = function() {
  function ZipDeflate2(filename, opts) {
    var _this = this;
    if (!opts)
      opts = {};
    ZipPassThrough.call(this, filename);
    this.d = new Deflate(opts, function(dat, final) {
      _this.ondata(null, dat, final);
    });
    this.compression = 8;
    this.flag = dbf(opts.level);
  }
  ZipDeflate2.prototype.process = function(chunk, final) {
    try {
      this.d.push(chunk, final);
    } catch (e) {
      this.ondata(e, null, final);
    }
  };
  ZipDeflate2.prototype.push = function(chunk, final) {
    ZipPassThrough.prototype.push.call(this, chunk, final);
  };
  return ZipDeflate2;
}();
var AsyncZipDeflate = function() {
  function AsyncZipDeflate2(filename, opts) {
    var _this = this;
    if (!opts)
      opts = {};
    ZipPassThrough.call(this, filename);
    this.d = new AsyncDeflate(opts, function(err2, dat, final) {
      _this.ondata(err2, dat, final);
    });
    this.compression = 8;
    this.flag = dbf(opts.level);
    this.terminate = this.d.terminate;
  }
  AsyncZipDeflate2.prototype.process = function(chunk, final) {
    this.d.push(chunk, final);
  };
  AsyncZipDeflate2.prototype.push = function(chunk, final) {
    ZipPassThrough.prototype.push.call(this, chunk, final);
  };
  return AsyncZipDeflate2;
}();
var Zip = function() {
  function Zip2(cb) {
    this.ondata = cb;
    this.u = [];
    this.d = 1;
  }
  Zip2.prototype.add = function(file) {
    var _this = this;
    if (!this.ondata)
      err(5);
    if (this.d & 2)
      this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);
    else {
      var f = strToU8(file.filename), fl_1 = f.length;
      var com = file.comment, o = com && strToU8(com);
      var u2 = fl_1 != file.filename.length || o && com.length != o.length;
      var hl_1 = fl_1 + exfl(file.extra) + 30;
      if (fl_1 > 65535)
        this.ondata(err(11, 0, 1), null, false);
      var header = new u8(hl_1);
      wzh(header, 0, file, f, u2, -1);
      var chks_1 = [header];
      var pAll_1 = function() {
        for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {
          var chk = chks_2[_i];
          _this.ondata(null, chk, false);
        }
        chks_1 = [];
      };
      var tr_1 = this.d;
      this.d = 0;
      var ind_1 = this.u.length;
      var uf_1 = mrg(file, {
        f,
        u: u2,
        o,
        t: function() {
          if (file.terminate)
            file.terminate();
        },
        r: function() {
          pAll_1();
          if (tr_1) {
            var nxt = _this.u[ind_1 + 1];
            if (nxt)
              nxt.r();
            else
              _this.d = 1;
          }
          tr_1 = 1;
        }
      });
      var cl_1 = 0;
      file.ondata = function(err2, dat, final) {
        if (err2) {
          _this.ondata(err2, dat, final);
          _this.terminate();
        } else {
          cl_1 += dat.length;
          chks_1.push(dat);
          if (final) {
            var dd = new u8(16);
            wbytes(dd, 0, 134695760);
            wbytes(dd, 4, file.crc);
            wbytes(dd, 8, cl_1);
            wbytes(dd, 12, file.size);
            chks_1.push(dd);
            uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;
            if (tr_1)
              uf_1.r();
            tr_1 = 1;
          } else if (tr_1)
            pAll_1();
        }
      };
      this.u.push(uf_1);
    }
  };
  Zip2.prototype.end = function() {
    var _this = this;
    if (this.d & 2) {
      this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
      return;
    }
    if (this.d)
      this.e();
    else
      this.u.push({
        r: function() {
          if (!(_this.d & 1))
            return;
          _this.u.splice(-1, 1);
          _this.e();
        },
        t: function() {
        }
      });
    this.d = 3;
  };
  Zip2.prototype.e = function() {
    var bt = 0, l2 = 0, tl = 0;
    for (var _i = 0, _a3 = this.u; _i < _a3.length; _i++) {
      var f = _a3[_i];
      tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
    }
    var out = new u8(tl + 22);
    for (var _b3 = 0, _c = this.u; _b3 < _c.length; _b3++) {
      var f = _c[_b3];
      wzh(out, bt, f, f.f, f.u, -f.c - 2, l2, f.o);
      bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l2 += f.b;
    }
    wzf(out, bt, this.u.length, tl, l2);
    this.ondata(null, out, true);
    this.d = 2;
  };
  Zip2.prototype.terminate = function() {
    for (var _i = 0, _a3 = this.u; _i < _a3.length; _i++) {
      var f = _a3[_i];
      f.t();
    }
    this.d = 2;
  };
  return Zip2;
}();
function zipSync(data2, opts) {
  if (!opts)
    opts = {};
  var r = {};
  var files = [];
  fltn(data2, "", r, opts);
  var o = 0;
  var tot = 0;
  for (var fn in r) {
    var _a3 = r[fn], file = _a3[0], p = _a3[1];
    var compression = p.level == 0 ? 0 : 8;
    var f = strToU8(fn), s = f.length;
    var com = p.comment, m = com && strToU8(com), ms = m && m.length;
    var exl = exfl(p.extra);
    if (s > 65535)
      err(11);
    var d = compression ? deflateSync(file, p) : file, l2 = d.length;
    var c2 = crc();
    c2.p(file);
    files.push(mrg(p, {
      size: file.length,
      crc: c2.d(),
      c: d,
      f,
      m,
      u: s != fn.length || m && com.length != ms,
      o,
      compression
    }));
    o += 30 + s + exl + l2;
    tot += 76 + 2 * (s + exl) + (ms || 0) + l2;
  }
  var out = new u8(tot + 22), oe = o, cdl = tot - o;
  for (var i = 0; i < files.length; ++i) {
    var f = files[i];
    wzh(out, f.o, f, f.f, f.u, f.c.length);
    var badd = 30 + f.f.length + exfl(f.extra);
    out.set(f.c, f.o + badd);
    wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
  }
  wzf(out, o, files.length, cdl, oe);
  return out;
}
var UnzipPassThrough = function() {
  function UnzipPassThrough2() {
  }
  UnzipPassThrough2.prototype.push = function(data2, final) {
    this.ondata(null, data2, final);
  };
  UnzipPassThrough2.compression = 0;
  return UnzipPassThrough2;
}();
var UnzipInflate = function() {
  function UnzipInflate2() {
    var _this = this;
    this.i = new Inflate(function(dat, final) {
      _this.ondata(null, dat, final);
    });
  }
  UnzipInflate2.prototype.push = function(data2, final) {
    try {
      this.i.push(data2, final);
    } catch (e) {
      this.ondata(e, null, final);
    }
  };
  UnzipInflate2.compression = 8;
  return UnzipInflate2;
}();
var AsyncUnzipInflate = function() {
  function AsyncUnzipInflate2(_, sz) {
    var _this = this;
    if (sz < 32e4) {
      this.i = new Inflate(function(dat, final) {
        _this.ondata(null, dat, final);
      });
    } else {
      this.i = new AsyncInflate(function(err2, dat, final) {
        _this.ondata(err2, dat, final);
      });
      this.terminate = this.i.terminate;
    }
  }
  AsyncUnzipInflate2.prototype.push = function(data2, final) {
    if (this.i.terminate)
      data2 = slc(data2, 0);
    this.i.push(data2, final);
  };
  AsyncUnzipInflate2.compression = 8;
  return AsyncUnzipInflate2;
}();
var Unzip = function() {
  function Unzip2(cb) {
    this.onfile = cb;
    this.k = [];
    this.o = {
      0: UnzipPassThrough
    };
    this.p = et;
  }
  Unzip2.prototype.push = function(chunk, final) {
    var _this = this;
    if (!this.onfile)
      err(5);
    if (!this.p)
      err(4);
    if (this.c > 0) {
      var len = Math.min(this.c, chunk.length);
      var toAdd = chunk.subarray(0, len);
      this.c -= len;
      if (this.d)
        this.d.push(toAdd, !this.c);
      else
        this.k[0].push(toAdd);
      chunk = chunk.subarray(len);
      if (chunk.length)
        return this.push(chunk, final);
    } else {
      var f = 0, i = 0, is = void 0, buf = void 0;
      if (!this.p.length)
        buf = chunk;
      else if (!chunk.length)
        buf = this.p;
      else {
        buf = new u8(this.p.length + chunk.length);
        buf.set(this.p), buf.set(chunk, this.p.length);
      }
      var l2 = buf.length, oc = this.c, add2 = oc && this.d;
      var _loop_2 = function() {
        var _a3;
        var sig = b4(buf, i);
        if (sig == 67324752) {
          f = 1, is = i;
          this_1.d = null;
          this_1.c = 0;
          var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u2 = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);
          if (l2 > i + 30 + fnl + es) {
            var chks_3 = [];
            this_1.k.unshift(chks_3);
            f = 2;
            var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);
            var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u2);
            if (sc_1 == 4294967295) {
              _a3 = dd ? [-2] : z64e(buf, i), sc_1 = _a3[0], su_1 = _a3[1];
            } else if (dd)
              sc_1 = -1;
            i += es;
            this_1.c = sc_1;
            var d_1;
            var file_1 = {
              name: fn_1,
              compression: cmp_1,
              start: function() {
                if (!file_1.ondata)
                  err(5);
                if (!sc_1)
                  file_1.ondata(null, et, true);
                else {
                  var ctr = _this.o[cmp_1];
                  if (!ctr)
                    file_1.ondata(err(14, "unknown compression type " + cmp_1, 1), null, false);
                  d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
                  d_1.ondata = function(err2, dat3, final2) {
                    file_1.ondata(err2, dat3, final2);
                  };
                  for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {
                    var dat2 = chks_4[_i];
                    d_1.push(dat2, false);
                  }
                  if (_this.k[0] == chks_3 && _this.c)
                    _this.d = d_1;
                  else
                    d_1.push(et, true);
                }
              },
              terminate: function() {
                if (d_1 && d_1.terminate)
                  d_1.terminate();
              }
            };
            if (sc_1 >= 0)
              file_1.size = sc_1, file_1.originalSize = su_1;
            this_1.onfile(file_1);
          }
          return "break";
        } else if (oc) {
          if (sig == 134695760) {
            is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
            return "break";
          } else if (sig == 33639248) {
            is = i -= 4, f = 3, this_1.c = 0;
            return "break";
          }
        }
      };
      var this_1 = this;
      for (; i < l2 - 4; ++i) {
        var state_1 = _loop_2();
        if (state_1 === "break")
          break;
      }
      this.p = et;
      if (oc < 0) {
        var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 134695760 && 4)) : buf.subarray(0, i);
        if (add2)
          add2.push(dat, !!f);
        else
          this.k[+(f == 2)].push(dat);
      }
      if (f & 2)
        return this.push(buf.subarray(i), final);
      this.p = buf.subarray(i);
    }
    if (final) {
      if (this.c)
        err(13);
      this.p = null;
    }
  };
  Unzip2.prototype.register = function(decoder) {
    this.o[decoder.compression] = decoder;
  };
  return Unzip2;
}();
function unzipSync(data2, opts) {
  var files = {};
  var e = data2.length - 22;
  for (; b4(data2, e) != 101010256; --e) {
    if (!e || data2.length - e > 65558)
      err(13);
  }
  ;
  var c2 = b2(data2, e + 8);
  if (!c2)
    return {};
  var o = b4(data2, e + 16);
  var z = o == 4294967295 || c2 == 65535;
  if (z) {
    var ze = b4(data2, e - 12);
    z = b4(data2, ze) == 101075792;
    if (z) {
      c2 = b4(data2, ze + 32);
      o = b4(data2, ze + 48);
    }
  }
  var fltr = opts && opts.filter;
  for (var i = 0; i < c2; ++i) {
    var _a3 = zh(data2, o, z), c_2 = _a3[0], sc = _a3[1], su = _a3[2], fn = _a3[3], no = _a3[4], off = _a3[5], b3 = slzh(data2, off);
    o = no;
    if (!fltr || fltr({
      name: fn,
      size: sc,
      originalSize: su,
      compression: c_2
    })) {
      if (!c_2)
        files[fn] = slc(data2, b3, b3 + sc);
      else if (c_2 == 8)
        files[fn] = inflateSync(data2.subarray(b3, b3 + sc), { out: new u8(su) });
      else
        err(14, "unknown compression type " + c_2);
    }
  }
  return files;
}

// node_modules/three/examples/jsm/exporters/EXRExporter.js
var textEncoder = new TextEncoder();
var NO_COMPRESSION = 0;
var ZIPS_COMPRESSION = 2;
var ZIP_COMPRESSION = 3;
var EXRExporter = class {
  /**
   * This method has two variants.
   *
   * - When exporting a data texture, it receives two parameters. The texture and the exporter options.
   * - When exporting a render target (e.g. a PMREM), it receives three parameters. The renderer, the
   * render target and the exporter options.
   *
   * @async
   * @param {(DataTexture|WebGPURenderer|WebGLRenderer)} arg1 - The data texture to export or a renderer.
   * @param {(EXRExporter~Options|RenderTarget)} arg2 - The exporter options or a render target.
   * @param {EXRExporter~Options} [arg3] - The exporter options.
   * @return {Promise<Uint8Array>} A Promise that resolves with the exported EXR.
   */
  async parse(arg1, arg2, arg3) {
    if (!arg1 || !(arg1.isWebGLRenderer || arg1.isWebGPURenderer || arg1.isDataTexture)) {
      throw Error("EXRExporter.parse: Unsupported first parameter, expected instance of WebGLRenderer, WebGPURenderer or DataTexture.");
    } else if (arg1.isWebGLRenderer || arg1.isWebGPURenderer) {
      const renderer2 = arg1, renderTarget = arg2, options = arg3;
      supportedRTT(renderTarget);
      const info = buildInfoRTT(renderTarget, options), dataBuffer = await getPixelData(renderer2, renderTarget, info), rawContentBuffer = reorganizeDataBuffer(dataBuffer, info), chunks = compressData(rawContentBuffer, info);
      return fillData(chunks, info);
    } else if (arg1.isDataTexture) {
      const texture = arg1, options = arg2;
      supportedDT(texture);
      const info = buildInfoDT(texture, options), dataBuffer = texture.image.data, rawContentBuffer = reorganizeDataBuffer(dataBuffer, info), chunks = compressData(rawContentBuffer, info);
      return fillData(chunks, info);
    }
  }
};
function supportedRTT(renderTarget) {
  if (!renderTarget || !renderTarget.isRenderTarget) {
    throw Error("EXRExporter.parse: Unsupported second parameter, expected instance of WebGLRenderTarget.");
  }
  if (renderTarget.isWebGLCubeRenderTarget || renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
    throw Error("EXRExporter.parse: Unsupported render target type, expected instance of WebGLRenderTarget.");
  }
  if (renderTarget.texture.type !== FloatType && renderTarget.texture.type !== HalfFloatType) {
    throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture type.");
  }
  if (renderTarget.texture.format !== RGBAFormat) {
    throw Error("EXRExporter.parse: Unsupported WebGLRenderTarget texture format, expected RGBAFormat.");
  }
}
function supportedDT(texture) {
  if (texture.type !== FloatType && texture.type !== HalfFloatType) {
    throw Error("EXRExporter.parse: Unsupported DataTexture texture type.");
  }
  if (texture.format !== RGBAFormat) {
    throw Error("EXRExporter.parse: Unsupported DataTexture texture format, expected RGBAFormat.");
  }
  if (!texture.image.data) {
    throw Error("EXRExporter.parse: Invalid DataTexture image data.");
  }
  if (texture.type === FloatType && texture.image.data.constructor.name !== "Float32Array") {
    throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Float32Array'.");
  }
  if (texture.type === HalfFloatType && texture.image.data.constructor.name !== "Uint16Array") {
    throw Error("EXRExporter.parse: DataTexture image data doesn't match type, expected 'Uint16Array'.");
  }
}
function buildInfoRTT(renderTarget, options = {}) {
  const compressionSizes = {
    0: 1,
    2: 1,
    3: 16
  };
  const WIDTH = renderTarget.width, HEIGHT = renderTarget.height, TYPE = renderTarget.texture.type, FORMAT = renderTarget.texture.format, COMPRESSION = options.compression !== void 0 ? options.compression : ZIP_COMPRESSION, EXPORTER_TYPE = options.type !== void 0 ? options.type : HalfFloatType, OUT_TYPE = EXPORTER_TYPE === FloatType ? 2 : 1, COMPRESSION_SIZE = compressionSizes[COMPRESSION], NUM_CHANNELS = 4;
  return {
    width: WIDTH,
    height: HEIGHT,
    type: TYPE,
    format: FORMAT,
    compression: COMPRESSION,
    blockLines: COMPRESSION_SIZE,
    dataType: OUT_TYPE,
    dataSize: 2 * OUT_TYPE,
    numBlocks: Math.ceil(HEIGHT / COMPRESSION_SIZE),
    numInputChannels: 4,
    numOutputChannels: NUM_CHANNELS
  };
}
function buildInfoDT(texture, options = {}) {
  const compressionSizes = {
    0: 1,
    2: 1,
    3: 16
  };
  const WIDTH = texture.image.width, HEIGHT = texture.image.height, TYPE = texture.type, FORMAT = texture.format, COMPRESSION = options.compression !== void 0 ? options.compression : ZIP_COMPRESSION, EXPORTER_TYPE = options.type !== void 0 ? options.type : HalfFloatType, OUT_TYPE = EXPORTER_TYPE === FloatType ? 2 : 1, COMPRESSION_SIZE = compressionSizes[COMPRESSION], NUM_CHANNELS = 4;
  return {
    width: WIDTH,
    height: HEIGHT,
    type: TYPE,
    format: FORMAT,
    compression: COMPRESSION,
    blockLines: COMPRESSION_SIZE,
    dataType: OUT_TYPE,
    dataSize: 2 * OUT_TYPE,
    numBlocks: Math.ceil(HEIGHT / COMPRESSION_SIZE),
    numInputChannels: 4,
    numOutputChannels: NUM_CHANNELS
  };
}
async function getPixelData(renderer2, rtt, info) {
  let dataBuffer;
  if (renderer2.isWebGLRenderer) {
    if (info.type === FloatType) {
      dataBuffer = new Float32Array(info.width * info.height * info.numInputChannels);
    } else {
      dataBuffer = new Uint16Array(info.width * info.height * info.numInputChannels);
    }
    await renderer2.readRenderTargetPixelsAsync(rtt, 0, 0, info.width, info.height, dataBuffer);
  } else {
    dataBuffer = await renderer2.readRenderTargetPixelsAsync(rtt, 0, 0, info.width, info.height);
  }
  return dataBuffer;
}
function reorganizeDataBuffer(inBuffer, info) {
  const w = info.width, h = info.height, dec = { r: 0, g: 0, b: 0, a: 0 }, offset = { value: 0 }, cOffset = info.numOutputChannels == 4 ? 1 : 0, getValue = info.type == FloatType ? getFloat32 : getFloat16, setValue = info.dataType == 1 ? setFloat16 : setFloat32, outBuffer = new Uint8Array(info.width * info.height * info.numOutputChannels * info.dataSize), dv = new DataView(outBuffer.buffer);
  for (let y = 0; y < h; ++y) {
    for (let x2 = 0; x2 < w; ++x2) {
      const i = y * w * 4 + x2 * 4;
      const r = getValue(inBuffer, i);
      const g3 = getValue(inBuffer, i + 1);
      const b3 = getValue(inBuffer, i + 2);
      const a2 = getValue(inBuffer, i + 3);
      const line2 = (h - y - 1) * w * (3 + cOffset) * info.dataSize;
      decodeLinear(dec, r, g3, b3, a2);
      offset.value = line2 + x2 * info.dataSize;
      setValue(dv, dec.a, offset);
      offset.value = line2 + cOffset * w * info.dataSize + x2 * info.dataSize;
      setValue(dv, dec.b, offset);
      offset.value = line2 + (1 + cOffset) * w * info.dataSize + x2 * info.dataSize;
      setValue(dv, dec.g, offset);
      offset.value = line2 + (2 + cOffset) * w * info.dataSize + x2 * info.dataSize;
      setValue(dv, dec.r, offset);
    }
  }
  return outBuffer;
}
function compressData(inBuffer, info) {
  let compress, tmpBuffer, sum2 = 0;
  const chunks = { data: new Array(), totalSize: 0 }, size2 = info.width * info.numOutputChannels * info.blockLines * info.dataSize;
  switch (info.compression) {
    case 0:
      compress = compressNONE;
      break;
    case 2:
    case 3:
      compress = compressZIP;
      break;
  }
  if (info.compression !== 0) {
    tmpBuffer = new Uint8Array(size2);
  }
  for (let i = 0; i < info.numBlocks; ++i) {
    const arr = inBuffer.subarray(size2 * i, size2 * (i + 1));
    const block = compress(arr, tmpBuffer);
    sum2 += block.length;
    chunks.data.push({ dataChunk: block, size: block.length });
  }
  chunks.totalSize = sum2;
  return chunks;
}
function compressNONE(data2) {
  return data2;
}
function compressZIP(data2, tmpBuffer) {
  let t1 = 0, t22 = Math.floor((data2.length + 1) / 2), s = 0;
  const stop = data2.length - 1;
  while (true) {
    if (s > stop) break;
    tmpBuffer[t1++] = data2[s++];
    if (s > stop) break;
    tmpBuffer[t22++] = data2[s++];
  }
  let p = tmpBuffer[0];
  for (let t3 = 1; t3 < tmpBuffer.length; t3++) {
    const d = tmpBuffer[t3] - p + (128 + 256);
    p = tmpBuffer[t3];
    tmpBuffer[t3] = d;
  }
  const deflate = zlibSync(tmpBuffer);
  return deflate;
}
function fillHeader(outBuffer, chunks, info) {
  const offset = { value: 0 };
  const dv = new DataView(outBuffer.buffer);
  setUint32(dv, 20000630, offset);
  setUint32(dv, 2, offset);
  setString(dv, "compression", offset);
  setString(dv, "compression", offset);
  setUint32(dv, 1, offset);
  setUint8(dv, info.compression, offset);
  setString(dv, "screenWindowCenter", offset);
  setString(dv, "v2f", offset);
  setUint32(dv, 8, offset);
  setUint32(dv, 0, offset);
  setUint32(dv, 0, offset);
  setString(dv, "screenWindowWidth", offset);
  setString(dv, "float", offset);
  setUint32(dv, 4, offset);
  setFloat32(dv, 1, offset);
  setString(dv, "pixelAspectRatio", offset);
  setString(dv, "float", offset);
  setUint32(dv, 4, offset);
  setFloat32(dv, 1, offset);
  setString(dv, "lineOrder", offset);
  setString(dv, "lineOrder", offset);
  setUint32(dv, 1, offset);
  setUint8(dv, 0, offset);
  setString(dv, "dataWindow", offset);
  setString(dv, "box2i", offset);
  setUint32(dv, 16, offset);
  setUint32(dv, 0, offset);
  setUint32(dv, 0, offset);
  setUint32(dv, info.width - 1, offset);
  setUint32(dv, info.height - 1, offset);
  setString(dv, "displayWindow", offset);
  setString(dv, "box2i", offset);
  setUint32(dv, 16, offset);
  setUint32(dv, 0, offset);
  setUint32(dv, 0, offset);
  setUint32(dv, info.width - 1, offset);
  setUint32(dv, info.height - 1, offset);
  setString(dv, "channels", offset);
  setString(dv, "chlist", offset);
  setUint32(dv, info.numOutputChannels * 18 + 1, offset);
  setString(dv, "A", offset);
  setUint32(dv, info.dataType, offset);
  offset.value += 4;
  setUint32(dv, 1, offset);
  setUint32(dv, 1, offset);
  setString(dv, "B", offset);
  setUint32(dv, info.dataType, offset);
  offset.value += 4;
  setUint32(dv, 1, offset);
  setUint32(dv, 1, offset);
  setString(dv, "G", offset);
  setUint32(dv, info.dataType, offset);
  offset.value += 4;
  setUint32(dv, 1, offset);
  setUint32(dv, 1, offset);
  setString(dv, "R", offset);
  setUint32(dv, info.dataType, offset);
  offset.value += 4;
  setUint32(dv, 1, offset);
  setUint32(dv, 1, offset);
  setUint8(dv, 0, offset);
  setUint8(dv, 0, offset);
  let sum2 = offset.value + info.numBlocks * 8;
  for (let i = 0; i < chunks.data.length; ++i) {
    setUint64(dv, sum2, offset);
    sum2 += chunks.data[i].size + 8;
  }
}
function fillData(chunks, info) {
  const TableSize = info.numBlocks * 8, HeaderSize = 259 + 18 * info.numOutputChannels, offset = { value: HeaderSize + TableSize }, outBuffer = new Uint8Array(HeaderSize + TableSize + chunks.totalSize + info.numBlocks * 8), dv = new DataView(outBuffer.buffer);
  fillHeader(outBuffer, chunks, info);
  for (let i = 0; i < chunks.data.length; ++i) {
    const data2 = chunks.data[i].dataChunk;
    const size2 = chunks.data[i].size;
    setUint32(dv, i * info.blockLines, offset);
    setUint32(dv, size2, offset);
    outBuffer.set(data2, offset.value);
    offset.value += size2;
  }
  return outBuffer;
}
function decodeLinear(dec, r, g3, b3, a2) {
  dec.r = r;
  dec.g = g3;
  dec.b = b3;
  dec.a = a2;
}
function setUint8(dv, value2, offset) {
  dv.setUint8(offset.value, value2);
  offset.value += 1;
}
function setUint32(dv, value2, offset) {
  dv.setUint32(offset.value, value2, true);
  offset.value += 4;
}
function setFloat16(dv, value2, offset) {
  dv.setUint16(offset.value, DataUtils.toHalfFloat(value2), true);
  offset.value += 2;
}
function setFloat32(dv, value2, offset) {
  dv.setFloat32(offset.value, value2, true);
  offset.value += 4;
}
function setUint64(dv, value2, offset) {
  dv.setBigUint64(offset.value, BigInt(value2), true);
  offset.value += 8;
}
function setString(dv, string, offset) {
  const tmp = textEncoder.encode(string + "\0");
  for (let i = 0; i < tmp.length; ++i) {
    setUint8(dv, tmp[i], offset);
  }
}
function decodeFloat16(binary) {
  const exponent = (binary & 31744) >> 10, fraction = binary & 1023;
  return (binary >> 15 ? -1 : 1) * (exponent ? exponent === 31 ? fraction ? NaN : Infinity : Math.pow(2, exponent - 15) * (1 + fraction / 1024) : 6103515625e-14 * (fraction / 1024));
}
function getFloat16(arr, i) {
  return decodeFloat16(arr[i]);
}
function getFloat32(arr, i) {
  return arr[i];
}

// node_modules/three/examples/jsm/exporters/GLTFExporter.js
var KHR_mesh_quantization_ExtraAttrTypes = {
  POSITION: [
    "byte",
    "byte normalized",
    "unsigned byte",
    "unsigned byte normalized",
    "short",
    "short normalized",
    "unsigned short",
    "unsigned short normalized"
  ],
  NORMAL: [
    "byte normalized",
    "short normalized"
  ],
  TANGENT: [
    "byte normalized",
    "short normalized"
  ],
  TEXCOORD: [
    "byte",
    "byte normalized",
    "unsigned byte",
    "short",
    "short normalized",
    "unsigned short"
  ]
};
var GLTFExporter = class {
  /**
   * Constructs a new glTF exporter.
   */
  constructor() {
    this.textureUtils = null;
    this.pluginCallbacks = [];
    this.register(function(writer) {
      return new GLTFLightExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsUnlitExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsTransmissionExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsVolumeExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsIorExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsSpecularExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsClearcoatExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsDispersionExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsIridescenceExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsSheenExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsAnisotropyExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsEmissiveStrengthExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMaterialsBumpExtension(writer);
    });
    this.register(function(writer) {
      return new GLTFMeshGpuInstancing(writer);
    });
  }
  /**
   * Registers a plugin callback. This API is internally used to implement the various
   * glTF extensions but can also used by third-party code to add additional logic
   * to the exporter.
   *
   * @param {function(writer:GLTFWriter)} callback - The callback function to register.
   * @return {GLTFExporter} A reference to this exporter.
   */
  register(callback) {
    if (this.pluginCallbacks.indexOf(callback) === -1) {
      this.pluginCallbacks.push(callback);
    }
    return this;
  }
  /**
   * Unregisters a plugin callback.
   *
   * @param {Function} callback - The callback function to unregister.
   * @return {GLTFExporter} A reference to this exporter.
   */
  unregister(callback) {
    if (this.pluginCallbacks.indexOf(callback) !== -1) {
      this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1);
    }
    return this;
  }
  /**
   * Sets the texture utils for this exporter. Only relevant when compressed textures have to be exported.
   *
   * Depending on whether you use {@link WebGLRenderer} or {@link WebGPURenderer}, you must inject the
   * corresponding texture utils {@link WebGLTextureUtils} or {@link WebGPUTextureUtils}.
   *
   * @param {WebGLTextureUtils|WebGPUTextureUtils} utils - The texture utils.
   * @return {GLTFExporter} A reference to this exporter.
   */
  setTextureUtils(utils) {
    this.textureUtils = utils;
    return this;
  }
  /**
   * Parses the given scenes and generates the glTF output.
   *
   * @param {Scene|Array<Scene>} input - A scene or an array of scenes.
   * @param {GLTFExporter~OnDone} onDone - A callback function that is executed when the export has finished.
   * @param {GLTFExporter~OnError} onError - A callback function that is executed when an error happens.
   * @param {GLTFExporter~Options} options - options
   */
  parse(input, onDone, onError, options) {
    const writer = new GLTFWriter();
    const plugins = [];
    for (let i = 0, il = this.pluginCallbacks.length; i < il; i++) {
      plugins.push(this.pluginCallbacks[i](writer));
    }
    writer.setPlugins(plugins);
    writer.setTextureUtils(this.textureUtils);
    writer.writeAsync(input, onDone, options).catch(onError);
  }
  /**
   * Async version of {@link GLTFExporter#parse}.
   *
   * @param {Scene|Array<Scene>} input - A scene or an array of scenes.
   * @param {GLTFExporter~Options} options - options.
   * @return {Promise<ArrayBuffer|string>} A Promise that resolved with the exported glTF data.
   */
  parseAsync(input, options) {
    const scope = this;
    return new Promise(function(resolve, reject2) {
      scope.parse(input, resolve, reject2, options);
    });
  }
};
var WEBGL_CONSTANTS = {
  POINTS: 0,
  LINES: 1,
  LINE_LOOP: 2,
  LINE_STRIP: 3,
  TRIANGLES: 4,
  TRIANGLE_STRIP: 5,
  TRIANGLE_FAN: 6,
  BYTE: 5120,
  UNSIGNED_BYTE: 5121,
  SHORT: 5122,
  UNSIGNED_SHORT: 5123,
  INT: 5124,
  UNSIGNED_INT: 5125,
  FLOAT: 5126,
  ARRAY_BUFFER: 34962,
  ELEMENT_ARRAY_BUFFER: 34963,
  NEAREST: 9728,
  LINEAR: 9729,
  NEAREST_MIPMAP_NEAREST: 9984,
  LINEAR_MIPMAP_NEAREST: 9985,
  NEAREST_MIPMAP_LINEAR: 9986,
  LINEAR_MIPMAP_LINEAR: 9987,
  CLAMP_TO_EDGE: 33071,
  MIRRORED_REPEAT: 33648,
  REPEAT: 10497
};
var KHR_MESH_QUANTIZATION = "KHR_mesh_quantization";
var THREE_TO_WEBGL = {};
THREE_TO_WEBGL[NearestFilter] = WEBGL_CONSTANTS.NEAREST;
THREE_TO_WEBGL[NearestMipmapNearestFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
THREE_TO_WEBGL[NearestMipmapLinearFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
THREE_TO_WEBGL[LinearFilter] = WEBGL_CONSTANTS.LINEAR;
THREE_TO_WEBGL[LinearMipmapNearestFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
THREE_TO_WEBGL[LinearMipmapLinearFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
THREE_TO_WEBGL[ClampToEdgeWrapping] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
THREE_TO_WEBGL[RepeatWrapping] = WEBGL_CONSTANTS.REPEAT;
THREE_TO_WEBGL[MirroredRepeatWrapping] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
var PATH_PROPERTIES = {
  scale: "scale",
  position: "translation",
  quaternion: "rotation",
  morphTargetInfluences: "weights"
};
var DEFAULT_SPECULAR_COLOR = new Color();
var GLB_HEADER_BYTES = 12;
var GLB_HEADER_MAGIC = 1179937895;
var GLB_VERSION = 2;
var GLB_CHUNK_PREFIX_BYTES = 8;
var GLB_CHUNK_TYPE_JSON = 1313821514;
var GLB_CHUNK_TYPE_BIN = 5130562;
function equalArray(array1, array2) {
  return array1.length === array2.length && array1.every(function(element, index2) {
    return element === array2[index2];
  });
}
function stringToArrayBuffer(text2) {
  return new TextEncoder().encode(text2).buffer;
}
function isIdentityMatrix(matrix2) {
  return equalArray(matrix2.elements, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
}
function getMinMax(attribute, start, count) {
  const output = {
    min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY),
    max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY)
  };
  for (let i = start; i < start + count; i++) {
    for (let a2 = 0; a2 < attribute.itemSize; a2++) {
      let value2;
      if (attribute.itemSize > 4) {
        value2 = attribute.array[i * attribute.itemSize + a2];
      } else {
        if (a2 === 0) value2 = attribute.getX(i);
        else if (a2 === 1) value2 = attribute.getY(i);
        else if (a2 === 2) value2 = attribute.getZ(i);
        else if (a2 === 3) value2 = attribute.getW(i);
        if (attribute.normalized === true) {
          value2 = MathUtils.normalize(value2, attribute.array);
        }
      }
      output.min[a2] = Math.min(output.min[a2], value2);
      output.max[a2] = Math.max(output.max[a2], value2);
    }
  }
  return output;
}
function getPaddedBufferSize(bufferSize) {
  return Math.ceil(bufferSize / 4) * 4;
}
function getPaddedArrayBuffer(arrayBuffer, paddingByte = 0) {
  const paddedLength = getPaddedBufferSize(arrayBuffer.byteLength);
  if (paddedLength !== arrayBuffer.byteLength) {
    const array = new Uint8Array(paddedLength);
    array.set(new Uint8Array(arrayBuffer));
    if (paddingByte !== 0) {
      for (let i = arrayBuffer.byteLength; i < paddedLength; i++) {
        array[i] = paddingByte;
      }
    }
    return array.buffer;
  }
  return arrayBuffer;
}
function getCanvas() {
  if (typeof document === "undefined" && typeof OffscreenCanvas !== "undefined") {
    return new OffscreenCanvas(1, 1);
  }
  return document.createElement("canvas");
}
function getToBlobPromise(canvas, mimeType) {
  if (canvas.toBlob !== void 0) {
    return new Promise((resolve) => canvas.toBlob(resolve, mimeType));
  }
  let quality;
  if (mimeType === "image/jpeg") {
    quality = 0.92;
  } else if (mimeType === "image/webp") {
    quality = 0.8;
  }
  return canvas.convertToBlob({
    type: mimeType,
    quality
  });
}
var GLTFWriter = class {
  constructor() {
    this.plugins = [];
    this.options = {};
    this.pending = [];
    this.buffers = [];
    this.byteOffset = 0;
    this.buffers = [];
    this.nodeMap = /* @__PURE__ */ new Map();
    this.skins = [];
    this.extensionsUsed = {};
    this.extensionsRequired = {};
    this.uids = /* @__PURE__ */ new Map();
    this.uid = 0;
    this.json = {
      asset: {
        version: "2.0",
        generator: "THREE.GLTFExporter r" + REVISION
      }
    };
    this.cache = {
      meshes: /* @__PURE__ */ new Map(),
      attributes: /* @__PURE__ */ new Map(),
      attributesNormalized: /* @__PURE__ */ new Map(),
      materials: /* @__PURE__ */ new Map(),
      textures: /* @__PURE__ */ new Map(),
      images: /* @__PURE__ */ new Map()
    };
    this.textureUtils = null;
  }
  setPlugins(plugins) {
    this.plugins = plugins;
  }
  setTextureUtils(utils) {
    this.textureUtils = utils;
  }
  /**
   * Parse scenes and generate GLTF output
   *
   * @param {Scene|Array<Scene>} input Scene or Array of THREE.Scenes
   * @param {Function} onDone Callback on completed
   * @param {Object} options options
   */
  async writeAsync(input, onDone, options = {}) {
    this.options = Object.assign({
      // default options
      binary: false,
      trs: false,
      onlyVisible: true,
      maxTextureSize: Infinity,
      animations: [],
      includeCustomExtensions: false
    }, options);
    if (this.options.animations.length > 0) {
      this.options.trs = true;
    }
    await this.processInputAsync(input);
    await Promise.all(this.pending);
    const writer = this;
    const buffers = writer.buffers;
    const json = writer.json;
    options = writer.options;
    const extensionsUsed = writer.extensionsUsed;
    const extensionsRequired = writer.extensionsRequired;
    const blob = new Blob(buffers, { type: "application/octet-stream" });
    const extensionsUsedList = Object.keys(extensionsUsed);
    const extensionsRequiredList = Object.keys(extensionsRequired);
    if (extensionsUsedList.length > 0) json.extensionsUsed = extensionsUsedList;
    if (extensionsRequiredList.length > 0) json.extensionsRequired = extensionsRequiredList;
    if (json.buffers && json.buffers.length > 0) json.buffers[0].byteLength = blob.size;
    if (options.binary === true) {
      const reader = new FileReader();
      reader.readAsArrayBuffer(blob);
      reader.onloadend = function() {
        const binaryChunk = getPaddedArrayBuffer(reader.result);
        const binaryChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES));
        binaryChunkPrefix.setUint32(0, binaryChunk.byteLength, true);
        binaryChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_BIN, true);
        const jsonChunk = getPaddedArrayBuffer(stringToArrayBuffer(JSON.stringify(json)), 32);
        const jsonChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES));
        jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true);
        jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true);
        const header = new ArrayBuffer(GLB_HEADER_BYTES);
        const headerView = new DataView(header);
        headerView.setUint32(0, GLB_HEADER_MAGIC, true);
        headerView.setUint32(4, GLB_VERSION, true);
        const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
        headerView.setUint32(8, totalByteLength, true);
        const glbBlob = new Blob([
          header,
          jsonChunkPrefix,
          jsonChunk,
          binaryChunkPrefix,
          binaryChunk
        ], { type: "application/octet-stream" });
        const glbReader = new FileReader();
        glbReader.readAsArrayBuffer(glbBlob);
        glbReader.onloadend = function() {
          onDone(glbReader.result);
        };
      };
    } else {
      if (json.buffers && json.buffers.length > 0) {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onloadend = function() {
          const base64data = reader.result;
          json.buffers[0].uri = base64data;
          onDone(json);
        };
      } else {
        onDone(json);
      }
    }
  }
  /**
   * Serializes a userData.
   *
   * @param {THREE.Object3D|THREE.Material} object
   * @param {Object} objectDef
   */
  serializeUserData(object, objectDef) {
    if (Object.keys(object.userData).length === 0) return;
    const options = this.options;
    const extensionsUsed = this.extensionsUsed;
    try {
      const json = JSON.parse(JSON.stringify(object.userData));
      if (options.includeCustomExtensions && json.gltfExtensions) {
        if (objectDef.extensions === void 0) objectDef.extensions = {};
        for (const extensionName in json.gltfExtensions) {
          objectDef.extensions[extensionName] = json.gltfExtensions[extensionName];
          extensionsUsed[extensionName] = true;
        }
        delete json.gltfExtensions;
      }
      if (Object.keys(json).length > 0) objectDef.extras = json;
    } catch (error) {
      console.warn("THREE.GLTFExporter: userData of '" + object.name + "' won't be serialized because of JSON.stringify error - " + error.message);
    }
  }
  /**
   * Returns ids for buffer attributes.
   *
   * @param {Object} attribute
   * @param {boolean} [isRelativeCopy=false]
   * @return {number} An integer
   */
  getUID(attribute, isRelativeCopy = false) {
    if (this.uids.has(attribute) === false) {
      const uids2 = /* @__PURE__ */ new Map();
      uids2.set(true, this.uid++);
      uids2.set(false, this.uid++);
      this.uids.set(attribute, uids2);
    }
    const uids = this.uids.get(attribute);
    return uids.get(isRelativeCopy);
  }
  /**
   * Checks if normal attribute values are normalized.
   *
   * @param {BufferAttribute} normal
   * @returns {boolean}
   */
  isNormalizedNormalAttribute(normal) {
    const cache = this.cache;
    if (cache.attributesNormalized.has(normal)) return false;
    const v = new Vector3();
    for (let i = 0, il = normal.count; i < il; i++) {
      if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1) > 5e-4) return false;
    }
    return true;
  }
  /**
   * Creates normalized normal buffer attribute.
   *
   * @param {BufferAttribute} normal
   * @returns {BufferAttribute}
   *
   */
  createNormalizedNormalAttribute(normal) {
    const cache = this.cache;
    if (cache.attributesNormalized.has(normal)) return cache.attributesNormalized.get(normal);
    const attribute = normal.clone();
    const v = new Vector3();
    for (let i = 0, il = attribute.count; i < il; i++) {
      v.fromBufferAttribute(attribute, i);
      if (v.x === 0 && v.y === 0 && v.z === 0) {
        v.setX(1);
      } else {
        v.normalize();
      }
      attribute.setXYZ(i, v.x, v.y, v.z);
    }
    cache.attributesNormalized.set(normal, attribute);
    return attribute;
  }
  /**
   * Applies a texture transform, if present, to the map definition. Requires
   * the KHR_texture_transform extension.
   *
   * @param {Object} mapDef
   * @param {THREE.Texture} texture
   */
  applyTextureTransform(mapDef, texture) {
    let didTransform = false;
    const transformDef = {};
    if (texture.offset.x !== 0 || texture.offset.y !== 0) {
      transformDef.offset = texture.offset.toArray();
      didTransform = true;
    }
    if (texture.rotation !== 0) {
      transformDef.rotation = texture.rotation;
      didTransform = true;
    }
    if (texture.repeat.x !== 1 || texture.repeat.y !== 1) {
      transformDef.scale = texture.repeat.toArray();
      didTransform = true;
    }
    if (didTransform) {
      mapDef.extensions = mapDef.extensions || {};
      mapDef.extensions["KHR_texture_transform"] = transformDef;
      this.extensionsUsed["KHR_texture_transform"] = true;
    }
  }
  async buildMetalRoughTextureAsync(metalnessMap, roughnessMap) {
    if (metalnessMap === roughnessMap) return metalnessMap;
    function getEncodingConversion(map2) {
      if (map2.colorSpace === SRGBColorSpace) {
        return function SRGBToLinear(c2) {
          return c2 < 0.04045 ? c2 * 0.0773993808 : Math.pow(c2 * 0.9478672986 + 0.0521327014, 2.4);
        };
      }
      return function LinearToLinear(c2) {
        return c2;
      };
    }
    if (metalnessMap instanceof CompressedTexture) {
      metalnessMap = await this.decompressTextureAsync(metalnessMap);
    }
    if (roughnessMap instanceof CompressedTexture) {
      roughnessMap = await this.decompressTextureAsync(roughnessMap);
    }
    const metalness = metalnessMap ? metalnessMap.image : null;
    const roughness = roughnessMap ? roughnessMap.image : null;
    const width2 = Math.max(metalness ? metalness.width : 0, roughness ? roughness.width : 0);
    const height2 = Math.max(metalness ? metalness.height : 0, roughness ? roughness.height : 0);
    const canvas = getCanvas();
    canvas.width = width2;
    canvas.height = height2;
    const context = canvas.getContext("2d", {
      willReadFrequently: true
    });
    context.fillStyle = "#00ffff";
    context.fillRect(0, 0, width2, height2);
    const composite = context.getImageData(0, 0, width2, height2);
    if (metalness) {
      context.drawImage(metalness, 0, 0, width2, height2);
      const convert = getEncodingConversion(metalnessMap);
      const data2 = context.getImageData(0, 0, width2, height2).data;
      for (let i = 2; i < data2.length; i += 4) {
        composite.data[i] = convert(data2[i] / 256) * 256;
      }
    }
    if (roughness) {
      context.drawImage(roughness, 0, 0, width2, height2);
      const convert = getEncodingConversion(roughnessMap);
      const data2 = context.getImageData(0, 0, width2, height2).data;
      for (let i = 1; i < data2.length; i += 4) {
        composite.data[i] = convert(data2[i] / 256) * 256;
      }
    }
    context.putImageData(composite, 0, 0);
    const reference = metalnessMap || roughnessMap;
    const texture = reference.clone();
    texture.source = new Source(canvas);
    texture.colorSpace = NoColorSpace;
    texture.channel = (metalnessMap || roughnessMap).channel;
    if (metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel) {
      console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match.");
    }
    console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures.");
    return texture;
  }
  async decompressTextureAsync(texture, maxTextureSize = Infinity) {
    if (this.textureUtils === null) {
      throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures.");
    }
    return await this.textureUtils.decompress(texture, maxTextureSize);
  }
  /**
   * Process a buffer to append to the default one.
   * @param {ArrayBuffer} buffer
   * @return {0}
   */
  processBuffer(buffer) {
    const json = this.json;
    const buffers = this.buffers;
    if (!json.buffers) json.buffers = [{ byteLength: 0 }];
    buffers.push(buffer);
    return 0;
  }
  /**
   * Process and generate a BufferView
   * @param {BufferAttribute} attribute
   * @param {number} componentType
   * @param {number} start
   * @param {number} count
   * @param {number} [target] Target usage of the BufferView
   * @return {Object}
   */
  processBufferView(attribute, componentType, start, count, target) {
    const json = this.json;
    if (!json.bufferViews) json.bufferViews = [];
    let componentSize;
    switch (componentType) {
      case WEBGL_CONSTANTS.BYTE:
      case WEBGL_CONSTANTS.UNSIGNED_BYTE:
        componentSize = 1;
        break;
      case WEBGL_CONSTANTS.SHORT:
      case WEBGL_CONSTANTS.UNSIGNED_SHORT:
        componentSize = 2;
        break;
      default:
        componentSize = 4;
    }
    let byteStride = attribute.itemSize * componentSize;
    if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) {
      byteStride = Math.ceil(byteStride / 4) * 4;
    }
    const byteLength = getPaddedBufferSize(count * byteStride);
    const dataView = new DataView(new ArrayBuffer(byteLength));
    let offset = 0;
    for (let i = start; i < start + count; i++) {
      for (let a2 = 0; a2 < attribute.itemSize; a2++) {
        let value2;
        if (attribute.itemSize > 4) {
          value2 = attribute.array[i * attribute.itemSize + a2];
        } else {
          if (a2 === 0) value2 = attribute.getX(i);
          else if (a2 === 1) value2 = attribute.getY(i);
          else if (a2 === 2) value2 = attribute.getZ(i);
          else if (a2 === 3) value2 = attribute.getW(i);
          if (attribute.normalized === true) {
            value2 = MathUtils.normalize(value2, attribute.array);
          }
        }
        if (componentType === WEBGL_CONSTANTS.FLOAT) {
          dataView.setFloat32(offset, value2, true);
        } else if (componentType === WEBGL_CONSTANTS.INT) {
          dataView.setInt32(offset, value2, true);
        } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_INT) {
          dataView.setUint32(offset, value2, true);
        } else if (componentType === WEBGL_CONSTANTS.SHORT) {
          dataView.setInt16(offset, value2, true);
        } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) {
          dataView.setUint16(offset, value2, true);
        } else if (componentType === WEBGL_CONSTANTS.BYTE) {
          dataView.setInt8(offset, value2);
        } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) {
          dataView.setUint8(offset, value2);
        }
        offset += componentSize;
      }
      if (offset % byteStride !== 0) {
        offset += byteStride - offset % byteStride;
      }
    }
    const bufferViewDef = {
      buffer: this.processBuffer(dataView.buffer),
      byteOffset: this.byteOffset,
      byteLength
    };
    if (target !== void 0) bufferViewDef.target = target;
    if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) {
      bufferViewDef.byteStride = byteStride;
    }
    this.byteOffset += byteLength;
    json.bufferViews.push(bufferViewDef);
    const output = {
      id: json.bufferViews.length - 1,
      byteLength: 0
    };
    return output;
  }
  /**
   * Process and generate a BufferView from an image Blob.
   * @param {Blob} blob
   * @return {Promise<number>} An integer
   */
  processBufferViewImage(blob) {
    const writer = this;
    const json = writer.json;
    if (!json.bufferViews) json.bufferViews = [];
    return new Promise(function(resolve) {
      const reader = new FileReader();
      reader.readAsArrayBuffer(blob);
      reader.onloadend = function() {
        const buffer = getPaddedArrayBuffer(reader.result);
        const bufferViewDef = {
          buffer: writer.processBuffer(buffer),
          byteOffset: writer.byteOffset,
          byteLength: buffer.byteLength
        };
        writer.byteOffset += buffer.byteLength;
        resolve(json.bufferViews.push(bufferViewDef) - 1);
      };
    });
  }
  /**
   * Process attribute to generate an accessor
   * @param {BufferAttribute} attribute Attribute to process
   * @param {?BufferGeometry} [geometry] Geometry used for truncated draw range
   * @param {number} [start=0]
   * @param {number} [count=Infinity]
   * @return {?number} Index of the processed accessor on the "accessors" array
   */
  processAccessor(attribute, geometry, start, count) {
    const json = this.json;
    const types = {
      1: "SCALAR",
      2: "VEC2",
      3: "VEC3",
      4: "VEC4",
      9: "MAT3",
      16: "MAT4"
    };
    let componentType;
    if (attribute.array.constructor === Float32Array) {
      componentType = WEBGL_CONSTANTS.FLOAT;
    } else if (attribute.array.constructor === Int32Array) {
      componentType = WEBGL_CONSTANTS.INT;
    } else if (attribute.array.constructor === Uint32Array) {
      componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
    } else if (attribute.array.constructor === Int16Array) {
      componentType = WEBGL_CONSTANTS.SHORT;
    } else if (attribute.array.constructor === Uint16Array) {
      componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
    } else if (attribute.array.constructor === Int8Array) {
      componentType = WEBGL_CONSTANTS.BYTE;
    } else if (attribute.array.constructor === Uint8Array) {
      componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
    } else {
      throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: " + attribute.array.constructor.name);
    }
    if (start === void 0) start = 0;
    if (count === void 0 || count === Infinity) count = attribute.count;
    if (count === 0) return null;
    const minMax = getMinMax(attribute, start, count);
    let bufferViewTarget;
    if (geometry !== void 0) {
      bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
    }
    const bufferView = this.processBufferView(attribute, componentType, start, count, bufferViewTarget);
    const accessorDef = {
      bufferView: bufferView.id,
      byteOffset: bufferView.byteOffset,
      componentType,
      count,
      max: minMax.max,
      min: minMax.min,
      type: types[attribute.itemSize]
    };
    if (attribute.normalized === true) accessorDef.normalized = true;
    if (!json.accessors) json.accessors = [];
    return json.accessors.push(accessorDef) - 1;
  }
  /**
   * Process image
   * @param {Image} image to process
   * @param {number} format Identifier of the format (RGBAFormat)
   * @param {boolean} flipY before writing out the image
   * @param {string} mimeType export format
   * @return {number}     Index of the processed texture in the "images" array
   */
  processImage(image, format, flipY, mimeType = "image/png") {
    if (image !== null) {
      const writer = this;
      const cache = writer.cache;
      const json = writer.json;
      const options = writer.options;
      const pending = writer.pending;
      if (!cache.images.has(image)) cache.images.set(image, {});
      const cachedImages = cache.images.get(image);
      const key2 = mimeType + ":flipY/" + flipY.toString();
      if (cachedImages[key2] !== void 0) return cachedImages[key2];
      if (!json.images) json.images = [];
      const imageDef = { mimeType };
      const canvas = getCanvas();
      canvas.width = Math.min(image.width, options.maxTextureSize);
      canvas.height = Math.min(image.height, options.maxTextureSize);
      const ctx = canvas.getContext("2d", {
        willReadFrequently: true
      });
      if (flipY === true) {
        ctx.translate(0, canvas.height);
        ctx.scale(1, -1);
      }
      if (image.data !== void 0) {
        if (format !== RGBAFormat) {
          console.error("GLTFExporter: Only RGBAFormat is supported.", format);
        }
        if (image.width > options.maxTextureSize || image.height > options.maxTextureSize) {
          console.warn("GLTFExporter: Image size is bigger than maxTextureSize", image);
        }
        const data2 = new Uint8ClampedArray(image.height * image.width * 4);
        for (let i = 0; i < data2.length; i += 4) {
          data2[i + 0] = image.data[i + 0];
          data2[i + 1] = image.data[i + 1];
          data2[i + 2] = image.data[i + 2];
          data2[i + 3] = image.data[i + 3];
        }
        ctx.putImageData(new ImageData(data2, image.width, image.height), 0, 0);
      } else {
        if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas) {
          ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        } else {
          throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");
        }
      }
      if (options.binary === true) {
        pending.push(
          getToBlobPromise(canvas, mimeType).then((blob) => writer.processBufferViewImage(blob)).then((bufferViewIndex) => {
            imageDef.bufferView = bufferViewIndex;
          })
        );
      } else {
        imageDef.uri = ImageUtils.getDataURL(canvas, mimeType);
      }
      const index2 = json.images.push(imageDef) - 1;
      cachedImages[key2] = index2;
      return index2;
    } else {
      throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.");
    }
  }
  /**
   * Process sampler
   * @param {Texture} map Texture to process
   * @return {number}      Index of the processed texture in the "samplers" array
   */
  processSampler(map2) {
    const json = this.json;
    if (!json.samplers) json.samplers = [];
    const samplerDef = {
      magFilter: THREE_TO_WEBGL[map2.magFilter],
      minFilter: THREE_TO_WEBGL[map2.minFilter],
      wrapS: THREE_TO_WEBGL[map2.wrapS],
      wrapT: THREE_TO_WEBGL[map2.wrapT]
    };
    return json.samplers.push(samplerDef) - 1;
  }
  /**
   * Process texture
   * @param {Texture} map Map to process
   * @return {Promise<number>} Index of the processed texture in the "textures" array
   */
  async processTextureAsync(map2) {
    const writer = this;
    const options = writer.options;
    const cache = this.cache;
    const json = this.json;
    if (cache.textures.has(map2)) return cache.textures.get(map2);
    if (!json.textures) json.textures = [];
    if (map2 instanceof CompressedTexture) {
      map2 = await this.decompressTextureAsync(map2, options.maxTextureSize);
    }
    let mimeType = map2.userData.mimeType;
    if (mimeType === "image/webp") mimeType = "image/png";
    const textureDef = {
      sampler: this.processSampler(map2),
      source: this.processImage(map2.image, map2.format, map2.flipY, mimeType)
    };
    if (map2.name) textureDef.name = map2.name;
    await this._invokeAllAsync(async function(ext) {
      ext.writeTexture && await ext.writeTexture(map2, textureDef);
    });
    const index2 = json.textures.push(textureDef) - 1;
    cache.textures.set(map2, index2);
    return index2;
  }
  /**
   * Process material
   * @param {THREE.Material} material Material to process
   * @return {Promise<number|null>} Index of the processed material in the "materials" array
   */
  async processMaterialAsync(material) {
    const cache = this.cache;
    const json = this.json;
    if (cache.materials.has(material)) return cache.materials.get(material);
    if (material.isShaderMaterial) {
      console.warn("GLTFExporter: THREE.ShaderMaterial not supported.");
      return null;
    }
    if (!json.materials) json.materials = [];
    const materialDef = { pbrMetallicRoughness: {} };
    if (material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true) {
      console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");
    }
    const color = material.color.toArray().concat([material.opacity]);
    if (!equalArray(color, [1, 1, 1, 1])) {
      materialDef.pbrMetallicRoughness.baseColorFactor = color;
    }
    if (material.isMeshStandardMaterial) {
      materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
      materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
    } else {
      materialDef.pbrMetallicRoughness.metallicFactor = 0;
      materialDef.pbrMetallicRoughness.roughnessFactor = 1;
    }
    if (material.metalnessMap || material.roughnessMap) {
      const metalRoughTexture = await this.buildMetalRoughTextureAsync(material.metalnessMap, material.roughnessMap);
      const metalRoughMapDef = {
        index: await this.processTextureAsync(metalRoughTexture),
        texCoord: metalRoughTexture.channel
      };
      this.applyTextureTransform(metalRoughMapDef, metalRoughTexture);
      materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
    }
    if (material.map) {
      const baseColorMapDef = {
        index: await this.processTextureAsync(material.map),
        texCoord: material.map.channel
      };
      this.applyTextureTransform(baseColorMapDef, material.map);
      materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
    }
    if (material.emissive) {
      const emissive = material.emissive;
      const maxEmissiveComponent = Math.max(emissive.r, emissive.g, emissive.b);
      if (maxEmissiveComponent > 0) {
        materialDef.emissiveFactor = material.emissive.toArray();
      }
      if (material.emissiveMap) {
        const emissiveMapDef = {
          index: await this.processTextureAsync(material.emissiveMap),
          texCoord: material.emissiveMap.channel
        };
        this.applyTextureTransform(emissiveMapDef, material.emissiveMap);
        materialDef.emissiveTexture = emissiveMapDef;
      }
    }
    if (material.normalMap) {
      const normalMapDef = {
        index: await this.processTextureAsync(material.normalMap),
        texCoord: material.normalMap.channel
      };
      if (material.normalScale && material.normalScale.x !== 1) {
        normalMapDef.scale = material.normalScale.x;
      }
      this.applyTextureTransform(normalMapDef, material.normalMap);
      materialDef.normalTexture = normalMapDef;
    }
    if (material.aoMap) {
      const occlusionMapDef = {
        index: await this.processTextureAsync(material.aoMap),
        texCoord: material.aoMap.channel
      };
      if (material.aoMapIntensity !== 1) {
        occlusionMapDef.strength = material.aoMapIntensity;
      }
      this.applyTextureTransform(occlusionMapDef, material.aoMap);
      materialDef.occlusionTexture = occlusionMapDef;
    }
    if (material.transparent) {
      materialDef.alphaMode = "BLEND";
    } else {
      if (material.alphaTest > 0) {
        materialDef.alphaMode = "MASK";
        materialDef.alphaCutoff = material.alphaTest;
      }
    }
    if (material.side === DoubleSide) materialDef.doubleSided = true;
    if (material.name !== "") materialDef.name = material.name;
    this.serializeUserData(material, materialDef);
    await this._invokeAllAsync(async function(ext) {
      ext.writeMaterialAsync && await ext.writeMaterialAsync(material, materialDef);
    });
    const index2 = json.materials.push(materialDef) - 1;
    cache.materials.set(material, index2);
    return index2;
  }
  /**
   * Process mesh
   * @param {THREE.Mesh} mesh Mesh to process
   * @return {Promise<number|null>} Index of the processed mesh in the "meshes" array
   */
  async processMeshAsync(mesh) {
    const cache = this.cache;
    const json = this.json;
    const meshCacheKeyParts = [mesh.geometry.uuid];
    if (Array.isArray(mesh.material)) {
      for (let i = 0, l2 = mesh.material.length; i < l2; i++) {
        meshCacheKeyParts.push(mesh.material[i].uuid);
      }
    } else {
      meshCacheKeyParts.push(mesh.material.uuid);
    }
    const meshCacheKey = meshCacheKeyParts.join(":");
    if (cache.meshes.has(meshCacheKey)) return cache.meshes.get(meshCacheKey);
    const geometry = mesh.geometry;
    let mode;
    if (mesh.isLineSegments) {
      mode = WEBGL_CONSTANTS.LINES;
    } else if (mesh.isLineLoop) {
      mode = WEBGL_CONSTANTS.LINE_LOOP;
    } else if (mesh.isLine) {
      mode = WEBGL_CONSTANTS.LINE_STRIP;
    } else if (mesh.isPoints) {
      mode = WEBGL_CONSTANTS.POINTS;
    } else {
      mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
    }
    const meshDef = {};
    const attributes = {};
    const primitives = [];
    const targets = [];
    const nameConversion = {
      uv: "TEXCOORD_0",
      uv1: "TEXCOORD_1",
      uv2: "TEXCOORD_2",
      uv3: "TEXCOORD_3",
      color: "COLOR_0",
      skinWeight: "WEIGHTS_0",
      skinIndex: "JOINTS_0"
    };
    const originalNormal = geometry.getAttribute("normal");
    if (originalNormal !== void 0 && !this.isNormalizedNormalAttribute(originalNormal)) {
      console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.");
      geometry.setAttribute("normal", this.createNormalizedNormalAttribute(originalNormal));
    }
    let modifiedAttribute = null;
    for (let attributeName in geometry.attributes) {
      if (attributeName.slice(0, 5) === "morph") continue;
      const attribute = geometry.attributes[attributeName];
      attributeName = nameConversion[attributeName] || attributeName.toUpperCase();
      const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
      if (!validVertexAttributes.test(attributeName)) attributeName = "_" + attributeName;
      if (cache.attributes.has(this.getUID(attribute))) {
        attributes[attributeName] = cache.attributes.get(this.getUID(attribute));
        continue;
      }
      modifiedAttribute = null;
      const array = attribute.array;
      if (attributeName === "JOINTS_0" && !(array instanceof Uint16Array) && !(array instanceof Uint8Array)) {
        console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.');
        modifiedAttribute = new BufferAttribute(new Uint16Array(array), attribute.itemSize, attribute.normalized);
      } else if ((array instanceof Uint32Array || array instanceof Int32Array) && !attributeName.startsWith("_")) {
        console.warn(`GLTFExporter: Attribute "${attributeName}" converted to type FLOAT.`);
        modifiedAttribute = GLTFExporter.Utils.toFloat32BufferAttribute(attribute);
      }
      const accessor = this.processAccessor(modifiedAttribute || attribute, geometry);
      if (accessor !== null) {
        if (!attributeName.startsWith("_")) {
          this.detectMeshQuantization(attributeName, attribute);
        }
        attributes[attributeName] = accessor;
        cache.attributes.set(this.getUID(attribute), accessor);
      }
    }
    if (originalNormal !== void 0) geometry.setAttribute("normal", originalNormal);
    if (Object.keys(attributes).length === 0) return null;
    if (mesh.morphTargetInfluences !== void 0 && mesh.morphTargetInfluences.length > 0) {
      const weights = [];
      const targetNames = [];
      const reverseDictionary = {};
      if (mesh.morphTargetDictionary !== void 0) {
        for (const key2 in mesh.morphTargetDictionary) {
          reverseDictionary[mesh.morphTargetDictionary[key2]] = key2;
        }
      }
      for (let i = 0; i < mesh.morphTargetInfluences.length; ++i) {
        const target = {};
        let warned = false;
        for (const attributeName in geometry.morphAttributes) {
          if (attributeName !== "position" && attributeName !== "normal") {
            if (!warned) {
              console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported.");
              warned = true;
            }
            continue;
          }
          const attribute = geometry.morphAttributes[attributeName][i];
          const gltfAttributeName = attributeName.toUpperCase();
          const baseAttribute = geometry.attributes[attributeName];
          if (cache.attributes.has(this.getUID(attribute, true))) {
            target[gltfAttributeName] = cache.attributes.get(this.getUID(attribute, true));
            continue;
          }
          const relativeAttribute = attribute.clone();
          if (!geometry.morphTargetsRelative) {
            for (let j2 = 0, jl = attribute.count; j2 < jl; j2++) {
              for (let a2 = 0; a2 < attribute.itemSize; a2++) {
                if (a2 === 0) relativeAttribute.setX(j2, attribute.getX(j2) - baseAttribute.getX(j2));
                if (a2 === 1) relativeAttribute.setY(j2, attribute.getY(j2) - baseAttribute.getY(j2));
                if (a2 === 2) relativeAttribute.setZ(j2, attribute.getZ(j2) - baseAttribute.getZ(j2));
                if (a2 === 3) relativeAttribute.setW(j2, attribute.getW(j2) - baseAttribute.getW(j2));
              }
            }
          }
          target[gltfAttributeName] = this.processAccessor(relativeAttribute, geometry);
          cache.attributes.set(this.getUID(baseAttribute, true), target[gltfAttributeName]);
        }
        targets.push(target);
        weights.push(mesh.morphTargetInfluences[i]);
        if (mesh.morphTargetDictionary !== void 0) targetNames.push(reverseDictionary[i]);
      }
      meshDef.weights = weights;
      if (targetNames.length > 0) {
        meshDef.extras = {};
        meshDef.extras.targetNames = targetNames;
      }
    }
    const isMultiMaterial = Array.isArray(mesh.material);
    if (isMultiMaterial && geometry.groups.length === 0) return null;
    let didForceIndices = false;
    if (isMultiMaterial && geometry.index === null) {
      const indices = [];
      for (let i = 0, il = geometry.attributes.position.count; i < il; i++) {
        indices[i] = i;
      }
      geometry.setIndex(indices);
      didForceIndices = true;
    }
    const materials = isMultiMaterial ? mesh.material : [mesh.material];
    const groups = isMultiMaterial ? geometry.groups : [{ materialIndex: 0, start: void 0, count: void 0 }];
    for (let i = 0, il = groups.length; i < il; i++) {
      const primitive = {
        mode,
        attributes
      };
      this.serializeUserData(geometry, primitive);
      if (targets.length > 0) primitive.targets = targets;
      if (geometry.index !== null) {
        let cacheKey = this.getUID(geometry.index);
        if (groups[i].start !== void 0 || groups[i].count !== void 0) {
          cacheKey += ":" + groups[i].start + ":" + groups[i].count;
        }
        if (cache.attributes.has(cacheKey)) {
          primitive.indices = cache.attributes.get(cacheKey);
        } else {
          primitive.indices = this.processAccessor(geometry.index, geometry, groups[i].start, groups[i].count);
          cache.attributes.set(cacheKey, primitive.indices);
        }
        if (primitive.indices === null) delete primitive.indices;
      }
      const material = await this.processMaterialAsync(materials[groups[i].materialIndex]);
      if (material !== null) primitive.material = material;
      primitives.push(primitive);
    }
    if (didForceIndices === true) {
      geometry.setIndex(null);
    }
    meshDef.primitives = primitives;
    if (!json.meshes) json.meshes = [];
    await this._invokeAllAsync(function(ext) {
      ext.writeMesh && ext.writeMesh(mesh, meshDef);
    });
    const index2 = json.meshes.push(meshDef) - 1;
    cache.meshes.set(meshCacheKey, index2);
    return index2;
  }
  /**
   * If a vertex attribute with a
   * [non-standard data type](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview)
   * is used, it is checked whether it is a valid data type according to the
   * [KHR_mesh_quantization](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md)
   * extension.
   * In this case the extension is automatically added to the list of used extensions.
   *
   * @param {string} attributeName
   * @param {THREE.BufferAttribute} attribute
   */
  detectMeshQuantization(attributeName, attribute) {
    if (this.extensionsUsed[KHR_MESH_QUANTIZATION]) return;
    let attrType = void 0;
    switch (attribute.array.constructor) {
      case Int8Array:
        attrType = "byte";
        break;
      case Uint8Array:
        attrType = "unsigned byte";
        break;
      case Int16Array:
        attrType = "short";
        break;
      case Uint16Array:
        attrType = "unsigned short";
        break;
      default:
        return;
    }
    if (attribute.normalized) attrType += " normalized";
    const attrNamePrefix = attributeName.split("_", 1)[0];
    if (KHR_mesh_quantization_ExtraAttrTypes[attrNamePrefix] && KHR_mesh_quantization_ExtraAttrTypes[attrNamePrefix].includes(attrType)) {
      this.extensionsUsed[KHR_MESH_QUANTIZATION] = true;
      this.extensionsRequired[KHR_MESH_QUANTIZATION] = true;
    }
  }
  /**
   * Process camera
   * @param {THREE.Camera} camera Camera to process
   * @return {number} Index of the processed mesh in the "camera" array
   */
  processCamera(camera) {
    const json = this.json;
    if (!json.cameras) json.cameras = [];
    const isOrtho = camera.isOrthographicCamera;
    const cameraDef = {
      type: isOrtho ? "orthographic" : "perspective"
    };
    if (isOrtho) {
      cameraDef.orthographic = {
        xmag: camera.right * 2,
        ymag: camera.top * 2,
        zfar: camera.far <= 0 ? 1e-3 : camera.far,
        znear: camera.near < 0 ? 0 : camera.near
      };
    } else {
      cameraDef.perspective = {
        aspectRatio: camera.aspect,
        yfov: MathUtils.degToRad(camera.fov),
        zfar: camera.far <= 0 ? 1e-3 : camera.far,
        znear: camera.near < 0 ? 0 : camera.near
      };
    }
    if (camera.name !== "") cameraDef.name = camera.type;
    return json.cameras.push(cameraDef) - 1;
  }
  /**
   * Creates glTF animation entry from AnimationClip object.
   *
   * Status:
   * - Only properties listed in PATH_PROPERTIES may be animated.
   *
   * @param {THREE.AnimationClip} clip
   * @param {THREE.Object3D} root
   * @return {number|null}
   */
  processAnimation(clip, root) {
    const json = this.json;
    const nodeMap = this.nodeMap;
    if (!json.animations) json.animations = [];
    clip = GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(), root);
    const tracks = clip.tracks;
    const channels = [];
    const samplers = [];
    for (let i = 0; i < tracks.length; ++i) {
      const track = tracks[i];
      const trackBinding = PropertyBinding.parseTrackName(track.name);
      let trackNode = PropertyBinding.findNode(root, trackBinding.nodeName);
      const trackProperty = PATH_PROPERTIES[trackBinding.propertyName];
      if (trackBinding.objectName === "bones") {
        if (trackNode.isSkinnedMesh === true) {
          trackNode = trackNode.skeleton.getBoneByName(trackBinding.objectIndex);
        } else {
          trackNode = void 0;
        }
      }
      if (!trackNode || !trackProperty) {
        console.warn('THREE.GLTFExporter: Could not export animation track "%s".', track.name);
        continue;
      }
      const inputItemSize = 1;
      let outputItemSize = track.values.length / track.times.length;
      if (trackProperty === PATH_PROPERTIES.morphTargetInfluences) {
        outputItemSize /= trackNode.morphTargetInfluences.length;
      }
      let interpolation;
      if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true) {
        interpolation = "CUBICSPLINE";
        outputItemSize /= 3;
      } else if (track.getInterpolation() === InterpolateDiscrete) {
        interpolation = "STEP";
      } else {
        interpolation = "LINEAR";
      }
      samplers.push({
        input: this.processAccessor(new BufferAttribute(track.times, inputItemSize)),
        output: this.processAccessor(new BufferAttribute(track.values, outputItemSize)),
        interpolation
      });
      channels.push({
        sampler: samplers.length - 1,
        target: {
          node: nodeMap.get(trackNode),
          path: trackProperty
        }
      });
    }
    json.animations.push({
      name: clip.name || "clip_" + json.animations.length,
      samplers,
      channels
    });
    return json.animations.length - 1;
  }
  /**
   * @param {THREE.Object3D} object
   * @return {number|null}
   */
  processSkin(object) {
    const json = this.json;
    const nodeMap = this.nodeMap;
    const node = json.nodes[nodeMap.get(object)];
    const skeleton = object.skeleton;
    if (skeleton === void 0) return null;
    const rootJoint = object.skeleton.bones[0];
    if (rootJoint === void 0) return null;
    const joints = [];
    const inverseBindMatrices = new Float32Array(skeleton.bones.length * 16);
    const temporaryBoneInverse = new Matrix4();
    for (let i = 0; i < skeleton.bones.length; ++i) {
      joints.push(nodeMap.get(skeleton.bones[i]));
      temporaryBoneInverse.copy(skeleton.boneInverses[i]);
      temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i * 16);
    }
    if (json.skins === void 0) json.skins = [];
    json.skins.push({
      inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)),
      joints,
      skeleton: nodeMap.get(rootJoint)
    });
    const skinIndex = node.skin = json.skins.length - 1;
    return skinIndex;
  }
  /**
   * Process Object3D node
   * @param {THREE.Object3D} object Object3D to processNodeAsync
   * @return {Promise<number>} Index of the node in the nodes list
   */
  async processNodeAsync(object) {
    const json = this.json;
    const options = this.options;
    const nodeMap = this.nodeMap;
    if (!json.nodes) json.nodes = [];
    const nodeDef = {};
    if (options.trs) {
      const rotation2 = object.quaternion.toArray();
      const position2 = object.position.toArray();
      const scale2 = object.scale.toArray();
      if (!equalArray(rotation2, [0, 0, 0, 1])) {
        nodeDef.rotation = rotation2;
      }
      if (!equalArray(position2, [0, 0, 0])) {
        nodeDef.translation = position2;
      }
      if (!equalArray(scale2, [1, 1, 1])) {
        nodeDef.scale = scale2;
      }
    } else {
      if (object.matrixAutoUpdate) {
        object.updateMatrix();
      }
      if (isIdentityMatrix(object.matrix) === false) {
        nodeDef.matrix = object.matrix.elements;
      }
    }
    if (object.name !== "") nodeDef.name = String(object.name);
    this.serializeUserData(object, nodeDef);
    if (object.isMesh || object.isLine || object.isPoints) {
      const meshIndex = await this.processMeshAsync(object);
      if (meshIndex !== null) nodeDef.mesh = meshIndex;
    } else if (object.isCamera) {
      nodeDef.camera = this.processCamera(object);
    }
    if (object.isSkinnedMesh) this.skins.push(object);
    const nodeIndex = json.nodes.push(nodeDef) - 1;
    nodeMap.set(object, nodeIndex);
    if (object.children.length > 0) {
      const children = [];
      for (let i = 0, l2 = object.children.length; i < l2; i++) {
        const child = object.children[i];
        if (child.visible || options.onlyVisible === false) {
          const childNodeIndex = await this.processNodeAsync(child);
          if (childNodeIndex !== null) children.push(childNodeIndex);
        }
      }
      if (children.length > 0) nodeDef.children = children;
    }
    await this._invokeAllAsync(function(ext) {
      ext.writeNode && ext.writeNode(object, nodeDef);
    });
    return nodeIndex;
  }
  /**
   * Process Scene
   * @param {Scene} scene Scene to process
   */
  async processSceneAsync(scene) {
    const json = this.json;
    const options = this.options;
    if (!json.scenes) {
      json.scenes = [];
      json.scene = 0;
    }
    const sceneDef = {};
    if (scene.name !== "") sceneDef.name = scene.name;
    json.scenes.push(sceneDef);
    const nodes = [];
    for (let i = 0, l2 = scene.children.length; i < l2; i++) {
      const child = scene.children[i];
      if (child.visible || options.onlyVisible === false) {
        const nodeIndex = await this.processNodeAsync(child);
        if (nodeIndex !== null) nodes.push(nodeIndex);
      }
    }
    if (nodes.length > 0) sceneDef.nodes = nodes;
    this.serializeUserData(scene, sceneDef);
  }
  /**
   * Creates a Scene to hold a list of objects and parse it
   * @param {Array<THREE.Object3D>} objects List of objects to process
   */
  async processObjectsAsync(objects) {
    const scene = new Scene();
    scene.name = "AuxScene";
    for (let i = 0; i < objects.length; i++) {
      scene.children.push(objects[i]);
    }
    await this.processSceneAsync(scene);
  }
  /**
   * @param {THREE.Object3D|Array<THREE.Object3D>} input
   */
  async processInputAsync(input) {
    const options = this.options;
    input = input instanceof Array ? input : [input];
    await this._invokeAllAsync(function(ext) {
      ext.beforeParse && ext.beforeParse(input);
    });
    const objectsWithoutScene = [];
    for (let i = 0; i < input.length; i++) {
      if (input[i] instanceof Scene) {
        await this.processSceneAsync(input[i]);
      } else {
        objectsWithoutScene.push(input[i]);
      }
    }
    if (objectsWithoutScene.length > 0) {
      await this.processObjectsAsync(objectsWithoutScene);
    }
    for (let i = 0; i < this.skins.length; ++i) {
      this.processSkin(this.skins[i]);
    }
    for (let i = 0; i < options.animations.length; ++i) {
      this.processAnimation(options.animations[i], input[0]);
    }
    await this._invokeAllAsync(function(ext) {
      ext.afterParse && ext.afterParse(input);
    });
  }
  async _invokeAllAsync(func) {
    for (let i = 0, il = this.plugins.length; i < il; i++) {
      await func(this.plugins[i]);
    }
  }
};
var GLTFLightExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_lights_punctual";
  }
  writeNode(light, nodeDef) {
    if (!light.isLight) return;
    if (!light.isDirectionalLight && !light.isPointLight && !light.isSpotLight) {
      console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.", light);
      return;
    }
    const writer = this.writer;
    const json = writer.json;
    const extensionsUsed = writer.extensionsUsed;
    const lightDef = {};
    if (light.name) lightDef.name = light.name;
    lightDef.color = light.color.toArray();
    lightDef.intensity = light.intensity;
    if (light.isDirectionalLight) {
      lightDef.type = "directional";
    } else if (light.isPointLight) {
      lightDef.type = "point";
      if (light.distance > 0) lightDef.range = light.distance;
    } else if (light.isSpotLight) {
      lightDef.type = "spot";
      if (light.distance > 0) lightDef.range = light.distance;
      lightDef.spot = {};
      lightDef.spot.innerConeAngle = (1 - light.penumbra) * light.angle;
      lightDef.spot.outerConeAngle = light.angle;
    }
    if (light.decay !== void 0 && light.decay !== 2) {
      console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2.");
    }
    if (light.target && (light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== -1)) {
      console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1.");
    }
    if (!extensionsUsed[this.name]) {
      json.extensions = json.extensions || {};
      json.extensions[this.name] = { lights: [] };
      extensionsUsed[this.name] = true;
    }
    const lights = json.extensions[this.name].lights;
    lights.push(lightDef);
    nodeDef.extensions = nodeDef.extensions || {};
    nodeDef.extensions[this.name] = { light: lights.length - 1 };
  }
};
var GLTFMaterialsUnlitExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_unlit";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshBasicMaterial) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = {};
    extensionsUsed[this.name] = true;
    materialDef.pbrMetallicRoughness.metallicFactor = 0;
    materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
  }
};
var GLTFMaterialsClearcoatExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_clearcoat";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.clearcoat === 0) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    extensionDef.clearcoatFactor = material.clearcoat;
    if (material.clearcoatMap) {
      const clearcoatMapDef = {
        index: await writer.processTextureAsync(material.clearcoatMap),
        texCoord: material.clearcoatMap.channel
      };
      writer.applyTextureTransform(clearcoatMapDef, material.clearcoatMap);
      extensionDef.clearcoatTexture = clearcoatMapDef;
    }
    extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness;
    if (material.clearcoatRoughnessMap) {
      const clearcoatRoughnessMapDef = {
        index: await writer.processTextureAsync(material.clearcoatRoughnessMap),
        texCoord: material.clearcoatRoughnessMap.channel
      };
      writer.applyTextureTransform(clearcoatRoughnessMapDef, material.clearcoatRoughnessMap);
      extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef;
    }
    if (material.clearcoatNormalMap) {
      const clearcoatNormalMapDef = {
        index: await writer.processTextureAsync(material.clearcoatNormalMap),
        texCoord: material.clearcoatNormalMap.channel
      };
      if (material.clearcoatNormalScale.x !== 1) clearcoatNormalMapDef.scale = material.clearcoatNormalScale.x;
      writer.applyTextureTransform(clearcoatNormalMapDef, material.clearcoatNormalMap);
      extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef;
    }
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsDispersionExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_dispersion";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.dispersion === 0) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    extensionDef.dispersion = material.dispersion;
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsIridescenceExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_iridescence";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.iridescence === 0) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    extensionDef.iridescenceFactor = material.iridescence;
    if (material.iridescenceMap) {
      const iridescenceMapDef = {
        index: await writer.processTextureAsync(material.iridescenceMap),
        texCoord: material.iridescenceMap.channel
      };
      writer.applyTextureTransform(iridescenceMapDef, material.iridescenceMap);
      extensionDef.iridescenceTexture = iridescenceMapDef;
    }
    extensionDef.iridescenceIor = material.iridescenceIOR;
    extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[0];
    extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[1];
    if (material.iridescenceThicknessMap) {
      const iridescenceThicknessMapDef = {
        index: await writer.processTextureAsync(material.iridescenceThicknessMap),
        texCoord: material.iridescenceThicknessMap.channel
      };
      writer.applyTextureTransform(iridescenceThicknessMapDef, material.iridescenceThicknessMap);
      extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef;
    }
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsTransmissionExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_transmission";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.transmission === 0) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    extensionDef.transmissionFactor = material.transmission;
    if (material.transmissionMap) {
      const transmissionMapDef = {
        index: await writer.processTextureAsync(material.transmissionMap),
        texCoord: material.transmissionMap.channel
      };
      writer.applyTextureTransform(transmissionMapDef, material.transmissionMap);
      extensionDef.transmissionTexture = transmissionMapDef;
    }
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsVolumeExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_volume";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.transmission === 0) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    extensionDef.thicknessFactor = material.thickness;
    if (material.thicknessMap) {
      const thicknessMapDef = {
        index: await writer.processTextureAsync(material.thicknessMap),
        texCoord: material.thicknessMap.channel
      };
      writer.applyTextureTransform(thicknessMapDef, material.thicknessMap);
      extensionDef.thicknessTexture = thicknessMapDef;
    }
    if (material.attenuationDistance !== Infinity) {
      extensionDef.attenuationDistance = material.attenuationDistance;
    }
    extensionDef.attenuationColor = material.attenuationColor.toArray();
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsIorExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_ior";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.ior === 1.5) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    extensionDef.ior = material.ior;
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsSpecularExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_specular";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.specularIntensity === 1 && material.specularColor.equals(DEFAULT_SPECULAR_COLOR) && !material.specularIntensityMap && !material.specularColorMap) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    if (material.specularIntensityMap) {
      const specularIntensityMapDef = {
        index: await writer.processTextureAsync(material.specularIntensityMap),
        texCoord: material.specularIntensityMap.channel
      };
      writer.applyTextureTransform(specularIntensityMapDef, material.specularIntensityMap);
      extensionDef.specularTexture = specularIntensityMapDef;
    }
    if (material.specularColorMap) {
      const specularColorMapDef = {
        index: await writer.processTextureAsync(material.specularColorMap),
        texCoord: material.specularColorMap.channel
      };
      writer.applyTextureTransform(specularColorMapDef, material.specularColorMap);
      extensionDef.specularColorTexture = specularColorMapDef;
    }
    extensionDef.specularFactor = material.specularIntensity;
    extensionDef.specularColorFactor = material.specularColor.toArray();
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsSheenExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_sheen";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.sheen == 0) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    if (material.sheenRoughnessMap) {
      const sheenRoughnessMapDef = {
        index: await writer.processTextureAsync(material.sheenRoughnessMap),
        texCoord: material.sheenRoughnessMap.channel
      };
      writer.applyTextureTransform(sheenRoughnessMapDef, material.sheenRoughnessMap);
      extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef;
    }
    if (material.sheenColorMap) {
      const sheenColorMapDef = {
        index: await writer.processTextureAsync(material.sheenColorMap),
        texCoord: material.sheenColorMap.channel
      };
      writer.applyTextureTransform(sheenColorMapDef, material.sheenColorMap);
      extensionDef.sheenColorTexture = sheenColorMapDef;
    }
    extensionDef.sheenRoughnessFactor = material.sheenRoughness;
    extensionDef.sheenColorFactor = material.sheenColor.toArray();
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsAnisotropyExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_anisotropy";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshPhysicalMaterial || material.anisotropy == 0) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    if (material.anisotropyMap) {
      const anisotropyMapDef = { index: await writer.processTextureAsync(material.anisotropyMap) };
      writer.applyTextureTransform(anisotropyMapDef, material.anisotropyMap);
      extensionDef.anisotropyTexture = anisotropyMapDef;
    }
    extensionDef.anisotropyStrength = material.anisotropy;
    extensionDef.anisotropyRotation = material.anisotropyRotation;
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsEmissiveStrengthExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "KHR_materials_emissive_strength";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshStandardMaterial || material.emissiveIntensity === 1) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    extensionDef.emissiveStrength = material.emissiveIntensity;
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMaterialsBumpExtension = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "EXT_materials_bump";
  }
  async writeMaterialAsync(material, materialDef) {
    if (!material.isMeshStandardMaterial || material.bumpScale === 1 && !material.bumpMap) return;
    const writer = this.writer;
    const extensionsUsed = writer.extensionsUsed;
    const extensionDef = {};
    if (material.bumpMap) {
      const bumpMapDef = {
        index: await writer.processTextureAsync(material.bumpMap),
        texCoord: material.bumpMap.channel
      };
      writer.applyTextureTransform(bumpMapDef, material.bumpMap);
      extensionDef.bumpTexture = bumpMapDef;
    }
    extensionDef.bumpFactor = material.bumpScale;
    materialDef.extensions = materialDef.extensions || {};
    materialDef.extensions[this.name] = extensionDef;
    extensionsUsed[this.name] = true;
  }
};
var GLTFMeshGpuInstancing = class {
  constructor(writer) {
    this.writer = writer;
    this.name = "EXT_mesh_gpu_instancing";
  }
  writeNode(object, nodeDef) {
    if (!object.isInstancedMesh) return;
    const writer = this.writer;
    const mesh = object;
    const translationAttr = new Float32Array(mesh.count * 3);
    const rotationAttr = new Float32Array(mesh.count * 4);
    const scaleAttr = new Float32Array(mesh.count * 3);
    const matrix2 = new Matrix4();
    const position2 = new Vector3();
    const quaternion = new Quaternion();
    const scale2 = new Vector3();
    for (let i = 0; i < mesh.count; i++) {
      mesh.getMatrixAt(i, matrix2);
      matrix2.decompose(position2, quaternion, scale2);
      position2.toArray(translationAttr, i * 3);
      quaternion.toArray(rotationAttr, i * 4);
      scale2.toArray(scaleAttr, i * 3);
    }
    const attributes = {
      TRANSLATION: writer.processAccessor(new BufferAttribute(translationAttr, 3)),
      ROTATION: writer.processAccessor(new BufferAttribute(rotationAttr, 4)),
      SCALE: writer.processAccessor(new BufferAttribute(scaleAttr, 3))
    };
    if (mesh.instanceColor)
      attributes._COLOR_0 = writer.processAccessor(mesh.instanceColor);
    nodeDef.extensions = nodeDef.extensions || {};
    nodeDef.extensions[this.name] = { attributes };
    writer.extensionsUsed[this.name] = true;
    writer.extensionsRequired[this.name] = true;
  }
};
GLTFExporter.Utils = {
  insertKeyframe: function(track, time2) {
    const tolerance = 1e-3;
    const valueSize = track.getValueSize();
    const times = new track.TimeBufferType(track.times.length + 1);
    const values2 = new track.ValueBufferType(track.values.length + valueSize);
    const interpolant = track.createInterpolant(new track.ValueBufferType(valueSize));
    let index2;
    if (track.times.length === 0) {
      times[0] = time2;
      for (let i = 0; i < valueSize; i++) {
        values2[i] = 0;
      }
      index2 = 0;
    } else if (time2 < track.times[0]) {
      if (Math.abs(track.times[0] - time2) < tolerance) return 0;
      times[0] = time2;
      times.set(track.times, 1);
      values2.set(interpolant.evaluate(time2), 0);
      values2.set(track.values, valueSize);
      index2 = 0;
    } else if (time2 > track.times[track.times.length - 1]) {
      if (Math.abs(track.times[track.times.length - 1] - time2) < tolerance) {
        return track.times.length - 1;
      }
      times[times.length - 1] = time2;
      times.set(track.times, 0);
      values2.set(track.values, 0);
      values2.set(interpolant.evaluate(time2), track.values.length);
      index2 = times.length - 1;
    } else {
      for (let i = 0; i < track.times.length; i++) {
        if (Math.abs(track.times[i] - time2) < tolerance) return i;
        if (track.times[i] < time2 && track.times[i + 1] > time2) {
          times.set(track.times.slice(0, i + 1), 0);
          times[i + 1] = time2;
          times.set(track.times.slice(i + 1), i + 2);
          values2.set(track.values.slice(0, (i + 1) * valueSize), 0);
          values2.set(interpolant.evaluate(time2), (i + 1) * valueSize);
          values2.set(track.values.slice((i + 1) * valueSize), (i + 2) * valueSize);
          index2 = i + 1;
          break;
        }
      }
    }
    track.times = times;
    track.values = values2;
    return index2;
  },
  mergeMorphTargetTracks: function(clip, root) {
    const tracks = [];
    const mergedTracks = {};
    const sourceTracks = clip.tracks;
    for (let i = 0; i < sourceTracks.length; ++i) {
      let sourceTrack = sourceTracks[i];
      const sourceTrackBinding = PropertyBinding.parseTrackName(sourceTrack.name);
      const sourceTrackNode = PropertyBinding.findNode(root, sourceTrackBinding.nodeName);
      if (sourceTrackBinding.propertyName !== "morphTargetInfluences" || sourceTrackBinding.propertyIndex === void 0) {
        tracks.push(sourceTrack);
        continue;
      }
      if (sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) {
        if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
          throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");
        }
        console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.");
        sourceTrack = sourceTrack.clone();
        sourceTrack.setInterpolation(InterpolateLinear);
      }
      const targetCount = sourceTrackNode.morphTargetInfluences.length;
      const targetIndex = sourceTrackNode.morphTargetDictionary[sourceTrackBinding.propertyIndex];
      if (targetIndex === void 0) {
        throw new Error("THREE.GLTFExporter: Morph target name not found: " + sourceTrackBinding.propertyIndex);
      }
      let mergedTrack;
      if (mergedTracks[sourceTrackNode.uuid] === void 0) {
        mergedTrack = sourceTrack.clone();
        const values2 = new mergedTrack.ValueBufferType(targetCount * mergedTrack.times.length);
        for (let j2 = 0; j2 < mergedTrack.times.length; j2++) {
          values2[j2 * targetCount + targetIndex] = mergedTrack.values[j2];
        }
        mergedTrack.name = (sourceTrackBinding.nodeName || "") + ".morphTargetInfluences";
        mergedTrack.values = values2;
        mergedTracks[sourceTrackNode.uuid] = mergedTrack;
        tracks.push(mergedTrack);
        continue;
      }
      const sourceInterpolant = sourceTrack.createInterpolant(new sourceTrack.ValueBufferType(1));
      mergedTrack = mergedTracks[sourceTrackNode.uuid];
      for (let j2 = 0; j2 < mergedTrack.times.length; j2++) {
        mergedTrack.values[j2 * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j2]);
      }
      for (let j2 = 0; j2 < sourceTrack.times.length; j2++) {
        const keyframeIndex = this.insertKeyframe(mergedTrack, sourceTrack.times[j2]);
        mergedTrack.values[keyframeIndex * targetCount + targetIndex] = sourceTrack.values[j2];
      }
    }
    clip.tracks = tracks;
    return clip;
  },
  toFloat32BufferAttribute: function(srcAttribute) {
    const dstAttribute = new BufferAttribute(new Float32Array(srcAttribute.count * srcAttribute.itemSize), srcAttribute.itemSize, false);
    if (!srcAttribute.normalized && !srcAttribute.isInterleavedBufferAttribute) {
      dstAttribute.array.set(srcAttribute.array);
      return dstAttribute;
    }
    for (let i = 0, il = srcAttribute.count; i < il; i++) {
      for (let j2 = 0; j2 < srcAttribute.itemSize; j2++) {
        dstAttribute.setComponent(i, j2, srcAttribute.getComponent(i, j2));
      }
    }
    return dstAttribute;
  }
};

// node_modules/three/examples/jsm/libs/ktx-parse.module.js
var t = 0;
var n = 2;
var l = 1;
var g = 1;
var x = 1;
var u = 2;
var T = 0;
var C = 1;
var R = 10;
var j = 0;
var q = 1;
var G = 2;
var Z = 15;
var $ = 128;
var tt = 64;
var nt = 16;
var it = 0;
var ct = 9;
var yt = 15;
var xt = 16;
var wt = 22;
var Ft = 37;
var Ct = 43;
var te2 = 76;
var ae = 83;
var ge = 97;
var ue = 100;
var we = 103;
var Ae = 109;
var Ge = 131;
var Je = 132;
var Qe = 133;
var Ze = 134;
var en = 137;
var nn = 138;
var rn = 141;
var on = 142;
var hn = 145;
var Un = 146;
var _n = 148;
var xn = 152;
var mn = 157;
var Dn = 158;
var In = 165;
var Sn = 166;
var pi = 1000066e3;
var Ii = class {
  constructor() {
    this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{ vendorId: 0, descriptorType: 0, descriptorBlockSize: 0, versionNumber: 2, colorModel: 0, colorPrimaries: 1, transferFunction: 2, flags: 0, texelBlockDimension: [0, 0, 0, 0], bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0], samples: [] }], this.keyValue = {}, this.globalData = null;
  }
};
var Si = class {
  constructor(t3, e, n2, i) {
    this._dataView = void 0, this._littleEndian = void 0, this._offset = void 0, this._dataView = new DataView(t3.buffer, t3.byteOffset + e, n2), this._littleEndian = i, this._offset = 0;
  }
  _nextUint8() {
    const t3 = this._dataView.getUint8(this._offset);
    return this._offset += 1, t3;
  }
  _nextUint16() {
    const t3 = this._dataView.getUint16(this._offset, this._littleEndian);
    return this._offset += 2, t3;
  }
  _nextUint32() {
    const t3 = this._dataView.getUint32(this._offset, this._littleEndian);
    return this._offset += 4, t3;
  }
  _nextUint64() {
    const t3 = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian);
    return this._offset += 8, t3;
  }
  _nextInt32() {
    const t3 = this._dataView.getInt32(this._offset, this._littleEndian);
    return this._offset += 4, t3;
  }
  _nextUint8Array(t3) {
    const e = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._offset, t3);
    return this._offset += t3, e;
  }
  _skip(t3) {
    return this._offset += t3, this;
  }
  _scan(t3, e) {
    void 0 === e && (e = 0);
    const n2 = this._offset;
    let i = 0;
    for (; this._dataView.getUint8(this._offset) !== e && i < t3; ) i++, this._offset++;
    return i < t3 && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n2, i);
  }
};
var Fi = new Uint8Array([0]);
var Oi = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10];
function Ei(t3) {
  return new TextEncoder().encode(t3);
}
function Ti(t3) {
  return new TextDecoder().decode(t3);
}
function Ci(t3) {
  let e = 0;
  for (const n3 of t3) e += n3.byteLength;
  const n2 = new Uint8Array(e);
  let i = 0;
  for (const e2 of t3) n2.set(new Uint8Array(e2), i), i += e2.byteLength;
  return n2;
}
function Mi(t3, e) {
  return void 0 === e && (e = 4), Math.ceil(t3 / e) * e - t3;
}
function Pi(t3) {
  const e = new Uint8Array(t3.buffer, t3.byteOffset, Oi.length);
  if (e[0] !== Oi[0] || e[1] !== Oi[1] || e[2] !== Oi[2] || e[3] !== Oi[3] || e[4] !== Oi[4] || e[5] !== Oi[5] || e[6] !== Oi[6] || e[7] !== Oi[7] || e[8] !== Oi[8] || e[9] !== Oi[9] || e[10] !== Oi[10] || e[11] !== Oi[11]) throw new Error("Missing KTX 2.0 identifier.");
  const n2 = new Ii(), i = 17 * Uint32Array.BYTES_PER_ELEMENT, s = new Si(t3, Oi.length, i, true);
  n2.vkFormat = s._nextUint32(), n2.typeSize = s._nextUint32(), n2.pixelWidth = s._nextUint32(), n2.pixelHeight = s._nextUint32(), n2.pixelDepth = s._nextUint32(), n2.layerCount = s._nextUint32(), n2.faceCount = s._nextUint32();
  const a2 = s._nextUint32();
  n2.supercompressionScheme = s._nextUint32();
  const r = s._nextUint32(), o = s._nextUint32(), l2 = s._nextUint32(), f = s._nextUint32(), h = s._nextUint64(), U = s._nextUint64(), c2 = new Si(t3, Oi.length + i, 3 * a2 * 8, true);
  for (let e2 = 0; e2 < a2; e2++) n2.levels.push({ levelData: new Uint8Array(t3.buffer, t3.byteOffset + c2._nextUint64(), c2._nextUint64()), uncompressedByteLength: c2._nextUint64() });
  const _ = new Si(t3, r, o, true), p = { vendorId: _._skip(4)._nextUint16(), descriptorType: _._nextUint16(), versionNumber: _._nextUint16(), descriptorBlockSize: _._nextUint16(), colorModel: _._nextUint8(), colorPrimaries: _._nextUint8(), transferFunction: _._nextUint8(), flags: _._nextUint8(), texelBlockDimension: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], bytesPlane: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], samples: [] }, g3 = (p.descriptorBlockSize / 4 - 6) / 4;
  for (let t4 = 0; t4 < g3; t4++) {
    const e2 = { bitOffset: _._nextUint16(), bitLength: _._nextUint8(), channelType: _._nextUint8(), samplePosition: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], sampleLower: -Infinity, sampleUpper: Infinity };
    64 & e2.channelType ? (e2.sampleLower = _._nextInt32(), e2.sampleUpper = _._nextInt32()) : (e2.sampleLower = _._nextUint32(), e2.sampleUpper = _._nextUint32()), p.samples[t4] = e2;
  }
  n2.dataFormatDescriptor.length = 0, n2.dataFormatDescriptor.push(p);
  const y = new Si(t3, l2, f, true);
  for (; y._offset < f; ) {
    const t4 = y._nextUint32(), e2 = y._scan(t4), i2 = Ti(e2);
    if (n2.keyValue[i2] = y._nextUint8Array(t4 - e2.byteLength - 1), i2.match(/^ktx/i)) {
      const t5 = Ti(n2.keyValue[i2]);
      n2.keyValue[i2] = t5.substring(0, t5.lastIndexOf("\0"));
    }
    y._skip(t4 % 4 ? 4 - t4 % 4 : 0);
  }
  if (U <= 0) return n2;
  const x2 = new Si(t3, h, U, true), u2 = x2._nextUint16(), b3 = x2._nextUint16(), d = x2._nextUint32(), w = x2._nextUint32(), m = x2._nextUint32(), D = x2._nextUint32(), B2 = [];
  for (let t4 = 0; t4 < a2; t4++) B2.push({ imageFlags: x2._nextUint32(), rgbSliceByteOffset: x2._nextUint32(), rgbSliceByteLength: x2._nextUint32(), alphaSliceByteOffset: x2._nextUint32(), alphaSliceByteLength: x2._nextUint32() });
  const L = h + x2._offset, v = L + d, A2 = v + w, k2 = A2 + m, V = new Uint8Array(t3.buffer, t3.byteOffset + L, d), I2 = new Uint8Array(t3.buffer, t3.byteOffset + v, w), S = new Uint8Array(t3.buffer, t3.byteOffset + A2, m), F = new Uint8Array(t3.buffer, t3.byteOffset + k2, D);
  return n2.globalData = { endpointCount: u2, selectorCount: b3, imageDescs: B2, endpointsData: V, selectorsData: I2, tablesData: S, extendedData: F }, n2;
}
var zi = { keepWriter: false };
function Wi(t3, e) {
  void 0 === e && (e = {}), e = { ...zi, ...e };
  let n2 = new ArrayBuffer(0);
  if (t3.globalData) {
    const e2 = new ArrayBuffer(20 + 5 * t3.globalData.imageDescs.length * 4), i2 = new DataView(e2);
    i2.setUint16(0, t3.globalData.endpointCount, true), i2.setUint16(2, t3.globalData.selectorCount, true), i2.setUint32(4, t3.globalData.endpointsData.byteLength, true), i2.setUint32(8, t3.globalData.selectorsData.byteLength, true), i2.setUint32(12, t3.globalData.tablesData.byteLength, true), i2.setUint32(16, t3.globalData.extendedData.byteLength, true);
    for (let e3 = 0; e3 < t3.globalData.imageDescs.length; e3++) {
      const n3 = t3.globalData.imageDescs[e3];
      i2.setUint32(20 + 5 * e3 * 4 + 0, n3.imageFlags, true), i2.setUint32(20 + 5 * e3 * 4 + 4, n3.rgbSliceByteOffset, true), i2.setUint32(20 + 5 * e3 * 4 + 8, n3.rgbSliceByteLength, true), i2.setUint32(20 + 5 * e3 * 4 + 12, n3.alphaSliceByteOffset, true), i2.setUint32(20 + 5 * e3 * 4 + 16, n3.alphaSliceByteLength, true);
    }
    n2 = Ci([e2, t3.globalData.endpointsData, t3.globalData.selectorsData, t3.globalData.tablesData, t3.globalData.extendedData]);
  }
  const i = [];
  let s = t3.keyValue;
  e.keepWriter || (s = { ...t3.keyValue, KTXwriter: "KTX-Parse v0.7.1" });
  for (const t4 in s) {
    const e2 = s[t4], n3 = Ei(t4), a3 = "string" == typeof e2 ? Ci([Ei(e2), Fi]) : e2, r2 = n3.byteLength + 1 + a3.byteLength, o2 = Mi(r2, 4);
    i.push(Ci([new Uint32Array([r2]), n3, Fi, a3, new Uint8Array(o2).fill(0)]));
  }
  const a2 = Ci(i);
  if (1 !== t3.dataFormatDescriptor.length || 0 !== t3.dataFormatDescriptor[0].descriptorType) throw new Error("Only BASICFORMAT Data Format Descriptor output supported.");
  const r = t3.dataFormatDescriptor[0], o = new ArrayBuffer(28 + 16 * r.samples.length), l2 = new DataView(o), f = 24 + 16 * r.samples.length;
  if (l2.setUint32(0, o.byteLength, true), l2.setUint16(4, r.vendorId, true), l2.setUint16(6, r.descriptorType, true), l2.setUint16(8, r.versionNumber, true), l2.setUint16(10, f, true), l2.setUint8(12, r.colorModel), l2.setUint8(13, r.colorPrimaries), l2.setUint8(14, r.transferFunction), l2.setUint8(15, r.flags), !Array.isArray(r.texelBlockDimension)) throw new Error("texelBlockDimension is now an array. For dimensionality `d`, set `d - 1`.");
  l2.setUint8(16, r.texelBlockDimension[0]), l2.setUint8(17, r.texelBlockDimension[1]), l2.setUint8(18, r.texelBlockDimension[2]), l2.setUint8(19, r.texelBlockDimension[3]);
  for (let t4 = 0; t4 < 8; t4++) l2.setUint8(20 + t4, r.bytesPlane[t4]);
  for (let t4 = 0; t4 < r.samples.length; t4++) {
    const e2 = r.samples[t4], n3 = 28 + 16 * t4;
    if (e2.channelID) throw new Error("channelID has been renamed to channelType.");
    l2.setUint16(n3 + 0, e2.bitOffset, true), l2.setUint8(n3 + 2, e2.bitLength), l2.setUint8(n3 + 3, e2.channelType), l2.setUint8(n3 + 4, e2.samplePosition[0]), l2.setUint8(n3 + 5, e2.samplePosition[1]), l2.setUint8(n3 + 6, e2.samplePosition[2]), l2.setUint8(n3 + 7, e2.samplePosition[3]), 64 & e2.channelType ? (l2.setInt32(n3 + 8, e2.sampleLower, true), l2.setInt32(n3 + 12, e2.sampleUpper, true)) : (l2.setUint32(n3 + 8, e2.sampleLower, true), l2.setUint32(n3 + 12, e2.sampleUpper, true));
  }
  const h = Oi.length + 68 + 3 * t3.levels.length * 8, U = h + o.byteLength;
  let c2 = n2.byteLength > 0 ? U + a2.byteLength : 0;
  c2 % 8 && (c2 += 8 - c2 % 8);
  const _ = [], p = new DataView(new ArrayBuffer(3 * t3.levels.length * 8)), g3 = new Uint32Array(t3.levels.length);
  let y = 0;
  0 === t3.supercompressionScheme && (y = function(t4, e2) {
    const n3 = Math.max(t4, 4), i2 = Math.min(t4, 4);
    let s2 = n3;
    for (; s2 % i2 != 0; ) s2 += n3;
    return s2;
  }(function(t4) {
    return t4.levels[0].levelData.byteLength / function(t5, e2) {
      let n3 = 1;
      const i2 = [t5.pixelWidth, t5.pixelHeight, t5.pixelDepth], s2 = function(t6) {
        const [e3, n4, i3] = t6.dataFormatDescriptor[0].texelBlockDimension;
        return [e3 + 1, n4 + 1, i3 + 1];
      }(t5);
      for (let t6 = 0; t6 < 3; t6++) if (i2[t6] > 0) {
        const e3 = Math.ceil(Math.floor(i2[t6] * Math.pow(2, -0)) / s2[t6]);
        n3 *= Math.max(1, e3);
      }
      return t5.layerCount > 0 && (n3 *= t5.layerCount), t5.faceCount > 0 && (n3 *= t5.faceCount), n3;
    }(t4);
  }(t3)));
  let x2 = (c2 || U + a2.byteLength) + n2.byteLength;
  for (let e2 = t3.levels.length - 1; e2 >= 0; e2--) {
    if (x2 % y) {
      const t4 = Mi(x2, y);
      _.push(new Uint8Array(t4)), x2 += t4;
    }
    const n3 = t3.levels[e2];
    _.push(n3.levelData), g3[e2] = x2, x2 += n3.levelData.byteLength;
  }
  for (let e2 = 0; e2 < t3.levels.length; e2++) {
    const n3 = t3.levels[e2];
    p.setBigUint64(24 * e2 + 0, BigInt(g3[e2]), true), p.setBigUint64(24 * e2 + 8, BigInt(n3.levelData.byteLength), true), p.setBigUint64(24 * e2 + 16, BigInt(n3.uncompressedByteLength), true);
  }
  const u2 = new ArrayBuffer(68), b3 = new DataView(u2);
  return b3.setUint32(0, t3.vkFormat, true), b3.setUint32(4, t3.typeSize, true), b3.setUint32(8, t3.pixelWidth, true), b3.setUint32(12, t3.pixelHeight, true), b3.setUint32(16, t3.pixelDepth, true), b3.setUint32(20, t3.layerCount, true), b3.setUint32(24, t3.faceCount, true), b3.setUint32(28, t3.levels.length, true), b3.setUint32(32, t3.supercompressionScheme, true), b3.setUint32(36, h, true), b3.setUint32(40, o.byteLength, true), b3.setUint32(44, U, true), b3.setUint32(48, a2.byteLength, true), b3.setBigUint64(52, BigInt(n2.byteLength > 0 ? c2 : 0), true), b3.setBigUint64(60, BigInt(n2.byteLength), true), new Uint8Array(Ci([new Uint8Array(Oi).buffer, u2, p.buffer, o, a2, c2 > 0 ? new ArrayBuffer(c2 - (U + a2.byteLength)) : new ArrayBuffer(0), n2, ..._]));
}

// node_modules/three/examples/jsm/exporters/KTX2Exporter.js
var VK_FORMAT_MAP = {
  [RGBAFormat]: {
    [FloatType]: {
      [NoColorSpace]: Ae,
      [LinearSRGBColorSpace]: Ae
    },
    [HalfFloatType]: {
      [NoColorSpace]: ge,
      [LinearSRGBColorSpace]: ge
    },
    [UnsignedByteType]: {
      [NoColorSpace]: Ft,
      [LinearSRGBColorSpace]: Ft,
      [SRGBColorSpace]: Ct
    }
  },
  [RGFormat]: {
    [FloatType]: {
      [NoColorSpace]: we,
      [LinearSRGBColorSpace]: we
    },
    [HalfFloatType]: {
      [NoColorSpace]: ae,
      [LinearSRGBColorSpace]: ae
    },
    [UnsignedByteType]: {
      [NoColorSpace]: xt,
      [LinearSRGBColorSpace]: xt,
      [SRGBColorSpace]: wt
    }
  },
  [RedFormat]: {
    [FloatType]: {
      [NoColorSpace]: ue,
      [LinearSRGBColorSpace]: ue
    },
    [HalfFloatType]: {
      [NoColorSpace]: te2,
      [LinearSRGBColorSpace]: te2
    },
    [UnsignedByteType]: {
      [NoColorSpace]: ct,
      [LinearSRGBColorSpace]: ct,
      [SRGBColorSpace]: yt
    }
  }
};
var KHR_DF_CHANNEL_MAP = [
  j,
  q,
  G,
  Z
];
var KHR_DF_CHANNEL_SAMPLE_LOWER_UPPER = {
  [FloatType]: [3212836864, 1065353216],
  [HalfFloatType]: [3212836864, 1065353216],
  [UnsignedByteType]: [0, 255]
};
var ERROR_INPUT = "THREE.KTX2Exporter: Supported inputs are DataTexture, Data3DTexture, or WebGLRenderer and WebGLRenderTarget.";
var ERROR_FORMAT = "THREE.KTX2Exporter: Supported formats are RGBAFormat, RGFormat, or RedFormat.";
var ERROR_TYPE = 'THREE.KTX2Exporter: Supported types are FloatType, HalfFloatType, or UnsignedByteType."';
var ERROR_COLOR_SPACE = "THREE.KTX2Exporter: Supported color spaces are SRGBColorSpace (UnsignedByteType only), LinearSRGBColorSpace, or NoColorSpace.";
var KTX2Exporter = class {
  /**
   * This method has two variants.
   *
   * - When exporting a data texture, it receives one parameter. The data or 3D data texture.
   * - When exporting a render target (e.g. a PMREM), it receives two parameters. The renderer and the
   * render target.
   *
   * @async
   * @param {(DataTexture|Data3DTexture|WebGPURenderer|WebGLRenderer)} arg1 - The data texture to export or a renderer.
   * @param {RenderTarget} [arg2] - The render target that should be exported
   * @return {Promise<Uint8Array>} A Promise that resolves with the exported KTX2.
   */
  async parse(arg1, arg2) {
    let texture;
    if (arg1.isDataTexture || arg1.isData3DTexture) {
      texture = arg1;
    } else if ((arg1.isWebGLRenderer || arg1.isWebGPURenderer) && arg2.isRenderTarget) {
      texture = await toDataTexture(arg1, arg2);
    } else {
      throw new Error(ERROR_INPUT);
    }
    if (VK_FORMAT_MAP[texture.format] === void 0) {
      throw new Error(ERROR_FORMAT);
    }
    if (VK_FORMAT_MAP[texture.format][texture.type] === void 0) {
      throw new Error(ERROR_TYPE);
    }
    if (VK_FORMAT_MAP[texture.format][texture.type][texture.colorSpace] === void 0) {
      throw new Error(ERROR_COLOR_SPACE);
    }
    const array = texture.image.data;
    const channelCount = getChannelCount(texture);
    const container = new Ii();
    container.vkFormat = VK_FORMAT_MAP[texture.format][texture.type][texture.colorSpace];
    container.typeSize = array.BYTES_PER_ELEMENT;
    container.pixelWidth = texture.image.width;
    container.pixelHeight = texture.image.height;
    if (texture.isData3DTexture) {
      container.pixelDepth = texture.image.depth;
    }
    const basicDesc = container.dataFormatDescriptor[0];
    basicDesc.colorModel = l;
    basicDesc.colorPrimaries = texture.colorSpace === NoColorSpace ? T : C;
    basicDesc.transferFunction = ColorManagement.getTransfer(texture.colorSpace) === SRGBTransfer ? u : x;
    basicDesc.texelBlockDimension = [0, 0, 0, 0];
    basicDesc.bytesPlane = [
      container.typeSize * channelCount,
      0,
      0,
      0,
      0,
      0,
      0,
      0
    ];
    for (let i = 0; i < channelCount; ++i) {
      let channelType = KHR_DF_CHANNEL_MAP[i];
      if (channelType === Z && basicDesc.transferFunction !== x) {
        channelType |= nt;
      }
      if (texture.type === FloatType || texture.type === HalfFloatType) {
        channelType |= $;
        channelType |= tt;
      }
      basicDesc.samples.push({
        channelType,
        bitOffset: i * array.BYTES_PER_ELEMENT * 8,
        bitLength: array.BYTES_PER_ELEMENT * 8 - 1,
        samplePosition: [0, 0, 0, 0],
        sampleLower: KHR_DF_CHANNEL_SAMPLE_LOWER_UPPER[texture.type][0],
        sampleUpper: KHR_DF_CHANNEL_SAMPLE_LOWER_UPPER[texture.type][1]
      });
    }
    container.levels = [{
      levelData: new Uint8Array(array.buffer, array.byteOffset, array.byteLength),
      uncompressedByteLength: array.byteLength
    }];
    container.keyValue["KTXwriter"] = `three.js ${REVISION}`;
    return Wi(container, { keepWriter: true });
  }
};
async function toDataTexture(renderer2, rtt) {
  const channelCount = getChannelCount(rtt.texture);
  let view;
  if (renderer2.isWebGLRenderer) {
    if (rtt.texture.type === FloatType) {
      view = new Float32Array(rtt.width * rtt.height * channelCount);
    } else if (rtt.texture.type === HalfFloatType) {
      view = new Uint16Array(rtt.width * rtt.height * channelCount);
    } else if (rtt.texture.type === UnsignedByteType) {
      view = new Uint8Array(rtt.width * rtt.height * channelCount);
    } else {
      throw new Error(ERROR_TYPE);
    }
    await renderer2.readRenderTargetPixelsAsync(rtt, 0, 0, rtt.width, rtt.height, view);
  } else {
    view = await renderer2.readRenderTargetPixelsAsync(rtt, 0, 0, rtt.width, rtt.height);
  }
  const texture = new DataTexture(view, rtt.width, rtt.height, rtt.texture.format, rtt.texture.type);
  texture.colorSpace = rtt.texture.colorSpace;
  return texture;
}
function getChannelCount(texture) {
  switch (texture.format) {
    case RGBAFormat:
      return 4;
    case RGFormat:
    case RGIntegerFormat:
      return 2;
    case RedFormat:
    case RedIntegerFormat:
      return 1;
    default:
      throw new Error(ERROR_FORMAT);
  }
}

// node_modules/three/examples/jsm/exporters/OBJExporter.js
var OBJExporter = class {
  /**
   * Parses the given 3D object and generates the OBJ output.
   *
   * If the 3D object is composed of multiple children and geometry, they are merged into a single mesh in the file.
   *
   * @param {Object3D} object - The 3D object to export.
   * @return {string} The exported OBJ.
   */
  parse(object) {
    let output = "";
    let indexVertex = 0;
    let indexVertexUvs = 0;
    let indexNormals = 0;
    const vertex = new Vector3();
    const color = new Color();
    const normal = new Vector3();
    const uv = new Vector2();
    const face = [];
    function parseMesh(mesh) {
      let nbVertex = 0;
      let nbNormals = 0;
      let nbVertexUvs = 0;
      const geometry = mesh.geometry;
      const normalMatrixWorld = new Matrix3();
      const vertices = geometry.getAttribute("position");
      const normals = geometry.getAttribute("normal");
      const uvs = geometry.getAttribute("uv");
      const indices = geometry.getIndex();
      output += "o " + mesh.name + "\n";
      if (mesh.material && mesh.material.name) {
        output += "usemtl " + mesh.material.name + "\n";
      }
      if (vertices !== void 0) {
        for (let i = 0, l2 = vertices.count; i < l2; i++, nbVertex++) {
          vertex.fromBufferAttribute(vertices, i);
          vertex.applyMatrix4(mesh.matrixWorld);
          output += "v " + vertex.x + " " + vertex.y + " " + vertex.z + "\n";
        }
      }
      if (uvs !== void 0) {
        for (let i = 0, l2 = uvs.count; i < l2; i++, nbVertexUvs++) {
          uv.fromBufferAttribute(uvs, i);
          output += "vt " + uv.x + " " + uv.y + "\n";
        }
      }
      if (normals !== void 0) {
        normalMatrixWorld.getNormalMatrix(mesh.matrixWorld);
        for (let i = 0, l2 = normals.count; i < l2; i++, nbNormals++) {
          normal.fromBufferAttribute(normals, i);
          normal.applyMatrix3(normalMatrixWorld).normalize();
          output += "vn " + normal.x + " " + normal.y + " " + normal.z + "\n";
        }
      }
      if (indices !== null) {
        for (let i = 0, l2 = indices.count; i < l2; i += 3) {
          for (let m = 0; m < 3; m++) {
            const j2 = indices.getX(i + m) + 1;
            face[m] = indexVertex + j2 + (normals || uvs ? "/" + (uvs ? indexVertexUvs + j2 : "") + (normals ? "/" + (indexNormals + j2) : "") : "");
          }
          output += "f " + face.join(" ") + "\n";
        }
      } else {
        for (let i = 0, l2 = vertices.count; i < l2; i += 3) {
          for (let m = 0; m < 3; m++) {
            const j2 = i + m + 1;
            face[m] = indexVertex + j2 + (normals || uvs ? "/" + (uvs ? indexVertexUvs + j2 : "") + (normals ? "/" + (indexNormals + j2) : "") : "");
          }
          output += "f " + face.join(" ") + "\n";
        }
      }
      indexVertex += nbVertex;
      indexVertexUvs += nbVertexUvs;
      indexNormals += nbNormals;
    }
    function parseLine(line2) {
      let nbVertex = 0;
      const geometry = line2.geometry;
      const type = line2.type;
      const vertices = geometry.getAttribute("position");
      output += "o " + line2.name + "\n";
      if (vertices !== void 0) {
        for (let i = 0, l2 = vertices.count; i < l2; i++, nbVertex++) {
          vertex.fromBufferAttribute(vertices, i);
          vertex.applyMatrix4(line2.matrixWorld);
          output += "v " + vertex.x + " " + vertex.y + " " + vertex.z + "\n";
        }
      }
      if (type === "Line") {
        output += "l ";
        for (let j2 = 1, l2 = vertices.count; j2 <= l2; j2++) {
          output += indexVertex + j2 + " ";
        }
        output += "\n";
      }
      if (type === "LineSegments") {
        for (let j2 = 1, k2 = j2 + 1, l2 = vertices.count; j2 < l2; j2 += 2, k2 = j2 + 1) {
          output += "l " + (indexVertex + j2) + " " + (indexVertex + k2) + "\n";
        }
      }
      indexVertex += nbVertex;
    }
    function parsePoints(points) {
      let nbVertex = 0;
      const geometry = points.geometry;
      const vertices = geometry.getAttribute("position");
      const colors = geometry.getAttribute("color");
      output += "o " + points.name + "\n";
      if (vertices !== void 0) {
        for (let i = 0, l2 = vertices.count; i < l2; i++, nbVertex++) {
          vertex.fromBufferAttribute(vertices, i);
          vertex.applyMatrix4(points.matrixWorld);
          output += "v " + vertex.x + " " + vertex.y + " " + vertex.z;
          if (colors !== void 0) {
            color.fromBufferAttribute(colors, i);
            ColorManagement.workingToColorSpace(color, SRGBColorSpace);
            output += " " + color.r + " " + color.g + " " + color.b;
          }
          output += "\n";
        }
        output += "p ";
        for (let j2 = 1, l2 = vertices.count; j2 <= l2; j2++) {
          output += indexVertex + j2 + " ";
        }
        output += "\n";
      }
      indexVertex += nbVertex;
    }
    object.traverse(function(child) {
      if (child.isMesh === true) {
        parseMesh(child);
      }
      if (child.isLine === true) {
        parseLine(child);
      }
      if (child.isPoints === true) {
        parsePoints(child);
      }
    });
    return output;
  }
};

// node_modules/three/examples/jsm/exporters/PLYExporter.js
var PLYExporter = class {
  /**
   * Parses the given 3D object and generates the PLY output.
   *
   * If the 3D object is composed of multiple children and geometry, they are merged into a single mesh in the file.
   *
   * @param {Object3D} object - The 3D object to export.
   * @param {PLYExporter~OnDone} onDone - A callback function that is executed when the export has finished.
   * @param {PLYExporter~Options} options - The export options.
   * @return {?string|ArrayBuffer} The exported PLY.
   */
  parse(object, onDone, options = {}) {
    function traverseMeshes(cb) {
      object.traverse(function(child) {
        if (child.isMesh === true || child.isPoints) {
          const mesh = child;
          const geometry = mesh.geometry;
          if (geometry.hasAttribute("position") === true) {
            cb(mesh, geometry);
          }
        }
      });
    }
    const defaultOptions = {
      binary: false,
      excludeAttributes: [],
      // normal, uv, color, index
      littleEndian: false
    };
    options = Object.assign(defaultOptions, options);
    const excludeAttributes = options.excludeAttributes;
    let includeIndices = true;
    let includeNormals = false;
    let includeColors = false;
    let includeUVs = false;
    let vertexCount = 0;
    let faceCount = 0;
    object.traverse(function(child) {
      if (child.isMesh === true) {
        const mesh = child;
        const geometry = mesh.geometry;
        const vertices = geometry.getAttribute("position");
        const normals = geometry.getAttribute("normal");
        const uvs = geometry.getAttribute("uv");
        const colors = geometry.getAttribute("color");
        const indices = geometry.getIndex();
        if (vertices === void 0) {
          return;
        }
        vertexCount += vertices.count;
        faceCount += indices ? indices.count / 3 : vertices.count / 3;
        if (normals !== void 0) includeNormals = true;
        if (uvs !== void 0) includeUVs = true;
        if (colors !== void 0) includeColors = true;
      } else if (child.isPoints) {
        const mesh = child;
        const geometry = mesh.geometry;
        const vertices = geometry.getAttribute("position");
        const normals = geometry.getAttribute("normal");
        const colors = geometry.getAttribute("color");
        vertexCount += vertices.count;
        if (normals !== void 0) includeNormals = true;
        if (colors !== void 0) includeColors = true;
        includeIndices = false;
      }
    });
    const tempColor = new Color();
    includeIndices = includeIndices && excludeAttributes.indexOf("index") === -1;
    includeNormals = includeNormals && excludeAttributes.indexOf("normal") === -1;
    includeColors = includeColors && excludeAttributes.indexOf("color") === -1;
    includeUVs = includeUVs && excludeAttributes.indexOf("uv") === -1;
    if (includeIndices && faceCount !== Math.floor(faceCount)) {
      console.error(
        "PLYExporter: Failed to generate a valid PLY file with triangle indices because the number of indices is not divisible by 3."
      );
      return null;
    }
    const indexByteCount = 4;
    let header = `ply
format ${options.binary ? options.littleEndian ? "binary_little_endian" : "binary_big_endian" : "ascii"} 1.0
element vertex ${vertexCount}
property float x
property float y
property float z
`;
    if (includeNormals === true) {
      header += "property float nx\nproperty float ny\nproperty float nz\n";
    }
    if (includeUVs === true) {
      header += "property float s\nproperty float t\n";
    }
    if (includeColors === true) {
      header += "property uchar red\nproperty uchar green\nproperty uchar blue\n";
    }
    if (includeIndices === true) {
      header += `element face ${faceCount}
property list uchar int vertex_index
`;
    }
    header += "end_header\n";
    const vertex = new Vector3();
    const normalMatrixWorld = new Matrix3();
    let result = null;
    if (options.binary === true) {
      const headerBin = new TextEncoder().encode(header);
      const vertexListLength = vertexCount * (4 * 3 + (includeNormals ? 4 * 3 : 0) + (includeColors ? 3 : 0) + (includeUVs ? 4 * 2 : 0));
      const faceListLength = includeIndices ? faceCount * (indexByteCount * 3 + 1) : 0;
      const output = new DataView(new ArrayBuffer(headerBin.length + vertexListLength + faceListLength));
      new Uint8Array(output.buffer).set(headerBin, 0);
      let vOffset = headerBin.length;
      let fOffset = headerBin.length + vertexListLength;
      let writtenVertices = 0;
      traverseMeshes(function(mesh, geometry) {
        const vertices = geometry.getAttribute("position");
        const normals = geometry.getAttribute("normal");
        const uvs = geometry.getAttribute("uv");
        const colors = geometry.getAttribute("color");
        const indices = geometry.getIndex();
        normalMatrixWorld.getNormalMatrix(mesh.matrixWorld);
        for (let i = 0, l2 = vertices.count; i < l2; i++) {
          vertex.fromBufferAttribute(vertices, i);
          vertex.applyMatrix4(mesh.matrixWorld);
          output.setFloat32(vOffset, vertex.x, options.littleEndian);
          vOffset += 4;
          output.setFloat32(vOffset, vertex.y, options.littleEndian);
          vOffset += 4;
          output.setFloat32(vOffset, vertex.z, options.littleEndian);
          vOffset += 4;
          if (includeNormals === true) {
            if (normals != null) {
              vertex.fromBufferAttribute(normals, i);
              vertex.applyMatrix3(normalMatrixWorld).normalize();
              output.setFloat32(vOffset, vertex.x, options.littleEndian);
              vOffset += 4;
              output.setFloat32(vOffset, vertex.y, options.littleEndian);
              vOffset += 4;
              output.setFloat32(vOffset, vertex.z, options.littleEndian);
              vOffset += 4;
            } else {
              output.setFloat32(vOffset, 0, options.littleEndian);
              vOffset += 4;
              output.setFloat32(vOffset, 0, options.littleEndian);
              vOffset += 4;
              output.setFloat32(vOffset, 0, options.littleEndian);
              vOffset += 4;
            }
          }
          if (includeUVs === true) {
            if (uvs != null) {
              output.setFloat32(vOffset, uvs.getX(i), options.littleEndian);
              vOffset += 4;
              output.setFloat32(vOffset, uvs.getY(i), options.littleEndian);
              vOffset += 4;
            } else {
              output.setFloat32(vOffset, 0, options.littleEndian);
              vOffset += 4;
              output.setFloat32(vOffset, 0, options.littleEndian);
              vOffset += 4;
            }
          }
          if (includeColors === true) {
            if (colors != null) {
              tempColor.fromBufferAttribute(colors, i);
              ColorManagement.workingToColorSpace(tempColor, SRGBColorSpace);
              output.setUint8(vOffset, Math.floor(tempColor.r * 255));
              vOffset += 1;
              output.setUint8(vOffset, Math.floor(tempColor.g * 255));
              vOffset += 1;
              output.setUint8(vOffset, Math.floor(tempColor.b * 255));
              vOffset += 1;
            } else {
              output.setUint8(vOffset, 255);
              vOffset += 1;
              output.setUint8(vOffset, 255);
              vOffset += 1;
              output.setUint8(vOffset, 255);
              vOffset += 1;
            }
          }
        }
        if (includeIndices === true) {
          if (indices !== null) {
            for (let i = 0, l2 = indices.count; i < l2; i += 3) {
              output.setUint8(fOffset, 3);
              fOffset += 1;
              output.setUint32(fOffset, indices.getX(i + 0) + writtenVertices, options.littleEndian);
              fOffset += indexByteCount;
              output.setUint32(fOffset, indices.getX(i + 1) + writtenVertices, options.littleEndian);
              fOffset += indexByteCount;
              output.setUint32(fOffset, indices.getX(i + 2) + writtenVertices, options.littleEndian);
              fOffset += indexByteCount;
            }
          } else {
            for (let i = 0, l2 = vertices.count; i < l2; i += 3) {
              output.setUint8(fOffset, 3);
              fOffset += 1;
              output.setUint32(fOffset, writtenVertices + i, options.littleEndian);
              fOffset += indexByteCount;
              output.setUint32(fOffset, writtenVertices + i + 1, options.littleEndian);
              fOffset += indexByteCount;
              output.setUint32(fOffset, writtenVertices + i + 2, options.littleEndian);
              fOffset += indexByteCount;
            }
          }
        }
        writtenVertices += vertices.count;
      });
      result = output.buffer;
    } else {
      let writtenVertices = 0;
      let vertexList = "";
      let faceList = "";
      traverseMeshes(function(mesh, geometry) {
        const vertices = geometry.getAttribute("position");
        const normals = geometry.getAttribute("normal");
        const uvs = geometry.getAttribute("uv");
        const colors = geometry.getAttribute("color");
        const indices = geometry.getIndex();
        normalMatrixWorld.getNormalMatrix(mesh.matrixWorld);
        for (let i = 0, l2 = vertices.count; i < l2; i++) {
          vertex.fromBufferAttribute(vertices, i);
          vertex.applyMatrix4(mesh.matrixWorld);
          let line2 = vertex.x + " " + vertex.y + " " + vertex.z;
          if (includeNormals === true) {
            if (normals != null) {
              vertex.fromBufferAttribute(normals, i);
              vertex.applyMatrix3(normalMatrixWorld).normalize();
              line2 += " " + vertex.x + " " + vertex.y + " " + vertex.z;
            } else {
              line2 += " 0 0 0";
            }
          }
          if (includeUVs === true) {
            if (uvs != null) {
              line2 += " " + uvs.getX(i) + " " + uvs.getY(i);
            } else {
              line2 += " 0 0";
            }
          }
          if (includeColors === true) {
            if (colors != null) {
              tempColor.fromBufferAttribute(colors, i);
              ColorManagement.workingToColorSpace(tempColor, SRGBColorSpace);
              line2 += " " + Math.floor(tempColor.r * 255) + " " + Math.floor(tempColor.g * 255) + " " + Math.floor(tempColor.b * 255);
            } else {
              line2 += " 255 255 255";
            }
          }
          vertexList += line2 + "\n";
        }
        if (includeIndices === true) {
          if (indices !== null) {
            for (let i = 0, l2 = indices.count; i < l2; i += 3) {
              faceList += `3 ${indices.getX(i + 0) + writtenVertices}`;
              faceList += ` ${indices.getX(i + 1) + writtenVertices}`;
              faceList += ` ${indices.getX(i + 2) + writtenVertices}
`;
            }
          } else {
            for (let i = 0, l2 = vertices.count; i < l2; i += 3) {
              faceList += `3 ${writtenVertices + i} ${writtenVertices + i + 1} ${writtenVertices + i + 2}
`;
            }
          }
          faceCount += indices ? indices.count / 3 : vertices.count / 3;
        }
        writtenVertices += vertices.count;
      });
      result = `${header}${vertexList}${includeIndices ? `${faceList}
` : "\n"}`;
    }
    if (typeof onDone === "function") requestAnimationFrame(() => onDone(result));
    return result;
  }
};

// node_modules/three/examples/jsm/exporters/STLExporter.js
var STLExporter = class {
  /**
   * Parses the given 3D object and generates the STL output.
   *
   * If the 3D object is composed of multiple children and geometry, they are merged into a single mesh in the file.
   *
   * @param {Object3D} scene - A scene, mesh or any other 3D object containing meshes to encode.
   * @param {STLExporter~Options} options - The export options.
   * @return {string|ArrayBuffer} The exported STL.
   */
  parse(scene, options = {}) {
    options = Object.assign({
      binary: false
    }, options);
    const binary = options.binary;
    const objects = [];
    let triangles = 0;
    scene.traverse(function(object) {
      if (object.isMesh) {
        const geometry = object.geometry;
        const index2 = geometry.index;
        const positionAttribute = geometry.getAttribute("position");
        triangles += index2 !== null ? index2.count / 3 : positionAttribute.count / 3;
        objects.push({
          object3d: object,
          geometry
        });
      }
    });
    let output;
    let offset = 80;
    if (binary === true) {
      const bufferLength = triangles * 2 + triangles * 3 * 4 * 4 + 80 + 4;
      const arrayBuffer = new ArrayBuffer(bufferLength);
      output = new DataView(arrayBuffer);
      output.setUint32(offset, triangles, true);
      offset += 4;
    } else {
      output = "";
      output += "solid exported\n";
    }
    const vA = new Vector3();
    const vB = new Vector3();
    const vC = new Vector3();
    const cb = new Vector3();
    const ab = new Vector3();
    const normal = new Vector3();
    for (let i = 0, il = objects.length; i < il; i++) {
      const object = objects[i].object3d;
      const geometry = objects[i].geometry;
      const index2 = geometry.index;
      const positionAttribute = geometry.getAttribute("position");
      if (index2 !== null) {
        for (let j2 = 0; j2 < index2.count; j2 += 3) {
          const a2 = index2.getX(j2 + 0);
          const b3 = index2.getX(j2 + 1);
          const c2 = index2.getX(j2 + 2);
          writeFace(a2, b3, c2, positionAttribute, object);
        }
      } else {
        for (let j2 = 0; j2 < positionAttribute.count; j2 += 3) {
          const a2 = j2 + 0;
          const b3 = j2 + 1;
          const c2 = j2 + 2;
          writeFace(a2, b3, c2, positionAttribute, object);
        }
      }
    }
    if (binary === false) {
      output += "endsolid exported\n";
    }
    return output;
    function writeFace(a2, b3, c2, positionAttribute, object) {
      vA.fromBufferAttribute(positionAttribute, a2);
      vB.fromBufferAttribute(positionAttribute, b3);
      vC.fromBufferAttribute(positionAttribute, c2);
      if (object.isSkinnedMesh === true) {
        object.applyBoneTransform(a2, vA);
        object.applyBoneTransform(b3, vB);
        object.applyBoneTransform(c2, vC);
      }
      vA.applyMatrix4(object.matrixWorld);
      vB.applyMatrix4(object.matrixWorld);
      vC.applyMatrix4(object.matrixWorld);
      writeNormal(vA, vB, vC);
      writeVertex(vA);
      writeVertex(vB);
      writeVertex(vC);
      if (binary === true) {
        output.setUint16(offset, 0, true);
        offset += 2;
      } else {
        output += "		endloop\n";
        output += "	endfacet\n";
      }
    }
    function writeNormal(vA2, vB2, vC2) {
      cb.subVectors(vC2, vB2);
      ab.subVectors(vA2, vB2);
      cb.cross(ab).normalize();
      normal.copy(cb).normalize();
      if (binary === true) {
        output.setFloat32(offset, normal.x, true);
        offset += 4;
        output.setFloat32(offset, normal.y, true);
        offset += 4;
        output.setFloat32(offset, normal.z, true);
        offset += 4;
      } else {
        output += "	facet normal " + normal.x + " " + normal.y + " " + normal.z + "\n";
        output += "		outer loop\n";
      }
    }
    function writeVertex(vertex) {
      if (binary === true) {
        output.setFloat32(offset, vertex.x, true);
        offset += 4;
        output.setFloat32(offset, vertex.y, true);
        offset += 4;
        output.setFloat32(offset, vertex.z, true);
        offset += 4;
      } else {
        output += "			vertex " + vertex.x + " " + vertex.y + " " + vertex.z + "\n";
      }
    }
  }
};

// node_modules/three/examples/jsm/exporters/USDZExporter.js
var USDZExporter = class {
  /**
   * Constructs a new USDZ exporter.
   */
  constructor() {
    this.textureUtils = null;
  }
  /**
   * Sets the texture utils for this exporter. Only relevant when compressed textures have to be exported.
   *
   * Depending on whether you use {@link WebGLRenderer} or {@link WebGPURenderer}, you must inject the
   * corresponding texture utils {@link WebGLTextureUtils} or {@link WebGPUTextureUtils}.
   *
   * @param {WebGLTextureUtils|WebGPUTextureUtils} utils - The texture utils.
   */
  setTextureUtils(utils) {
    this.textureUtils = utils;
  }
  /**
   * Parse the given 3D object and generates the USDZ output.
   *
   * @param {Object3D} scene - The 3D object to export.
   * @param {USDZExporter~OnDone} onDone - A callback function that is executed when the export has finished.
   * @param {USDZExporter~OnError} onError - A callback function that is executed when an error happens.
   * @param {USDZExporter~Options} options - The export options.
   */
  parse(scene, onDone, onError, options) {
    this.parseAsync(scene, options).then(onDone).catch(onError);
  }
  /**
   * Async version of {@link USDZExporter#parse}.
   *
   * @async
   * @param {Object3D} scene - The 3D object to export.
   * @param {USDZExporter~Options} options - The export options.
   * @return {Promise<ArrayBuffer>} A Promise that resolved with the exported USDZ data.
   */
  async parseAsync(scene, options = {}) {
    options = Object.assign({
      ar: {
        anchoring: { type: "plane" },
        planeAnchoring: { alignment: "horizontal" }
      },
      includeAnchoringProperties: true,
      quickLookCompatible: false,
      maxTextureSize: 1024
    }, options);
    const files = {};
    const modelFileName = "model.usda";
    files[modelFileName] = null;
    let output = buildHeader();
    output += buildSceneStart(options);
    const materials = {};
    const textures = {};
    scene.traverseVisible((object) => {
      if (object.isMesh) {
        const geometry = object.geometry;
        const material = object.material;
        if (material.isMeshStandardMaterial) {
          const geometryFileName = "geometries/Geometry_" + geometry.id + ".usda";
          if (!(geometryFileName in files)) {
            const meshObject = buildMeshObject(geometry);
            files[geometryFileName] = buildUSDFileAsString(meshObject);
          }
          if (!(material.uuid in materials)) {
            materials[material.uuid] = material;
          }
          output += buildXform(object, geometry, materials[material.uuid]);
        } else {
          console.warn("THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)", object);
        }
      } else if (object.isCamera) {
        output += buildCamera(object);
      }
    });
    output += buildSceneEnd();
    output += buildMaterials(materials, textures, options.quickLookCompatible);
    files[modelFileName] = strToU8(output);
    output = null;
    for (const id in textures) {
      let texture = textures[id];
      if (texture.isCompressedTexture === true) {
        if (this.textureUtils === null) {
          throw new Error("THREE.USDZExporter: setTextureUtils() must be called to process compressed textures.");
        } else {
          texture = await this.textureUtils.decompress(texture);
        }
      }
      const canvas = imageToCanvas(texture.image, texture.flipY, options.maxTextureSize);
      const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png", 1));
      files[`textures/Texture_${id}.png`] = new Uint8Array(await blob.arrayBuffer());
    }
    let offset = 0;
    for (const filename in files) {
      const file = files[filename];
      const headerSize = 34 + filename.length;
      offset += headerSize;
      const offsetMod64 = offset & 63;
      if (offsetMod64 !== 4) {
        const padLength = 64 - offsetMod64;
        const padding = new Uint8Array(padLength);
        files[filename] = [file, { extra: { 12345: padding } }];
      }
      offset = file.length;
    }
    return zipSync(files, { level: 0 });
  }
};
function imageToCanvas(image, flipY, maxTextureSize) {
  if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
    const scale2 = maxTextureSize / Math.max(image.width, image.height);
    const canvas = document.createElement("canvas");
    canvas.width = image.width * Math.min(1, scale2);
    canvas.height = image.height * Math.min(1, scale2);
    const context = canvas.getContext("2d");
    if (flipY === true) {
      context.translate(0, canvas.height);
      context.scale(1, -1);
    }
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    return canvas;
  } else {
    throw new Error("THREE.USDZExporter: No valid image data found. Unable to process texture.");
  }
}
var PRECISION = 7;
function buildHeader() {
  return `#usda 1.0
(
	customLayerData = {
		string creator = "Three.js USDZExporter"
	}
	defaultPrim = "Root"
	metersPerUnit = 1
	upAxis = "Y"
)

`;
}
function buildSceneStart(options) {
  const alignment = options.includeAnchoringProperties === true ? `
		token preliminary:anchoring:type = "${options.ar.anchoring.type}"
		token preliminary:planeAnchoring:alignment = "${options.ar.planeAnchoring.alignment}"
	` : "";
  return `def Xform "Root"
{
	def Scope "Scenes" (
		kind = "sceneLibrary"
	)
	{
		def Xform "Scene" (
			customData = {
				bool preliminary_collidesWithEnvironment = 0
				string sceneName = "Scene"
			}
			sceneName = "Scene"
		)
		{${alignment}
`;
}
function buildSceneEnd() {
  return `
		}
	}
}

`;
}
function buildUSDFileAsString(dataToInsert) {
  let output = buildHeader();
  output += dataToInsert;
  return strToU8(output);
}
function buildXform(object, geometry, material) {
  const name2 = "Object_" + object.id;
  const transform2 = buildMatrix(object.matrixWorld);
  if (object.matrixWorld.determinant() < 0) {
    console.warn("THREE.USDZExporter: USDZ does not support negative scales", object);
  }
  return `			def Xform "${name2}" (
				prepend references = @./geometries/Geometry_${geometry.id}.usda@</Geometry>
				prepend apiSchemas = ["MaterialBindingAPI"]
			)
			{
				matrix4d xformOp:transform = ${transform2}
				uniform token[] xformOpOrder = ["xformOp:transform"]

				rel material:binding = </Materials/Material_${material.id}>
			}

`;
}
function buildMatrix(matrix2) {
  const array = matrix2.elements;
  return `( ${buildMatrixRow(array, 0)}, ${buildMatrixRow(array, 4)}, ${buildMatrixRow(array, 8)}, ${buildMatrixRow(array, 12)} )`;
}
function buildMatrixRow(array, offset) {
  return `(${array[offset + 0]}, ${array[offset + 1]}, ${array[offset + 2]}, ${array[offset + 3]})`;
}
function buildMeshObject(geometry) {
  const mesh = buildMesh(geometry);
  return `
def "Geometry"
{
${mesh}
}
`;
}
function buildMesh(geometry) {
  const name2 = "Geometry";
  const attributes = geometry.attributes;
  const count = attributes.position.count;
  return `
	def Mesh "${name2}"
	{
		int[] faceVertexCounts = [${buildMeshVertexCount(geometry)}]
		int[] faceVertexIndices = [${buildMeshVertexIndices(geometry)}]
		normal3f[] normals = [${buildVector3Array(attributes.normal, count)}] (
			interpolation = "vertex"
		)
		point3f[] points = [${buildVector3Array(attributes.position, count)}]
${buildPrimvars(attributes)}
		uniform token subdivisionScheme = "none"
	}
`;
}
function buildMeshVertexCount(geometry) {
  const count = geometry.index !== null ? geometry.index.count : geometry.attributes.position.count;
  return Array(count / 3).fill(3).join(", ");
}
function buildMeshVertexIndices(geometry) {
  const index2 = geometry.index;
  const array = [];
  if (index2 !== null) {
    for (let i = 0; i < index2.count; i++) {
      array.push(index2.getX(i));
    }
  } else {
    const length2 = geometry.attributes.position.count;
    for (let i = 0; i < length2; i++) {
      array.push(i);
    }
  }
  return array.join(", ");
}
function buildVector3Array(attribute, count) {
  if (attribute === void 0) {
    console.warn("USDZExporter: Normals missing.");
    return Array(count).fill("(0, 0, 0)").join(", ");
  }
  const array = [];
  for (let i = 0; i < attribute.count; i++) {
    const x2 = attribute.getX(i);
    const y = attribute.getY(i);
    const z = attribute.getZ(i);
    array.push(`(${x2.toPrecision(PRECISION)}, ${y.toPrecision(PRECISION)}, ${z.toPrecision(PRECISION)})`);
  }
  return array.join(", ");
}
function buildVector2Array(attribute) {
  const array = [];
  for (let i = 0; i < attribute.count; i++) {
    const x2 = attribute.getX(i);
    const y = attribute.getY(i);
    array.push(`(${x2.toPrecision(PRECISION)}, ${1 - y.toPrecision(PRECISION)})`);
  }
  return array.join(", ");
}
function buildPrimvars(attributes) {
  let string = "";
  for (let i = 0; i < 4; i++) {
    const id = i > 0 ? i : "";
    const attribute = attributes["uv" + id];
    if (attribute !== void 0) {
      string += `
		texCoord2f[] primvars:st${id} = [${buildVector2Array(attribute)}] (
			interpolation = "vertex"
		)`;
    }
  }
  const colorAttribute = attributes.color;
  if (colorAttribute !== void 0) {
    const count = colorAttribute.count;
    string += `
	color3f[] primvars:displayColor = [${buildVector3Array(colorAttribute, count)}] (
		interpolation = "vertex"
		)`;
  }
  return string;
}
function buildMaterials(materials, textures, quickLookCompatible = false) {
  const array = [];
  for (const uuid in materials) {
    const material = materials[uuid];
    array.push(buildMaterial(material, textures, quickLookCompatible));
  }
  return `def "Materials"
{
${array.join("")}
}

`;
}
function buildMaterial(material, textures, quickLookCompatible = false) {
  const pad = "			";
  const inputs = [];
  const samplers = [];
  function buildTexture(texture, mapType, color) {
    const id = texture.source.id + "_" + texture.flipY;
    textures[id] = texture;
    const uv = texture.channel > 0 ? "st" + texture.channel : "st";
    const WRAPPINGS = {
      1e3: "repeat",
      // RepeatWrapping
      1001: "clamp",
      // ClampToEdgeWrapping
      1002: "mirror"
      // MirroredRepeatWrapping
    };
    const repeat = texture.repeat.clone();
    const offset = texture.offset.clone();
    const rotation2 = texture.rotation;
    const xRotationOffset = Math.sin(rotation2);
    const yRotationOffset = Math.cos(rotation2);
    offset.y = 1 - offset.y - repeat.y;
    if (quickLookCompatible) {
      offset.x = offset.x / repeat.x;
      offset.y = offset.y / repeat.y;
      offset.x += xRotationOffset / repeat.x;
      offset.y += yRotationOffset - 1;
    } else {
      offset.x += xRotationOffset * repeat.x;
      offset.y += (1 - yRotationOffset) * repeat.y;
    }
    return `
		def Shader "PrimvarReader_${mapType}"
		{
			uniform token info:id = "UsdPrimvarReader_float2"
			float2 inputs:fallback = (0.0, 0.0)
			token inputs:varname = "${uv}"
			float2 outputs:result
		}

		def Shader "Transform2d_${mapType}"
		{
			uniform token info:id = "UsdTransform2d"
			token inputs:in.connect = </Materials/Material_${material.id}/PrimvarReader_${mapType}.outputs:result>
			float inputs:rotation = ${(rotation2 * (180 / Math.PI)).toFixed(PRECISION)}
			float2 inputs:scale = ${buildVector2(repeat)}
			float2 inputs:translation = ${buildVector2(offset)}
			float2 outputs:result
		}

		def Shader "Texture_${texture.id}_${mapType}"
		{
			uniform token info:id = "UsdUVTexture"
			asset inputs:file = @textures/Texture_${id}.png@
			float2 inputs:st.connect = </Materials/Material_${material.id}/Transform2d_${mapType}.outputs:result>
			${color !== void 0 ? "float4 inputs:scale = " + buildColor4(color) : ""}
			token inputs:sourceColorSpace = "${texture.colorSpace === NoColorSpace ? "raw" : "sRGB"}"
			token inputs:wrapS = "${WRAPPINGS[texture.wrapS]}"
			token inputs:wrapT = "${WRAPPINGS[texture.wrapT]}"
			float outputs:r
			float outputs:g
			float outputs:b
			float3 outputs:rgb
			${material.transparent || material.alphaTest > 0 ? "float outputs:a" : ""}
		}`;
  }
  if (material.side === DoubleSide) {
    console.warn("THREE.USDZExporter: USDZ does not support double sided materials", material);
  }
  if (material.map !== null) {
    inputs.push(`${pad}color3f inputs:diffuseColor.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:rgb>`);
    if (material.transparent) {
      inputs.push(`${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:a>`);
    } else if (material.alphaTest > 0) {
      inputs.push(`${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:a>`);
      inputs.push(`${pad}float inputs:opacityThreshold = ${material.alphaTest}`);
    }
    samplers.push(buildTexture(material.map, "diffuse", material.color));
  } else {
    inputs.push(`${pad}color3f inputs:diffuseColor = ${buildColor(material.color)}`);
  }
  if (material.emissiveMap !== null) {
    inputs.push(`${pad}color3f inputs:emissiveColor.connect = </Materials/Material_${material.id}/Texture_${material.emissiveMap.id}_emissive.outputs:rgb>`);
    samplers.push(buildTexture(material.emissiveMap, "emissive", new Color(material.emissive.r * material.emissiveIntensity, material.emissive.g * material.emissiveIntensity, material.emissive.b * material.emissiveIntensity)));
  } else if (material.emissive.getHex() > 0) {
    inputs.push(`${pad}color3f inputs:emissiveColor = ${buildColor(material.emissive)}`);
  }
  if (material.normalMap !== null) {
    inputs.push(`${pad}normal3f inputs:normal.connect = </Materials/Material_${material.id}/Texture_${material.normalMap.id}_normal.outputs:rgb>`);
    samplers.push(buildTexture(material.normalMap, "normal"));
  }
  if (material.aoMap !== null) {
    inputs.push(`${pad}float inputs:occlusion.connect = </Materials/Material_${material.id}/Texture_${material.aoMap.id}_occlusion.outputs:r>`);
    samplers.push(buildTexture(material.aoMap, "occlusion", new Color(material.aoMapIntensity, material.aoMapIntensity, material.aoMapIntensity)));
  }
  if (material.roughnessMap !== null) {
    inputs.push(`${pad}float inputs:roughness.connect = </Materials/Material_${material.id}/Texture_${material.roughnessMap.id}_roughness.outputs:g>`);
    samplers.push(buildTexture(material.roughnessMap, "roughness", new Color(material.roughness, material.roughness, material.roughness)));
  } else {
    inputs.push(`${pad}float inputs:roughness = ${material.roughness}`);
  }
  if (material.metalnessMap !== null) {
    inputs.push(`${pad}float inputs:metallic.connect = </Materials/Material_${material.id}/Texture_${material.metalnessMap.id}_metallic.outputs:b>`);
    samplers.push(buildTexture(material.metalnessMap, "metallic", new Color(material.metalness, material.metalness, material.metalness)));
  } else {
    inputs.push(`${pad}float inputs:metallic = ${material.metalness}`);
  }
  if (material.alphaMap !== null) {
    inputs.push(`${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>`);
    inputs.push(`${pad}float inputs:opacityThreshold = 0.0001`);
    samplers.push(buildTexture(material.alphaMap, "opacity"));
  } else {
    inputs.push(`${pad}float inputs:opacity = ${material.opacity}`);
  }
  if (material.isMeshPhysicalMaterial) {
    if (material.clearcoatMap !== null) {
      inputs.push(`${pad}float inputs:clearcoat.connect = </Materials/Material_${material.id}/Texture_${material.clearcoatMap.id}_clearcoat.outputs:r>`);
      samplers.push(buildTexture(material.clearcoatMap, "clearcoat", new Color(material.clearcoat, material.clearcoat, material.clearcoat)));
    } else {
      inputs.push(`${pad}float inputs:clearcoat = ${material.clearcoat}`);
    }
    if (material.clearcoatRoughnessMap !== null) {
      inputs.push(`${pad}float inputs:clearcoatRoughness.connect = </Materials/Material_${material.id}/Texture_${material.clearcoatRoughnessMap.id}_clearcoatRoughness.outputs:g>`);
      samplers.push(buildTexture(material.clearcoatRoughnessMap, "clearcoatRoughness", new Color(material.clearcoatRoughness, material.clearcoatRoughness, material.clearcoatRoughness)));
    } else {
      inputs.push(`${pad}float inputs:clearcoatRoughness = ${material.clearcoatRoughness}`);
    }
    inputs.push(`${pad}float inputs:ior = ${material.ior}`);
  }
  return `
	def Material "Material_${material.id}"
	{
		def Shader "PreviewSurface"
		{
			uniform token info:id = "UsdPreviewSurface"
${inputs.join("\n")}
			int inputs:useSpecularWorkflow = 0
			token outputs:surface
		}

		token outputs:surface.connect = </Materials/Material_${material.id}/PreviewSurface.outputs:surface>

${samplers.join("\n")}

	}
`;
}
function buildColor(color) {
  return `(${color.r}, ${color.g}, ${color.b})`;
}
function buildColor4(color) {
  return `(${color.r}, ${color.g}, ${color.b}, 1.0)`;
}
function buildVector2(vector) {
  return `(${vector.x}, ${vector.y})`;
}
function buildCamera(camera) {
  const name2 = camera.name ? camera.name : "Camera_" + camera.id;
  const transform2 = buildMatrix(camera.matrixWorld);
  if (camera.matrixWorld.determinant() < 0) {
    console.warn("THREE.USDZExporter: USDZ does not support negative scales", camera);
  }
  if (camera.isOrthographicCamera) {
    return `def Camera "${name2}"
		{
			matrix4d xformOp:transform = ${transform2}
			uniform token[] xformOpOrder = ["xformOp:transform"]

			float2 clippingRange = (${camera.near.toPrecision(PRECISION)}, ${camera.far.toPrecision(PRECISION)})
			float horizontalAperture = ${((Math.abs(camera.left) + Math.abs(camera.right)) * 10).toPrecision(PRECISION)}
			float verticalAperture = ${((Math.abs(camera.top) + Math.abs(camera.bottom)) * 10).toPrecision(PRECISION)}
			token projection = "orthographic"
		}

	`;
  } else {
    return `def Camera "${name2}"
		{
			matrix4d xformOp:transform = ${transform2}
			uniform token[] xformOpOrder = ["xformOp:transform"]

			float2 clippingRange = (${camera.near.toPrecision(PRECISION)}, ${camera.far.toPrecision(PRECISION)})
			float focalLength = ${camera.getFocalLength().toPrecision(PRECISION)}
			float focusDistance = ${camera.focus.toPrecision(PRECISION)}
			float horizontalAperture = ${camera.getFilmWidth().toPrecision(PRECISION)}
			token projection = "perspective"
			float verticalAperture = ${camera.getFilmHeight().toPrecision(PRECISION)}
		}

	`;
  }
}

// node_modules/three/examples/jsm/geometries/BoxLineGeometry.js
var BoxLineGeometry = class extends BufferGeometry {
  /**
   * Constructs a new box line 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 sections along the width of the sides.
   * @param {number} [heightSegments=1] - Number of segmented rectangular sections along the height of the sides.
   * @param {number} [depthSegments=1] - Number of segmented rectangular sections along the depth of the sides.
   */
  constructor(width2 = 1, height2 = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
    super();
    widthSegments = Math.floor(widthSegments);
    heightSegments = Math.floor(heightSegments);
    depthSegments = Math.floor(depthSegments);
    const widthHalf = width2 / 2;
    const heightHalf = height2 / 2;
    const depthHalf = depth / 2;
    const segmentWidth = width2 / widthSegments;
    const segmentHeight = height2 / heightSegments;
    const segmentDepth = depth / depthSegments;
    const vertices = [];
    let x2 = -widthHalf;
    let y = -heightHalf;
    let z = -depthHalf;
    for (let i = 0; i <= widthSegments; i++) {
      vertices.push(x2, -heightHalf, -depthHalf, x2, heightHalf, -depthHalf);
      vertices.push(x2, heightHalf, -depthHalf, x2, heightHalf, depthHalf);
      vertices.push(x2, heightHalf, depthHalf, x2, -heightHalf, depthHalf);
      vertices.push(x2, -heightHalf, depthHalf, x2, -heightHalf, -depthHalf);
      x2 += segmentWidth;
    }
    for (let i = 0; i <= heightSegments; i++) {
      vertices.push(-widthHalf, y, -depthHalf, widthHalf, y, -depthHalf);
      vertices.push(widthHalf, y, -depthHalf, widthHalf, y, depthHalf);
      vertices.push(widthHalf, y, depthHalf, -widthHalf, y, depthHalf);
      vertices.push(-widthHalf, y, depthHalf, -widthHalf, y, -depthHalf);
      y += segmentHeight;
    }
    for (let i = 0; i <= depthSegments; i++) {
      vertices.push(-widthHalf, -heightHalf, z, -widthHalf, heightHalf, z);
      vertices.push(-widthHalf, heightHalf, z, widthHalf, heightHalf, z);
      vertices.push(widthHalf, heightHalf, z, widthHalf, -heightHalf, z);
      vertices.push(widthHalf, -heightHalf, z, -widthHalf, -heightHalf, z);
      z += segmentDepth;
    }
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
  }
};

// node_modules/three/examples/jsm/math/ConvexHull.js
var Visible = 0;
var Deleted = 1;
var _v12 = new Vector3();
var _line3 = new Line3();
var _plane3 = new Plane();
var _closestPoint = new Vector3();
var _triangle = new Triangle();
var ConvexHull = class {
  /**
   * Constructs a new convex hull.
   */
  constructor() {
    this.tolerance = -1;
    this.faces = [];
    this.newFaces = [];
    this.assigned = new VertexList();
    this.unassigned = new VertexList();
    this.vertices = [];
  }
  /**
   * Computes to convex hull for the given array of points.
   *
   * @param {Array<Vector3>} points - The array of points in 3D space.
   * @return {ConvexHull} A reference to this convex hull.
   */
  setFromPoints(points) {
    if (points.length >= 4) {
      this.makeEmpty();
      for (let i = 0, l2 = points.length; i < l2; i++) {
        this.vertices.push(new VertexNode(points[i]));
      }
      this._compute();
    }
    return this;
  }
  /**
   * Computes the convex hull of the given 3D object (including its descendants),
   * accounting for the world transforms of both the 3D object and its descendants.
   *
   * @param {Object3D} object - The 3D object to compute the convex hull for.
   * @return {ConvexHull} A reference to this convex hull.
   */
  setFromObject(object) {
    const points = [];
    object.updateMatrixWorld(true);
    object.traverse(function(node) {
      const geometry = node.geometry;
      if (geometry !== void 0) {
        const attribute = geometry.attributes.position;
        if (attribute !== void 0) {
          for (let i = 0, l2 = attribute.count; i < l2; i++) {
            const point = new Vector3();
            point.fromBufferAttribute(attribute, i).applyMatrix4(node.matrixWorld);
            points.push(point);
          }
        }
      }
    });
    return this.setFromPoints(points);
  }
  /**
   * Returns `true` if the given point lies in the convex hull.
   *
   * @param {Vector3} point - The point to test.
   * @return {boolean} Whether the given point lies in the convex hull or not.
   */
  containsPoint(point) {
    const faces = this.faces;
    for (let i = 0, l2 = faces.length; i < l2; i++) {
      const face = faces[i];
      if (face.distanceToPoint(point) > this.tolerance) return false;
    }
    return true;
  }
  /**
   * Computes the intersections point of the given ray and this convex hull.
   *
   * @param {Ray} ray - The ray to test.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3|null} The intersection point. Returns `null` if not intersection was detected.
   */
  intersectRay(ray, target) {
    const faces = this.faces;
    let tNear = -Infinity;
    let tFar = Infinity;
    for (let i = 0, l2 = faces.length; i < l2; i++) {
      const face = faces[i];
      const vN = face.distanceToPoint(ray.origin);
      const vD = face.normal.dot(ray.direction);
      if (vN > 0 && vD >= 0) return null;
      const t3 = vD !== 0 ? -vN / vD : 0;
      if (t3 <= 0) continue;
      if (vD > 0) {
        tFar = Math.min(t3, tFar);
      } else {
        tNear = Math.max(t3, tNear);
      }
      if (tNear > tFar) {
        return null;
      }
    }
    if (tNear !== -Infinity) {
      ray.at(tNear, target);
    } else {
      ray.at(tFar, target);
    }
    return target;
  }
  /**
   * Returns `true` if the given ray intersects with this convex hull.
   *
   * @param {Ray} ray - The ray to test.
   * @return {boolean} Whether the given ray intersects with this convex hull or not.
   */
  intersectsRay(ray) {
    return this.intersectRay(ray, _v12) !== null;
  }
  /**
   * Makes the convex hull empty.
   *
   * @return {ConvexHull} A reference to this convex hull.
   */
  makeEmpty() {
    this.faces = [];
    this.vertices = [];
    return this;
  }
  // private
  /**
   * Adds a vertex to the 'assigned' list of vertices and assigns it to the given face.
   *
   * @private
   * @param {VertexNode} vertex - The vertex to add.
   * @param {Face} face - The target face.
   * @return {ConvexHull} A reference to this convex hull.
   */
  _addVertexToFace(vertex, face) {
    vertex.face = face;
    if (face.outside === null) {
      this.assigned.append(vertex);
    } else {
      this.assigned.insertBefore(face.outside, vertex);
    }
    face.outside = vertex;
    return this;
  }
  /**
   * Removes a vertex from the 'assigned' list of vertices and from the given face.
   * It also makes sure that the link from 'face' to the first vertex it sees in 'assigned'
   * is linked correctly after the removal.
   *
   * @private
   * @param {VertexNode} vertex - The vertex to remove.
   * @param {Face} face - The target face.
   * @return {ConvexHull} A reference to this convex hull.
   */
  _removeVertexFromFace(vertex, face) {
    if (vertex === face.outside) {
      if (vertex.next !== null && vertex.next.face === face) {
        face.outside = vertex.next;
      } else {
        face.outside = null;
      }
    }
    this.assigned.remove(vertex);
    return this;
  }
  /**
   * Removes all the visible vertices that a given face is able to see which are stored in
   * the 'assigned' vertex list.
   *
   * @private
   * @param {Face} face - The target face.
   * @return {VertexNode|undefined} A reference to this convex hull.
   */
  _removeAllVerticesFromFace(face) {
    if (face.outside !== null) {
      const start = face.outside;
      let end = face.outside;
      while (end.next !== null && end.next.face === face) {
        end = end.next;
      }
      this.assigned.removeSubList(start, end);
      start.prev = end.next = null;
      face.outside = null;
      return start;
    }
  }
  /**
   * Removes all the visible vertices that `face` is able to see.
   *
   * - If `absorbingFace` doesn't exist, then all the removed vertices will be added to the 'unassigned' vertex list.
   * - If `absorbingFace` exists, then this method will assign all the vertices of 'face' that can see 'absorbingFace'.
   * - If a vertex cannot see `absorbingFace`, it's added to the 'unassigned' vertex list.
   *
   * @private
   * @param {Face} face - The given face.
   * @param {Face} [absorbingFace] - An optional face that tries to absorb the vertices of the first face.
   * @return {ConvexHull} A reference to this convex hull.
   */
  _deleteFaceVertices(face, absorbingFace) {
    const faceVertices = this._removeAllVerticesFromFace(face);
    if (faceVertices !== void 0) {
      if (absorbingFace === void 0) {
        this.unassigned.appendChain(faceVertices);
      } else {
        let vertex = faceVertices;
        do {
          const nextVertex = vertex.next;
          const distance = absorbingFace.distanceToPoint(vertex.point);
          if (distance > this.tolerance) {
            this._addVertexToFace(vertex, absorbingFace);
          } else {
            this.unassigned.append(vertex);
          }
          vertex = nextVertex;
        } while (vertex !== null);
      }
    }
    return this;
  }
  /**
   * Reassigns as many vertices as possible from the unassigned list to the new faces.
   *
   * @private
   * @param {Array<Face>} newFaces - The new faces.
   * @return {ConvexHull} A reference to this convex hull.
   */
  _resolveUnassignedPoints(newFaces) {
    if (this.unassigned.isEmpty() === false) {
      let vertex = this.unassigned.first();
      do {
        const nextVertex = vertex.next;
        let maxDistance = this.tolerance;
        let maxFace = null;
        for (let i = 0; i < newFaces.length; i++) {
          const face = newFaces[i];
          if (face.mark === Visible) {
            const distance = face.distanceToPoint(vertex.point);
            if (distance > maxDistance) {
              maxDistance = distance;
              maxFace = face;
            }
            if (maxDistance > 1e3 * this.tolerance) break;
          }
        }
        if (maxFace !== null) {
          this._addVertexToFace(vertex, maxFace);
        }
        vertex = nextVertex;
      } while (vertex !== null);
    }
    return this;
  }
  /**
   * Computes the extremes values (min/max vectors) which will be used to
   * compute the initial hull.
   *
   * @private
   * @return {Object} The extremes.
   */
  _computeExtremes() {
    const min = new Vector3();
    const max2 = new Vector3();
    const minVertices = [];
    const maxVertices = [];
    for (let i = 0; i < 3; i++) {
      minVertices[i] = maxVertices[i] = this.vertices[0];
    }
    min.copy(this.vertices[0].point);
    max2.copy(this.vertices[0].point);
    for (let i = 0, l2 = this.vertices.length; i < l2; i++) {
      const vertex = this.vertices[i];
      const point = vertex.point;
      for (let j2 = 0; j2 < 3; j2++) {
        if (point.getComponent(j2) < min.getComponent(j2)) {
          min.setComponent(j2, point.getComponent(j2));
          minVertices[j2] = vertex;
        }
      }
      for (let j2 = 0; j2 < 3; j2++) {
        if (point.getComponent(j2) > max2.getComponent(j2)) {
          max2.setComponent(j2, point.getComponent(j2));
          maxVertices[j2] = vertex;
        }
      }
    }
    this.tolerance = 3 * Number.EPSILON * (Math.max(Math.abs(min.x), Math.abs(max2.x)) + Math.max(Math.abs(min.y), Math.abs(max2.y)) + Math.max(Math.abs(min.z), Math.abs(max2.z)));
    return { min: minVertices, max: maxVertices };
  }
  /**
   * Computes the initial simplex assigning to its faces all the points that are
   * candidates to form part of the hull.
   *
   * @private
   * @return {ConvexHull} A reference to this convex hull.
   */
  _computeInitialHull() {
    const vertices = this.vertices;
    const extremes = this._computeExtremes();
    const min = extremes.min;
    const max2 = extremes.max;
    let maxDistance = 0;
    let index2 = 0;
    for (let i = 0; i < 3; i++) {
      const distance = max2[i].point.getComponent(i) - min[i].point.getComponent(i);
      if (distance > maxDistance) {
        maxDistance = distance;
        index2 = i;
      }
    }
    const v0 = min[index2];
    const v12 = max2[index2];
    let v2;
    let v3;
    maxDistance = 0;
    _line3.set(v0.point, v12.point);
    for (let i = 0, l2 = this.vertices.length; i < l2; i++) {
      const vertex = vertices[i];
      if (vertex !== v0 && vertex !== v12) {
        _line3.closestPointToPoint(vertex.point, true, _closestPoint);
        const distance = _closestPoint.distanceToSquared(vertex.point);
        if (distance > maxDistance) {
          maxDistance = distance;
          v2 = vertex;
        }
      }
    }
    maxDistance = -1;
    _plane3.setFromCoplanarPoints(v0.point, v12.point, v2.point);
    for (let i = 0, l2 = this.vertices.length; i < l2; i++) {
      const vertex = vertices[i];
      if (vertex !== v0 && vertex !== v12 && vertex !== v2) {
        const distance = Math.abs(_plane3.distanceToPoint(vertex.point));
        if (distance > maxDistance) {
          maxDistance = distance;
          v3 = vertex;
        }
      }
    }
    const faces = [];
    if (_plane3.distanceToPoint(v3.point) < 0) {
      faces.push(
        Face.create(v0, v12, v2),
        Face.create(v3, v12, v0),
        Face.create(v3, v2, v12),
        Face.create(v3, v0, v2)
      );
      for (let i = 0; i < 3; i++) {
        const j2 = (i + 1) % 3;
        faces[i + 1].getEdge(2).setTwin(faces[0].getEdge(j2));
        faces[i + 1].getEdge(1).setTwin(faces[j2 + 1].getEdge(0));
      }
    } else {
      faces.push(
        Face.create(v0, v2, v12),
        Face.create(v3, v0, v12),
        Face.create(v3, v12, v2),
        Face.create(v3, v2, v0)
      );
      for (let i = 0; i < 3; i++) {
        const j2 = (i + 1) % 3;
        faces[i + 1].getEdge(2).setTwin(faces[0].getEdge((3 - i) % 3));
        faces[i + 1].getEdge(0).setTwin(faces[j2 + 1].getEdge(1));
      }
    }
    for (let i = 0; i < 4; i++) {
      this.faces.push(faces[i]);
    }
    for (let i = 0, l2 = vertices.length; i < l2; i++) {
      const vertex = vertices[i];
      if (vertex !== v0 && vertex !== v12 && vertex !== v2 && vertex !== v3) {
        maxDistance = this.tolerance;
        let maxFace = null;
        for (let j2 = 0; j2 < 4; j2++) {
          const distance = this.faces[j2].distanceToPoint(vertex.point);
          if (distance > maxDistance) {
            maxDistance = distance;
            maxFace = this.faces[j2];
          }
        }
        if (maxFace !== null) {
          this._addVertexToFace(vertex, maxFace);
        }
      }
    }
    return this;
  }
  /**
   * Removes inactive (e.g. deleted) faces from the internal face list.
   *
   * @private
   * @return {ConvexHull} A reference to this convex hull.
   */
  _reindexFaces() {
    const activeFaces = [];
    for (let i = 0; i < this.faces.length; i++) {
      const face = this.faces[i];
      if (face.mark === Visible) {
        activeFaces.push(face);
      }
    }
    this.faces = activeFaces;
    return this;
  }
  /**
   * Finds the next vertex to create faces with the current hull.
   *
   * - Let the initial face be the first face existing in the 'assigned' vertex list.
   * - If a face doesn't exist then return since there're no vertices left.
   * - Otherwise for each vertex that face sees find the one furthest away from it.
   *
   * @private
   * @return {?VertexNode} The next vertex to add.
   */
  _nextVertexToAdd() {
    if (this.assigned.isEmpty() === false) {
      let eyeVertex, maxDistance = 0;
      const eyeFace = this.assigned.first().face;
      let vertex = eyeFace.outside;
      do {
        const distance = eyeFace.distanceToPoint(vertex.point);
        if (distance > maxDistance) {
          maxDistance = distance;
          eyeVertex = vertex;
        }
        vertex = vertex.next;
      } while (vertex !== null && vertex.face === eyeFace);
      return eyeVertex;
    }
  }
  /**
   * Computes a chain of half edges in CCW order called the 'horizon'. For an edge
   * to be part of the horizon it must join a face that can see 'eyePoint' and a face
   * that cannot see 'eyePoint'.
   *
   * @private
   * @param {Vector3} eyePoint - The 3D-coordinates of a point.
   * @param {HalfEdge} crossEdge - The edge used to jump to the current face.
   * @param {Face} face - The current face being tested.
   * @param {Array<HalfEdge>} horizon - The edges that form part of the horizon in CCW order.
   * @return {ConvexHull} A reference to this convex hull.
   */
  _computeHorizon(eyePoint, crossEdge, face, horizon) {
    this._deleteFaceVertices(face);
    face.mark = Deleted;
    let edge;
    if (crossEdge === null) {
      edge = crossEdge = face.getEdge(0);
    } else {
      edge = crossEdge.next;
    }
    do {
      const twinEdge = edge.twin;
      const oppositeFace = twinEdge.face;
      if (oppositeFace.mark === Visible) {
        if (oppositeFace.distanceToPoint(eyePoint) > this.tolerance) {
          this._computeHorizon(eyePoint, twinEdge, oppositeFace, horizon);
        } else {
          horizon.push(edge);
        }
      }
      edge = edge.next;
    } while (edge !== crossEdge);
    return this;
  }
  /**
   * Creates a face with the vertices 'eyeVertex.point', 'horizonEdge.tail' and 'horizonEdge.head'
   * in CCW order. All the half edges are created in CCW order thus the face is always pointing
   * outside the hull.
   *
   * @private
   * @param {VertexNode} eyeVertex - The vertex that is added to the hull.
   * @param {HalfEdge} horizonEdge - A single edge of the horizon.
   * @return {HalfEdge} The half edge whose vertex is the eyeVertex.
   */
  _addAdjoiningFace(eyeVertex, horizonEdge) {
    const face = Face.create(eyeVertex, horizonEdge.tail(), horizonEdge.head());
    this.faces.push(face);
    face.getEdge(-1).setTwin(horizonEdge.twin);
    return face.getEdge(0);
  }
  /**
   * Adds 'horizon.length' faces to the hull, each face will be linked with the horizon
   * opposite face and the face on the left/right.
   *
   * @private
   * @param {VertexNode} eyeVertex - The vertex that is added to the hull.
   * @param {Array<HalfEdge>} horizon - The horizon.
   * @return {ConvexHull} A reference to this convex hull.
   */
  _addNewFaces(eyeVertex, horizon) {
    this.newFaces = [];
    let firstSideEdge = null;
    let previousSideEdge = null;
    for (let i = 0; i < horizon.length; i++) {
      const horizonEdge = horizon[i];
      const sideEdge = this._addAdjoiningFace(eyeVertex, horizonEdge);
      if (firstSideEdge === null) {
        firstSideEdge = sideEdge;
      } else {
        sideEdge.next.setTwin(previousSideEdge);
      }
      this.newFaces.push(sideEdge.face);
      previousSideEdge = sideEdge;
    }
    firstSideEdge.next.setTwin(previousSideEdge);
    return this;
  }
  /**
   * Adds a vertex to the hull with the following algorithm:
   *
   * - Compute the 'horizon' which is a chain of half edges. For an edge to belong to this group
   * it must be the edge connecting a face that can see 'eyeVertex' and a face which cannot see 'eyeVertex'.
   * - All the faces that can see 'eyeVertex' have its visible vertices removed from the assigned vertex list.
   * - A new set of faces is created with each edge of the 'horizon' and 'eyeVertex'. Each face is connected
   * with the opposite horizon face and the face on the left/right.
   * - The vertices removed from all the visible faces are assigned to the new faces if possible.
   *
   * @private
   * @param {VertexNode} eyeVertex - The vertex to add.
   * @return {ConvexHull} A reference to this convex hull.
   */
  _addVertexToHull(eyeVertex) {
    const horizon = [];
    this.unassigned.clear();
    this._removeVertexFromFace(eyeVertex, eyeVertex.face);
    this._computeHorizon(eyeVertex.point, null, eyeVertex.face, horizon);
    this._addNewFaces(eyeVertex, horizon);
    this._resolveUnassignedPoints(this.newFaces);
    return this;
  }
  /**
   * Cleans up internal properties after computing the convex hull.
   *
   * @private
   * @return {ConvexHull} A reference to this convex hull.
   */
  _cleanup() {
    this.assigned.clear();
    this.unassigned.clear();
    this.newFaces = [];
    return this;
  }
  /**
   * Starts the execution of the quick hull algorithm.
   *
   * @private
   * @return {ConvexHull} A reference to this convex hull.
   */
  _compute() {
    let vertex;
    this._computeInitialHull();
    while ((vertex = this._nextVertexToAdd()) !== void 0) {
      this._addVertexToHull(vertex);
    }
    this._reindexFaces();
    this._cleanup();
    return this;
  }
};
var Face = class _Face {
  /**
   * Constructs a new face.
   */
  constructor() {
    this.normal = new Vector3();
    this.midpoint = new Vector3();
    this.area = 0;
    this.constant = 0;
    this.outside = null;
    this.mark = Visible;
    this.edge = null;
  }
  /**
   * Creates a face from the given vertex nodes.
   *
   * @private
   * @param {VertexNode} a - The first vertex node.
   * @param {VertexNode} b - The second vertex node.
   * @param {VertexNode} c - The third vertex node.
   * @return {Face} The created face.
   */
  static create(a2, b3, c2) {
    const face = new _Face();
    const e0 = new HalfEdge(a2, face);
    const e1 = new HalfEdge(b3, face);
    const e2 = new HalfEdge(c2, face);
    e0.next = e2.prev = e1;
    e1.next = e0.prev = e2;
    e2.next = e1.prev = e0;
    face.edge = e0;
    return face.compute();
  }
  /**
   * Returns an edge by the given index.
   *
   * @private
   * @param {number} i - The edge index.
   * @return {HalfEdge} The edge.
   */
  getEdge(i) {
    let edge = this.edge;
    while (i > 0) {
      edge = edge.next;
      i--;
    }
    while (i < 0) {
      edge = edge.prev;
      i++;
    }
    return edge;
  }
  /**
   * Computes all properties of the face.
   *
   * @private
   * @return {Face} A reference to this face.
   */
  compute() {
    const a2 = this.edge.tail();
    const b3 = this.edge.head();
    const c2 = this.edge.next.head();
    _triangle.set(a2.point, b3.point, c2.point);
    _triangle.getNormal(this.normal);
    _triangle.getMidpoint(this.midpoint);
    this.area = _triangle.getArea();
    this.constant = this.normal.dot(this.midpoint);
    return this;
  }
  /**
   * Returns the signed distance from a given point to the plane representation of this face.
   *
   * @private
   * @param {Vector3} point - The point to compute the distance to.
   * @return {number} The distance.
   */
  distanceToPoint(point) {
    return this.normal.dot(point) - this.constant;
  }
};
var HalfEdge = class {
  /**
   * Constructs a new half edge.
   *
   * @param {VertexNode} vertex - A reference to its destination vertex.
   * @param {Face} face - A reference to its face.
   */
  constructor(vertex, face) {
    this.vertex = vertex;
    this.prev = null;
    this.next = null;
    this.twin = null;
    this.face = face;
  }
  /**
   * Returns the destination vertex.
   *
   * @private
   * @return {VertexNode} The destination vertex.
   */
  head() {
    return this.vertex;
  }
  /**
   * Returns the origin vertex.
   *
   * @private
   * @return {VertexNode} The destination vertex.
   */
  tail() {
    return this.prev ? this.prev.vertex : null;
  }
  /**
   * Returns the Euclidean length (straight-line length) of the edge.
   *
   * @private
   * @return {number} The edge's length.
   */
  length() {
    const head2 = this.head();
    const tail = this.tail();
    if (tail !== null) {
      return tail.point.distanceTo(head2.point);
    }
    return -1;
  }
  /**
   * Returns the square of the Euclidean length (straight-line length) of the edge.
   *
   * @private
   * @return {number} The square of the edge's length.
   */
  lengthSquared() {
    const head2 = this.head();
    const tail = this.tail();
    if (tail !== null) {
      return tail.point.distanceToSquared(head2.point);
    }
    return -1;
  }
  /**
   * Sets the twin edge of this half-edge. It also ensures that the twin reference
   * of the given half-edge is correctly set.
   *
   * @private
   * @param {HalfEdge} edge - The twin edge to set.
   * @return {HalfEdge} A reference to this edge.
   */
  setTwin(edge) {
    this.twin = edge;
    edge.twin = this;
    return this;
  }
};
var VertexNode = class {
  /**
   * Constructs a new vertex node.
   *
   * @param {Vector3} point - A point in 3D space.
   */
  constructor(point) {
    this.point = point;
    this.prev = null;
    this.next = null;
    this.face = null;
  }
};
var VertexList = class {
  /**
   * Constructs a new vertex list.
   */
  constructor() {
    this.head = null;
    this.tail = null;
  }
  /**
   * Returns the head reference.
   *
   * @private
   * @return {VertexNode} The head reference.
   */
  first() {
    return this.head;
  }
  /**
   * Returns the tail reference.
   *
   * @private
   * @return {VertexNode} The tail reference.
   */
  last() {
    return this.tail;
  }
  /**
   * Clears the linked list.
   *
   * @private
   * @return {VertexList} A reference to this vertex list.
   */
  clear() {
    this.head = this.tail = null;
    return this;
  }
  /**
   * Inserts a vertex before a target vertex.
   *
   * @private
   * @param {VertexNode} target - The target.
   * @param {VertexNode} vertex - The vertex to insert.
   * @return {VertexList} A reference to this vertex list.
   */
  insertBefore(target, vertex) {
    vertex.prev = target.prev;
    vertex.next = target;
    if (vertex.prev === null) {
      this.head = vertex;
    } else {
      vertex.prev.next = vertex;
    }
    target.prev = vertex;
    return this;
  }
  /**
   * Inserts a vertex after a target vertex.
   *
   * @private
   * @param {VertexNode} target - The target.
   * @param {VertexNode} vertex - The vertex to insert.
   * @return {VertexList} A reference to this vertex list.
   */
  insertAfter(target, vertex) {
    vertex.prev = target;
    vertex.next = target.next;
    if (vertex.next === null) {
      this.tail = vertex;
    } else {
      vertex.next.prev = vertex;
    }
    target.next = vertex;
    return this;
  }
  /**
   * Appends a vertex to this vertex list.
   *
   * @private
   * @param {VertexNode} vertex - The vertex to append.
   * @return {VertexList} A reference to this vertex list.
   */
  append(vertex) {
    if (this.head === null) {
      this.head = vertex;
    } else {
      this.tail.next = vertex;
    }
    vertex.prev = this.tail;
    vertex.next = null;
    this.tail = vertex;
    return this;
  }
  /**
   * Appends a chain of vertices where the given vertex is the head.
   *
   * @private
   * @param {VertexNode} vertex - The head vertex of a chain of vertices.
   * @return {VertexList} A reference to this vertex list.
   */
  appendChain(vertex) {
    if (this.head === null) {
      this.head = vertex;
    } else {
      this.tail.next = vertex;
    }
    vertex.prev = this.tail;
    while (vertex.next !== null) {
      vertex = vertex.next;
    }
    this.tail = vertex;
    return this;
  }
  /**
   * Removes a vertex from the linked list.
   *
   * @private
   * @param {VertexNode} vertex - The vertex to remove.
   * @return {VertexList} A reference to this vertex list.
   */
  remove(vertex) {
    if (vertex.prev === null) {
      this.head = vertex.next;
    } else {
      vertex.prev.next = vertex.next;
    }
    if (vertex.next === null) {
      this.tail = vertex.prev;
    } else {
      vertex.next.prev = vertex.prev;
    }
    return this;
  }
  /**
   * Removes a sublist of vertices from the linked list.
   *
   * @private
   * @param {VertexNode} a - The head of the sublist.
   * @param {VertexNode} b - The tail of the sublist.
   * @return {VertexList} A reference to this vertex list.
   */
  removeSubList(a2, b3) {
    if (a2.prev === null) {
      this.head = b3.next;
    } else {
      a2.prev.next = b3.next;
    }
    if (b3.next === null) {
      this.tail = a2.prev;
    } else {
      b3.next.prev = a2.prev;
    }
    return this;
  }
  /**
   * Returns `true` if the linked list is empty.
   *
   * @private
   * @return {boolean} Whether the linked list is empty or not.
   */
  isEmpty() {
    return this.head === null;
  }
};

// node_modules/three/examples/jsm/geometries/ConvexGeometry.js
var ConvexGeometry = class extends BufferGeometry {
  /**
   * Constructs a new convex geometry.
   *
   * @param {Array<Vector3>} points - An array of points in 3D space which should be enclosed by the convex hull.
   */
  constructor(points = []) {
    super();
    const vertices = [];
    const normals = [];
    const convexHull = new ConvexHull().setFromPoints(points);
    const faces = convexHull.faces;
    for (let i = 0; i < faces.length; i++) {
      const face = faces[i];
      let edge = face.edge;
      do {
        const point = edge.head().point;
        vertices.push(point.x, point.y, point.z);
        normals.push(face.normal.x, face.normal.y, face.normal.z);
        edge = edge.next;
      } while (edge !== face.edge);
    }
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  }
};

// node_modules/three/examples/jsm/geometries/DecalGeometry.js
var DecalGeometry = class extends BufferGeometry {
  /**
   * Constructs a new decal geometry.
   *
   * @param {Mesh} [mesh] - The base mesh the decal should be projected on.
   * @param {Vector3} [position] - The position of the decal projector.
   * @param {Euler} [orientation] - The orientation of the decal projector.
   * @param {Vector3} [size] - Tje scale of the decal projector.
   */
  constructor(mesh = new Mesh(), position2 = new Vector3(), orientation = new Euler(), size2 = new Vector3(1, 1, 1)) {
    super();
    const vertices = [];
    const normals = [];
    const uvs = [];
    const plane2 = new Vector3();
    const normalMatrix = new Matrix3().getNormalMatrix(mesh.matrixWorld);
    const projectorMatrix = new Matrix4();
    projectorMatrix.makeRotationFromEuler(orientation);
    projectorMatrix.setPosition(position2);
    const projectorMatrixInverse = new Matrix4();
    projectorMatrixInverse.copy(projectorMatrix).invert();
    generate();
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    if (normals.length > 0) {
      this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    }
    function generate() {
      let decalVertices = [];
      const vertex = new Vector3();
      const normal = new Vector3();
      const geometry = mesh.geometry;
      const positionAttribute = geometry.attributes.position;
      const normalAttribute = geometry.attributes.normal;
      if (geometry.index !== null) {
        const index2 = geometry.index;
        for (let i = 0; i < index2.count; i++) {
          vertex.fromBufferAttribute(positionAttribute, index2.getX(i));
          if (normalAttribute) {
            normal.fromBufferAttribute(normalAttribute, index2.getX(i));
            pushDecalVertex(decalVertices, vertex, normal);
          } else {
            pushDecalVertex(decalVertices, vertex);
          }
        }
      } else {
        if (positionAttribute === void 0) return;
        for (let i = 0; i < positionAttribute.count; i++) {
          vertex.fromBufferAttribute(positionAttribute, i);
          if (normalAttribute) {
            normal.fromBufferAttribute(normalAttribute, i);
            pushDecalVertex(decalVertices, vertex, normal);
          } else {
            pushDecalVertex(decalVertices, vertex);
          }
        }
      }
      decalVertices = clipGeometry(decalVertices, plane2.set(1, 0, 0));
      decalVertices = clipGeometry(decalVertices, plane2.set(-1, 0, 0));
      decalVertices = clipGeometry(decalVertices, plane2.set(0, 1, 0));
      decalVertices = clipGeometry(decalVertices, plane2.set(0, -1, 0));
      decalVertices = clipGeometry(decalVertices, plane2.set(0, 0, 1));
      decalVertices = clipGeometry(decalVertices, plane2.set(0, 0, -1));
      for (let i = 0; i < decalVertices.length; i++) {
        const decalVertex = decalVertices[i];
        uvs.push(
          0.5 + decalVertex.position.x / size2.x,
          0.5 + decalVertex.position.y / size2.y
        );
        decalVertex.position.applyMatrix4(projectorMatrix);
        vertices.push(decalVertex.position.x, decalVertex.position.y, decalVertex.position.z);
        if (decalVertex.normal !== null) {
          normals.push(decalVertex.normal.x, decalVertex.normal.y, decalVertex.normal.z);
        }
      }
    }
    function pushDecalVertex(decalVertices, vertex, normal = null) {
      vertex.applyMatrix4(mesh.matrixWorld);
      vertex.applyMatrix4(projectorMatrixInverse);
      if (normal) {
        normal.applyNormalMatrix(normalMatrix);
        decalVertices.push(new DecalVertex(vertex.clone(), normal.clone()));
      } else {
        decalVertices.push(new DecalVertex(vertex.clone()));
      }
    }
    function clipGeometry(inVertices, plane3) {
      const outVertices = [];
      const s = 0.5 * Math.abs(size2.dot(plane3));
      for (let i = 0; i < inVertices.length; i += 3) {
        let total = 0;
        let nV1;
        let nV2;
        let nV3;
        let nV4;
        const d1 = inVertices[i + 0].position.dot(plane3) - s;
        const d2 = inVertices[i + 1].position.dot(plane3) - s;
        const d3 = inVertices[i + 2].position.dot(plane3) - s;
        const v1Out = d1 > 0;
        const v2Out = d2 > 0;
        const v3Out = d3 > 0;
        total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
        switch (total) {
          case 0: {
            outVertices.push(inVertices[i]);
            outVertices.push(inVertices[i + 1]);
            outVertices.push(inVertices[i + 2]);
            break;
          }
          case 1: {
            if (v1Out) {
              nV1 = inVertices[i + 1];
              nV2 = inVertices[i + 2];
              nV3 = clip(inVertices[i], nV1, plane3, s);
              nV4 = clip(inVertices[i], nV2, plane3, s);
            }
            if (v2Out) {
              nV1 = inVertices[i];
              nV2 = inVertices[i + 2];
              nV3 = clip(inVertices[i + 1], nV1, plane3, s);
              nV4 = clip(inVertices[i + 1], nV2, plane3, s);
              outVertices.push(nV3);
              outVertices.push(nV2.clone());
              outVertices.push(nV1.clone());
              outVertices.push(nV2.clone());
              outVertices.push(nV3.clone());
              outVertices.push(nV4);
              break;
            }
            if (v3Out) {
              nV1 = inVertices[i];
              nV2 = inVertices[i + 1];
              nV3 = clip(inVertices[i + 2], nV1, plane3, s);
              nV4 = clip(inVertices[i + 2], nV2, plane3, s);
            }
            outVertices.push(nV1.clone());
            outVertices.push(nV2.clone());
            outVertices.push(nV3);
            outVertices.push(nV4);
            outVertices.push(nV3.clone());
            outVertices.push(nV2.clone());
            break;
          }
          case 2: {
            if (!v1Out) {
              nV1 = inVertices[i].clone();
              nV2 = clip(nV1, inVertices[i + 1], plane3, s);
              nV3 = clip(nV1, inVertices[i + 2], plane3, s);
              outVertices.push(nV1);
              outVertices.push(nV2);
              outVertices.push(nV3);
            }
            if (!v2Out) {
              nV1 = inVertices[i + 1].clone();
              nV2 = clip(nV1, inVertices[i + 2], plane3, s);
              nV3 = clip(nV1, inVertices[i], plane3, s);
              outVertices.push(nV1);
              outVertices.push(nV2);
              outVertices.push(nV3);
            }
            if (!v3Out) {
              nV1 = inVertices[i + 2].clone();
              nV2 = clip(nV1, inVertices[i], plane3, s);
              nV3 = clip(nV1, inVertices[i + 1], plane3, s);
              outVertices.push(nV1);
              outVertices.push(nV2);
              outVertices.push(nV3);
            }
            break;
          }
          case 3: {
            break;
          }
        }
      }
      return outVertices;
    }
    function clip(v0, v12, p, s) {
      const d0 = v0.position.dot(p) - s;
      const d1 = v12.position.dot(p) - s;
      const s0 = d0 / (d0 - d1);
      const position3 = new Vector3(
        v0.position.x + s0 * (v12.position.x - v0.position.x),
        v0.position.y + s0 * (v12.position.y - v0.position.y),
        v0.position.z + s0 * (v12.position.z - v0.position.z)
      );
      let normal = null;
      if (v0.normal !== null && v12.normal !== null) {
        normal = new Vector3(
          v0.normal.x + s0 * (v12.normal.x - v0.normal.x),
          v0.normal.y + s0 * (v12.normal.y - v0.normal.y),
          v0.normal.z + s0 * (v12.normal.z - v0.normal.z)
        );
      }
      const v = new DecalVertex(position3, normal);
      return v;
    }
  }
};
var DecalVertex = class {
  constructor(position2, normal = null) {
    this.position = position2;
    this.normal = normal;
  }
  clone() {
    const position2 = this.position.clone();
    const normal = this.normal !== null ? this.normal.clone() : null;
    return new this.constructor(position2, normal);
  }
};

// node_modules/three/examples/jsm/geometries/ParametricFunctions.js
function klein(v, u2, target) {
  u2 *= Math.PI;
  v *= 2 * Math.PI;
  u2 = u2 * 2;
  let x2, z;
  if (u2 < Math.PI) {
    x2 = 3 * Math.cos(u2) * (1 + Math.sin(u2)) + 2 * (1 - Math.cos(u2) / 2) * Math.cos(u2) * Math.cos(v);
    z = -8 * Math.sin(u2) - 2 * (1 - Math.cos(u2) / 2) * Math.sin(u2) * Math.cos(v);
  } else {
    x2 = 3 * Math.cos(u2) * (1 + Math.sin(u2)) + 2 * (1 - Math.cos(u2) / 2) * Math.cos(v + Math.PI);
    z = -8 * Math.sin(u2);
  }
  const y = -2 * (1 - Math.cos(u2) / 2) * Math.sin(v);
  target.set(x2, y, z);
}
function plane(u2, v, target) {
  target.set(u2, 0, v);
}
function mobius(u2, t3, target) {
  u2 = u2 - 0.5;
  const v = 2 * Math.PI * t3;
  const a2 = 2;
  const x2 = Math.cos(v) * (a2 + u2 * Math.cos(v / 2));
  const y = Math.sin(v) * (a2 + u2 * Math.cos(v / 2));
  const z = u2 * Math.sin(v / 2);
  target.set(x2, y, z);
}
function mobius3d(u2, t3, target) {
  u2 *= Math.PI;
  t3 *= 2 * Math.PI;
  u2 = u2 * 2;
  const phi = u2 / 2;
  const major = 2.25, a2 = 0.125, b3 = 0.65;
  let x2 = a2 * Math.cos(t3) * Math.cos(phi) - b3 * Math.sin(t3) * Math.sin(phi);
  const z = a2 * Math.cos(t3) * Math.sin(phi) + b3 * Math.sin(t3) * Math.cos(phi);
  const y = (major + x2) * Math.sin(u2);
  x2 = (major + x2) * Math.cos(u2);
  target.set(x2, y, z);
}

// node_modules/three/examples/jsm/geometries/ParametricGeometry.js
var ParametricGeometry = class extends BufferGeometry {
  /**
   * Constructs a new parametric geometry.
   *
   * @param {ParametricGeometry~Func} func - The parametric function. Default is a function that generates a curved plane surface.
   * @param {number} [slices=8] - The number of slices to use for the parametric function.
   * @param {number} [stacks=8] - The stacks of slices to use for the parametric function.
   */
  constructor(func = (u2, v, target) => target.set(u2, v, Math.cos(u2) * Math.sin(v)), slices = 8, stacks = 8) {
    super();
    this.type = "ParametricGeometry";
    this.parameters = {
      func,
      slices,
      stacks
    };
    const indices = [];
    const vertices = [];
    const normals = [];
    const uvs = [];
    const EPS2 = 1e-5;
    const normal = new Vector3();
    const p0 = new Vector3(), p1 = new Vector3();
    const pu = new Vector3(), pv = new Vector3();
    const sliceCount = slices + 1;
    for (let i = 0; i <= stacks; i++) {
      const v = i / stacks;
      for (let j2 = 0; j2 <= slices; j2++) {
        const u2 = j2 / slices;
        func(u2, v, p0);
        vertices.push(p0.x, p0.y, p0.z);
        if (u2 - EPS2 >= 0) {
          func(u2 - EPS2, v, p1);
          pu.subVectors(p0, p1);
        } else {
          func(u2 + EPS2, v, p1);
          pu.subVectors(p1, p0);
        }
        if (v - EPS2 >= 0) {
          func(u2, v - EPS2, p1);
          pv.subVectors(p0, p1);
        } else {
          func(u2, v + EPS2, p1);
          pv.subVectors(p1, p0);
        }
        normal.crossVectors(pu, pv).normalize();
        normals.push(normal.x, normal.y, normal.z);
        uvs.push(u2, v);
      }
    }
    for (let i = 0; i < stacks; i++) {
      for (let j2 = 0; j2 < slices; j2++) {
        const a2 = i * sliceCount + j2;
        const b3 = i * sliceCount + j2 + 1;
        const c2 = (i + 1) * sliceCount + j2 + 1;
        const d = (i + 1) * sliceCount + j2;
        indices.push(a2, b3, d);
        indices.push(b3, c2, d);
      }
    }
    this.setIndex(indices);
    this.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    this.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  }
  copy(source) {
    super.copy(source);
    this.parameters = Object.assign({}, source.parameters);
    return this;
  }
};

// node_modules/three/examples/jsm/geometries/RoundedBoxGeometry.js
var _tempNormal = new Vector3();
function getUv(faceDirVector, normal, uvAxis, projectionAxis, radius, sideLength) {
  const totArcLength = 2 * Math.PI * radius / 4;
  const centerLength = Math.max(sideLength - 2 * radius, 0);
  const halfArc = Math.PI / 4;
  _tempNormal.copy(normal);
  _tempNormal[projectionAxis] = 0;
  _tempNormal.normalize();
  const arcUvRatio = 0.5 * totArcLength / (totArcLength + centerLength);
  const arcAngleRatio = 1 - _tempNormal.angleTo(faceDirVector) / halfArc;
  if (Math.sign(_tempNormal[uvAxis]) === 1) {
    return arcAngleRatio * arcUvRatio;
  } else {
    const lenUv = centerLength / (totArcLength + centerLength);
    return lenUv + arcUvRatio + arcUvRatio * (1 - arcAngleRatio);
  }
}
var RoundedBoxGeometry = class extends BoxGeometry {
  /**
   * Constructs a new rounded 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} [segments=2] - Number of segmented that form the rounded corners.
   * @param {number} [radius=0.1] - The radius of the rounded corners.
   */
  constructor(width2 = 1, height2 = 1, depth = 1, segments = 2, radius = 0.1) {
    segments = segments * 2 + 1;
    radius = Math.min(width2 / 2, height2 / 2, depth / 2, radius);
    super(width2, height2, depth, segments, segments, segments);
    if (segments === 1) return;
    const geometry2 = this.toNonIndexed();
    this.index = null;
    this.attributes.position = geometry2.attributes.position;
    this.attributes.normal = geometry2.attributes.normal;
    this.attributes.uv = geometry2.attributes.uv;
    const position2 = new Vector3();
    const normal = new Vector3();
    const box = new Vector3(width2, height2, depth).divideScalar(2).subScalar(radius);
    const positions = this.attributes.position.array;
    const normals = this.attributes.normal.array;
    const uvs = this.attributes.uv.array;
    const faceTris = positions.length / 6;
    const faceDirVector = new Vector3();
    const halfSegmentSize = 0.5 / segments;
    for (let i = 0, j2 = 0; i < positions.length; i += 3, j2 += 2) {
      position2.fromArray(positions, i);
      normal.copy(position2);
      normal.x -= Math.sign(normal.x) * halfSegmentSize;
      normal.y -= Math.sign(normal.y) * halfSegmentSize;
      normal.z -= Math.sign(normal.z) * halfSegmentSize;
      normal.normalize();
      positions[i + 0] = box.x * Math.sign(position2.x) + normal.x * radius;
      positions[i + 1] = box.y * Math.sign(position2.y) + normal.y * radius;
      positions[i + 2] = box.z * Math.sign(position2.z) + normal.z * radius;
      normals[i + 0] = normal.x;
      normals[i + 1] = normal.y;
      normals[i + 2] = normal.z;
      const side = Math.floor(i / faceTris);
      switch (side) {
        case 0:
          faceDirVector.set(1, 0, 0);
          uvs[j2 + 0] = getUv(faceDirVector, normal, "z", "y", radius, depth);
          uvs[j2 + 1] = 1 - getUv(faceDirVector, normal, "y", "z", radius, height2);
          break;
        case 1:
          faceDirVector.set(-1, 0, 0);
          uvs[j2 + 0] = 1 - getUv(faceDirVector, normal, "z", "y", radius, depth);
          uvs[j2 + 1] = 1 - getUv(faceDirVector, normal, "y", "z", radius, height2);
          break;
        case 2:
          faceDirVector.set(0, 1, 0);
          uvs[j2 + 0] = 1 - getUv(faceDirVector, normal, "x", "z", radius, width2);
          uvs[j2 + 1] = getUv(faceDirVector, normal, "z", "x", radius, depth);
          break;
        case 3:
          faceDirVector.set(0, -1, 0);
          uvs[j2 + 0] = 1 - getUv(faceDirVector, normal, "x", "z", radius, width2);
          uvs[j2 + 1] = 1 - getUv(faceDirVector, normal, "z", "x", radius, depth);
          break;
        case 4:
          faceDirVector.set(0, 0, 1);
          uvs[j2 + 0] = 1 - getUv(faceDirVector, normal, "x", "y", radius, width2);
          uvs[j2 + 1] = 1 - getUv(faceDirVector, normal, "y", "x", radius, height2);
          break;
        case 5:
          faceDirVector.set(0, 0, -1);
          uvs[j2 + 0] = getUv(faceDirVector, normal, "x", "y", radius, width2);
          uvs[j2 + 1] = 1 - getUv(faceDirVector, normal, "y", "x", radius, height2);
          break;
      }
    }
  }
};

// node_modules/three/examples/jsm/geometries/TeapotGeometry.js
var TeapotGeometry = class extends BufferGeometry {
  /**
   * Constructs a new teapot geometry.
   *
   * @param {number} [size=50] - Relative scale of the teapot.
   * @param {number} [segments=10] - Number of line segments to subdivide each patch edge.
   * @param {boolean} [bottom=true] - Whether the bottom of the teapot is generated or not.
   * @param {boolean} [lid=true] - Whether the lid is generated or not.
   * @param {boolean} [body=true] - Whether the body is generated or not.
   * @param {boolean} [fitLid=true] - Whether the lid is slightly stretched to prevent gaps between the body and lid or not.
   * @param {boolean} [blinn=true] -  Whether the teapot is scaled vertically for better aesthetics or not.
   */
  constructor(size2 = 50, segments = 10, bottom = true, lid = true, body = true, fitLid = true, blinn = true) {
    const teapotPatches = [
      /*rim*/
      0,
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10,
      11,
      12,
      13,
      14,
      15,
      3,
      16,
      17,
      18,
      7,
      19,
      20,
      21,
      11,
      22,
      23,
      24,
      15,
      25,
      26,
      27,
      18,
      28,
      29,
      30,
      21,
      31,
      32,
      33,
      24,
      34,
      35,
      36,
      27,
      37,
      38,
      39,
      30,
      40,
      41,
      0,
      33,
      42,
      43,
      4,
      36,
      44,
      45,
      8,
      39,
      46,
      47,
      12,
      /*body*/
      12,
      13,
      14,
      15,
      48,
      49,
      50,
      51,
      52,
      53,
      54,
      55,
      56,
      57,
      58,
      59,
      15,
      25,
      26,
      27,
      51,
      60,
      61,
      62,
      55,
      63,
      64,
      65,
      59,
      66,
      67,
      68,
      27,
      37,
      38,
      39,
      62,
      69,
      70,
      71,
      65,
      72,
      73,
      74,
      68,
      75,
      76,
      77,
      39,
      46,
      47,
      12,
      71,
      78,
      79,
      48,
      74,
      80,
      81,
      52,
      77,
      82,
      83,
      56,
      56,
      57,
      58,
      59,
      84,
      85,
      86,
      87,
      88,
      89,
      90,
      91,
      92,
      93,
      94,
      95,
      59,
      66,
      67,
      68,
      87,
      96,
      97,
      98,
      91,
      99,
      100,
      101,
      95,
      102,
      103,
      104,
      68,
      75,
      76,
      77,
      98,
      105,
      106,
      107,
      101,
      108,
      109,
      110,
      104,
      111,
      112,
      113,
      77,
      82,
      83,
      56,
      107,
      114,
      115,
      84,
      110,
      116,
      117,
      88,
      113,
      118,
      119,
      92,
      /*handle*/
      120,
      121,
      122,
      123,
      124,
      125,
      126,
      127,
      128,
      129,
      130,
      131,
      132,
      133,
      134,
      135,
      123,
      136,
      137,
      120,
      127,
      138,
      139,
      124,
      131,
      140,
      141,
      128,
      135,
      142,
      143,
      132,
      132,
      133,
      134,
      135,
      144,
      145,
      146,
      147,
      148,
      149,
      150,
      151,
      68,
      152,
      153,
      154,
      135,
      142,
      143,
      132,
      147,
      155,
      156,
      144,
      151,
      157,
      158,
      148,
      154,
      159,
      160,
      68,
      /*spout*/
      161,
      162,
      163,
      164,
      165,
      166,
      167,
      168,
      169,
      170,
      171,
      172,
      173,
      174,
      175,
      176,
      164,
      177,
      178,
      161,
      168,
      179,
      180,
      165,
      172,
      181,
      182,
      169,
      176,
      183,
      184,
      173,
      173,
      174,
      175,
      176,
      185,
      186,
      187,
      188,
      189,
      190,
      191,
      192,
      193,
      194,
      195,
      196,
      176,
      183,
      184,
      173,
      188,
      197,
      198,
      185,
      192,
      199,
      200,
      189,
      196,
      201,
      202,
      193,
      /*lid*/
      203,
      203,
      203,
      203,
      204,
      205,
      206,
      207,
      208,
      208,
      208,
      208,
      209,
      210,
      211,
      212,
      203,
      203,
      203,
      203,
      207,
      213,
      214,
      215,
      208,
      208,
      208,
      208,
      212,
      216,
      217,
      218,
      203,
      203,
      203,
      203,
      215,
      219,
      220,
      221,
      208,
      208,
      208,
      208,
      218,
      222,
      223,
      224,
      203,
      203,
      203,
      203,
      221,
      225,
      226,
      204,
      208,
      208,
      208,
      208,
      224,
      227,
      228,
      209,
      209,
      210,
      211,
      212,
      229,
      230,
      231,
      232,
      233,
      234,
      235,
      236,
      237,
      238,
      239,
      240,
      212,
      216,
      217,
      218,
      232,
      241,
      242,
      243,
      236,
      244,
      245,
      246,
      240,
      247,
      248,
      249,
      218,
      222,
      223,
      224,
      243,
      250,
      251,
      252,
      246,
      253,
      254,
      255,
      249,
      256,
      257,
      258,
      224,
      227,
      228,
      209,
      252,
      259,
      260,
      229,
      255,
      261,
      262,
      233,
      258,
      263,
      264,
      237,
      /*bottom*/
      265,
      265,
      265,
      265,
      266,
      267,
      268,
      269,
      270,
      271,
      272,
      273,
      92,
      119,
      118,
      113,
      265,
      265,
      265,
      265,
      269,
      274,
      275,
      276,
      273,
      277,
      278,
      279,
      113,
      112,
      111,
      104,
      265,
      265,
      265,
      265,
      276,
      280,
      281,
      282,
      279,
      283,
      284,
      285,
      104,
      103,
      102,
      95,
      265,
      265,
      265,
      265,
      282,
      286,
      287,
      266,
      285,
      288,
      289,
      270,
      95,
      94,
      93,
      92
    ];
    const teapotVertices = [
      1.4,
      0,
      2.4,
      1.4,
      -0.784,
      2.4,
      0.784,
      -1.4,
      2.4,
      0,
      -1.4,
      2.4,
      1.3375,
      0,
      2.53125,
      1.3375,
      -0.749,
      2.53125,
      0.749,
      -1.3375,
      2.53125,
      0,
      -1.3375,
      2.53125,
      1.4375,
      0,
      2.53125,
      1.4375,
      -0.805,
      2.53125,
      0.805,
      -1.4375,
      2.53125,
      0,
      -1.4375,
      2.53125,
      1.5,
      0,
      2.4,
      1.5,
      -0.84,
      2.4,
      0.84,
      -1.5,
      2.4,
      0,
      -1.5,
      2.4,
      -0.784,
      -1.4,
      2.4,
      -1.4,
      -0.784,
      2.4,
      -1.4,
      0,
      2.4,
      -0.749,
      -1.3375,
      2.53125,
      -1.3375,
      -0.749,
      2.53125,
      -1.3375,
      0,
      2.53125,
      -0.805,
      -1.4375,
      2.53125,
      -1.4375,
      -0.805,
      2.53125,
      -1.4375,
      0,
      2.53125,
      -0.84,
      -1.5,
      2.4,
      -1.5,
      -0.84,
      2.4,
      -1.5,
      0,
      2.4,
      -1.4,
      0.784,
      2.4,
      -0.784,
      1.4,
      2.4,
      0,
      1.4,
      2.4,
      -1.3375,
      0.749,
      2.53125,
      -0.749,
      1.3375,
      2.53125,
      0,
      1.3375,
      2.53125,
      -1.4375,
      0.805,
      2.53125,
      -0.805,
      1.4375,
      2.53125,
      0,
      1.4375,
      2.53125,
      -1.5,
      0.84,
      2.4,
      -0.84,
      1.5,
      2.4,
      0,
      1.5,
      2.4,
      0.784,
      1.4,
      2.4,
      1.4,
      0.784,
      2.4,
      0.749,
      1.3375,
      2.53125,
      1.3375,
      0.749,
      2.53125,
      0.805,
      1.4375,
      2.53125,
      1.4375,
      0.805,
      2.53125,
      0.84,
      1.5,
      2.4,
      1.5,
      0.84,
      2.4,
      1.75,
      0,
      1.875,
      1.75,
      -0.98,
      1.875,
      0.98,
      -1.75,
      1.875,
      0,
      -1.75,
      1.875,
      2,
      0,
      1.35,
      2,
      -1.12,
      1.35,
      1.12,
      -2,
      1.35,
      0,
      -2,
      1.35,
      2,
      0,
      0.9,
      2,
      -1.12,
      0.9,
      1.12,
      -2,
      0.9,
      0,
      -2,
      0.9,
      -0.98,
      -1.75,
      1.875,
      -1.75,
      -0.98,
      1.875,
      -1.75,
      0,
      1.875,
      -1.12,
      -2,
      1.35,
      -2,
      -1.12,
      1.35,
      -2,
      0,
      1.35,
      -1.12,
      -2,
      0.9,
      -2,
      -1.12,
      0.9,
      -2,
      0,
      0.9,
      -1.75,
      0.98,
      1.875,
      -0.98,
      1.75,
      1.875,
      0,
      1.75,
      1.875,
      -2,
      1.12,
      1.35,
      -1.12,
      2,
      1.35,
      0,
      2,
      1.35,
      -2,
      1.12,
      0.9,
      -1.12,
      2,
      0.9,
      0,
      2,
      0.9,
      0.98,
      1.75,
      1.875,
      1.75,
      0.98,
      1.875,
      1.12,
      2,
      1.35,
      2,
      1.12,
      1.35,
      1.12,
      2,
      0.9,
      2,
      1.12,
      0.9,
      2,
      0,
      0.45,
      2,
      -1.12,
      0.45,
      1.12,
      -2,
      0.45,
      0,
      -2,
      0.45,
      1.5,
      0,
      0.225,
      1.5,
      -0.84,
      0.225,
      0.84,
      -1.5,
      0.225,
      0,
      -1.5,
      0.225,
      1.5,
      0,
      0.15,
      1.5,
      -0.84,
      0.15,
      0.84,
      -1.5,
      0.15,
      0,
      -1.5,
      0.15,
      -1.12,
      -2,
      0.45,
      -2,
      -1.12,
      0.45,
      -2,
      0,
      0.45,
      -0.84,
      -1.5,
      0.225,
      -1.5,
      -0.84,
      0.225,
      -1.5,
      0,
      0.225,
      -0.84,
      -1.5,
      0.15,
      -1.5,
      -0.84,
      0.15,
      -1.5,
      0,
      0.15,
      -2,
      1.12,
      0.45,
      -1.12,
      2,
      0.45,
      0,
      2,
      0.45,
      -1.5,
      0.84,
      0.225,
      -0.84,
      1.5,
      0.225,
      0,
      1.5,
      0.225,
      -1.5,
      0.84,
      0.15,
      -0.84,
      1.5,
      0.15,
      0,
      1.5,
      0.15,
      1.12,
      2,
      0.45,
      2,
      1.12,
      0.45,
      0.84,
      1.5,
      0.225,
      1.5,
      0.84,
      0.225,
      0.84,
      1.5,
      0.15,
      1.5,
      0.84,
      0.15,
      -1.6,
      0,
      2.025,
      -1.6,
      -0.3,
      2.025,
      -1.5,
      -0.3,
      2.25,
      -1.5,
      0,
      2.25,
      -2.3,
      0,
      2.025,
      -2.3,
      -0.3,
      2.025,
      -2.5,
      -0.3,
      2.25,
      -2.5,
      0,
      2.25,
      -2.7,
      0,
      2.025,
      -2.7,
      -0.3,
      2.025,
      -3,
      -0.3,
      2.25,
      -3,
      0,
      2.25,
      -2.7,
      0,
      1.8,
      -2.7,
      -0.3,
      1.8,
      -3,
      -0.3,
      1.8,
      -3,
      0,
      1.8,
      -1.5,
      0.3,
      2.25,
      -1.6,
      0.3,
      2.025,
      -2.5,
      0.3,
      2.25,
      -2.3,
      0.3,
      2.025,
      -3,
      0.3,
      2.25,
      -2.7,
      0.3,
      2.025,
      -3,
      0.3,
      1.8,
      -2.7,
      0.3,
      1.8,
      -2.7,
      0,
      1.575,
      -2.7,
      -0.3,
      1.575,
      -3,
      -0.3,
      1.35,
      -3,
      0,
      1.35,
      -2.5,
      0,
      1.125,
      -2.5,
      -0.3,
      1.125,
      -2.65,
      -0.3,
      0.9375,
      -2.65,
      0,
      0.9375,
      -2,
      -0.3,
      0.9,
      -1.9,
      -0.3,
      0.6,
      -1.9,
      0,
      0.6,
      -3,
      0.3,
      1.35,
      -2.7,
      0.3,
      1.575,
      -2.65,
      0.3,
      0.9375,
      -2.5,
      0.3,
      1.125,
      -1.9,
      0.3,
      0.6,
      -2,
      0.3,
      0.9,
      1.7,
      0,
      1.425,
      1.7,
      -0.66,
      1.425,
      1.7,
      -0.66,
      0.6,
      1.7,
      0,
      0.6,
      2.6,
      0,
      1.425,
      2.6,
      -0.66,
      1.425,
      3.1,
      -0.66,
      0.825,
      3.1,
      0,
      0.825,
      2.3,
      0,
      2.1,
      2.3,
      -0.25,
      2.1,
      2.4,
      -0.25,
      2.025,
      2.4,
      0,
      2.025,
      2.7,
      0,
      2.4,
      2.7,
      -0.25,
      2.4,
      3.3,
      -0.25,
      2.4,
      3.3,
      0,
      2.4,
      1.7,
      0.66,
      0.6,
      1.7,
      0.66,
      1.425,
      3.1,
      0.66,
      0.825,
      2.6,
      0.66,
      1.425,
      2.4,
      0.25,
      2.025,
      2.3,
      0.25,
      2.1,
      3.3,
      0.25,
      2.4,
      2.7,
      0.25,
      2.4,
      2.8,
      0,
      2.475,
      2.8,
      -0.25,
      2.475,
      3.525,
      -0.25,
      2.49375,
      3.525,
      0,
      2.49375,
      2.9,
      0,
      2.475,
      2.9,
      -0.15,
      2.475,
      3.45,
      -0.15,
      2.5125,
      3.45,
      0,
      2.5125,
      2.8,
      0,
      2.4,
      2.8,
      -0.15,
      2.4,
      3.2,
      -0.15,
      2.4,
      3.2,
      0,
      2.4,
      3.525,
      0.25,
      2.49375,
      2.8,
      0.25,
      2.475,
      3.45,
      0.15,
      2.5125,
      2.9,
      0.15,
      2.475,
      3.2,
      0.15,
      2.4,
      2.8,
      0.15,
      2.4,
      0,
      0,
      3.15,
      0.8,
      0,
      3.15,
      0.8,
      -0.45,
      3.15,
      0.45,
      -0.8,
      3.15,
      0,
      -0.8,
      3.15,
      0,
      0,
      2.85,
      0.2,
      0,
      2.7,
      0.2,
      -0.112,
      2.7,
      0.112,
      -0.2,
      2.7,
      0,
      -0.2,
      2.7,
      -0.45,
      -0.8,
      3.15,
      -0.8,
      -0.45,
      3.15,
      -0.8,
      0,
      3.15,
      -0.112,
      -0.2,
      2.7,
      -0.2,
      -0.112,
      2.7,
      -0.2,
      0,
      2.7,
      -0.8,
      0.45,
      3.15,
      -0.45,
      0.8,
      3.15,
      0,
      0.8,
      3.15,
      -0.2,
      0.112,
      2.7,
      -0.112,
      0.2,
      2.7,
      0,
      0.2,
      2.7,
      0.45,
      0.8,
      3.15,
      0.8,
      0.45,
      3.15,
      0.112,
      0.2,
      2.7,
      0.2,
      0.112,
      2.7,
      0.4,
      0,
      2.55,
      0.4,
      -0.224,
      2.55,
      0.224,
      -0.4,
      2.55,
      0,
      -0.4,
      2.55,
      1.3,
      0,
      2.55,
      1.3,
      -0.728,
      2.55,
      0.728,
      -1.3,
      2.55,
      0,
      -1.3,
      2.55,
      1.3,
      0,
      2.4,
      1.3,
      -0.728,
      2.4,
      0.728,
      -1.3,
      2.4,
      0,
      -1.3,
      2.4,
      -0.224,
      -0.4,
      2.55,
      -0.4,
      -0.224,
      2.55,
      -0.4,
      0,
      2.55,
      -0.728,
      -1.3,
      2.55,
      -1.3,
      -0.728,
      2.55,
      -1.3,
      0,
      2.55,
      -0.728,
      -1.3,
      2.4,
      -1.3,
      -0.728,
      2.4,
      -1.3,
      0,
      2.4,
      -0.4,
      0.224,
      2.55,
      -0.224,
      0.4,
      2.55,
      0,
      0.4,
      2.55,
      -1.3,
      0.728,
      2.55,
      -0.728,
      1.3,
      2.55,
      0,
      1.3,
      2.55,
      -1.3,
      0.728,
      2.4,
      -0.728,
      1.3,
      2.4,
      0,
      1.3,
      2.4,
      0.224,
      0.4,
      2.55,
      0.4,
      0.224,
      2.55,
      0.728,
      1.3,
      2.55,
      1.3,
      0.728,
      2.55,
      0.728,
      1.3,
      2.4,
      1.3,
      0.728,
      2.4,
      0,
      0,
      0,
      1.425,
      0,
      0,
      1.425,
      0.798,
      0,
      0.798,
      1.425,
      0,
      0,
      1.425,
      0,
      1.5,
      0,
      0.075,
      1.5,
      0.84,
      0.075,
      0.84,
      1.5,
      0.075,
      0,
      1.5,
      0.075,
      -0.798,
      1.425,
      0,
      -1.425,
      0.798,
      0,
      -1.425,
      0,
      0,
      -0.84,
      1.5,
      0.075,
      -1.5,
      0.84,
      0.075,
      -1.5,
      0,
      0.075,
      -1.425,
      -0.798,
      0,
      -0.798,
      -1.425,
      0,
      0,
      -1.425,
      0,
      -1.5,
      -0.84,
      0.075,
      -0.84,
      -1.5,
      0.075,
      0,
      -1.5,
      0.075,
      0.798,
      -1.425,
      0,
      1.425,
      -0.798,
      0,
      0.84,
      -1.5,
      0.075,
      1.5,
      -0.84,
      0.075
    ];
    super();
    segments = Math.max(2, Math.floor(segments));
    const blinnScale = 1.3;
    const maxHeight = 3.15 * (blinn ? 1 : blinnScale);
    const maxHeight2 = maxHeight / 2;
    const trueSize = size2 / maxHeight2;
    let numTriangles = bottom ? (8 * segments - 4) * segments : 0;
    numTriangles += lid ? (16 * segments - 4) * segments : 0;
    numTriangles += body ? 40 * segments * segments : 0;
    const indices = new Uint32Array(numTriangles * 3);
    let numVertices = bottom ? 4 : 0;
    numVertices += lid ? 8 : 0;
    numVertices += body ? 20 : 0;
    numVertices *= (segments + 1) * (segments + 1);
    const vertices = new Float32Array(numVertices * 3);
    const normals = new Float32Array(numVertices * 3);
    const uvs = new Float32Array(numVertices * 2);
    const ms = new Matrix4();
    ms.set(
      -1,
      3,
      -3,
      1,
      3,
      -6,
      3,
      0,
      -3,
      3,
      0,
      0,
      1,
      0,
      0,
      0
    );
    const g3 = [];
    const sp = [];
    const tp = [];
    const dsp = [];
    const dtp = [];
    const mgm = [];
    const vert = [];
    const sdir = [];
    const tdir = [];
    const norm = new Vector3();
    let tcoord;
    let sval;
    let tval;
    let p;
    let dsval = 0;
    let dtval = 0;
    const normOut = new Vector3();
    const gmx = new Matrix4();
    const tmtx = new Matrix4();
    const vsp = new Vector4();
    const vtp = new Vector4();
    const vdsp = new Vector4();
    const vdtp = new Vector4();
    const vsdir = new Vector3();
    const vtdir = new Vector3();
    const mst = ms.clone();
    mst.transpose();
    const notDegenerate = (vtx1, vtx2, vtx3) => (
      // if any vertex matches, return false
      !(vertices[vtx1 * 3] === vertices[vtx2 * 3] && vertices[vtx1 * 3 + 1] === vertices[vtx2 * 3 + 1] && vertices[vtx1 * 3 + 2] === vertices[vtx2 * 3 + 2] || vertices[vtx1 * 3] === vertices[vtx3 * 3] && vertices[vtx1 * 3 + 1] === vertices[vtx3 * 3 + 1] && vertices[vtx1 * 3 + 2] === vertices[vtx3 * 3 + 2] || vertices[vtx2 * 3] === vertices[vtx3 * 3] && vertices[vtx2 * 3 + 1] === vertices[vtx3 * 3 + 1] && vertices[vtx2 * 3 + 2] === vertices[vtx3 * 3 + 2])
    );
    for (let i = 0; i < 3; i++) {
      mgm[i] = new Matrix4();
    }
    const minPatches = body ? 0 : 20;
    const maxPatches = bottom ? 32 : 28;
    const vertPerRow = segments + 1;
    let surfCount = 0;
    let vertCount = 0;
    let normCount = 0;
    let uvCount = 0;
    let indexCount = 0;
    for (let surf = minPatches; surf < maxPatches; surf++) {
      if (lid || (surf < 20 || surf >= 28)) {
        for (let i = 0; i < 3; i++) {
          for (let r = 0; r < 4; r++) {
            for (let c2 = 0; c2 < 4; c2++) {
              g3[c2 * 4 + r] = teapotVertices[teapotPatches[surf * 16 + r * 4 + c2] * 3 + i];
              if (fitLid && (surf >= 20 && surf < 28) && i !== 2) {
                g3[c2 * 4 + r] *= 1.077;
              }
              if (!blinn && i === 2) {
                g3[c2 * 4 + r] *= blinnScale;
              }
            }
          }
          gmx.set(g3[0], g3[1], g3[2], g3[3], g3[4], g3[5], g3[6], g3[7], g3[8], g3[9], g3[10], g3[11], g3[12], g3[13], g3[14], g3[15]);
          tmtx.multiplyMatrices(gmx, ms);
          mgm[i].multiplyMatrices(mst, tmtx);
        }
        for (let sstep = 0; sstep <= segments; sstep++) {
          const s = sstep / segments;
          for (let tstep = 0; tstep <= segments; tstep++) {
            const t3 = tstep / segments;
            for (p = 4, sval = tval = 1; p--; ) {
              sp[p] = sval;
              tp[p] = tval;
              sval *= s;
              tval *= t3;
              if (p === 3) {
                dsp[p] = dtp[p] = 0;
                dsval = dtval = 1;
              } else {
                dsp[p] = dsval * (3 - p);
                dtp[p] = dtval * (3 - p);
                dsval *= s;
                dtval *= t3;
              }
            }
            vsp.fromArray(sp);
            vtp.fromArray(tp);
            vdsp.fromArray(dsp);
            vdtp.fromArray(dtp);
            for (let i = 0; i < 3; i++) {
              tcoord = vsp.clone();
              tcoord.applyMatrix4(mgm[i]);
              vert[i] = tcoord.dot(vtp);
              tcoord = vdsp.clone();
              tcoord.applyMatrix4(mgm[i]);
              sdir[i] = tcoord.dot(vtp);
              tcoord = vsp.clone();
              tcoord.applyMatrix4(mgm[i]);
              tdir[i] = tcoord.dot(vdtp);
            }
            vsdir.fromArray(sdir);
            vtdir.fromArray(tdir);
            norm.crossVectors(vtdir, vsdir);
            norm.normalize();
            if (vert[0] === 0 && vert[1] === 0) {
              normOut.set(0, vert[2] > maxHeight2 ? 1 : -1, 0);
            } else {
              normOut.set(norm.x, norm.z, -norm.y);
            }
            vertices[vertCount++] = trueSize * vert[0];
            vertices[vertCount++] = trueSize * (vert[2] - maxHeight2);
            vertices[vertCount++] = -trueSize * vert[1];
            normals[normCount++] = normOut.x;
            normals[normCount++] = normOut.y;
            normals[normCount++] = normOut.z;
            uvs[uvCount++] = 1 - t3;
            uvs[uvCount++] = 1 - s;
          }
        }
        for (let sstep = 0; sstep < segments; sstep++) {
          for (let tstep = 0; tstep < segments; tstep++) {
            const v12 = surfCount * vertPerRow * vertPerRow + sstep * vertPerRow + tstep;
            const v2 = v12 + 1;
            const v3 = v2 + vertPerRow;
            const v4 = v12 + vertPerRow;
            if (notDegenerate(v12, v2, v3)) {
              indices[indexCount++] = v12;
              indices[indexCount++] = v2;
              indices[indexCount++] = v3;
            }
            if (notDegenerate(v12, v3, v4)) {
              indices[indexCount++] = v12;
              indices[indexCount++] = v3;
              indices[indexCount++] = v4;
            }
          }
        }
        surfCount++;
      }
    }
    this.setIndex(new BufferAttribute(indices, 1));
    this.setAttribute("position", new BufferAttribute(vertices, 3));
    this.setAttribute("normal", new BufferAttribute(normals, 3));
    this.setAttribute("uv", new BufferAttribute(uvs, 2));
    this.computeBoundingSphere();
  }
};

// node_modules/three/examples/jsm/geometries/TextGeometry.js
var TextGeometry = class extends ExtrudeGeometry {
  /**
   * Constructs a new text geometry.
   *
   * @param {string} text - The text that should be transformed into a geometry.
   * @param {TextGeometry~Options} [parameters] - The text settings.
   */
  constructor(text2, parameters = {}) {
    const font = parameters.font;
    if (font === void 0) {
      super();
    } else {
      const shapes = font.generateShapes(text2, parameters.size);
      if (parameters.depth === void 0) parameters.depth = 50;
      if (parameters.bevelThickness === void 0) parameters.bevelThickness = 10;
      if (parameters.bevelSize === void 0) parameters.bevelSize = 8;
      if (parameters.bevelEnabled === void 0) parameters.bevelEnabled = false;
      super(shapes, parameters);
    }
    this.type = "TextGeometry";
  }
};

// node_modules/three/examples/jsm/helpers/LightProbeHelper.js
var LightProbeHelper = class extends Mesh {
  /**
   * Constructs a new light probe helper.
   *
   * @param {LightProbe} lightProbe - The light probe to visualize.
   * @param {number} [size=1] - The size of the helper.
   */
  constructor(lightProbe, size2 = 1) {
    const material = new ShaderMaterial({
      type: "LightProbeHelperMaterial",
      uniforms: {
        sh: { value: lightProbe.sh.coefficients },
        // by reference
        intensity: { value: lightProbe.intensity }
      },
      vertexShader: (
        /* glsl */
        `

				varying vec3 vNormal;

				void main() {

					vNormal = normalize( normalMatrix * normal );

					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

				}

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

				#define RECIPROCAL_PI 0.318309886

				vec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {

					// matrix is assumed to be orthogonal

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

				}

				// source: https://graphics.stanford.edu/papers/envmap/envmap.pdf,
				vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {

					// normal is assumed to have unit length,

					float x = normal.x, y = normal.y, z = normal.z;

					// band 0,
					vec3 result = shCoefficients[ 0 ] * 0.886227;

					// band 1,
					result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
					result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
					result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;

					// band 2,
					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;

				}

				uniform vec3 sh[ 9 ]; // sh coefficients

				uniform float intensity; // light probe intensity

				varying vec3 vNormal;

				void main() {

					vec3 normal = normalize( vNormal );

					vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );

					vec3 irradiance = shGetIrradianceAt( worldNormal, sh );

					vec3 outgoingLight = RECIPROCAL_PI * irradiance * intensity;

					gl_FragColor = linearToOutputTexel( vec4( outgoingLight, 1.0 ) );

				}

			`
      )
    });
    const geometry = new SphereGeometry(1, 32, 16);
    super(geometry, material);
    this.lightProbe = lightProbe;
    this.size = size2;
    this.type = "LightProbeHelper";
    this.onBeforeRender();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
  onBeforeRender() {
    this.position.copy(this.lightProbe.position);
    this.scale.set(1, 1, 1).multiplyScalar(this.size);
    this.material.uniforms.intensity.value = this.lightProbe.intensity;
  }
};

// node_modules/three/examples/jsm/helpers/OctreeHelper.js
var OctreeHelper = class extends LineSegments {
  /**
   * Constructs a new Octree helper.
   *
   * @param {Octree} octree - The octree to visualize.
   * @param {number|Color|string} [color=0xffff00] - The helper's color.
   */
  constructor(octree, color = 16776960) {
    super(new BufferGeometry(), new LineBasicMaterial({ color, toneMapped: false }));
    this.octree = octree;
    this.color = color;
    this.type = "OctreeHelper";
    this.update();
  }
  /**
   * Updates the helper. This method must be called whenever the Octree's
   * structure is changed.
   */
  update() {
    const vertices = [];
    function traverse(tree) {
      for (let i = 0; i < tree.length; i++) {
        const min = tree[i].box.min;
        const max2 = tree[i].box.max;
        vertices.push(max2.x, max2.y, max2.z);
        vertices.push(min.x, max2.y, max2.z);
        vertices.push(min.x, max2.y, max2.z);
        vertices.push(min.x, min.y, max2.z);
        vertices.push(min.x, min.y, max2.z);
        vertices.push(max2.x, min.y, max2.z);
        vertices.push(max2.x, min.y, max2.z);
        vertices.push(max2.x, max2.y, max2.z);
        vertices.push(max2.x, max2.y, min.z);
        vertices.push(min.x, max2.y, min.z);
        vertices.push(min.x, max2.y, min.z);
        vertices.push(min.x, min.y, min.z);
        vertices.push(min.x, min.y, min.z);
        vertices.push(max2.x, min.y, min.z);
        vertices.push(max2.x, min.y, min.z);
        vertices.push(max2.x, max2.y, min.z);
        vertices.push(max2.x, max2.y, max2.z);
        vertices.push(max2.x, max2.y, min.z);
        vertices.push(min.x, max2.y, max2.z);
        vertices.push(min.x, max2.y, min.z);
        vertices.push(min.x, min.y, max2.z);
        vertices.push(min.x, min.y, min.z);
        vertices.push(max2.x, min.y, max2.z);
        vertices.push(max2.x, min.y, min.z);
        traverse(tree[i].subTrees);
      }
    }
    traverse(this.octree.subTrees);
    this.geometry.dispose();
    this.geometry = new BufferGeometry();
    this.geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
};

// node_modules/three/examples/jsm/helpers/PositionalAudioHelper.js
var PositionalAudioHelper = class extends Line {
  /**
   * Constructs a new positional audio helper.
   *
   * @param {PositionalAudio} audio - The audio to visualize.
   * @param {number} [range=1] - The range of the directional cone.
   * @param {number} [divisionsInnerAngle=16] - The number of divisions of the inner part of the directional cone.
   * @param {number} [divisionsOuterAngle=2] The number of divisions of the outer part of the directional cone.
   */
  constructor(audio, range = 1, divisionsInnerAngle = 16, divisionsOuterAngle = 2) {
    const geometry = new BufferGeometry();
    const divisions = divisionsInnerAngle + divisionsOuterAngle * 2;
    const positions = new Float32Array((divisions * 3 + 3) * 3);
    geometry.setAttribute("position", new BufferAttribute(positions, 3));
    const materialInnerAngle = new LineBasicMaterial({ color: 65280 });
    const materialOuterAngle = new LineBasicMaterial({ color: 16776960 });
    super(geometry, [materialOuterAngle, materialInnerAngle]);
    this.audio = audio;
    this.range = range;
    this.divisionsInnerAngle = divisionsInnerAngle;
    this.divisionsOuterAngle = divisionsOuterAngle;
    this.type = "PositionalAudioHelper";
    this.update();
  }
  /**
   * Updates the helper. This method must be called whenever the directional cone
   * of the positional audio is changed.
   */
  update() {
    const audio = this.audio;
    const range = this.range;
    const divisionsInnerAngle = this.divisionsInnerAngle;
    const divisionsOuterAngle = this.divisionsOuterAngle;
    const coneInnerAngle = MathUtils.degToRad(audio.panner.coneInnerAngle);
    const coneOuterAngle = MathUtils.degToRad(audio.panner.coneOuterAngle);
    const halfConeInnerAngle = coneInnerAngle / 2;
    const halfConeOuterAngle = coneOuterAngle / 2;
    let start = 0;
    let count = 0;
    let i;
    let stride;
    const geometry = this.geometry;
    const positionAttribute = geometry.attributes.position;
    geometry.clearGroups();
    function generateSegment(from, to, divisions, materialIndex) {
      const step = (to - from) / divisions;
      positionAttribute.setXYZ(start, 0, 0, 0);
      count++;
      for (i = from; i < to; i += step) {
        stride = start + count;
        positionAttribute.setXYZ(stride, Math.sin(i) * range, 0, Math.cos(i) * range);
        positionAttribute.setXYZ(stride + 1, Math.sin(Math.min(i + step, to)) * range, 0, Math.cos(Math.min(i + step, to)) * range);
        positionAttribute.setXYZ(stride + 2, 0, 0, 0);
        count += 3;
      }
      geometry.addGroup(start, count, materialIndex);
      start += count;
      count = 0;
    }
    generateSegment(-halfConeOuterAngle, -halfConeInnerAngle, divisionsOuterAngle, 0);
    generateSegment(-halfConeInnerAngle, halfConeInnerAngle, divisionsInnerAngle, 1);
    generateSegment(halfConeInnerAngle, halfConeOuterAngle, divisionsOuterAngle, 0);
    positionAttribute.needsUpdate = true;
    if (coneInnerAngle === coneOuterAngle) this.material[0].visible = false;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose();
    this.material[0].dispose();
    this.material[1].dispose();
  }
};

// node_modules/three/examples/jsm/helpers/RectAreaLightHelper.js
var RectAreaLightHelper = class extends Line {
  /**
   * Constructs a new rect area light helper.
   *
   * @param {RectAreaLight} light - The light to visualize.
   * @param {number|Color|string} [color] - The helper's color.
   * If this is not the set, the helper will take the color of the light.
   */
  constructor(light, color) {
    const positions = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
    geometry.computeBoundingSphere();
    const material = new LineBasicMaterial({ fog: false });
    super(geometry, material);
    this.light = light;
    this.color = color;
    this.type = "RectAreaLightHelper";
    const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
    const geometry2 = new BufferGeometry();
    geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3));
    geometry2.computeBoundingSphere();
    this.add(new Mesh(geometry2, new MeshBasicMaterial({ side: BackSide, fog: false })));
  }
  updateMatrixWorld() {
    this.scale.set(0.5 * this.light.width, 0.5 * this.light.height, 1);
    if (this.color !== void 0) {
      this.material.color.set(this.color);
      this.children[0].material.color.set(this.color);
    } else {
      this.material.color.copy(this.light.color).multiplyScalar(this.light.intensity);
      const c2 = this.material.color;
      const max2 = Math.max(c2.r, c2.g, c2.b);
      if (max2 > 1) c2.multiplyScalar(1 / max2);
      this.children[0].material.color.copy(this.material.color);
    }
    this.matrixWorld.extractRotation(this.light.matrixWorld).scale(this.scale).copyPosition(this.light.matrixWorld);
    this.children[0].matrixWorld.copy(this.matrixWorld);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
    this.children[0].geometry.dispose();
    this.children[0].material.dispose();
  }
};

// node_modules/three/examples/jsm/utils/BufferGeometryUtils.js
var BufferGeometryUtils_exports = {};
__export(BufferGeometryUtils_exports, {
  computeMikkTSpaceTangents: () => computeMikkTSpaceTangents,
  computeMorphedAttributes: () => computeMorphedAttributes,
  deepCloneAttribute: () => deepCloneAttribute,
  deinterleaveAttribute: () => deinterleaveAttribute,
  deinterleaveGeometry: () => deinterleaveGeometry,
  estimateBytesUsed: () => estimateBytesUsed,
  interleaveAttributes: () => interleaveAttributes,
  mergeAttributes: () => mergeAttributes,
  mergeGeometries: () => mergeGeometries,
  mergeGroups: () => mergeGroups,
  mergeVertices: () => mergeVertices,
  toCreasedNormals: () => toCreasedNormals,
  toTrianglesDrawMode: () => toTrianglesDrawMode
});
function computeMikkTSpaceTangents(geometry, MikkTSpace, negateSign = true) {
  if (!MikkTSpace || !MikkTSpace.isReady) {
    throw new Error("BufferGeometryUtils: Initialized MikkTSpace library required.");
  }
  if (!geometry.hasAttribute("position") || !geometry.hasAttribute("normal") || !geometry.hasAttribute("uv")) {
    throw new Error('BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.');
  }
  function getAttributeArray(attribute) {
    if (attribute.normalized || attribute.isInterleavedBufferAttribute) {
      const dstArray = new Float32Array(attribute.count * attribute.itemSize);
      for (let i = 0, j2 = 0; i < attribute.count; i++) {
        dstArray[j2++] = attribute.getX(i);
        dstArray[j2++] = attribute.getY(i);
        if (attribute.itemSize > 2) {
          dstArray[j2++] = attribute.getZ(i);
        }
      }
      return dstArray;
    }
    if (attribute.array instanceof Float32Array) {
      return attribute.array;
    }
    return new Float32Array(attribute.array);
  }
  const _geometry2 = geometry.index ? geometry.toNonIndexed() : geometry;
  const tangents = MikkTSpace.generateTangents(
    getAttributeArray(_geometry2.attributes.position),
    getAttributeArray(_geometry2.attributes.normal),
    getAttributeArray(_geometry2.attributes.uv)
  );
  if (negateSign) {
    for (let i = 3; i < tangents.length; i += 4) {
      tangents[i] *= -1;
    }
  }
  _geometry2.setAttribute("tangent", new BufferAttribute(tangents, 4));
  if (geometry !== _geometry2) {
    geometry.copy(_geometry2);
  }
  return geometry;
}
function mergeGeometries(geometries, useGroups = false) {
  const isIndexed = geometries[0].index !== null;
  const attributesUsed = new Set(Object.keys(geometries[0].attributes));
  const morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes));
  const attributes = {};
  const morphAttributes = {};
  const morphTargetsRelative = geometries[0].morphTargetsRelative;
  const mergedGeometry = new BufferGeometry();
  let offset = 0;
  for (let i = 0; i < geometries.length; ++i) {
    const geometry = geometries[i];
    let attributesCount = 0;
    if (isIndexed !== (geometry.index !== null)) {
      console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + i + ". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.");
      return null;
    }
    for (const name2 in geometry.attributes) {
      if (!attributesUsed.has(name2)) {
        console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + i + '. All geometries must have compatible attributes; make sure "' + name2 + '" attribute exists among all geometries, or in none of them.');
        return null;
      }
      if (attributes[name2] === void 0) attributes[name2] = [];
      attributes[name2].push(geometry.attributes[name2]);
      attributesCount++;
    }
    if (attributesCount !== attributesUsed.size) {
      console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + i + ". Make sure all geometries have the same number of attributes.");
      return null;
    }
    if (morphTargetsRelative !== geometry.morphTargetsRelative) {
      console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + i + ". .morphTargetsRelative must be consistent throughout all geometries.");
      return null;
    }
    for (const name2 in geometry.morphAttributes) {
      if (!morphAttributesUsed.has(name2)) {
        console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + i + ".  .morphAttributes must be consistent throughout all geometries.");
        return null;
      }
      if (morphAttributes[name2] === void 0) morphAttributes[name2] = [];
      morphAttributes[name2].push(geometry.morphAttributes[name2]);
    }
    if (useGroups) {
      let count;
      if (isIndexed) {
        count = geometry.index.count;
      } else if (geometry.attributes.position !== void 0) {
        count = geometry.attributes.position.count;
      } else {
        console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + i + ". The geometry must have either an index or a position attribute");
        return null;
      }
      mergedGeometry.addGroup(offset, count, i);
      offset += count;
    }
  }
  if (isIndexed) {
    let indexOffset = 0;
    const mergedIndex = [];
    for (let i = 0; i < geometries.length; ++i) {
      const index2 = geometries[i].index;
      for (let j2 = 0; j2 < index2.count; ++j2) {
        mergedIndex.push(index2.getX(j2) + indexOffset);
      }
      indexOffset += geometries[i].attributes.position.count;
    }
    mergedGeometry.setIndex(mergedIndex);
  }
  for (const name2 in attributes) {
    const mergedAttribute = mergeAttributes(attributes[name2]);
    if (!mergedAttribute) {
      console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the " + name2 + " attribute.");
      return null;
    }
    mergedGeometry.setAttribute(name2, mergedAttribute);
  }
  for (const name2 in morphAttributes) {
    const numMorphTargets = morphAttributes[name2][0].length;
    if (numMorphTargets === 0) break;
    mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
    mergedGeometry.morphAttributes[name2] = [];
    for (let i = 0; i < numMorphTargets; ++i) {
      const morphAttributesToMerge = [];
      for (let j2 = 0; j2 < morphAttributes[name2].length; ++j2) {
        morphAttributesToMerge.push(morphAttributes[name2][j2][i]);
      }
      const mergedMorphAttribute = mergeAttributes(morphAttributesToMerge);
      if (!mergedMorphAttribute) {
        console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the " + name2 + " morphAttribute.");
        return null;
      }
      mergedGeometry.morphAttributes[name2].push(mergedMorphAttribute);
    }
  }
  return mergedGeometry;
}
function mergeAttributes(attributes) {
  let TypedArray;
  let itemSize;
  let normalized;
  let gpuType = -1;
  let arrayLength = 0;
  for (let i = 0; i < attributes.length; ++i) {
    const attribute = attributes[i];
    if (TypedArray === void 0) TypedArray = attribute.array.constructor;
    if (TypedArray !== attribute.array.constructor) {
      console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.");
      return null;
    }
    if (itemSize === void 0) itemSize = attribute.itemSize;
    if (itemSize !== attribute.itemSize) {
      console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.");
      return null;
    }
    if (normalized === void 0) normalized = attribute.normalized;
    if (normalized !== attribute.normalized) {
      console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.");
      return null;
    }
    if (gpuType === -1) gpuType = attribute.gpuType;
    if (gpuType !== attribute.gpuType) {
      console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.");
      return null;
    }
    arrayLength += attribute.count * itemSize;
  }
  const array = new TypedArray(arrayLength);
  const result = new BufferAttribute(array, itemSize, normalized);
  let offset = 0;
  for (let i = 0; i < attributes.length; ++i) {
    const attribute = attributes[i];
    if (attribute.isInterleavedBufferAttribute) {
      const tupleOffset = offset / itemSize;
      for (let j2 = 0, l2 = attribute.count; j2 < l2; j2++) {
        for (let c2 = 0; c2 < itemSize; c2++) {
          const value2 = attribute.getComponent(j2, c2);
          result.setComponent(j2 + tupleOffset, c2, value2);
        }
      }
    } else {
      array.set(attribute.array, offset);
    }
    offset += attribute.count * itemSize;
  }
  if (gpuType !== void 0) {
    result.gpuType = gpuType;
  }
  return result;
}
function deepCloneAttribute(attribute) {
  if (attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute) {
    return deinterleaveAttribute(attribute);
  }
  if (attribute.isInstancedBufferAttribute) {
    return new InstancedBufferAttribute().copy(attribute);
  }
  return new BufferAttribute().copy(attribute);
}
function interleaveAttributes(attributes) {
  let TypedArray;
  let arrayLength = 0;
  let stride = 0;
  for (let i = 0, l2 = attributes.length; i < l2; ++i) {
    const attribute = attributes[i];
    if (TypedArray === void 0) TypedArray = attribute.array.constructor;
    if (TypedArray !== attribute.array.constructor) {
      console.error("AttributeBuffers of different types cannot be interleaved");
      return null;
    }
    arrayLength += attribute.array.length;
    stride += attribute.itemSize;
  }
  const interleavedBuffer = new InterleavedBuffer(new TypedArray(arrayLength), stride);
  let offset = 0;
  const res = [];
  const getters = ["getX", "getY", "getZ", "getW"];
  const setters = ["setX", "setY", "setZ", "setW"];
  for (let j2 = 0, l2 = attributes.length; j2 < l2; j2++) {
    const attribute = attributes[j2];
    const itemSize = attribute.itemSize;
    const count = attribute.count;
    const iba = new InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, attribute.normalized);
    res.push(iba);
    offset += itemSize;
    for (let c2 = 0; c2 < count; c2++) {
      for (let k2 = 0; k2 < itemSize; k2++) {
        iba[setters[k2]](c2, attribute[getters[k2]](c2));
      }
    }
  }
  return res;
}
function deinterleaveAttribute(attribute) {
  const cons = attribute.data.array.constructor;
  const count = attribute.count;
  const itemSize = attribute.itemSize;
  const normalized = attribute.normalized;
  const array = new cons(count * itemSize);
  let newAttribute;
  if (attribute.isInstancedInterleavedBufferAttribute) {
    newAttribute = new InstancedBufferAttribute(array, itemSize, normalized, attribute.meshPerAttribute);
  } else {
    newAttribute = new BufferAttribute(array, itemSize, normalized);
  }
  for (let i = 0; i < count; i++) {
    newAttribute.setX(i, attribute.getX(i));
    if (itemSize >= 2) {
      newAttribute.setY(i, attribute.getY(i));
    }
    if (itemSize >= 3) {
      newAttribute.setZ(i, attribute.getZ(i));
    }
    if (itemSize >= 4) {
      newAttribute.setW(i, attribute.getW(i));
    }
  }
  return newAttribute;
}
function deinterleaveGeometry(geometry) {
  const attributes = geometry.attributes;
  const morphTargets = geometry.morphTargets;
  const attrMap = /* @__PURE__ */ new Map();
  for (const key2 in attributes) {
    const attr = attributes[key2];
    if (attr.isInterleavedBufferAttribute) {
      if (!attrMap.has(attr)) {
        attrMap.set(attr, deinterleaveAttribute(attr));
      }
      attributes[key2] = attrMap.get(attr);
    }
  }
  for (const key2 in morphTargets) {
    const attr = morphTargets[key2];
    if (attr.isInterleavedBufferAttribute) {
      if (!attrMap.has(attr)) {
        attrMap.set(attr, deinterleaveAttribute(attr));
      }
      morphTargets[key2] = attrMap.get(attr);
    }
  }
}
function estimateBytesUsed(geometry) {
  let mem = 0;
  for (const name2 in geometry.attributes) {
    const attr = geometry.getAttribute(name2);
    mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  }
  const indices = geometry.getIndex();
  mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  return mem;
}
function mergeVertices(geometry, tolerance = 1e-4) {
  tolerance = Math.max(tolerance, Number.EPSILON);
  const hashToIndex = {};
  const indices = geometry.getIndex();
  const positions = geometry.getAttribute("position");
  const vertexCount = indices ? indices.count : positions.count;
  let nextIndex = 0;
  const attributeNames = Object.keys(geometry.attributes);
  const tmpAttributes = {};
  const tmpMorphAttributes = {};
  const newIndices = [];
  const getters = ["getX", "getY", "getZ", "getW"];
  const setters = ["setX", "setY", "setZ", "setW"];
  for (let i = 0, l2 = attributeNames.length; i < l2; i++) {
    const name2 = attributeNames[i];
    const attr = geometry.attributes[name2];
    tmpAttributes[name2] = new attr.constructor(
      new attr.array.constructor(attr.count * attr.itemSize),
      attr.itemSize,
      attr.normalized
    );
    const morphAttributes = geometry.morphAttributes[name2];
    if (morphAttributes) {
      if (!tmpMorphAttributes[name2]) tmpMorphAttributes[name2] = [];
      morphAttributes.forEach((morphAttr, i2) => {
        const array = new morphAttr.array.constructor(morphAttr.count * morphAttr.itemSize);
        tmpMorphAttributes[name2][i2] = new morphAttr.constructor(array, morphAttr.itemSize, morphAttr.normalized);
      });
    }
  }
  const halfTolerance = tolerance * 0.5;
  const exponent = Math.log10(1 / tolerance);
  const hashMultiplier = Math.pow(10, exponent);
  const hashAdditive = halfTolerance * hashMultiplier;
  for (let i = 0; i < vertexCount; i++) {
    const index2 = indices ? indices.getX(i) : i;
    let hash = "";
    for (let j2 = 0, l2 = attributeNames.length; j2 < l2; j2++) {
      const name2 = attributeNames[j2];
      const attribute = geometry.getAttribute(name2);
      const itemSize = attribute.itemSize;
      for (let k2 = 0; k2 < itemSize; k2++) {
        hash += `${~~(attribute[getters[k2]](index2) * hashMultiplier + hashAdditive)},`;
      }
    }
    if (hash in hashToIndex) {
      newIndices.push(hashToIndex[hash]);
    } else {
      for (let j2 = 0, l2 = attributeNames.length; j2 < l2; j2++) {
        const name2 = attributeNames[j2];
        const attribute = geometry.getAttribute(name2);
        const morphAttributes = geometry.morphAttributes[name2];
        const itemSize = attribute.itemSize;
        const newArray = tmpAttributes[name2];
        const newMorphArrays = tmpMorphAttributes[name2];
        for (let k2 = 0; k2 < itemSize; k2++) {
          const getterFunc = getters[k2];
          const setterFunc = setters[k2];
          newArray[setterFunc](nextIndex, attribute[getterFunc](index2));
          if (morphAttributes) {
            for (let m = 0, ml = morphAttributes.length; m < ml; m++) {
              newMorphArrays[m][setterFunc](nextIndex, morphAttributes[m][getterFunc](index2));
            }
          }
        }
      }
      hashToIndex[hash] = nextIndex;
      newIndices.push(nextIndex);
      nextIndex++;
    }
  }
  const result = geometry.clone();
  for (const name2 in geometry.attributes) {
    const tmpAttribute = tmpAttributes[name2];
    result.setAttribute(name2, new tmpAttribute.constructor(
      tmpAttribute.array.slice(0, nextIndex * tmpAttribute.itemSize),
      tmpAttribute.itemSize,
      tmpAttribute.normalized
    ));
    if (!(name2 in tmpMorphAttributes)) continue;
    for (let j2 = 0; j2 < tmpMorphAttributes[name2].length; j2++) {
      const tmpMorphAttribute = tmpMorphAttributes[name2][j2];
      result.morphAttributes[name2][j2] = new tmpMorphAttribute.constructor(
        tmpMorphAttribute.array.slice(0, nextIndex * tmpMorphAttribute.itemSize),
        tmpMorphAttribute.itemSize,
        tmpMorphAttribute.normalized
      );
    }
  }
  result.setIndex(newIndices);
  return result;
}
function toTrianglesDrawMode(geometry, drawMode) {
  if (drawMode === TrianglesDrawMode) {
    console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.");
    return geometry;
  }
  if (drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode) {
    let index2 = geometry.getIndex();
    if (index2 === null) {
      const indices = [];
      const position2 = geometry.getAttribute("position");
      if (position2 !== void 0) {
        for (let i = 0; i < position2.count; i++) {
          indices.push(i);
        }
        geometry.setIndex(indices);
        index2 = geometry.getIndex();
      } else {
        console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.");
        return geometry;
      }
    }
    const numberOfTriangles = index2.count - 2;
    const newIndices = [];
    if (drawMode === TriangleFanDrawMode) {
      for (let i = 1; i <= numberOfTriangles; i++) {
        newIndices.push(index2.getX(0));
        newIndices.push(index2.getX(i));
        newIndices.push(index2.getX(i + 1));
      }
    } else {
      for (let i = 0; i < numberOfTriangles; i++) {
        if (i % 2 === 0) {
          newIndices.push(index2.getX(i));
          newIndices.push(index2.getX(i + 1));
          newIndices.push(index2.getX(i + 2));
        } else {
          newIndices.push(index2.getX(i + 2));
          newIndices.push(index2.getX(i + 1));
          newIndices.push(index2.getX(i));
        }
      }
    }
    if (newIndices.length / 3 !== numberOfTriangles) {
      console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");
    }
    const newGeometry = geometry.clone();
    newGeometry.setIndex(newIndices);
    newGeometry.clearGroups();
    return newGeometry;
  } else {
    console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:", drawMode);
    return geometry;
  }
}
function computeMorphedAttributes(object) {
  const _vA2 = new Vector3();
  const _vB2 = new Vector3();
  const _vC2 = new Vector3();
  const _tempA = new Vector3();
  const _tempB = new Vector3();
  const _tempC = new Vector3();
  const _morphA = new Vector3();
  const _morphB = new Vector3();
  const _morphC = new Vector3();
  function _calculateMorphedAttributeData(object2, attribute, morphAttribute, morphTargetsRelative2, a3, b5, c3, modifiedAttributeArray) {
    _vA2.fromBufferAttribute(attribute, a3);
    _vB2.fromBufferAttribute(attribute, b5);
    _vC2.fromBufferAttribute(attribute, c3);
    const morphInfluences = object2.morphTargetInfluences;
    if (morphAttribute && morphInfluences) {
      _morphA.set(0, 0, 0);
      _morphB.set(0, 0, 0);
      _morphC.set(0, 0, 0);
      for (let i2 = 0, il2 = morphAttribute.length; i2 < il2; i2++) {
        const influence = morphInfluences[i2];
        const morph = morphAttribute[i2];
        if (influence === 0) continue;
        _tempA.fromBufferAttribute(morph, a3);
        _tempB.fromBufferAttribute(morph, b5);
        _tempC.fromBufferAttribute(morph, c3);
        if (morphTargetsRelative2) {
          _morphA.addScaledVector(_tempA, influence);
          _morphB.addScaledVector(_tempB, influence);
          _morphC.addScaledVector(_tempC, influence);
        } else {
          _morphA.addScaledVector(_tempA.sub(_vA2), influence);
          _morphB.addScaledVector(_tempB.sub(_vB2), influence);
          _morphC.addScaledVector(_tempC.sub(_vC2), influence);
        }
      }
      _vA2.add(_morphA);
      _vB2.add(_morphB);
      _vC2.add(_morphC);
    }
    if (object2.isSkinnedMesh) {
      object2.applyBoneTransform(a3, _vA2);
      object2.applyBoneTransform(b5, _vB2);
      object2.applyBoneTransform(c3, _vC2);
    }
    modifiedAttributeArray[a3 * 3 + 0] = _vA2.x;
    modifiedAttributeArray[a3 * 3 + 1] = _vA2.y;
    modifiedAttributeArray[a3 * 3 + 2] = _vA2.z;
    modifiedAttributeArray[b5 * 3 + 0] = _vB2.x;
    modifiedAttributeArray[b5 * 3 + 1] = _vB2.y;
    modifiedAttributeArray[b5 * 3 + 2] = _vB2.z;
    modifiedAttributeArray[c3 * 3 + 0] = _vC2.x;
    modifiedAttributeArray[c3 * 3 + 1] = _vC2.y;
    modifiedAttributeArray[c3 * 3 + 2] = _vC2.z;
  }
  const geometry = object.geometry;
  const material = object.material;
  let a2, b3, c2;
  const index2 = geometry.index;
  const positionAttribute = geometry.attributes.position;
  const morphPosition = geometry.morphAttributes.position;
  const morphTargetsRelative = geometry.morphTargetsRelative;
  const normalAttribute = geometry.attributes.normal;
  const morphNormal = geometry.morphAttributes.position;
  const groups = geometry.groups;
  const drawRange = geometry.drawRange;
  let i, j2, il, jl;
  let group;
  let start, end;
  const modifiedPosition = new Float32Array(positionAttribute.count * positionAttribute.itemSize);
  const modifiedNormal = new Float32Array(normalAttribute.count * normalAttribute.itemSize);
  if (index2 !== null) {
    if (Array.isArray(material)) {
      for (i = 0, il = groups.length; i < il; i++) {
        group = groups[i];
        start = Math.max(group.start, drawRange.start);
        end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
        for (j2 = start, jl = end; j2 < jl; j2 += 3) {
          a2 = index2.getX(j2);
          b3 = index2.getX(j2 + 1);
          c2 = index2.getX(j2 + 2);
          _calculateMorphedAttributeData(
            object,
            positionAttribute,
            morphPosition,
            morphTargetsRelative,
            a2,
            b3,
            c2,
            modifiedPosition
          );
          _calculateMorphedAttributeData(
            object,
            normalAttribute,
            morphNormal,
            morphTargetsRelative,
            a2,
            b3,
            c2,
            modifiedNormal
          );
        }
      }
    } else {
      start = Math.max(0, drawRange.start);
      end = Math.min(index2.count, drawRange.start + drawRange.count);
      for (i = start, il = end; i < il; i += 3) {
        a2 = index2.getX(i);
        b3 = index2.getX(i + 1);
        c2 = index2.getX(i + 2);
        _calculateMorphedAttributeData(
          object,
          positionAttribute,
          morphPosition,
          morphTargetsRelative,
          a2,
          b3,
          c2,
          modifiedPosition
        );
        _calculateMorphedAttributeData(
          object,
          normalAttribute,
          morphNormal,
          morphTargetsRelative,
          a2,
          b3,
          c2,
          modifiedNormal
        );
      }
    }
  } else {
    if (Array.isArray(material)) {
      for (i = 0, il = groups.length; i < il; i++) {
        group = groups[i];
        start = Math.max(group.start, drawRange.start);
        end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
        for (j2 = start, jl = end; j2 < jl; j2 += 3) {
          a2 = j2;
          b3 = j2 + 1;
          c2 = j2 + 2;
          _calculateMorphedAttributeData(
            object,
            positionAttribute,
            morphPosition,
            morphTargetsRelative,
            a2,
            b3,
            c2,
            modifiedPosition
          );
          _calculateMorphedAttributeData(
            object,
            normalAttribute,
            morphNormal,
            morphTargetsRelative,
            a2,
            b3,
            c2,
            modifiedNormal
          );
        }
      }
    } else {
      start = Math.max(0, drawRange.start);
      end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
      for (i = start, il = end; i < il; i += 3) {
        a2 = i;
        b3 = i + 1;
        c2 = i + 2;
        _calculateMorphedAttributeData(
          object,
          positionAttribute,
          morphPosition,
          morphTargetsRelative,
          a2,
          b3,
          c2,
          modifiedPosition
        );
        _calculateMorphedAttributeData(
          object,
          normalAttribute,
          morphNormal,
          morphTargetsRelative,
          a2,
          b3,
          c2,
          modifiedNormal
        );
      }
    }
  }
  const morphedPositionAttribute = new Float32BufferAttribute(modifiedPosition, 3);
  const morphedNormalAttribute = new Float32BufferAttribute(modifiedNormal, 3);
  return {
    positionAttribute,
    normalAttribute,
    morphedPositionAttribute,
    morphedNormalAttribute
  };
}
function mergeGroups(geometry) {
  if (geometry.groups.length === 0) {
    console.warn("THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.");
    return geometry;
  }
  let groups = geometry.groups;
  groups = groups.sort((a2, b3) => {
    if (a2.materialIndex !== b3.materialIndex) return a2.materialIndex - b3.materialIndex;
    return a2.start - b3.start;
  });
  if (geometry.getIndex() === null) {
    const positionAttribute = geometry.getAttribute("position");
    const indices = [];
    for (let i = 0; i < positionAttribute.count; i += 3) {
      indices.push(i, i + 1, i + 2);
    }
    geometry.setIndex(indices);
  }
  const index2 = geometry.getIndex();
  const newIndices = [];
  for (let i = 0; i < groups.length; i++) {
    const group = groups[i];
    const groupStart = group.start;
    const groupLength = groupStart + group.count;
    for (let j2 = groupStart; j2 < groupLength; j2++) {
      newIndices.push(index2.getX(j2));
    }
  }
  geometry.dispose();
  geometry.setIndex(newIndices);
  let start = 0;
  for (let i = 0; i < groups.length; i++) {
    const group = groups[i];
    group.start = start;
    start += group.count;
  }
  let currentGroup = groups[0];
  geometry.groups = [currentGroup];
  for (let i = 1; i < groups.length; i++) {
    const group = groups[i];
    if (currentGroup.materialIndex === group.materialIndex) {
      currentGroup.count += group.count;
    } else {
      currentGroup = group;
      geometry.groups.push(currentGroup);
    }
  }
  return geometry;
}
function toCreasedNormals(geometry, creaseAngle = Math.PI / 3) {
  const creaseDot = Math.cos(creaseAngle);
  const hashMultiplier = (1 + 1e-10) * 100;
  const verts = [new Vector3(), new Vector3(), new Vector3()];
  const tempVec1 = new Vector3();
  const tempVec2 = new Vector3();
  const tempNorm = new Vector3();
  const tempNorm2 = new Vector3();
  function hashVertex(v) {
    const x2 = ~~(v.x * hashMultiplier);
    const y = ~~(v.y * hashMultiplier);
    const z = ~~(v.z * hashMultiplier);
    return `${x2},${y},${z}`;
  }
  const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry;
  const posAttr = resultGeometry.attributes.position;
  const vertexMap = {};
  for (let i = 0, l2 = posAttr.count / 3; i < l2; i++) {
    const i3 = 3 * i;
    const a2 = verts[0].fromBufferAttribute(posAttr, i3 + 0);
    const b3 = verts[1].fromBufferAttribute(posAttr, i3 + 1);
    const c2 = verts[2].fromBufferAttribute(posAttr, i3 + 2);
    tempVec1.subVectors(c2, b3);
    tempVec2.subVectors(a2, b3);
    const normal = new Vector3().crossVectors(tempVec1, tempVec2).normalize();
    for (let n2 = 0; n2 < 3; n2++) {
      const vert = verts[n2];
      const hash = hashVertex(vert);
      if (!(hash in vertexMap)) {
        vertexMap[hash] = [];
      }
      vertexMap[hash].push(normal);
    }
  }
  const normalArray = new Float32Array(posAttr.count * 3);
  const normAttr = new BufferAttribute(normalArray, 3, false);
  for (let i = 0, l2 = posAttr.count / 3; i < l2; i++) {
    const i3 = 3 * i;
    const a2 = verts[0].fromBufferAttribute(posAttr, i3 + 0);
    const b3 = verts[1].fromBufferAttribute(posAttr, i3 + 1);
    const c2 = verts[2].fromBufferAttribute(posAttr, i3 + 2);
    tempVec1.subVectors(c2, b3);
    tempVec2.subVectors(a2, b3);
    tempNorm.crossVectors(tempVec1, tempVec2).normalize();
    for (let n2 = 0; n2 < 3; n2++) {
      const vert = verts[n2];
      const hash = hashVertex(vert);
      const otherNormals = vertexMap[hash];
      tempNorm2.set(0, 0, 0);
      for (let k2 = 0, lk = otherNormals.length; k2 < lk; k2++) {
        const otherNorm = otherNormals[k2];
        if (tempNorm.dot(otherNorm) > creaseDot) {
          tempNorm2.add(otherNorm);
        }
      }
      tempNorm2.normalize();
      normAttr.setXYZ(i3 + n2, tempNorm2.x, tempNorm2.y, tempNorm2.z);
    }
  }
  resultGeometry.setAttribute("normal", normAttr);
  return resultGeometry;
}

// node_modules/three/examples/jsm/helpers/TextureHelper.js
var TextureHelper = class extends Mesh {
  /**
   * Constructs a new texture helper.
   *
   * @param {Texture} texture - The texture to visualize.
   * @param {number} [width=1] - The helper's width.
   * @param {number} [height=1] - The helper's height.
   * @param {number} [depth=1] - The helper's depth.
   */
  constructor(texture, width2 = 1, height2 = 1, depth = 1) {
    const material = new ShaderMaterial({
      type: "TextureHelperMaterial",
      side: DoubleSide,
      transparent: true,
      uniforms: {
        map: { value: texture },
        alpha: { value: getAlpha(texture) }
      },
      vertexShader: [
        "attribute vec3 uvw;",
        "varying vec3 vUvw;",
        "void main() {",
        "	vUvw = uvw;",
        "	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
        "}"
      ].join("\n"),
      fragmentShader: [
        "precision highp float;",
        "precision highp sampler2DArray;",
        "precision highp sampler3D;",
        "uniform {samplerType} map;",
        "uniform float alpha;",
        "varying vec3 vUvw;",
        "vec4 textureHelper( in sampler2D map ) { return texture( map, vUvw.xy ); }",
        "vec4 textureHelper( in sampler2DArray map ) { return texture( map, vUvw ); }",
        "vec4 textureHelper( in sampler3D map ) { return texture( map, vUvw ); }",
        "vec4 textureHelper( in samplerCube map ) { return texture( map, vUvw ); }",
        "void main() {",
        "	gl_FragColor = linearToOutputTexel( vec4( textureHelper( map ).xyz, alpha ) );",
        "}"
      ].join("\n").replace("{samplerType}", getSamplerType(texture))
    });
    const geometry = texture.isCubeTexture ? createCubeGeometry(width2, height2, depth) : createSliceGeometry(texture, width2, height2, depth);
    super(geometry, material);
    this.texture = texture;
    this.type = "TextureHelper";
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
};
function getSamplerType(texture) {
  if (texture.isCubeTexture) {
    return "samplerCube";
  } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
    return "sampler2DArray";
  } else if (texture.isData3DTexture || texture.isCompressed3DTexture) {
    return "sampler3D";
  } else {
    return "sampler2D";
  }
}
function getImageCount(texture) {
  if (texture.isCubeTexture) {
    return 6;
  } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
    return texture.image.depth;
  } else if (texture.isData3DTexture || texture.isCompressed3DTexture) {
    return texture.image.depth;
  } else {
    return 1;
  }
}
function getAlpha(texture) {
  if (texture.isCubeTexture) {
    return 1;
  } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) {
    return Math.max(1 / texture.image.depth, 0.25);
  } else if (texture.isData3DTexture || texture.isCompressed3DTexture) {
    return Math.max(1 / texture.image.depth, 0.25);
  } else {
    return 1;
  }
}
function createCubeGeometry(width2, height2, depth) {
  const geometry = new BoxGeometry(width2, height2, depth);
  const position2 = geometry.attributes.position;
  const uv = geometry.attributes.uv;
  const uvw = new BufferAttribute(new Float32Array(uv.count * 3), 3);
  const _direction = new Vector3();
  for (let j2 = 0, jl = uv.count; j2 < jl; ++j2) {
    _direction.fromBufferAttribute(position2, j2).normalize();
    const u2 = _direction.x;
    const v = _direction.y;
    const w = _direction.z;
    uvw.setXYZ(j2, u2, v, w);
  }
  geometry.deleteAttribute("uv");
  geometry.setAttribute("uvw", uvw);
  return geometry;
}
function createSliceGeometry(texture, width2, height2, depth) {
  const sliceCount = getImageCount(texture);
  const geometries = [];
  for (let i = 0; i < sliceCount; ++i) {
    const geometry = new PlaneGeometry(width2, height2);
    if (sliceCount > 1) {
      geometry.translate(0, 0, depth * (i / (sliceCount - 1) - 0.5));
    }
    const uv = geometry.attributes.uv;
    const uvw = new BufferAttribute(new Float32Array(uv.count * 3), 3);
    for (let j2 = 0, jl = uv.count; j2 < jl; ++j2) {
      const u2 = uv.getX(j2);
      const v = texture.flipY ? uv.getY(j2) : 1 - uv.getY(j2);
      const w = sliceCount === 1 ? 1 : texture.isDataArrayTexture || texture.isCompressedArrayTexture ? i : i / (sliceCount - 1);
      uvw.setXYZ(j2, u2, v, w);
    }
    geometry.deleteAttribute("uv");
    geometry.setAttribute("uvw", uvw);
    geometries.push(geometry);
  }
  return mergeGeometries(geometries);
}

// node_modules/three/examples/jsm/helpers/VertexNormalsHelper.js
var _v13 = new Vector3();
var _v23 = new Vector3();
var _normalMatrix = new Matrix3();
var VertexNormalsHelper = class extends LineSegments {
  /**
   * Constructs a new vertex normals helper.
   *
   * @param {Object3D} object - The object for which to visualize vertex normals.
   * @param {number} [size=1] - The helper's size.
   * @param {number|Color|string} [color=0xff0000] - The helper's color.
   */
  constructor(object, size2 = 1, color = 16711680) {
    const geometry = new BufferGeometry();
    const nNormals = object.geometry.attributes.normal.count;
    const positions = new Float32BufferAttribute(nNormals * 2 * 3, 3);
    geometry.setAttribute("position", positions);
    super(geometry, new LineBasicMaterial({ color, toneMapped: false }));
    this.object = object;
    this.size = size2;
    this.type = "VertexNormalsHelper";
    this.matrixAutoUpdate = false;
    this.isVertexNormalsHelper = true;
    this.update();
  }
  /**
   * Updates the vertex normals preview based on the object's world transform.
   */
  update() {
    this.object.updateMatrixWorld(true);
    _normalMatrix.getNormalMatrix(this.object.matrixWorld);
    const matrixWorld = this.object.matrixWorld;
    const position2 = this.geometry.attributes.position;
    const objGeometry = this.object.geometry;
    if (objGeometry) {
      const objPos = objGeometry.attributes.position;
      const objNorm = objGeometry.attributes.normal;
      let idx = 0;
      for (let j2 = 0, jl = objPos.count; j2 < jl; j2++) {
        _v13.fromBufferAttribute(objPos, j2).applyMatrix4(matrixWorld);
        _v23.fromBufferAttribute(objNorm, j2);
        _v23.applyMatrix3(_normalMatrix).normalize().multiplyScalar(this.size).add(_v13);
        position2.setXYZ(idx, _v13.x, _v13.y, _v13.z);
        idx = idx + 1;
        position2.setXYZ(idx, _v23.x, _v23.y, _v23.z);
        idx = idx + 1;
      }
    }
    position2.needsUpdate = true;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
};

// node_modules/three/examples/jsm/helpers/VertexTangentsHelper.js
var _v14 = new Vector3();
var _v24 = new Vector3();
var VertexTangentsHelper = class extends LineSegments {
  /**
   * Constructs a new vertex tangents helper.
   *
   * @param {Object3D} object - The object for which to visualize vertex tangents.
   * @param {number} [size=1] - The helper's size.
   * @param {number|Color|string} [color=0xff0000] - The helper's color.
   */
  constructor(object, size2 = 1, color = 65535) {
    const geometry = new BufferGeometry();
    const nTangents = object.geometry.attributes.tangent.count;
    const positions = new Float32BufferAttribute(nTangents * 2 * 3, 3);
    geometry.setAttribute("position", positions);
    super(geometry, new LineBasicMaterial({ color, toneMapped: false }));
    this.object = object;
    this.size = size2;
    this.type = "VertexTangentsHelper";
    this.matrixAutoUpdate = false;
    this.update();
  }
  /**
   * Updates the vertex normals preview based on the object's world transform.
   */
  update() {
    this.object.updateMatrixWorld(true);
    const matrixWorld = this.object.matrixWorld;
    const position2 = this.geometry.attributes.position;
    const objGeometry = this.object.geometry;
    const objPos = objGeometry.attributes.position;
    const objTan = objGeometry.attributes.tangent;
    let idx = 0;
    for (let j2 = 0, jl = objPos.count; j2 < jl; j2++) {
      _v14.fromBufferAttribute(objPos, j2).applyMatrix4(matrixWorld);
      _v24.fromBufferAttribute(objTan, j2);
      _v24.transformDirection(matrixWorld).multiplyScalar(this.size).add(_v14);
      position2.setXYZ(idx, _v14.x, _v14.y, _v14.z);
      idx = idx + 1;
      position2.setXYZ(idx, _v24.x, _v24.y, _v24.z);
      idx = idx + 1;
    }
    position2.needsUpdate = true;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this.geometry.dispose();
    this.material.dispose();
  }
};

// node_modules/three/examples/jsm/helpers/ViewHelper.js
var ViewHelper = class extends Object3D {
  /**
   * Constructs a new view helper.
   *
   * @param {Camera} camera - The camera whose transformation should be visualized.
   * @param {HTMLDOMElement} [domElement] - The DOM element that is used to render the view.
   */
  constructor(camera, domElement) {
    super();
    this.isViewHelper = true;
    this.animating = false;
    this.center = new Vector3();
    const color1 = new Color("#ff4466");
    const color2 = new Color("#88ff44");
    const color3 = new Color("#4488ff");
    const color4 = new Color("#000000");
    const options = {};
    const interactiveObjects = [];
    const raycaster = new Raycaster();
    const mouse = new Vector2();
    const dummy = new Object3D();
    const orthoCamera = new OrthographicCamera(-2, 2, 2, -2, 0, 4);
    orthoCamera.position.set(0, 0, 2);
    const geometry = new CylinderGeometry(0.04, 0.04, 0.8, 5).rotateZ(-Math.PI / 2).translate(0.4, 0, 0);
    const xAxis2 = new Mesh(geometry, getAxisMaterial(color1));
    const yAxis2 = new Mesh(geometry, getAxisMaterial(color2));
    const zAxis2 = new Mesh(geometry, getAxisMaterial(color3));
    yAxis2.rotation.z = Math.PI / 2;
    zAxis2.rotation.y = -Math.PI / 2;
    this.add(xAxis2);
    this.add(zAxis2);
    this.add(yAxis2);
    const spriteMaterial1 = getSpriteMaterial(color1);
    const spriteMaterial2 = getSpriteMaterial(color2);
    const spriteMaterial3 = getSpriteMaterial(color3);
    const spriteMaterial4 = getSpriteMaterial(color4);
    const posXAxisHelper = new Sprite(spriteMaterial1);
    const posYAxisHelper = new Sprite(spriteMaterial2);
    const posZAxisHelper = new Sprite(spriteMaterial3);
    const negXAxisHelper = new Sprite(spriteMaterial4);
    const negYAxisHelper = new Sprite(spriteMaterial4);
    const negZAxisHelper = new Sprite(spriteMaterial4);
    posXAxisHelper.position.x = 1;
    posYAxisHelper.position.y = 1;
    posZAxisHelper.position.z = 1;
    negXAxisHelper.position.x = -1;
    negYAxisHelper.position.y = -1;
    negZAxisHelper.position.z = -1;
    negXAxisHelper.material.opacity = 0.2;
    negYAxisHelper.material.opacity = 0.2;
    negZAxisHelper.material.opacity = 0.2;
    posXAxisHelper.userData.type = "posX";
    posYAxisHelper.userData.type = "posY";
    posZAxisHelper.userData.type = "posZ";
    negXAxisHelper.userData.type = "negX";
    negYAxisHelper.userData.type = "negY";
    negZAxisHelper.userData.type = "negZ";
    this.add(posXAxisHelper);
    this.add(posYAxisHelper);
    this.add(posZAxisHelper);
    this.add(negXAxisHelper);
    this.add(negYAxisHelper);
    this.add(negZAxisHelper);
    interactiveObjects.push(posXAxisHelper);
    interactiveObjects.push(posYAxisHelper);
    interactiveObjects.push(posZAxisHelper);
    interactiveObjects.push(negXAxisHelper);
    interactiveObjects.push(negYAxisHelper);
    interactiveObjects.push(negZAxisHelper);
    const point = new Vector3();
    const dim = 128;
    const turnRate = 2 * Math.PI;
    this.render = function(renderer2) {
      this.quaternion.copy(camera.quaternion).invert();
      this.updateMatrixWorld();
      point.set(0, 0, 1);
      point.applyQuaternion(camera.quaternion);
      const x2 = domElement.offsetWidth - dim;
      const y = renderer2.isWebGPURenderer ? domElement.offsetHeight - dim : 0;
      renderer2.clearDepth();
      renderer2.getViewport(viewport);
      renderer2.setViewport(x2, y, dim, dim);
      renderer2.render(this, orthoCamera);
      renderer2.setViewport(viewport.x, viewport.y, viewport.z, viewport.w);
    };
    const targetPosition = new Vector3();
    const targetQuaternion = new Quaternion();
    const q1 = new Quaternion();
    const q2 = new Quaternion();
    const viewport = new Vector4();
    let radius = 0;
    this.handleClick = function(event) {
      if (this.animating === true) return false;
      const rect = domElement.getBoundingClientRect();
      const offsetX = rect.left + (domElement.offsetWidth - dim);
      const offsetY = rect.top + (domElement.offsetHeight - dim);
      mouse.x = (event.clientX - offsetX) / (rect.right - offsetX) * 2 - 1;
      mouse.y = -((event.clientY - offsetY) / (rect.bottom - offsetY)) * 2 + 1;
      raycaster.setFromCamera(mouse, orthoCamera);
      const intersects = raycaster.intersectObjects(interactiveObjects);
      if (intersects.length > 0) {
        const intersection = intersects[0];
        const object = intersection.object;
        prepareAnimationData(object, this.center);
        this.animating = true;
        return true;
      } else {
        return false;
      }
    };
    this.setLabels = function(labelX, labelY, labelZ) {
      options.labelX = labelX;
      options.labelY = labelY;
      options.labelZ = labelZ;
      updateLabels();
    };
    this.setLabelStyle = function(font, color, radius2) {
      options.font = font;
      options.color = color;
      options.radius = radius2;
      updateLabels();
    };
    this.update = function(delta) {
      const step = delta * turnRate;
      q1.rotateTowards(q2, step);
      camera.position.set(0, 0, 1).applyQuaternion(q1).multiplyScalar(radius).add(this.center);
      camera.quaternion.rotateTowards(targetQuaternion, step);
      if (q1.angleTo(q2) === 0) {
        this.animating = false;
      }
    };
    this.dispose = function() {
      geometry.dispose();
      xAxis2.material.dispose();
      yAxis2.material.dispose();
      zAxis2.material.dispose();
      posXAxisHelper.material.map.dispose();
      posYAxisHelper.material.map.dispose();
      posZAxisHelper.material.map.dispose();
      negXAxisHelper.material.map.dispose();
      negYAxisHelper.material.map.dispose();
      negZAxisHelper.material.map.dispose();
      posXAxisHelper.material.dispose();
      posYAxisHelper.material.dispose();
      posZAxisHelper.material.dispose();
      negXAxisHelper.material.dispose();
      negYAxisHelper.material.dispose();
      negZAxisHelper.material.dispose();
    };
    function prepareAnimationData(object, focusPoint) {
      switch (object.userData.type) {
        case "posX":
          targetPosition.set(1, 0, 0);
          targetQuaternion.setFromEuler(new Euler(0, Math.PI * 0.5, 0));
          break;
        case "posY":
          targetPosition.set(0, 1, 0);
          targetQuaternion.setFromEuler(new Euler(-Math.PI * 0.5, 0, 0));
          break;
        case "posZ":
          targetPosition.set(0, 0, 1);
          targetQuaternion.setFromEuler(new Euler());
          break;
        case "negX":
          targetPosition.set(-1, 0, 0);
          targetQuaternion.setFromEuler(new Euler(0, -Math.PI * 0.5, 0));
          break;
        case "negY":
          targetPosition.set(0, -1, 0);
          targetQuaternion.setFromEuler(new Euler(Math.PI * 0.5, 0, 0));
          break;
        case "negZ":
          targetPosition.set(0, 0, -1);
          targetQuaternion.setFromEuler(new Euler(0, Math.PI, 0));
          break;
        default:
          console.error("ViewHelper: Invalid axis.");
      }
      radius = camera.position.distanceTo(focusPoint);
      targetPosition.multiplyScalar(radius).add(focusPoint);
      dummy.position.copy(focusPoint);
      dummy.lookAt(camera.position);
      q1.copy(dummy.quaternion);
      dummy.lookAt(targetPosition);
      q2.copy(dummy.quaternion);
    }
    function getAxisMaterial(color) {
      return new MeshBasicMaterial({ color, toneMapped: false });
    }
    function getSpriteMaterial(color, text2) {
      const { font = "24px Arial", color: labelColor = "#000000", radius: radius2 = 14 } = options;
      const canvas = document.createElement("canvas");
      canvas.width = 64;
      canvas.height = 64;
      const context = canvas.getContext("2d");
      context.beginPath();
      context.arc(32, 32, radius2, 0, 2 * Math.PI);
      context.closePath();
      context.fillStyle = color.getStyle();
      context.fill();
      if (text2) {
        context.font = font;
        context.textAlign = "center";
        context.fillStyle = labelColor;
        context.fillText(text2, 32, 41);
      }
      const texture = new CanvasTexture(canvas);
      texture.colorSpace = SRGBColorSpace;
      return new SpriteMaterial({ map: texture, toneMapped: false });
    }
    function updateLabels() {
      posXAxisHelper.material.map.dispose();
      posYAxisHelper.material.map.dispose();
      posZAxisHelper.material.map.dispose();
      posXAxisHelper.material.dispose();
      posYAxisHelper.material.dispose();
      posZAxisHelper.material.dispose();
      posXAxisHelper.material = getSpriteMaterial(color1, options.labelX);
      posYAxisHelper.material = getSpriteMaterial(color2, options.labelY);
      posZAxisHelper.material = getSpriteMaterial(color3, options.labelZ);
    }
  }
};

// node_modules/three/examples/jsm/interactive/HTMLMesh.js
var HTMLMesh = class extends Mesh {
  /**
   * Constructs a new HTML mesh.
   *
   * @param {HTMLElement} dom - The DOM element to display as a plane mesh.
   */
  constructor(dom) {
    const texture = new HTMLTexture(dom);
    const geometry = new PlaneGeometry(texture.image.width * 1e-3, texture.image.height * 1e-3);
    const material = new MeshBasicMaterial({ map: texture, toneMapped: false, transparent: true });
    super(geometry, material);
    function onEvent(event) {
      material.map.dispatchDOMEvent(event);
    }
    this.addEventListener("mousedown", onEvent);
    this.addEventListener("mousemove", onEvent);
    this.addEventListener("mouseup", onEvent);
    this.addEventListener("click", onEvent);
    this.dispose = function() {
      geometry.dispose();
      material.dispose();
      material.map.dispose();
      canvases.delete(dom);
      this.removeEventListener("mousedown", onEvent);
      this.removeEventListener("mousemove", onEvent);
      this.removeEventListener("mouseup", onEvent);
      this.removeEventListener("click", onEvent);
    };
  }
};
var HTMLTexture = class extends CanvasTexture {
  constructor(dom) {
    super(html2canvas(dom));
    this.dom = dom;
    this.anisotropy = 16;
    this.colorSpace = SRGBColorSpace;
    this.minFilter = LinearFilter;
    this.magFilter = LinearFilter;
    this.generateMipmaps = false;
    const observer = new MutationObserver(() => {
      if (!this.scheduleUpdate) {
        this.scheduleUpdate = setTimeout(() => this.update(), 16);
      }
    });
    const config = { attributes: true, childList: true, subtree: true, characterData: true };
    observer.observe(dom, config);
    this.observer = observer;
  }
  dispatchDOMEvent(event) {
    if (event.data) {
      htmlevent(this.dom, event.type, event.data.x, event.data.y);
    }
  }
  update() {
    this.image = html2canvas(this.dom);
    this.needsUpdate = true;
    this.scheduleUpdate = null;
  }
  dispose() {
    if (this.observer) {
      this.observer.disconnect();
    }
    this.scheduleUpdate = clearTimeout(this.scheduleUpdate);
    super.dispose();
  }
};
var canvases = /* @__PURE__ */ new WeakMap();
function html2canvas(element) {
  const range = document.createRange();
  const color = new Color();
  function Clipper(context2) {
    const clips = [];
    let isClipping = false;
    function doClip() {
      if (isClipping) {
        isClipping = false;
        context2.restore();
      }
      if (clips.length === 0) return;
      let minX = -Infinity, minY = -Infinity;
      let maxX = Infinity, maxY = Infinity;
      for (let i = 0; i < clips.length; i++) {
        const clip = clips[i];
        minX = Math.max(minX, clip.x);
        minY = Math.max(minY, clip.y);
        maxX = Math.min(maxX, clip.x + clip.width);
        maxY = Math.min(maxY, clip.y + clip.height);
      }
      context2.save();
      context2.beginPath();
      context2.rect(minX, minY, maxX - minX, maxY - minY);
      context2.clip();
      isClipping = true;
    }
    return {
      add: function(clip) {
        clips.push(clip);
        doClip();
      },
      remove: function() {
        clips.pop();
        doClip();
      }
    };
  }
  function drawText(style, x2, y, string) {
    if (string !== "") {
      if (style.textTransform === "uppercase") {
        string = string.toUpperCase();
      }
      context.font = style.fontWeight + " " + style.fontSize + " " + style.fontFamily;
      context.textBaseline = "top";
      context.fillStyle = style.color;
      context.fillText(string, x2, y + parseFloat(style.fontSize) * 0.1);
    }
  }
  function buildRectPath(x2, y, w, h, r) {
    if (w < 2 * r) r = w / 2;
    if (h < 2 * r) r = h / 2;
    context.beginPath();
    context.moveTo(x2 + r, y);
    context.arcTo(x2 + w, y, x2 + w, y + h, r);
    context.arcTo(x2 + w, y + h, x2, y + h, r);
    context.arcTo(x2, y + h, x2, y, r);
    context.arcTo(x2, y, x2 + w, y, r);
    context.closePath();
  }
  function drawBorder(style, which, x2, y, width2, height2) {
    const borderWidth = style[which + "Width"];
    const borderStyle = style[which + "Style"];
    const borderColor = style[which + "Color"];
    if (borderWidth !== "0px" && borderStyle !== "none" && borderColor !== "transparent" && borderColor !== "rgba(0, 0, 0, 0)") {
      context.strokeStyle = borderColor;
      context.lineWidth = parseFloat(borderWidth);
      context.beginPath();
      context.moveTo(x2, y);
      context.lineTo(x2 + width2, y + height2);
      context.stroke();
    }
  }
  function drawElement(element2, style) {
    if (element2.nodeType === Node.COMMENT_NODE || element2.nodeName === "SCRIPT" || element2.style && element2.style.display === "none") {
      return;
    }
    let x2 = 0, y = 0, width2 = 0, height2 = 0;
    if (element2.nodeType === Node.TEXT_NODE) {
      range.selectNode(element2);
      const rect = range.getBoundingClientRect();
      x2 = rect.left - offset.left - 0.5;
      y = rect.top - offset.top - 0.5;
      width2 = rect.width;
      height2 = rect.height;
      drawText(style, x2, y, element2.nodeValue.trim());
    } else if (element2 instanceof HTMLCanvasElement) {
      const rect = element2.getBoundingClientRect();
      x2 = rect.left - offset.left - 0.5;
      y = rect.top - offset.top - 0.5;
      context.save();
      const dpr = window.devicePixelRatio;
      context.scale(1 / dpr, 1 / dpr);
      context.drawImage(element2, x2, y);
      context.restore();
    } else if (element2 instanceof HTMLImageElement) {
      const rect = element2.getBoundingClientRect();
      x2 = rect.left - offset.left - 0.5;
      y = rect.top - offset.top - 0.5;
      width2 = rect.width;
      height2 = rect.height;
      context.drawImage(element2, x2, y, width2, height2);
    } else {
      const rect = element2.getBoundingClientRect();
      x2 = rect.left - offset.left - 0.5;
      y = rect.top - offset.top - 0.5;
      width2 = rect.width;
      height2 = rect.height;
      style = window.getComputedStyle(element2);
      buildRectPath(x2, y, width2, height2, parseFloat(style.borderRadius));
      const backgroundColor = style.backgroundColor;
      if (backgroundColor !== "transparent" && backgroundColor !== "rgba(0, 0, 0, 0)") {
        context.fillStyle = backgroundColor;
        context.fill();
      }
      const borders = ["borderTop", "borderLeft", "borderBottom", "borderRight"];
      let match = true;
      let prevBorder = null;
      for (const border of borders) {
        if (prevBorder !== null) {
          match = style[border + "Width"] === style[prevBorder + "Width"] && style[border + "Color"] === style[prevBorder + "Color"] && style[border + "Style"] === style[prevBorder + "Style"];
        }
        if (match === false) break;
        prevBorder = border;
      }
      if (match === true) {
        const width3 = parseFloat(style.borderTopWidth);
        if (style.borderTopWidth !== "0px" && style.borderTopStyle !== "none" && style.borderTopColor !== "transparent" && style.borderTopColor !== "rgba(0, 0, 0, 0)") {
          context.strokeStyle = style.borderTopColor;
          context.lineWidth = width3;
          context.stroke();
        }
      } else {
        drawBorder(style, "borderTop", x2, y, width2, 0);
        drawBorder(style, "borderLeft", x2, y, 0, height2);
        drawBorder(style, "borderBottom", x2, y + height2, width2, 0);
        drawBorder(style, "borderRight", x2 + width2, y, 0, height2);
      }
      if (element2 instanceof HTMLInputElement) {
        let accentColor = style.accentColor;
        if (accentColor === void 0 || accentColor === "auto") accentColor = style.color;
        color.set(accentColor);
        const luminance = Math.sqrt(0.299 * color.r ** 2 + 0.587 * color.g ** 2 + 0.114 * color.b ** 2);
        const accentTextColor = luminance < 0.5 ? "white" : "#111111";
        if (element2.type === "radio") {
          buildRectPath(x2, y, width2, height2, height2);
          context.fillStyle = "white";
          context.strokeStyle = accentColor;
          context.lineWidth = 1;
          context.fill();
          context.stroke();
          if (element2.checked) {
            buildRectPath(x2 + 2, y + 2, width2 - 4, height2 - 4, height2);
            context.fillStyle = accentColor;
            context.strokeStyle = accentTextColor;
            context.lineWidth = 2;
            context.fill();
            context.stroke();
          }
        }
        if (element2.type === "checkbox") {
          buildRectPath(x2, y, width2, height2, 2);
          context.fillStyle = element2.checked ? accentColor : "white";
          context.strokeStyle = element2.checked ? accentTextColor : accentColor;
          context.lineWidth = 1;
          context.stroke();
          context.fill();
          if (element2.checked) {
            const currentTextAlign = context.textAlign;
            context.textAlign = "center";
            const properties = {
              color: accentTextColor,
              fontFamily: style.fontFamily,
              fontSize: height2 + "px",
              fontWeight: "bold"
            };
            drawText(properties, x2 + width2 / 2, y, "✔");
            context.textAlign = currentTextAlign;
          }
        }
        if (element2.type === "range") {
          const [min, max2, value2] = ["min", "max", "value"].map((property2) => parseFloat(element2[property2]));
          const position2 = (value2 - min) / (max2 - min) * (width2 - height2);
          buildRectPath(x2, y + height2 / 4, width2, height2 / 2, height2 / 4);
          context.fillStyle = accentTextColor;
          context.strokeStyle = accentColor;
          context.lineWidth = 1;
          context.fill();
          context.stroke();
          buildRectPath(x2, y + height2 / 4, position2 + height2 / 2, height2 / 2, height2 / 4);
          context.fillStyle = accentColor;
          context.fill();
          buildRectPath(x2 + position2, y, height2, height2, height2 / 2);
          context.fillStyle = accentColor;
          context.fill();
        }
        if (element2.type === "color" || element2.type === "text" || element2.type === "number") {
          clipper.add({ x: x2, y, width: width2, height: height2 });
          drawText(style, x2 + parseInt(style.paddingLeft), y + parseInt(style.paddingTop), element2.value);
          clipper.remove();
        }
      }
    }
    const isClipping = style.overflow === "auto" || style.overflow === "hidden";
    if (isClipping) clipper.add({ x: x2, y, width: width2, height: height2 });
    for (let i = 0; i < element2.childNodes.length; i++) {
      drawElement(element2.childNodes[i], style);
    }
    if (isClipping) clipper.remove();
  }
  const offset = element.getBoundingClientRect();
  let canvas = canvases.get(element);
  if (canvas === void 0) {
    canvas = document.createElement("canvas");
    canvas.width = offset.width;
    canvas.height = offset.height;
    canvases.set(element, canvas);
  }
  const context = canvas.getContext(
    "2d"
    /*, { alpha: false }*/
  );
  const clipper = new Clipper(context);
  context.clearRect(0, 0, canvas.width, canvas.height);
  drawElement(element);
  return canvas;
}
function htmlevent(element, event, x2, y) {
  const mouseEventInit = {
    clientX: x2 * element.offsetWidth + element.offsetLeft,
    clientY: y * element.offsetHeight + element.offsetTop,
    view: element.ownerDocument.defaultView
  };
  window.dispatchEvent(new MouseEvent(event, mouseEventInit));
  const rect = element.getBoundingClientRect();
  x2 = x2 * rect.width + rect.left;
  y = y * rect.height + rect.top;
  function traverse(element2) {
    if (element2.nodeType !== Node.TEXT_NODE && element2.nodeType !== Node.COMMENT_NODE) {
      const rect2 = element2.getBoundingClientRect();
      if (x2 > rect2.left && x2 < rect2.right && y > rect2.top && y < rect2.bottom) {
        element2.dispatchEvent(new MouseEvent(event, mouseEventInit));
        if (element2 instanceof HTMLInputElement && element2.type === "range" && (event === "mousedown" || event === "click")) {
          const [min, max2] = ["min", "max"].map((property2) => parseFloat(element2[property2]));
          const width2 = rect2.width;
          const offsetX = x2 - rect2.x;
          const proportion = offsetX / width2;
          element2.value = min + (max2 - min) * proportion;
          element2.dispatchEvent(new InputEvent("input", { bubbles: true }));
        }
        if (element2 instanceof HTMLInputElement && (element2.type === "text" || element2.type === "number") && (event === "mousedown" || event === "click")) {
          element2.focus();
        }
      }
      for (let i = 0; i < element2.childNodes.length; i++) {
        traverse(element2.childNodes[i]);
      }
    }
  }
  traverse(element);
}

// node_modules/three/examples/jsm/interactive/InteractiveGroup.js
var _pointer2 = new Vector2();
var _event = { type: "", data: _pointer2 };
var _events = {
  "move": "mousemove",
  "select": "click",
  "selectstart": "mousedown",
  "selectend": "mouseup"
};
var _raycaster3 = new Raycaster();
var InteractiveGroup = class extends Group {
  constructor() {
    super();
    this.raycaster = new Raycaster();
    this.element = null;
    this.camera = null;
    this.controllers = [];
    this._onPointerEvent = this.onPointerEvent.bind(this);
    this._onXRControllerEvent = this.onXRControllerEvent.bind(this);
  }
  onPointerEvent(event) {
    event.stopPropagation();
    const rect = this.element.getBoundingClientRect();
    _pointer2.x = (event.clientX - rect.left) / rect.width * 2 - 1;
    _pointer2.y = -(event.clientY - rect.top) / rect.height * 2 + 1;
    this.raycaster.setFromCamera(_pointer2, this.camera);
    const intersects = this.raycaster.intersectObjects(this.children, false);
    if (intersects.length > 0) {
      const intersection = intersects[0];
      const object = intersection.object;
      const uv = intersection.uv;
      _event.type = event.type;
      _event.data.set(uv.x, 1 - uv.y);
      object.dispatchEvent(_event);
    }
  }
  onXRControllerEvent(event) {
    const controller = event.target;
    _raycaster3.setFromXRController(controller);
    const intersections = _raycaster3.intersectObjects(this.children, false);
    if (intersections.length > 0) {
      const intersection = intersections[0];
      const object = intersection.object;
      const uv = intersection.uv;
      _event.type = _events[event.type];
      _event.data.set(uv.x, 1 - uv.y);
      object.dispatchEvent(_event);
    }
  }
  /**
   * Calling this method makes sure the interactive group listens to Pointer and Mouse events.
   * The target is the `domElement` of the given renderer. The camera is required for the internal
   * raycasting so 3D objects can be detected based on the events.
   *
   * @param {(WebGPURenderer|WebGLRenderer)} renderer - The renderer.
   * @param {Camera} camera - The camera.
   */
  listenToPointerEvents(renderer2, camera) {
    this.camera = camera;
    this.element = renderer2.domElement;
    this.element.addEventListener("pointerdown", this._onPointerEvent);
    this.element.addEventListener("pointerup", this._onPointerEvent);
    this.element.addEventListener("pointermove", this._onPointerEvent);
    this.element.addEventListener("mousedown", this._onPointerEvent);
    this.element.addEventListener("mouseup", this._onPointerEvent);
    this.element.addEventListener("mousemove", this._onPointerEvent);
    this.element.addEventListener("click", this._onPointerEvent);
  }
  /**
   * Disconnects this interactive group from all Pointer and Mouse Events.
   */
  disconnectionPointerEvents() {
    if (this.element !== null) {
      this.element.removeEventListener("pointerdown", this._onPointerEvent);
      this.element.removeEventListener("pointerup", this._onPointerEvent);
      this.element.removeEventListener("pointermove", this._onPointerEvent);
      this.element.removeEventListener("mousedown", this._onPointerEvent);
      this.element.removeEventListener("mouseup", this._onPointerEvent);
      this.element.removeEventListener("mousemove", this._onPointerEvent);
      this.element.removeEventListener("click", this._onPointerEvent);
    }
  }
  /**
   * Calling this method makes sure the interactive group listens to events of
   * the given XR controller.
   *
   * @param {Group} controller - The XR controller.
   */
  listenToXRControllerEvents(controller) {
    this.controllers.push(controller);
    controller.addEventListener("move", this._onXRControllerEvent);
    controller.addEventListener("select", this._onXRControllerEvent);
    controller.addEventListener("selectstart", this._onXRControllerEvent);
    controller.addEventListener("selectend", this._onXRControllerEvent);
  }
  /**
   * Disconnects this interactive group from all XR controllers.
   */
  disconnectXrControllerEvents() {
    for (const controller of this.controllers) {
      controller.removeEventListener("move", this._onXRControllerEvent);
      controller.removeEventListener("select", this._onXRControllerEvent);
      controller.removeEventListener("selectstart", this._onXRControllerEvent);
      controller.removeEventListener("selectend", this._onXRControllerEvent);
    }
  }
  /**
   * Disconnects this interactive group from the DOM and all XR controllers.
   */
  disconnect() {
    this.disconnectionPointerEvents();
    this.disconnectXrControllerEvents();
    this.camera = null;
    this.element = null;
    this.controllers = [];
  }
};

// node_modules/three/examples/jsm/interactive/SelectionBox.js
var _frustum = new Frustum();
var _center3 = new Vector3();
var _tmpPoint = new Vector3();
var _vecNear = new Vector3();
var _vecTopLeft = new Vector3();
var _vecTopRight = new Vector3();
var _vecDownRight = new Vector3();
var _vecDownLeft = new Vector3();
var _vecFarTopLeft = new Vector3();
var _vecFarTopRight = new Vector3();
var _vecFarDownRight = new Vector3();
var _vecFarDownLeft = new Vector3();
var _vectemp1 = new Vector3();
var _vectemp2 = new Vector3();
var _vectemp3 = new Vector3();
var _matrix2 = new Matrix4();
var _quaternion3 = new Quaternion();
var _scale = new Vector3();
var SelectionBox = class {
  /**
   * Constructs a new selection box.
   *
   * @param {Camera} camera - The camera the scene is rendered with.
   * @param {Scene} scene - The scene.
   * @param {number} [deep=Number.MAX_VALUE] - How deep the selection frustum of perspective cameras should extend.
   */
  constructor(camera, scene, deep = Number.MAX_VALUE) {
    this.camera = camera;
    this.scene = scene;
    this.startPoint = new Vector3();
    this.endPoint = new Vector3();
    this.collection = [];
    this.instances = {};
    this.deep = deep;
  }
  /**
   * This method selects 3D objects in the scene based on the given start
   * and end point. If no parameters are provided, the method uses the start
   * and end values of the respective members.
   *
   * @param {Vector3} [startPoint] - The start point.
   * @param {Vector3} [endPoint] - The end point.
   * @return {Array<Object3D>} The selected 3D objects.
   */
  select(startPoint, endPoint) {
    this.startPoint = startPoint || this.startPoint;
    this.endPoint = endPoint || this.endPoint;
    this.collection = [];
    this._updateFrustum(this.startPoint, this.endPoint);
    this._searchChildInFrustum(_frustum, this.scene);
    return this.collection;
  }
  // private
  _updateFrustum(startPoint, endPoint) {
    startPoint = startPoint || this.startPoint;
    endPoint = endPoint || this.endPoint;
    if (startPoint.x === endPoint.x) {
      endPoint.x += Number.EPSILON;
    }
    if (startPoint.y === endPoint.y) {
      endPoint.y += Number.EPSILON;
    }
    this.camera.updateProjectionMatrix();
    this.camera.updateMatrixWorld();
    if (this.camera.isPerspectiveCamera) {
      _tmpPoint.copy(startPoint);
      _tmpPoint.x = Math.min(startPoint.x, endPoint.x);
      _tmpPoint.y = Math.max(startPoint.y, endPoint.y);
      endPoint.x = Math.max(startPoint.x, endPoint.x);
      endPoint.y = Math.min(startPoint.y, endPoint.y);
      _vecNear.setFromMatrixPosition(this.camera.matrixWorld);
      _vecTopLeft.copy(_tmpPoint);
      _vecTopRight.set(endPoint.x, _tmpPoint.y, 0);
      _vecDownRight.copy(endPoint);
      _vecDownLeft.set(_tmpPoint.x, endPoint.y, 0);
      _vecTopLeft.unproject(this.camera);
      _vecTopRight.unproject(this.camera);
      _vecDownRight.unproject(this.camera);
      _vecDownLeft.unproject(this.camera);
      _vectemp1.copy(_vecTopLeft).sub(_vecNear);
      _vectemp2.copy(_vecTopRight).sub(_vecNear);
      _vectemp3.copy(_vecDownRight).sub(_vecNear);
      _vectemp1.normalize();
      _vectemp2.normalize();
      _vectemp3.normalize();
      _vectemp1.multiplyScalar(this.deep);
      _vectemp2.multiplyScalar(this.deep);
      _vectemp3.multiplyScalar(this.deep);
      _vectemp1.add(_vecNear);
      _vectemp2.add(_vecNear);
      _vectemp3.add(_vecNear);
      const planes = _frustum.planes;
      planes[0].setFromCoplanarPoints(_vecNear, _vecTopLeft, _vecTopRight);
      planes[1].setFromCoplanarPoints(_vecNear, _vecTopRight, _vecDownRight);
      planes[2].setFromCoplanarPoints(_vecDownRight, _vecDownLeft, _vecNear);
      planes[3].setFromCoplanarPoints(_vecDownLeft, _vecTopLeft, _vecNear);
      planes[4].setFromCoplanarPoints(_vecTopRight, _vecDownRight, _vecDownLeft);
      planes[5].setFromCoplanarPoints(_vectemp3, _vectemp2, _vectemp1);
      planes[5].normal.multiplyScalar(-1);
    } else if (this.camera.isOrthographicCamera) {
      const left = Math.min(startPoint.x, endPoint.x);
      const top = Math.max(startPoint.y, endPoint.y);
      const right = Math.max(startPoint.x, endPoint.x);
      const down = Math.min(startPoint.y, endPoint.y);
      _vecTopLeft.set(left, top, -1);
      _vecTopRight.set(right, top, -1);
      _vecDownRight.set(right, down, -1);
      _vecDownLeft.set(left, down, -1);
      _vecFarTopLeft.set(left, top, 1);
      _vecFarTopRight.set(right, top, 1);
      _vecFarDownRight.set(right, down, 1);
      _vecFarDownLeft.set(left, down, 1);
      _vecTopLeft.unproject(this.camera);
      _vecTopRight.unproject(this.camera);
      _vecDownRight.unproject(this.camera);
      _vecDownLeft.unproject(this.camera);
      _vecFarTopLeft.unproject(this.camera);
      _vecFarTopRight.unproject(this.camera);
      _vecFarDownRight.unproject(this.camera);
      _vecFarDownLeft.unproject(this.camera);
      const planes = _frustum.planes;
      planes[0].setFromCoplanarPoints(_vecTopLeft, _vecFarTopLeft, _vecFarTopRight);
      planes[1].setFromCoplanarPoints(_vecTopRight, _vecFarTopRight, _vecFarDownRight);
      planes[2].setFromCoplanarPoints(_vecFarDownRight, _vecFarDownLeft, _vecDownLeft);
      planes[3].setFromCoplanarPoints(_vecFarDownLeft, _vecFarTopLeft, _vecTopLeft);
      planes[4].setFromCoplanarPoints(_vecTopRight, _vecDownRight, _vecDownLeft);
      planes[5].setFromCoplanarPoints(_vecFarDownRight, _vecFarTopRight, _vecFarTopLeft);
      planes[5].normal.multiplyScalar(-1);
    } else {
      console.error("THREE.SelectionBox: Unsupported camera type.");
    }
  }
  _searchChildInFrustum(frustum, object) {
    if (object.isMesh || object.isLine || object.isPoints) {
      if (object.isInstancedMesh) {
        this.instances[object.uuid] = [];
        for (let instanceId = 0; instanceId < object.count; instanceId++) {
          object.getMatrixAt(instanceId, _matrix2);
          _matrix2.decompose(_center3, _quaternion3, _scale);
          _center3.applyMatrix4(object.matrixWorld);
          if (frustum.containsPoint(_center3)) {
            this.instances[object.uuid].push(instanceId);
          }
        }
      } else {
        if (object.geometry.boundingSphere === null) object.geometry.computeBoundingSphere();
        _center3.copy(object.geometry.boundingSphere.center);
        _center3.applyMatrix4(object.matrixWorld);
        if (frustum.containsPoint(_center3)) {
          this.collection.push(object);
        }
      }
    }
    if (object.children.length > 0) {
      for (let x2 = 0; x2 < object.children.length; x2++) {
        this._searchChildInFrustum(frustum, object.children[x2]);
      }
    }
  }
};

// node_modules/three/examples/jsm/interactive/SelectionHelper.js
var SelectionHelper = class {
  /**
   * Constructs a new selection helper.
   *
   * @param {(WebGPURenderer|WebGLRenderer)} renderer - The renderer.
   * @param {string} cssClassName - The CSS class name of the `div`.
   */
  constructor(renderer2, cssClassName) {
    this.element = document.createElement("div");
    this.element.classList.add(cssClassName);
    this.element.style.pointerEvents = "none";
    this.renderer = renderer2;
    this.isDown = false;
    this.enabled = true;
    this._startPoint = new Vector2();
    this._pointTopLeft = new Vector2();
    this._pointBottomRight = new Vector2();
    this._onPointerDown = (function(event) {
      if (this.enabled === false) return;
      this.isDown = true;
      this._onSelectStart(event);
    }).bind(this);
    this._onPointerMove = (function(event) {
      if (this.enabled === false) return;
      if (this.isDown) {
        this._onSelectMove(event);
      }
    }).bind(this);
    this._onPointerUp = (function() {
      if (this.enabled === false) return;
      this.isDown = false;
      this._onSelectOver();
    }).bind(this);
    this.renderer.domElement.addEventListener("pointerdown", this._onPointerDown);
    this.renderer.domElement.addEventListener("pointermove", this._onPointerMove);
    this.renderer.domElement.addEventListener("pointerup", this._onPointerUp);
  }
  /**
   * Call this method if you no longer want use to the controls. It frees all internal
   * resources and removes all event listeners.
   */
  dispose() {
    this.renderer.domElement.removeEventListener("pointerdown", this._onPointerDown);
    this.renderer.domElement.removeEventListener("pointermove", this._onPointerMove);
    this.renderer.domElement.removeEventListener("pointerup", this._onPointerUp);
    this.element.remove();
  }
  // private
  _onSelectStart(event) {
    this.element.style.display = "none";
    this.renderer.domElement.parentElement.appendChild(this.element);
    this.element.style.left = event.clientX + "px";
    this.element.style.top = event.clientY + "px";
    this.element.style.width = "0px";
    this.element.style.height = "0px";
    this._startPoint.x = event.clientX;
    this._startPoint.y = event.clientY;
  }
  _onSelectMove(event) {
    this.element.style.display = "block";
    this._pointBottomRight.x = Math.max(this._startPoint.x, event.clientX);
    this._pointBottomRight.y = Math.max(this._startPoint.y, event.clientY);
    this._pointTopLeft.x = Math.min(this._startPoint.x, event.clientX);
    this._pointTopLeft.y = Math.min(this._startPoint.y, event.clientY);
    this.element.style.left = this._pointTopLeft.x + "px";
    this.element.style.top = this._pointTopLeft.y + "px";
    this.element.style.width = this._pointBottomRight.x - this._pointTopLeft.x + "px";
    this.element.style.height = this._pointBottomRight.y - this._pointTopLeft.y + "px";
  }
  _onSelectOver() {
    this.element.remove();
  }
};

// node_modules/three/examples/jsm/lights/LightProbeGenerator.js
var LightProbeGenerator = class {
  /**
   * Creates a light probe from the given (radiance) environment map.
   * The method expects that the environment map is represented as a cube texture.
   *
   * @param {CubeTexture} cubeTexture - The environment map.
   * @return {LightProbe} The created light probe.
   */
  static fromCubeTexture(cubeTexture) {
    let totalWeight = 0;
    const coord = new Vector3();
    const dir = new Vector3();
    const color = new Color();
    const shBasis = [0, 0, 0, 0, 0, 0, 0, 0, 0];
    const sh = new SphericalHarmonics3();
    const shCoefficients = sh.coefficients;
    for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
      const image = cubeTexture.image[faceIndex];
      const width2 = image.width;
      const height2 = image.height;
      const canvas = document.createElement("canvas");
      canvas.width = width2;
      canvas.height = height2;
      const context = canvas.getContext("2d");
      context.drawImage(image, 0, 0, width2, height2);
      const imageData = context.getImageData(0, 0, width2, height2);
      const data2 = imageData.data;
      const imageWidth = imageData.width;
      const pixelSize = 2 / imageWidth;
      for (let i = 0, il = data2.length; i < il; i += 4) {
        color.setRGB(data2[i] / 255, data2[i + 1] / 255, data2[i + 2] / 255);
        convertColorToLinear(color, cubeTexture.colorSpace);
        const pixelIndex = i / 4;
        const col = -1 + (pixelIndex % imageWidth + 0.5) * pixelSize;
        const row = 1 - (Math.floor(pixelIndex / imageWidth) + 0.5) * pixelSize;
        switch (faceIndex) {
          case 0:
            coord.set(-1, row, -col);
            break;
          case 1:
            coord.set(1, row, col);
            break;
          case 2:
            coord.set(-col, 1, -row);
            break;
          case 3:
            coord.set(-col, -1, row);
            break;
          case 4:
            coord.set(-col, row, 1);
            break;
          case 5:
            coord.set(col, row, -1);
            break;
        }
        const lengthSq = coord.lengthSq();
        const weight = 4 / (Math.sqrt(lengthSq) * lengthSq);
        totalWeight += weight;
        dir.copy(coord).normalize();
        SphericalHarmonics3.getBasisAt(dir, shBasis);
        for (let j2 = 0; j2 < 9; j2++) {
          shCoefficients[j2].x += shBasis[j2] * color.r * weight;
          shCoefficients[j2].y += shBasis[j2] * color.g * weight;
          shCoefficients[j2].z += shBasis[j2] * color.b * weight;
        }
      }
    }
    const norm = 4 * Math.PI / totalWeight;
    for (let j2 = 0; j2 < 9; j2++) {
      shCoefficients[j2].x *= norm;
      shCoefficients[j2].y *= norm;
      shCoefficients[j2].z *= norm;
    }
    return new LightProbe(sh);
  }
  /**
   * Creates a light probe from the given (radiance) environment map.
   * The method expects that the environment map is represented as a cube render target.
   *
   * The cube render target must be in RGBA so `cubeRenderTarget.texture.format` must be
   * set to {@link RGBAFormat}.
   *
   * @async
   * @param {WebGPURenderer|WebGLRenderer} renderer - The renderer.
   * @param {CubeRenderTarget|WebGLCubeRenderTarget} cubeRenderTarget - The environment map.
   * @return {Promise<LightProbe>} A Promise that resolves with the created light probe.
   */
  static async fromCubeRenderTarget(renderer2, cubeRenderTarget) {
    const flip = renderer2.coordinateSystem === WebGLCoordinateSystem ? -1 : 1;
    let totalWeight = 0;
    const coord = new Vector3();
    const dir = new Vector3();
    const color = new Color();
    const shBasis = [0, 0, 0, 0, 0, 0, 0, 0, 0];
    const sh = new SphericalHarmonics3();
    const shCoefficients = sh.coefficients;
    const dataType = cubeRenderTarget.texture.type;
    const imageWidth = cubeRenderTarget.width;
    let data2;
    if (renderer2.isWebGLRenderer) {
      if (dataType === HalfFloatType) {
        data2 = new Uint16Array(imageWidth * imageWidth * 4);
      } else {
        data2 = new Uint8Array(imageWidth * imageWidth * 4);
      }
    }
    for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
      if (renderer2.isWebGLRenderer) {
        await renderer2.readRenderTargetPixelsAsync(cubeRenderTarget, 0, 0, imageWidth, imageWidth, data2, faceIndex);
      } else {
        data2 = await renderer2.readRenderTargetPixelsAsync(cubeRenderTarget, 0, 0, imageWidth, imageWidth, 0, faceIndex);
      }
      const pixelSize = 2 / imageWidth;
      for (let i = 0, il = data2.length; i < il; i += 4) {
        let r, g3, b3;
        if (dataType === HalfFloatType) {
          r = DataUtils.fromHalfFloat(data2[i]);
          g3 = DataUtils.fromHalfFloat(data2[i + 1]);
          b3 = DataUtils.fromHalfFloat(data2[i + 2]);
        } else {
          r = data2[i] / 255;
          g3 = data2[i + 1] / 255;
          b3 = data2[i + 2] / 255;
        }
        color.setRGB(r, g3, b3);
        convertColorToLinear(color, cubeRenderTarget.texture.colorSpace);
        const pixelIndex = i / 4;
        const col = (1 - (pixelIndex % imageWidth + 0.5) * pixelSize) * flip;
        const row = 1 - (Math.floor(pixelIndex / imageWidth) + 0.5) * pixelSize;
        switch (faceIndex) {
          case 0:
            coord.set(-1 * flip, row, col * flip);
            break;
          case 1:
            coord.set(1 * flip, row, -col * flip);
            break;
          case 2:
            coord.set(col, 1, -row);
            break;
          case 3:
            coord.set(col, -1, row);
            break;
          case 4:
            coord.set(col, row, 1);
            break;
          case 5:
            coord.set(-col, row, -1);
            break;
        }
        const lengthSq = coord.lengthSq();
        const weight = 4 / (Math.sqrt(lengthSq) * lengthSq);
        totalWeight += weight;
        dir.copy(coord).normalize();
        SphericalHarmonics3.getBasisAt(dir, shBasis);
        for (let j2 = 0; j2 < 9; j2++) {
          shCoefficients[j2].x += shBasis[j2] * color.r * weight;
          shCoefficients[j2].y += shBasis[j2] * color.g * weight;
          shCoefficients[j2].z += shBasis[j2] * color.b * weight;
        }
      }
    }
    const norm = 4 * Math.PI / totalWeight;
    for (let j2 = 0; j2 < 9; j2++) {
      shCoefficients[j2].x *= norm;
      shCoefficients[j2].y *= norm;
      shCoefficients[j2].z *= norm;
    }
    return new LightProbe(sh);
  }
};
function convertColorToLinear(color, colorSpace) {
  switch (colorSpace) {
    case SRGBColorSpace:
      color.convertSRGBToLinear();
      break;
    case LinearSRGBColorSpace:
    case NoColorSpace:
      break;
    default:
      console.warn("WARNING: LightProbeGenerator convertColorToLinear() encountered an unsupported color space.");
      break;
  }
  return color;
}

// node_modules/three/examples/jsm/lights/RectAreaLightTexturesLib.js
var RectAreaLightTexturesLib = class {
  /**
   * Inits the texture library.
   *
   * @return {RectAreaLightTexturesLib}
   */
  static init() {
    const LTC_MAT_1 = [1, 0, 0, 2e-5, 1, 0, 0, 503905e-9, 1, 0, 0, 201562e-8, 1, 0, 0, 453516e-8, 1, 0, 0, 806253e-8, 1, 0, 0, 0.0125978, 1, 0, 0, 0.018141, 1, 0, 0, 0.0246924, 1, 0, 0, 0.0322525, 1, 0, 0, 0.0408213, 1, 0, 0, 0.0503999, 1, 0, 0, 0.0609894, 1, 0, 0, 0.0725906, 1, 0, 0, 0.0852058, 1, 0, 0, 0.0988363, 1, 0, 0, 0.113484, 1, 0, 0, 0.129153, 1, 0, 0, 0.145839, 1, 0, 0, 0.163548, 1, 0, 0, 0.182266, 1, 0, 0, 0.201942, 1, 0, 0, 0.222314, 1, 0, 0, 0.241906, 1, 0, 0, 0.262314, 1, 0, 0, 0.285754, 1, 0, 0, 0.310159, 1, 0, 0, 0.335426, 1, 0, 0, 0.361341, 1, 0, 0, 0.387445, 1, 0, 0, 0.412784, 1, 0, 0, 0.438197, 1, 0, 0, 0.466966, 1, 0, 0, 0.49559, 1, 0, 0, 0.523448, 1, 0, 0, 0.549938, 1, 0, 0, 0.57979, 1, 0, 0, 0.608746, 1, 0, 0, 0.636185, 1, 0, 0, 0.664748, 1, 0, 0, 0.69313, 1, 0, 0, 0.71966, 1, 0, 0, 0.747662, 1, 0, 0, 0.774023, 1, 0, 0, 0.799775, 1, 0, 0, 0.825274, 1, 0, 0, 0.849156, 1, 0, 0, 0.873248, 1, 0, 0, 0.89532, 1, 0, 0, 0.917565, 1, 0, 0, 0.937863, 1, 0, 0, 0.958139, 1, 0, 0, 0.976563, 1, 0, 0, 0.994658, 1, 0, 0, 1.0112, 1, 0, 0, 1.02712, 1, 0, 0, 1.04189, 1, 0, 0, 1.05568, 1, 0, 0, 1.06877, 1, 0, 0, 1.08058, 1, 0, 0, 1.09194, 1, 0, 0, 1.10191, 1, 0, 0, 1.11161, 1, 0, 0, 1.1199, 1, 0, 0, 1.12813, 0.999547, -448815e-12, 0.0224417, 199902e-10, 0.999495, -113079e-10, 0.0224406, 503651e-9, 0.999496, -452317e-10, 0.0224406, 201461e-8, 0.999496, -101772e-9, 0.0224406, 453287e-8, 0.999495, -180928e-9, 0.0224406, 805845e-8, 0.999497, -282702e-9, 0.0224406, 0.0125914, 0.999496, -407096e-9, 0.0224406, 0.0181319, 0.999498, -554114e-9, 0.0224406, 0.02468, 0.999499, -723768e-9, 0.0224406, 0.0322363, 0.999495, -916058e-9, 0.0224405, 0.0408009, 0.999499, -113101e-8, 0.0224408, 0.050375, 0.999494, -136863e-8, 0.0224405, 0.0609586, 0.999489, -162896e-8, 0.0224401, 0.0725537, 0.999489, -191201e-8, 0.0224414, 0.0851619, 0.999498, -221787e-8, 0.0224413, 0.0987867, 0.999492, -254642e-8, 0.0224409, 0.113426, 0.999507, -289779e-8, 0.0224417, 0.129088, 0.999494, -32716e-7, 0.0224386, 0.145767, 0.999546, -36673e-7, 0.0224424, 0.163472, 0.999543, -408166e-8, 0.0224387, 0.182182, 0.999499, -450056e-8, 0.0224338, 0.201843, 0.999503, -483661e-8, 0.0224203, 0.222198, 0.999546, -452928e-8, 0.022315, 0.241714, 0.999508, -587403e-8, 0.0224329, 0.262184, 0.999509, -638806e-8, 0.0224271, 0.285609, 0.999501, -691028e-8, 0.0224166, 0.309998, 0.999539, -741979e-8, 0.0223989, 0.335262, 0.999454, -786282e-8, 0.0223675, 0.361154, 0.999529, -811928e-8, 0.0222828, 0.387224, 0.999503, -799941e-8, 0.0221063, 0.41252, 0.999561, -952753e-8, 0.0223057, 0.438006, 0.999557, -99134e-7, 0.0222065, 0.466735, 0.999541, -0.0100935, 0.0220402, 0.495332, 0.999562, -996821e-8, 0.0218067, 0.523197, 0.999556, -0.0105031, 0.0217096, 0.550223, 0.999561, -0.0114191, 0.0217215, 0.579498, 0.999588, -0.0111818, 0.0213357, 0.608416, 0.999633, -0.0107725, 0.0208689, 0.635965, 0.999527, -0.0121671, 0.0210149, 0.664476, 0.999508, -0.0116005, 0.020431, 0.692786, 0.999568, -0.0115604, 0.0199791, 0.719709, 0.999671, -0.0121117, 0.0197415, 0.74737, 0.999688, -0.0110769, 0.0188846, 0.773692, 0.99962, -0.0122368, 0.0188452, 0.799534, 0.999823, -0.0110325, 0.0178001, 0.825046, 0.999599, -0.0114923, 0.0174221, 0.849075, 0.999619, -0.0105923, 0.0164345, 0.872999, 0.999613, -0.0105988, 0.0158227, 0.895371, 0.99964, -979861e-8, 0.0148131, 0.917364, 0.99977, -967238e-8, 0.0140721, 0.938002, 0.999726, -869175e-8, 0.0129543, 0.957917, 0.99973, -866872e-8, 0.0122329, 0.976557, 0.999773, -731956e-8, 0.0108958, 0.994459, 0.999811, -756027e-8, 0.0102715, 1.01118, 0.999862, -583732e-8, 878781e-8, 1.02701, 0.999835, -631438e-8, 827529e-8, 1.04186, 0.999871, -450785e-8, 674583e-8, 1.05569, 0.999867, -486079e-8, 621041e-8, 1.06861, 0.999939, -322072e-8, 478301e-8, 1.08064, 0.999918, -318199e-8, 406395e-8, 1.09181, 1.00003, -193348e-8, 280682e-8, 1.10207, 0.999928, -153729e-8, 198741e-8, 1.11152, 0.999933, -623666e-9, 917714e-9, 1.12009, 1, -102387e-11, 907581e-12, 1.12813, 0.997866, -896716e-12, 0.0448334, 199584e-10, 0.997987, -225945e-10, 0.0448389, 502891e-9, 0.997987, -903781e-10, 0.0448388, 201156e-8, 0.997985, -203351e-9, 0.0448388, 452602e-8, 0.997986, -361514e-9, 0.0448388, 804629e-8, 0.997987, -56487e-8, 0.0448389, 0.0125724, 0.997988, -813423e-9, 0.0448389, 0.0181045, 0.997984, -110718e-8, 0.0448387, 0.0246427, 0.997985, -144616e-8, 0.0448388, 0.0321875, 0.997987, -183038e-8, 0.044839, 0.0407392, 0.997983, -225987e-8, 0.0448387, 0.0502986, 0.997991, -273467e-8, 0.0448389, 0.0608667, 0.997984, -325481e-8, 0.0448384, 0.0724444, 0.998002, -382043e-8, 0.044839, 0.0850348, 0.997997, -443145e-8, 0.0448396, 0.0986372, 0.998007, -508796e-8, 0.0448397, 0.113255, 0.998008, -578985e-8, 0.04484, 0.128891, 0.998003, -653683e-8, 0.0448384, 0.145548, 0.997983, -732713e-8, 0.0448358, 0.163221, 0.997985, -815454e-8, 0.0448358, 0.181899, 0.998005, -898985e-8, 0.0448286, 0.201533, 0.998026, -964404e-8, 0.0447934, 0.221821, 0.998055, -922677e-8, 0.044611, 0.241282, 0.99804, -0.0117361, 0.0448245, 0.261791, 0.998048, -0.0127628, 0.0448159, 0.285181, 0.998088, -0.0138055, 0.0447996, 0.30954, 0.998058, -0.0148206, 0.0447669, 0.334751, 0.998099, -0.0156998, 0.044697, 0.36061, 0.998116, -0.0161976, 0.0445122, 0.386603, 0.998195, -0.015945, 0.0441711, 0.411844, 0.998168, -0.0183947, 0.0444255, 0.43773, 0.998184, -0.0197913, 0.0443809, 0.466009, 0.998251, -0.0201426, 0.0440689, 0.494574, 0.998305, -0.0198847, 0.0435632, 0.522405, 0.998273, -0.0210577, 0.043414, 0.549967, 0.998254, -0.0227901, 0.0433943, 0.578655, 0.998349, -0.0223108, 0.0426529, 0.60758, 0.99843, -0.0223088, 0.042, 0.635524, 0.998373, -0.0241141, 0.0418987, 0.663621, 0.998425, -0.0231446, 0.0408118, 0.691906, 0.998504, -0.0233684, 0.0400565, 0.719339, 0.998443, -0.0241652, 0.0394634, 0.74643, 0.99848, -0.0228715, 0.0380002, 0.773086, 0.998569, -0.023519, 0.0372322, 0.798988, 0.998619, -0.0223108, 0.0356468, 0.824249, 0.998594, -0.0223105, 0.034523, 0.848808, 0.998622, -0.0213426, 0.0328887, 0.87227, 0.998669, -0.0207912, 0.0314374, 0.895157, 0.998705, -0.0198416, 0.0296925, 0.916769, 0.998786, -0.0189168, 0.0279634, 0.937773, 0.998888, -0.0178811, 0.0261597, 0.957431, 0.99906, -0.0166845, 0.0242159, 0.976495, 0.999038, -0.0155464, 0.0222638, 0.994169, 0.999237, -0.0141349, 0.0201967, 1.01112, 0.999378, -0.0129324, 0.0181744, 1.02692, 0.999433, -0.0113192, 0.0159898, 1.04174, 0.999439, -0.0101244, 0.0140385, 1.05559, 0.999614, -837456e-8, 0.0117826, 1.06852, 0.999722, -721769e-8, 983745e-8, 1.08069, 0.999817, -554067e-8, 769002e-8, 1.09176, 0.99983, -426961e-8, 5782e-6, 1.10211, 0.999964, -273904e-8, 374503e-8, 1.11152, 1.00001, -136739e-8, 187176e-8, 1.12031, 0.999946, 393227e-10, -28919e-9, 1.12804, 0.995847, -13435e-10, 0.0671785, 19916e-9, 0.995464, -338387e-10, 0.0671527, 501622e-9, 0.99547, -135355e-9, 0.0671531, 200649e-8, 0.995471, -30455e-8, 0.0671532, 451461e-8, 0.99547, -541423e-9, 0.0671531, 8026e-6, 0.995471, -84598e-8, 0.0671531, 0.0125407, 0.99547, -121823e-8, 0.0671531, 0.0180589, 0.99547, -165817e-8, 0.0671531, 0.0245806, 0.995463, -216583e-8, 0.0671526, 0.0321062, 0.995468, -274127e-8, 0.0671527, 0.0406366, 0.995474, -338447e-8, 0.0671534, 0.0501717, 0.995473, -409554e-8, 0.0671533, 0.0607131, 0.995478, -487451e-8, 0.0671531, 0.0722618, 0.995476, -572148e-8, 0.0671532, 0.0848191, 0.995477, -663658e-8, 0.0671539, 0.0983882, 0.995498, -761986e-8, 0.0671541, 0.112972, 0.995509, -867094e-8, 0.0671542, 0.128568, 0.995509, -978951e-8, 0.0671531, 0.145183, 0.995503, -0.0109725, 0.0671491, 0.162808, 0.995501, -0.012211, 0.0671465, 0.181441, 0.99553, -0.0134565, 0.0671371, 0.201015, 0.99555, -0.014391, 0.0670831, 0.221206, 0.99558, -0.014351, 0.0668883, 0.240813, 0.995577, -0.0173997, 0.0671055, 0.261257, 0.995602, -0.0191111, 0.0671178, 0.284467, 0.995623, -0.0206705, 0.0670946, 0.308765, 0.995658, -0.022184, 0.0670472, 0.333905, 0.995705, -0.0234832, 0.0669417, 0.359677, 0.995719, -0.0241933, 0.0666714, 0.385554, 0.995786, -0.0243539, 0.066266, 0.410951, 0.995887, -0.0271866, 0.0664367, 0.437163, 0.995944, -0.0296012, 0.0664931, 0.464842, 0.996004, -0.0301045, 0.0660105, 0.49332, 0.996128, -0.0298311, 0.0652694, 0.521131, 0.996253, -0.0316426, 0.0650739, 0.549167, 0.996244, -0.0339043, 0.0649433, 0.57737, 0.996309, -0.033329, 0.0638926, 0.606073, 0.996417, -0.0338935, 0.0630849, 0.634527, 0.996372, -0.0353104, 0.0625083, 0.66256, 0.996542, -0.0348942, 0.0611986, 0.690516, 0.996568, -0.0351614, 0.060069, 0.718317, 0.996711, -0.0354317, 0.0588522, 0.74528, 0.996671, -0.0349513, 0.0571902, 0.772061, 0.996865, -0.0345622, 0.0555321, 0.798089, 0.996802, -0.0342566, 0.0537816, 0.823178, 0.996992, -0.0330862, 0.0516095, 0.847949, 0.996944, -0.0324666, 0.0495537, 0.871431, 0.997146, -0.0309544, 0.0470302, 0.894357, 0.997189, -0.0299372, 0.0446043, 0.916142, 0.997471, -0.0281389, 0.0418812, 0.937193, 0.997515, -0.0268702, 0.0391823, 0.957, 0.997812, -0.0247166, 0.0361338, 0.975936, 0.998027, -0.0233525, 0.0333945, 0.99391, 0.998233, -0.0209839, 0.0301917, 1.01075, 0.998481, -0.0194309, 0.027271, 1.02669, 0.998859, -0.0169728, 0.0240162, 1.04173, 0.99894, -0.0152322, 0.0210517, 1.05551, 0.999132, -0.0127497, 0.0178632, 1.06856, 0.999369, -0.0108282, 0.014787, 1.08054, 0.999549, -845886e-8, 0.0116185, 1.09185, 0.999805, -63937e-7, 867209e-8, 1.10207, 0.99985, -414582e-8, 566823e-8, 1.1117, 0.999912, -207443e-8, 277562e-8, 1.12022, 1.00001, 870226e-10, -53766e-9, 1.12832, 0.991943, -178672e-11, 0.0893382, 198384e-10, 0.991952, -450183e-10, 0.089339, 499849e-9, 0.991956, -180074e-9, 0.0893394, 19994e-7, 0.991955, -405167e-9, 0.0893393, 449867e-8, 0.991953, -720298e-9, 0.0893391, 799764e-8, 0.991955, -112548e-8, 0.0893393, 0.0124964, 0.991957, -16207e-7, 0.0893395, 0.0179951, 0.991958, -220601e-8, 0.0893396, 0.0244939, 0.991947, -288137e-8, 0.0893385, 0.0319929, 0.991962, -364693e-8, 0.0893399, 0.0404933, 0.991965, -450264e-8, 0.0893399, 0.049995, 0.99198, -544862e-8, 0.0893411, 0.0604995, 0.99197, -648491e-8, 0.0893397, 0.0720074, 0.991976, -761164e-8, 0.089341, 0.0845207, 0.99198, -882891e-8, 0.0893405, 0.0980413, 0.991982, -0.0101367, 0.0893396, 0.112571, 0.992008, -0.011535, 0.0893415, 0.128115, 0.992026, -0.0130228, 0.0893414, 0.144672, 0.992064, -0.0145966, 0.0893418, 0.162241, 0.992041, -0.0162421, 0.0893359, 0.180801, 0.992086, -0.0178888, 0.0893214, 0.200302, 0.992157, -0.0190368, 0.0892401, 0.220332, 0.992181, -0.0195584, 0.0890525, 0.240144, 0.992175, -0.0227257, 0.0892153, 0.260728, 0.99221, -0.0254195, 0.089304, 0.283473, 0.99222, -0.0274883, 0.0892703, 0.307673, 0.992317, -0.0294905, 0.0892027, 0.332729, 0.992374, -0.0311861, 0.0890577, 0.358387, 0.992505, -0.0320656, 0.0886994, 0.384102, 0.992568, -0.0329715, 0.0883198, 0.409767, 0.992675, -0.036006, 0.0883602, 0.436145, 0.992746, -0.0392897, 0.0884591, 0.463217, 0.992873, -0.0399337, 0.0878287, 0.491557, 0.992934, -0.040231, 0.0870108, 0.519516, 0.993091, -0.0422013, 0.0865857, 0.547741, 0.993259, -0.0443503, 0.0861937, 0.575792, 0.993455, -0.0446368, 0.0851187, 0.604233, 0.993497, -0.0454299, 0.0840576, 0.632925, 0.993694, -0.0463296, 0.0829671, 0.660985, 0.993718, -0.0470619, 0.0817185, 0.688714, 0.993973, -0.0468838, 0.0800294, 0.716743, 0.994207, -0.046705, 0.0781286, 0.74377, 0.994168, -0.0469698, 0.0763337, 0.77042, 0.9945, -0.0456816, 0.0738184, 0.796659, 0.994356, -0.0455518, 0.0715545, 0.821868, 0.994747, -0.0439488, 0.0686085, 0.846572, 0.994937, -0.0430056, 0.065869, 0.870435, 0.995142, -0.0413414, 0.0626446, 0.893272, 0.995451, -0.0396521, 0.05929, 0.915376, 0.995445, -0.0378453, 0.0558503, 0.936196, 0.995967, -0.0355219, 0.0520949, 0.956376, 0.996094, -0.0335146, 0.048377, 0.975327, 0.996622, -0.030682, 0.0442575, 0.993471, 0.996938, -0.0285504, 0.0404693, 1.01052, 0.997383, -0.0253399, 0.0360903, 1.02637, 0.997714, -0.0231651, 0.0322176, 1.04139, 0.998249, -0.0198138, 0.0278433, 1.05542, 0.998596, -0.0174337, 0.0238759, 1.06846, 0.998946, -0.0141349, 0.0195944, 1.08056, 0.99928, -0.0115603, 0.0156279, 1.09181, 0.999507, -839065e-8, 0.0114607, 1.10213, 0.999697, -5666e-6, 763325e-8, 1.11169, 0.999869, -269902e-8, 364946e-8, 1.12042, 1.00001, 623836e-10, -319288e-10, 1.12832, 0.987221, -222675e-11, 0.111332, 197456e-10, 0.98739, -561116e-10, 0.111351, 497563e-9, 0.987448, -224453e-9, 0.111357, 199031e-8, 0.987441, -505019e-9, 0.111357, 44782e-7, 0.987442, -897816e-9, 0.111357, 796129e-8, 0.987442, -140284e-8, 0.111357, 0.0124396, 0.987444, -202012e-8, 0.111357, 0.0179132, 0.987442, -274964e-8, 0.111357, 0.0243824, 0.987446, -359147e-8, 0.111357, 0.0318474, 0.987435, -454562e-8, 0.111356, 0.0403086, 0.987461, -561225e-8, 0.111358, 0.0497678, 0.987458, -679125e-8, 0.111358, 0.0602239, 0.987443, -80828e-7, 0.111356, 0.0716792, 0.987476, -94872e-7, 0.111358, 0.0841364, 0.98749, -0.0110044, 0.111361, 0.097597, 0.987508, -0.0126344, 0.111362, 0.112062, 0.987494, -0.0143767, 0.111357, 0.127533, 0.987526, -0.0162307, 0.111359, 0.144015, 0.987558, -0.0181912, 0.111361, 0.161502, 0.987602, -0.0202393, 0.111355, 0.179979, 0.987692, -0.022273, 0.111346, 0.199386, 0.987702, -0.0235306, 0.111215, 0.219183, 0.987789, -0.0247628, 0.111061, 0.239202, 0.987776, -0.0280668, 0.111171, 0.259957, 0.987856, -0.0316751, 0.111327, 0.282198, 0.987912, -0.0342468, 0.111282, 0.306294, 0.988, -0.0367205, 0.111198, 0.331219, 0.988055, -0.0387766, 0.110994, 0.356708, 0.988241, -0.0397722, 0.110547, 0.382234, 0.988399, -0.0416076, 0.110198, 0.408227, 0.988539, -0.0448192, 0.110137, 0.434662, 0.988661, -0.0483793, 0.110143, 0.461442, 0.988967, -0.0495895, 0.109453, 0.489318, 0.989073, -0.0506797, 0.108628, 0.517516, 0.989274, -0.0526953, 0.108003, 0.545844, 0.989528, -0.054578, 0.107255, 0.573823, 0.989709, -0.0561503, 0.106294, 0.601944, 0.989991, -0.056866, 0.104896, 0.630855, 0.990392, -0.0572914, 0.103336, 0.658925, 0.990374, -0.0586224, 0.10189, 0.686661, 0.990747, -0.0584764, 0.099783, 0.714548, 0.991041, -0.0582662, 0.0974309, 0.74186, 0.991236, -0.0584118, 0.0951678, 0.768422, 0.991585, -0.0573055, 0.0921581, 0.794817, 0.991984, -0.0564241, 0.0891167, 0.820336, 0.9921, -0.0553608, 0.085805, 0.84493, 0.992749, -0.0533816, 0.0820354, 0.868961, 0.99288, -0.0518661, 0.0782181, 0.891931, 0.993511, -0.0492492, 0.0738935, 0.914186, 0.993617, -0.0471956, 0.0696402, 0.93532, 0.99411, -0.044216, 0.0649659, 0.95543, 0.994595, -0.0416654, 0.0603177, 0.974685, 0.994976, -0.0384314, 0.0553493, 0.992807, 0.995579, -0.0353491, 0.0503942, 1.00996, 0.996069, -0.0319787, 0.0452123, 1.02606, 0.996718, -0.028472, 0.0400112, 1.04114, 0.997173, -0.0250789, 0.0349456, 1.05517, 0.997818, -0.0213326, 0.029653, 1.0683, 0.998318, -0.0178509, 0.024549, 1.0805, 0.998853, -0.0141118, 0.0194197, 1.09177, 0.999218, -0.0105914, 0.0143869, 1.1022, 0.999594, -693474e-8, 943517e-8, 1.11175, 0.99975, -340478e-8, 464051e-8, 1.12056, 1.00001, 109172e-9, -112821e-9, 1.12853, 0.983383, -266524e-11, 0.133358, 196534e-10, 0.981942, -671009e-10, 0.133162, 494804e-9, 0.981946, -268405e-9, 0.133163, 197923e-8, 0.981944, -603912e-9, 0.133163, 445326e-8, 0.981941, -107362e-8, 0.133162, 791693e-8, 0.981946, -167755e-8, 0.133163, 0.0123703, 0.981944, -241569e-8, 0.133162, 0.0178135, 0.981945, -328807e-8, 0.133163, 0.0242466, 0.981945, -429472e-8, 0.133162, 0.03167, 0.981955, -543573e-8, 0.133164, 0.0400846, 0.981951, -671105e-8, 0.133163, 0.0494901, 0.981968, -812092e-8, 0.133165, 0.0598886, 0.981979, -966541e-8, 0.133166, 0.0712811, 0.981996, -0.0113446, 0.133168, 0.083669, 0.982014, -0.0131585, 0.133169, 0.0970533, 0.982011, -0.0151073, 0.133167, 0.111438, 0.982062, -0.0171906, 0.133172, 0.126826, 0.9821, -0.0194067, 0.133175, 0.143215, 0.982149, -0.0217502, 0.133176, 0.160609, 0.982163, -0.0241945, 0.133173, 0.178981, 0.982247, -0.0265907, 0.133148, 0.198249, 0.982291, -0.027916, 0.132974, 0.217795, 0.982396, -0.0299663, 0.132868, 0.238042, 0.982456, -0.0334544, 0.132934, 0.258901, 0.982499, -0.0378636, 0.133137, 0.280639, 0.982617, -0.0409274, 0.133085, 0.304604, 0.98274, -0.0438523, 0.132985, 0.329376, 0.982944, -0.0462288, 0.132728, 0.354697, 0.98308, -0.0475995, 0.132228, 0.380102, 0.983391, -0.0501901, 0.131924, 0.406256, 0.983514, -0.0535899, 0.131737, 0.432735, 0.98373, -0.0571858, 0.131567, 0.459359, 0.984056, -0.0592353, 0.130932, 0.486637, 0.984234, -0.0610488, 0.130092, 0.51509, 0.984748, -0.0630758, 0.12923, 0.543461, 0.985073, -0.0647398, 0.128174, 0.571376, 0.985195, -0.0671941, 0.127133, 0.599414, 0.985734, -0.0681345, 0.125576, 0.628134, 0.986241, -0.0686089, 0.123639, 0.656399, 0.986356, -0.0698511, 0.121834, 0.684258, 0.986894, -0.0700931, 0.119454, 0.711818, 0.987382, -0.0698321, 0.116718, 0.739511, 0.988109, -0.0693975, 0.113699, 0.766267, 0.988363, -0.0689584, 0.110454, 0.792456, 0.989112, -0.0672353, 0.106602, 0.81813, 0.989241, -0.0662034, 0.10267, 0.842889, 0.990333, -0.0638938, 0.0981381, 0.867204, 0.990591, -0.0618534, 0.0935388, 0.89038, 0.991106, -0.0593117, 0.088553, 0.912576, 0.991919, -0.0562676, 0.0832187, 0.934118, 0.992111, -0.0534085, 0.0778302, 0.954254, 0.992997, -0.0495459, 0.0720453, 0.973722, 0.993317, -0.0463707, 0.0663458, 0.991949, 0.994133, -0.0421245, 0.0601883, 1.00936, 0.994705, -0.0384977, 0.0542501, 1.02559, 0.995495, -0.0340956, 0.0479862, 1.04083, 0.996206, -0.030105, 0.041887, 1.05497, 0.996971, -0.0256095, 0.0355355, 1.06824, 0.997796, -0.0213932, 0.0293655, 1.08056, 0.998272, -0.0169612, 0.0232926, 1.09182, 0.998857, -0.0126756, 0.0172786, 1.10219, 0.99939, -832486e-8, 0.0113156, 1.11192, 0.999752, -410826e-8, 557892e-8, 1.12075, 1, 150957e-9, -119101e-9, 1.12885, 0.975169, -309397e-11, 0.154669, 195073e-10, 0.975439, -779608e-10, 0.154712, 491534e-9, 0.975464, -311847e-9, 0.154716, 196617e-8, 0.975464, -701656e-9, 0.154716, 442387e-8, 0.975462, -12474e-7, 0.154715, 78647e-7, 0.975461, -194906e-8, 0.154715, 0.0122886, 0.975464, -280667e-8, 0.154715, 0.0176959, 0.975468, -382025e-8, 0.154716, 0.0240867, 0.975471, -498985e-8, 0.154716, 0.0314612, 0.975472, -631541e-8, 0.154717, 0.0398199, 0.975486, -779719e-8, 0.154718, 0.0491639, 0.975489, -943505e-8, 0.154718, 0.0594932, 0.975509, -0.0112295, 0.154721, 0.0708113, 0.97554, -0.0131802, 0.154724, 0.0831176, 0.975557, -0.0152876, 0.154726, 0.096415, 0.975585, -0.0175512, 0.154728, 0.110705, 0.975605, -0.0199713, 0.154729, 0.125992, 0.975645, -0.0225447, 0.154729, 0.142272, 0.975711, -0.0252649, 0.154735, 0.159549, 0.975788, -0.0280986, 0.154736, 0.177805, 0.975872, -0.0308232, 0.154704, 0.196911, 0.975968, -0.0324841, 0.154525, 0.216324, 0.976063, -0.0351281, 0.154432, 0.236628, 0.976157, -0.0388618, 0.15446, 0.257539, 0.976204, -0.0437704, 0.154665, 0.278975, 0.976358, -0.047514, 0.154652, 0.302606, 0.976571, -0.0508638, 0.154535, 0.327204, 0.976725, -0.0534995, 0.154221, 0.352276, 0.977013, -0.0555547, 0.153737, 0.377696, 0.977294, -0.0586728, 0.153403, 0.403855, 0.977602, -0.0622715, 0.15312, 0.430333, 0.977932, -0.0658166, 0.152755, 0.456855, 0.978241, -0.0689877, 0.152233, 0.483668, 0.978602, -0.0712805, 0.15132, 0.512097, 0.979234, -0.0732775, 0.150235, 0.540455, 0.97977, -0.075163, 0.148978, 0.568486, 0.979995, -0.0778026, 0.147755, 0.596524, 0.98078, -0.0791854, 0.146019, 0.624825, 0.981628, -0.0799666, 0.143906, 0.653403, 0.982067, -0.0808532, 0.141561, 0.681445, 0.98271, -0.0816024, 0.139025, 0.708918, 0.983734, -0.0812511, 0.135764, 0.736594, 0.98431, -0.0806201, 0.132152, 0.763576, 0.985071, -0.0801605, 0.12846, 0.789797, 0.98618, -0.0784208, 0.124084, 0.815804, 0.986886, -0.0766643, 0.1193, 0.840869, 0.987485, -0.0747744, 0.114236, 0.864952, 0.988431, -0.0716701, 0.108654, 0.888431, 0.988886, -0.0691609, 0.102994, 0.910963, 0.990024, -0.0654048, 0.0967278, 0.932629, 0.990401, -0.0619765, 0.090384, 0.95313, 0.991093, -0.0579296, 0.0837885, 0.972587, 0.992018, -0.0536576, 0.0770171, 0.991184, 0.992536, -0.0493719, 0.0701486, 1.00863, 0.993421, -0.0444813, 0.062953, 1.02494, 0.993928, -0.040008, 0.0560455, 1.04017, 0.994994, -0.0347982, 0.04856, 1.05463, 0.995866, -0.0301017, 0.0416152, 1.06807, 0.996916, -0.0248225, 0.0342597, 1.08039, 0.997766, -0.0199229, 0.0271668, 1.09177, 0.998479, -0.0147422, 0.0201387, 1.10235, 0.99921, -980173e-8, 0.0131944, 1.11206, 0.999652, -47426e-7, 640712e-8, 1.12104, 0.999998, 891673e-10, -10379e-8, 1.12906, 0.967868, -351885e-11, 0.175947, 193569e-10, 0.968001, -886733e-10, 0.175972, 487782e-9, 0.96801, -354697e-9, 0.175973, 195115e-8, 0.968012, -798063e-9, 0.175974, 439006e-8, 0.968011, -141879e-8, 0.175973, 780461e-8, 0.968011, -221686e-8, 0.175973, 0.0121948, 0.968016, -319231e-8, 0.175974, 0.0175607, 0.968019, -434515e-8, 0.175974, 0.0239027, 0.968018, -567538e-8, 0.175974, 0.0312208, 0.968033, -718308e-8, 0.175977, 0.0395158, 0.968049, -886836e-8, 0.175979, 0.0487885, 0.968047, -0.0107312, 0.175978, 0.0590394, 0.968072, -0.0127719, 0.175981, 0.0702705, 0.968108, -0.0149905, 0.175986, 0.0824836, 0.968112, -0.0173866, 0.175985, 0.0956783, 0.968173, -0.0199611, 0.175993, 0.109862, 0.96827, -0.0227128, 0.176008, 0.125033, 0.968292, -0.025639, 0.17601, 0.141193, 0.968339, -0.0287299, 0.176007, 0.158336, 0.968389, -0.0319399, 0.176001, 0.176441, 0.968501, -0.034941, 0.175962, 0.195359, 0.968646, -0.0370812, 0.175793, 0.214686, 0.968789, -0.0402329, 0.175708, 0.234973, 0.96886, -0.0442601, 0.1757, 0.255871, 0.969013, -0.049398, 0.175876, 0.277238, 0.969242, -0.0539932, 0.17594, 0.300326, 0.969419, -0.0577299, 0.175781, 0.324702, 0.969763, -0.0605643, 0.175432, 0.349527, 0.970093, -0.0634488, 0.174992, 0.374976, 0.970361, -0.0670589, 0.174611, 0.401097, 0.970825, -0.0708246, 0.174226, 0.427496, 0.971214, -0.0742871, 0.173684, 0.453858, 0.971622, -0.0782608, 0.173186, 0.480637, 0.972175, -0.0813151, 0.172288, 0.508655, 0.972944, -0.0832678, 0.170979, 0.536973, 0.973595, -0.0855964, 0.169573, 0.565138, 0.974345, -0.0882163, 0.168152, 0.593222, 0.975233, -0.0901671, 0.166314, 0.621201, 0.976239, -0.0912111, 0.163931, 0.649919, 0.977289, -0.0916959, 0.161106, 0.678011, 0.978076, -0.0927061, 0.158272, 0.705717, 0.979533, -0.0925562, 0.15475, 0.733228, 0.980335, -0.0918159, 0.150638, 0.760454, 0.981808, -0.0908508, 0.146201, 0.786918, 0.983061, -0.0896172, 0.141386, 0.812953, 0.984148, -0.0871588, 0.135837, 0.838281, 0.985047, -0.0850624, 0.130135, 0.862594, 0.986219, -0.0818541, 0.123882, 0.88633, 0.987043, -0.0784523, 0.117126, 0.908952, 0.988107, -0.0749601, 0.110341, 0.930744, 0.988955, -0.0703548, 0.102885, 0.951728, 0.989426, -0.0662798, 0.0954167, 0.971166, 0.990421, -0.0610834, 0.0876331, 0.989984, 0.991032, -0.0562936, 0.0797785, 1.00765, 0.992041, -0.0508154, 0.0718166, 1.02434, 0.992794, -0.0454045, 0.0637125, 1.03976, 0.993691, -0.0398194, 0.0555338, 1.05418, 0.994778, -0.0341482, 0.0473388, 1.06772, 0.995915, -0.028428, 0.0391016, 1.08028, 0.997109, -0.022642, 0.0309953, 1.09185, 0.998095, -0.0168738, 0.0230288, 1.10247, 0.998985, -0.0111274, 0.0150722, 1.11229, 0.999581, -543881e-8, 740605e-8, 1.12131, 1.00003, 162239e-9, -105549e-9, 1.12946, 0.959505, -393734e-11, 0.196876, 191893e-10, 0.959599, -992157e-10, 0.196895, 483544e-9, 0.959641, -396868e-9, 0.196903, 19342e-7, 0.959599, -892948e-9, 0.196895, 435193e-8, 0.959603, -158747e-8, 0.196896, 77368e-7, 0.959604, -248042e-8, 0.196896, 0.0120888, 0.959605, -357184e-8, 0.196896, 0.0174082, 0.959605, -486169e-8, 0.196896, 0.0236949, 0.959613, -635008e-8, 0.196897, 0.0309497, 0.959619, -803696e-8, 0.196898, 0.0391725, 0.959636, -992255e-8, 0.196901, 0.0483649, 0.959634, -0.0120067, 0.1969, 0.0585266, 0.959675, -0.0142898, 0.196906, 0.0696609, 0.959712, -0.0167717, 0.196911, 0.0817678, 0.959752, -0.0194524, 0.196918, 0.0948494, 0.959807, -0.0223321, 0.196925, 0.10891, 0.959828, -0.0254091, 0.196924, 0.123947, 0.959906, -0.0286815, 0.196934, 0.139968, 0.960005, -0.0321371, 0.196944, 0.156968, 0.960071, -0.0357114, 0.196936, 0.17491, 0.960237, -0.0389064, 0.196882, 0.193597, 0.960367, -0.041623, 0.196731, 0.21285, 0.960562, -0.0452655, 0.196654, 0.233075, 0.960735, -0.0496207, 0.196643, 0.253941, 0.960913, -0.0549379, 0.196774, 0.275278, 0.961121, -0.0603414, 0.196893, 0.297733, 0.96139, -0.0644244, 0.196717, 0.321877, 0.961818, -0.067556, 0.196314, 0.346476, 0.962175, -0.0712709, 0.195917, 0.371907, 0.96255, -0.0752848, 0.1955, 0.397916, 0.963164, -0.0792073, 0.195026, 0.424229, 0.963782, -0.0828225, 0.194424, 0.450637, 0.964306, -0.0873119, 0.193831, 0.477288, 0.964923, -0.0911051, 0.192973, 0.504716, 0.966048, -0.093251, 0.19151, 0.533053, 0.967024, -0.0958983, 0.190013, 0.561366, 0.968038, -0.09835, 0.188253, 0.589464, 0.969152, -0.100754, 0.186257, 0.617433, 0.970557, -0.102239, 0.183775, 0.645801, 0.972104, -0.102767, 0.180645, 0.674278, 0.973203, -0.103492, 0.177242, 0.702004, 0.975123, -0.103793, 0.17345, 0.729529, 0.97641, -0.102839, 0.168886, 0.756712, 0.978313, -0.101687, 0.163892, 0.783801, 0.980036, -0.100314, 0.158439, 0.809671, 0.981339, -0.097836, 0.152211, 0.835402, 0.982794, -0.0950006, 0.145679, 0.860081, 0.984123, -0.0920994, 0.138949, 0.883757, 0.984918, -0.0878641, 0.131283, 0.90685, 0.985999, -0.083939, 0.123464, 0.928786, 0.987151, -0.0791234, 0.115324, 0.94983, 0.987827, -0.0739332, 0.106854, 0.96962, 0.988806, -0.0688088, 0.0982691, 0.98861, 0.989588, -0.0628962, 0.0893456, 1.00667, 0.990438, -0.0573146, 0.0805392, 1.02344, 0.991506, -0.0509433, 0.0713725, 1.03933, 0.992492, -0.0448724, 0.0623732, 1.05378, 0.993663, -0.0383497, 0.0530838, 1.06747, 0.994956, -0.0319593, 0.0439512, 1.08007, 0.99634, -0.025401, 0.0347803, 1.09182, 0.99761, -0.0189687, 0.0257954, 1.1025, 0.99863, -0.0124441, 0.0169893, 1.11247, 0.99947, -614003e-8, 829498e-8, 1.12151, 1.00008, 216624e-9, -146107e-9, 1.12993, 0.950129, -434955e-11, 0.217413, 190081e-10, 0.950264, -10957e-8, 0.217444, 47884e-8, 0.9503, -438299e-9, 0.217451, 191543e-8, 0.950246, -986124e-9, 0.21744, 430951e-8, 0.950246, -175311e-8, 0.21744, 766137e-8, 0.950245, -273923e-8, 0.21744, 0.011971, 0.950253, -394453e-8, 0.217441, 0.0172385, 0.950258, -536897e-8, 0.217442, 0.0234641, 0.950267, -701262e-8, 0.217444, 0.030648, 0.950277, -887551e-8, 0.217446, 0.038791, 0.950284, -0.0109576, 0.217446, 0.0478931, 0.950312, -0.0132591, 0.217451, 0.0579568, 0.950334, -0.01578, 0.217454, 0.0689821, 0.950378, -0.0185204, 0.217462, 0.0809714, 0.950417, -0.0214803, 0.217467, 0.0939265, 0.950488, -0.0246594, 0.217479, 0.10785, 0.950534, -0.0280565, 0.217483, 0.122743, 0.950633, -0.0316685, 0.217498, 0.138611, 0.950698, -0.0354787, 0.217499, 0.155442, 0.950844, -0.0394003, 0.217507, 0.173208, 0.950999, -0.0426812, 0.217419, 0.191605, 0.951221, -0.0461302, 0.217317, 0.21084, 0.951412, -0.0502131, 0.217238, 0.230945, 0.951623, -0.0549183, 0.21722, 0.251745, 0.951867, -0.0604493, 0.217306, 0.273001, 0.952069, -0.0665189, 0.217466, 0.294874, 0.952459, -0.0709179, 0.217266, 0.318732, 0.952996, -0.0746112, 0.216891, 0.34318, 0.953425, -0.0789252, 0.216503, 0.36849, 0.953885, -0.0833293, 0.216042, 0.394373, 0.954617, -0.087371, 0.215469, 0.420505, 0.955429, -0.0914054, 0.214802, 0.446907, 0.956068, -0.0961671, 0.214146, 0.473522, 0.957094, -0.10048, 0.213286, 0.50052, 0.958372, -0.103248, 0.211796, 0.528715, 0.959654, -0.106033, 0.21016, 0.557065, 0.961305, -0.108384, 0.208149, 0.585286, 0.962785, -0.111122, 0.206024, 0.613334, 0.964848, -0.112981, 0.203442, 0.641334, 0.966498, -0.113717, 0.19996, 0.669955, 0.968678, -0.114121, 0.196105, 0.698094, 0.970489, -0.114524, 0.191906, 0.725643, 0.972903, -0.113792, 0.186963, 0.752856, 0.974701, -0.112406, 0.181343, 0.780013, 0.976718, -0.110685, 0.175185, 0.806268, 0.978905, -0.108468, 0.168535, 0.832073, 0.980267, -0.105061, 0.161106, 0.857149, 0.981967, -0.101675, 0.153387, 0.881145, 0.983063, -0.0974492, 0.145199, 0.904255, 0.984432, -0.0925815, 0.136527, 0.926686, 0.985734, -0.0877983, 0.127584, 0.947901, 0.986228, -0.081884, 0.118125, 0.968111, 0.98719, -0.0761208, 0.108594, 0.98719, 0.988228, -0.0698196, 0.0989996, 1.00559, 0.989046, -0.0632739, 0.0890074, 1.02246, 0.990242, -0.056522, 0.0790832, 1.03841, 0.991252, -0.0495272, 0.0689182, 1.05347, 0.992542, -0.0425373, 0.0588592, 1.06724, 0.994096, -0.0353198, 0.0486833, 1.08009, 0.995593, -0.028235, 0.0385977, 1.09177, 0.99711, -0.0209511, 0.0286457, 1.10274, 0.998263, -0.0139289, 0.0188497, 1.11262, 0.999254, -67359e-7, 9208e-6, 1.12191, 0.999967, 141846e-9, -657764e-10, 1.13024, 0.935608, -474692e-11, 0.236466, 187817e-10, 0.93996, -11971e-8, 0.237568, 473646e-9, 0.939959, -478845e-9, 0.237567, 18946e-7, 0.939954, -10774e-7, 0.237566, 426284e-8, 0.939956, -191538e-8, 0.237566, 757842e-8, 0.939954, -299277e-8, 0.237566, 0.0118413, 0.93996, -430961e-8, 0.237567, 0.0170518, 0.939969, -586589e-8, 0.237569, 0.02321, 0.939982, -766166e-8, 0.237572, 0.0303164, 0.939987, -969686e-8, 0.237572, 0.0383711, 0.939997, -0.0119715, 0.237574, 0.0473751, 0.940031, -0.0144858, 0.237581, 0.0573298, 0.940073, -0.0172399, 0.237589, 0.0682366, 0.94012, -0.0202335, 0.237598, 0.080097, 0.940162, -0.0234663, 0.237604, 0.0929116, 0.940237, -0.0269387, 0.237615, 0.106686, 0.940328, -0.0306489, 0.237632, 0.121421, 0.940419, -0.0345917, 0.237645, 0.137115, 0.940522, -0.0387481, 0.237654, 0.153766, 0.940702, -0.0429906, 0.237661, 0.17133, 0.940871, -0.0465089, 0.237561, 0.189502, 0.941103, -0.050531, 0.23748, 0.208616, 0.941369, -0.0550657, 0.237423, 0.228595, 0.941641, -0.0601337, 0.237399, 0.249287, 0.941903, -0.0658804, 0.237443, 0.270467, 0.942224, -0.0722674, 0.237597, 0.292024, 0.942633, -0.0771788, 0.237419, 0.315272, 0.943172, -0.0815623, 0.237068, 0.339579, 0.943691, -0.0863973, 0.236682, 0.364717, 0.944382, -0.0911536, 0.236213, 0.390435, 0.945392, -0.0952967, 0.235562, 0.416425, 0.946185, -0.0998948, 0.234832, 0.442772, 0.947212, -0.104796, 0.234114, 0.469347, 0.948778, -0.10928, 0.233222, 0.496162, 0.950149, -0.113081, 0.231845, 0.523978, 0.951989, -0.115893, 0.230005, 0.552295, 0.953921, -0.11846, 0.227862, 0.580569, 0.955624, -0.12115, 0.225439, 0.608698, 0.958234, -0.123373, 0.222635, 0.636696, 0.960593, -0.124519, 0.219093, 0.665208, 0.963201, -0.124736, 0.214749, 0.693557, 0.965642, -0.125012, 0.210059, 0.721334, 0.968765, -0.124661, 0.204935, 0.748613, 0.971753, -0.122996, 0.198661, 0.776224, 0.973751, -0.120998, 0.191823, 0.802461, 0.976709, -0.118583, 0.184359, 0.828399, 0.977956, -0.115102, 0.176437, 0.853693, 0.979672, -0.111077, 0.167681, 0.877962, 0.981816, -0.10688, 0.158872, 0.901564, 0.98238, -0.101469, 0.149398, 0.924057, 0.983964, -0.0960013, 0.139436, 0.945751, 0.984933, -0.0899626, 0.12943, 0.966272, 0.985694, -0.0832973, 0.11894, 0.985741, 0.986822, -0.0767082, 0.108349, 1.00407, 0.987725, -0.0693614, 0.0976026, 1.02154, 0.98877, -0.06211, 0.086652, 1.03757, 0.990129, -0.0544143, 0.0756182, 1.05296, 0.991337, -0.046744, 0.0645753, 1.06683, 0.992978, -0.0387931, 0.0534683, 1.0798, 0.994676, -0.030973, 0.0424137, 1.09181, 0.99645, -0.0230311, 0.0314035, 1.10286, 0.997967, -0.0152065, 0.0206869, 1.11291, 0.99922, -744837e-8, 0.010155, 1.12237, 1.00002, 240209e-9, -752767e-10, 1.13089, 0.922948, -515351e-11, 0.255626, 186069e-10, 0.928785, -129623e-9, 0.257244, 468009e-9, 0.928761, -51849e-8, 0.257237, 187202e-8, 0.928751, -11666e-7, 0.257235, 421204e-8, 0.928751, -207395e-8, 0.257234, 74881e-7, 0.928754, -324055e-8, 0.257235, 0.0117002, 0.92876, -466639e-8, 0.257236, 0.0168486, 0.928763, -635149e-8, 0.257237, 0.0229334, 0.928774, -829584e-8, 0.257239, 0.029955, 0.928791, -0.0104995, 0.257243, 0.0379139, 0.928804, -0.0129623, 0.257245, 0.0468108, 0.928847, -0.0156846, 0.257255, 0.0566473, 0.92889, -0.0186661, 0.257263, 0.0674246, 0.928924, -0.0219067, 0.257268, 0.0791433, 0.928989, -0.0254066, 0.257282, 0.0918076, 0.92909, -0.0291651, 0.257301, 0.105419, 0.92918, -0.0331801, 0.257316, 0.119978, 0.92929, -0.0374469, 0.257332, 0.135491, 0.929453, -0.041939, 0.257357, 0.151948, 0.929586, -0.0464612, 0.257347, 0.169275, 0.929858, -0.0503426, 0.257269, 0.187257, 0.930125, -0.0548409, 0.257199, 0.206204, 0.930403, -0.0598063, 0.257149, 0.22601, 0.930726, -0.0652437, 0.257122, 0.246561, 0.931098, -0.0712376, 0.257153, 0.267618, 0.931396, -0.0777506, 0.257237, 0.288993, 0.931947, -0.0832374, 0.257124, 0.311527, 0.932579, -0.0883955, 0.25683, 0.335697, 0.933194, -0.0937037, 0.256444, 0.360634, 0.934013, -0.0987292, 0.255939, 0.386126, 0.935307, -0.103215, 0.255282, 0.412018, 0.936374, -0.108234, 0.254538, 0.438292, 0.93776, -0.113234, 0.253728, 0.464805, 0.939599, -0.118013, 0.25275, 0.491464, 0.941036, -0.122661, 0.251404, 0.518751, 0.94337, -0.125477, 0.249435, 0.547133, 0.945318, -0.128374, 0.247113, 0.575456, 0.947995, -0.130996, 0.244441, 0.60372, 0.950818, -0.133438, 0.241352, 0.63174, 0.954378, -0.135004, 0.237849, 0.659971, 0.957151, -0.135313, 0.233188, 0.688478, 0.960743, -0.13521, 0.228001, 0.716767, 0.964352, -0.135007, 0.222249, 0.744349, 0.967273, -0.133523, 0.21542, 0.771786, 0.969767, -0.131155, 0.208039, 0.798639, 0.973195, -0.128492, 0.200076, 0.824774, 0.975557, -0.125094, 0.191451, 0.850222, 0.977692, -0.120578, 0.18184, 0.874761, 0.98026, -0.115882, 0.172102, 0.898497, 0.981394, -0.110372, 0.161859, 0.921636, 0.982386, -0.10415, 0.15108, 0.943467, 0.983783, -0.0978128, 0.140407, 0.964045, 0.98422, -0.0906171, 0.129058, 0.98398, 0.985447, -0.0832921, 0.117614, 1.00276, 0.986682, -0.0754412, 0.10585, 1.02047, 0.987326, -0.0673885, 0.0940943, 1.03678, 0.988707, -0.0592565, 0.0822093, 1.05218, 0.990185, -0.050717, 0.070192, 1.06652, 0.991866, -0.0423486, 0.0582081, 1.07965, 0.993897, -0.0336118, 0.0460985, 1.09188, 0.995841, -0.0252178, 0.0342737, 1.10307, 0.997605, -0.0164893, 0.0224829, 1.11324, 0.999037, -817112e-8, 0.0110647, 1.12262, 1.00003, 291686e-9, -168673e-9, 1.13139, 0.915304, -552675e-11, 0.275999, 183285e-10, 0.91668, -139285e-9, 0.276414, 461914e-9, 0.916664, -55713e-8, 0.276409, 184763e-8, 0.916653, -125354e-8, 0.276406, 415715e-8, 0.916651, -222851e-8, 0.276405, 739053e-8, 0.916655, -348205e-8, 0.276406, 0.0115478, 0.916653, -501414e-8, 0.276405, 0.0166291, 0.916667, -682478e-8, 0.276409, 0.0226346, 0.91668, -891398e-8, 0.276412, 0.0295648, 0.91669, -0.0112817, 0.276413, 0.0374199, 0.916727, -0.013928, 0.276422, 0.0462016, 0.916759, -0.0168528, 0.276429, 0.0559101, 0.916793, -0.0200558, 0.276436, 0.0665466, 0.916849, -0.0235373, 0.276448, 0.0781139, 0.916964, -0.0272973, 0.276474, 0.0906156, 0.917047, -0.0313344, 0.276491, 0.104051, 0.917152, -0.0356465, 0.276511, 0.118424, 0.917286, -0.0402271, 0.276533, 0.133736, 0.917469, -0.0450408, 0.276564, 0.149978, 0.917686, -0.0497872, 0.276563, 0.167057, 0.917953, -0.0540937, 0.276493, 0.184846, 0.918228, -0.0590709, 0.276437, 0.203614, 0.918572, -0.0644277, 0.276398, 0.223212, 0.918918, -0.0702326, 0.276362, 0.243584, 0.919356, -0.076484, 0.276383, 0.264465, 0.919842, -0.0830808, 0.276434, 0.285701, 0.920451, -0.0892972, 0.276407, 0.307559, 0.921113, -0.095016, 0.276128, 0.331501, 0.921881, -0.100771, 0.275754, 0.356207, 0.923027, -0.106029, 0.275254, 0.381477, 0.924364, -0.111029, 0.274595, 0.40722, 0.925818, -0.116345, 0.273841, 0.433385, 0.92746, -0.121424, 0.272913, 0.459848, 0.929167, -0.12657, 0.271837, 0.486493, 0.931426, -0.131581, 0.270575, 0.513432, 0.934001, -0.135038, 0.268512, 0.541502, 0.936296, -0.138039, 0.266135, 0.569658, 0.939985, -0.140687, 0.263271, 0.598375, 0.943516, -0.143247, 0.260058, 0.626563, 0.94782, -0.145135, 0.256138, 0.654711, 0.951023, -0.145733, 0.251154, 0.683285, 0.955338, -0.145554, 0.245562, 0.711831, 0.959629, -0.145008, 0.239265, 0.739573, 0.963123, -0.144003, 0.232064, 0.767027, 0.966742, -0.141289, 0.224036, 0.794359, 0.969991, -0.138247, 0.215305, 0.820361, 0.973403, -0.134786, 0.206051, 0.846548, 0.975317, -0.129966, 0.195914, 0.871541, 0.977647, -0.12471, 0.185184, 0.895313, 0.980137, -0.119086, 0.174161, 0.918398, 0.981031, -0.112297, 0.162792, 0.940679, 0.982037, -0.105372, 0.150952, 0.961991, 0.983164, -0.097821, 0.138921, 0.981913, 0.983757, -0.0897245, 0.126611, 1.00109, 0.985036, -0.0815974, 0.114228, 1.01902, 0.986289, -0.0727725, 0.101389, 1.03604, 0.987329, -0.0639323, 0.0886476, 1.05149, 0.989193, -0.0548109, 0.0756837, 1.06619, 0.990716, -0.045687, 0.0627581, 1.07948, 0.992769, -0.0364315, 0.0498337, 1.09172, 0.99524, -0.0271761, 0.0370305, 1.1033, 0.997154, -0.0179609, 0.0243959, 1.11353, 0.998845, -878063e-8, 0.0119567, 1.12319, 1.00002, 259038e-9, -108146e-9, 1.13177, 0.903945, -591681e-11, 0.295126, 181226e-10, 0.903668, -148672e-9, 0.295037, 455367e-9, 0.903677, -594683e-9, 0.29504, 182145e-8, 0.903673, -133805e-8, 0.295039, 409831e-8, 0.903666, -237872e-8, 0.295036, 728584e-8, 0.903668, -371676e-8, 0.295037, 0.0113842, 0.903679, -535212e-8, 0.29504, 0.0163936, 0.903684, -728479e-8, 0.295041, 0.0223141, 0.903698, -951473e-8, 0.295044, 0.0291462, 0.903718, -0.0120419, 0.295049, 0.0368904, 0.903754, -0.0148664, 0.295058, 0.0455477, 0.903801, -0.017988, 0.29507, 0.0551194, 0.903851, -0.0214064, 0.295082, 0.0656058, 0.903921, -0.0251219, 0.295097, 0.0770109, 0.904002, -0.0291337, 0.295116, 0.0893354, 0.904111, -0.033441, 0.29514, 0.102583, 0.904246, -0.0380415, 0.295169, 0.116755, 0.904408, -0.0429258, 0.295202, 0.131853, 0.904637, -0.0480468, 0.295245, 0.147869, 0.904821, -0.0529208, 0.295214, 0.164658, 0.905163, -0.0577748, 0.295185, 0.182274, 0.905469, -0.0631763, 0.295143, 0.200828, 0.905851, -0.068917, 0.295112, 0.2202, 0.906322, -0.0750861, 0.295104, 0.240372, 0.906761, -0.0815855, 0.295086, 0.261082, 0.90735, -0.0882138, 0.295095, 0.282123, 0.908087, -0.095082, 0.295139, 0.303563, 0.908826, -0.101488, 0.29492, 0.327028, 0.909832, -0.107577, 0.294577, 0.351464, 0.911393, -0.113033, 0.294115, 0.376497, 0.912804, -0.118629, 0.293446, 0.402115, 0.914081, -0.124232, 0.292581, 0.428111, 0.91637, -0.129399, 0.29166, 0.454442, 0.91814, -0.134892, 0.290422, 0.481024, 0.921179, -0.140069, 0.289194, 0.507924, 0.924544, -0.144431, 0.287421, 0.535557, 0.927995, -0.147498, 0.284867, 0.563984, 0.931556, -0.150197, 0.281722, 0.5923, 0.935777, -0.152711, 0.278207, 0.620832, 0.940869, -0.154836, 0.274148, 0.649069, 0.945994, -0.155912, 0.269057, 0.677746, 0.949634, -0.155641, 0.262799, 0.706293, 0.955032, -0.154809, 0.256097, 0.734278, 0.95917, -0.153678, 0.248618, 0.761751, 0.962931, -0.151253, 0.239794, 0.789032, 0.966045, -0.147625, 0.230281, 0.815422, 0.96971, -0.143964, 0.220382, 0.841787, 0.972747, -0.139464, 0.209846, 0.867446, 0.975545, -0.133459, 0.198189, 0.892004, 0.978381, -0.127424, 0.186362, 0.915458, 0.979935, -0.120506, 0.173964, 0.937948, 0.980948, -0.11282, 0.161429, 0.959732, 0.982234, -0.104941, 0.148557, 0.980118, 0.982767, -0.0962905, 0.135508, 0.999463, 0.983544, -0.0873625, 0.122338, 1.01756, 0.984965, -0.0783447, 0.108669, 1.03492, 0.986233, -0.0684798, 0.0949911, 1.05087, 0.987796, -0.0590867, 0.0811386, 1.0656, 0.989885, -0.0489145, 0.0673099, 1.0794, 0.991821, -0.0391, 0.0535665, 1.09174, 0.99448, -0.029087, 0.0397529, 1.10341, 0.996769, -0.019114, 0.0261463, 1.11383, 0.998641, -947007e-8, 0.0128731, 1.1237, 0.999978, 446316e-9, -169093e-9, 1.13253, 0.888362, -627064e-11, 0.312578, 178215e-10, 0.889988, -157791e-9, 0.313148, 448451e-9, 0.889825, -631076e-9, 0.313092, 179356e-8, 0.88984, -141994e-8, 0.313097, 403554e-8, 0.889828, -25243e-7, 0.313092, 717429e-8, 0.889831, -394421e-8, 0.313093, 0.0112099, 0.889831, -567962e-8, 0.313093, 0.0161425, 0.889844, -773051e-8, 0.313096, 0.0219724, 0.889858, -0.0100968, 0.3131, 0.0286999, 0.889882, -0.0127786, 0.313106, 0.0363256, 0.889918, -0.0157757, 0.313116, 0.0448509, 0.889967, -0.0190878, 0.313129, 0.0542758, 0.89003, -0.022715, 0.313145, 0.0646032, 0.890108, -0.0266566, 0.313165, 0.0758339, 0.890218, -0.0309131, 0.313193, 0.0879729, 0.890351, -0.0354819, 0.313226, 0.101019, 0.89051, -0.0403613, 0.313263, 0.114979, 0.890672, -0.0455385, 0.313294, 0.129848, 0.890882, -0.0509444, 0.313333, 0.145616, 0.891189, -0.0559657, 0.313324, 0.162122, 0.891457, -0.0613123, 0.313281, 0.179524, 0.891856, -0.0671488, 0.313281, 0.197855, 0.892312, -0.0732732, 0.313268, 0.216991, 0.892819, -0.0797865, 0.313263, 0.236924, 0.893369, -0.0865269, 0.313247, 0.257433, 0.894045, -0.0931592, 0.313205, 0.278215, 0.894884, -0.100532, 0.313276, 0.299467, 0.895832, -0.107716, 0.313205, 0.322276, 0.897043, -0.114099, 0.312873, 0.34642, 0.898515, -0.119941, 0.312331, 0.371187, 0.900191, -0.126044, 0.311731, 0.396656, 0.90188, -0.131808, 0.310859, 0.422488, 0.904359, -0.137289, 0.309857, 0.448744, 0.906923, -0.142991, 0.308714, 0.475239, 0.910634, -0.148253, 0.307465, 0.501983, 0.914502, -0.153332, 0.305774, 0.529254, 0.919046, -0.156646, 0.303156, 0.557709, 0.923194, -0.159612, 0.299928, 0.586267, 0.928858, -0.162027, 0.296245, 0.614925, 0.934464, -0.164203, 0.291832, 0.643187, 0.939824, -0.165602, 0.286565, 0.671601, 0.944582, -0.165383, 0.280073, 0.700213, 0.949257, -0.164439, 0.272891, 0.728432, 0.954389, -0.162953, 0.264771, 0.756082, 0.958595, -0.161007, 0.255927, 0.78369, 0.962138, -0.157243, 0.245769, 0.810769, 0.966979, -0.152872, 0.235127, 0.836999, 0.969566, -0.148209, 0.22347, 0.862684, 0.972372, -0.142211, 0.211147, 0.887847, 0.975916, -0.135458, 0.198606, 0.911843, 0.978026, -0.128398, 0.185498, 0.934795, 0.979686, -0.120313, 0.17171, 0.956787, 0.980748, -0.11166, 0.158159, 0.978046, 0.981622, -0.103035, 0.144399, 0.997693, 0.982356, -0.0930328, 0.13001, 1.01642, 0.983308, -0.0834627, 0.115778, 1.03366, 0.985037, -0.0732249, 0.101327, 1.05014, 0.986493, -0.0628145, 0.086554, 1.06507, 0.988484, -0.0526556, 0.0720413, 1.07907, 0.991051, -0.0415744, 0.0571151, 1.09189, 0.993523, -0.0314275, 0.0426643, 1.10369, 0.99628, -0.0203603, 0.0279325, 1.11423, 0.998344, -0.0102446, 0.0138182, 1.12421, 0.999997, 42612e-8, -193628e-9, 1.1333, 0.871555, -660007e-11, 0.329176, 174749e-10, 0.875255, -166579e-9, 0.330571, 441051e-9, 0.875644, -666394e-9, 0.330718, 176441e-8, 0.875159, -149903e-8, 0.330536, 396899e-8, 0.87516, -266493e-8, 0.330536, 7056e-6, 0.875158, -416393e-8, 0.330535, 0.0110251, 0.87516, -599598e-8, 0.330535, 0.0158764, 0.875163, -816108e-8, 0.330536, 0.0216101, 0.875174, -0.0106591, 0.330538, 0.0282266, 0.875199, -0.0134899, 0.330545, 0.0357266, 0.875257, -0.0166538, 0.330563, 0.0441117, 0.875304, -0.0201501, 0.330575, 0.0533821, 0.875373, -0.0239785, 0.330595, 0.0635395, 0.875464, -0.0281389, 0.330619, 0.0745872, 0.875565, -0.0326301, 0.330645, 0.0865255, 0.875691, -0.0374516, 0.330676, 0.0993599, 0.875897, -0.0425993, 0.330733, 0.113093, 0.876091, -0.0480576, 0.330776, 0.127722, 0.876353, -0.0537216, 0.330826, 0.143227, 0.876649, -0.0589807, 0.330809, 0.159462, 0.877034, -0.0647865, 0.330819, 0.176642, 0.877443, -0.0709789, 0.330817, 0.194702, 0.877956, -0.0774782, 0.330832, 0.213577, 0.878499, -0.0843175, 0.330822, 0.233246, 0.879144, -0.0912714, 0.330804, 0.253512, 0.879982, -0.0980824, 0.330766, 0.274137, 0.88097, -0.105823, 0.330864, 0.295209, 0.882051, -0.113671, 0.330896, 0.317226, 0.883397, -0.120303, 0.330545, 0.341068, 0.884987, -0.12667, 0.330068, 0.365613, 0.886789, -0.133118, 0.329418, 0.390807, 0.889311, -0.139024, 0.328683, 0.416494, 0.891995, -0.144971, 0.327729, 0.442618, 0.895106, -0.150747, 0.326521, 0.469131, 0.899527, -0.156283, 0.325229, 0.495921, 0.90504, -0.161707, 0.32378, 0.523162, 0.909875, -0.165661, 0.32122, 0.55092, 0.91561, -0.168755, 0.317942, 0.579928, 0.921225, -0.171193, 0.313983, 0.608539, 0.927308, -0.17319, 0.309636, 0.636854, 0.933077, -0.174819, 0.304262, 0.66523, 0.938766, -0.175002, 0.297563, 0.693609, 0.943667, -0.173946, 0.289613, 0.722157, 0.949033, -0.172221, 0.281227, 0.750021, 0.953765, -0.169869, 0.271545, 0.777466, 0.95804, -0.166578, 0.261034, 0.804853, 0.962302, -0.161761, 0.249434, 0.831569, 0.966544, -0.156636, 0.237484, 0.857779, 0.969372, -0.150784, 0.224395, 0.883051, 0.972486, -0.143672, 0.210786, 0.907864, 0.975853, -0.135772, 0.196556, 0.931223, 0.977975, -0.127942, 0.182307, 0.954061, 0.979122, -0.118347, 0.167607, 0.97531, 0.980719, -0.109112, 0.152739, 0.995666, 0.981223, -0.0991789, 0.137932, 1.01475, 0.98216, -0.0883553, 0.122692, 1.03253, 0.983379, -0.0780825, 0.107493, 1.04917, 0.985434, -0.0665646, 0.0917791, 1.06464, 0.987332, -0.0557714, 0.0764949, 1.07896, 0.990004, -0.0442805, 0.060721, 1.09199, 0.992975, -0.0331676, 0.0452284, 1.10393, 0.995811, -0.0219547, 0.0297934, 1.11476, 0.9982, -0.0107613, 0.0146415, 1.12484, 1.00002, 248678e-9, -14555e-8, 1.13413, 0.859519, -693595e-11, 0.347264, 171673e-10, 0.859843, -17503e-8, 0.347394, 433219e-9, 0.859656, -700076e-9, 0.347319, 173277e-8, 0.859671, -157517e-8, 0.347325, 389875e-8, 0.859669, -280028e-8, 0.347324, 693112e-8, 0.85967, -43754e-7, 0.347324, 0.01083, 0.859665, -630049e-8, 0.347321, 0.0155954, 0.859685, -85755e-7, 0.347328, 0.0212278, 0.859694, -0.0112003, 0.347329, 0.0277273, 0.859718, -0.0141747, 0.347336, 0.0350946, 0.85976, -0.0174988, 0.347348, 0.0433314, 0.85982, -0.0211722, 0.347366, 0.0524384, 0.859892, -0.0251941, 0.347387, 0.0624168, 0.860006, -0.0295649, 0.347422, 0.0732708, 0.860122, -0.0342825, 0.347453, 0.0849999, 0.860282, -0.0393462, 0.347499, 0.0976102, 0.860482, -0.0447513, 0.347554, 0.111104, 0.860719, -0.0504775, 0.347614, 0.125479, 0.860998, -0.0563577, 0.347666, 0.140703, 0.861322, -0.0619473, 0.347662, 0.156681, 0.861724, -0.0681277, 0.347684, 0.173597, 0.862198, -0.0746567, 0.347709, 0.191371, 0.862733, -0.0815234, 0.347727, 0.209976, 0.863371, -0.0886643, 0.347744, 0.229351, 0.86414, -0.0957908, 0.347734, 0.24934, 0.865138, -0.102912, 0.34772, 0.269797, 0.866182, -0.110924, 0.3478, 0.290654, 0.867436, -0.119223, 0.347911, 0.312074, 0.869087, -0.126197, 0.347649, 0.335438, 0.870859, -0.133145, 0.347222, 0.359732, 0.872997, -0.139869, 0.346645, 0.38467, 0.875939, -0.146089, 0.345935, 0.41019, 0.879012, -0.152334, 0.345012, 0.436218, 0.883353, -0.15821, 0.343924, 0.462641, 0.888362, -0.164097, 0.342636, 0.489449, 0.895026, -0.169528, 0.341351, 0.516629, 0.900753, -0.174408, 0.339115, 0.544109, 0.906814, -0.17751, 0.335809, 0.572857, 0.912855, -0.180101, 0.331597, 0.601554, 0.919438, -0.182116, 0.32698, 0.630198, 0.925962, -0.183494, 0.321449, 0.658404, 0.931734, -0.184159, 0.314595, 0.686625, 0.93762, -0.18304, 0.306462, 0.71531, 0.943858, -0.181323, 0.297514, 0.744272, 0.948662, -0.178683, 0.287447, 0.771462, 0.953299, -0.175379, 0.276166, 0.798593, 0.957346, -0.170395, 0.263758, 0.8256, 0.962565, -0.165042, 0.251019, 0.852575, 0.966075, -0.158655, 0.237011, 0.878316, 0.969048, -0.151707, 0.222518, 0.90329, 0.972423, -0.143271, 0.207848, 0.927745, 0.975833, -0.134824, 0.192463, 0.950859, 0.977629, -0.125444, 0.1768, 0.972947, 0.978995, -0.114949, 0.161033, 0.993263, 0.980533, -0.104936, 0.145523, 1.01337, 0.980745, -0.0935577, 0.129799, 1.03128, 0.981814, -0.0822956, 0.113486, 1.04825, 0.983943, -0.0710082, 0.0972925, 1.06405, 0.986141, -0.0587931, 0.0808138, 1.0785, 0.988878, -0.0472755, 0.0644915, 1.09204, 0.992132, -0.0349128, 0.0478128, 1.10413, 0.9953, -0.0232407, 0.031621, 1.11527, 0.998117, -0.0112713, 0.0154935, 1.12551, 1.00003, 339743e-9, -195763e-9, 1.13504, 0.845441, -729126e-11, 0.364305, 169208e-10, 0.843588, -183164e-9, 0.363506, 425067e-9, 0.843412, -73253e-8, 0.36343, 169999e-8, 0.843401, -164818e-8, 0.363426, 382495e-8, 0.843399, -293008e-8, 0.363425, 679993e-8, 0.843401, -457822e-8, 0.363425, 0.010625, 0.843394, -659249e-8, 0.363421, 0.0153002, 0.843398, -897282e-8, 0.363421, 0.0208258, 0.843415, -0.0117191, 0.363426, 0.0272024, 0.843438, -0.0148312, 0.363432, 0.0344305, 0.843483, -0.018309, 0.363447, 0.0425116, 0.84356, -0.0221521, 0.363472, 0.0514471, 0.843646, -0.0263597, 0.363499, 0.061238, 0.843743, -0.0309315, 0.363527, 0.0718873, 0.84388, -0.0358658, 0.363569, 0.0833969, 0.844079, -0.0411624, 0.363631, 0.0957742, 0.844279, -0.0468128, 0.363688, 0.109015, 0.844549, -0.0527923, 0.363761, 0.123124, 0.844858, -0.0588204, 0.363817, 0.138044, 0.84522, -0.0647573, 0.36383, 0.153755, 0.845669, -0.0713181, 0.363879, 0.170394, 0.846155, -0.0781697, 0.363908, 0.187861, 0.846789, -0.0853913, 0.363969, 0.206176, 0.847502, -0.0928086, 0.363999, 0.225244, 0.8484, -0.10005, 0.363997, 0.244926, 0.849461, -0.107615, 0.364008, 0.265188, 0.850562, -0.115814, 0.364055, 0.28587, 0.851962, -0.124334, 0.364179, 0.306926, 0.854326, -0.131995, 0.364233, 0.329605, 0.856295, -0.139338, 0.363856, 0.35359, 0.858857, -0.146346, 0.363347, 0.37831, 0.862428, -0.152994, 0.362807, 0.403722, 0.866203, -0.159463, 0.361963, 0.429537, 0.871629, -0.165623, 0.36112, 0.456, 0.877365, -0.171649, 0.359917, 0.482773, 0.883744, -0.177151, 0.35848, 0.509705, 0.890693, -0.182381, 0.356523, 0.537215, 0.897278, -0.186076, 0.3533, 0.565493, 0.903958, -0.188602, 0.349095, 0.594293, 0.910908, -0.190755, 0.344215, 0.623165, 0.918117, -0.192063, 0.338606, 0.651573, 0.924644, -0.192758, 0.331544, 0.679869, 0.931054, -0.192238, 0.323163, 0.708668, 0.937303, -0.190035, 0.313529, 0.737201, 0.943387, -0.187162, 0.303152, 0.764977, 0.948494, -0.183876, 0.29146, 0.792683, 0.952546, -0.178901, 0.277917, 0.819228, 0.958077, -0.173173, 0.264753, 0.846559, 0.962462, -0.16645, 0.25002, 0.872962, 0.966569, -0.159452, 0.234873, 0.898729, 0.969108, -0.15074, 0.218752, 0.923126, 0.973072, -0.141523, 0.202673, 0.947278, 0.975452, -0.132075, 0.186326, 0.969938, 0.977784, -0.121257, 0.169396, 0.991325, 0.97899, -0.110182, 0.153044, 1.01123, 0.979777, -0.0989634, 0.136485, 1.0299, 0.980865, -0.0865894, 0.119343, 1.04727, 0.982432, -0.0746115, 0.102452, 1.06341, 0.984935, -0.0621822, 0.0852423, 1.07834, 0.987776, -0.0495694, 0.0678546, 1.092, 0.99103, -0.0372386, 0.0506917, 1.1043, 0.99474, -0.0244353, 0.0333316, 1.11576, 0.997768, -0.0121448, 0.0164348, 1.12617, 1.00003, 31774e-8, -169504e-9, 1.13598, 0.825551, -756799e-11, 0.378425, 165099e-10, 0.82664, -190922e-9, 0.378923, 416504e-9, 0.826323, -763495e-9, 0.378779, 16656e-7, 0.826359, -171789e-8, 0.378795, 374768e-8, 0.82636, -305402e-8, 0.378795, 666259e-8, 0.826368, -477185e-8, 0.378798, 0.0104104, 0.826364, -687131e-8, 0.378795, 0.0149912, 0.826368, -935232e-8, 0.378795, 0.0204054, 0.826376, -0.0122146, 0.378797, 0.0266532, 0.826399, -0.0154581, 0.378803, 0.0337355, 0.82646, -0.0190825, 0.378824, 0.0416537, 0.826525, -0.0230873, 0.378846, 0.0504091, 0.826614, -0.0274719, 0.378876, 0.0600032, 0.82674, -0.0322355, 0.378917, 0.0704393, 0.826888, -0.0373766, 0.378964, 0.0817195, 0.827078, -0.0428936, 0.379024, 0.0938492, 0.827318, -0.0487778, 0.379099, 0.106828, 0.82764, -0.0549935, 0.379199, 0.120659, 0.827926, -0.0611058, 0.379227, 0.13526, 0.828325, -0.0675054, 0.379275, 0.150713, 0.828801, -0.0743455, 0.379332, 0.167034, 0.8294, -0.0815523, 0.379415, 0.184209, 0.830094, -0.0890779, 0.379495, 0.202203, 0.8309, -0.096736, 0.379555, 0.220945, 0.831943, -0.104135, 0.379577, 0.240306, 0.833037, -0.112106, 0.379604, 0.260317, 0.834278, -0.120554, 0.379668, 0.2808, 0.836192, -0.129128, 0.3799, 0.301654, 0.838671, -0.137541, 0.380109, 0.323502, 0.840939, -0.14523, 0.379809, 0.347176, 0.844575, -0.15248, 0.379593, 0.371706, 0.848379, -0.159607, 0.37909, 0.39688, 0.853616, -0.166267, 0.378617, 0.422702, 0.858921, -0.172698, 0.377746, 0.448919, 0.865324, -0.178823, 0.376749, 0.475661, 0.872207, -0.184542, 0.375363, 0.502599, 0.880018, -0.189836, 0.373657, 0.529914, 0.88694, -0.194294, 0.370673, 0.557683, 0.894779, -0.197022, 0.36662, 0.586848, 0.902242, -0.199108, 0.36138, 0.615831, 0.909914, -0.200398, 0.355434, 0.644478, 0.917088, -0.20094, 0.348173, 0.672905, 0.923888, -0.200671, 0.339482, 0.701327, 0.930495, -0.198773, 0.32956, 0.730101, 0.937247, -0.195394, 0.318363, 0.758383, 0.943108, -0.191956, 0.306323, 0.786539, 0.948296, -0.187227, 0.292576, 0.813637, 0.953472, -0.181165, 0.278234, 0.840793, 0.958485, -0.174119, 0.263054, 0.867712, 0.962714, -0.166564, 0.246756, 0.893635, 0.966185, -0.158181, 0.229945, 0.919028, 0.970146, -0.148275, 0.212633, 0.943413, 0.973491, -0.138157, 0.195229, 0.966627, 0.975741, -0.127574, 0.178048, 0.988817, 0.977238, -0.11554, 0.160312, 1.00924, 0.978411, -0.10364, 0.142857, 1.02845, 0.979811, -0.0913122, 0.125317, 1.04648, 0.98116, -0.0782558, 0.107627, 1.06284, 0.983543, -0.0655957, 0.0895862, 1.07798, 0.986789, -0.0520411, 0.0713756, 1.092, 0.990292, -0.0389727, 0.053228, 1.10484, 0.994187, -0.025808, 0.0351945, 1.11642, 0.997499, -0.0126071, 0.0173198, 1.12703, 0.999999, 275604e-9, -148602e-9, 1.13674, 0.81075, -78735e-10, 0.394456, 161829e-10, 0.808692, -198293e-9, 0.393453, 407564e-9, 0.80846, -792877e-9, 0.39334, 162965e-8, 0.808595, -178416e-8, 0.393407, 366711e-8, 0.808597, -317182e-8, 0.393408, 651934e-8, 0.808598, -495589e-8, 0.393408, 0.0101866, 0.808591, -713627e-8, 0.393403, 0.0146689, 0.808592, -971285e-8, 0.393402, 0.0199667, 0.80861, -0.0126855, 0.393407, 0.0260803, 0.808633, -0.0160538, 0.393413, 0.0330107, 0.80868, -0.0198175, 0.393429, 0.0407589, 0.808748, -0.0239758, 0.393453, 0.0493264, 0.808854, -0.0285286, 0.39349, 0.0587161, 0.808992, -0.0334748, 0.39354, 0.0689304, 0.809141, -0.0388116, 0.393588, 0.0799707, 0.809352, -0.0445375, 0.39366, 0.0918432, 0.809608, -0.0506427, 0.393742, 0.104549, 0.809915, -0.0570708, 0.393834, 0.118085, 0.810253, -0.0633526, 0.393885, 0.132377, 0.810687, -0.0700966, 0.393953, 0.147537, 0.811233, -0.0772274, 0.394047, 0.163543, 0.811865, -0.0847629, 0.394148, 0.180394, 0.812648, -0.0925663, 0.394265, 0.198051, 0.813583, -0.100416, 0.394363, 0.216443, 0.814683, -0.108119, 0.394402, 0.235502, 0.815948, -0.11644, 0.394489, 0.255242, 0.817278, -0.125036, 0.394542, 0.275441, 0.819605, -0.133655, 0.39486, 0.296094, 0.822256, -0.142682, 0.395248, 0.317309, 0.825349, -0.150756, 0.395241, 0.340516, 0.829605, -0.158392, 0.395285, 0.364819, 0.83391, -0.165801, 0.394922, 0.389736, 0.839808, -0.172677, 0.394691, 0.415409, 0.845708, -0.179448, 0.394006, 0.441546, 0.853025, -0.185746, 0.393279, 0.46832, 0.859666, -0.191684, 0.391655, 0.495302, 0.86789, -0.197146, 0.390068, 0.52262, 0.875845, -0.201904, 0.38727, 0.550336, 0.882634, -0.205023, 0.382688, 0.578825, 0.891076, -0.207098, 0.377543, 0.608103, 0.900589, -0.208474, 0.371752, 0.63723, 0.90791, -0.209068, 0.364016, 0.665769, 0.915971, -0.208655, 0.355593, 0.694428, 0.923455, -0.20729, 0.345439, 0.723224, 0.931514, -0.203821, 0.334099, 0.751925, 0.937885, -0.19986, 0.321069, 0.780249, 0.943136, -0.194993, 0.306571, 0.8077, 0.948818, -0.189132, 0.291556, 0.83497, 0.954433, -0.181617, 0.275745, 0.86188, 0.959078, -0.173595, 0.258695, 0.888562, 0.962705, -0.164855, 0.240825, 0.914008, 0.966753, -0.155129, 0.22268, 0.939145, 0.970704, -0.144241, 0.204542, 0.963393, 0.973367, -0.133188, 0.185927, 0.985983, 0.975984, -0.121146, 0.167743, 1.00704, 0.976994, -0.108366, 0.149218, 1.02715, 0.978485, -0.0956746, 0.13131, 1.0455, 0.980074, -0.0820733, 0.112513, 1.06221, 0.98225, -0.0684061, 0.0938323, 1.07782, 0.98553, -0.0549503, 0.0749508, 1.09199, 0.989529, -0.0407857, 0.055848, 1.10508, 0.993536, -0.0271978, 0.0368581, 1.11684, 0.997247, -0.0132716, 0.0181845, 1.12789, 1, 431817e-9, -198809e-9, 1.13792, 0.785886, -812608e-11, 0.405036, 157669e-10, 0.790388, -205278e-9, 0.407355, 398297e-9, 0.790145, -820824e-9, 0.407231, 159263e-8, 0.790135, -184681e-8, 0.407226, 358336e-8, 0.790119, -328316e-8, 0.407218, 637039e-8, 0.790126, -512988e-8, 0.40722, 99539e-7, 0.79013, -738684e-8, 0.407221, 0.0143339, 0.790135, -0.0100538, 0.407221, 0.0195107, 0.790134, -0.0131306, 0.407217, 0.0254848, 0.79016, -0.0166169, 0.407224, 0.0322572, 0.790197, -0.020512, 0.407236, 0.0398284, 0.790273, -0.0248157, 0.407263, 0.0482014, 0.790381, -0.029527, 0.407304, 0.0573777, 0.790521, -0.0346446, 0.407355, 0.0673602, 0.790704, -0.0401665, 0.40742, 0.0781522, 0.790925, -0.0460896, 0.407499, 0.0897582, 0.791195, -0.0524017, 0.407589, 0.10218, 0.791522, -0.0590121, 0.407691, 0.11541, 0.791878, -0.0654876, 0.407748, 0.12939, 0.792361, -0.0725207, 0.407849, 0.144237, 0.792942, -0.0799844, 0.407963, 0.159924, 0.79362, -0.0877896, 0.408087, 0.176425, 0.794529, -0.0958451, 0.408259, 0.193733, 0.795521, -0.103827, 0.408362, 0.211756, 0.796778, -0.111937, 0.408482, 0.230524, 0.798027, -0.120521, 0.408547, 0.249967, 0.799813, -0.129242, 0.408721, 0.269926, 0.802387, -0.138048, 0.409148, 0.290338, 0.805279, -0.147301, 0.409641, 0.311193, 0.809251, -0.155895, 0.410154, 0.333611, 0.813733, -0.163942, 0.410297, 0.357615, 0.819081, -0.171666, 0.410373, 0.382339, 0.825427, -0.178905, 0.410348, 0.407828, 0.83172, -0.185812, 0.409486, 0.434034, 0.83877, -0.192318, 0.408776, 0.460493, 0.845817, -0.198249, 0.407176, 0.487346, 0.854664, -0.204034, 0.405719, 0.514832, 0.863495, -0.208908, 0.403282, 0.542401, 0.871883, -0.212765, 0.399293, 0.570683, 0.88065, -0.214911, 0.393803, 0.599947, 0.89004, -0.216214, 0.387536, 0.62932, 0.898476, -0.216745, 0.379846, 0.658319, 0.906738, -0.216387, 0.370625, 0.687138, 0.914844, -0.215053, 0.360139, 0.71601, 0.923877, -0.212007, 0.348849, 0.745124, 0.931925, -0.207481, 0.335639, 0.773366, 0.938054, -0.202418, 0.320798, 0.801636, 0.943895, -0.196507, 0.304772, 0.829055, 0.949468, -0.189009, 0.288033, 0.856097, 0.955152, -0.180539, 0.270532, 0.88301, 0.959403, -0.171437, 0.251639, 0.909296, 0.963309, -0.161661, 0.232563, 0.934868, 0.967399, -0.150425, 0.213231, 0.959662, 0.972009, -0.138659, 0.194247, 0.98302, 0.97433, -0.126595, 0.174718, 1.00517, 0.975823, -0.113205, 0.155518, 1.02566, 0.976371, -0.0996096, 0.136709, 1.04418, 0.978705, -0.0860754, 0.117571, 1.06146, 0.981477, -0.0714438, 0.0980046, 1.07777, 0.984263, -0.0572304, 0.0782181, 1.09214, 0.988423, -0.0428875, 0.0584052, 1.10553, 0.993, -0.0282442, 0.038522, 1.11758, 0.99704, -0.0140183, 0.0190148, 1.12864, 0.999913, 369494e-9, -145203e-9, 1.13901, 0.777662, -84153e-10, 0.423844, 154403e-10, 0.770458, -211714e-9, 0.419915, 38845e-8, 0.770716, -846888e-9, 0.420055, 155386e-8, 0.770982, -190567e-8, 0.420202, 349653e-8, 0.770981, -338782e-8, 0.420201, 621606e-8, 0.77098, -529338e-8, 0.4202, 971274e-8, 0.770983, -762223e-8, 0.4202, 0.0139867, 0.770985, -0.0103741, 0.420198, 0.0190381, 0.770996, -0.0135489, 0.4202, 0.0248677, 0.771029, -0.0171461, 0.420212, 0.0314764, 0.771052, -0.0211647, 0.420215, 0.0388648, 0.771131, -0.0256048, 0.420245, 0.047036, 0.771235, -0.0304647, 0.420284, 0.0559911, 0.771383, -0.0357436, 0.420341, 0.0657346, 0.771591, -0.0414392, 0.420423, 0.0762694, 0.771819, -0.0475462, 0.420506, 0.0875984, 0.772123, -0.0540506, 0.420617, 0.099727, 0.772464, -0.060797, 0.42072, 0.112637, 0.772855, -0.0675393, 0.420799, 0.126313, 0.773317, -0.0748323, 0.420893, 0.140824, 0.773981, -0.0825681, 0.421058, 0.15617, 0.774746, -0.0906307, 0.421226, 0.172322, 0.77566, -0.0988982, 0.421397, 0.189253, 0.776837, -0.106994, 0.421569, 0.206912, 0.778097, -0.115528, 0.421704, 0.225359, 0.779588, -0.124317, 0.421849, 0.24447, 0.781574, -0.133139, 0.422097, 0.264156, 0.784451, -0.142179, 0.422615, 0.284318, 0.787682, -0.15165, 0.423269, 0.304902, 0.792433, -0.160771, 0.424396, 0.3265, 0.797359, -0.169166, 0.424772, 0.35014, 0.803986, -0.177149, 0.425475, 0.374768, 0.809504, -0.184745, 0.424996, 0.399928, 0.815885, -0.19173, 0.424247, 0.425796, 0.823513, -0.198525, 0.423515, 0.452287, 0.832549, -0.204709, 0.422787, 0.479321, 0.841653, -0.210447, 0.421187, 0.506718, 0.850401, -0.215501, 0.418519, 0.53432, 0.859854, -0.219752, 0.414715, 0.56242, 0.869364, -0.222305, 0.409462, 0.591558, 0.878837, -0.223744, 0.402926, 0.621074, 0.888636, -0.224065, 0.395043, 0.650538, 0.898132, -0.223742, 0.38564, 0.679538, 0.907181, -0.222308, 0.375378, 0.708674, 0.915621, -0.219837, 0.363212, 0.737714, 0.9239, -0.215233, 0.349313, 0.767014, 0.931644, -0.209592, 0.334162, 0.795133, 0.938887, -0.203644, 0.317943, 0.823228, 0.945282, -0.196349, 0.300581, 0.850822, 0.950758, -0.18742, 0.282195, 0.877594, 0.956146, -0.177879, 0.262481, 0.904564, 0.960355, -0.167643, 0.242487, 0.930741, 0.965256, -0.156671, 0.222668, 0.955868, 0.968029, -0.144123, 0.201907, 0.979869, 0.97251, -0.131305, 0.18202, 1.00291, 0.974925, -0.118335, 0.161909, 1.02392, 0.975402, -0.103714, 0.142129, 1.0433, 0.976987, -0.089415, 0.122447, 1.06089, 0.979677, -0.0748858, 0.102248, 1.07713, 0.983184, -0.0596086, 0.0814851, 1.09218, 0.987466, -0.0447671, 0.0609484, 1.10585, 0.992348, -0.0295217, 0.0401835, 1.11829, 0.996674, -0.0143917, 0.0198163, 1.12966, 1.00003, 321364e-9, -149983e-9, 1.1402, 0.757901, -869074e-11, 0.436176, 151011e-10, 0.751195, -217848e-9, 0.432317, 378533e-9, 0.751178, -871373e-9, 0.432307, 15141e-7, 0.751195, -196061e-8, 0.432317, 34068e-7, 0.751198, -348552e-8, 0.432318, 605659e-8, 0.751195, -544599e-8, 0.432315, 946353e-8, 0.751207, -784203e-8, 0.43232, 0.013628, 0.751213, -0.0106732, 0.43232, 0.0185499, 0.751221, -0.0139393, 0.432319, 0.0242302, 0.751244, -0.0176398, 0.432325, 0.0306694, 0.7513, -0.0217743, 0.432348, 0.0378698, 0.751358, -0.0263412, 0.432367, 0.0458321, 0.751458, -0.0313396, 0.432404, 0.0545587, 0.751608, -0.0367682, 0.432464, 0.0640543, 0.7518, -0.0426246, 0.43254, 0.0743222, 0.752065, -0.0489031, 0.432645, 0.0853668, 0.752376, -0.0555828, 0.432762, 0.0971911, 0.752715, -0.0623861, 0.432859, 0.109768, 0.753137, -0.069415, 0.432958, 0.123126, 0.753676, -0.0770039, 0.433099, 0.137308, 0.754345, -0.084971, 0.433272, 0.15229, 0.755235, -0.0932681, 0.433504, 0.168075, 0.756186, -0.10171, 0.433693, 0.184625, 0.757363, -0.110019, 0.433857, 0.201897, 0.75884, -0.11887, 0.434102, 0.220014, 0.760467, -0.127881, 0.434306, 0.238778, 0.762969, -0.136766, 0.434751, 0.258172, 0.765823, -0.14612, 0.43529, 0.278062, 0.769676, -0.15566, 0.436236, 0.298437, 0.774909, -0.165177, 0.437754, 0.319532, 0.77994, -0.17402, 0.438343, 0.342505, 0.785757, -0.182201, 0.438609, 0.366693, 0.792487, -0.190104, 0.438762, 0.391668, 0.80038, -0.197438, 0.438795, 0.417494, 0.808494, -0.204365, 0.438226, 0.443933, 0.817695, -0.210714, 0.437283, 0.470929, 0.828111, -0.216651, 0.436087, 0.498569, 0.837901, -0.221804, 0.433717, 0.526165, 0.847813, -0.226318, 0.430133, 0.554155, 0.858314, -0.229297, 0.425213, 0.582822, 0.868891, -0.230999, 0.418576, 0.612847, 0.878941, -0.231155, 0.410405, 0.642445, 0.888809, -0.230935, 0.400544, 0.672024, 0.898089, -0.229343, 0.389613, 0.701366, 0.908081, -0.226886, 0.377197, 0.730763, 0.916819, -0.222676, 0.363397, 0.759642, 0.924968, -0.216835, 0.347437, 0.788775, 0.932906, -0.210245, 0.32995, 0.817135, 0.940025, -0.202992, 0.312262, 0.844912, 0.946101, -0.19436, 0.293313, 0.872164, 0.952835, -0.184125, 0.273638, 0.899443, 0.957347, -0.173657, 0.252385, 0.926389, 0.961434, -0.162204, 0.231038, 0.951947, 0.965522, -0.14979, 0.209834, 0.976751, 0.969412, -0.136307, 0.188821, 1.00022, 0.973902, -0.122527, 0.168013, 1.02229, 0.974045, -0.108213, 0.147634, 1.04199, 0.975775, -0.0927397, 0.12705, 1.06019, 0.978383, -0.0778212, 0.106309, 1.07711, 0.98211, -0.0621216, 0.0849279, 1.09245, 0.986517, -0.0463847, 0.0633519, 1.10651, 0.991696, -0.0309353, 0.0419698, 1.11903, 0.996349, -0.0150914, 0.0206272, 1.13073, 1.00003, 442449e-9, -231396e-9, 1.14146, 0.727498, -885074e-11, 0.441528, 145832e-10, 0.730897, -223525e-9, 0.443589, 368298e-9, 0.730796, -893996e-9, 0.443528, 147303e-8, 0.730805, -201149e-8, 0.443533, 331433e-8, 0.730814, -357596e-8, 0.443538, 589222e-8, 0.730815, -558734e-8, 0.443538, 920678e-8, 0.730822, -804544e-8, 0.44354, 0.0132582, 0.730836, -0.0109501, 0.443545, 0.0180468, 0.730848, -0.0143008, 0.443546, 0.0235732, 0.730871, -0.0180969, 0.443552, 0.0298382, 0.730915, -0.022338, 0.443567, 0.0368438, 0.730982, -0.0270225, 0.443591, 0.044591, 0.731076, -0.0321491, 0.443627, 0.0530831, 0.731245, -0.0377166, 0.443699, 0.0623243, 0.73144, -0.0437216, 0.443777, 0.0723181, 0.7317, -0.0501576, 0.443881, 0.0830691, 0.732034, -0.0569942, 0.444014, 0.0945809, 0.732388, -0.0638756, 0.444113, 0.106825, 0.732853, -0.071203, 0.444247, 0.119859, 0.733473, -0.0790076, 0.444442, 0.13369, 0.734195, -0.0871937, 0.444645, 0.148304, 0.735069, -0.095696, 0.444877, 0.163702, 0.736169, -0.10426, 0.445133, 0.179861, 0.73747, -0.112853, 0.44537, 0.196778, 0.738991, -0.12199, 0.445651, 0.214496, 0.740865, -0.131153, 0.445958, 0.232913, 0.743637, -0.140245, 0.446548, 0.251977, 0.746797, -0.149722, 0.447246, 0.271551, 0.751517, -0.159341, 0.448656, 0.291774, 0.756156, -0.169106, 0.449866, 0.312455, 0.761519, -0.178436, 0.450919, 0.334552, 0.768295, -0.186904, 0.451776, 0.358491, 0.776613, -0.195117, 0.452832, 0.383446, 0.783966, -0.202695, 0.45249, 0.408945, 0.793542, -0.20985, 0.452587, 0.435364, 0.803192, -0.216403, 0.451852, 0.462336, 0.813892, -0.22251, 0.450708, 0.48987, 0.824968, -0.227676, 0.4486, 0.517697, 0.835859, -0.232443, 0.445156, 0.545975, 0.846825, -0.235775, 0.440351, 0.574483, 0.858085, -0.237897, 0.433641, 0.604246, 0.868825, -0.238074, 0.425354, 0.634101, 0.879638, -0.237661, 0.415383, 0.664201, 0.889966, -0.236186, 0.404136, 0.693918, 0.899479, -0.233599, 0.390917, 0.723481, 0.908769, -0.229737, 0.376352, 0.75258, 0.917966, -0.223836, 0.360372, 0.781764, 0.926304, -0.217067, 0.342551, 0.811139, 0.934626, -0.209309, 0.324238, 0.839585, 0.941841, -0.20071, 0.304484, 0.867044, 0.94789, -0.190602, 0.283607, 0.894579, 0.954196, -0.179253, 0.262205, 0.921743, 0.958383, -0.167646, 0.239847, 0.948026, 0.963119, -0.155073, 0.218078, 0.973296, 0.966941, -0.141426, 0.195899, 0.998135, 0.970836, -0.126849, 0.174121, 1.02021, 0.973301, -0.112296, 0.153052, 1.04085, 0.97448, -0.0964965, 0.131733, 1.05946, 0.977045, -0.080489, 0.10997, 1.07693, 0.980751, -0.064844, 0.0881657, 1.09254, 0.985475, -0.0481938, 0.0657987, 1.10697, 0.991089, -0.0319185, 0.0435215, 1.12004, 0.996122, -0.0158088, 0.0214779, 1.13173, 1.00001, 372455e-9, -200295e-9, 1.14291, 0.708622, -907597e-11, 0.45304, 141962e-10, 0.711162, -228911e-9, 0.454662, 358052e-9, 0.709812, -914446e-9, 0.453797, 143034e-8, 0.709865, -205819e-8, 0.453834, 321935e-8, 0.709864, -365894e-8, 0.453833, 572331e-8, 0.709855, -571692e-8, 0.453826, 894278e-8, 0.709862, -823201e-8, 0.453828, 0.012878, 0.709875, -0.011204, 0.453832, 0.0175295, 0.709896, -0.0146323, 0.453839, 0.0228978, 0.709925, -0.0185163, 0.453847, 0.0289839, 0.709974, -0.0228551, 0.453866, 0.0357894, 0.710045, -0.0276473, 0.453892, 0.0433161, 0.710133, -0.032891, 0.453924, 0.0515665, 0.710292, -0.0385851, 0.453992, 0.0605458, 0.710485, -0.0447254, 0.45407, 0.0702574, 0.710769, -0.0513051, 0.454192, 0.0807077, 0.711106, -0.0582733, 0.454329, 0.091896, 0.711516, -0.0652866, 0.45446, 0.103814, 0.712071, -0.0728426, 0.454653, 0.116508, 0.712676, -0.0808307, 0.45484, 0.129968, 0.713476, -0.0892216, 0.455096, 0.144206, 0.714377, -0.0979047, 0.455346, 0.159212, 0.715579, -0.106531, 0.455647, 0.174973, 0.716977, -0.115492, 0.455961, 0.191504, 0.71862, -0.124821, 0.456315, 0.208835, 0.72084, -0.134079, 0.4568, 0.226869, 0.723786, -0.143427, 0.457521, 0.245582, 0.727464, -0.153061, 0.458475, 0.264957, 0.732771, -0.162768, 0.460239, 0.284948, 0.736515, -0.172627, 0.460899, 0.30522, 0.743519, -0.182487, 0.463225, 0.326717, 0.750041, -0.191295, 0.464027, 0.350113, 0.758589, -0.199746, 0.465227, 0.374782, 0.767703, -0.207584, 0.465877, 0.400226, 0.777484, -0.214973, 0.465996, 0.426442, 0.788792, -0.221796, 0.466019, 0.453688, 0.800194, -0.228038, 0.465083, 0.481246, 0.811234, -0.233346, 0.462506, 0.509086, 0.822859, -0.238073, 0.459257, 0.537338, 0.835082, -0.241764, 0.454863, 0.566108, 0.846332, -0.244241, 0.448163, 0.595126, 0.858355, -0.244736, 0.439709, 0.625574, 0.87034, -0.244278, 0.429837, 0.65617, 0.881027, -0.24255, 0.418002, 0.686029, 0.891007, -0.239912, 0.404325, 0.716039, 0.900874, -0.236133, 0.389222, 0.745518, 0.911072, -0.230672, 0.373269, 0.775026, 0.920359, -0.22356, 0.355083, 0.804521, 0.928604, -0.215591, 0.335533, 0.834045, 0.937175, -0.206503, 0.315278, 0.861612, 0.942825, -0.196684, 0.293653, 0.889131, 0.949805, -0.185116, 0.271503, 0.916853, 0.955535, -0.172703, 0.248821, 0.943541, 0.959843, -0.159978, 0.225591, 0.970132, 0.964393, -0.146375, 0.202719, 0.994709, 0.968008, -0.131269, 0.179928, 1.0186, 0.971013, -0.11569, 0.158007, 1.03928, 0.973334, -0.1003, 0.13624, 1.05887, 0.975775, -0.0833352, 0.1138, 1.07652, 0.979579, -0.0668981, 0.0913141, 1.09297, 0.984323, -0.0500902, 0.0683051, 1.10734, 0.990351, -0.0332377, 0.0451771, 1.12084, 0.995823, -0.0161491, 0.0221705, 1.13296, 1.0001, 234083e-9, -108712e-9, 1.14441, 0.683895, -924677e-11, 0.46015, 137429e-10, 0.68833, -233383e-9, 0.463134, 346865e-9, 0.688368, -933547e-9, 0.463159, 138748e-8, 0.688367, -210049e-8, 0.463159, 312187e-8, 0.688369, -373415e-8, 0.463159, 555004e-8, 0.688377, -583449e-8, 0.463163, 867216e-8, 0.688386, -840128e-8, 0.463166, 0.0124884, 0.688398, -0.0114343, 0.463169, 0.0169993, 0.688418, -0.0149329, 0.463175, 0.0222054, 0.688453, -0.0188964, 0.463188, 0.028108, 0.688515, -0.0233239, 0.463214, 0.0347085, 0.68857, -0.0282136, 0.463231, 0.0420091, 0.688679, -0.033564, 0.463276, 0.0500132, 0.688854, -0.0393733, 0.463356, 0.0587255, 0.689038, -0.0456354, 0.46343, 0.0681476, 0.689321, -0.0523433, 0.463553, 0.0782897, 0.689662, -0.059412, 0.463693, 0.0891501, 0.690188, -0.0665736, 0.4639, 0.100735, 0.690755, -0.0743106, 0.464107, 0.113074, 0.691405, -0.0824722, 0.464329, 0.126161, 0.692198, -0.0910484, 0.464585, 0.140007, 0.693196, -0.0998778, 0.464893, 0.154612, 0.69454, -0.108651, 0.465285, 0.169984, 0.695921, -0.117855, 0.465596, 0.186106, 0.697749, -0.12734, 0.466056, 0.203034, 0.700375, -0.136714, 0.466771, 0.220703, 0.703395, -0.146386, 0.467579, 0.239062, 0.707904, -0.156096, 0.469067, 0.258188, 0.711673, -0.165904, 0.469851, 0.277759, 0.717489, -0.175812, 0.471815, 0.297935, 0.724051, -0.185931, 0.47389, 0.318916, 0.731965, -0.195238, 0.47587, 0.341591, 0.741151, -0.204021, 0.477523, 0.366062, 0.751416, -0.212113, 0.478881, 0.391396, 0.761848, -0.21979, 0.479226, 0.417599, 0.771886, -0.2267, 0.478495, 0.444401, 0.783998, -0.232991, 0.477622, 0.472084, 0.796523, -0.238645, 0.475833, 0.500193, 0.808851, -0.243396, 0.472568, 0.52865, 0.821191, -0.247226, 0.467857, 0.557362, 0.834261, -0.250102, 0.461871, 0.586768, 0.846762, -0.251056, 0.453543, 0.617085, 0.859867, -0.250604, 0.443494, 0.647659, 0.871948, -0.248783, 0.431711, 0.678119, 0.882967, -0.245855, 0.417911, 0.708399, 0.892826, -0.242168, 0.401993, 0.738256, 0.90332, -0.237062, 0.385371, 0.767999, 0.913633, -0.22997, 0.366837, 0.798191, 0.922774, -0.221687, 0.346372, 0.827756, 0.931371, -0.212345, 0.325682, 0.856425, 0.938929, -0.20206, 0.303665, 0.884299, 0.944821, -0.190981, 0.280786, 0.912023, 0.951792, -0.178065, 0.2573, 0.939669, 0.957712, -0.164634, 0.233448, 0.96655, 0.961912, -0.150863, 0.209504, 0.992366, 0.966382, -0.13577, 0.18597, 1.01633, 0.969588, -0.119593, 0.162905, 1.03843, 0.971777, -0.103203, 0.14053, 1.05841, 0.97433, -0.0865888, 0.117909, 1.07632, 0.978686, -0.0690829, 0.0944101, 1.09326, 0.983281, -0.0516568, 0.0705671, 1.10796, 0.989562, -0.034558, 0.0468592, 1.12182, 0.995465, -0.0167808, 0.0229846, 1.1342, 0.999991, 373016e-9, -235606e-9, 1.1459, 0.662251, -939016e-11, 0.468575, 132714e-10, 0.666634, -237624e-9, 0.471675, 335842e-9, 0.666411, -950385e-9, 0.471516, 134321e-8, 0.666399, -213833e-8, 0.471509, 302221e-8, 0.666386, -38014e-7, 0.471499, 537283e-8, 0.666405, -593958e-8, 0.471511, 839533e-8, 0.666406, -855253e-8, 0.471508, 0.0120898, 0.666428, -0.0116401, 0.471519, 0.0164569, 0.666444, -0.0152015, 0.471522, 0.0214971, 0.66649, -0.0192362, 0.471543, 0.027212, 0.666537, -0.0237428, 0.471558, 0.033603, 0.666617, -0.0287198, 0.471591, 0.0406728, 0.666718, -0.0341647, 0.471631, 0.0484238, 0.666889, -0.0400759, 0.47171, 0.0568621, 0.667104, -0.0464479, 0.471805, 0.0659915, 0.667374, -0.0532677, 0.471923, 0.0758178, 0.667772, -0.0603805, 0.472098, 0.0863425, 0.668371, -0.0677392, 0.472363, 0.0975917, 0.668971, -0.0756028, 0.472596, 0.109567, 0.669696, -0.0839293, 0.472869, 0.122272, 0.670481, -0.0926683, 0.473126, 0.135718, 0.6715, -0.1016, 0.473442, 0.149914, 0.672911, -0.110566, 0.47389, 0.164882, 0.674512, -0.119984, 0.474354, 0.180602, 0.67651, -0.129574, 0.474922, 0.19711, 0.679292, -0.139106, 0.475764, 0.214371, 0.682798, -0.148993, 0.476886, 0.232405, 0.686955, -0.158737, 0.478179, 0.251153, 0.691406, -0.168754, 0.479432, 0.270436, 0.697438, -0.178703, 0.481481, 0.290374, 0.704761, -0.188955, 0.484143, 0.311044, 0.713599, -0.198814, 0.487007, 0.333003, 0.723194, -0.207869, 0.488962, 0.357144, 0.732601, -0.216189, 0.489815, 0.382169, 0.744193, -0.22398, 0.490888, 0.408227, 0.754907, -0.231156, 0.490355, 0.434928, 0.767403, -0.23747, 0.489548, 0.462599, 0.78107, -0.243503, 0.488274, 0.490908, 0.793893, -0.248114, 0.484843, 0.519421, 0.807296, -0.25222, 0.4803, 0.548561, 0.820529, -0.255265, 0.474097, 0.577772, 0.833716, -0.256741, 0.466041, 0.607782, 0.848403, -0.25637, 0.456547, 0.638807, 0.860755, -0.254804, 0.443946, 0.670058, 0.874012, -0.251834, 0.430852, 0.700749, 0.885619, -0.247867, 0.414903, 0.731446, 0.896069, -0.242634, 0.397276, 0.761191, 0.906266, -0.236093, 0.378535, 0.791053, 0.916759, -0.227543, 0.358038, 0.821298, 0.92523, -0.21783, 0.335705, 0.850747, 0.93436, -0.207534, 0.313797, 0.879258, 0.941631, -0.195983, 0.289671, 0.907734, 0.947564, -0.183567, 0.265319, 0.935206, 0.953681, -0.169345, 0.240815, 0.962739, 0.960008, -0.154909, 0.216119, 0.989227, 0.964145, -0.140161, 0.192096, 1.01465, 0.968171, -0.123411, 0.167855, 1.03737, 0.969859, -0.106525, 0.144817, 1.05767, 0.972666, -0.0891023, 0.12149, 1.0761, 0.977055, -0.0718094, 0.0975306, 1.09336, 0.982527, -0.0534213, 0.0730217, 1.10878, 0.989001, -0.0355579, 0.0483366, 1.12285, 0.99512, -0.0176383, 0.023938, 1.13548, 1.00007, 368831e-9, -211581e-9, 1.14744, 0.651047, -960845e-11, 0.484101, 12922e-9, 0.644145, -241347e-9, 0.478968, 324578e-9, 0.64396, -965142e-9, 0.478831, 129798e-8, 0.64396, -217154e-8, 0.47883, 292046e-8, 0.643968, -386049e-8, 0.478835, 519202e-8, 0.643974, -603186e-8, 0.478838, 81128e-7, 0.643977, -86854e-7, 0.478836, 0.011683, 0.643982, -0.0118207, 0.478834, 0.0159031, 0.644024, -0.0154374, 0.478856, 0.0207743, 0.644059, -0.0195343, 0.478868, 0.0262975, 0.644122, -0.0241103, 0.478896, 0.0324747, 0.644207, -0.0291638, 0.478933, 0.039309, 0.64432, -0.0346919, 0.478981, 0.0468029, 0.644481, -0.0406919, 0.479053, 0.0549614, 0.644722, -0.047159, 0.479169, 0.0637909, 0.645013, -0.0540748, 0.479302, 0.0732974, 0.645503, -0.0612001, 0.479541, 0.0834898, 0.646117, -0.0687303, 0.479829, 0.0943873, 0.646707, -0.0767846, 0.480061, 0.105991, 0.647431, -0.0852465, 0.480343, 0.11831, 0.64831, -0.0940719, 0.48066, 0.131348, 0.649486, -0.103056, 0.481083, 0.14514, 0.650864, -0.112261, 0.481528, 0.159676, 0.652604, -0.121852, 0.482102, 0.174979, 0.654825, -0.131505, 0.482813, 0.191079, 0.657876, -0.141189, 0.483876, 0.207927, 0.661339, -0.151239, 0.48499, 0.225586, 0.665463, -0.161091, 0.486279, 0.243947, 0.670542, -0.171235, 0.487968, 0.262957, 0.677361, -0.181347, 0.49053, 0.282781, 0.685672, -0.191679, 0.493862, 0.303311, 0.694551, -0.201781, 0.49699, 0.324607, 0.703753, -0.211164, 0.498884, 0.347916, 0.713703, -0.219675, 0.500086, 0.372628, 0.725911, -0.227836, 0.501554, 0.398694, 0.73862, -0.23533, 0.502193, 0.425529, 0.752118, -0.241786, 0.501811, 0.453209, 0.76579, -0.247865, 0.500185, 0.481381, 0.779568, -0.252696, 0.497159, 0.51011, 0.793991, -0.256802, 0.492765, 0.539322, 0.808182, -0.259942, 0.486827, 0.569078, 0.821698, -0.261703, 0.478386, 0.598818, 0.836009, -0.262006, 0.468772, 0.629762, 0.849824, -0.260333, 0.456352, 0.661366, 0.863888, -0.257398, 0.442533, 0.69295, 0.876585, -0.253264, 0.426573, 0.723608, 0.888665, -0.248026, 0.408964, 0.754378, 0.899537, -0.241487, 0.389677, 0.784761, 0.9094, -0.233463, 0.368516, 0.814688, 0.920166, -0.223397, 0.346624, 0.845009, 0.928899, -0.21255, 0.322717, 0.874431, 0.937156, -0.200869, 0.298698, 0.902922, 0.943861, -0.188387, 0.273491, 0.931356, 0.949557, -0.174341, 0.247866, 0.958854, 0.955862, -0.158994, 0.222496, 0.986098, 0.961721, -0.143664, 0.197522, 1.01229, 0.965976, -0.127412, 0.17302, 1.03571, 0.968652, -0.109798, 0.148954, 1.05699, 0.971084, -0.0916787, 0.125044, 1.07587, 0.975584, -0.0739634, 0.100577, 1.09372, 0.98122, -0.055322, 0.0753666, 1.10948, 0.988253, -0.0366825, 0.0498899, 1.12394, 0.99482, -0.0180389, 0.024611, 1.13694, 1.00001, 229839e-9, -188283e-9, 1.14919, 0.613867, -964198e-11, 0.479449, 123452e-10, 0.621485, -244534e-9, 0.485399, 313091e-9, 0.621429, -978202e-9, 0.485353, 125245e-8, 0.62112, -220004e-8, 0.485114, 281687e-8, 0.621119, -39111e-7, 0.485112, 500783e-8, 0.621122, -611091e-8, 0.485112, 782498e-8, 0.621133, -879922e-8, 0.485117, 0.0112687, 0.621152, -0.0119756, 0.485125, 0.0153394, 0.621183, -0.0156396, 0.485139, 0.0200382, 0.621227, -0.0197898, 0.485158, 0.0253663, 0.621298, -0.0244253, 0.485192, 0.0313261, 0.621388, -0.0295441, 0.485233, 0.0379204, 0.621507, -0.0351432, 0.485286, 0.0451523, 0.621693, -0.0412198, 0.485378, 0.0530277, 0.621933, -0.0477673, 0.485495, 0.0615522, 0.622232, -0.0547574, 0.485635, 0.0707316, 0.622809, -0.0619417, 0.485943, 0.0805883, 0.623407, -0.069625, 0.486232, 0.0911267, 0.62406, -0.077796, 0.486516, 0.102354, 0.624835, -0.0863731, 0.486838, 0.114279, 0.625758, -0.095251, 0.487188, 0.126902, 0.627043, -0.104299, 0.487695, 0.140285, 0.628438, -0.113724, 0.488163, 0.154397, 0.630325, -0.123417, 0.488858, 0.169267, 0.632801, -0.133137, 0.489754, 0.184941, 0.635784, -0.143052, 0.490815, 0.20136, 0.639406, -0.153132, 0.492048, 0.218643, 0.643872, -0.163143, 0.49363, 0.236615, 0.6499, -0.17333, 0.496009, 0.255449, 0.657201, -0.183622, 0.498994, 0.275006, 0.666221, -0.194019, 0.502888, 0.295354, 0.674419, -0.204192, 0.505459, 0.316244, 0.683729, -0.21406, 0.507771, 0.33849, 0.695584, -0.222854, 0.510245, 0.363166, 0.708583, -0.231315, 0.512293, 0.389071, 0.721233, -0.238911, 0.512747, 0.415737, 0.735134, -0.245657, 0.512482, 0.443331, 0.750179, -0.251879, 0.511526, 0.471891, 0.765073, -0.256911, 0.508935, 0.500892, 0.779794, -0.261144, 0.504341, 0.530294, 0.794801, -0.264316, 0.498515, 0.560144, 0.810339, -0.266276, 0.491015, 0.590213, 0.824818, -0.266981, 0.481126, 0.620865, 0.839375, -0.265778, 0.468685, 0.652687, 0.853043, -0.262748, 0.453925, 0.684759, 0.867335, -0.258474, 0.437912, 0.716209, 0.88037, -0.253187, 0.419648, 0.747508, 0.891711, -0.246476, 0.39982, 0.77797, 0.902896, -0.238735, 0.37879, 0.808586, 0.913601, -0.22885, 0.355891, 0.838843, 0.923019, -0.217656, 0.331773, 0.869014, 0.933432, -0.205539, 0.307356, 0.898512, 0.939691, -0.192595, 0.281321, 0.9269, 0.946938, -0.178945, 0.255441, 0.955297, 0.952372, -0.163587, 0.229013, 0.983231, 0.95909, -0.147214, 0.203179, 1.00971, 0.963675, -0.13064, 0.17792, 1.03438, 0.968247, -0.113121, 0.152898, 1.05625, 0.97001, -0.0945824, 0.128712, 1.07598, 0.974458, -0.0755648, 0.103349, 1.094, 0.980168, -0.0571998, 0.0776731, 1.1104, 0.987295, -0.0377994, 0.0514445, 1.12491, 0.994432, -0.0186417, 0.025429, 1.13851, 0.999975, 542714e-9, -282356e-9, 1.15108, 0.592656, -980249e-11, 0.486018, 119532e-10, 0.598467, -247275e-9, 0.490781, 301531e-9, 0.597934, -988317e-9, 0.490343, 120517e-8, 0.597903, -222366e-8, 0.490319, 27116e-7, 0.597913, -395315e-8, 0.490327, 482077e-8, 0.597919, -617653e-8, 0.490329, 753264e-8, 0.597936, -889375e-8, 0.490339, 0.0108478, 0.597956, -0.0121043, 0.490347, 0.0147668, 0.597992, -0.0158073, 0.490365, 0.0192905, 0.598032, -0.0200017, 0.490382, 0.0244204, 0.598109, -0.0246865, 0.49042, 0.0301593, 0.598215, -0.0298594, 0.490474, 0.03651, 0.59833, -0.0355167, 0.490524, 0.0434757, 0.598525, -0.0416559, 0.490624, 0.0510629, 0.598778, -0.0482692, 0.490753, 0.0592781, 0.599135, -0.0553114, 0.49094, 0.0681304, 0.599802, -0.062542, 0.491328, 0.0776467, 0.600361, -0.0703638, 0.491598, 0.0878184, 0.60101, -0.0786256, 0.491882, 0.0986573, 0.601811, -0.0872962, 0.492232, 0.11018, 0.602861, -0.0962284, 0.492684, 0.1224, 0.604167, -0.10538, 0.493213, 0.135354, 0.605693, -0.114896, 0.493799, 0.149034, 0.607682, -0.124654, 0.494576, 0.163469, 0.610672, -0.13456, 0.4959, 0.178747, 0.613313, -0.144581, 0.496713, 0.194723, 0.617603, -0.154703, 0.498499, 0.211617, 0.622174, -0.16489, 0.500188, 0.229183, 0.628855, -0.175164, 0.503072, 0.247786, 0.636963, -0.185565, 0.506798, 0.267116, 0.644866, -0.195911, 0.509719, 0.28702, 0.653741, -0.206104, 0.512776, 0.307763, 0.664942, -0.216447, 0.516812, 0.329631, 0.67633, -0.22552, 0.519181, 0.353515, 0.690012, -0.234316, 0.521681, 0.379226, 0.704243, -0.242032, 0.523129, 0.405901, 0.719396, -0.249172, 0.523768, 0.433585, 0.734471, -0.255543, 0.522541, 0.462085, 0.750539, -0.260697, 0.520217, 0.491233, 0.766365, -0.26501, 0.516293, 0.521094, 0.781677, -0.268409, 0.509708, 0.551014, 0.797132, -0.270399, 0.501944, 0.581463, 0.812655, -0.271247, 0.492025, 0.612402, 0.828592, -0.270708, 0.480424, 0.643798, 0.844044, -0.268085, 0.465955, 0.67682, 0.857305, -0.263459, 0.448425, 0.708496, 0.87114, -0.258151, 0.430243, 0.74046, 0.884936, -0.251171, 0.410578, 0.771583, 0.895772, -0.243305, 0.38862, 0.802234, 0.906961, -0.234037, 0.365214, 0.833179, 0.917775, -0.222714, 0.34116, 0.86353, 0.927883, -0.210175, 0.31572, 0.893557, 0.936617, -0.196925, 0.289159, 0.922976, 0.943384, -0.182788, 0.261996, 0.951606, 0.949713, -0.167965, 0.235324, 0.979958, 0.955818, -0.151109, 0.208408, 1.00765, 0.961344, -0.133834, 0.182591, 1.03329, 0.965469, -0.115987, 0.156958, 1.0557, 0.968693, -0.09746, 0.132239, 1.07583, 0.973165, -0.0778514, 0.106195, 1.09451, 0.979387, -0.0585067, 0.0797669, 1.11137, 0.98671, -0.0390409, 0.0530263, 1.12643, 0.994093, -0.019408, 0.0263163, 1.14016, 1.00002, 540029e-9, -194487e-9, 1.15299, 0.574483, -989066e-11, 0.494533, 114896e-10, 0.574478, -249127e-9, 0.494528, 289403e-9, 0.574607, -996811e-9, 0.494637, 115797e-8, 0.574396, -224241e-8, 0.494458, 260498e-8, 0.574377, -398632e-8, 0.49444, 463102e-8, 0.574386, -622836e-8, 0.494445, 723623e-8, 0.574401, -89683e-7, 0.494453, 0.010421, 0.574419, -0.0122056, 0.49446, 0.0141859, 0.574459, -0.0159396, 0.494481, 0.0185322, 0.574525, -0.0201692, 0.49452, 0.0234617, 0.574587, -0.0248924, 0.494547, 0.0289762, 0.574697, -0.0301074, 0.494604, 0.0350797, 0.574853, -0.0358114, 0.494688, 0.0417767, 0.575027, -0.041999, 0.494772, 0.0490718, 0.575294, -0.0486618, 0.494915, 0.0569728, 0.575733, -0.0557148, 0.495173, 0.0654955, 0.576356, -0.0630489, 0.495537, 0.0746612, 0.576944, -0.0709285, 0.495836, 0.0844615, 0.57765, -0.0792723, 0.496177, 0.0949142, 0.578491, -0.0880167, 0.496563, 0.10603, 0.579639, -0.0969462, 0.497096, 0.117841, 0.580989, -0.10622, 0.497684, 0.130367, 0.582587, -0.115861, 0.498337, 0.143609, 0.584951, -0.125605, 0.499414, 0.157625, 0.587602, -0.135608, 0.500518, 0.172413, 0.59076, -0.145742, 0.501767, 0.187999, 0.594992, -0.155934, 0.503542, 0.20445, 0.600656, -0.166303, 0.506135, 0.221764, 0.607816, -0.176681, 0.509542, 0.24002, 0.61522, -0.187071, 0.51263, 0.258992, 0.623702, -0.197465, 0.516021, 0.278773, 0.634192, -0.207816, 0.520422, 0.299377, 0.644936, -0.218183, 0.524073, 0.320802, 0.657888, -0.2278, 0.528049, 0.34384, 0.670666, -0.236747, 0.52986, 0.36916, 0.685626, -0.24484, 0.531892, 0.395867, 0.701304, -0.252071, 0.532727, 0.423488, 0.717727, -0.258714, 0.532146, 0.452201, 0.733914, -0.264211, 0.529883, 0.481579, 0.750529, -0.26859, 0.5259, 0.511558, 0.76747, -0.272046, 0.51999, 0.542042, 0.785189, -0.274225, 0.513083, 0.572799, 0.800954, -0.275189, 0.502936, 0.603816, 0.816962, -0.274946, 0.490921, 0.635461, 0.83336, -0.272695, 0.47684, 0.6676, 0.848143, -0.268223, 0.459405, 0.70051, 0.861818, -0.262768, 0.440319, 0.732902, 0.876828, -0.255872, 0.420123, 0.765084, 0.889312, -0.247703, 0.398379, 0.796391, 0.900412, -0.238381, 0.374496, 0.827333, 0.912251, -0.227783, 0.349874, 0.858385, 0.921792, -0.214832, 0.323181, 0.888652, 0.931273, -0.200949, 0.296624, 0.917763, 0.940295, -0.186537, 0.269211, 0.947878, 0.946812, -0.171538, 0.241447, 0.977016, 0.953588, -0.155254, 0.213829, 1.00501, 0.958841, -0.137156, 0.186807, 1.03179, 0.963746, -0.118699, 0.160706, 1.05502, 0.966468, -0.0998358, 0.135504, 1.07568, 0.971178, -0.0805186, 0.109131, 1.09479, 0.97831, -0.0599348, 0.0818293, 1.1123, 0.985886, -0.0399661, 0.0545872, 1.12771, 0.994021, -0.0198682, 0.0269405, 1.14186, 1.00009, 271022e-9, -12989e-8, 1.15514, 0.538716, -990918e-11, 0.486732, 109675e-10, 0.550656, -250642e-9, 0.497518, 277412e-9, 0.55057, -100265e-8, 0.497441, 110974e-8, 0.550903, -225672e-8, 0.497733, 249779e-8, 0.550568, -401046e-8, 0.497438, 443906e-8, 0.550574, -626613e-8, 0.49744, 693637e-8, 0.550591, -90226e-7, 0.497449, 998921e-8, 0.550623, -0.0122795, 0.497469, 0.0135984, 0.550667, -0.0160361, 0.497495, 0.0177654, 0.550724, -0.0202908, 0.497526, 0.0224915, 0.550792, -0.0250421, 0.497557, 0.0277795, 0.550918, -0.0302878, 0.49763, 0.0336334, 0.551058, -0.0360241, 0.497701, 0.0400573, 0.551276, -0.0422473, 0.497824, 0.0470585, 0.551551, -0.0489441, 0.497977, 0.0546433, 0.552074, -0.0559596, 0.498312, 0.0628367, 0.552681, -0.0633978, 0.498679, 0.071646, 0.553324, -0.0713176, 0.499031, 0.0810746, 0.554011, -0.0797268, 0.499365, 0.091129, 0.55488, -0.0885238, 0.499779, 0.101837, 0.556171, -0.0974417, 0.500444, 0.113239, 0.557498, -0.106841, 0.501025, 0.125316, 0.559299, -0.116533, 0.501864, 0.138128, 0.561647, -0.126298, 0.502967, 0.151695, 0.564347, -0.136388, 0.504129, 0.16604, 0.567863, -0.146576, 0.505713, 0.181207, 0.572569, -0.156832, 0.507953, 0.197259, 0.578919, -0.167323, 0.511186, 0.214258, 0.585387, -0.177712, 0.514042, 0.232038, 0.593134, -0.188184, 0.517484, 0.250733, 0.603295, -0.198717, 0.522345, 0.270454, 0.613854, -0.209177, 0.526751, 0.290807, 0.626092, -0.219644, 0.531595, 0.312202, 0.637868, -0.229494, 0.534721, 0.334435, 0.652458, -0.238718, 0.538304, 0.359184, 0.666985, -0.247061, 0.539875, 0.385637, 0.683301, -0.254652, 0.541042, 0.41328, 0.69998, -0.261376, 0.540735, 0.441903, 0.717824, -0.267085, 0.539139, 0.471609, 0.734617, -0.271465, 0.534958, 0.501446, 0.753663, -0.27528, 0.53032, 0.532571, 0.770512, -0.277617, 0.522134, 0.563641, 0.787356, -0.278525, 0.51206, 0.595067, 0.806252, -0.278512, 0.50119, 0.627226, 0.822061, -0.277023, 0.486791, 0.659402, 0.838959, -0.273175, 0.470467, 0.692874, 0.85379, -0.267238, 0.450688, 0.725702, 0.868268, -0.260327, 0.429741, 0.75832, 0.881994, -0.251946, 0.407223, 0.790189, 0.893885, -0.242432, 0.383214, 0.821625, 0.905118, -0.231904, 0.357297, 0.853011, 0.916045, -0.219545, 0.330733, 0.883773, 0.927614, -0.205378, 0.303916, 0.914435, 0.936005, -0.190388, 0.275941, 0.944502, 0.944533, -0.1749, 0.247493, 0.974439, 0.950758, -0.158588, 0.218996, 1.00286, 0.957078, -0.141027, 0.191559, 1.0304, 0.962448, -0.121507, 0.164457, 1.05466, 0.964993, -0.102068, 0.138636, 1.0761, 0.970017, -0.0822598, 0.111861, 1.09541, 0.97661, -0.062033, 0.0843438, 1.11317, 0.985073, -0.0409832, 0.0558496, 1.12911, 0.993515, -0.020146, 0.0275331, 1.1438, 1.00006, 27329e-8, -107883e-9, 1.15736, 0.525324, -999341e-11, 0.498153, 105385e-10, 0.526513, -251605e-9, 0.499277, 265329e-9, 0.526517, -100641e-8, 0.499282, 10613e-7, 0.526588, -226466e-8, 0.499337, 238823e-8, 0.526539, -40255e-7, 0.499302, 424535e-8, 0.526547, -628954e-8, 0.499306, 663364e-8, 0.526561, -905628e-8, 0.499313, 955337e-8, 0.526593, -0.0123253, 0.499334, 0.0130054, 0.526642, -0.0160957, 0.499365, 0.0169911, 0.5267, -0.0203661, 0.499396, 0.0215122, 0.526792, -0.0251347, 0.499451, 0.0265718, 0.526904, -0.0303985, 0.499511, 0.0321732, 0.527079, -0.0361554, 0.499617, 0.0383231, 0.527285, -0.0423982, 0.499731, 0.045026, 0.527602, -0.0491121, 0.499924, 0.0522936, 0.528166, -0.0561127, 0.500306, 0.0601528, 0.52879, -0.0635988, 0.5007, 0.0686059, 0.529421, -0.071581, 0.501048, 0.0776518, 0.530144, -0.0799854, 0.501421, 0.0873148, 0.531062, -0.0888032, 0.501884, 0.0976084, 0.532374, -0.0977643, 0.50259, 0.108588, 0.533828, -0.107197, 0.50329, 0.120234, 0.53581, -0.116887, 0.504312, 0.132602, 0.538063, -0.126755, 0.505365, 0.145721, 0.5409, -0.136819, 0.506668, 0.159617, 0.544882, -0.147117, 0.508731, 0.174369, 0.550238, -0.157446, 0.511601, 0.190028, 0.556038, -0.167988, 0.514431, 0.206587, 0.563031, -0.178364, 0.517808, 0.224046, 0.571543, -0.189007, 0.521937, 0.242503, 0.582255, -0.199546, 0.527415, 0.261977, 0.59272, -0.210084, 0.531682, 0.282162, 0.605648, -0.220448, 0.537123, 0.303426, 0.61785, -0.230593, 0.540664, 0.325323, 0.632223, -0.240238, 0.544467, 0.348993, 0.648819, -0.24887, 0.547594, 0.375462, 0.665825, -0.256657, 0.54912, 0.403024, 0.683389, -0.263711, 0.549294, 0.431773, 0.701495, -0.269666, 0.547649, 0.461494, 0.719197, -0.274169, 0.543786, 0.491623, 0.737906, -0.278124, 0.538644, 0.522994, 0.756652, -0.280632, 0.531057, 0.554775, 0.775279, -0.281741, 0.521972, 0.586441, 0.792688, -0.281652, 0.509613, 0.618596, 0.811894, -0.280345, 0.496497, 0.651462, 0.827938, -0.277128, 0.47968, 0.684023, 0.844837, -0.271646, 0.460688, 0.718024, 0.859239, -0.264397, 0.438872, 0.751207, 0.874088, -0.256144, 0.41577, 0.784232, 0.887693, -0.246311, 0.391369, 0.816191, 0.899402, -0.235497, 0.365872, 0.847828, 0.910973, -0.223631, 0.338618, 0.87934, 0.92204, -0.209874, 0.310803, 0.910325, 0.930987, -0.194265, 0.281802, 0.940695, 0.94, -0.178125, 0.252836, 0.970958, 0.948018, -0.161479, 0.224239, 1.00078, 0.955141, -0.144038, 0.195857, 1.0288, 0.960513, -0.124915, 0.168487, 1.05371, 0.963964, -0.104284, 0.141495, 1.07596, 0.968713, -0.0838732, 0.114437, 1.09628, 0.975524, -0.0635579, 0.0863105, 1.11448, 0.98431, -0.042291, 0.0574774, 1.13069, 0.992916, -0.0209131, 0.0284343, 1.14568, 0.999926, 743097e-9, -379265e-9, 1.15955, 0.501042, -998428e-11, 0.498726, 100306e-10, 0.502992, -252112e-9, 0.500665, 253283e-9, 0.502417, -100791e-8, 0.500092, 101259e-8, 0.502965, -226919e-8, 0.500621, 227978e-8, 0.502318, -403109e-8, 0.499994, 405011e-8, 0.502333, -629832e-8, 0.500005, 632868e-8, 0.502362, -906907e-8, 0.500027, 911446e-8, 0.502369, -0.0123423, 0.500023, 0.0124078, 0.50243, -0.0161178, 0.500066, 0.016211, 0.502493, -0.0203937, 0.500103, 0.0205256, 0.502592, -0.0251684, 0.500166, 0.0253548, 0.502707, -0.0304389, 0.50023, 0.0307029, 0.502881, -0.0362015, 0.500335, 0.0365753, 0.503124, -0.0424507, 0.500488, 0.0429798, 0.503443, -0.0491582, 0.500686, 0.0499268, 0.504083, -0.0561476, 0.501155, 0.0574541, 0.504668, -0.0636846, 0.501524, 0.0655408, 0.505319, -0.0716834, 0.501904, 0.0742072, 0.50609, -0.0800925, 0.502321, 0.0834699, 0.507122, -0.0888425, 0.502896, 0.0933603, 0.508414, -0.097855, 0.503603, 0.10391, 0.509955, -0.107304, 0.504416, 0.115113, 0.512061, -0.116921, 0.505565, 0.127054, 0.514419, -0.12689, 0.506732, 0.139709, 0.517529, -0.136934, 0.508338, 0.153173, 0.522085, -0.147327, 0.510987, 0.167528, 0.526986, -0.157612, 0.513527, 0.182708, 0.533122, -0.168213, 0.516717, 0.198881, 0.540807, -0.178688, 0.520832, 0.215986, 0.550687, -0.189511, 0.52632, 0.234335, 0.560567, -0.199998, 0.531009, 0.253375, 0.571698, -0.210652, 0.535839, 0.273499, 0.584364, -0.220917, 0.541091, 0.294355, 0.599066, -0.23137, 0.546875, 0.316525, 0.614148, -0.241206, 0.551306, 0.339671, 0.631157, -0.250379, 0.555187, 0.36531, 0.647919, -0.258397, 0.556595, 0.392767, 0.666112, -0.265528, 0.556949, 0.421397, 0.686158, -0.271827, 0.556617, 0.451433, 0.704838, -0.27674, 0.552975, 0.482131, 0.723957, -0.280733, 0.547814, 0.513458, 0.74262, -0.283359, 0.53997, 0.545446, 0.762009, -0.284541, 0.530422, 0.57775, 0.781314, -0.284507, 0.518546, 0.610434, 0.799116, -0.283309, 0.504178, 0.643178, 0.817604, -0.280378, 0.48843, 0.676248, 0.83459, -0.275619, 0.469457, 0.709698, 0.850974, -0.26856, 0.447698, 0.744245, 0.866747, -0.260094, 0.424791, 0.777695, 0.881412, -0.249929, 0.399913, 0.810392, 0.8936, -0.239137, 0.37308, 0.842872, 0.905943, -0.226818, 0.345705, 0.874677, 0.916408, -0.213699, 0.31706, 0.906257, 0.927215, -0.198428, 0.288444, 0.936881, 0.935625, -0.181643, 0.258329, 0.96795, 0.944076, -0.164386, 0.228488, 0.998216, 0.951229, -0.146339, 0.199763, 1.02689, 0.958793, -0.127709, 0.172153, 1.0535, 0.963219, -0.107244, 0.144989, 1.07646, 0.967562, -0.0857764, 0.11685, 1.09675, 0.974866, -0.0645377, 0.0880571, 1.11576, 0.983353, -0.0431732, 0.0587352, 1.13227, 0.992503, -0.0218356, 0.0294181, 1.1478, 1.00003, 605203e-9, -231013e-9, 1.16207, 0.482935, -101177e-10, 0.504695, 968142e-11, 0.477554, -251521e-9, 0.499071, 240676e-9, 0.477904, -100683e-8, 0.499436, 96342e-8, 0.478368, -226636e-8, 0.499899, 21687e-7, 0.477977, -402719e-8, 0.499513, 385384e-8, 0.477993, -629226e-8, 0.499525, 60221e-7, 0.478011, -906011e-8, 0.499536, 867289e-8, 0.478051, -0.0123305, 0.499566, 0.0118074, 0.478089, -0.016102, 0.499587, 0.0154269, 0.478171, -0.0203736, 0.499645, 0.0195341, 0.478254, -0.025143, 0.499692, 0.0241318, 0.47839, -0.0304071, 0.499779, 0.0292247, 0.478588, -0.0361631, 0.499911, 0.0348196, 0.478812, -0.0424023, 0.500046, 0.0409231, 0.479208, -0.0490724, 0.500326, 0.047552, 0.479841, -0.0560722, 0.500805, 0.0547377, 0.480392, -0.0636125, 0.501152, 0.0624607, 0.481068, -0.0716134, 0.501561, 0.0707473, 0.481898, -0.0800062, 0.502054, 0.0796118, 0.483022, -0.0886568, 0.502728, 0.0890974, 0.484332, -0.0977553, 0.503479, 0.0992099, 0.486126, -0.107173, 0.504546, 0.10999, 0.488066, -0.11677, 0.50557, 0.121476, 0.490521, -0.126725, 0.506849, 0.133672, 0.494232, -0.136793, 0.50911, 0.146731, 0.498302, -0.147116, 0.511345, 0.160577, 0.503565, -0.157446, 0.514344, 0.175335, 0.510902, -0.168121, 0.518824, 0.191207, 0.519263, -0.178799, 0.523666, 0.208058, 0.528204, -0.189407, 0.528296, 0.225875, 0.538854, -0.200145, 0.533724, 0.244782, 0.551278, -0.210701, 0.539833, 0.264753, 0.565222, -0.221303, 0.546131, 0.285745, 0.579403, -0.231688, 0.551496, 0.307592, 0.595469, -0.241718, 0.556809, 0.330582, 0.610929, -0.250992, 0.559641, 0.354995, 0.629433, -0.259602, 0.562379, 0.382471, 0.648504, -0.267038, 0.563676, 0.411126, 0.66756, -0.273388, 0.562092, 0.440924, 0.689143, -0.278788, 0.560807, 0.472118, 0.709056, -0.282783, 0.555701, 0.503774, 0.729855, -0.285836, 0.548698, 0.536364, 0.748954, -0.287078, 0.538544, 0.56895, 0.768373, -0.287133, 0.526711, 0.601991, 0.78827, -0.285839, 0.512511, 0.635403, 0.807465, -0.283238, 0.496323, 0.668797, 0.825194, -0.27906, 0.477638, 0.702584, 0.842203, -0.272286, 0.456253, 0.736393, 0.857749, -0.263854, 0.432412, 0.77096, 0.874799, -0.253943, 0.407806, 0.80489, 0.887497, -0.24237, 0.38033, 0.83771, 0.89966, -0.230278, 0.352446, 0.870376, 0.911753, -0.21646, 0.323268, 0.902256, 0.923011, -0.202071, 0.294314, 0.933306, 0.932375, -0.185519, 0.264104, 0.965177, 0.940537, -0.167604, 0.234035, 0.996303, 0.948904, -0.149068, 0.20412, 1.0261, 0.955263, -0.129539, 0.175431, 1.05304, 0.960303, -0.109932, 0.148116, 1.07617, 0.965512, -0.0880572, 0.119693, 1.09742, 0.973466, -0.0660548, 0.0901619, 1.11721, 0.98284, -0.0439228, 0.0599875, 1.13436, 0.992216, -0.0219588, 0.0298975, 1.15006, 0.999946, 119402e-9, -208547e-10, 1.16471, 0.447827, -100414e-10, 0.491543, 914833e-11, 0.454778, -251257e-9, 0.499172, 22891e-8, 0.453519, -100342e-8, 0.497787, 914184e-9, 0.45357, -225776e-8, 0.497847, 205701e-8, 0.453578, -401371e-8, 0.497855, 365705e-8, 0.45357, -627107e-8, 0.497841, 571453e-8, 0.453598, -902968e-8, 0.497864, 823019e-8, 0.453627, -0.0122888, 0.497882, 0.0112049, 0.453684, -0.0160475, 0.497923, 0.0146405, 0.453764, -0.0203044, 0.49798, 0.0185394, 0.453866, -0.0250576, 0.498049, 0.0229054, 0.453996, -0.0303028, 0.49813, 0.0277424, 0.454196, -0.0360379, 0.498267, 0.0330587, 0.454457, -0.0422521, 0.498445, 0.0388613, 0.454926, -0.0488393, 0.498812, 0.0451767, 0.455525, -0.0558653, 0.499272, 0.0520153, 0.456074, -0.0633772, 0.499625, 0.0593754, 0.456752, -0.0713606, 0.500049, 0.0672751, 0.457648, -0.07971, 0.500615, 0.0757447, 0.458849, -0.0883032, 0.501399, 0.0848231, 0.46029, -0.0974095, 0.502293, 0.0945135, 0.462, -0.106729, 0.503301, 0.104848, 0.464121, -0.116354, 0.504533, 0.115884, 0.466889, -0.126214, 0.506172, 0.127652, 0.470744, -0.136324, 0.508667, 0.14024, 0.47488, -0.146595, 0.510995, 0.153673, 0.480845, -0.157027, 0.514832, 0.168053, 0.488262, -0.167658, 0.519506, 0.183508, 0.496547, -0.178343, 0.524347, 0.199948, 0.506254, -0.188916, 0.52983, 0.217503, 0.517961, -0.199975, 0.536357, 0.236272, 0.531484, -0.210624, 0.543641, 0.256096, 0.545496, -0.221227, 0.550048, 0.277085, 0.559497, -0.231568, 0.555076, 0.298615, 0.575752, -0.241698, 0.560541, 0.321547, 0.591999, -0.251172, 0.564156, 0.345602, 0.610654, -0.260178, 0.567607, 0.371851, 0.630484, -0.268094, 0.56923, 0.40076, 0.651807, -0.274661, 0.569779, 0.430801, 0.67239, -0.280331, 0.566791, 0.461939, 0.693024, -0.284501, 0.562007, 0.493854, 0.715473, -0.287852, 0.555791, 0.526992, 0.736323, -0.28929, 0.546345, 0.560102, 0.755771, -0.289405, 0.534, 0.593543, 0.775424, -0.2881, 0.519114, 0.627256, 0.795447, -0.285562, 0.502543, 0.661464, 0.815319, -0.281416, 0.484773, 0.695206, 0.831769, -0.275523, 0.463445, 0.729044, 0.849464, -0.267516, 0.440269, 0.764069, 0.866775, -0.257584, 0.415049, 0.799089, 0.881252, -0.245817, 0.388049, 0.831948, 0.894209, -0.233127, 0.35889, 0.865526, 0.906922, -0.219579, 0.329915, 0.89818, 0.919686, -0.204491, 0.300441, 0.930013, 0.929044, -0.188962, 0.269445, 0.962061, 0.938393, -0.171079, 0.238402, 0.994214, 0.94661, -0.15199, 0.208204, 1.02533, 0.953095, -0.131953, 0.178653, 1.0529, 0.958644, -0.111233, 0.150684, 1.0771, 0.963925, -0.0903098, 0.122359, 1.09855, 0.971995, -0.0680505, 0.0923342, 1.11874, 0.981658, -0.0448512, 0.0614195, 1.13635, 0.991649, -0.0221931, 0.0303582, 1.15238, 0.999985, 393403e-9, -111086e-9, 1.16772, 0.396806, -971563e-11, 0.457671, 842355e-11, 0.429186, -249421e-9, 0.495017, 21625e-8, 0.429324, -998052e-9, 0.495173, 865322e-9, 0.429175, -224487e-8, 0.494999, 194637e-8, 0.429129, -399041e-8, 0.494952, 346004e-8, 0.429153, -623476e-8, 0.494974, 540684e-8, 0.429168, -89773e-7, 0.494983, 778714e-8, 0.429207, -0.0122175, 0.495012, 0.0106022, 0.429257, -0.0159542, 0.495047, 0.0138535, 0.429338, -0.0201864, 0.495106, 0.0175443, 0.429431, -0.0249104, 0.495165, 0.0216774, 0.429587, -0.0301252, 0.495279, 0.0262594, 0.429796, -0.0358249, 0.495432, 0.0312968, 0.430065, -0.0419972, 0.495621, 0.0367985, 0.430588, -0.0485144, 0.496061, 0.042798, 0.43113, -0.0555028, 0.496472, 0.0492914, 0.431743, -0.0629852, 0.496904, 0.0562907, 0.432448, -0.0709256, 0.497369, 0.0638056, 0.433414, -0.0791942, 0.498032, 0.071885, 0.434638, -0.0877346, 0.498854, 0.0805517, 0.43611, -0.0968056, 0.499812, 0.0898047, 0.437859, -0.106002, 0.500891, 0.0997142, 0.440017, -0.115648, 0.502198, 0.110289, 0.443236, -0.125427, 0.504389, 0.121644, 0.44697, -0.135492, 0.506809, 0.133769, 0.451689, -0.145746, 0.509858, 0.146787, 0.45811, -0.156219, 0.514247, 0.160793, 0.465305, -0.166834, 0.518816, 0.175791, 0.474085, -0.177546, 0.524331, 0.191906, 0.484808, -0.188262, 0.53104, 0.209199, 0.49732, -0.199346, 0.538511, 0.227825, 0.509693, -0.209951, 0.544554, 0.247269, 0.524367, -0.220533, 0.551616, 0.267978, 0.539228, -0.231082, 0.557368, 0.289672, 0.55644, -0.241342, 0.563782, 0.31268, 0.574204, -0.250964, 0.568851, 0.33651, 0.593388, -0.260306, 0.57312, 0.362219, 0.613358, -0.268667, 0.574916, 0.390322, 0.634512, -0.275591, 0.575053, 0.420478, 0.65563, -0.281328, 0.572404, 0.451614, 0.678265, -0.285948, 0.568893, 0.484112, 0.70011, -0.289408, 0.561878, 0.517348, 0.723005, -0.291328, 0.55359, 0.551355, 0.743744, -0.291418, 0.541099, 0.585109, 0.763949, -0.290252, 0.526489, 0.619487, 0.784186, -0.287648, 0.509496, 0.65404, 0.804304, -0.283782, 0.491484, 0.688649, 0.823629, -0.278067, 0.470517, 0.723133, 0.84094, -0.270588, 0.44705, 0.757163, 0.857852, -0.261188, 0.421252, 0.792816, 0.874934, -0.249313, 0.394191, 0.827248, 0.888709, -0.236492, 0.365359, 0.861074, 0.902589, -0.222185, 0.336016, 0.894417, 0.914201, -0.207314, 0.30527, 0.926825, 0.925978, -0.191146, 0.274532, 0.9595, 0.93512, -0.174135, 0.243393, 0.991583, 0.943656, -0.155231, 0.212414, 1.02356, 0.951719, -0.134403, 0.182005, 1.05239, 0.957164, -0.113023, 0.153043, 1.07754, 0.962656, -0.0914493, 0.124186, 1.09984, 0.970695, -0.0694179, 0.0941654, 1.12, 0.980749, -0.0466199, 0.0629671, 1.13849, 0.991205, -0.0227032, 0.0311146, 1.15494, 0.999884, 632388e-9, -254483e-9, 1.1706, 0.379821, -957289e-11, 0.460637, 789337e-11, 0.405188, -247483e-9, 0.491396, 204064e-9, 0.404796, -989434e-9, 0.490914, 815853e-9, 0.40483, -222607e-8, 0.490949, 183559e-8, 0.40473, -395723e-8, 0.49084, 326332e-8, 0.404731, -618287e-8, 0.490836, 509945e-8, 0.404768, -890258e-8, 0.490871, 734463e-8, 0.404791, -0.0121156, 0.490883, 999992e-8, 0.404857, -0.0158214, 0.490938, 0.0130676, 0.404943, -0.0200178, 0.491004, 0.0165503, 0.405059, -0.0247027, 0.491093, 0.0204521, 0.405213, -0.0298729, 0.491205, 0.0247788, 0.405399, -0.0355226, 0.491333, 0.0295373, 0.405731, -0.0416352, 0.491604, 0.034741, 0.406303, -0.0480807, 0.492116, 0.0404255, 0.406814, -0.0550458, 0.492506, 0.0465732, 0.407404, -0.0624652, 0.492926, 0.0532058, 0.408149, -0.0702958, 0.493442, 0.0603442, 0.409128, -0.0784623, 0.494136, 0.0680297, 0.410408, -0.087007, 0.495054, 0.0762786, 0.411813, -0.0959639, 0.495962, 0.0851046, 0.413735, -0.105075, 0.497257, 0.0945878, 0.416137, -0.114646, 0.498882, 0.104725, 0.41934, -0.124394, 0.501132, 0.11563, 0.423326, -0.134328, 0.503883, 0.127325, 0.428419, -0.14458, 0.50747, 0.139911, 0.43484, -0.154979, 0.511964, 0.153481, 0.442641, -0.165628, 0.517328, 0.168114, 0.452511, -0.176365, 0.524258, 0.183995, 0.463473, -0.187298, 0.531248, 0.200953, 0.475564, -0.198244, 0.538367, 0.219176, 0.488664, -0.208938, 0.545175, 0.238514, 0.504073, -0.219599, 0.553227, 0.259129, 0.520832, -0.230378, 0.560653, 0.280997, 0.538455, -0.240703, 0.567523, 0.303821, 0.55709, -0.250548, 0.573287, 0.327948, 0.576646, -0.259964, 0.577795, 0.353362, 0.596705, -0.268721, 0.580077, 0.380336, 0.618053, -0.276054, 0.58018, 0.4101, 0.640303, -0.282176, 0.578747, 0.44161, 0.662365, -0.286931, 0.574294, 0.474106, 0.684542, -0.290521, 0.567035, 0.507549, 0.707984, -0.292672, 0.558687, 0.541853, 0.730913, -0.293189, 0.547606, 0.576581, 0.752948, -0.292199, 0.533471, 0.61172, 0.773452, -0.289508, 0.516395, 0.646339, 0.794715, -0.285716, 0.497873, 0.682131, 0.814251, -0.280051, 0.476845, 0.716396, 0.833057, -0.272873, 0.453449, 0.751503, 0.84959, -0.263982, 0.427857, 0.786085, 0.867022, -0.252745, 0.400335, 0.821355, 0.882277, -0.239655, 0.371304, 0.85646, 0.895375, -0.225386, 0.340397, 0.890828, 0.909347, -0.209587, 0.310005, 0.923532, 0.921885, -0.193433, 0.2796, 0.956419, 0.932127, -0.176135, 0.247276, 0.989445, 0.941869, -0.157872, 0.216186, 1.02221, 0.949735, -0.137577, 0.185602, 1.05195, 0.956617, -0.115285, 0.155767, 1.07822, 0.961974, -0.0928418, 0.126103, 1.10149, 0.96972, -0.0700592, 0.0956758, 1.12207, 0.98012, -0.0474671, 0.0643269, 1.1408, 0.990825, -0.0238113, 0.0320863, 1.1577, 0.999876, 381574e-9, -812203e-10, 1.17403, 0.367636, -961342e-11, 0.469176, 753287e-11, 0.380377, -244772e-9, 0.485434, 191797e-9, 0.380416, -978857e-9, 0.485475, 767015e-9, 0.380376, -220165e-8, 0.485435, 172522e-8, 0.380419, -391408e-8, 0.485487, 306734e-8, 0.380438, -611549e-8, 0.485505, 479332e-8, 0.380462, -880558e-8, 0.485525, 690391e-8, 0.380496, -0.0119837, 0.485551, 940039e-8, 0.38056, -0.0156487, 0.485605, 0.0122848, 0.38064, -0.0197988, 0.485666, 0.0155601, 0.380767, -0.0244324, 0.48577, 0.0192313, 0.380909, -0.0295444, 0.485871, 0.0233032, 0.381142, -0.0351321, 0.48606, 0.0277861, 0.381472, -0.0411535, 0.486336, 0.0326939, 0.382015, -0.0475408, 0.486833, 0.0380565, 0.382523, -0.0544395, 0.487231, 0.0438615, 0.383129, -0.061784, 0.487683, 0.0501332, 0.383952, -0.0695085, 0.488313, 0.0568996, 0.38498, -0.0775819, 0.489077, 0.0641952, 0.386331, -0.0860443, 0.490113, 0.0720324, 0.387788, -0.0948406, 0.491099, 0.0804379, 0.389808, -0.103899, 0.492566, 0.0894899, 0.39252, -0.113313, 0.494601, 0.0992098, 0.395493, -0.123007, 0.496619, 0.109641, 0.399826, -0.132859, 0.499912, 0.120919, 0.405341, -0.143077, 0.504061, 0.133107, 0.411932, -0.153465, 0.508905, 0.146263, 0.420591, -0.164108, 0.515482, 0.160544, 0.43101, -0.174893, 0.523191, 0.176123, 0.441881, -0.185839, 0.53026, 0.192757, 0.453919, -0.196633, 0.537295, 0.210535, 0.468715, -0.207611, 0.546156, 0.229886, 0.485182, -0.218517, 0.555173, 0.250543, 0.501926, -0.229249, 0.562728, 0.27221, 0.51785, -0.239481, 0.567494, 0.294892, 0.536947, -0.249395, 0.573889, 0.318987, 0.557115, -0.259, 0.578831, 0.344348, 0.577966, -0.268075, 0.582055, 0.371223, 0.599489, -0.276115, 0.583307, 0.399834, 0.62479, -0.282523, 0.583902, 0.431415, 0.647504, -0.287663, 0.57953, 0.464301, 0.670601, -0.291538, 0.573103, 0.498123, 0.693539, -0.293842, 0.563731, 0.532662, 0.717385, -0.294681, 0.553169, 0.567925, 0.741533, -0.293717, 0.539908, 0.603502, 0.762142, -0.291156, 0.521902, 0.639074, 0.783014, -0.28719, 0.502815, 0.674439, 0.805158, -0.281773, 0.482598, 0.710497, 0.823646, -0.274682, 0.458949, 0.7456, 0.841879, -0.266184, 0.433129, 0.781085, 0.859515, -0.255682, 0.406064, 0.816, 0.875335, -0.242849, 0.376509, 0.851074, 0.890147, -0.228329, 0.345502, 0.886473, 0.903144, -0.212491, 0.31428, 0.920751, 0.916618, -0.195695, 0.282994, 0.954606, 0.927953, -0.178267, 0.251091, 0.988402, 0.937414, -0.159549, 0.219107, 1.02141, 0.946823, -0.140022, 0.18896, 1.05167, 0.954651, -0.118154, 0.158667, 1.07819, 0.959955, -0.0946636, 0.128808, 1.1025, 0.96858, -0.0711792, 0.0973787, 1.12391, 0.97938, -0.0475046, 0.0650965, 1.14322, 0.990498, -0.024059, 0.0326267, 1.16077, 0.999844, -512408e-10, 112444e-9, 1.17727, 0.316912, -934977e-11, 0.425996, 695559e-11, 0.356423, -241372e-9, 0.479108, 179562e-9, 0.356272, -965292e-9, 0.478897, 71811e-8, 0.356262, -217182e-8, 0.478894, 161574e-8, 0.356265, -386092e-8, 0.478895, 287261e-8, 0.356278, -60324e-7, 0.478905, 448907e-8, 0.356293, -868565e-8, 0.478914, 646572e-8, 0.356346, -0.0118207, 0.478965, 880438e-8, 0.356395, -0.0154355, 0.479001, 0.0115066, 0.356484, -0.019529, 0.479075, 0.0145762, 0.356609, -0.0240991, 0.47918, 0.018018, 0.356766, -0.0291413, 0.479305, 0.0218379, 0.357009, -0.0346498, 0.479512, 0.0260454, 0.357424, -0.0405462, 0.479909, 0.0306657, 0.357899, -0.0468825, 0.480337, 0.0357054, 0.358424, -0.0536887, 0.480771, 0.0411728, 0.359041, -0.0609416, 0.481242, 0.0470841, 0.359903, -0.0685239, 0.481943, 0.0534831, 0.360932, -0.0764883, 0.482741, 0.0603795, 0.362196, -0.0848364, 0.483688, 0.0678028, 0.363847, -0.0935002, 0.484947, 0.0758086, 0.365972, -0.102471, 0.486588, 0.0844173, 0.368741, -0.111751, 0.488787, 0.0937199, 0.372146, -0.121334, 0.491405, 0.103732, 0.377114, -0.131147, 0.495604, 0.114608, 0.38226, -0.141213, 0.499436, 0.126345, 0.389609, -0.151632, 0.505334, 0.139116, 0.397925, -0.162073, 0.51168, 0.152995, 0.407824, -0.172819, 0.518876, 0.168071, 0.420014, -0.183929, 0.527639, 0.184495, 0.434266, -0.195032, 0.537588, 0.20232, 0.447352, -0.205792, 0.544379, 0.221189, 0.463726, -0.216704, 0.553422, 0.241616, 0.481406, -0.227531, 0.562074, 0.263298, 0.498707, -0.238017, 0.568227, 0.286116, 0.518039, -0.247936, 0.574473, 0.3101, 0.538277, -0.257437, 0.579191, 0.335401, 0.561166, -0.266829, 0.584807, 0.362246, 0.583189, -0.275329, 0.586476, 0.390609, 0.606024, -0.28234, 0.585578, 0.420998, 0.632419, -0.287924, 0.584496, 0.454357, 0.656128, -0.291972, 0.577766, 0.488233, 0.679953, -0.29456, 0.56875, 0.523248, 0.704654, -0.295816, 0.558388, 0.559168, 0.729016, -0.295157, 0.544826, 0.595326, 0.752062, -0.292779, 0.528273, 0.631864, 0.773138, -0.288681, 0.508482, 0.667793, 0.794869, -0.283358, 0.487341, 0.704035, 0.815101, -0.27608, 0.46354, 0.739925, 0.834212, -0.26767, 0.438672, 0.775539, 0.852368, -0.257397, 0.411239, 0.810895, 0.870207, -0.245689, 0.3829, 0.846472, 0.884063, -0.231452, 0.351496, 0.881788, 0.898284, -0.215561, 0.31895, 0.917438, 0.912964, -0.198208, 0.287367, 0.952422, 0.924666, -0.180426, 0.254487, 0.987551, 0.934429, -0.161525, 0.222226, 1.02142, 0.943485, -0.141197, 0.191143, 1.05218, 0.9521, -0.120085, 0.161112, 1.07937, 0.957876, -0.0975881, 0.130982, 1.10403, 0.966943, -0.0726842, 0.0990553, 1.12616, 0.978313, -0.0483705, 0.0662818, 1.14619, 0.990048, -0.0239072, 0.0329243, 1.16413, 0.999984, 461885e-9, -772859e-10, 1.18099, 0.321287, -935049e-11, 0.455413, 659662e-11, 0.332595, -237513e-9, 0.471437, 167562e-9, 0.332729, -949964e-9, 0.471618, 670192e-9, 0.332305, -213618e-8, 0.471028, 150712e-8, 0.332326, -379765e-8, 0.471055, 267959e-8, 0.332344, -593353e-8, 0.471072, 418751e-8, 0.332356, -854349e-8, 0.471077, 603172e-8, 0.332403, -0.0116268, 0.471121, 821362e-8, 0.332461, -0.0151824, 0.47117, 0.0107357, 0.332552, -0.0192088, 0.471251, 0.0136014, 0.332657, -0.0237024, 0.47133, 0.0168152, 0.332835, -0.0286615, 0.471487, 0.0203853, 0.333083, -0.0340765, 0.471708, 0.0243212, 0.333547, -0.0398563, 0.47219, 0.0286518, 0.333989, -0.0460916, 0.472587, 0.0333763, 0.334532, -0.0527897, 0.473054, 0.0385084, 0.335167, -0.0599284, 0.473568, 0.0440638, 0.33608, -0.0673514, 0.474362, 0.0500962, 0.337146, -0.0752237, 0.475231, 0.0566022, 0.338462, -0.083418, 0.476282, 0.0636272, 0.34014, -0.0919382, 0.477615, 0.0712153, 0.342341, -0.100741, 0.479404, 0.079417, 0.345088, -0.109905, 0.481618, 0.0882631, 0.349049, -0.119369, 0.485081, 0.0978851, 0.353939, -0.129033, 0.489317, 0.108336, 0.359893, -0.139038, 0.494309, 0.119698, 0.366945, -0.149411, 0.499983, 0.132024, 0.375814, -0.159843, 0.507185, 0.145558, 0.387112, -0.170664, 0.516392, 0.160433, 0.40023, -0.181897, 0.526519, 0.176648, 0.412555, -0.192785, 0.53423, 0.193922, 0.427023, -0.203663, 0.542741, 0.212662, 0.443685, -0.214695, 0.552066, 0.232944, 0.461499, -0.225561, 0.560762, 0.254495, 0.480975, -0.236257, 0.569421, 0.277531, 0.501, -0.24639, 0.576101, 0.301724, 0.521691, -0.256101, 0.581493, 0.327112, 0.543478, -0.265289, 0.585221, 0.353917, 0.566094, -0.273938, 0.587614, 0.381941, 0.589578, -0.281679, 0.587991, 0.41172, 0.614583, -0.287655, 0.585928, 0.444148, 0.641813, -0.292228, 0.582092, 0.478617, 0.666189, -0.295172, 0.57398, 0.51397, 0.690475, -0.29648, 0.561676, 0.550118, 0.715543, -0.296203, 0.548758, 0.586933, 0.740405, -0.293999, 0.532792, 0.62384, 0.762183, -0.28998, 0.512735, 0.660723, 0.786069, -0.28478, 0.492402, 0.69807, 0.806812, -0.277568, 0.469058, 0.734422, 0.826987, -0.268951, 0.443017, 0.770946, 0.844588, -0.259049, 0.415501, 0.80699, 0.863725, -0.2471, 0.387328, 0.842107, 0.879137, -0.234157, 0.356108, 0.878078, 0.894634, -0.218719, 0.324315, 0.914058, 0.909162, -0.201293, 0.291813, 0.949922, 0.92072, -0.18267, 0.258474, 0.985337, 0.93158, -0.163212, 0.225593, 1.0205, 0.941238, -0.142771, 0.193986, 1.05273, 0.949293, -0.120956, 0.163392, 1.08075, 0.956226, -0.0985743, 0.132934, 1.10559, 0.96546, -0.075118, 0.101255, 1.12823, 0.977403, -0.0497921, 0.0675441, 1.149, 0.989648, -0.0241574, 0.0334681, 1.16765, 1.00001, 5762e-7, -184807e-9, 1.18519, 0.303474, -916603e-11, 0.4542, 61243e-10, 0.308894, -232869e-9, 0.462306, 155592e-9, 0.309426, -931661e-9, 0.463093, 622499e-9, 0.308643, -20949e-7, 0.461933, 139979e-8, 0.308651, -37242e-7, 0.461941, 248874e-8, 0.308662, -581873e-8, 0.46195, 388933e-8, 0.308687, -837818e-8, 0.461974, 560247e-8, 0.308728, -0.0114016, 0.462011, 762948e-8, 0.308789, -0.0148884, 0.462067, 997326e-8, 0.308882, -0.0188369, 0.462151, 0.0126375, 0.309007, -0.0232436, 0.462263, 0.0156271, 0.30918, -0.0281054, 0.462417, 0.0189498, 0.309442, -0.0334065, 0.462667, 0.0226167, 0.309901, -0.0390589, 0.463162, 0.0266614, 0.310331, -0.0452042, 0.463555, 0.0310715, 0.310858, -0.0517735, 0.464019, 0.0358698, 0.311576, -0.0587359, 0.464669, 0.0410848, 0.312436, -0.0660383, 0.465406, 0.0467453, 0.313526, -0.0737266, 0.466339, 0.0528718, 0.314903, -0.0817574, 0.467504, 0.0595039, 0.316814, -0.090167, 0.469226, 0.0666888, 0.318965, -0.0987555, 0.470981, 0.0744658, 0.322077, -0.107792, 0.473814, 0.082912, 0.325947, -0.117098, 0.477241, 0.0920846, 0.331008, -0.126602, 0.48184, 0.102137, 0.337893, -0.136619, 0.488334, 0.113135, 0.345106, -0.146838, 0.494415, 0.12511, 0.355111, -0.157357, 0.503275, 0.138356, 0.365095, -0.167955, 0.510966, 0.152686, 0.378344, -0.179157, 0.521508, 0.16856, 0.391599, -0.190143, 0.530455, 0.18561, 0.407786, -0.20123, 0.541275, 0.204308, 0.425294, -0.212456, 0.551784, 0.224623, 0.444021, -0.223568, 0.561493, 0.246172, 0.463418, -0.234154, 0.569886, 0.268979, 0.484077, -0.244546, 0.577116, 0.293411, 0.505513, -0.254301, 0.582914, 0.318936, 0.527672, -0.263564, 0.587208, 0.345856, 0.550565, -0.272332, 0.589277, 0.374054, 0.573656, -0.280011, 0.588426, 0.403276, 0.59827, -0.286924, 0.587504, 0.43474, 0.624731, -0.291994, 0.583401, 0.468767, 0.652396, -0.295159, 0.576997, 0.504411, 0.67732, -0.296954, 0.565863, 0.54114, 0.703147, -0.296877, 0.552316, 0.57816, 0.728715, -0.295147, 0.536773, 0.616124, 0.752448, -0.291275, 0.51771, 0.653885, 0.775169, -0.285905, 0.496087, 0.691537, 0.799307, -0.279064, 0.474232, 0.729251, 0.819482, -0.270294, 0.447676, 0.766267, 0.837659, -0.260032, 0.419656, 0.802616, 0.856903, -0.248497, 0.391328, 0.838583, 0.873325, -0.235252, 0.360285, 0.874711, 0.889788, -0.221126, 0.329215, 0.91077, 0.904486, -0.204304, 0.296392, 0.94653, 0.917711, -0.185562, 0.262159, 0.983828, 0.928969, -0.165635, 0.229142, 1.01955, 0.939707, -0.14442, 0.19673, 1.05317, 0.948167, -0.122147, 0.165095, 1.0823, 0.955222, -0.099098, 0.13451, 1.10791, 0.964401, -0.0755332, 0.102476, 1.1312, 0.976605, -0.0513817, 0.0689667, 1.15218, 0.989085, -0.0258499, 0.034506, 1.17129, 0.999908, 617773e-9, -271268e-9, 1.18961, 0.285803, -905752e-11, 0.452348, 572272e-11, 0.284689, -22732e-8, 0.450581, 143626e-9, 0.285263, -910214e-9, 0.451482, 575099e-9, 0.285302, -204784e-8, 0.451553, 129395e-8, 0.285318, -364057e-8, 0.451574, 23006e-7, 0.28533, -568813e-8, 0.451585, 359547e-8, 0.285361, -819001e-8, 0.451618, 517934e-8, 0.285397, -0.0111458, 0.45165, 7054e-6, 0.285447, -0.0145536, 0.451688, 922167e-8, 0.285527, -0.0184127, 0.451758, 0.0116869, 0.285688, -0.0227207, 0.451929, 0.0144555, 0.28584, -0.0274712, 0.452055, 0.0175341, 0.286136, -0.0326278, 0.452369, 0.0209406, 0.286574, -0.0381792, 0.452853, 0.0246965, 0.287012, -0.0441879, 0.453272, 0.0287996, 0.287542, -0.0506096, 0.453752, 0.033268, 0.288299, -0.0573634, 0.454488, 0.0381504, 0.289186, -0.0645458, 0.455294, 0.0434447, 0.290302, -0.0720405, 0.456301, 0.0491973, 0.291776, -0.0799046, 0.457648, 0.0554453, 0.29372, -0.088117, 0.459483, 0.0622311, 0.296052, -0.0965328, 0.461571, 0.0695992, 0.299563, -0.105409, 0.465085, 0.077658, 0.30335, -0.114553, 0.468506, 0.0864176, 0.309167, -0.123917, 0.474423, 0.0961078, 0.31529, -0.13381, 0.47995, 0.106643, 0.324163, -0.144021, 0.488592, 0.118322, 0.333272, -0.154382, 0.496461, 0.131133, 0.344224, -0.165015, 0.50562, 0.145208, 0.357733, -0.176168, 0.516719, 0.16073, 0.373046, -0.187468, 0.528513, 0.177807, 0.38788, -0.198488, 0.537713, 0.196072, 0.405133, -0.209545, 0.547999, 0.21605, 0.423845, -0.220724, 0.55759, 0.237484, 0.443777, -0.231518, 0.566246, 0.26039, 0.464824, -0.242035, 0.574326, 0.284835, 0.486635, -0.251898, 0.58037, 0.310518, 0.51012, -0.261304, 0.58568, 0.337678, 0.535301, -0.270384, 0.590197, 0.366242, 0.559193, -0.27841, 0.590569, 0.395873, 0.583544, -0.285325, 0.588161, 0.426857, 0.608834, -0.291113, 0.584249, 0.459477, 0.635753, -0.294882, 0.57763, 0.494734, 0.664367, -0.297088, 0.569479, 0.532023, 0.689688, -0.297364, 0.555064, 0.569629, 0.715732, -0.295949, 0.539522, 0.608124, 0.741307, -0.292259, 0.521613, 0.646231, 0.764949, -0.287063, 0.49969, 0.684938, 0.788599, -0.28012, 0.476747, 0.723548, 0.81048, -0.27153, 0.45116, 0.761135, 0.831372, -0.261289, 0.424101, 0.798916, 0.850092, -0.249559, 0.39443, 0.835952, 0.867777, -0.236348, 0.363849, 0.871606, 0.884632, -0.221569, 0.332477, 0.907843, 0.90047, -0.20618, 0.300667, 0.944187, 0.914524, -0.188771, 0.266552, 0.981371, 0.926892, -0.168362, 0.232349, 1.01841, 0.937951, -0.146761, 0.199359, 1.05308, 0.947236, -0.123813, 0.1675, 1.0839, 0.954367, -0.099984, 0.136166, 1.11047, 0.963907, -0.0759278, 0.103808, 1.13414, 0.976218, -0.0511367, 0.0697061, 1.15575, 0.988772, -0.0267415, 0.0352529, 1.17531, 0.999888, -520778e-9, 289926e-9, 1.19389, 0.263546, -883274e-11, 0.441896, 526783e-11, 0.262352, -221849e-9, 0.439889, 132311e-9, 0.262325, -886683e-9, 0.439848, 528824e-9, 0.26228, -199476e-8, 0.439765, 118975e-8, 0.262372, -354671e-8, 0.439922, 211568e-8, 0.26239, -554141e-8, 0.439941, 330652e-8, 0.262412, -797888e-8, 0.439961, 476346e-8, 0.262453, -0.0108584, 0.440002, 648818e-8, 0.262528, -0.0141788, 0.440085, 84835e-7, 0.262615, -0.017938, 0.440166, 0.0107533, 0.262744, -0.0221346, 0.440291, 0.0133044, 0.262939, -0.026762, 0.440493, 0.0161445, 0.263277, -0.0317573, 0.440889, 0.0192974, 0.26368, -0.0371832, 0.441338, 0.0227699, 0.264106, -0.0430371, 0.441753, 0.0265698, 0.264624, -0.0493035, 0.442227, 0.0307178, 0.265378, -0.0558669, 0.442985, 0.0352616, 0.266253, -0.0628718, 0.443795, 0.0401968, 0.267478, -0.0701569, 0.445008, 0.04559, 0.269062, -0.077845, 0.446599, 0.0514539, 0.270926, -0.0857941, 0.448349, 0.0578382, 0.273693, -0.0940773, 0.451221, 0.0648363, 0.276746, -0.102704, 0.454097, 0.0724389, 0.281693, -0.111735, 0.459517, 0.0808744, 0.287335, -0.121004, 0.46531, 0.0901551, 0.29448, -0.130734, 0.472605, 0.100371, 0.30257, -0.140777, 0.480251, 0.111644, 0.312465, -0.15111, 0.489444, 0.124111, 0.324856, -0.16189, 0.500919, 0.137979, 0.33774, -0.172946, 0.511317, 0.153163, 0.35255, -0.184152, 0.522684, 0.169817, 0.367786, -0.19522, 0.53248, 0.187886, 0.385474, -0.20632, 0.543326, 0.207634, 0.404976, -0.217744, 0.554109, 0.229165, 0.425203, -0.228691, 0.563395, 0.252068, 0.446704, -0.239299, 0.571565, 0.276471, 0.468951, -0.249348, 0.577935, 0.302323, 0.493487, -0.258933, 0.584309, 0.329882, 0.517861, -0.268009, 0.58773, 0.358525, 0.543309, -0.276238, 0.589612, 0.388585, 0.569704, -0.28356, 0.589294, 0.419787, 0.594871, -0.289497, 0.585137, 0.452114, 0.622555, -0.294452, 0.580356, 0.486466, 0.651167, -0.296918, 0.57185, 0.523079, 0.677332, -0.297647, 0.558428, 0.5611, 0.703718, -0.296321, 0.542232, 0.599592, 0.730262, -0.293339, 0.524541, 0.639138, 0.754304, -0.288036, 0.502691, 0.677978, 0.778051, -0.281018, 0.479212, 0.716537, 0.801557, -0.272414, 0.454071, 0.75586, 0.822559, -0.262419, 0.425952, 0.794477, 0.843051, -0.250702, 0.397313, 0.832664, 0.86232, -0.237264, 0.366534, 0.869876, 0.879044, -0.222716, 0.334816, 0.906973, 0.896362, -0.206827, 0.303143, 0.943558, 0.910342, -0.189659, 0.269699, 0.979759, 0.924119, -0.171108, 0.236411, 1.01718, 0.935374, -0.149579, 0.202224, 1.05289, 0.944295, -0.126295, 0.16989, 1.08496, 0.952227, -0.101511, 0.138089, 1.11256, 0.962041, -0.0766392, 0.105053, 1.1375, 0.97528, -0.0511967, 0.070329, 1.15983, 0.988476, -0.025463, 0.0351268, 1.17987, 0.999962, 286808e-10, 145564e-10, 1.19901, 0.227089, -841413e-11, 0.404216, 472707e-11, 0.239725, -215083e-9, 0.426708, 120833e-9, 0.239904, -860718e-9, 0.427028, 483555e-9, 0.239911, -193661e-8, 0.427039, 108806e-8, 0.239914, -344276e-8, 0.42704, 193457e-8, 0.239933, -537907e-8, 0.427064, 302363e-8, 0.239944, -774482e-8, 0.427065, 435604e-8, 0.239993, -0.01054, 0.427122, 593398e-8, 0.240052, -0.0137626, 0.427179, 775987e-8, 0.240148, -0.0174115, 0.427279, 983854e-8, 0.240278, -0.021484, 0.42741, 0.0121763, 0.240472, -0.0259729, 0.427618, 0.0147827, 0.240839, -0.0308131, 0.428086, 0.0176837, 0.241201, -0.0360893, 0.428482, 0.0208775, 0.241626, -0.0417723, 0.428907, 0.0243821, 0.242207, -0.0478337, 0.42952, 0.0282228, 0.24298, -0.0542199, 0.430332, 0.0324333, 0.243881, -0.0610015, 0.431222, 0.0370252, 0.245123, -0.0680874, 0.432512, 0.0420535, 0.24667, -0.0755482, 0.434088, 0.0475414, 0.248779, -0.0832873, 0.436323, 0.0535542, 0.251665, -0.0913546, 0.439509, 0.0601716, 0.255305, -0.0998489, 0.443478, 0.0674282, 0.260049, -0.108576, 0.448713, 0.0754673, 0.266192, -0.117754, 0.455524, 0.084339, 0.273158, -0.127294, 0.4627, 0.0941683, 0.282131, -0.137311, 0.472068, 0.10515, 0.293332, -0.147736, 0.483565, 0.117402, 0.304667, -0.158357, 0.493702, 0.130824, 0.317785, -0.169274, 0.504708, 0.145724, 0.333245, -0.180595, 0.517107, 0.16215, 0.349843, -0.191892, 0.528849, 0.180149, 0.367944, -0.203168, 0.540301, 0.199746, 0.387579, -0.214443, 0.551514, 0.221047, 0.408247, -0.225624, 0.560906, 0.243981, 0.43014, -0.236422, 0.56959, 0.268513, 0.452669, -0.24654, 0.576098, 0.294409, 0.476196, -0.256157, 0.580925, 0.322002, 0.501157, -0.265289, 0.584839, 0.351052, 0.527632, -0.273671, 0.587614, 0.3812, 0.555754, -0.281254, 0.589119, 0.412994, 0.581682, -0.287448, 0.585204, 0.445498, 0.608196, -0.292614, 0.579006, 0.479505, 0.635661, -0.296068, 0.571297, 0.514643, 0.664999, -0.297395, 0.560855, 0.552213, 0.691039, -0.296645, 0.544525, 0.591365, 0.7179, -0.293785, 0.526535, 0.630883, 0.744059, -0.289089, 0.50545, 0.670932, 0.76863, -0.282239, 0.482514, 0.710904, 0.793273, -0.273688, 0.457246, 0.750259, 0.814731, -0.26328, 0.428872, 0.78948, 0.835603, -0.251526, 0.399384, 0.828597, 0.85489, -0.238339, 0.368811, 0.866892, 0.872828, -0.223607, 0.336617, 0.90563, 0.889462, -0.207538, 0.303997, 0.943538, 0.904929, -0.190297, 0.270812, 0.980591, 0.919101, -0.172034, 0.237453, 1.01935, 0.930536, -0.152058, 0.204431, 1.05498, 0.941223, -0.129515, 0.172495, 1.08717, 0.94982, -0.104263, 0.140175, 1.11551, 0.960592, -0.0781944, 0.106465, 1.14098, 0.974629, -0.051688, 0.0711592, 1.16418, 0.98811, -0.0253929, 0.0354432, 1.18465, 1.00004, 804378e-9, -330876e-9, 1.20462, 0.214668, -821282e-11, 0.406619, 433582e-11, 0.218053, -208144e-9, 0.413025, 109887e-9, 0.217987, -832212e-9, 0.412901, 439362e-9, 0.217971, -187246e-8, 0.412876, 988623e-9, 0.217968, -332855e-8, 0.41286, 175772e-8, 0.217985, -520055e-8, 0.412882, 274729e-8, 0.218014, -748814e-8, 0.412916, 395842e-8, 0.218054, -0.0101901, 0.412957, 539274e-8, 0.218106, -0.0133057, 0.413005, 705348e-8, 0.218217, -0.0168342, 0.413139, 894581e-8, 0.218338, -0.0207707, 0.413258, 0.0110754, 0.21855, -0.0251001, 0.413509, 0.0134551, 0.218913, -0.0297861, 0.413992, 0.0161081, 0.219265, -0.0348956, 0.414383, 0.0190307, 0.219696, -0.0403909, 0.414839, 0.0222458, 0.220329, -0.0462003, 0.415567, 0.025792, 0.220989, -0.0524208, 0.41621, 0.0296637, 0.222027, -0.058948, 0.417385, 0.0339323, 0.223301, -0.0658208, 0.418779, 0.0386055, 0.224988, -0.0730347, 0.420665, 0.0437355, 0.227211, -0.0805274, 0.423198, 0.0493844, 0.230131, -0.088395, 0.426566, 0.0556135, 0.233908, -0.0966208, 0.43091, 0.0624829, 0.239092, -0.105223, 0.437148, 0.0701636, 0.245315, -0.11424, 0.444302, 0.0786949, 0.253166, -0.12368, 0.453262, 0.0882382, 0.262374, -0.133569, 0.463211, 0.0988682, 0.273145, -0.143836, 0.474271, 0.110727, 0.285512, -0.154577, 0.4863, 0.123945, 0.299512, -0.165501, 0.498817, 0.138581, 0.314287, -0.176698, 0.510341, 0.154676, 0.331083, -0.188066, 0.522583, 0.172459, 0.349615, -0.199597, 0.534879, 0.191979, 0.369318, -0.210843, 0.546083, 0.21309, 0.390377, -0.222068, 0.5562, 0.235998, 0.412411, -0.233059, 0.564704, 0.260518, 0.435715, -0.24357, 0.572314, 0.286795, 0.461196, -0.253356, 0.579395, 0.314559, 0.485587, -0.262362, 0.581985, 0.343581, 0.511908, -0.270895, 0.584347, 0.374367, 0.539798, -0.278452, 0.58505, 0.406015, 0.567974, -0.284877, 0.583344, 0.439168, 0.594303, -0.290124, 0.577348, 0.473005, 0.622951, -0.294183, 0.570751, 0.508534, 0.652404, -0.296389, 0.561541, 0.544764, 0.679291, -0.296605, 0.546426, 0.582927, 0.706437, -0.294095, 0.528599, 0.622681, 0.734485, -0.28978, 0.508676, 0.663567, 0.758841, -0.283363, 0.484768, 0.704092, 0.78537, -0.275015, 0.460434, 0.745101, 0.807315, -0.264689, 0.432166, 0.784712, 0.8271, -0.252597, 0.401807, 0.824241, 0.849191, -0.239154, 0.371458, 0.863803, 0.867046, -0.224451, 0.338873, 0.903063, 0.8852, -0.208342, 0.306175, 0.942763, 0.901771, -0.190684, 0.272759, 0.981559, 0.915958, -0.172105, 0.239306, 1.02048, 0.928046, -0.152214, 0.206071, 1.05765, 0.939961, -0.130247, 0.17367, 1.08999, 0.948711, -0.10672, 0.142201, 1.11829, 0.959305, -0.0808688, 0.108454, 1.14467, 0.973009, -0.0539145, 0.0728109, 1.16839, 0.987631, -0.0262947, 0.0360625, 1.19004, 0.999978, 132758e-8, -559424e-9, 1.21058, 0.193925, -793421e-11, 0.391974, 392537e-11, 0.196746, -200315e-9, 0.397675, 991033e-10, 0.19667, -801099e-9, 0.397521, 396342e-9, 0.196633, -180246e-8, 0.397445, 891829e-9, 0.196654, -320443e-8, 0.397482, 158582e-8, 0.196659, -500647e-8, 0.39748, 247867e-8, 0.196683, -72086e-7, 0.397506, 357167e-8, 0.196728, -981001e-8, 0.397562, 486675e-8, 0.196792, -0.0128096, 0.397633, 636707e-8, 0.19689, -0.0162055, 0.397746, 807752e-8, 0.197017, -0.0199943, 0.397884, 0.0100052, 0.19729, -0.024139, 0.39827, 0.0121691, 0.197583, -0.0286671, 0.398639, 0.0145755, 0.197927, -0.0335858, 0.399034, 0.0172355, 0.198383, -0.0388806, 0.399554, 0.0201718, 0.199002, -0.0444736, 0.400289, 0.0234194, 0.199739, -0.0504583, 0.401111, 0.026984, 0.200784, -0.056729, 0.402349, 0.0309217, 0.202075, -0.0633643, 0.403841, 0.0352496, 0.203898, -0.0703247, 0.406076, 0.0400313, 0.206199, -0.0775565, 0.408841, 0.0453282, 0.209252, -0.085184, 0.41259, 0.0511794, 0.213638, -0.0931994, 0.418288, 0.0577459, 0.21881, -0.101617, 0.424681, 0.0650508, 0.225642, -0.11052, 0.433429, 0.0732759, 0.233717, -0.119772, 0.442897, 0.0824683, 0.242823, -0.129505, 0.452888, 0.0927484, 0.254772, -0.139906, 0.466407, 0.104417, 0.266603, -0.150402, 0.477413, 0.117211, 0.28073, -0.161395, 0.490519, 0.131598, 0.295399, -0.172465, 0.50201, 0.147407, 0.312705, -0.183982, 0.515311, 0.165031, 0.331335, -0.195532, 0.52786, 0.184336, 0.351037, -0.206971, 0.5392, 0.205361, 0.372175, -0.218117, 0.54941, 0.228043, 0.394548, -0.229327, 0.558642, 0.25267, 0.419598, -0.240052, 0.567861, 0.279071, 0.443922, -0.249937, 0.573332, 0.306882, 0.471495, -0.259407, 0.58013, 0.33661, 0.496769, -0.267749, 0.580564, 0.367328, 0.524951, -0.275524, 0.581696, 0.399753, 0.55318, -0.282148, 0.579885, 0.433134, 0.581577, -0.287533, 0.575471, 0.467534, 0.609231, -0.291612, 0.567445, 0.502943, 0.637478, -0.293911, 0.557657, 0.53871, 0.667795, -0.295096, 0.546535, 0.576568, 0.694272, -0.294073, 0.529561, 0.614929, 0.722937, -0.290386, 0.510561, 0.655909, 0.749682, -0.284481, 0.487846, 0.697663, 0.774754, -0.276188, 0.462487, 0.738515, 0.799301, -0.266215, 0.43481, 0.779802, 0.820762, -0.254116, 0.404879, 0.820045, 0.843231, -0.240393, 0.374559, 0.860294, 0.861857, -0.225503, 0.341582, 0.900965, 0.880815, -0.209382, 0.308778, 0.941727, 0.89766, -0.19155, 0.275232, 0.980916, 0.912926, -0.172346, 0.240938, 1.02162, 0.926391, -0.151799, 0.207223, 1.0597, 0.938429, -0.129968, 0.17484, 1.09291, 0.947834, -0.10651, 0.142984, 1.12248, 0.958432, -0.0824098, 0.109902, 1.149, 0.972402, -0.0565242, 0.0744454, 1.1733, 0.987191, -0.028427, 0.0373794, 1.19538, 0.999975, 385685e-10, -4203e-8, 1.21676, 0.178114, -766075e-11, 0.385418, 354027e-11, 0.176074, -191966e-9, 0.381002, 887135e-10, 0.17601, -767549e-9, 0.380861, 354715e-9, 0.17598, -172696e-8, 0.380798, 798168e-9, 0.175994, -307012e-8, 0.380824, 141928e-8, 0.176017, -479684e-8, 0.380858, 221859e-8, 0.176019, -690648e-8, 0.380839, 319714e-8, 0.176072, -939888e-8, 0.380913, 43572e-7, 0.176131, -0.0122726, 0.380979, 5702e-6, 0.176239, -0.0155264, 0.38112, 723689e-8, 0.176371, -0.0191551, 0.381272, 896907e-8, 0.176638, -0.023117, 0.381669, 0.0109194, 0.176912, -0.0274633, 0.382015, 0.0130903, 0.177279, -0.032173, 0.382476, 0.0154949, 0.17774, -0.0372219, 0.383041, 0.0181669, 0.178344, -0.0426132, 0.38378, 0.0211209, 0.179153, -0.0483309, 0.384773, 0.0243899, 0.180197, -0.0543447, 0.386076, 0.0280062, 0.181581, -0.0607122, 0.387809, 0.032004, 0.18344, -0.0673855, 0.390205, 0.036453, 0.186139, -0.0743989, 0.393944, 0.0414162, 0.189432, -0.0817731, 0.39832, 0.0469394, 0.193795, -0.0895464, 0.404188, 0.0531442, 0.199641, -0.0978264, 0.4121, 0.0601374, 0.206679, -0.106499, 0.421425, 0.0680078, 0.214865, -0.115654, 0.431504, 0.076919, 0.224406, -0.125268, 0.442526, 0.0868835, 0.235876, -0.135475, 0.455465, 0.0981875, 0.248335, -0.146023, 0.4681, 0.110759, 0.262868, -0.157016, 0.482069, 0.124885, 0.278962, -0.168245, 0.496182, 0.140645, 0.295082, -0.17958, 0.507401, 0.157838, 0.313738, -0.191227, 0.520252, 0.17695, 0.333573, -0.202718, 0.531708, 0.197817, 0.356433, -0.214424, 0.544509, 0.220785, 0.378853, -0.225492, 0.55373, 0.245306, 0.402717, -0.236236, 0.561348, 0.271593, 0.428375, -0.246568, 0.568538, 0.299776, 0.454724, -0.255941, 0.573462, 0.329433, 0.482291, -0.264511, 0.576356, 0.360598, 0.509706, -0.272129, 0.576446, 0.393204, 0.538805, -0.278979, 0.575298, 0.427227, 0.568919, -0.284528, 0.572154, 0.462157, 0.596804, -0.288801, 0.564691, 0.497997, 0.625987, -0.291334, 0.555134, 0.534467, 0.656414, -0.292722, 0.545051, 0.571736, 0.683916, -0.292185, 0.528813, 0.610158, 0.711809, -0.290043, 0.51106, 0.649061, 0.739547, -0.285246, 0.490103, 0.690081, 0.766914, -0.277647, 0.465523, 0.732554, 0.791375, -0.267603, 0.437718, 0.773982, 0.814772, -0.256109, 0.40882, 0.81609, 0.836691, -0.242281, 0.377823, 0.856849, 0.856984, -0.227155, 0.34496, 0.898363, 0.876332, -0.210395, 0.311335, 0.939471, 0.894988, -0.192612, 0.277703, 0.980799, 0.911113, -0.173236, 0.243019, 1.02215, 0.924092, -0.152258, 0.209037, 1.06139, 0.936828, -0.129575, 0.175909, 1.09635, 0.946869, -0.10594, 0.143852, 1.12707, 0.958284, -0.081318, 0.110289, 1.15419, 0.972325, -0.0556133, 0.0747232, 1.17909, 0.986878, -0.0297899, 0.0383149, 1.20163, 0.999936, -197169e-8, 912402e-9, 1.22338, 0.151174, -720365e-11, 0.351531, 309789e-11, 0.155594, -18279e-8, 0.361806, 78608e-9, 0.156099, -731569e-9, 0.362982, 314615e-9, 0.156053, -164578e-8, 0.362869, 707845e-9, 0.156093, -29261e-7, 0.362961, 125884e-8, 0.156099, -457155e-8, 0.362959, 196783e-8, 0.15612, -658224e-8, 0.362982, 283622e-8, 0.156168, -895774e-8, 0.363048, 386625e-8, 0.156221, -0.0116962, 0.363101, 506109e-8, 0.156324, -0.0147973, 0.363241, 642675e-8, 0.156476, -0.0182503, 0.363448, 797175e-8, 0.156731, -0.0220266, 0.36384, 971484e-8, 0.156994, -0.026176, 0.364179, 0.0116575, 0.157341, -0.0306701, 0.36462, 0.0138207, 0.157867, -0.0354591, 0.365364, 0.0162356, 0.15846, -0.0406141, 0.366111, 0.0189092, 0.159308, -0.0460519, 0.367248, 0.021885, 0.160426, -0.0518096, 0.368767, 0.0252004, 0.161877, -0.0578906, 0.370745, 0.0288825, 0.163995, -0.0642812, 0.373831, 0.0330139, 0.16655, -0.0710067, 0.377366, 0.0376283, 0.170237, -0.0781522, 0.382799, 0.0428493, 0.175096, -0.0857172, 0.389915, 0.0487324, 0.181069, -0.0938025, 0.398487, 0.0554214, 0.188487, -0.102363, 0.408799, 0.0630189, 0.197029, -0.111343, 0.419991, 0.071634, 0.206684, -0.120812, 0.431455, 0.0812797, 0.218698, -0.131033, 0.445746, 0.0923651, 0.230726, -0.141373, 0.457471, 0.104545, 0.245516, -0.152387, 0.472388, 0.118449, 0.261551, -0.163628, 0.486671, 0.133923, 0.277437, -0.174814, 0.49762, 0.150849, 0.296662, -0.186713, 0.51162, 0.169924, 0.31795, -0.198513, 0.525435, 0.190848, 0.339422, -0.210119, 0.536267, 0.213504, 0.362143, -0.221354, 0.545982, 0.237947, 0.387198, -0.23224, 0.555364, 0.264427, 0.412349, -0.24257, 0.561489, 0.292519, 0.439274, -0.252284, 0.566903, 0.322561, 0.466779, -0.261023, 0.569614, 0.353952, 0.496011, -0.26899, 0.571589, 0.387278, 0.524964, -0.275498, 0.570325, 0.421356, 0.556518, -0.281449, 0.568792, 0.457314, 0.584363, -0.285526, 0.560268, 0.493199, 0.614214, -0.28844, 0.55205, 0.530276, 0.645684, -0.289777, 0.541906, 0.56855, 0.673446, -0.289722, 0.526464, 0.606927, 0.701924, -0.287792, 0.509872, 0.645945, 0.73037, -0.284315, 0.490649, 0.685564, 0.757405, -0.278804, 0.467964, 0.726511, 0.784025, -0.269543, 0.441468, 0.768601, 0.808255, -0.258117, 0.41216, 0.811321, 0.830739, -0.244728, 0.380606, 0.853496, 0.851914, -0.229428, 0.348111, 0.895374, 0.872586, -0.212508, 0.314732, 0.937674, 0.891581, -0.194025, 0.280338, 0.979869, 0.907641, -0.174711, 0.245203, 1.02253, 0.922233, -0.153509, 0.21077, 1.06371, 0.935878, -0.130418, 0.177399, 1.09972, 0.946338, -0.105558, 0.144507, 1.13124, 0.957265, -0.080059, 0.110508, 1.15973, 0.971668, -0.0539766, 0.0742311, 1.18515, 0.9866, -0.0277101, 0.0375224, 1.20858, 1.00021, -515531e-9, 135226e-9, 1.23135, 0.137468, -686011e-11, 0.345041, 273315e-11, 0.13703, -173378e-9, 0.343936, 690761e-10, 0.136986, -693048e-9, 0.34383, 276126e-9, 0.136964, -155931e-8, 0.343761, 621337e-9, 0.137003, -277211e-8, 0.343863, 110494e-8, 0.137012, -433103e-8, 0.343868, 172744e-8, 0.137043, -623606e-8, 0.343916, 249022e-8, 0.13709, -84868e-7, 0.343986, 339559e-8, 0.137145, -0.0110814, 0.344045, 444687e-8, 0.137242, -0.0140187, 0.344177, 565007e-8, 0.137431, -0.0172713, 0.344491, 701868e-8, 0.137644, -0.0208605, 0.344805, 856042e-8, 0.13791, -0.024792, 0.345172, 0.0102863, 0.138295, -0.0290461, 0.345734, 0.0122185, 0.138764, -0.0335957, 0.346371, 0.0143771, 0.139415, -0.038467, 0.347298, 0.0167894, 0.140272, -0.0436176, 0.348527, 0.0194895, 0.141457, -0.0491016, 0.350276, 0.0225043, 0.14303, -0.0548764, 0.352646, 0.0258962, 0.145289, -0.0610096, 0.356206, 0.0297168, 0.148502, -0.0674777, 0.361488, 0.0340562, 0.152188, -0.074345, 0.367103, 0.0389534, 0.157359, -0.0817442, 0.375247, 0.0445541, 0.16379, -0.0896334, 0.385064, 0.0509535, 0.171376, -0.098005, 0.396082, 0.0582611, 0.179901, -0.106817, 0.407418, 0.06654, 0.189892, -0.116239, 0.420031, 0.075994, 0.201838, -0.12627, 0.434321, 0.0867239, 0.214311, -0.136701, 0.447631, 0.0987517, 0.228902, -0.147616, 0.462046, 0.112353, 0.245107, -0.158871, 0.476942, 0.127605, 0.262292, -0.170261, 0.490285, 0.144469, 0.281215, -0.182017, 0.503783, 0.163282, 0.301058, -0.193729, 0.515505, 0.183873, 0.322752, -0.205512, 0.52682, 0.206466, 0.347547, -0.217214, 0.539473, 0.231194, 0.370969, -0.227966, 0.546625, 0.257288, 0.397533, -0.238555, 0.55472, 0.285789, 0.42398, -0.248278, 0.559468, 0.315746, 0.452928, -0.257422, 0.564095, 0.347724, 0.482121, -0.265306, 0.565426, 0.380922, 0.510438, -0.272043, 0.563205, 0.415639, 0.541188, -0.277614, 0.561087, 0.451702, 0.571667, -0.281927, 0.554922, 0.48845, 0.602432, -0.285015, 0.546838, 0.526442, 0.634126, -0.286512, 0.537415, 0.564896, 0.662816, -0.286388, 0.522906, 0.604037, 0.692411, -0.284734, 0.507003, 0.643795, 0.720946, -0.281297, 0.488398, 0.68298, 0.748293, -0.276262, 0.466353, 0.723466, 0.776931, -0.269978, 0.443573, 0.764565, 0.801065, -0.260305, 0.415279, 0.805838, 0.825843, -0.247426, 0.384773, 0.849985, 0.84807, -0.232437, 0.352555, 0.893174, 0.869122, -0.215806, 0.318642, 0.936564, 0.888963, -0.197307, 0.28381, 0.980253, 0.905547, -0.177203, 0.247888, 1.02463, 0.918554, -0.155542, 0.212904, 1.06714, 0.931395, -0.131948, 0.1787, 1.10451, 0.941749, -0.106723, 0.145902, 1.13694, 0.954551, -0.0804939, 0.111193, 1.1666, 0.970279, -0.0534239, 0.0744697, 1.19249, 0.986117, -0.0257452, 0.0368788, 1.21665, 0.999938, 190634e-8, -10291e-7, 1.23981, 0.118493, -647439e-11, 0.32272, 23772e-10, 0.118765, -163023e-9, 0.323456, 598573e-10, 0.118772, -65212e-8, 0.323477, 239447e-9, 0.118843, -146741e-8, 0.323657, 538881e-9, 0.118804, -260846e-8, 0.323553, 95826e-8, 0.118826, -407576e-8, 0.323595, 149845e-8, 0.118846, -586826e-8, 0.323617, 216047e-8, 0.118886, -798578e-8, 0.32367, 294679e-8, 0.118947, -0.0104273, 0.323753, 386124e-8, 0.119055, -0.0131909, 0.323922, 490999e-8, 0.119241, -0.0162444, 0.324251, 610804e-8, 0.11944, -0.0196339, 0.324544, 745805e-8, 0.119739, -0.0233378, 0.325026, 897805e-8, 0.12011, -0.0273179, 0.325586, 0.0106895, 0.120571, -0.0316143, 0.326231, 0.0126073, 0.12124, -0.0361939, 0.327264, 0.0147654, 0.122162, -0.0410511, 0.328733, 0.0172001, 0.123378, -0.0462233, 0.330659, 0.0199375, 0.125183, -0.0517109, 0.333754, 0.0230498, 0.127832, -0.0575652, 0.338507, 0.026597, 0.130909, -0.0637441, 0.343666, 0.0306345, 0.135221, -0.0704302, 0.351063, 0.035273, 0.14082, -0.0776364, 0.360604, 0.0406137, 0.146781, -0.0852293, 0.369638, 0.0466788, 0.155121, -0.0935351, 0.3827, 0.0537628, 0.16398, -0.102234, 0.39522, 0.0617985, 0.173926, -0.111465, 0.40793, 0.07097, 0.185137, -0.121296, 0.42105, 0.0813426, 0.19826, -0.13169, 0.435735, 0.0931596, 0.212938, -0.142614, 0.450932, 0.106547, 0.229046, -0.153884, 0.465726, 0.121575, 0.246246, -0.165382, 0.479461, 0.138286, 0.264637, -0.176806, 0.492106, 0.15666, 0.284959, -0.188793, 0.504774, 0.17728, 0.308157, -0.200763, 0.518805, 0.19988, 0.330951, -0.21239, 0.528231, 0.224293, 0.3549, -0.223521, 0.536376, 0.250541, 0.381502, -0.234169, 0.544846, 0.278902, 0.409529, -0.244077, 0.551717, 0.309227, 0.437523, -0.253363, 0.55517, 0.341426, 0.467624, -0.261659, 0.557772, 0.37518, 0.497268, -0.268498, 0.556442, 0.41007, 0.528294, -0.274018, 0.553915, 0.446445, 0.559053, -0.278169, 0.549153, 0.483779, 0.589329, -0.281229, 0.539878, 0.522249, 0.622503, -0.282902, 0.53162, 0.561754, 0.652382, -0.282815, 0.518119, 0.601544, 0.681847, -0.281247, 0.502187, 0.641574, 0.712285, -0.277986, 0.484824, 0.682633, 0.740094, -0.273017, 0.463483, 0.723426, 0.768478, -0.266692, 0.441299, 0.763747, 0.794556, -0.258358, 0.415238, 0.805565, 0.819408, -0.248807, 0.386912, 0.847254, 0.843411, -0.236214, 0.356165, 0.891091, 0.862397, -0.219794, 0.320562, 0.936174, 0.883113, -0.201768, 0.285322, 0.982562, 0.90023, -0.181672, 0.249713, 1.02862, 0.915192, -0.159279, 0.214546, 1.07163, 0.928458, -0.134725, 0.180285, 1.10995, 0.94069, -0.10913, 0.147119, 1.14354, 0.953409, -0.0821315, 0.112492, 1.17372, 0.969537, -0.0542677, 0.0752014, 1.20043, 0.985612, -0.0259096, 0.0370361, 1.22528, 0.999835, 298198e-8, -151801e-8, 1.24959, 0.10097, -602574e-11, 0.300277, 202619e-11, 0.101577, -152164e-9, 0.302077, 511662e-10, 0.101572, -608889e-9, 0.302066, 204751e-9, 0.101566, -136997e-8, 0.302047, 460753e-9, 0.101592, -243557e-8, 0.302114, 819497e-9, 0.101608, -38053e-7, 0.30214, 128154e-8, 0.101627, -547906e-8, 0.30216, 18483e-7, 0.101669, -745647e-8, 0.302224, 252223e-8, 0.101732, -973615e-8, 0.302318, 330716e-8, 0.101844, -0.0123097, 0.302513, 421061e-8, 0.102025, -0.0151681, 0.30285, 524481e-8, 0.102224, -0.0183334, 0.303166, 64154e-7, 0.102515, -0.0217819, 0.303654, 774063e-8, 0.102886, -0.0255067, 0.304243, 92398e-7, 0.103395, -0.029514, 0.305089, 0.0109339, 0.104109, -0.0337912, 0.306301, 0.0128561, 0.105074, -0.0383565, 0.30798, 0.0150338, 0.10654, -0.0432132, 0.310726, 0.0175228, 0.108478, -0.0484244, 0.314351, 0.0203648, 0.111015, -0.0539339, 0.319032, 0.0236325, 0.114682, -0.0598885, 0.32605, 0.0274188, 0.11911, -0.0663375, 0.334109, 0.0317905, 0.124736, -0.0733011, 0.344013, 0.0368502, 0.131479, -0.0807744, 0.355358, 0.0427104, 0.139283, -0.0888204, 0.367614, 0.0494788, 0.148054, -0.0973394, 0.380072, 0.0572367, 0.159037, -0.10665, 0.395678, 0.0662704, 0.169794, -0.116221, 0.40795, 0.0763192, 0.18314, -0.126632, 0.423546, 0.087956, 0.197515, -0.137383, 0.438213, 0.101042, 0.213514, -0.148641, 0.453248, 0.115827, 0.23065, -0.160117, 0.46688, 0.132283, 0.249148, -0.171807, 0.479962, 0.150644, 0.270219, -0.183695, 0.494618, 0.171073, 0.292338, -0.195574, 0.506937, 0.193378, 0.314999, -0.207205, 0.516463, 0.217585, 0.340991, -0.218955, 0.528123, 0.24428, 0.367982, -0.229917, 0.537025, 0.272784, 0.39432, -0.239737, 0.541627, 0.302742, 0.423364, -0.249048, 0.546466, 0.335112, 0.453751, -0.257329, 0.549466, 0.369032, 0.48416, -0.264623, 0.549503, 0.404577, 0.515262, -0.270411, 0.547008, 0.441337, 0.547036, -0.274581, 0.542249, 0.479162, 0.576614, -0.277266, 0.533015, 0.517904, 0.611143, -0.279144, 0.525512, 0.558508, 0.640989, -0.279001, 0.51154, 0.598995, 0.671182, -0.277324, 0.495641, 0.639935, 0.700848, -0.273908, 0.477526, 0.681017, 0.729862, -0.269063, 0.457955, 0.722764, 0.758273, -0.262282, 0.434846, 0.764349, 0.784121, -0.254281, 0.409203, 0.806206, 0.809798, -0.24505, 0.382694, 0.848617, 0.834953, -0.233861, 0.354034, 0.892445, 0.856817, -0.221308, 0.321764, 0.936263, 0.877609, -0.205996, 0.288118, 0.982401, 0.897489, -0.186702, 0.253277, 1.02975, 0.913792, -0.164618, 0.217963, 1.07488, 0.92785, -0.140023, 0.183221, 1.11487, 0.940378, -0.11328, 0.149385, 1.14947, 0.95273, -0.0853958, 0.114152, 1.1807, 0.969059, -0.0568698, 0.0769845, 1.20912, 0.985574, -0.0276502, 0.0381186, 1.23498, 0.999943, 239052e-8, -126861e-8, 1.25987, 0.0852715, -560067e-11, 0.279021, 171162e-11, 0.0854143, -140871e-9, 0.279483, 430516e-10, 0.0854191, -563385e-9, 0.2795, 172184e-9, 0.0854188, -126753e-8, 0.279493, 387464e-9, 0.0854229, -225337e-8, 0.279501, 68918e-8, 0.0854443, -352086e-8, 0.279549, 107803e-8, 0.0854697, -506962e-8, 0.279591, 155536e-8, 0.0855093, -689873e-8, 0.279652, 212354e-8, 0.0855724, -900821e-8, 0.279752, 278703e-8, 0.0856991, -0.0113799, 0.280011, 35551e-7, 0.085855, -0.0140314, 0.280297, 443449e-8, 0.0860682, -0.016963, 0.280682, 543636e-8, 0.086344, -0.0201438, 0.281159, 65788e-7, 0.0867426, -0.0235999, 0.281886, 787977e-8, 0.087239, -0.0273069, 0.282745, 93606e-7, 0.0879815, -0.031269, 0.284139, 0.011056, 0.0891258, -0.035531, 0.28647, 0.0130065, 0.0906909, -0.0400947, 0.289708, 0.0152495, 0.0927624, -0.0449638, 0.293904, 0.0178454, 0.0958376, -0.0502427, 0.300471, 0.0208915, 0.0995827, -0.0559514, 0.30806, 0.0244247, 0.104526, -0.0622152, 0.317874, 0.0285721, 0.110532, -0.0690046, 0.329332, 0.0334227, 0.117385, -0.0763068, 0.341217, 0.0390466, 0.12522, -0.084184, 0.353968, 0.0455786, 0.134037, -0.0925248, 0.366797, 0.0530773, 0.144014, -0.101487, 0.380209, 0.0617424, 0.156013, -0.111273, 0.395956, 0.071777, 0.168872, -0.121431, 0.41053, 0.0830905, 0.183089, -0.132105, 0.425073, 0.0959341, 0.198763, -0.143286, 0.439833, 0.110448, 0.216159, -0.154841, 0.454507, 0.126769, 0.234859, -0.166588, 0.468368, 0.14495, 0.255879, -0.178626, 0.482846, 0.165233, 0.27677, -0.190218, 0.493489, 0.187217, 0.301184, -0.202227, 0.506549, 0.211659, 0.325852, -0.213764, 0.5158, 0.237922, 0.352824, -0.22487, 0.525442, 0.26632, 0.380882, -0.235246, 0.532487, 0.296691, 0.410137, -0.244847, 0.537703, 0.329179, 0.439787, -0.253122, 0.540361, 0.363135, 0.472291, -0.260517, 0.542734, 0.399222, 0.501856, -0.266519, 0.538826, 0.436352, 0.534816, -0.270905, 0.535152, 0.474505, 0.565069, -0.273826, 0.525979, 0.513988, 0.597154, -0.275333, 0.516394, 0.554852, 0.630473, -0.275314, 0.506206, 0.596592, 0.660574, -0.273323, 0.489769, 0.638117, 0.692015, -0.270008, 0.472578, 0.680457, 0.720647, -0.265001, 0.452134, 0.723008, 0.750528, -0.258311, 0.430344, 0.765954, 0.777568, -0.250046, 0.405624, 0.809012, 0.80387, -0.240114, 0.378339, 0.852425, 0.828439, -0.228737, 0.349877, 0.895346, 0.851472, -0.216632, 0.318968, 0.940695, 0.873906, -0.202782, 0.287489, 0.987235, 0.89467, -0.187059, 0.254394, 1.03348, 0.912281, -0.168818, 0.221294, 1.07812, 0.927358, -0.146494, 0.18675, 1.11928, 0.940385, -0.120009, 0.152322, 1.15609, 0.952672, -0.0917183, 0.117514, 1.18875, 0.968496, -0.0620321, 0.0797405, 1.21821, 0.985236, -0.0314945, 0.0402383, 1.24523, 0.99998, -575153e-9, 110644e-9, 1.27133, 0.0702429, -512222e-11, 0.255273, 140947e-11, 0.0702981, -128826e-9, 0.255469, 354488e-10, 0.0703691, -515562e-9, 0.255727, 141874e-9, 0.0703805, -116e-5, 0.255754, 31929e-8, 0.0703961, -206224e-8, 0.255813, 567999e-9, 0.0704102, -322223e-8, 0.255839, 88871e-8, 0.0704298, -463928e-8, 0.255863, 128272e-8, 0.0704759, -631375e-8, 0.255953, 175283e-8, 0.0705434, -824317e-8, 0.256079, 230342e-8, 0.0706693, -0.010412, 0.25636, 29443e-7, 0.0708189, -0.0128439, 0.256647, 368031e-8, 0.0710364, -0.0155177, 0.257084, 452614e-8, 0.0713223, -0.0184374, 0.257637, 549706e-8, 0.0717182, -0.0216002, 0.258416, 661246e-8, 0.072321, -0.0249966, 0.259699, 790147e-8, 0.0731446, -0.0286566, 0.261475, 93884e-7, 0.0743352, -0.0325888, 0.264132, 0.0111186, 0.0760676, -0.036843, 0.26815, 0.013145, 0.078454, -0.0414292, 0.273636, 0.0155251, 0.0818618, -0.0464634, 0.281653, 0.0183525, 0.0857382, -0.0519478, 0.289992, 0.0216642, 0.0908131, -0.0579836, 0.30066, 0.0255956, 0.0967512, -0.0645124, 0.312204, 0.0301954, 0.103717, -0.0716505, 0.325001, 0.0356017, 0.111596, -0.0793232, 0.338129, 0.041896, 0.120933, -0.087645, 0.352853, 0.0492447, 0.130787, -0.096492, 0.366192, 0.0576749, 0.142311, -0.105973, 0.380864, 0.0673969, 0.155344, -0.116182, 0.396575, 0.0785899, 0.169535, -0.126815, 0.411443, 0.0912377, 0.185173, -0.138015, 0.426256, 0.105607, 0.201755, -0.149325, 0.439607, 0.121551, 0.221334, -0.161207, 0.455467, 0.139608, 0.241461, -0.173162, 0.469096, 0.159591, 0.26294, -0.18504, 0.481014, 0.18156, 0.286776, -0.196881, 0.493291, 0.205781, 0.311596, -0.208311, 0.503556, 0.231819, 0.338667, -0.219671, 0.513268, 0.260274, 0.366021, -0.230451, 0.519414, 0.290862, 0.395875, -0.240131, 0.526766, 0.323196, 0.425564, -0.248566, 0.52905, 0.357071, 0.457094, -0.256195, 0.530796, 0.393262, 0.488286, -0.262331, 0.528703, 0.430797, 0.522291, -0.267141, 0.52727, 0.470231, 0.554172, -0.270411, 0.519848, 0.510477, 0.586427, -0.271986, 0.510307, 0.551594, 0.619638, -0.27192, 0.499158, 0.593849, 0.650656, -0.269817, 0.483852, 0.636314, 0.68284, -0.266267, 0.467515, 0.679679, 0.714356, -0.26113, 0.44931, 0.723884, 0.742717, -0.254067, 0.425789, 0.767245, 0.770894, -0.245652, 0.401144, 0.811819, 0.797358, -0.235554, 0.374224, 0.856315, 0.823377, -0.223896, 0.346167, 0.901077, 0.847456, -0.210865, 0.316056, 0.946502, 0.870697, -0.196574, 0.284503, 0.993711, 0.891068, -0.180814, 0.251628, 1.04134, 0.909267, -0.163314, 0.219065, 1.08609, 0.925653, -0.143304, 0.186446, 1.12702, 0.940017, -0.121322, 0.153416, 1.16371, 0.952398, -0.0973872, 0.120334, 1.19712, 0.967568, -0.0698785, 0.08352, 1.22791, 0.984772, -0.0390031, 0.0439209, 1.25672, 1.00026, -70087e-7, 315668e-8, 1.28428, 0.0556653, -459654e-11, 0.227325, 112556e-11, 0.0565238, -116382e-9, 0.230826, 284985e-10, 0.0565717, -465666e-9, 0.231026, 114036e-9, 0.0565859, -104773e-8, 0.231079, 256656e-9, 0.0565761, -186255e-8, 0.231025, 45663e-8, 0.0565913, -291002e-8, 0.231058, 714664e-9, 0.0566108, -418998e-8, 0.231085, 103224e-8, 0.0566532, -570206e-8, 0.231169, 141202e-8, 0.0567473, -743666e-8, 0.231417, 186018e-8, 0.0568567, -940298e-8, 0.231661, 238264e-8, 0.0569859, -0.0115991, 0.231895, 298699e-8, 0.0572221, -0.0140096, 0.232456, 368957e-8, 0.057519, -0.0166508, 0.233096, 450303e-8, 0.0579534, -0.01951, 0.234094, 544945e-8, 0.0585922, -0.0225991, 0.235629, 655564e-8, 0.0595647, -0.0259416, 0.238106, 785724e-8, 0.0609109, -0.0295661, 0.241557, 939127e-8, 0.0628751, -0.0335126, 0.246652, 0.0112198, 0.0656908, -0.0378604, 0.254091, 0.0134168, 0.0691347, -0.0426543, 0.262666, 0.0160374, 0.0732165, -0.0478967, 0.272029, 0.0191514, 0.0782863, -0.0536716, 0.283007, 0.0228597, 0.0843973, -0.0600683, 0.295732, 0.0272829, 0.0913598, -0.0670095, 0.308779, 0.032484, 0.0994407, -0.0745516, 0.322886, 0.0385886, 0.108189, -0.082712, 0.336408, 0.0457133, 0.118574, -0.0914927, 0.351692, 0.0539832, 0.129989, -0.100854, 0.366502, 0.0635162, 0.142722, -0.110837, 0.381675, 0.0744386, 0.156654, -0.121353, 0.3963, 0.0868483, 0.172151, -0.132414, 0.411477, 0.100963, 0.188712, -0.143809, 0.42508, 0.116795, 0.208093, -0.155765, 0.441328, 0.134715, 0.227936, -0.167608, 0.454328, 0.154396, 0.249495, -0.179579, 0.467235, 0.176179, 0.27362, -0.191488, 0.480248, 0.200193, 0.296371, -0.202618, 0.487886, 0.225775, 0.324234, -0.214133, 0.499632, 0.25441, 0.353049, -0.225212, 0.509532, 0.285077, 0.381785, -0.234875, 0.514265, 0.317047, 0.414038, -0.244205, 0.521282, 0.351874, 0.445251, -0.252145, 0.522931, 0.388279, 0.476819, -0.258433, 0.520947, 0.425825, 0.509209, -0.263411, 0.517669, 0.465104, 0.542759, -0.266732, 0.512841, 0.505741, 0.574822, -0.268263, 0.503317, 0.547611, 0.609324, -0.268489, 0.493035, 0.590953, 0.641772, -0.266941, 0.478816, 0.63488, 0.674049, -0.263297, 0.462863, 0.679072, 0.705071, -0.257618, 0.442931, 0.723487, 0.734709, -0.250625, 0.421299, 0.768708, 0.763704, -0.24179, 0.397085, 0.814375, 0.791818, -0.231115, 0.370577, 0.859907, 0.817439, -0.21922, 0.34232, 0.906715, 0.843202, -0.205658, 0.312627, 0.953943, 0.866639, -0.190563, 0.280933, 1.00185, 0.888129, -0.173978, 0.248393, 1.05105, 0.907239, -0.155485, 0.216007, 1.09704, 0.923893, -0.134782, 0.183233, 1.13857, 0.938882, -0.11249, 0.150376, 1.17539, 0.952464, -0.0890706, 0.117177, 1.20924, 0.968529, -0.0646523, 0.0813095, 1.24055, 0.984763, -0.038606, 0.0439378, 1.27018, 1.00053, -0.01238, 598668e-8, 1.29873, 0.0437928, -409594e-11, 0.204012, 879224e-12, 0.0440166, -103395e-9, 0.205049, 221946e-10, 0.0440529, -413633e-9, 0.205225, 887981e-10, 0.0440493, -930594e-9, 0.2052, 199858e-9, 0.0439884, -165352e-8, 0.204901, 355495e-9, 0.0440716, -25849e-7, 0.205255, 556983e-9, 0.0440968, -372222e-8, 0.205311, 805326e-9, 0.0441359, -506478e-8, 0.205391, 110333e-8, 0.0442231, -660384e-8, 0.205638, 145768e-8, 0.0443254, -835246e-8, 0.205877, 187275e-8, 0.0444832, -0.0102992, 0.20627, 235938e-8, 0.0447001, -0.0124449, 0.206796, 29299e-7, 0.0450168, -0.0147935, 0.207593, 36005e-7, 0.0454816, -0.017336, 0.208819, 439246e-8, 0.0462446, -0.0201156, 0.211036, 533864e-8, 0.0473694, -0.0231568, 0.214388, 646984e-8, 0.0490191, -0.0264941, 0.219357, 783856e-8, 0.0512776, -0.030184, 0.226061, 950182e-8, 0.0541279, -0.0342661, 0.234094, 0.0115156, 0.0578989, -0.0388539, 0.244297, 0.0139687, 0.0620835, -0.0438735, 0.254457, 0.0169015, 0.0673497, -0.04951, 0.266706, 0.0204554, 0.0731759, -0.0556263, 0.278753, 0.0246606, 0.0803937, -0.0624585, 0.29309, 0.0297126, 0.0879287, -0.0697556, 0.305856, 0.0355868, 0.0970669, -0.0778795, 0.321059, 0.0425768, 0.106508, -0.0863541, 0.333873, 0.05056, 0.11776, -0.0955935, 0.349008, 0.0598972, 0.130081, -0.105438, 0.363776, 0.0706314, 0.144454, -0.115899, 0.380112, 0.0828822, 0.1596, -0.126827, 0.394843, 0.0967611, 0.176097, -0.138161, 0.409033, 0.112381, 0.194726, -0.149904, 0.424257, 0.129952, 0.213944, -0.161675, 0.436945, 0.149333, 0.235516, -0.173659, 0.450176, 0.170892, 0.260564, -0.185963, 0.466305, 0.194984, 0.285183, -0.197582, 0.477328, 0.220805, 0.311095, -0.208697, 0.486566, 0.248694, 0.338924, -0.219519, 0.494811, 0.279015, 0.369757, -0.229766, 0.504065, 0.311725, 0.3996, -0.238879, 0.507909, 0.345844, 0.430484, -0.246802, 0.509805, 0.381749, 0.46413, -0.253924, 0.511436, 0.420251, 0.497077, -0.259319, 0.508787, 0.459957, 0.530434, -0.263297, 0.50394, 0.501356, 0.565725, -0.265619, 0.49804, 0.544252, 0.599254, -0.265842, 0.487346, 0.587856, 0.631251, -0.263978, 0.472975, 0.631969, 0.663972, -0.26043, 0.457135, 0.677471, 0.697724, -0.255358, 0.439844, 0.723744, 0.727725, -0.248308, 0.417872, 0.770653, 0.756417, -0.239181, 0.39273, 0.817357, 0.785419, -0.22814, 0.367839, 0.864221, 0.81266, -0.215681, 0.339449, 0.912701, 0.839391, -0.201623, 0.309279, 0.962419, 0.86366, -0.185624, 0.278029, 1.0122, 0.885028, -0.16797, 0.245294, 1.06186, 0.904639, -0.148336, 0.212689, 1.10934, 0.922048, -0.12637, 0.179616, 1.15063, 0.936952, -0.102928, 0.146749, 1.18885, 0.951895, -0.0785268, 0.112733, 1.22352, 0.967198, -0.0530153, 0.0760056, 1.25681, 0.984405, -0.02649, 0.0383183, 1.28762, 1.00021, 70019e-8, -20039e-8, 1.31656, 0.0325964, -355447e-11, 0.176706, 655682e-12, 0.0329333, -899174e-10, 0.178527, 165869e-10, 0.0329181, -359637e-9, 0.178453, 663498e-10, 0.0329085, -808991e-9, 0.178383, 149332e-9, 0.0329181, -143826e-8, 0.178394, 265873e-9, 0.0329425, -224678e-8, 0.178517, 416597e-9, 0.0329511, -323575e-8, 0.17849, 603299e-9, 0.033011, -439875e-8, 0.178695, 829422e-9, 0.0330733, -574059e-8, 0.178843, 109908e-8, 0.0331857, -725896e-8, 0.179176, 141933e-8, 0.0333445, -895289e-8, 0.179618, 17999e-7, 0.0335674, -0.0108219, 0.180238, 225316e-8, 0.033939, -0.0128687, 0.181417, 279765e-8, 0.0345239, -0.015114, 0.183395, 34564e-7, 0.0354458, -0.017596, 0.186616, 425864e-8, 0.0368313, -0.0203524, 0.191547, 524936e-8, 0.0386115, -0.0234105, 0.197508, 647033e-8, 0.0410303, -0.0268509, 0.205395, 798121e-8, 0.0442245, -0.0307481, 0.215365, 98557e-7, 0.0478659, -0.0350863, 0.225595, 0.0121417, 0.0522416, -0.0399506, 0.236946, 0.0149385, 0.0574513, -0.045357, 0.249442, 0.0183189, 0.0631208, -0.0512863, 0.261222, 0.0223644, 0.0701124, -0.0579273, 0.275418, 0.0272418, 0.0777331, -0.0650652, 0.288989, 0.0329458, 0.0862709, -0.0728813, 0.302546, 0.0396819, 0.096103, -0.081363, 0.317164, 0.04757, 0.106976, -0.0904463, 0.331733, 0.0567012, 0.119175, -0.100105, 0.34661, 0.067202, 0.132919, -0.110375, 0.362249, 0.0792588, 0.147727, -0.121115, 0.376978, 0.0928672, 0.163618, -0.132299, 0.390681, 0.108228, 0.182234, -0.143887, 0.406571, 0.125502, 0.201809, -0.155827, 0.42042, 0.144836, 0.225041, -0.168357, 0.438411, 0.166706, 0.247621, -0.18004, 0.450368, 0.189909, 0.27097, -0.191536, 0.460083, 0.215251, 0.296658, -0.203024, 0.469765, 0.243164, 0.325892, -0.214056, 0.481837, 0.273388, 0.35406, -0.224104, 0.487474, 0.305344, 0.384372, -0.233489, 0.492773, 0.339741, 0.41749, -0.241874, 0.498451, 0.376287, 0.45013, -0.248834, 0.499632, 0.414195, 0.481285, -0.254658, 0.495233, 0.454077, 0.519183, -0.259367, 0.496401, 0.496352, 0.551544, -0.261818, 0.487686, 0.538798, 0.587349, -0.262964, 0.479453, 0.583626, 0.621679, -0.262128, 0.467709, 0.629451, 0.654991, -0.258998, 0.452123, 0.67566, 0.686873, -0.254119, 0.433495, 0.723248, 0.719801, -0.246946, 0.413657, 0.771156, 0.750355, -0.237709, 0.390366, 0.81989, 0.780033, -0.226549, 0.364947, 0.868601, 0.809254, -0.214186, 0.337256, 0.920034, 0.836576, -0.199639, 0.307395, 0.971706, 0.861774, -0.183169, 0.275431, 1.02479, 0.885707, -0.165111, 0.243431, 1.07837, 0.904742, -0.144363, 0.210921, 1.12783, 0.915604, -0.121305, 0.17647, 1.17254, 0.930959, -0.0962119, 0.143106, 1.21012, 0.948404, -0.069969, 0.108112, 1.24474, 0.967012, -0.0427586, 0.0708478, 1.27718, 0.984183, -0.0147043, 0.032335, 1.3083, 0.999577, 0.0142165, -726867e-8, 1.3382, 0.0229227, -299799e-11, 0.148623, 462391e-12, 0.0232194, -758796e-10, 0.15054, 117033e-10, 0.0232315, -303636e-9, 0.15063, 468397e-10, 0.0232354, -683189e-9, 0.150624, 105472e-9, 0.0232092, -12136e-7, 0.150445, 187744e-9, 0.0232523, -189765e-8, 0.150679, 294847e-9, 0.0232828, -273247e-8, 0.150789, 428013e-9, 0.0233371, -371287e-8, 0.150995, 591134e-9, 0.0234015, -484794e-8, 0.15118, 787642e-9, 0.023514, -612877e-8, 0.151562, 102547e-8, 0.023679, -756125e-8, 0.152116, 131351e-8, 0.0239559, -914651e-8, 0.153162, 166594e-8, 0.0244334, -0.010904, 0.155133, 210182e-8, 0.025139, -0.0128615, 0.158035, 264406e-8, 0.0262598, -0.0150628, 0.162751, 332923e-8, 0.0277875, -0.0175532, 0.168944, 419773e-8, 0.0298472, -0.0203981, 0.176835, 530034e-8, 0.0325444, -0.023655, 0.186686, 669777e-8, 0.0355581, -0.0272982, 0.196248, 842661e-8, 0.0392841, -0.0314457, 0.207352, 0.0105854, 0.0436815, -0.0361157, 0.219279, 0.0132458, 0.0485272, -0.0412932, 0.230728, 0.0164736, 0.0541574, -0.0470337, 0.242994, 0.0203715, 0.0609479, -0.0535002, 0.257042, 0.0250953, 0.0685228, -0.0605409, 0.27102, 0.0306856, 0.0768042, -0.0680553, 0.28406, 0.037193, 0.0864844, -0.0765011, 0.299186, 0.0449795, 0.0969415, -0.0852674, 0.3132, 0.0538316, 0.108478, -0.0947333, 0.327138, 0.0641149, 0.121705, -0.10481, 0.342345, 0.0759185, 0.136743, -0.115474, 0.358472, 0.0894116, 0.152986, -0.126536, 0.374067, 0.104562, 0.170397, -0.138061, 0.388267, 0.121632, 0.191392, -0.150203, 0.406467, 0.140996, 0.211566, -0.161751, 0.418641, 0.161696, 0.233567, -0.173407, 0.430418, 0.184557, 0.257769, -0.185397, 0.44277, 0.210092, 0.28531, -0.197048, 0.457191, 0.237827, 0.311726, -0.20784, 0.464712, 0.267253, 0.340537, -0.218345, 0.472539, 0.299332, 0.372921, -0.228306, 0.482331, 0.333988, 0.402924, -0.236665, 0.484378, 0.369722, 0.434475, -0.244097, 0.484717, 0.407836, 0.469736, -0.250547, 0.487093, 0.448465, 0.505045, -0.25511, 0.485575, 0.490263, 0.540262, -0.258444, 0.481225, 0.534495, 0.576347, -0.259903, 0.473481, 0.579451, 0.608656, -0.259572, 0.4603, 0.625604, 0.646679, -0.257908, 0.450341, 0.674511, 0.679902, -0.253663, 0.431561, 0.723269, 0.714159, -0.247419, 0.412684, 0.773263, 0.745345, -0.239122, 0.389388, 0.824182, 0.778248, -0.228837, 0.365361, 0.876634, 0.807208, -0.216197, 0.337667, 0.92945, 0.835019, -0.201772, 0.307197, 0.985261, 0.860261, -0.185291, 0.274205, 1.04299, 0.877601, -0.165809, 0.240178, 1.09816, 0.898211, -0.143897, 0.207571, 1.14694, 0.915789, -0.119513, 0.174904, 1.19008, 0.931831, -0.0932919, 0.141423, 1.2297, 0.949244, -0.0656528, 0.105603, 1.26553, 0.967527, -0.0370262, 0.0679551, 1.29986, 0.984139, -730117e-8, 0.0283133, 1.33252, 0.999713, 0.0234648, -0.0121785, 1.36397, 0.0152135, -245447e-11, 0.122795, 304092e-12, 0.0151652, -615778e-10, 0.122399, 76292e-10, 0.0151181, -245948e-9, 0.122023, 304802e-10, 0.0151203, -553394e-9, 0.12203, 686634e-10, 0.015125, -983841e-9, 0.122037, 122463e-9, 0.0151427, -153774e-8, 0.12214, 192706e-9, 0.0151708, -22103e-7, 0.122237, 281219e-9, 0.0152115, -300741e-8, 0.12238, 390804e-9, 0.0152877, -392494e-8, 0.1227, 526317e-9, 0.015412, -496597e-8, 0.123244, 69443e-8, 0.0156201, -613314e-8, 0.124228, 90547e-8, 0.0159658, -744113e-8, 0.125945, 11732e-7, 0.0165674, -892546e-8, 0.129098, 151888e-8, 0.017487, -0.010627, 0.133865, 197007e-8, 0.018839, -0.0126043, 0.140682, 25637e-7, 0.020554, -0.0148814, 0.148534, 333637e-8, 0.0226727, -0.0175123, 0.157381, 433738e-8, 0.0251879, -0.0205266, 0.166685, 561664e-8, 0.0283635, -0.0240319, 0.177796, 725563e-8, 0.0318694, -0.0279432, 0.188251, 928811e-8, 0.0361044, -0.0324313, 0.200038, 0.011835, 0.0406656, -0.0373527, 0.210685, 0.0149146, 0.0463846, -0.0430132, 0.224182, 0.0187254, 0.0525696, -0.0491013, 0.23634, 0.0232283, 0.0598083, -0.0559175, 0.250013, 0.0286521, 0.0679437, -0.0633657, 0.263981, 0.0350634, 0.0771181, -0.0714602, 0.278072, 0.0425882, 0.0881273, -0.0803502, 0.29511, 0.0514487, 0.0996628, -0.0896903, 0.309976, 0.0615766, 0.112702, -0.099644, 0.325611, 0.0732139, 0.126488, -0.109829, 0.339321, 0.0862324, 0.142625, -0.120859, 0.35574, 0.101275, 0.15953, -0.131956, 0.369845, 0.117892, 0.176991, -0.143145, 0.38146, 0.136205, 0.199715, -0.155292, 0.40052, 0.157252, 0.220787, -0.167066, 0.412055, 0.179966, 0.243697, -0.178396, 0.423133, 0.204418, 0.272106, -0.190433, 0.439524, 0.232141, 0.297637, -0.201265, 0.447041, 0.261109, 0.325273, -0.211834, 0.454488, 0.292627, 0.357219, -0.221889, 0.465004, 0.326669, 0.387362, -0.230729, 0.468527, 0.362426, 0.423131, -0.23924, 0.475836, 0.401533, 0.45543, -0.246067, 0.475017, 0.441902, 0.493393, -0.251557, 0.478017, 0.484239, 0.526253, -0.255571, 0.4709, 0.528586, 0.560554, -0.257752, 0.463167, 0.574346, 0.599306, -0.258076, 0.456452, 0.621655, 0.634541, -0.256471, 0.443725, 0.670492, 0.668907, -0.253283, 0.428719, 0.721943, 0.705619, -0.247562, 0.411348, 0.772477, 0.739034, -0.240626, 0.388939, 0.8264, 0.771408, -0.231493, 0.36425, 0.881702, 0.803312, -0.220125, 0.337321, 0.9385, 0.828457, -0.206645, 0.305364, 0.997437, 0.854819, -0.190664, 0.273715, 1.05693, 0.878666, -0.171429, 0.242218, 1.11251, 0.898404, -0.149235, 0.209556, 1.16398, 0.917416, -0.12435, 0.176863, 1.21014, 0.933133, -0.0972703, 0.142775, 1.25178, 0.95066, -0.0683607, 0.106735, 1.29028, 0.968589, -0.0378724, 0.0681609, 1.32703, 0.984776, -605712e-8, 0.0273966, 1.36158, 0.99994, 0.0263276, -0.0138124, 1.3943, 867437e-8, -186005e-11, 0.0928979, 173682e-12, 864003e-8, -466389e-10, 0.0925237, 435505e-11, 864593e-8, -186594e-9, 0.0925806, 174322e-10, 864095e-8, -419639e-9, 0.0924903, 392862e-10, 863851e-8, -746272e-9, 0.0924589, 702598e-10, 868531e-8, -116456e-8, 0.0929, 111188e-9, 869667e-8, -167711e-8, 0.0928529, 163867e-9, 874332e-8, -228051e-8, 0.0930914, 23104e-8, 882709e-8, -297864e-8, 0.0935679, 31741e-8, 898874e-8, -377557e-8, 0.0946165, 430186e-9, 929346e-8, -469247e-8, 0.0967406, 580383e-9, 978271e-8, -575491e-8, 0.100084, 783529e-9, 0.0105746, -701514e-8, 0.105447, 106304e-8, 0.0116949, -851797e-8, 0.112494, 144685e-8, 0.0130419, -0.0102757, 0.119876, 196439e-8, 0.0148375, -0.012381, 0.129034, 266433e-8, 0.0168725, -0.01482, 0.137812, 358364e-8, 0.0193689, -0.0176563, 0.147696, 478132e-8, 0.0222691, -0.0209211, 0.157795, 631721e-8, 0.0256891, -0.0246655, 0.168431, 826346e-8, 0.0294686, -0.0288597, 0.178587, 0.0106714, 0.0340412, -0.0336441, 0.190251, 0.0136629, 0.0393918, -0.039033, 0.202999, 0.0173272, 0.0453947, -0.0450087, 0.215655, 0.0217448, 0.0521936, -0.0515461, 0.228686, 0.0269941, 0.0600279, -0.058817, 0.242838, 0.033272, 0.0692398, -0.0667228, 0.258145, 0.0406457, 0.0793832, -0.0752401, 0.273565, 0.0492239, 0.0902297, -0.0841851, 0.287735, 0.0590105, 0.102014, -0.0936479, 0.301161, 0.0702021, 0.116054, -0.103967, 0.317438, 0.0832001, 0.13191, -0.114622, 0.334166, 0.0977951, 0.148239, -0.125452, 0.348192, 0.113985, 0.165809, -0.136453, 0.361094, 0.131928, 0.184616, -0.147648, 0.373534, 0.151811, 0.207491, -0.159607, 0.39101, 0.174476, 0.230106, -0.171119, 0.402504, 0.198798, 0.257036, -0.182906, 0.418032, 0.225796, 0.281172, -0.193605, 0.425468, 0.254027, 0.312034, -0.204771, 0.440379, 0.285713, 0.340402, -0.214988, 0.445406, 0.319196, 0.370231, -0.224711, 0.44968, 0.35537, 0.407105, -0.233516, 0.460747, 0.393838, 0.439037, -0.240801, 0.460624, 0.433747, 0.47781, -0.24762, 0.465957, 0.477234, 0.510655, -0.251823, 0.460054, 0.52044, 0.550584, -0.255552, 0.459172, 0.567853, 0.585872, -0.257036, 0.450311, 0.615943, 0.620466, -0.257535, 0.437763, 0.667693, 0.660496, -0.255248, 0.426639, 0.718988, 0.695578, -0.251141, 0.409185, 0.772503, 0.732176, -0.244718, 0.39015, 0.827023, 0.760782, -0.236782, 0.362594, 0.885651, 0.79422, -0.225923, 0.33711, 0.943756, 0.824521, -0.213855, 0.308272, 1.00874, 0.854964, -0.197723, 0.278529, 1.06764, 0.878065, -0.179209, 0.246208, 1.12836, 0.899834, -0.157569, 0.21329, 1.18318, 0.918815, -0.133206, 0.181038, 1.23161, 0.934934, -0.106545, 0.146993, 1.27644, 0.952115, -0.0780574, 0.111175, 1.31842, 0.96906, -0.0478279, 0.0728553, 1.35839, 0.985178, -0.0160014, 0.032579, 1.39697, 1.00039, 0.0173126, -95256e-7, 1.43312, 384146e-8, -124311e-11, 0.0613583, 778271e-13, 390023e-8, -314043e-10, 0.0622919, 196626e-11, 389971e-8, -125622e-9, 0.0622632, 787379e-11, 389491e-8, -282352e-9, 0.0620659, 1778e-8, 391618e-8, -502512e-9, 0.0624687, 320918e-10, 392662e-8, -784458e-9, 0.0625113, 515573e-10, 396053e-8, -112907e-8, 0.0628175, 778668e-10, 401911e-8, -153821e-8, 0.0633286, 113811e-9, 414994e-8, -20208e-7, 0.0646443, 16445e-8, 441223e-8, -260007e-8, 0.0673886, 237734e-9, 484427e-8, -33097e-7, 0.0716528, 345929e-9, 549109e-8, -418966e-8, 0.0774998, 505987e-9, 636293e-8, -527331e-8, 0.0844758, 739208e-9, 746566e-8, -660428e-8, 0.0921325, 107347e-8, 876625e-8, -818826e-8, 0.0997067, 153691e-8, 0.0103125, -0.0100811, 0.107433, 217153e-8, 0.0123309, -0.0123643, 0.117088, 303427e-8, 0.0146274, -0.0150007, 0.126438, 416018e-8, 0.0172295, -0.0180531, 0.135672, 561513e-8, 0.0204248, -0.0215962, 0.146244, 7478e-6, 0.0241597, -0.0256234, 0.157481, 981046e-8, 0.0284693, -0.0302209, 0.169125, 0.0127148, 0.033445, -0.0353333, 0.181659, 0.0162453, 0.0391251, -0.0410845, 0.1944, 0.0205417, 0.0454721, -0.0473451, 0.207082, 0.0256333, 0.0530983, -0.0542858, 0.221656, 0.0317036, 0.0615356, -0.0618384, 0.236036, 0.0388319, 0.0703363, -0.0697631, 0.248398, 0.046974, 0.0810391, -0.0784757, 0.263611, 0.0565246, 0.0920144, -0.0873488, 0.275857, 0.0671724, 0.105584, -0.0973652, 0.292555, 0.0798105, 0.119506, -0.107271, 0.306333, 0.0935945, 0.134434, -0.117608, 0.318888, 0.109106, 0.153399, -0.128938, 0.337552, 0.127074, 0.171258, -0.139944, 0.349955, 0.14643, 0.191059, -0.151288, 0.361545, 0.168, 0.215069, -0.163018, 0.378421, 0.192082, 0.237838, -0.174226, 0.38879, 0.217838, 0.266965, -0.186063, 0.405857, 0.246931, 0.292827, -0.196909, 0.414146, 0.277505, 0.324352, -0.207473, 0.426955, 0.310711, 0.354427, -0.217713, 0.433429, 0.346794, 0.389854, -0.227183, 0.443966, 0.385237, 0.420749, -0.235131, 0.44471, 0.424955, 0.459597, -0.242786, 0.451729, 0.468446, 0.495316, -0.248767, 0.45072, 0.513422, 0.534903, -0.253351, 0.450924, 0.560618, 0.572369, -0.256277, 0.445266, 0.609677, 0.612383, -0.2576, 0.438798, 0.660995, 0.644037, -0.256931, 0.421693, 0.713807, 0.686749, -0.254036, 0.4109, 0.767616, 0.719814, -0.249785, 0.390151, 0.82533, 0.754719, -0.244283, 0.367847, 0.888311, 0.792022, -0.235076, 0.345013, 0.948177, 0.822404, -0.225061, 0.316193, 1.01661, 0.853084, -0.211113, 0.287013, 1.08075, 0.879871, -0.19449, 0.255424, 1.14501, 0.901655, -0.174023, 0.222879, 1.20203, 0.919957, -0.1509, 0.18989, 1.25698, 0.938412, -0.124923, 0.15606, 1.30588, 0.953471, -0.0968139, 0.120512, 1.3529, 0.970451, -0.066734, 0.0828515, 1.3986, 0.985522, -0.034734, 0.0424458, 1.44148, 1.00099, -102222e-8, 678929e-9, 1.48398, 965494e-9, -627338e-12, 0.0306409, 197672e-13, 99168e-8, -158573e-10, 0.0314638, 499803e-12, 991068e-9, -634012e-10, 0.031363, 200682e-11, 974567e-9, -14144e-8, 0.03036, 457312e-11, 998079e-9, -252812e-9, 0.031496, 860131e-11, 102243e-8, -396506e-9, 0.0319955, 148288e-10, 107877e-8, -577593e-9, 0.0331376, 249141e-10, 121622e-8, -816816e-9, 0.0359396, 423011e-10, 14455e-7, -113761e-8, 0.0399652, 724613e-10, 178791e-8, -156959e-8, 0.0450556, 123929e-9, 225668e-8, -214064e-8, 0.0508025, 208531e-9, 285627e-8, -287655e-8, 0.0568443, 341969e-9, 35991e-7, -380271e-8, 0.0630892, 544158e-9, 455524e-8, -496264e-8, 0.0702204, 842423e-9, 569143e-8, -63793e-7, 0.0773426, 126704e-8, 716928e-8, -813531e-8, 0.0860839, 186642e-8, 885307e-8, -0.0101946, 0.0944079, 267014e-8, 0.0109316, -0.0126386, 0.103951, 374033e-8, 0.0133704, -0.0154876, 0.113786, 51304e-7, 0.0161525, -0.0187317, 0.123477, 688858e-8, 0.0194267, -0.0224652, 0.133986, 910557e-8, 0.0230967, -0.0265976, 0.143979, 0.0118074, 0.0273627, -0.0312848, 0.154645, 0.0151266, 0.0323898, -0.0365949, 0.166765, 0.0191791, 0.0379225, -0.0422914, 0.177932, 0.0239236, 0.0447501, -0.0487469, 0.19167, 0.0296568, 0.0519391, -0.0556398, 0.203224, 0.0362924, 0.0599464, -0.0631646, 0.215652, 0.0440585, 0.0702427, -0.0714308, 0.232089, 0.0531619, 0.0806902, -0.0800605, 0.245258, 0.0634564, 0.0923194, -0.0892815, 0.258609, 0.0752481, 0.106938, -0.09931, 0.276654, 0.0888914, 0.121238, -0.109575, 0.289847, 0.104055, 0.138817, -0.120461, 0.307566, 0.121266, 0.15595, -0.131209, 0.320117, 0.139944, 0.178418, -0.143049, 0.339677, 0.161591, 0.197875, -0.154074, 0.349886, 0.184303, 0.224368, -0.166307, 0.369352, 0.210669, 0.252213, -0.178051, 0.386242, 0.238895, 0.277321, -0.189335, 0.395294, 0.269182, 0.310332, -0.200683, 0.412148, 0.302508, 0.338809, -0.210856, 0.418266, 0.337264, 0.372678, -0.220655, 0.428723, 0.374881, 0.405632, -0.230053, 0.433887, 0.415656, 0.442293, -0.237993, 0.439911, 0.457982, 0.477256, -0.244897, 0.440175, 0.502831, 0.515592, -0.250657, 0.441079, 0.550277, 0.550969, -0.255459, 0.435219, 0.601102, 0.592883, -0.257696, 0.432882, 0.651785, 0.629092, -0.259894, 0.421054, 0.708961, 0.672033, -0.258592, 0.41177, 0.763806, 0.709147, -0.256525, 0.395267, 0.824249, 0.745367, -0.254677, 0.375013, 0.8951, 0.784715, -0.247892, 0.353906, 0.959317, 0.818107, -0.240162, 0.327801, 1.03153, 0.847895, -0.229741, 0.298821, 1.10601, 0.879603, -0.213084, 0.269115, 1.164, 0.902605, -0.195242, 0.236606, 1.22854, 0.922788, -0.174505, 0.203442, 1.29017, 0.944831, -0.150169, 0.169594, 1.34157, 0.959656, -0.124099, 0.135909, 1.3956, 0.972399, -0.0960626, 0.0990563, 1.45128, 0.986549, -0.0657097, 0.0602348, 1.50312, 1.00013, -0.0333558, 0.0186694, 1.55364, 619747e-11, -1e-7, 778326e-8, 796756e-16, 237499e-13, -999999e-13, 282592e-10, 114596e-15, 100292e-11, -166369e-11, 250354e-9, 677492e-14, 350752e-11, -637769e-11, 357289e-9, 631655e-13, 826445e-11, -174689e-10, 516179e-9, 31851e-11, 242481e-10, -450868e-10, 10223e-7, 130577e-11, 455631e-10, -89044e-9, 144302e-8, 374587e-11, 971222e-10, -178311e-9, 241912e-8, 102584e-10, 171403e-9, -313976e-9, 354938e-8, 236481e-10, 292747e-9, -520026e-9, 513765e-8, 496014e-10, 789827e-9, -118187e-8, 0.0238621, 139056e-9, 114093e-8, -171827e-8, 0.0286691, 244093e-9, 176119e-8, -249667e-8, 0.0368565, 420623e-9, 22233e-7, -333742e-8, 0.0400469, 65673e-8, 343382e-8, -481976e-8, 0.0535751, 109323e-8, 427602e-8, -600755e-8, 0.057099, 155268e-8, 461435e-8, -737637e-8, 0.0551084, 215031e-8, 695698e-8, -971401e-8, 0.0715767, 316529e-8, 867619e-8, -0.0120943, 0.0793314, 436995e-8, 0.0106694, -0.0148202, 0.0869391, 58959e-7, 0.0140351, -0.0183501, 0.101572, 798757e-8, 0.0168939, -0.022006, 0.11018, 0.0104233, 0.020197, -0.0261568, 0.119041, 0.0134167, 0.0254702, -0.0312778, 0.135404, 0.0173009, 0.0298384, -0.0362469, 0.1437, 0.0215428, 0.035159, -0.042237, 0.15512, 0.0268882, 0.0427685, -0.0488711, 0.17128, 0.033235, 0.0494848, -0.0557997, 0.181813, 0.0404443, 0.0592394, -0.0635578, 0.198745, 0.0490043, 0.0681463, -0.071838, 0.210497, 0.0588239, 0.0804753, -0.0809297, 0.228864, 0.0702835, 0.0942205, -0.0906488, 0.247008, 0.0834012, 0.106777, -0.100216, 0.258812, 0.0975952, 0.124471, -0.110827, 0.278617, 0.114162, 0.138389, -0.121193, 0.287049, 0.131983, 0.159543, -0.13253, 0.307151, 0.152541, 0.176432, -0.143611, 0.31564, 0.174673, 0.201723, -0.15548, 0.33538, 0.199842, 0.229721, -0.167166, 0.355256, 0.227097, 0.250206, -0.178238, 0.360047, 0.256014, 0.282118, -0.189905, 0.378761, 0.28855, 0.312821, -0.201033, 0.39181, 0.323348, 0.341482, -0.211584, 0.397716, 0.360564, 0.377368, -0.221314, 0.410141, 0.400004, 0.418229, -0.230474, 0.423485, 0.442371, 0.444881, -0.239443, 0.418874, 0.488796, 0.488899, -0.245987, 0.427545, 0.535012, 0.520317, -0.253948, 0.422147, 0.589678, 0.568566, -0.256616, 0.42719, 0.637683, 0.599607, -0.26376, 0.415114, 0.703363, 0.64222, -0.268687, 0.408715, 0.771363, 0.685698, -0.2694, 0.399722, 0.83574, 0.732327, -0.266642, 0.388651, 0.897764, 0.769873, -0.267712, 0.369198, 0.983312, 0.806733, -0.263479, 0.346802, 1.06222, 0.843466, -0.254575, 0.321368, 1.13477, 0.873008, -0.242749, 0.29211, 1.20712, 0.908438, -0.22725, 0.262143, 1.27465, 0.936321, -0.207621, 0.228876, 1.33203, 0.950353, -0.187932, 0.19484, 1.40439, 0.96442, -0.165154, 0.163178, 1.4732, 0.979856, -0.139302, 0.127531, 1.53574, 0.982561, -0.11134, 0.0903457, 1.59982, 0.996389, -0.0808124, 0.0489007, 1.6577];
    const LTC_MAT_2 = [1, 0, 0, 0, 1, 791421e-36, 0, 0, 1, 104392e-29, 0, 0, 1, 349405e-26, 0, 0, 1, 109923e-23, 0, 0, 1, 947414e-22, 0, 0, 1, 359627e-20, 0, 0, 1, 772053e-19, 0, 0, 1, 108799e-17, 0, 0, 1, 110655e-16, 0, 0, 1, 865818e-16, 0, 0, 0.999998, 545037e-15, 0, 0, 0.999994, 285095e-14, 0, 0, 0.999989, 126931e-13, 0, 0, 0.999973, 489938e-13, 0, 0, 0.999947, 166347e-12, 0, 0, 0.999894, 502694e-12, 0, 0, 0.999798, 136532e-11, 0, 0, 0.999617, 335898e-11, 0, 0, 0.999234, 752126e-11, 0, 0, 0.998258, 152586e-10, 0, 0, 0.99504, 266207e-10, 0, 0, 0.980816, 236802e-10, 0, 0, 0.967553, 207684e-11, 0, 0, 0.966877, 403733e-11, 0, 0, 0.965752, 741174e-11, 0, 0, 0.96382, 127746e-10, 0, 0, 0.960306, 202792e-10, 0, 0, 0.953619, 280232e-10, 0, 0, 0.941103, 278816e-10, 0, 0, 0.926619, 160221e-10, 0, 0, 0.920983, 235164e-10, 0, 0, 0.912293, 311924e-10, 0, 0.0158731, 0.899277, 348118e-10, 0, 0.0476191, 0.880884, 26041e-9, 0, 0.0793651, 0.870399, 338726e-10, 0, 0.111111, 0.856138, 392906e-10, 0, 0.142857, 0.837436, 372874e-10, 0, 0.174603, 0.820973, 392558e-10, 0, 0.206349, 0.803583, 434658e-10, 0, 0.238095, 0.782168, 40256e-9, 0, 0.269841, 0.764107, 448159e-10, 0, 0.301587, 0.743092, 457627e-10, 0, 0.333333, 0.721626, 455314e-10, 0, 0.365079, 0.700375, 477335e-10, 0, 0.396825, 0.677334, 461072e-10, 0, 0.428571, 0.655702, 484393e-10, 0, 0.460317, 0.632059, 464583e-10, 0, 0.492064, 0.610125, 483923e-10, 0, 0.52381, 0.58653, 464342e-10, 0, 0.555556, 0.564508, 477033e-10, 0, 0.587302, 0.541405, 459263e-10, 0, 0.619048, 0.519556, 46412e-9, 0, 0.650794, 0.497292, 448913e-10, 0, 0.68254, 0.475898, 445789e-10, 0, 0.714286, 0.454722, 433496e-10, 0, 0.746032, 0.434042, 423054e-10, 0, 0.777778, 0.414126, 413737e-10, 0, 0.809524, 0.394387, 397265e-10, 0, 0.84127, 0.375841, 390709e-10, 0, 0.873016, 0.357219, 369938e-10, 0, 0.904762, 0.340084, 365618e-10, 0, 0.936508, 0.322714, 342533e-10, 0, 0.968254, 0.306974, 339596e-10, 0, 1, 1, 101524e-23, 0, 0, 1, 10292e-22, 0, 0, 1, 130908e-23, 0, 0, 1, 473331e-23, 0, 0, 1, 625319e-22, 0, 0, 1, 107932e-20, 0, 0, 1, 163779e-19, 0, 0, 1, 203198e-18, 0, 0, 1, 204717e-17, 0, 0, 0.999999, 168995e-16, 0, 0, 0.999998, 115855e-15, 0, 0, 0.999996, 66947e-14, 0, 0, 0.999991, 330863e-14, 0, 0, 0.999983, 141737e-13, 0, 0, 0.999968, 532626e-13, 0, 0, 0.99994, 177431e-12, 0, 0, 0.999891, 528835e-12, 0, 0, 0.999797, 142169e-11, 0, 0, 0.999617, 347057e-11, 0, 0, 0.999227, 77231e-10, 0, 0, 0.998239, 155753e-10, 0, 0, 0.994937, 268495e-10, 0, 0, 0.980225, 213742e-10, 0, 0, 0.967549, 21631e-10, 0, 0, 0.966865, 417989e-11, 0, 0, 0.965739, 763341e-11, 0, 0, 0.963794, 130892e-10, 0, 0, 0.960244, 206456e-10, 0, 0, 0.953495, 282016e-10, 0, 148105e-9, 0.940876, 271581e-10, 0, 2454e-6, 0.926569, 164159e-10, 0, 867491e-8, 0.920905, 239521e-10, 0, 0.01956, 0.912169, 315127e-10, 0, 0.035433, 0.899095, 346626e-10, 0, 0.056294, 0.882209, 290223e-10, 0, 0.0818191, 0.870272, 342992e-10, 0, 0.111259, 0.855977, 394164e-10, 0, 0.142857, 0.837431, 372343e-10, 0, 0.174603, 0.820826, 396691e-10, 0, 0.206349, 0.803408, 435395e-10, 0, 0.238095, 0.782838, 419579e-10, 0, 0.269841, 0.763941, 450953e-10, 0, 0.301587, 0.742904, 455847e-10, 0, 0.333333, 0.721463, 458833e-10, 0, 0.365079, 0.700197, 477159e-10, 0, 0.396825, 0.677501, 470641e-10, 0, 0.428571, 0.655527, 484732e-10, 0, 0.460317, 0.6324, 476834e-10, 0, 0.492064, 0.609964, 484213e-10, 0, 0.52381, 0.586839, 475541e-10, 0, 0.555556, 0.564353, 476951e-10, 0, 0.587302, 0.541589, 467611e-10, 0, 0.619048, 0.519413, 463493e-10, 0, 0.650794, 0.497337, 453994e-10, 0, 0.68254, 0.475797, 445308e-10, 0, 0.714286, 0.454659, 435787e-10, 0, 0.746032, 0.434065, 424839e-10, 0, 0.777778, 0.414018, 41436e-9, 0, 0.809524, 0.39455, 401902e-10, 0, 0.84127, 0.375742, 390813e-10, 0, 0.873016, 0.357501, 377116e-10, 0, 0.904762, 0.339996, 36535e-9, 0, 0.936508, 0.323069, 351265e-10, 0, 0.968254, 0.306897, 339112e-10, 0, 1, 1, 10396e-19, 0, 0, 1, 104326e-20, 0, 0, 1, 110153e-20, 0, 0, 1, 144668e-20, 0, 0, 1, 34528e-19, 0, 0, 1, 175958e-19, 0, 0, 1, 12627e-17, 0, 0, 1, 936074e-18, 0, 0, 1, 645742e-17, 0, 0, 0.999998, 401228e-16, 0, 0, 0.999997, 222338e-15, 0, 0, 0.999995, 10967e-13, 0, 0, 0.999991, 482132e-14, 0, 0, 0.999981, 189434e-13, 0, 0, 0.999967, 667716e-13, 0, 0, 0.999938, 212066e-12, 0, 0, 0.999886, 60977e-11, 0, 0, 0.999792, 159504e-11, 0, 0, 0.999608, 381191e-11, 0, 0, 0.999209, 833727e-11, 0, 0, 0.998179, 165288e-10, 0, 0, 0.994605, 274387e-10, 0, 0, 0.979468, 167316e-10, 0, 0, 0.967529, 242877e-11, 0, 0, 0.966836, 461696e-11, 0, 0, 0.96569, 830977e-11, 0, 0, 0.963706, 140427e-10, 0, 244659e-11, 0.960063, 217353e-10, 0, 760774e-9, 0.953113, 286606e-10, 0, 367261e-8, 0.940192, 247691e-10, 0, 940263e-8, 0.927731, 195814e-10, 0, 0.018333, 0.920669, 252531e-10, 0, 0.0306825, 0.911799, 324277e-10, 0, 0.0465556, 0.89857, 340982e-10, 0, 0.0659521, 0.883283, 319622e-10, 0, 0.0887677, 0.86989, 35548e-9, 0, 0.114784, 0.855483, 397143e-10, 0, 0.143618, 0.837987, 391665e-10, 0, 0.174606, 0.820546, 411306e-10, 0, 0.206349, 0.802878, 436753e-10, 0, 0.238095, 0.783402, 444e-7, 0, 0.269841, 0.763439, 458726e-10, 0, 0.301587, 0.742925, 467097e-10, 0, 0.333333, 0.721633, 478887e-10, 0, 0.365079, 0.69985, 481251e-10, 0, 0.396825, 0.67783, 491811e-10, 0, 0.428571, 0.655126, 488199e-10, 0, 0.460318, 0.632697, 496025e-10, 0, 0.492064, 0.609613, 48829e-9, 0, 0.52381, 0.587098, 492754e-10, 0, 0.555556, 0.564119, 482625e-10, 0, 0.587302, 0.541813, 482807e-10, 0, 0.619048, 0.519342, 471552e-10, 0, 0.650794, 0.497514, 466765e-10, 0, 0.68254, 0.475879, 455582e-10, 0, 0.714286, 0.454789, 446007e-10, 0, 0.746032, 0.434217, 435382e-10, 0, 0.777778, 0.414086, 421753e-10, 0, 0.809524, 0.394744, 412093e-10, 0, 0.84127, 0.375782, 396634e-10, 0, 0.873016, 0.357707, 386419e-10, 0, 0.904762, 0.340038, 370345e-10, 0, 0.936508, 0.323284, 359725e-10, 0, 0.968254, 0.306954, 3436e-8, 0, 1, 1, 599567e-19, 0, 0, 1, 600497e-19, 0, 0, 1, 614839e-19, 0, 0, 1, 686641e-19, 0, 0, 1, 972658e-19, 0, 0, 1, 221271e-18, 0, 0, 1, 833195e-18, 0, 0, 1, 403601e-17, 0, 0, 0.999999, 206001e-16, 0, 0, 0.999998, 101739e-15, 0, 0, 0.999997, 470132e-15, 0, 0, 0.999993, 200436e-14, 0, 0, 0.999988, 783682e-14, 0, 0, 0.999979, 280338e-13, 0, 0, 0.999962, 917033e-13, 0, 0, 0.999933, 274514e-12, 0, 0, 0.999881, 753201e-12, 0, 0, 0.999783, 189826e-11, 0, 0, 0.999594, 440279e-11, 0, 0, 0.999178, 93898e-10, 0, 0, 0.998073, 181265e-10, 0, 0, 0.993993, 280487e-10, 0, 0, 0.979982, 149422e-10, 0, 0, 0.968145, 378481e-11, 0, 0, 0.966786, 53771e-10, 0, 0, 0.965611, 947508e-11, 0, 388934e-10, 0.963557, 156616e-10, 0, 9693e-7, 0.959752, 235144e-10, 0, 370329e-8, 0.952461, 291568e-10, 0, 868428e-8, 0.940193, 240102e-10, 0, 0.0161889, 0.929042, 231235e-10, 0, 0.0263948, 0.920266, 273968e-10, 0, 0.0394088, 0.911178, 337915e-10, 0, 0.0552818, 0.897873, 333629e-10, 0, 0.0740138, 0.884053, 351405e-10, 0, 0.0955539, 0.869455, 378034e-10, 0, 0.119795, 0.854655, 399378e-10, 0, 0.14656, 0.838347, 419108e-10, 0, 0.175573, 0.820693, 440831e-10, 0, 0.206388, 0.802277, 445599e-10, 0, 0.238095, 0.783634, 472691e-10, 0, 0.269841, 0.763159, 476984e-10, 0, 0.301587, 0.742914, 491487e-10, 0, 0.333333, 0.721662, 502312e-10, 0, 0.365079, 0.699668, 502817e-10, 0, 0.396825, 0.677839, 51406e-9, 0, 0.428571, 0.655091, 511095e-10, 0, 0.460317, 0.632665, 516067e-10, 0, 0.492064, 0.609734, 512255e-10, 0, 0.52381, 0.587043, 510263e-10, 0, 0.555556, 0.564298, 50565e-9, 0, 0.587302, 0.541769, 497951e-10, 0, 0.619048, 0.519529, 492698e-10, 0, 0.650794, 0.497574, 482066e-10, 0, 0.68254, 0.476028, 473689e-10, 0, 0.714286, 0.454961, 461941e-10, 0, 0.746032, 0.434341, 450618e-10, 0, 0.777778, 0.414364, 438355e-10, 0, 0.809524, 0.394832, 424196e-10, 0, 0.84127, 0.376109, 412563e-10, 0, 0.873016, 0.35779, 396226e-10, 0, 0.904762, 0.340379, 384886e-10, 0, 0.936508, 0.323385, 368214e-10, 0, 0.968254, 0.307295, 356636e-10, 0, 1, 1, 106465e-17, 0, 0, 1, 106555e-17, 0, 0, 1, 107966e-17, 0, 0, 1, 114601e-17, 0, 0, 1, 137123e-17, 0, 0, 1, 21243e-16, 0, 0, 0.999999, 489653e-17, 0, 0, 0.999999, 160283e-16, 0, 0, 0.999998, 62269e-15, 0, 0, 0.999997, 251859e-15, 0, 0, 0.999996, 996192e-15, 0, 0, 0.999992, 374531e-14, 0, 0, 0.999986, 132022e-13, 0, 0, 0.999975, 433315e-13, 0, 0, 0.999959, 131956e-12, 0, 0, 0.999927, 372249e-12, 0, 0, 0.999871, 972461e-12, 0, 0, 0.999771, 235343e-11, 0, 0, 0.999572, 52768e-10, 0, 0, 0.999133, 109237e-10, 0, 0, 0.997912, 203675e-10, 0, 0, 0.993008, 279396e-10, 0, 0, 0.980645, 139604e-10, 0, 0, 0.970057, 646596e-11, 0, 0, 0.966717, 65089e-10, 0, 474145e-10, 0.965497, 111863e-10, 0, 89544e-8, 0.96334, 179857e-10, 0, 32647e-7, 0.959294, 259045e-10, 0, 75144e-7, 0.951519, 292327e-10, 0, 0.0138734, 0.940517, 249769e-10, 0, 0.0224952, 0.93014, 26803e-9, 0, 0.0334828, 0.91972, 303656e-10, 0, 0.0468973, 0.910294, 353323e-10, 0, 0.0627703, 0.897701, 351002e-10, 0, 0.0811019, 0.884522, 388104e-10, 0, 0.10186, 0.869489, 412932e-10, 0, 0.124985, 0.853983, 415781e-10, 0, 0.150372, 0.838425, 454066e-10, 0, 0.177868, 0.820656, 471624e-10, 0, 0.207245, 0.801875, 475243e-10, 0, 0.238143, 0.783521, 505621e-10, 0, 0.269841, 0.763131, 50721e-9, 0, 0.301587, 0.74261, 523293e-10, 0, 0.333333, 0.72148, 528699e-10, 0, 0.365079, 0.699696, 538677e-10, 0, 0.396825, 0.677592, 539255e-10, 0, 0.428571, 0.65525, 546367e-10, 0, 0.460317, 0.632452, 541348e-10, 0, 0.492064, 0.609903, 544976e-10, 0, 0.52381, 0.586928, 536201e-10, 0, 0.555556, 0.564464, 535185e-10, 0, 0.587302, 0.541801, 524949e-10, 0, 0.619048, 0.519681, 51812e-9, 0, 0.650794, 0.497685, 507687e-10, 0, 0.68254, 0.47622, 496243e-10, 0, 0.714286, 0.455135, 485714e-10, 0, 0.746032, 0.4346, 471847e-10, 0, 0.777778, 0.414564, 459294e-10, 0, 0.809524, 0.395165, 444705e-10, 0, 0.84127, 0.376333, 430772e-10, 0, 0.873016, 0.358197, 416229e-10, 0, 0.904762, 0.34064, 401019e-10, 0, 0.936508, 0.323816, 386623e-10, 0, 0.968254, 0.307581, 370933e-10, 0, 1, 1, 991541e-17, 0, 0, 1, 992077e-17, 0, 0, 1, 100041e-16, 0, 0, 1, 10385e-15, 0, 0, 1, 115777e-16, 0, 0, 1, 150215e-16, 0, 0, 0.999999, 254738e-16, 0, 0, 0.999999, 598822e-16, 0, 0, 0.999998, 179597e-15, 0, 0, 0.999997, 602367e-15, 0, 0, 0.999994, 206835e-14, 0, 0, 0.99999, 694952e-14, 0, 0, 0.999984, 223363e-13, 0, 0, 0.999972, 678578e-13, 0, 0, 0.999952, 193571e-12, 0, 0, 0.999919, 516594e-12, 0, 0, 0.99986, 128739e-11, 0, 0, 0.999753, 299298e-11, 0, 0, 0.999546, 648258e-11, 0, 0, 0.999074, 129985e-10, 0, 0, 0.997671, 232176e-10, 0, 0, 0.991504, 256701e-10, 0, 0, 0.981148, 131141e-10, 0, 0, 0.971965, 869048e-11, 0, 280182e-10, 0.966624, 808301e-11, 0, 695475e-9, 0.965344, 135235e-10, 0, 265522e-8, 0.963048, 210592e-10, 0, 622975e-8, 0.958673, 287473e-10, 0, 0.0116234, 0.950262, 281379e-10, 0, 0.018976, 0.940836, 271089e-10, 0, 0.0283844, 0.930996, 30926e-9, 0, 0.0399151, 0.919848, 348359e-10, 0, 0.0536063, 0.909136, 366092e-10, 0, 0.0694793, 0.897554, 384162e-10, 0, 0.0875342, 0.884691, 430971e-10, 0, 0.107749, 0.869414, 447803e-10, 0, 0.130087, 0.853462, 452858e-10, 0, 0.154481, 0.838187, 495769e-10, 0, 0.180833, 0.820381, 502709e-10, 0, 0.209005, 0.801844, 522713e-10, 0, 0.238791, 0.783061, 541505e-10, 0, 0.269869, 0.763205, 553712e-10, 0, 0.301587, 0.742362, 564909e-10, 0, 0.333333, 0.721393, 572646e-10, 0, 0.365079, 0.699676, 581012e-10, 0, 0.396825, 0.677395, 58096e-9, 0, 0.428571, 0.655208, 585766e-10, 0, 0.460317, 0.632451, 583602e-10, 0, 0.492064, 0.609839, 580234e-10, 0, 0.52381, 0.587093, 577161e-10, 0, 0.555556, 0.564467, 568447e-10, 0, 0.587302, 0.542043, 563166e-10, 0, 0.619048, 0.519826, 55156e-9, 0, 0.650794, 0.497952, 541682e-10, 0, 0.68254, 0.476477, 528971e-10, 0, 0.714286, 0.455412, 514952e-10, 0, 0.746032, 0.434926, 502222e-10, 0, 0.777778, 0.4149, 485779e-10, 0, 0.809524, 0.395552, 472242e-10, 0, 0.84127, 0.376712, 454891e-10, 0, 0.873016, 0.358622, 440924e-10, 0, 0.904762, 0.341048, 422984e-10, 0, 0.936508, 0.324262, 408582e-10, 0, 0.968254, 0.308013, 390839e-10, 0, 1, 1, 613913e-16, 0, 0, 1, 614145e-16, 0, 0, 1, 617708e-16, 0, 0, 1, 633717e-16, 0, 0, 1, 681648e-16, 0, 0, 1, 808291e-16, 0, 0, 1, 114608e-15, 0, 0, 0.999998, 210507e-15, 0, 0, 0.999997, 499595e-15, 0, 0, 0.999995, 139897e-14, 0, 0, 0.999994, 419818e-14, 0, 0, 0.999988, 127042e-13, 0, 0, 0.999979, 375153e-13, 0, 0, 0.999965, 106206e-12, 0, 0, 0.999945, 285381e-12, 0, 0, 0.999908, 723611e-12, 0, 0, 0.999846, 17255e-10, 0, 0, 0.999733, 386104e-11, 0, 0, 0.999511, 808493e-11, 0, 0, 0.998993, 156884e-10, 0, 0, 0.997326, 265538e-10, 0, 0, 0.989706, 206466e-10, 0, 0, 0.981713, 130756e-10, 0, 70005e-10, 0.973636, 106473e-10, 0, 464797e-9, 0.966509, 10194e-9, 0, 201743e-8, 0.965149, 165881e-10, 0, 497549e-8, 0.962669, 249147e-10, 0, 953262e-8, 0.95786, 317449e-10, 0, 0.0158211, 0.949334, 281045e-10, 0, 0.0239343, 0.941041, 303263e-10, 0, 0.0339372, 0.931575, 356754e-10, 0, 0.0458738, 0.920102, 397075e-10, 0, 0.059772, 0.908002, 384886e-10, 0, 0.075645, 0.897269, 43027e-9, 0, 0.0934929, 0.884559, 479925e-10, 0, 0.113302, 0.869161, 48246e-9, 0, 0.135045, 0.853342, 509505e-10, 0, 0.158678, 0.837633, 542846e-10, 0, 0.184136, 0.820252, 554139e-10, 0, 0.211325, 0.801872, 581412e-10, 0, 0.240113, 0.782418, 585535e-10, 0, 0.270306, 0.7631, 610923e-10, 0, 0.301594, 0.742183, 613678e-10, 0, 0.333333, 0.721098, 627275e-10, 0, 0.365079, 0.699512, 629413e-10, 0, 0.396825, 0.677372, 636351e-10, 0, 0.428571, 0.655059, 633555e-10, 0, 0.460317, 0.632567, 636513e-10, 0, 0.492064, 0.609784, 628965e-10, 0, 0.52381, 0.587237, 625546e-10, 0, 0.555556, 0.564525, 615825e-10, 0, 0.587302, 0.542181, 605048e-10, 0, 0.619048, 0.520017, 596329e-10, 0, 0.650794, 0.498204, 581516e-10, 0, 0.68254, 0.476742, 569186e-10, 0, 0.714286, 0.455803, 553833e-10, 0, 0.746032, 0.435251, 537807e-10, 0, 0.777778, 0.415374, 522025e-10, 0, 0.809524, 0.395921, 503421e-10, 0, 0.84127, 0.377253, 488211e-10, 0, 0.873016, 0.359021, 468234e-10, 0, 0.904762, 0.341637, 453269e-10, 0, 0.936508, 0.3247, 433014e-10, 0, 0.968254, 0.308625, 418007e-10, 0, 1, 1, 286798e-15, 0, 0, 1, 286877e-15, 0, 0, 1, 288094e-15, 0, 0, 1, 293506e-15, 0, 0, 1, 309262e-15, 0, 0, 0.999999, 348593e-15, 0, 0, 0.999999, 444582e-15, 0, 0, 0.999998, 688591e-15, 0, 0, 0.999996, 134391e-14, 0, 0, 0.999993, 317438e-14, 0, 0, 0.999989, 835609e-14, 0, 0, 0.999983, 228677e-13, 0, 0, 0.999974, 623361e-13, 0, 0, 0.999959, 165225e-12, 0, 0, 0.999936, 419983e-12, 0, 0, 0.999896, 101546e-11, 0, 0, 0.99983, 232376e-11, 0, 0, 0.999709, 50156e-10, 0, 0, 0.999469, 10167e-9, 0, 0, 0.998886, 190775e-10, 0, 0, 0.996819, 300511e-10, 0, 0, 0.988837, 185092e-10, 0, 168222e-12, 0.982178, 134622e-10, 0, 259622e-9, 0.975017, 125961e-10, 0, 142595e-8, 0.967101, 13507e-9, 0, 382273e-8, 0.964905, 205003e-10, 0, 764164e-8, 0.96218, 29546e-9, 0, 0.0130121, 0.956821, 343738e-10, 0, 0.0200253, 0.948829, 305063e-10, 0, 0.0287452, 0.941092, 346487e-10, 0, 0.039218, 0.931883, 412061e-10, 0, 0.0514748, 0.920211, 444651e-10, 0, 0.0655351, 0.907307, 431252e-10, 0, 0.0814082, 0.89684, 490382e-10, 0, 0.0990939, 0.884119, 53334e-9, 0, 0.118583, 0.869148, 54114e-9, 0, 0.139856, 0.853377, 578536e-10, 0, 0.162882, 0.836753, 592285e-10, 0, 0.187615, 0.820063, 622787e-10, 0, 0.213991, 0.801694, 645492e-10, 0, 0.241918, 0.782116, 65353e-9, 0, 0.271267, 0.762673, 674344e-10, 0, 0.301847, 0.742133, 682788e-10, 0, 0.333333, 0.720779, 691959e-10, 0, 0.365079, 0.699386, 696817e-10, 0, 0.396826, 0.67732, 699583e-10, 0, 0.428572, 0.654888, 698447e-10, 0, 0.460318, 0.632499, 694063e-10, 0, 0.492064, 0.609825, 691612e-10, 0, 0.52381, 0.587287, 681576e-10, 0, 0.555556, 0.564743, 674138e-10, 0, 0.587302, 0.542409, 661617e-10, 0, 0.619048, 0.520282, 647785e-10, 0, 0.650794, 0.498506, 633836e-10, 0, 0.68254, 0.477102, 615905e-10, 0, 0.714286, 0.456167, 601013e-10, 0, 0.746032, 0.435728, 581457e-10, 0, 0.777778, 0.415809, 564215e-10, 0, 0.809524, 0.396517, 544997e-10, 0, 0.84127, 0.377737, 525061e-10, 0, 0.873016, 0.359698, 506831e-10, 0, 0.904762, 0.342164, 48568e-9, 0, 0.936508, 0.325417, 467826e-10, 0, 0.968254, 0.309186, 446736e-10, 0, 1, 1, 109018e-14, 0, 0, 1, 10904e-13, 0, 0, 1, 109393e-14, 0, 0, 1, 11095e-13, 0, 0, 1, 1154e-12, 0, 0, 1, 126089e-14, 0, 0, 0.999999, 15059e-13, 0, 0, 0.999997, 207899e-14, 0, 0, 0.999994, 348164e-14, 0, 0, 0.999993, 705728e-14, 0, 0, 0.999987, 163692e-13, 0, 0, 0.999981, 406033e-13, 0, 0, 0.999969, 10245e-11, 0, 0, 0.999953, 255023e-12, 0, 0, 0.999925, 61511e-11, 0, 0, 0.999881, 142218e-11, 0, 0, 0.99981, 313086e-11, 0, 0, 0.99968, 653119e-11, 0, 0, 0.999418, 12832e-9, 0, 0, 0.998748, 232497e-10, 0, 0, 0.996066, 329522e-10, 0, 0, 0.988379, 179613e-10, 0, 108799e-9, 0.982567, 143715e-10, 0, 921302e-9, 0.976097, 148096e-10, 0, 280738e-8, 0.968475, 178905e-10, 0, 596622e-8, 0.964606, 253921e-10, 0, 0.0105284, 0.961564, 348623e-10, 0, 0.0165848, 0.955517, 357612e-10, 0, 0.0242, 0.948381, 343493e-10, 0, 0.03342, 0.941095, 405849e-10, 0, 0.0442777, 0.931923, 475394e-10, 0, 0.0567958, 0.91996, 484328e-10, 0, 0.0709879, 0.907419, 502146e-10, 0, 0.086861, 0.89618, 561654e-10, 0, 0.104415, 0.88337, 587612e-10, 0, 0.123643, 0.869046, 618057e-10, 0, 0.144531, 0.853278, 657392e-10, 0, 0.167057, 0.836091, 66303e-9, 0, 0.191188, 0.819644, 704445e-10, 0, 0.216878, 0.801246, 714071e-10, 0, 0.244062, 0.782031, 740093e-10, 0, 0.272649, 0.762066, 74685e-9, 0, 0.302509, 0.741964, 766647e-10, 0, 0.333442, 0.720554, 766328e-10, 0, 0.365079, 0.699098, 777857e-10, 0, 0.396826, 0.677189, 774633e-10, 0, 0.428572, 0.65484, 776235e-10, 0, 0.460318, 0.632496, 770316e-10, 0, 0.492064, 0.609908, 762669e-10, 0, 0.52381, 0.587312, 753972e-10, 0, 0.555556, 0.564938, 739994e-10, 0, 0.587302, 0.542577, 728382e-10, 0, 0.619048, 0.52062, 71112e-9, 0, 0.650794, 0.498819, 694004e-10, 0, 0.68254, 0.477555, 675575e-10, 0, 0.714286, 0.456568, 653449e-10, 0, 0.746032, 0.436278, 636068e-10, 0, 0.777778, 0.41637, 613466e-10, 0, 0.809524, 0.397144, 594177e-10, 0, 0.84127, 0.378412, 570987e-10, 0, 0.873016, 0.360376, 550419e-10, 0, 0.904762, 0.342906, 527422e-10, 0, 0.936508, 0.326136, 506544e-10, 0, 0.968254, 0.30997, 484307e-10, 0, 1, 1, 354014e-14, 0, 0, 1, 354073e-14, 0, 0, 1, 354972e-14, 0, 0, 1, 358929e-14, 0, 0, 1, 370093e-14, 0, 0, 0.999999, 396194e-14, 0, 0, 0.999998, 453352e-14, 0, 0, 0.999997, 578828e-14, 0, 0, 0.999994, 863812e-14, 0, 0, 0.999991, 153622e-13, 0, 0, 0.999985, 316356e-13, 0, 0, 0.999977, 712781e-13, 0, 0, 0.999964, 166725e-12, 0, 0, 0.999945, 390501e-12, 0, 0, 0.999912, 895622e-12, 0, 0, 0.999866, 198428e-11, 0, 0, 0.999786, 421038e-11, 0, 0, 0.999647, 850239e-11, 0, 0, 0.999356, 162059e-10, 0, 0, 0.998563, 282652e-10, 0, 0, 0.994928, 336309e-10, 0, 244244e-10, 0.987999, 178458e-10, 0, 523891e-9, 0.982893, 159162e-10, 0, 194729e-8, 0.977044, 178056e-10, 0, 451099e-8, 0.969972, 230624e-10, 0, 835132e-8, 0.964237, 313922e-10, 0, 0.013561, 0.960791, 406145e-10, 0, 0.0202056, 0.954292, 372796e-10, 0, 0.0283321, 0.948052, 403199e-10, 0, 0.0379739, 0.940938, 479537e-10, 0, 0.0491551, 0.931689, 545292e-10, 0, 0.0618918, 0.91987, 54038e-9, 0, 0.0761941, 0.907665, 589909e-10, 0, 0.0920672, 0.895281, 642651e-10, 0, 0.109511, 0.882621, 659707e-10, 0, 0.12852, 0.86873, 709973e-10, 0, 0.149085, 0.853008, 742221e-10, 0, 0.171189, 0.835944, 761754e-10, 0, 0.194809, 0.818949, 797052e-10, 0, 0.21991, 0.800951, 812434e-10, 0, 0.246447, 0.781847, 838075e-10, 0, 0.274352, 0.761649, 84501e-9, 0, 0.303535, 0.74152, 860258e-10, 0, 0.333857, 0.720495, 866233e-10, 0, 0.365104, 0.698742, 868326e-10, 0, 0.396826, 0.677096, 87133e-9, 0, 0.428572, 0.654782, 863497e-10, 0, 0.460318, 0.632335, 860206e-10, 0, 0.492064, 0.610031, 849337e-10, 0, 0.52381, 0.587457, 838279e-10, 0, 0.555556, 0.56513, 82309e-9, 0, 0.587302, 0.542877, 803542e-10, 0, 0.619048, 0.5209, 786928e-10, 0, 0.650794, 0.499291, 765171e-10, 0, 0.68254, 0.477971, 744753e-10, 0, 0.714286, 0.457221, 72209e-9, 0, 0.746032, 0.436803, 697448e-10, 0, 0.777778, 0.417083, 675333e-10, 0, 0.809524, 0.397749, 648058e-10, 0, 0.84127, 0.379177, 625759e-10, 0, 0.873016, 0.361061, 598584e-10, 0, 0.904762, 0.343713, 575797e-10, 0, 0.936508, 0.326894, 549999e-10, 0, 0.968254, 0.310816, 527482e-10, 0, 1, 1, 10153e-12, 0, 0, 1, 101544e-13, 0, 0, 1, 101751e-13, 0, 0, 1, 102662e-13, 0, 0, 1, 10521e-12, 0, 0, 0.999999, 111049e-13, 0, 0, 0.999999, 123408e-13, 0, 0, 0.999996, 14924e-12, 0, 0, 0.999992, 204471e-13, 0, 0, 0.999989, 326539e-13, 0, 0, 0.99998, 603559e-13, 0, 0, 0.999971, 123936e-12, 0, 0, 0.999955, 269058e-12, 0, 0, 0.999933, 593604e-12, 0, 0, 0.999901, 129633e-11, 0, 0, 0.999847, 275621e-11, 0, 0, 0.999761, 564494e-11, 0, 0, 0.999607, 110485e-10, 0, 0, 0.999282, 204388e-10, 0, 0, 0.99831, 341084e-10, 0, 22038e-11, 0.993288, 294949e-10, 0, 242388e-9, 0.987855, 192736e-10, 0, 12503e-7, 0.983167, 182383e-10, 0, 32745e-7, 0.977908, 218633e-10, 0, 646321e-8, 0.971194, 290662e-10, 0, 0.0109133, 0.963867, 386401e-10, 0, 0.0166927, 0.95982, 462827e-10, 0, 0.0238494, 0.953497, 420705e-10, 0, 0.0324178, 0.947621, 477743e-10, 0, 0.0424225, 0.940611, 568258e-10, 0, 0.0538808, 0.931174, 618061e-10, 0, 0.0668047, 0.919919, 627098e-10, 0, 0.0812014, 0.907856, 694714e-10, 0, 0.0970745, 0.894509, 735008e-10, 0, 0.114424, 0.881954, 763369e-10, 0, 0.133246, 0.868309, 821896e-10, 0, 0.153534, 0.852511, 83769e-9, 0, 0.175275, 0.835821, 881615e-10, 0, 0.198453, 0.817981, 896368e-10, 0, 0.223042, 0.800504, 930906e-10, 0, 0.249009, 0.78141, 945056e-10, 0, 0.276304, 0.761427, 963605e-10, 0, 0.304862, 0.74094, 968088e-10, 0, 0.334584, 0.720233, 981481e-10, 0, 0.365322, 0.698592, 979122e-10, 0, 0.396826, 0.676763, 981057e-10, 0, 0.428571, 0.654808, 973956e-10, 0, 0.460318, 0.632326, 962619e-10, 0, 0.492064, 0.610049, 952996e-10, 0, 0.52381, 0.58763, 933334e-10, 0, 0.555556, 0.565261, 917573e-10, 0, 0.587302, 0.543244, 896636e-10, 0, 0.619048, 0.521273, 873304e-10, 0, 0.650794, 0.499818, 852648e-10, 0, 0.68254, 0.478536, 823961e-10, 0, 0.714286, 0.457826, 79939e-9, 0, 0.746032, 0.437549, 77126e-9, 0, 0.777778, 0.41776, 743043e-10, 0, 0.809524, 0.39863, 716426e-10, 0, 0.84127, 0.379954, 686456e-10, 0, 0.873016, 0.362025, 660514e-10, 0, 0.904762, 0.344581, 630755e-10, 0, 0.936508, 0.327909, 605439e-10, 0, 0.968254, 0.311736, 576345e-10, 0, 1, 1, 263344e-13, 0, 0, 1, 263373e-13, 0, 0, 1, 263815e-13, 0, 0, 1, 265753e-13, 0, 0, 1, 271132e-13, 0, 0, 0.999999, 283279e-13, 0, 0, 0.999997, 30833e-12, 0, 0, 0.999995, 358711e-13, 0, 0, 0.999992, 461266e-13, 0, 0, 0.999985, 67574e-12, 0, 0, 0.999977, 11358e-11, 0, 0, 0.999966, 213657e-12, 0, 0, 0.999948, 431151e-12, 0, 0, 0.999923, 896656e-12, 0, 0, 0.999884, 186603e-11, 0, 0, 0.999826, 381115e-11, 0, 0, 0.999732, 754184e-11, 0, 0, 0.999561, 143192e-10, 0, 0, 0.999191, 257061e-10, 0, 0, 0.997955, 405724e-10, 0, 744132e-10, 0.992228, 276537e-10, 0, 716477e-9, 0.987638, 208885e-10, 0, 22524e-7, 0.983395, 215226e-10, 0, 484816e-8, 0.978614, 270795e-10, 0, 860962e-8, 0.972389, 365282e-10, 0, 0.0136083, 0.964392, 474747e-10, 0, 0.0198941, 0.95861, 509141e-10, 0, 0.0275023, 0.952806, 48963e-9, 0, 0.0364584, 0.94712, 571119e-10, 0, 0.04678, 0.940104, 671704e-10, 0, 0.0584799, 0.930398, 687586e-10, 0, 0.0715665, 0.919866, 738161e-10, 0, 0.086045, 0.907853, 813235e-10, 0, 0.101918, 0.894078, 834582e-10, 0, 0.119186, 0.881177, 892093e-10, 0, 0.137845, 0.867575, 944548e-10, 0, 0.157891, 0.852107, 969607e-10, 0, 0.179316, 0.835502, 101456e-9, 0, 0.202106, 0.81756, 103256e-9, 0, 0.226243, 0.79984, 106954e-9, 0, 0.251704, 0.780998, 108066e-9, 0, 0.278451, 0.761132, 110111e-9, 0, 0.306436, 0.740429, 110459e-9, 0, 0.335586, 0.719836, 111219e-9, 0, 0.365796, 0.698467, 11145e-8, 0, 0.3969, 0.676446, 110393e-9, 0, 0.428571, 0.654635, 110035e-9, 0, 0.460318, 0.632411, 108548e-9, 0, 0.492064, 0.609986, 106963e-9, 0, 0.52381, 0.587872, 105238e-9, 0, 0.555556, 0.565528, 102665e-9, 0, 0.587302, 0.543563, 100543e-9, 0, 0.619048, 0.52176, 976182e-10, 0, 0.650794, 0.500188, 947099e-10, 0, 0.68254, 0.479204, 919929e-10, 0, 0.714286, 0.458413, 886139e-10, 0, 0.746032, 0.438314, 857839e-10, 0, 0.777778, 0.418573, 82411e-9, 0, 0.809524, 0.39947, 792211e-10, 0, 0.84127, 0.380892, 759546e-10, 0, 0.873016, 0.362953, 727571e-10, 0, 0.904762, 0.345601, 695738e-10, 0, 0.936508, 0.328895, 664907e-10, 0, 0.968254, 0.312808, 634277e-10, 0, 1, 1, 628647e-13, 0, 0, 1, 628705e-13, 0, 0, 1, 629587e-13, 0, 0, 1, 633441e-13, 0, 0, 0.999999, 644087e-13, 0, 0, 0.999998, 667856e-13, 0, 0, 0.999997, 715889e-13, 0, 0, 0.999995, 809577e-13, 0, 0, 0.999989, 992764e-13, 0, 0, 0.999983, 135834e-12, 0, 0, 0.999974, 210482e-12, 0, 0, 0.999959, 365215e-12, 0, 0, 0.999939, 686693e-12, 0, 0, 0.999911, 13472e-10, 0, 0, 0.999868, 26731e-10, 0, 0, 0.999804, 524756e-11, 0, 0, 0.9997, 100403e-10, 0, 0, 0.99951, 185019e-10, 0, 0, 0.999078, 322036e-10, 0, 620676e-11, 0.997428, 470002e-10, 0, 341552e-9, 0.99162, 287123e-10, 0, 143727e-8, 0.987479, 234706e-10, 0, 349201e-8, 0.983582, 260083e-10, 0, 66242e-7, 0.979186, 337927e-10, 0, 0.0109113, 0.97325, 454689e-10, 0, 0.0164064, 0.965221, 573759e-10, 0, 0.0231463, 0.957262, 544114e-10, 0, 0.0311571, 0.952211, 587006e-10, 0, 0.0404572, 0.946631, 692256e-10, 0, 0.0510592, 0.939391, 787819e-10, 0, 0.0629723, 0.929795, 792368e-10, 0, 0.0762025, 0.91965, 875075e-10, 0, 0.090753, 0.907737, 950903e-10, 0, 0.106626, 0.893899, 972963e-10, 0, 0.123822, 0.880239, 10459e-8, 0, 0.142337, 0.866562, 107689e-9, 0, 0.16217, 0.85164, 113081e-9, 0, 0.183314, 0.835021, 116636e-9, 0, 0.20576, 0.817311, 120074e-9, 0, 0.229496, 0.798845, 121921e-9, 0, 0.254502, 0.780479, 12475e-8, 0, 0.280753, 0.760694, 125255e-9, 0, 0.308212, 0.740142, 126719e-9, 0, 0.336825, 0.719248, 12636e-8, 0, 0.366517, 0.698209, 126712e-9, 0, 0.397167, 0.676398, 125769e-9, 0, 0.428578, 0.654378, 124432e-9, 0, 0.460318, 0.632484, 123272e-9, 0, 0.492064, 0.610113, 12085e-8, 0, 0.52381, 0.587931, 118411e-9, 0, 0.555556, 0.565872, 11569e-8, 0, 0.587302, 0.543814, 112521e-9, 0, 0.619048, 0.522265, 109737e-9, 0, 0.650794, 0.500835, 106228e-9, 0, 0.68254, 0.479818, 102591e-9, 0, 0.714286, 0.459258, 991288e-10, 0, 0.746032, 0.439061, 952325e-10, 0, 0.777778, 0.419552, 91895e-9, 0, 0.809524, 0.400399, 879051e-10, 0, 0.84127, 0.381976, 844775e-10, 0, 0.873016, 0.364009, 806316e-10, 0, 0.904762, 0.346761, 771848e-10, 0, 0.936508, 0.330049, 735429e-10, 0, 0.968254, 0.314018, 702103e-10, 0, 1, 1, 139968e-12, 0, 0, 1, 139979e-12, 0, 0, 1, 140145e-12, 0, 0, 1, 14087e-11, 0, 0, 0.999999, 142865e-12, 0, 0, 0.999998, 147279e-12, 0, 0, 0.999997, 156057e-12, 0, 0, 0.999992, 17276e-11, 0, 0, 0.999989, 204352e-12, 0, 0, 0.99998, 26494e-11, 0, 0, 0.999969, 383435e-12, 0, 0, 0.999953, 618641e-12, 0, 0, 0.999929, 108755e-11, 0, 0, 0.999898, 201497e-11, 0, 0, 0.999849, 381346e-11, 0, 0, 0.999778, 719815e-11, 0, 0, 0.999661, 133215e-10, 0, 0, 0.999451, 238313e-10, 0, 0, 0.998936, 401343e-10, 0, 113724e-9, 0.99662, 517346e-10, 0, 820171e-9, 0.991094, 304323e-10, 0, 238143e-8, 0.987487, 281757e-10, 0, 493527e-8, 0.983731, 320048e-10, 0, 856859e-8, 0.979647, 423905e-10, 0, 0.0133393, 0.973837, 562935e-10, 0, 0.0192863, 0.96584, 677442e-10, 0, 0.0264369, 0.956309, 623073e-10, 0, 0.03481, 0.951523, 704131e-10, 0, 0.0444184, 0.946003, 836594e-10, 0, 0.0552713, 0.938454, 911736e-10, 0, 0.0673749, 0.929279, 938264e-10, 0, 0.0807329, 0.919239, 103754e-9, 0, 0.0953479, 0.907293, 109928e-9, 0, 0.111221, 0.893936, 115257e-9, 0, 0.128352, 0.879674, 122265e-9, 0, 0.14674, 0.865668, 125733e-9, 0, 0.166382, 0.850998, 132305e-9, 0, 0.187276, 0.834498, 134844e-9, 0, 0.209413, 0.816903, 139276e-9, 0, 0.232786, 0.798235, 140984e-9, 0, 0.257382, 0.779724, 14378e-8, 0, 0.283181, 0.760251, 144623e-9, 0, 0.310156, 0.739808, 145228e-9, 0, 0.338269, 0.718762, 14539e-8, 0, 0.367461, 0.697815, 144432e-9, 0, 0.397646, 0.67631, 143893e-9, 0, 0.428685, 0.654278, 141846e-9, 0, 0.460318, 0.632347, 13935e-8, 0, 0.492064, 0.610296, 137138e-9, 0, 0.52381, 0.588039, 133806e-9, 0, 0.555556, 0.566218, 130755e-9, 0, 0.587302, 0.544346, 127128e-9, 0, 0.619048, 0.522701, 123002e-9, 0, 0.650794, 0.501542, 119443e-9, 0, 0.68254, 0.480508, 115055e-9, 0, 0.714286, 0.460092, 111032e-9, 0, 0.746032, 0.440021, 106635e-9, 0, 0.777778, 0.420446, 102162e-9, 0, 0.809524, 0.401512, 98184e-9, 0, 0.84127, 0.38299, 936497e-10, 0, 0.873016, 0.365232, 89813e-9, 0, 0.904762, 0.347865, 853073e-10, 0, 0.936508, 0.331342, 817068e-10, 0, 0.968254, 0.315202, 773818e-10, 0, 1, 1, 29368e-11, 0, 0, 1, 2937e-10, 0, 0, 1, 293998e-12, 0, 0, 1, 295298e-12, 0, 0, 0.999999, 298865e-12, 0, 0, 0.999998, 3067e-10, 0, 0, 0.999995, 322082e-12, 0, 0, 0.999992, 350767e-12, 0, 0, 0.999986, 403538e-12, 0, 0, 0.999976, 501372e-12, 0, 0, 0.999964, 68562e-11, 0, 0, 0.999945, 10374e-10, 0, 0, 0.999919, 171269e-11, 0, 0, 0.999882, 300175e-11, 0, 0, 0.999829, 542144e-11, 0, 0, 0.999749, 984182e-11, 0, 0, 0.99962, 176213e-10, 0, 0, 0.999382, 305995e-10, 0, 138418e-10, 0.998751, 496686e-10, 0, 389844e-9, 0.995344, 510733e-10, 0, 150343e-8, 0.990768, 345829e-10, 0, 352451e-8, 0.987464, 342841e-10, 0, 655379e-8, 0.983846, 399072e-10, 0, 0.0106554, 0.980007, 533219e-10, 0, 0.0158723, 0.974494, 696992e-10, 0, 0.0222333, 0.96622, 776754e-10, 0, 0.029758, 0.956273, 747718e-10, 0, 0.0384596, 0.950952, 864611e-10, 0, 0.0483473, 0.945215, 100464e-9, 0, 0.0594266, 0.937287, 103729e-9, 0, 0.0717019, 0.928649, 111665e-9, 0, 0.0851752, 0.918791, 12353e-8, 0, 0.0998479, 0.906685, 127115e-9, 0, 0.115721, 0.893706, 13628e-8, 0, 0.132794, 0.879248, 142427e-9, 0, 0.151067, 0.864685, 148091e-9, 0, 0.170538, 0.850032, 153517e-9, 0, 0.191204, 0.833853, 157322e-9, 0, 0.213063, 0.816353, 161086e-9, 0, 0.236107, 0.797834, 164111e-9, 0, 0.260329, 0.778831, 165446e-9, 0, 0.285714, 0.759756, 167492e-9, 0, 0.312243, 0.739419, 166928e-9, 0, 0.339887, 0.718491, 167e-6, 0, 0.368604, 0.697392, 165674e-9, 0, 0.398329, 0.676102, 163815e-9, 0, 0.428961, 0.654243, 162003e-9, 0, 0.460331, 0.632176, 158831e-9, 0, 0.492064, 0.610407, 155463e-9, 0, 0.52381, 0.588394, 152062e-9, 0, 0.555556, 0.56645, 147665e-9, 0, 0.587302, 0.5449, 14375e-8, 0, 0.619048, 0.523276, 138905e-9, 0, 0.650794, 0.502179, 134189e-9, 0, 0.68254, 0.481359, 129392e-9, 0, 0.714286, 0.46092, 124556e-9, 0, 0.746032, 0.441084, 11957e-8, 0, 0.777778, 0.421517, 114652e-9, 0, 0.809524, 0.402721, 109688e-9, 0, 0.84127, 0.384222, 104667e-9, 0, 0.873016, 0.366534, 999633e-10, 0, 0.904762, 0.349205, 950177e-10, 0, 0.936508, 0.332702, 907301e-10, 0, 0.968254, 0.316599, 859769e-10, 0, 1, 1, 585473e-12, 0, 0, 1, 585507e-12, 0, 0, 1, 58602e-11, 0, 0, 0.999999, 588259e-12, 0, 0, 0.999999, 594381e-12, 0, 0, 0.999998, 607754e-12, 0, 0, 0.999995, 633729e-12, 0, 0, 0.99999, 68137e-11, 0, 0, 0.999984, 767003e-12, 0, 0, 0.999973, 921212e-12, 0, 0, 0.999959, 120218e-11, 0, 0, 0.999936, 172024e-11, 0, 0, 0.999907, 268088e-11, 0, 0, 0.999866, 445512e-11, 0, 0, 0.999806, 768481e-11, 0, 0, 0.999716, 1342e-8, 0, 0, 0.999576, 232473e-10, 0, 0, 0.9993, 391694e-10, 0, 129917e-9, 0.998498, 608429e-10, 0, 845035e-9, 0.994132, 489743e-10, 0, 237616e-8, 0.99031, 384644e-10, 0, 484456e-8, 0.987409, 421768e-10, 0, 832472e-8, 0.983981, 504854e-10, 0, 0.0128643, 0.980268, 671028e-10, 0, 0.0184947, 0.974875, 852749e-10, 0, 0.025237, 0.966063, 85531e-9, 0, 0.0331046, 0.956779, 900588e-10, 0, 0.0421067, 0.950259, 10577e-8, 0, 0.0522487, 0.944239, 119458e-9, 0, 0.0635343, 0.936341, 122164e-9, 0, 0.0759654, 0.928047, 134929e-9, 0, 0.0895434, 0.918065, 145544e-9, 0, 0.104269, 0.906267, 150531e-9, 0, 0.120142, 0.893419, 161652e-9, 0, 0.137163, 0.878758, 16593e-8, 0, 0.15533, 0.863699, 174014e-9, 0, 0.174645, 0.848876, 177877e-9, 0, 0.195106, 0.833032, 184049e-9, 0, 0.21671, 0.815557, 186088e-9, 0, 0.239454, 0.797323, 19054e-8, 0, 0.263332, 0.778124, 191765e-9, 0, 0.288336, 0.758929, 192535e-9, 0, 0.314451, 0.738979, 192688e-9, 0, 0.341658, 0.718213, 191522e-9, 0, 0.369924, 0.696947, 190491e-9, 0, 0.399202, 0.675807, 187913e-9, 0, 0.429416, 0.654147, 184451e-9, 0, 0.460447, 0.63229, 181442e-9, 0, 0.492064, 0.610499, 177139e-9, 0, 0.523809, 0.588747, 172596e-9, 0, 0.555555, 0.566783, 167457e-9, 0, 0.587301, 0.545359, 162518e-9, 0, 0.619048, 0.523984, 156818e-9, 0, 0.650794, 0.502917, 151884e-9, 0, 0.68254, 0.482294, 145514e-9, 0, 0.714286, 0.461945, 140199e-9, 0, 0.746032, 0.442133, 134101e-9, 0, 0.777778, 0.422705, 128374e-9, 0, 0.809524, 0.403916, 122996e-9, 0, 0.84127, 0.38554, 116808e-9, 0, 0.873016, 0.367909, 111973e-9, 0, 0.904762, 0.350651, 105938e-9, 0, 0.936508, 0.334208, 101355e-9, 0, 0.968254, 0.318123, 957629e-10, 0, 1, 1, 111633e-11, 0, 0, 1, 111639e-11, 0, 0, 1, 111725e-11, 0, 0, 1, 112096e-11, 0, 0, 0.999999, 11311e-10, 0, 0, 0.999997, 115315e-11, 0, 0, 0.999995, 11956e-10, 0, 0, 0.999989, 127239e-11, 0, 0, 0.999981, 140772e-11, 0, 0, 0.999969, 164541e-11, 0, 0, 0.999952, 206607e-11, 0, 0, 0.999928, 281783e-11, 0, 0, 0.999895, 416835e-11, 0, 0, 0.999848, 658728e-11, 0, 0, 0.999781, 108648e-10, 0, 0, 0.999682, 182579e-10, 0, 0, 0.999523, 306003e-10, 0, 159122e-10, 0.999205, 499862e-10, 0, 391184e-9, 0.998131, 73306e-9, 0, 147534e-8, 0.993334, 513229e-10, 0, 34227e-7, 0.99016, 467783e-10, 0, 632232e-8, 0.987321, 523413e-10, 0, 0.0102295, 0.984099, 64267e-9, 0, 0.0151794, 0.980432, 843042e-10, 0, 0.0211947, 0.974976, 102819e-9, 0, 0.0282899, 0.966429, 996234e-10, 0, 0.0364739, 0.957633, 111074e-9, 0, 0.0457522, 0.949422, 128644e-9, 0, 0.0561278, 0.943045, 140076e-9, 0, 0.0676023, 0.935448, 146349e-9, 0, 0.0801762, 0.927225, 161854e-9, 0, 0.0938499, 0.917033, 169135e-9, 0, 0.108623, 0.905762, 179987e-9, 0, 0.124496, 0.892879, 189832e-9, 0, 0.141469, 0.878435, 195881e-9, 0, 0.159541, 0.863114, 20466e-8, 0, 0.178713, 0.84776, 209473e-9, 0, 0.198985, 0.832084, 214861e-9, 0, 0.220355, 0.814915, 217695e-9, 0, 0.242823, 0.796711, 220313e-9, 0, 0.266385, 0.777603, 22313e-8, 0, 0.291036, 0.757991, 222471e-9, 0, 0.316767, 0.738371, 222869e-9, 0, 0.343563, 0.717872, 221243e-9, 0, 0.371402, 0.696619, 218089e-9, 0, 0.400248, 0.675379, 21562e-8, 0, 0.430047, 0.65411, 21169e-8, 0, 0.460709, 0.63241, 206947e-9, 0, 0.492079, 0.61046, 201709e-9, 0, 0.52381, 0.58903, 196753e-9, 0, 0.555556, 0.567267, 189637e-9, 0, 0.587302, 0.545886, 184735e-9, 0, 0.619048, 0.524714, 177257e-9, 0, 0.650794, 0.503789, 171424e-9, 0, 0.68254, 0.483204, 164688e-9, 0, 0.714286, 0.462976, 157172e-9, 0, 0.746032, 0.443294, 151341e-9, 0, 0.777778, 0.423988, 143737e-9, 0, 0.809524, 0.405325, 138098e-9, 0, 0.84127, 0.386981, 130698e-9, 0, 0.873016, 0.369436, 125276e-9, 0, 0.904762, 0.35219, 118349e-9, 0, 0.936508, 0.335804, 11312e-8, 0, 0.968254, 0.319749, 106687e-9, 0, 1, 1, 204685e-11, 0, 0, 1, 204694e-11, 0, 0, 1, 204831e-11, 0, 0, 0.999999, 205428e-11, 0, 0, 0.999999, 207056e-11, 0, 0, 0.999997, 210581e-11, 0, 0, 0.999993, 21732e-10, 0, 0, 0.999987, 229365e-11, 0, 0, 0.999979, 250243e-11, 0, 0, 0.999965, 286127e-11, 0, 0, 0.999947, 348028e-11, 0, 0, 0.999918, 455588e-11, 0, 0, 0.999881, 643303e-11, 0, 0, 0.999828, 970064e-11, 0, 0, 0.999753, 153233e-10, 0, 0, 0.999642, 24793e-9, 0, 0, 0.999464, 402032e-10, 0, 122947e-9, 0.999089, 635852e-10, 0, 807414e-9, 0.997567, 857026e-10, 0, 227206e-8, 0.992903, 594912e-10, 0, 462812e-8, 0.990011, 578515e-10, 0, 794162e-8, 0.987192, 65399e-9, 0, 0.0122534, 0.98418, 819675e-10, 0, 0.0175888, 0.980491, 105514e-9, 0, 0.0239635, 0.974779, 121532e-9, 0, 0.031387, 0.96675, 119144e-9, 0, 0.0398644, 0.958248, 136125e-9, 0, 0.0493982, 0.948884, 155408e-9, 0, 0.0599896, 0.941673, 162281e-9, 0, 0.0716382, 0.934521, 176754e-9, 0, 0.0843437, 0.926205, 192873e-9, 0, 0.0981056, 0.916089, 200038e-9, 0, 0.112923, 0.904963, 213624e-9, 0, 0.128796, 0.892089, 221834e-9, 0, 0.145725, 0.878028, 232619e-9, 0, 0.163709, 0.86249, 238632e-9, 0, 0.182749, 0.846587, 247002e-9, 0, 0.202847, 0.830988, 250702e-9, 0, 0.224001, 0.814165, 255562e-9, 0, 0.246214, 0.796135, 257505e-9, 0, 0.269482, 0.777052, 258625e-9, 0, 0.293805, 0.757201, 258398e-9, 0, 0.319176, 0.737655, 256714e-9, 0, 0.345587, 0.717477, 255187e-9, 0, 0.373021, 0.696433, 251792e-9, 0, 0.401454, 0.675084, 247223e-9, 0, 0.430844, 0.653907, 242213e-9, 0, 0.461125, 0.632561, 237397e-9, 0, 0.492187, 0.610658, 229313e-9, 0, 0.52381, 0.589322, 224402e-9, 0, 0.555556, 0.567857, 216116e-9, 0, 0.587302, 0.54652, 209124e-9, 0, 0.619048, 0.525433, 201601e-9, 0, 0.650794, 0.504679, 192957e-9, 0, 0.68254, 0.484203, 186052e-9, 0, 0.714286, 0.464203, 177672e-9, 0, 0.746032, 0.444549, 170005e-9, 0, 0.777778, 0.425346, 162401e-9, 0, 0.809524, 0.406706, 1544e-7, 0, 0.84127, 0.388576, 147437e-9, 0, 0.873016, 0.37094, 139493e-9, 0, 0.904762, 0.353996, 133219e-9, 0, 0.936508, 0.337391, 125573e-9, 0, 0.968254, 0.321648, 119867e-9, 0, 1, 1, 362511e-11, 0, 0, 1, 362525e-11, 0, 0, 1, 362739e-11, 0, 0, 0.999999, 363673e-11, 0, 0, 0.999998, 366214e-11, 0, 0, 0.999996, 371698e-11, 0, 0, 0.999992, 382116e-11, 0, 0, 0.999986, 400554e-11, 0, 0, 0.999976, 432058e-11, 0, 0, 0.999961, 485194e-11, 0, 0, 0.999938, 574808e-11, 0, 0, 0.999908, 726643e-11, 0, 0, 0.999865, 984707e-11, 0, 0, 0.999807, 142217e-10, 0, 0, 0.999723, 215581e-10, 0, 0, 0.999602, 336114e-10, 0, 119113e-10, 0.999398, 527353e-10, 0, 355813e-9, 0.998946, 805809e-10, 0, 137768e-8, 0.996647, 942908e-10, 0, 322469e-8, 0.992298, 668733e-10, 0, 597897e-8, 0.989802, 716564e-10, 0, 968903e-8, 0.987019, 821355e-10, 0, 0.0143845, 0.984219, 104555e-9, 0, 0.0200831, 0.980425, 131245e-9, 0, 0.0267948, 0.974241, 139613e-9, 0, 0.034525, 0.967006, 145931e-9, 0, 0.0432757, 0.95893, 167153e-9, 0, 0.0530471, 0.949157, 188146e-9, 0, 0.0638386, 0.94062, 194625e-9, 0, 0.0756487, 0.933509, 213721e-9, 0, 0.0884762, 0.925088, 229616e-9, 0, 0.10232, 0.915178, 239638e-9, 0, 0.117178, 0.904093, 254814e-9, 0, 0.133051, 0.891337, 263685e-9, 0, 0.149939, 0.877326, 274789e-9, 0, 0.167841, 0.861794, 280534e-9, 0, 0.18676, 0.845758, 289534e-9, 0, 0.206696, 0.829792, 294446e-9, 0, 0.22765, 0.813037, 296877e-9, 0, 0.249625, 0.795285, 300217e-9, 0, 0.27262, 0.776323, 299826e-9, 0, 0.296636, 0.756673, 299787e-9, 0, 0.321671, 0.736856, 297867e-9, 0, 0.347718, 0.716883, 294052e-9, 0, 0.374768, 0.696089, 289462e-9, 0, 0.402804, 0.67505, 285212e-9, 0, 0.431796, 0.653509, 27653e-8, 0, 0.461695, 0.63258, 271759e-9, 0, 0.49242, 0.61104, 262811e-9, 0, 0.523822, 0.589567, 255151e-9, 0, 0.555556, 0.568322, 246434e-9, 0, 0.587302, 0.547235, 237061e-9, 0, 0.619048, 0.52616, 228343e-9, 0, 0.650794, 0.505716, 219236e-9, 0, 0.68254, 0.485274, 209595e-9, 0, 0.714286, 0.465411, 201011e-9, 0, 0.746032, 0.445854, 19109e-8, 0, 0.777778, 0.426911, 182897e-9, 0, 0.809524, 0.408222, 173569e-9, 0, 0.84127, 0.390307, 165496e-9, 0, 0.873016, 0.372624, 156799e-9, 0, 0.904762, 0.355804, 14917e-8, 0, 0.936508, 0.33924, 140907e-9, 0, 0.968254, 0.323534, 134062e-9, 0, 1, 1, 622487e-11, 0, 0, 1, 62251e-10, 0, 0, 1, 622837e-11, 0, 0, 0.999999, 624259e-11, 0, 0, 0.999998, 628127e-11, 0, 0, 0.999996, 636451e-11, 0, 0, 0.999991, 65218e-10, 0, 0, 0.999984, 679782e-11, 0, 0, 0.999973, 726361e-11, 0, 0, 0.999955, 803644e-11, 0, 0, 0.999931, 931397e-11, 0, 0, 0.999896, 114299e-10, 0, 0, 0.999847, 149402e-10, 0, 0, 0.999784, 207461e-10, 0, 0, 0.999692, 302493e-10, 0, 0, 0.999554, 454957e-10, 0, 997275e-10, 0.999326, 690762e-10, 0, 724813e-9, 0.998757, 101605e-9, 0, 20972e-7, 0.995367, 958745e-10, 0, 432324e-8, 0.99209, 832808e-10, 0, 746347e-8, 0.989517, 887601e-10, 0, 0.0115534, 0.987008, 10564e-8, 0, 0.0166134, 0.98421, 133179e-9, 0, 0.0226552, 0.98021, 161746e-9, 0, 0.0296838, 0.973676, 161821e-9, 0, 0.0377016, 0.967052, 178635e-9, 0, 0.0467079, 0.959385, 206765e-9, 0, 0.0567013, 0.949461, 22476e-8, 0, 0.0676796, 0.939578, 23574e-8, 0, 0.0796403, 0.932416, 25893e-8, 0, 0.0925812, 0.923759, 271228e-9, 0, 0.106501, 0.914223, 289165e-9, 0, 0.121397, 0.902942, 301156e-9, 0, 0.13727, 0.890419, 313852e-9, 0, 0.15412, 0.876639, 324408e-9, 0, 0.171946, 0.861316, 33249e-8, 0, 0.190751, 0.84496, 338497e-9, 0, 0.210537, 0.828427, 345861e-9, 0, 0.231305, 0.811871, 347863e-9, 0, 0.253057, 0.794397, 350225e-9, 0, 0.275797, 0.775726, 349915e-9, 0, 0.299525, 0.75617, 347297e-9, 0, 0.324242, 0.736091, 344232e-9, 0, 0.349947, 0.716213, 340835e-9, 0, 0.376633, 0.695736, 332369e-9, 0, 0.404289, 0.674961, 327943e-9, 0, 0.432895, 0.653518, 318533e-9, 0, 0.462415, 0.632574, 310391e-9, 0, 0.492788, 0.61134, 300755e-9, 0, 0.523909, 0.590017, 290506e-9, 0, 0.555556, 0.568752, 280446e-9, 0, 0.587302, 0.548061, 269902e-9, 0, 0.619048, 0.52711, 258815e-9, 0, 0.650794, 0.506682, 248481e-9, 0, 0.68254, 0.486524, 237141e-9, 0, 0.714286, 0.466812, 226872e-9, 0, 0.746032, 0.44732, 216037e-9, 0, 0.777778, 0.428473, 205629e-9, 0, 0.809524, 0.409921, 195691e-9, 0, 0.84127, 0.392028, 185457e-9, 0, 0.873016, 0.374606, 176436e-9, 0, 0.904762, 0.357601, 166508e-9, 0, 0.936508, 0.341348, 158385e-9, 0, 0.968254, 0.32542, 149203e-9, 0, 1, 1, 103967e-10, 0, 0, 1, 10397e-9, 0, 0, 1, 104019e-10, 0, 0, 0.999999, 104231e-10, 0, 0, 0.999998, 104806e-10, 0, 0, 0.999995, 106042e-10, 0, 0, 0.999991, 108366e-10, 0, 0, 0.999982, 112415e-10, 0, 0, 0.999968, 119174e-10, 0, 0, 0.99995, 130227e-10, 0, 0, 0.999922, 148176e-10, 0, 0, 0.999884, 177303e-10, 0, 0, 0.99983, 224564e-10, 0, 0, 0.999758, 300966e-10, 0, 0, 0.999654, 423193e-10, 0, 549083e-11, 0.999503, 614848e-10, 0, 296087e-9, 0.999237, 903576e-10, 0, 123144e-8, 0.998491, 1271e-7, 0, 295954e-8, 0.994594, 107754e-9, 0, 555829e-8, 0.99178, 103025e-9, 0, 907209e-8, 0.989265, 11154e-8, 0, 0.0135257, 0.986998, 136296e-9, 0, 0.0189327, 0.984137, 169154e-9, 0, 0.0252993, 0.979798, 196671e-9, 0, 0.0326272, 0.97337, 196678e-9, 0, 0.0409157, 0.967239, 223121e-9, 0, 0.0501623, 0.959543, 253809e-9, 0, 0.0603638, 0.949466, 265972e-9, 0, 0.0715171, 0.939074, 288372e-9, 0, 0.0836187, 0.931118, 310983e-9, 0, 0.0966657, 0.922525, 325561e-9, 0, 0.110656, 0.912983, 345725e-9, 0, 0.125588, 0.901617, 3556e-7, 0, 0.141461, 0.889487, 374012e-9, 0, 0.158275, 0.875787, 383445e-9, 0, 0.176031, 0.860654, 393972e-9, 0, 0.19473, 0.844417, 400311e-9, 0, 0.214374, 0.82741, 405004e-9, 0, 0.234967, 0.810545, 407378e-9, 0, 0.256512, 0.793312, 407351e-9, 0, 0.279011, 0.774847, 406563e-9, 0, 0.302468, 0.755621, 404903e-9, 0, 0.326887, 0.735511, 397486e-9, 0, 0.352266, 0.715435, 39357e-8, 0, 0.378605, 0.695403, 384739e-9, 0, 0.405897, 0.674681, 376108e-9, 0, 0.43413, 0.65359, 365997e-9, 0, 0.463277, 0.632471, 354957e-9, 0, 0.493295, 0.61151, 343593e-9, 0, 0.524106, 0.59064, 331841e-9, 0, 0.555561, 0.569386, 318891e-9, 0, 0.587302, 0.548785, 3072e-7, 0, 0.619048, 0.528146, 29361e-8, 0, 0.650794, 0.507872, 281709e-9, 0, 0.68254, 0.487805, 268627e-9, 0, 0.714286, 0.468196, 255887e-9, 0, 0.746032, 0.448922, 243997e-9, 0, 0.777778, 0.430093, 231662e-9, 0, 0.809524, 0.411845, 220339e-9, 0, 0.84127, 0.393808, 208694e-9, 0, 0.873016, 0.376615, 198045e-9, 0, 0.904762, 0.359655, 187375e-9, 0, 0.936508, 0.343452, 177371e-9, 0, 0.968254, 0.32765, 167525e-9, 0, 1, 1, 169351e-10, 0, 0, 1, 169356e-10, 0, 0, 1, 169427e-10, 0, 0, 0.999999, 169736e-10, 0, 0, 0.999998, 170575e-10, 0, 0, 0.999995, 172372e-10, 0, 0, 0.99999, 175739e-10, 0, 0, 0.999979, 181568e-10, 0, 0, 0.999966, 191206e-10, 0, 0, 0.999944, 20677e-9, 0, 0, 0.999912, 231644e-10, 0, 0, 0.999869, 271268e-10, 0, 0, 0.999811, 334272e-10, 0, 0, 0.99973, 433979e-10, 0, 0, 0.999617, 590083e-10, 0, 680315e-10, 0.999445, 829497e-10, 0, 612796e-9, 0.999138, 118019e-9, 0, 187408e-8, 0.998095, 156712e-9, 0, 395791e-8, 0.993919, 125054e-9, 0, 692144e-8, 0.991333, 126091e-9, 0, 0.0107962, 0.989226, 144912e-9, 0, 0.0155986, 0.986954, 175737e-9, 0, 0.0213364, 0.983982, 213883e-9, 0, 0.0280114, 0.979128, 234526e-9, 0, 0.0356226, 0.973327, 243725e-9, 0, 0.0441668, 0.967416, 2773e-7, 0, 0.0536399, 0.959729, 308799e-9, 0, 0.0640376, 0.949758, 322447e-9, 0, 0.0753554, 0.939173, 350021e-9, 0, 0.0875893, 0.9296, 370089e-9, 0, 0.100736, 0.921181, 391365e-9, 0, 0.114793, 0.91164, 413636e-9, 0, 0.129759, 0.900435, 427068e-9, 0, 0.145632, 0.888183, 441046e-9, 0, 0.162412, 0.874772, 454968e-9, 0, 0.180101, 0.859566, 461882e-9, 0, 0.1987, 0.843579, 471556e-9, 0, 0.218213, 0.826453, 474335e-9, 0, 0.238641, 0.809164, 477078e-9, 0, 0.259989, 0.792179, 47755e-8, 0, 0.282262, 0.773866, 472573e-9, 0, 0.305464, 0.754944, 469765e-9, 0, 0.329599, 0.735133, 462371e-9, 0, 0.35467, 0.714858, 453674e-9, 0, 0.380678, 0.694829, 443888e-9, 0, 0.407622, 0.674453, 432052e-9, 0, 0.435493, 0.653685, 420315e-9, 0, 0.464275, 0.632666, 406829e-9, 0, 0.493938, 0.611676, 392234e-9, 0, 0.524422, 0.591193, 379208e-9, 0, 0.555624, 0.570145, 36319e-8, 0, 0.587302, 0.549566, 349111e-9, 0, 0.619048, 0.529278, 334166e-9, 0, 0.650794, 0.509026, 318456e-9, 0, 0.68254, 0.489186, 30449e-8, 0, 0.714286, 0.469662, 289051e-9, 0, 0.746032, 0.450691, 275494e-9, 0, 0.777778, 0.431841, 261437e-9, 0, 0.809524, 0.413752, 247846e-9, 0, 0.84127, 0.395951, 235085e-9, 0, 0.873016, 0.378633, 222245e-9, 0, 0.904762, 0.36194, 210533e-9, 0, 0.936508, 0.345599, 198494e-9, 0, 0.968254, 0.329999, 188133e-9, 0, 1, 1, 269663e-10, 0, 0, 1, 26967e-9, 0, 0, 1, 269772e-10, 0, 0, 0.999999, 270214e-10, 0, 0, 0.999998, 271415e-10, 0, 0, 0.999994, 27398e-9, 0, 0, 0.999988, 278771e-10, 0, 0, 0.999977, 287019e-10, 0, 0, 0.999961, 300544e-10, 0, 0, 0.999937, 322138e-10, 0, 0, 0.999904, 356163e-10, 0, 0, 0.999854, 409465e-10, 0, 0, 0.99979, 492651e-10, 0, 0, 0.999699, 621722e-10, 0, 88288e-11, 0.999572, 819715e-10, 0, 223369e-9, 0.999381, 111689e-9, 0, 105414e-8, 0.999016, 153862e-9, 0, 26493e-7, 0.997437, 187667e-9, 0, 508608e-8, 0.993545, 155672e-9, 0, 840554e-8, 0.991135, 161455e-9, 0, 0.012629, 0.989157, 188241e-9, 0, 0.0177661, 0.986874, 226229e-9, 0, 0.0238198, 0.983714, 268668e-9, 0, 0.0307887, 0.978301, 277109e-9, 0, 0.0386688, 0.973227, 303446e-9, 0, 0.0474554, 0.967317, 341851e-9, 0, 0.0571428, 0.959477, 370885e-9, 0, 0.0677256, 0.950012, 392753e-9, 0, 0.0791988, 0.939484, 42781e-8, 0, 0.0915576, 0.928135, 443866e-9, 0, 0.104798, 0.919819, 472959e-9, 0, 0.118918, 0.910049, 491551e-9, 0, 0.133915, 0.899181, 512616e-9, 0, 0.149788, 0.886881, 523563e-9, 0, 0.166537, 0.87359, 540183e-9, 0, 0.184164, 0.858613, 547386e-9, 0, 0.202669, 0.842809, 554809e-9, 0, 0.222056, 0.825727, 558316e-9, 0, 0.242329, 0.808086, 557824e-9, 0, 0.263492, 0.790728, 556346e-9, 0, 0.285551, 0.772987, 552672e-9, 0, 0.30851, 0.7541, 543738e-9, 0, 0.332376, 0.734669, 536107e-9, 0, 0.357153, 0.714411, 523342e-9, 0, 0.382845, 0.694196, 512238e-9, 0, 0.409454, 0.674252, 497465e-9, 0, 0.436977, 0.65357, 481096e-9, 0, 0.465404, 0.632999, 467054e-9, 0, 0.494713, 0.611994, 448771e-9, 0, 0.524864, 0.591604, 431889e-9, 0, 0.555779, 0.571134, 415238e-9, 0, 0.587302, 0.550528, 396369e-9, 0, 0.619048, 0.530292, 379477e-9, 0, 0.650794, 0.510364, 361488e-9, 0, 0.68254, 0.490749, 343787e-9, 0, 0.714286, 0.471266, 327822e-9, 0, 0.746032, 0.452462, 310626e-9, 0, 0.777778, 0.433907, 295352e-9, 0, 0.809524, 0.415659, 279179e-9, 0, 0.84127, 0.398138, 264685e-9, 0, 0.873016, 0.380833, 249905e-9, 0, 0.904762, 0.364247, 236282e-9, 0, 0.936508, 0.348041, 222905e-9, 0, 0.968254, 0.332389, 210522e-9, 0, 1, 1, 420604e-10, 0, 0, 1, 420614e-10, 0, 0, 1, 420757e-10, 0, 0, 0.999999, 42138e-9, 0, 0, 0.999997, 423067e-10, 0, 0, 0.999993, 426668e-10, 0, 0, 0.999986, 433372e-10, 0, 0, 0.999974, 444857e-10, 0, 0, 0.999956, 463554e-10, 0, 0, 0.99993, 493105e-10, 0, 0, 0.999892, 539077e-10, 0, 0, 0.999838, 610005e-10, 0, 0, 0.999767, 718822e-10, 0, 0, 0.999666, 884581e-10, 0, 365471e-10, 0.999525, 113398e-9, 0, 485623e-9, 0.999311, 150043e-9, 0, 162096e-8, 0.998865, 200063e-9, 0, 355319e-8, 0.996278, 211014e-9, 0, 633818e-8, 0.992956, 189672e-9, 0, 0.0100043, 0.991017, 210262e-9, 0, 0.0145648, 0.989055, 244292e-9, 0, 0.0200237, 0.986741, 290481e-9, 0, 0.0263798, 0.983288, 334303e-9, 0, 0.033629, 0.977784, 340307e-9, 0, 0.0417652, 0.973037, 377864e-9, 0, 0.0507821, 0.967181, 4239e-7, 0, 0.060673, 0.958971, 443854e-9, 0, 0.0714314, 0.950093, 483039e-9, 0, 0.0830518, 0.939552, 517934e-9, 0, 0.0955288, 0.927678, 539449e-9, 0, 0.108859, 0.918278, 568604e-9, 0, 0.123038, 0.908449, 588505e-9, 0, 0.138065, 0.897713, 612473e-9, 0, 0.153938, 0.885533, 625575e-9, 0, 0.170657, 0.872131, 63854e-8, 0, 0.188224, 0.857517, 647034e-9, 0, 0.20664, 0.841796, 65209e-8, 0, 0.225909, 0.824726, 6544e-7, 0, 0.246035, 0.807297, 655744e-9, 0, 0.267022, 0.789058, 646716e-9, 0, 0.288878, 0.77189, 643898e-9, 0, 0.311607, 0.753082, 629973e-9, 0, 0.335216, 0.7341, 621564e-9, 0, 0.359713, 0.714094, 605171e-9, 0, 0.385103, 0.693839, 588752e-9, 0, 0.41139, 0.673891, 573294e-9, 0, 0.438576, 0.653565, 552682e-9, 0, 0.466656, 0.633326, 533446e-9, 0, 0.495617, 0.612582, 514635e-9, 0, 0.525431, 0.59205, 49303e-8, 0, 0.556041, 0.571918, 471842e-9, 0, 0.587338, 0.551572, 451713e-9, 0, 0.619048, 0.531553, 430049e-9, 0, 0.650794, 0.51175, 410445e-9, 0, 0.68254, 0.49238, 390098e-9, 0, 0.714286, 0.473143, 370033e-9, 0, 0.746032, 0.45423, 351205e-9, 0, 0.777778, 0.435963, 332049e-9, 0, 0.809524, 0.41787, 315021e-9, 0, 0.84127, 0.400387, 297315e-9, 0, 0.873016, 0.383332, 281385e-9, 0, 0.904762, 0.366665, 265397e-9, 0, 0.936508, 0.350633, 250601e-9, 0, 0.968254, 0.334964, 23589e-8, 0, 1, 1, 643736e-10, 0, 0, 1, 64375e-9, 0, 0, 1, 643947e-10, 0, 0, 0.999999, 64481e-9, 0, 0, 0.999997, 647143e-10, 0, 0, 0.999994, 652119e-10, 0, 0, 0.999985, 661359e-10, 0, 0, 0.999972, 677116e-10, 0, 0, 0.999952, 702599e-10, 0, 0, 0.999922, 742517e-10, 0, 0, 0.99988, 803906e-10, 0, 0, 0.99982, 897315e-10, 0, 0, 0.999741, 103838e-9, 0, 0, 0.999629, 12496e-8, 0, 149024e-9, 0.999474, 156161e-9, 0, 861027e-9, 0.999229, 201034e-9, 0, 231198e-8, 0.998662, 259069e-9, 0, 458147e-8, 0.995299, 245439e-9, 0, 770895e-8, 0.992732, 24498e-8, 0, 0.0117126, 0.990847, 273211e-9, 0, 0.0165989, 0.988911, 316492e-9, 0, 0.0223674, 0.98654, 37161e-8, 0, 0.0290135, 0.982636, 410352e-9, 0, 0.0365309, 0.977346, 421756e-9, 0, 0.0449117, 0.972909, 475578e-9, 0, 0.0541481, 0.966821, 522482e-9, 0, 0.0642326, 0.958686, 545008e-9, 0, 0.075158, 0.949754, 589286e-9, 0, 0.0869181, 0.939184, 619995e-9, 0, 0.0995074, 0.927505, 654266e-9, 0, 0.112922, 0.916606, 682362e-9, 0, 0.127157, 0.906707, 704286e-9, 0, 0.142212, 0.895937, 725909e-9, 0, 0.158085, 0.883913, 743939e-9, 0, 0.174776, 0.870642, 755157e-9, 0, 0.192287, 0.856241, 764387e-9, 0, 0.210619, 0.84069, 771032e-9, 0, 0.229775, 0.823728, 765906e-9, 0, 0.249761, 0.806481, 767604e-9, 0, 0.270582, 0.787924, 754385e-9, 0, 0.292243, 0.770588, 749668e-9, 0, 0.314753, 0.751991, 731613e-9, 0, 0.338118, 0.733407, 717655e-9, 0, 0.362347, 0.713688, 700604e-9, 0, 0.387447, 0.693595, 678765e-9, 0, 0.413424, 0.673426, 657042e-9, 0, 0.440284, 0.65359, 635892e-9, 0, 0.468027, 0.633576, 611569e-9, 0, 0.496645, 0.613144, 586011e-9, 0, 0.526122, 0.592711, 563111e-9, 0, 0.556417, 0.572722, 537699e-9, 0, 0.587451, 0.552762, 512556e-9, 0, 0.619048, 0.532985, 489757e-9, 0, 0.650794, 0.513219, 464139e-9, 0, 0.68254, 0.493992, 442193e-9, 0, 0.714286, 0.47509, 418629e-9, 0, 0.746032, 0.456287, 397045e-9, 0, 0.777778, 0.438152, 375504e-9, 0, 0.809524, 0.420294, 35492e-8, 0, 0.84127, 0.402749, 335327e-9, 0, 0.873016, 0.385879, 316422e-9, 0, 0.904762, 0.369352, 298333e-9, 0, 0.936508, 0.353301, 281417e-9, 0, 0.968254, 0.337781, 265203e-9, 0, 1, 1, 968267e-10, 0, 0, 1, 968284e-10, 0, 0, 1, 968556e-10, 0, 0, 0.999999, 969733e-10, 0, 0, 0.999997, 972913e-10, 0, 0, 0.999993, 979688e-10, 0, 0, 0.999984, 992239e-10, 0, 0, 0.999969, 101356e-9, 0, 0, 0.999946, 104784e-9, 0, 0, 0.999913, 110111e-9, 0, 0, 0.999868, 118217e-9, 0, 0, 0.999801, 130396e-9, 0, 0, 0.999712, 148523e-9, 0, 124907e-10, 0.999589, 175233e-9, 0, 355405e-9, 0.999416, 213999e-9, 0, 13528e-7, 0.999136, 268529e-9, 0, 312557e-8, 0.998367, 333088e-9, 0, 573045e-8, 0.994701, 304757e-9, 0, 919397e-8, 0.992497, 318031e-9, 0, 0.0135261, 0.990608, 353863e-9, 0, 0.0187278, 0.988715, 409044e-9, 0, 0.0247947, 0.986241, 472967e-9, 0, 0.0317196, 0.981696, 495104e-9, 0, 0.039494, 0.977097, 532873e-9, 0, 0.0481087, 0.972583, 594447e-9, 0, 0.0575549, 0.966142, 636867e-9, 0, 0.0678242, 0.95823, 669899e-9, 0, 0.0789089, 0.949677, 719499e-9, 0, 0.0908023, 0.939226, 750584e-9, 0, 0.103499, 0.927501, 793183e-9, 0, 0.116993, 0.915199, 81995e-8, 0, 0.131282, 0.90498, 847654e-9, 0, 0.146364, 0.894243, 868929e-9, 0, 0.162237, 0.882154, 884278e-9, 0, 0.178902, 0.869161, 898108e-9, 0, 0.196358, 0.854751, 901254e-9, 0, 0.21461, 0.839368, 90679e-8, 0, 0.23366, 0.822874, 901541e-9, 0, 0.253512, 0.805514, 897297e-9, 0, 0.274174, 0.78716, 881856e-9, 0, 0.29565, 0.769061, 870032e-9, 0, 0.31795, 0.751, 851719e-9, 0, 0.341081, 0.732614, 830671e-9, 0, 0.365053, 0.713171, 806569e-9, 0, 0.389874, 0.693472, 78338e-8, 0, 0.415553, 0.673528, 756404e-9, 0, 0.442098, 0.653397, 726872e-9, 0, 0.469512, 0.633781, 700494e-9, 0, 0.497794, 0.613877, 67105e-8, 0, 0.526935, 0.593506, 640361e-9, 0, 0.556908, 0.573667, 613502e-9, 0, 0.587657, 0.553932, 583177e-9, 0, 0.61906, 0.534345, 554375e-9, 0, 0.650794, 0.515042, 527811e-9, 0, 0.68254, 0.495674, 499367e-9, 0, 0.714286, 0.477132, 47429e-8, 0, 0.746032, 0.458609, 447726e-9, 0, 0.777778, 0.440354, 424205e-9, 0, 0.809524, 0.422765, 399549e-9, 0, 0.84127, 0.405472, 378315e-9, 0, 0.873016, 0.388482, 355327e-9, 0, 0.904762, 0.372191, 336122e-9, 0, 0.936508, 0.356099, 315247e-9, 0, 0.968254, 0.340737, 29794e-8, 0, 1, 1, 143327e-9, 0, 0, 1, 14333e-8, 0, 0, 1, 143366e-9, 0, 0, 0.999999, 143524e-9, 0, 0, 0.999996, 143952e-9, 0, 0, 0.999991, 144862e-9, 0, 0, 0.999981, 146544e-9, 0, 0, 0.999966, 149391e-9, 0, 0, 0.999941, 153946e-9, 0, 0, 0.999905, 160971e-9, 0, 0, 0.999852, 171562e-9, 0, 0, 0.99978, 18729e-8, 0, 0, 0.999681, 210386e-9, 0, 826239e-10, 0.999546, 243906e-9, 0, 664807e-9, 0.999352, 291739e-9, 0, 196192e-8, 0.999027, 357419e-9, 0, 405941e-8, 0.997886, 422349e-9, 0, 699664e-8, 0.99419, 385008e-9, 0, 0.0107896, 0.99214, 409775e-9, 0, 0.0154415, 0.990274, 456418e-9, 0, 0.0209488, 0.988455, 527008e-9, 0, 0.0273037, 0.985804, 597685e-9, 0, 0.0344969, 0.98103, 613124e-9, 0, 0.0425183, 0.976674, 668321e-9, 0, 0.0513575, 0.972021, 736985e-9, 0, 0.0610046, 0.965274, 773789e-9, 0, 0.0714508, 0.958046, 830852e-9, 0, 0.0826877, 0.949333, 875766e-9, 0, 0.0947085, 0.939135, 917088e-9, 0, 0.107507, 0.927119, 952244e-9, 0, 0.121078, 0.91469, 990626e-9, 0, 0.135419, 0.903006, 101304e-8, 0, 0.150526, 0.892368, 103834e-8, 0, 0.166399, 0.880231, 105002e-8, 0, 0.183038, 0.867432, 106331e-8, 0, 0.200443, 0.853208, 106783e-8, 0, 0.218618, 0.837956, 106458e-8, 0, 0.237566, 0.821772, 105945e-8, 0, 0.257291, 0.804328, 104685e-8, 0, 0.2778, 0.786465, 103178e-8, 0, 0.2991, 0.768004, 101077e-8, 0, 0.321199, 0.74972, 985504e-9, 0, 0.344106, 0.731682, 962893e-9, 0, 0.36783, 0.712813, 932146e-9, 0, 0.392383, 0.693139, 89871e-8, 0, 0.417774, 0.673566, 869678e-9, 0, 0.444013, 0.653483, 835525e-9, 0, 0.471107, 0.633891, 799853e-9, 0, 0.49906, 0.614433, 766838e-9, 0, 0.527869, 0.594586, 732227e-9, 0, 0.557517, 0.574769, 696442e-9, 0, 0.587966, 0.555149, 663935e-9, 0, 0.61913, 0.535898, 629826e-9, 0, 0.650794, 0.516753, 596486e-9, 0, 0.68254, 0.497816, 567078e-9, 0, 0.714286, 0.479034, 534399e-9, 0, 0.746032, 0.460975, 507013e-9, 0, 0.777778, 0.442935, 477421e-9, 0, 0.809524, 0.425263, 451101e-9, 0, 0.84127, 0.408248, 424964e-9, 0, 0.873016, 0.391339, 39993e-8, 0, 0.904762, 0.37513, 377619e-9, 0, 0.936508, 0.359172, 354418e-9, 0, 0.968254, 0.343876, 334823e-9, 0, 1, 1, 209042e-9, 0, 0, 1, 209045e-9, 0, 0, 1, 209093e-9, 0, 0, 0.999999, 209304e-9, 0, 0, 0.999996, 209871e-9, 0, 0, 0.999991, 211078e-9, 0, 0, 0.999979, 213304e-9, 0, 0, 0.999963, 217061e-9, 0, 0, 0.999933, 223042e-9, 0, 0, 0.999894, 232206e-9, 0, 0, 0.999837, 245901e-9, 0, 0, 0.999756, 266023e-9, 0, 102927e-11, 0.999648, 295204e-9, 0, 233468e-9, 0.999499, 336958e-9, 0, 108237e-8, 0.999283, 395563e-9, 0, 268832e-8, 0.998896, 473785e-9, 0, 511138e-8, 0.997006, 520008e-9, 0, 837705e-8, 0.993819, 497261e-9, 0, 0.0124928, 0.991632, 523722e-9, 0, 0.0174561, 0.989875, 587258e-9, 0, 0.0232596, 0.988109, 676329e-9, 0, 0.0298932, 0.985155, 747701e-9, 0, 0.0373453, 0.980479, 768803e-9, 0, 0.0456045, 0.976271, 841054e-9, 0, 0.0546593, 0.971347, 911469e-9, 0, 0.0644994, 0.964528, 953057e-9, 0, 0.0751152, 0.957632, 102221e-8, 0, 0.0864981, 0.948681, 106122e-8, 0, 0.0986407, 0.938716, 111857e-8, 0, 0.111537, 0.926629, 114762e-8, 0, 0.125182, 0.914025, 118995e-8, 0, 0.139571, 0.901026, 121228e-8, 0, 0.154703, 0.890358, 123946e-8, 0, 0.170576, 0.878283, 12527e-7, 0, 0.18719, 0.865459, 125536e-8, 0, 0.204547, 0.851407, 126134e-8, 0, 0.222648, 0.836276, 124759e-8, 0, 0.241498, 0.820436, 124443e-8, 0, 0.261101, 0.803253, 122071e-8, 0, 0.281465, 0.785562, 120107e-8, 0, 0.302595, 0.76718, 117762e-8, 0, 0.324501, 0.748551, 114289e-8, 0, 0.347192, 0.730564, 110872e-8, 0, 0.370679, 0.712253, 107636e-8, 0, 0.394973, 0.692867, 103646e-8, 0, 0.420085, 0.673695, 996793e-9, 0, 0.446027, 0.653912, 95675e-8, 0, 0.47281, 0.634129, 916739e-9, 0, 0.500441, 0.615004, 874401e-9, 0, 0.528921, 0.595587, 833411e-9, 0, 0.558244, 0.575965, 794556e-9, 0, 0.588384, 0.5566, 75196e-8, 0, 0.619281, 0.537428, 716381e-9, 0, 0.650795, 0.518623, 676558e-9, 0, 0.68254, 0.499964, 64074e-8, 0, 0.714286, 0.481356, 605984e-9, 0, 0.746032, 0.463279, 570256e-9, 0, 0.777778, 0.445673, 540138e-9, 0, 0.809524, 0.428032, 507299e-9, 0, 0.84127, 0.411112, 479553e-9, 0, 0.873016, 0.394444, 450737e-9, 0, 0.904762, 0.378247, 424269e-9, 0, 0.936508, 0.362415, 399111e-9, 0, 0.968254, 0.347103, 375274e-9, 0, 1, 1, 300729e-9, 0, 0, 1, 300733e-9, 0, 0, 1, 300797e-9, 0, 0, 0.999998, 301072e-9, 0, 0, 0.999996, 301817e-9, 0, 0, 0.999989, 303398e-9, 0, 0, 0.999977, 306309e-9, 0, 0, 0.999958, 311209e-9, 0, 0, 0.999927, 318975e-9, 0, 0, 0.999884, 330804e-9, 0, 0, 0.99982, 34834e-8, 0, 0, 0.999733, 373854e-9, 0, 326995e-10, 0.999613, 410424e-9, 0, 477174e-9, 0.999447, 462047e-9, 0, 161099e-8, 0.999204, 533322e-9, 0, 353153e-8, 0.998725, 624964e-9, 0, 627965e-8, 0.995871, 631786e-9, 0, 98693e-7, 0.993194, 632017e-9, 0, 0.0143011, 0.991541, 68923e-8, 0, 0.019568, 0.989773, 766892e-9, 0, 0.0256593, 0.987647, 863668e-9, 0, 0.0325625, 0.984193, 922089e-9, 0, 0.0402647, 0.980016, 970749e-9, 0, 0.0487532, 0.975859, 106027e-8, 0, 0.058016, 0.970514, 112239e-8, 0, 0.0680419, 0.963625, 117212e-8, 0, 0.0788208, 0.956959, 125211e-8, 0, 0.0903439, 0.947956, 129411e-8, 0, 0.102604, 0.93809, 135879e-8, 0, 0.115594, 0.92659, 139309e-8, 0, 0.129309, 0.913829, 143253e-8, 0, 0.143745, 0.90005, 145809e-8, 0, 0.158901, 0.888129, 14748e-7, 0, 0.174774, 0.87607, 148756e-8, 0, 0.191365, 0.863461, 148714e-8, 0, 0.208674, 0.849594, 148892e-8, 0, 0.226705, 0.834531, 146496e-8, 0, 0.245461, 0.81903, 14579e-7, 0, 0.264947, 0.802122, 143039e-8, 0, 0.28517, 0.78445, 139717e-8, 0, 0.306137, 0.766434, 136312e-8, 0, 0.327857, 0.747816, 132597e-8, 0, 0.350341, 0.729519, 128323e-8, 0, 0.373598, 0.711454, 123803e-8, 0, 0.397642, 0.692699, 119097e-8, 0, 0.422485, 0.673723, 114565e-8, 0, 0.448139, 0.654386, 109552e-8, 0, 0.474619, 0.634673, 104553e-8, 0, 0.501933, 0.615554, 99985e-8, 0, 0.530089, 0.596462, 948207e-9, 0, 0.559087, 0.577385, 902299e-9, 0, 0.588913, 0.558257, 856448e-9, 0, 0.619525, 0.5392, 810395e-9, 0, 0.650826, 0.520543, 768558e-9, 0, 0.68254, 0.502206, 7239e-7, 0, 0.714286, 0.48402, 685794e-9, 0, 0.746032, 0.465779, 64471e-8, 0, 0.777778, 0.448455, 609583e-9, 0, 0.809524, 0.431091, 57227e-8, 0, 0.84127, 0.414147, 54042e-8, 0, 0.873016, 0.39765, 506545e-9, 0, 0.904762, 0.381576, 477635e-9, 0, 0.936508, 0.365881, 448446e-9, 0, 0.968254, 0.350582, 421424e-9, 0, 1, 1, 427144e-9, 0, 0, 1, 427151e-9, 0, 0, 1, 427232e-9, 0, 0, 0.999998, 42759e-8, 0, 0, 0.999995, 428555e-9, 0, 0, 0.999988, 430603e-9, 0, 0, 0.999976, 434368e-9, 0, 0, 0.999952, 440688e-9, 0, 0, 0.999919, 450667e-9, 0, 0, 0.999871, 46578e-8, 0, 0, 0.999801, 488024e-9, 0, 0, 0.999704, 520092e-9, 0, 129791e-9, 0.999572, 565553e-9, 0, 821056e-9, 0.999389, 628906e-9, 0, 225241e-8, 0.999114, 714911e-9, 0, 449109e-8, 0.998488, 819218e-9, 0, 756249e-8, 0.995234, 80415e-8, 0, 0.0114716, 0.993021, 830181e-9, 0, 0.0162131, 0.991407, 902645e-9, 0, 0.021776, 0.989625, 996934e-9, 0, 0.0281471, 0.987064, 109707e-8, 0, 0.0353118, 0.983265, 114353e-8, 0, 0.0432562, 0.979535, 12272e-7, 0, 0.0519665, 0.975224, 132642e-8, 0, 0.0614298, 0.969574, 138092e-8, 0, 0.0716348, 0.963021, 145896e-8, 0, 0.0825709, 0.956046, 152834e-8, 0, 0.094229, 0.947136, 158217e-8, 0, 0.106602, 0.937313, 16347e-7, 0, 0.119682, 0.926073, 168383e-8, 0, 0.133465, 0.913121, 171627e-8, 0, 0.147947, 0.899165, 174229e-8, 0, 0.163125, 0.885891, 176137e-8, 0, 0.178998, 0.873783, 176406e-8, 0, 0.195566, 0.861331, 176156e-8, 0, 0.21283, 0.847569, 175346e-8, 0, 0.230793, 0.832785, 172753e-8, 0, 0.249459, 0.817442, 170204e-8, 0, 0.268832, 0.800613, 166576e-8, 0, 0.28892, 0.783597, 162909e-8, 0, 0.30973, 0.76571, 15826e-7, 0, 0.331271, 0.747021, 153106e-8, 0, 0.353554, 0.728593, 148036e-8, 0, 0.37659, 0.710661, 142808e-8, 0, 0.400391, 0.692426, 136906e-8, 0, 0.424973, 0.673623, 131066e-8, 0, 0.450347, 0.65494, 125569e-8, 0, 0.476531, 0.635448, 119517e-8, 0, 0.503535, 0.616221, 113828e-8, 0, 0.531372, 0.597531, 10816e-7, 0, 0.560047, 0.578795, 102673e-8, 0, 0.589554, 0.559892, 970985e-9, 0, 0.619869, 0.541307, 919773e-9, 0, 0.650923, 0.522608, 868479e-9, 0, 0.68254, 0.504484, 82137e-8, 0, 0.714286, 0.486603, 772916e-9, 0, 0.746032, 0.468802, 730353e-9, 0, 0.777778, 0.451172, 684955e-9, 0, 0.809524, 0.434348, 647565e-9, 0, 0.84127, 0.417445, 605863e-9, 0, 0.873016, 0.401077, 571885e-9, 0, 0.904762, 0.385039, 536034e-9, 0, 0.936508, 0.369483, 504227e-9, 0, 0.968254, 0.354272, 473165e-9, 0, 1, 1, 599525e-9, 0, 0, 1, 599533e-9, 0, 0, 1, 599639e-9, 0, 0, 0.999998, 600097e-9, 0, 0, 0.999994, 601336e-9, 0, 0, 0.999987, 603958e-9, 0, 0, 0.999972, 608775e-9, 0, 0, 0.999949, 616842e-9, 0, 0, 0.999912, 629534e-9, 0, 0, 0.999857, 648658e-9, 0, 0, 0.999781, 676615e-9, 0, 538873e-11, 0.999674, 716574e-9, 0, 308602e-9, 0.999528, 772641e-9, 0, 127003e-8, 0.999326, 849806e-9, 0, 300783e-8, 0.999009, 952682e-9, 0, 556637e-8, 0.998112, 106394e-8, 0, 895889e-8, 0.994496, 102228e-8, 0, 0.0131827, 0.992806, 108586e-8, 0, 0.0182277, 0.991211, 11759e-7, 0, 0.0240795, 0.989415, 128955e-8, 0, 0.030723, 0.986499, 139038e-8, 0, 0.0381418, 0.982679, 144539e-8, 0, 0.046321, 0.978839, 153954e-8, 0, 0.0552459, 0.974295, 164417e-8, 0, 0.0649034, 0.968784, 171517e-8, 0, 0.0752814, 0.962324, 180282e-8, 0, 0.0863693, 0.954956, 186387e-8, 0, 0.0981578, 0.94624, 193817e-8, 0, 0.110639, 0.936517, 198156e-8, 0, 0.123806, 0.925186, 203042e-8, 0, 0.137655, 0.91252, 20664e-7, 0, 0.15218, 0.898441, 207822e-8, 0, 0.16738, 0.884394, 20992e-7, 0, 0.183253, 0.871273, 208748e-8, 0, 0.199799, 0.859057, 208686e-8, 0, 0.21702, 0.845243, 205519e-8, 0, 0.234918, 0.830723, 202868e-8, 0, 0.253496, 0.815801, 199501e-8, 0, 0.272761, 0.79914, 194193e-8, 0, 0.292719, 0.782372, 188824e-8, 0, 0.313377, 0.76482, 183695e-8, 0, 0.334745, 0.746586, 177418e-8, 0, 0.356833, 0.7281, 170628e-8, 0, 0.379654, 0.709842, 164063e-8, 0, 0.403221, 0.692019, 157355e-8, 0, 0.427548, 0.67364, 150262e-8, 0, 0.452651, 0.655277, 143473e-8, 0, 0.478545, 0.636438, 136371e-8, 0, 0.505246, 0.617364, 129911e-8, 0, 0.532768, 0.598603, 123014e-8, 0, 0.561122, 0.580195, 116587e-8, 0, 0.590309, 0.561786, 110398e-8, 0, 0.620318, 0.543377, 104148e-8, 0, 0.651102, 0.525093, 983984e-9, 0, 0.682545, 0.506791, 92667e-8, 0, 0.714286, 0.489291, 874326e-9, 0, 0.746032, 0.471811, 821734e-9, 0, 0.777778, 0.454435, 774698e-9, 0, 0.809524, 0.437493, 727302e-9, 0, 0.84127, 0.420977, 684039e-9, 0, 0.873016, 0.404729, 64373e-8, 0, 0.904762, 0.388756, 60285e-8, 0, 0.936508, 0.373344, 56765e-8, 0, 0.968254, 0.358191, 531929e-9, 0, 1, 1, 832169e-9, 0, 0, 1, 832178e-9, 0, 0, 1, 83231e-8, 0, 0, 0.999998, 832893e-9, 0, 0, 0.999995, 834465e-9, 0, 0, 0.999985, 837791e-9, 0, 0, 0.999969, 843893e-9, 0, 0, 0.999944, 854086e-9, 0, 0, 0.999903, 870071e-9, 0, 0, 0.999843, 894042e-9, 0, 0, 0.999759, 928865e-9, 0, 531805e-10, 0.999643, 978242e-9, 0, 579365e-9, 0.99948, 104684e-8, 0, 182774e-8, 0.999255, 114012e-8, 0, 387804e-8, 0.998885, 126188e-8, 0, 675709e-8, 0.997405, 135888e-8, 0, 0.010468, 0.99424, 133626e-8, 0, 0.0150018, 0.992458, 140905e-8, 0, 0.0203443, 0.990929, 152305e-8, 0, 0.0264786, 0.989116, 165882e-8, 0, 0.0333875, 0.985624, 174128e-8, 0, 0.0410536, 0.982003, 182108e-8, 0, 0.0494609, 0.978336, 194498e-8, 0, 0.0585941, 0.973184, 202708e-8, 0, 0.0684396, 0.9678, 212166e-8, 0, 0.0789851, 0.961348, 221366e-8, 0, 0.0902199, 0.953841, 228219e-8, 0, 0.102134, 0.94534, 235662e-8, 0, 0.114721, 0.935552, 240572e-8, 0, 0.127972, 0.924064, 244405e-8, 0, 0.141884, 0.911827, 247557e-8, 0, 0.156451, 0.897731, 248374e-8, 0, 0.171672, 0.883409, 249863e-8, 0, 0.187545, 0.868625, 246688e-8, 0, 0.20407, 0.856529, 246523e-8, 0, 0.221249, 0.842999, 242368e-8, 0, 0.239083, 0.828505, 237354e-8, 0, 0.257578, 0.813825, 232588e-8, 0, 0.276738, 0.797813, 226731e-8, 0, 0.296569, 0.781097, 219704e-8, 0, 0.31708, 0.764038, 212394e-8, 0, 0.338281, 0.746067, 204786e-8, 0, 0.360181, 0.727687, 196728e-8, 0, 0.382794, 0.709571, 188779e-8, 0, 0.406133, 0.691503, 180532e-8, 0, 0.430213, 0.673673, 171849e-8, 0, 0.45505, 0.655732, 164147e-8, 0, 0.480662, 0.637399, 155858e-8, 0, 0.507065, 0.618616, 147641e-8, 0, 0.534278, 0.60005, 140125e-8, 0, 0.562313, 0.581713, 132441e-8, 0, 0.59118, 0.563546, 125014e-8, 0, 0.620875, 0.545605, 118249e-8, 0, 0.651373, 0.527559, 11116e-7, 0, 0.682593, 0.509764, 104979e-8, 0, 0.714286, 0.49193, 985977e-9, 0, 0.746032, 0.475011, 928592e-9, 0, 0.777778, 0.457878, 873466e-9, 0, 0.809524, 0.440979, 819585e-9, 0, 0.84127, 0.424613, 772365e-9, 0, 0.873016, 0.408549, 722195e-9, 0, 0.904762, 0.392771, 680014e-9, 0, 0.936508, 0.377317, 636797e-9, 0, 0.968254, 0.362352, 598318e-9, 0, 1, 1, 114313e-8, 0, 0, 1, 114314e-8, 0, 0, 0.999999, 114331e-8, 0, 0, 0.999998, 114404e-8, 0, 0, 0.999994, 114601e-8, 0, 0, 0.999984, 115019e-8, 0, 0, 0.999967, 115784e-8, 0, 0, 0.999937, 11706e-7, 0, 0, 0.999894, 119054e-8, 0, 0, 0.999828, 122031e-8, 0, 0, 0.999735, 126331e-8, 0, 169263e-9, 0.999606, 132382e-8, 0, 949167e-9, 0.999426, 14071e-7, 0, 249668e-8, 0.999173, 151895e-8, 0, 486392e-8, 0.99873, 166102e-8, 0, 806323e-8, 0.996243, 17023e-7, 0, 0.0120895, 0.993779, 172782e-8, 0, 0.0169288, 0.9919, 18108e-7, 0, 0.0225633, 0.990524, 196028e-8, 0, 0.028974, 0.98868, 212014e-8, 0, 0.036142, 0.984663, 217598e-8, 0, 0.044049, 0.981457, 230563e-8, 0, 0.0526781, 0.977608, 243966e-8, 0, 0.0620137, 0.972215, 251336e-8, 0, 0.0720418, 0.966798, 26285e-7, 0, 0.0827499, 0.960241, 271409e-8, 0, 0.0941271, 0.952489, 278381e-8, 0, 0.106164, 0.944127, 285399e-8, 0, 0.118852, 0.934282, 290994e-8, 0, 0.132185, 0.923271, 294558e-8, 0, 0.146157, 0.910803, 296269e-8, 0, 0.160766, 0.896705, 296803e-8, 0, 0.176007, 0.88238, 296637e-8, 0, 0.19188, 0.867116, 293163e-8, 0, 0.208385, 0.853636, 289418e-8, 0, 0.225523, 0.840469, 284663e-8, 0, 0.243296, 0.82639, 278594e-8, 0, 0.261709, 0.811759, 271618e-8, 0, 0.280767, 0.796113, 263187e-8, 0, 0.300476, 0.779518, 254589e-8, 0, 0.320845, 0.763142, 246003e-8, 0, 0.341883, 0.745464, 236529e-8, 0, 0.363601, 0.727491, 226536e-8, 0, 0.386011, 0.709414, 216375e-8, 0, 0.409128, 0.691396, 207127e-8, 0, 0.432967, 0.67368, 197106e-8, 0, 0.457545, 0.656049, 187022e-8, 0, 0.482881, 0.638188, 177605e-8, 0, 0.508992, 0.620177, 168482e-8, 0, 0.535899, 0.601506, 158909e-8, 0, 0.563619, 0.58362, 150583e-8, 0, 0.592165, 0.565496, 141791e-8, 0, 0.621544, 0.54789, 133693e-8, 0, 0.651743, 0.530323, 126038e-8, 0, 0.682709, 0.512795, 118556e-8, 0, 0.714286, 0.495199, 111527e-8, 0, 0.746032, 0.478101, 10489e-7, 0, 0.777778, 0.461511, 984264e-9, 0, 0.809524, 0.444879, 92591e-8, 0, 0.84127, 0.428424, 866582e-9, 0, 0.873016, 0.412495, 814463e-9, 0, 0.904762, 0.396975, 764498e-9, 0, 0.936508, 0.381614, 715967e-9, 0, 0.968254, 0.366732, 672483e-9, 0, 1, 1, 155501e-8, 0, 0, 1, 155503e-8, 0, 0, 1, 155524e-8, 0, 0, 0.999998, 155615e-8, 0, 0, 0.999994, 15586e-7, 0, 0, 0.999983, 156379e-8, 0, 0, 0.999963, 15733e-7, 0, 0, 0.999932, 158911e-8, 0, 0, 0.999882, 161376e-8, 0, 0, 0.99981, 165041e-8, 0, 100875e-10, 0.999708, 170304e-8, 0, 367658e-9, 0.999565, 177658e-8, 0, 14234e-7, 0.999368, 187688e-8, 0, 327939e-8, 0.999081, 200989e-8, 0, 596629e-8, 0.99852, 217177e-8, 0, 94852e-7, 0.99549, 21745e-7, 0, 0.013824, 0.993252, 222357e-8, 0, 0.0189642, 0.991727, 235022e-8, 0, 0.0248856, 0.989951, 250561e-8, 0, 0.0315669, 0.988029, 268829e-8, 0, 0.0389882, 0.984029, 27496e-7, 0, 0.0471302, 0.980683, 289793e-8, 0, 0.0559754, 0.976554, 303315e-8, 0, 0.0655081, 0.97139, 313257e-8, 0, 0.0757138, 0.965544, 323656e-8, 0, 0.08658, 0.95912, 333432e-8, 0, 0.0980954, 0.951183, 34039e-7, 0, 0.110251, 0.942974, 347515e-8, 0, 0.123038, 0.932642, 350381e-8, 0, 0.13645, 0.922158, 354519e-8, 0, 0.150482, 0.909404, 353851e-8, 0, 0.165129, 0.896071, 35435e-7, 0, 0.18039, 0.881206, 349936e-8, 0, 0.196263, 0.866077, 347256e-8, 0, 0.212748, 0.85093, 3415e-6, 0, 0.229847, 0.837703, 333367e-8, 0, 0.247561, 0.823878, 3249e-6, 0, 0.265895, 0.809449, 316347e-8, 0, 0.284854, 0.794379, 306351e-8, 0, 0.304445, 0.778138, 29499e-7, 0, 0.324675, 0.761997, 284099e-8, 0, 0.345555, 0.744938, 272104e-8, 0, 0.367095, 0.727212, 260715e-8, 0, 0.389309, 0.709549, 248855e-8, 0, 0.41221, 0.691704, 236783e-8, 0, 0.435814, 0.673689, 225178e-8, 0, 0.460138, 0.656453, 213765e-8, 0, 0.485203, 0.639128, 202178e-8, 0, 0.511028, 0.621512, 191443e-8, 0, 0.537634, 0.603598, 180977e-8, 0, 0.565041, 0.58559, 170456e-8, 0, 0.593268, 0.567852, 160927e-8, 0, 0.622327, 0.5503, 151395e-8, 0, 0.652217, 0.533033, 142499e-8, 0, 0.682907, 0.515942, 133955e-8, 0, 0.714296, 0.498814, 12602e-7, 0, 0.746032, 0.481595, 118188e-8, 0, 0.777778, 0.465117, 111171e-8, 0, 0.809524, 0.448865, 104091e-8, 0, 0.84127, 0.432711, 976618e-9, 0, 0.873016, 0.416822, 91859e-8, 0, 0.904762, 0.401272, 857704e-9, 0, 0.936508, 0.386226, 807172e-9, 0, 0.968254, 0.371321, 75464e-8, 0, 1, 1, 209596e-8, 0, 0, 1, 209598e-8, 0, 0, 1, 209624e-8, 0, 0, 0.999997, 209736e-8, 0, 0, 0.999991, 210039e-8, 0, 0, 0.999979, 210678e-8, 0, 0, 0.999959, 211847e-8, 0, 0, 0.999925, 21379e-7, 0, 0, 0.99987, 216809e-8, 0, 0, 0.999791, 221281e-8, 0, 681487e-10, 0.999677, 227669e-8, 0, 658161e-9, 0.999521, 236533e-8, 0, 200635e-8, 0.999301, 248514e-8, 0, 41779e-7, 0.998977, 264185e-8, 0, 718648e-8, 0.998191, 281695e-8, 0, 0.0110239, 0.994801, 278518e-8, 0, 0.015672, 0.993091, 288774e-8, 0, 0.0211091, 0.991571, 303931e-8, 0, 0.0273123, 0.9897, 321643e-8, 0, 0.034259, 0.987023, 337332e-8, 0, 0.0419282, 0.983289, 346146e-8, 0, 0.0502998, 0.979892, 363704e-8, 0, 0.0593562, 0.975111, 373601e-8, 0, 0.069081, 0.970351, 38842e-7, 0, 0.0794598, 0.964131, 397053e-8, 0, 0.0904798, 0.957747, 408078e-8, 0, 0.10213, 0.949536, 413533e-8, 0, 0.1144, 0.941372, 420305e-8, 0, 0.127284, 0.931049, 422815e-8, 0, 0.140772, 0.920647, 425048e-8, 0, 0.154862, 0.908033, 42281e-7, 0, 0.169548, 0.895028, 422026e-8, 0, 0.184828, 0.879968, 415042e-8, 0, 0.200701, 0.864875, 408821e-8, 0, 0.217167, 0.84918, 400909e-8, 0, 0.234227, 0.834934, 391178e-8, 0, 0.251884, 0.821397, 380066e-8, 0, 0.270141, 0.807135, 367974e-8, 0, 0.289004, 0.792363, 355172e-8, 0, 0.308479, 0.776661, 3411e-6, 0, 0.328575, 0.760705, 328123e-8, 0, 0.349301, 0.744408, 314003e-8, 0, 0.370668, 0.726994, 29906e-7, 0, 0.392689, 0.709598, 285034e-8, 0, 0.415379, 0.692112, 271179e-8, 0, 0.438754, 0.674435, 257185e-8, 0, 0.46283, 0.65676, 243425e-8, 0, 0.48763, 0.639982, 230351e-8, 0, 0.513173, 0.622983, 21777e-7, 0, 0.539482, 0.605471, 204991e-8, 0, 0.566579, 0.58796, 193759e-8, 0, 0.594488, 0.570463, 181976e-8, 0, 0.623226, 0.553058, 171497e-8, 0, 0.6528, 0.535894, 161109e-8, 0, 0.683198, 0.519089, 151394e-8, 0, 0.714354, 0.502454, 142122e-8, 0, 0.746032, 0.485681, 133488e-8, 0, 0.777778, 0.468935, 124975e-8, 0, 0.809524, 0.452951, 117309e-8, 0, 0.84127, 0.437139, 110155e-8, 0, 0.873016, 0.421446, 103124e-8, 0, 0.904762, 0.405951, 966387e-9, 0, 0.936508, 0.391003, 908119e-9, 0, 0.968254, 0.376198, 848057e-9, 0, 1, 1, 280076e-8, 0, 0, 1, 280078e-8, 0, 0, 0.999999, 280109e-8, 0, 0, 0.999997, 280246e-8, 0, 0, 0.999992, 280616e-8, 0, 0, 0.999979, 281396e-8, 0, 0, 0.999956, 282822e-8, 0, 0, 0.999916, 285186e-8, 0, 0, 0.999857, 28885e-7, 0, 0, 0.999768, 294259e-8, 0, 196026e-9, 0.999645, 301946e-8, 0, 104842e-8, 0.99947, 312541e-8, 0, 270199e-8, 0.999229, 326733e-8, 0, 519449e-8, 0.998852, 344992e-8, 0, 852602e-8, 0.997558, 361052e-8, 0, 0.0126804, 0.994417, 35898e-7, 0, 0.017635, 0.992824, 372393e-8, 0, 0.023365, 0.991344, 390695e-8, 0, 0.0298456, 0.989337, 410392e-8, 0, 0.0370529, 0.985811, 420987e-8, 0, 0.0449651, 0.982772, 437488e-8, 0, 0.0535615, 0.979001, 455069e-8, 0, 0.0628243, 0.974102, 464462e-8, 0, 0.0727368, 0.969197, 480577e-8, 0, 0.0832844, 0.962759, 487818e-8, 0, 0.0944545, 0.956207, 498176e-8, 0, 0.106236, 0.947909, 503392e-8, 0, 0.118619, 0.939596, 507474e-8, 0, 0.131595, 0.929642, 509798e-8, 0, 0.145159, 0.918807, 508476e-8, 0, 0.159305, 0.906921, 505634e-8, 0, 0.174028, 0.893312, 498845e-8, 0, 0.189327, 0.878933, 49133e-7, 0, 0.2052, 0.863986, 48259e-7, 0, 0.221647, 0.847936, 470848e-8, 0, 0.23867, 0.832253, 456889e-8, 0, 0.25627, 0.818619, 442726e-8, 0, 0.274453, 0.804788, 427677e-8, 0, 0.293222, 0.790241, 411906e-8, 0, 0.312585, 0.775162, 394833e-8, 0, 0.33255, 0.759463, 377366e-8, 0, 0.353126, 0.743598, 361026e-8, 0, 0.374324, 0.72697, 343627e-8, 0, 0.396158, 0.709646, 326422e-8, 0, 0.418641, 0.69277, 309717e-8, 0, 0.44179, 0.675371, 29356e-7, 0, 0.465624, 0.657863, 277712e-8, 0, 0.490163, 0.640772, 261738e-8, 0, 0.515429, 0.624441, 24737e-7, 0, 0.541445, 0.607497, 233125e-8, 0, 0.568236, 0.590438, 218994e-8, 0, 0.595828, 0.573224, 20664e-7, 0, 0.624242, 0.556168, 193526e-8, 0, 0.653496, 0.539232, 182463e-8, 0, 0.683588, 0.522352, 170735e-8, 0, 0.714482, 0.506172, 160555e-8, 0, 0.746032, 0.489842, 150451e-8, 0, 0.777778, 0.473463, 140938e-8, 0, 0.809524, 0.457266, 132568e-8, 0, 0.84127, 0.441609, 12376e-7, 0, 0.873016, 0.426348, 116265e-8, 0, 0.904762, 0.411002, 108935e-8, 0, 0.936508, 0.396045, 101946e-8, 0, 0.968254, 0.381448, 955665e-9, 0, 1, 1, 37121e-7, 0, 0, 1, 371213e-8, 0, 0, 1, 371251e-8, 0, 0, 0.999997, 371417e-8, 0, 0, 0.99999, 371863e-8, 0, 0, 0.999977, 372807e-8, 0, 0, 0.99995, 374529e-8, 0, 0, 0.999908, 37738e-7, 0, 0, 0.999843, 381789e-8, 0, 123596e-10, 0.999745, 388273e-8, 0, 407442e-9, 0.999608, 397443e-8, 0, 15447e-7, 0.999415, 409998e-8, 0, 351385e-8, 0.999143, 426662e-8, 0, 63316e-7, 0.9987, 447625e-8, 0, 998679e-8, 0.996363, 455323e-8, 0, 0.0144569, 0.994021, 461052e-8, 0, 0.0197151, 0.992372, 476359e-8, 0, 0.0257344, 0.991007, 499101e-8, 0, 0.0324882, 0.988767, 51972e-7, 0, 0.0399517, 0.984872, 528407e-8, 0, 0.0481022, 0.982004, 548926e-8, 0, 0.0569191, 0.977714, 564385e-8, 0, 0.0663839, 0.973076, 57693e-7, 0, 0.0764801, 0.967565, 58924e-7, 0, 0.0871928, 0.961384, 599629e-8, 0, 0.0985095, 0.954435, 605998e-8, 0, 0.110419, 0.946303, 61133e-7, 0, 0.122912, 0.937662, 612028e-8, 0, 0.13598, 0.927867, 612209e-8, 0, 0.149617, 0.916475, 604813e-8, 0, 0.163817, 0.90541, 603088e-8, 0, 0.178577, 0.891591, 592218e-8, 0, 0.193894, 0.877573, 578854e-8, 0, 0.209767, 0.862511, 566648e-8, 0, 0.226196, 0.846861, 551481e-8, 0, 0.243182, 0.83068, 533754e-8, 0, 0.260728, 0.815725, 515487e-8, 0, 0.278837, 0.802321, 49655e-7, 0, 0.297515, 0.787826, 475421e-8, 0, 0.316768, 0.773454, 456002e-8, 0, 0.336605, 0.758224, 434727e-8, 0, 0.357034, 0.74265, 414444e-8, 0, 0.378067, 0.726729, 393738e-8, 0, 0.399717, 0.710155, 373575e-8, 0, 0.421998, 0.693312, 353736e-8, 0, 0.444928, 0.67653, 334368e-8, 0, 0.468523, 0.659444, 315981e-8, 0, 0.492806, 0.642051, 297809e-8, 0, 0.517798, 0.625758, 280592e-8, 0, 0.543525, 0.609615, 264254e-8, 0, 0.570012, 0.592919, 248459e-8, 0, 0.597288, 0.576298, 233327e-8, 0, 0.625379, 0.559489, 219519e-8, 0, 0.654307, 0.542891, 205441e-8, 0, 0.684084, 0.526255, 193385e-8, 0, 0.714693, 0.509853, 180745e-8, 0, 0.746044, 0.494131, 169817e-8, 0, 0.777778, 0.478114, 15913e-7, 0, 0.809524, 0.462274, 148981e-8, 0, 0.84127, 0.446412, 139537e-8, 0, 0.873016, 0.431274, 130984e-8, 0, 0.904762, 0.41635, 122403e-8, 0, 0.936508, 0.401476, 114809e-8, 0, 0.968254, 0.386993, 107563e-8, 0, 1, 1, 488216e-8, 0, 0, 1, 48822e-7, 0, 0, 1, 488265e-8, 0, 0, 0.999997, 488463e-8, 0, 0, 0.999988, 488999e-8, 0, 0, 0.999974, 490129e-8, 0, 0, 0.999946, 492191e-8, 0, 0, 0.999897, 495598e-8, 0, 0, 0.999825, 500855e-8, 0, 744791e-10, 0.999718, 508559e-8, 0, 712744e-9, 0.999565, 5194e-6, 0, 215249e-8, 0.999352, 534147e-8, 0, 444576e-8, 0.999046, 553523e-8, 0, 759218e-8, 0.998492, 577016e-8, 0, 0.0115714, 0.995564, 578487e-8, 0, 0.0163557, 0.993339, 586414e-8, 0, 0.021915, 0.991834, 606002e-8, 0, 0.0282201, 0.990496, 633312e-8, 0, 0.0352433, 0.987826, 651941e-8, 0, 0.042959, 0.98383, 660842e-8, 0, 0.0513439, 0.98109, 685523e-8, 0, 0.0603772, 0.976131, 695778e-8, 0, 0.0700402, 0.971922, 714236e-8, 0, 0.0803163, 0.965901, 721437e-8, 0, 0.0911908, 0.959606, 732017e-8, 0, 0.102651, 0.952504, 735788e-8, 0, 0.114686, 0.944365, 738493e-8, 0, 0.127286, 0.935652, 737969e-8, 0, 0.140443, 0.925813, 733612e-8, 0, 0.154151, 0.914397, 723094e-8, 0, 0.168405, 0.903257, 714002e-8, 0, 0.183201, 0.890015, 700149e-8, 0, 0.198536, 0.876014, 682813e-8, 0, 0.214409, 0.861436, 665567e-8, 0, 0.23082, 0.845752, 644526e-8, 0, 0.24777, 0.829169, 621635e-8, 0, 0.265263, 0.813435, 597789e-8, 0, 0.283301, 0.799701, 575694e-8, 0, 0.301889, 0.785726, 549866e-8, 0, 0.321035, 0.77152, 52503e-7, 0, 0.340746, 0.75683, 499619e-8, 0, 0.361032, 0.741951, 47543e-7, 0, 0.381904, 0.726367, 45084e-7, 0, 0.403374, 0.710537, 426784e-8, 0, 0.425457, 0.693965, 403487e-8, 0, 0.448169, 0.677724, 38075e-7, 0, 0.47153, 0.66117, 359431e-8, 0, 0.495561, 0.644274, 338354e-8, 0, 0.520284, 0.627449, 318163e-8, 0, 0.545725, 0.611645, 299672e-8, 0, 0.571911, 0.595614, 281016e-8, 0, 0.598873, 0.579426, 264252e-8, 0, 0.62664, 0.563016, 247509e-8, 0, 0.655239, 0.546728, 232647e-8, 0, 0.684692, 0.530539, 217803e-8, 0, 0.714999, 0.514164, 204216e-8, 0, 0.746106, 0.498344, 191403e-8, 0, 0.777778, 0.482957, 179203e-8, 0, 0.809524, 0.467336, 167695e-8, 0, 0.84127, 0.451994, 157567e-8, 0, 0.873016, 0.436514, 147113e-8, 0, 0.904762, 0.42178, 138034e-8, 0, 0.936508, 0.407271, 129219e-8, 0, 0.968254, 0.392822, 12098e-7, 0, 1, 1, 637427e-8, 0, 0, 1, 637431e-8, 0, 0, 0.999999, 637485e-8, 0, 0, 0.999996, 637721e-8, 0, 0, 0.999987, 638357e-8, 0, 0, 0.999971, 6397e-6, 0, 0, 0.999939, 642142e-8, 0, 0, 0.999888, 646177e-8, 0, 0, 0.999807, 652387e-8, 0, 207916e-9, 0.999689, 661454e-8, 0, 112051e-8, 0.99952, 674155e-8, 0, 287719e-8, 0.999283, 691313e-8, 0, 550145e-8, 0.998936, 713598e-8, 0, 897928e-8, 0.998165, 738501e-8, 0, 0.0132829, 0.994847, 734388e-8, 0, 0.01838, 0.993182, 749991e-8, 0, 0.0242381, 0.991665, 77246e-7, 0, 0.030826, 0.989708, 797579e-8, 0, 0.0381152, 0.986663, 813011e-8, 0, 0.0460794, 0.983288, 830365e-8, 0, 0.0546951, 0.980104, 853496e-8, 0, 0.0639411, 0.974855, 861045e-8, 0, 0.0737988, 0.97045, 879133e-8, 0, 0.0842516, 0.964509, 886377e-8, 0, 0.0952848, 0.957594, 890346e-8, 0, 0.106886, 0.950546, 893289e-8, 0, 0.119044, 0.942225, 890074e-8, 0, 0.131749, 0.933365, 886826e-8, 0, 0.144994, 0.923202, 87316e-7, 0, 0.158772, 0.912605, 863082e-8, 0, 0.173078, 0.901099, 847403e-8, 0, 0.187908, 0.888177, 825838e-8, 0, 0.203261, 0.873955, 801834e-8, 0, 0.219134, 0.860091, 779026e-8, 0, 0.235527, 0.84434, 752478e-8, 0, 0.252443, 0.828517, 724074e-8, 0, 0.269883, 0.81239, 693769e-8, 0, 0.287851, 0.79721, 664817e-8, 0, 0.306352, 0.783489, 634763e-8, 0, 0.325393, 0.769514, 604221e-8, 0, 0.344981, 0.755419, 573568e-8, 0, 0.365126, 0.741083, 544359e-8, 0, 0.385839, 0.726059, 515515e-8, 0, 0.407132, 0.710809, 487139e-8, 0, 0.42902, 0.695052, 459846e-8, 0, 0.45152, 0.678886, 433412e-8, 0, 0.474651, 0.663042, 407981e-8, 0, 0.498433, 0.646634, 384264e-8, 0, 0.52289, 0.630117, 360897e-8, 0, 0.548048, 0.613804, 338863e-8, 0, 0.573936, 0.598338, 318486e-8, 0, 0.600584, 0.582687, 298377e-8, 0, 0.628027, 0.566809, 280082e-8, 0, 0.656295, 0.550817, 262255e-8, 0, 0.685417, 0.534937, 245835e-8, 0, 0.715406, 0.519151, 230574e-8, 0, 0.74624, 0.503118, 21549e-7, 0, 0.777778, 0.487723, 202008e-8, 0, 0.809524, 0.472725, 189355e-8, 0, 0.84127, 0.457599, 177108e-8, 0, 0.873016, 0.442558, 165843e-8, 0, 0.904762, 0.427624, 155494e-8, 0, 0.936508, 0.413171, 145273e-8, 0, 0.968254, 0.399122, 136454e-8, 0, 1, 1, 826496e-8, 0, 0, 1, 826499e-8, 0, 0, 1, 826564e-8, 0, 0, 0.999996, 826842e-8, 0, 0, 0.999987, 827589e-8, 0, 0, 0.999967, 829167e-8, 0, 0, 0.999933, 832037e-8, 0, 0, 0.999876, 836768e-8, 0, 109338e-10, 0.999786, 844031e-8, 0, 427145e-9, 0.999655, 854603e-8, 0, 16384e-7, 0.999468, 869337e-8, 0, 372392e-8, 0.999203, 8891e-6, 0, 668513e-8, 0.998803, 914387e-8, 0, 0.0104968, 0.99748, 935838e-8, 0, 0.015125, 0.994446, 933309e-8, 0, 0.0205338, 0.99292, 953084e-8, 0, 0.0266884, 0.991414, 97893e-7, 0, 0.0335565, 0.989049, 0.0100228, 0, 0.0411086, 0.98582, 0.0101664, 0, 0.0493181, 0.982441, 0.0103582, 0, 0.0581613, 0.978595, 0.0105292, 0, 0.0676169, 0.973495, 0.0106274, 0, 0.0776661, 0.968405, 0.0107261, 0, 0.0882926, 0.962717, 0.0108234, 0, 0.0994817, 0.955478, 0.0108102, 0, 0.111221, 0.948275, 0.0107914, 0, 0.123499, 0.940006, 0.0107161, 0, 0.136308, 0.930831, 0.0106309, 0, 0.149639, 0.920648, 0.0104083, 0, 0.163485, 0.910205, 0.0102312, 0, 0.177843, 0.898445, 0.0100051, 0, 0.192707, 0.885986, 971928e-8, 0, 0.208077, 0.872204, 940747e-8, 0, 0.22395, 0.858436, 91085e-7, 0, 0.240326, 0.843454, 876595e-8, 0, 0.257208, 0.827437, 839794e-8, 0, 0.274596, 0.811488, 803692e-8, 0, 0.292496, 0.796039, 767352e-8, 0, 0.310911, 0.781083, 73097e-7, 0, 0.329849, 0.767642, 694032e-8, 0, 0.349316, 0.753901, 657476e-8, 0, 0.369323, 0.740131, 622699e-8, 0, 0.38988, 0.725845, 58838e-7, 0, 0.410999, 0.710991, 555586e-8, 0, 0.432696, 0.696002, 523089e-8, 0, 0.454987, 0.680461, 492494e-8, 0, 0.47789, 0.664875, 463464e-8, 0, 0.501426, 0.649273, 435422e-8, 0, 0.52562, 0.63302, 40875e-7, 0, 0.550498, 0.61705, 384075e-8, 0, 0.576089, 0.601154, 359557e-8, 0, 0.602427, 0.586008, 337636e-8, 0, 0.629544, 0.570699, 316019e-8, 0, 0.657479, 0.555166, 296033e-8, 0, 0.686264, 0.539645, 277552e-8, 0, 0.715924, 0.524159, 259499e-8, 0, 0.746459, 0.508682, 243257e-8, 0, 0.777789, 0.493163, 227851e-8, 0, 0.809524, 0.478004, 213083e-8, 0, 0.84127, 0.46347, 199502e-8, 0, 0.873016, 0.448778, 186967e-8, 0, 0.904762, 0.434105, 174732e-8, 0, 0.936508, 0.419576, 163861e-8, 0, 0.968254, 0.405541, 153341e-8, 0, 1, 1, 0.0106462, 0, 0, 1, 0.0106462, 0, 0, 0.999999, 0.010647, 0, 0, 0.999995, 0.0106502, 0, 0, 0.999985, 0.0106589, 0, 0, 0.999964, 0.0106773, 0, 0, 0.999925, 0.0107106, 0, 0, 0.999861, 0.0107655, 0, 712986e-10, 0.999763, 0.0108497, 0, 743959e-9, 0.999616, 0.0109716, 0, 227361e-8, 0.999408, 0.0111408, 0, 46983e-7, 0.999112, 0.0113659, 0, 800158e-8, 0.998637, 0.0116475, 0, 0.0121493, 0.996223, 0.0117231, 0, 0.0171023, 0.994006, 0.0118064, 0, 0.0228218, 0.992444, 0.0120254, 0, 0.0292711, 0.991028, 0.0123314, 0, 0.036417, 0.98803, 0.0124954, 0, 0.0442295, 0.984816, 0.0126538, 0, 0.0526815, 0.981399, 0.0128537, 0, 0.0617492, 0.977085, 0.0129694, 0, 0.0714114, 0.972154, 0.013091, 0, 0.0816495, 0.966617, 0.0131166, 0, 0.0924472, 0.960628, 0.0131583, 0, 0.10379, 0.953295, 0.0131094, 0, 0.115665, 0.94575, 0.0129966, 0, 0.128062, 0.937654, 0.0128796, 0, 0.140972, 0.927716, 0.0126477, 0, 0.154387, 0.917932, 0.0123889, 0, 0.168301, 0.907719, 0.012131, 0, 0.182709, 0.89584, 0.0118013, 0, 0.197608, 0.883526, 0.0114145, 0, 0.212994, 0.870301, 0.0110075, 0, 0.228867, 0.856272, 0.0106019, 0, 0.245227, 0.842251, 0.0101938, 0, 0.262074, 0.826466, 973254e-8, 0, 0.279412, 0.810859, 92846e-7, 0, 0.297244, 0.795051, 883304e-8, 0, 0.315575, 0.780053, 840272e-8, 0, 0.334412, 0.76575, 796438e-8, 0, 0.35376, 0.752298, 752526e-8, 0, 0.373631, 0.739153, 711486e-8, 0, 0.394034, 0.725514, 670361e-8, 0, 0.414983, 0.711473, 632656e-8, 0, 0.436491, 0.696936, 595206e-8, 0, 0.458575, 0.682126, 559191e-8, 0, 0.481253, 0.667027, 525362e-8, 0, 0.504547, 0.651875, 493805e-8, 0, 0.528481, 0.636463, 462848e-8, 0, 0.553081, 0.620641, 433936e-8, 0, 0.578377, 0.604931, 407e-5, 0, 0.604404, 0.589549, 380864e-8, 0, 0.631197, 0.574712, 357049e-8, 0, 0.658795, 0.559775, 334466e-8, 0, 0.687238, 0.544514, 312505e-8, 0, 0.716559, 0.529555, 293199e-8, 0, 0.746776, 0.514402, 274204e-8, 0, 0.777849, 0.499302, 256647e-8, 0, 0.809524, 0.484114, 239901e-8, 0, 0.84127, 0.469308, 225148e-8, 0, 0.873016, 0.455133, 210178e-8, 0, 0.904762, 0.440939, 19727e-7, 0, 0.936508, 0.426627, 184382e-8, 0, 0.968254, 0.412509, 172548e-8, 0, 1, 1, 0.013628, 0, 0, 1, 0.0136281, 0, 0, 0.999999, 0.0136289, 0, 0, 0.999995, 0.0136327, 0, 0, 0.999983, 0.0136427, 0, 0, 0.99996, 0.0136638, 0, 0, 0.999917, 0.0137022, 0, 0, 0.999846, 0.0137652, 0, 204597e-9, 0.999736, 0.0138615, 0, 116837e-8, 0.999573, 0.0140007, 0, 303325e-8, 0.99934, 0.0141927, 0, 580613e-8, 0.999004, 0.0144457, 0, 945626e-8, 0.998407, 0.0147489, 0, 0.0139421, 0.995464, 0.014731, 0, 0.0192202, 0.993328, 0.0148283, 0, 0.0252495, 0.991799, 0.0150797, 0, 0.0319921, 0.990397, 0.0154316, 0, 0.0394138, 0.986835, 0.0155005, 0, 0.0474843, 0.983938, 0.0157308, 0, 0.0561763, 0.980154, 0.0158753, 0, 0.0654661, 0.975659, 0.0159581, 0, 0.0753326, 0.970171, 0.0159832, 0, 0.0857571, 0.964803, 0.0160084, 0, 0.0967236, 0.958366, 0.0159484, 0, 0.108218, 0.950613, 0.0158001, 0, 0.120227, 0.942874, 0.0155845, 0, 0.132741, 0.935005, 0.0154292, 0, 0.145751, 0.924991, 0.0150742, 0, 0.159249, 0.914814, 0.0146757, 0, 0.17323, 0.904743, 0.0143097, 0, 0.187687, 0.893216, 0.0138695, 0, 0.202619, 0.880769, 0.0133706, 0, 0.218021, 0.868136, 0.0128606, 0, 0.233894, 0.85469, 0.0123403, 0, 0.250238, 0.840593, 0.0118091, 0, 0.267052, 0.825808, 0.011253, 0, 0.284341, 0.81009, 0.0107099, 0, 0.302106, 0.79504, 0.0101636, 0, 0.320354, 0.779757, 964041e-8, 0, 0.33909, 0.764697, 911896e-8, 0, 0.358322, 0.750913, 859533e-8, 0, 0.378059, 0.738175, 811592e-8, 0, 0.398311, 0.725242, 764504e-8, 0, 0.41909, 0.711864, 718885e-8, 0, 0.440412, 0.698009, 675843e-8, 0, 0.462292, 0.683841, 634984e-8, 0, 0.484748, 0.669391, 595502e-8, 0, 0.507802, 0.654731, 558671e-8, 0, 0.531477, 0.639805, 523578e-8, 0, 0.555802, 0.624789, 490834e-8, 0, 0.580805, 0.609325, 459448e-8, 0, 0.606522, 0.593975, 430342e-8, 0, 0.63299, 0.578983, 403019e-8, 0, 0.66025, 0.564442, 37707e-7, 0, 0.688346, 0.549835, 35316e-7, 0, 0.717319, 0.535039, 330255e-8, 0, 0.7472, 0.520403, 308932e-8, 0, 0.777982, 0.505687, 289335e-8, 0, 0.809524, 0.490939, 270818e-8, 0, 0.84127, 0.476233, 25343e-7, 0, 0.873016, 0.461624, 237097e-8, 0, 0.904762, 0.447833, 222065e-8, 0, 0.936508, 0.433992, 207561e-8, 0, 0.968254, 0.420147, 194955e-8, 0, 1, 1, 0.0173415, 0, 0, 1, 0.0173416, 0, 0, 0.999999, 0.0173426, 0, 0, 0.999995, 0.0173468, 0, 0, 0.999983, 0.0173582, 0, 0, 0.999954, 0.0173822, 0, 0, 0.999908, 0.0174258, 0, 669501e-11, 0.999828, 0.0174973, 0, 427399e-9, 0.999705, 0.0176063, 0, 171019e-8, 0.999524, 0.0177631, 0, 39248e-7, 0.999263, 0.0179781, 0, 705382e-8, 0.998878, 0.018258, 0, 0.0110552, 0.998012, 0.0185551, 0, 0.0158812, 0.994614, 0.0184264, 0, 0.0214852, 0.993132, 0.0186385, 0, 0.0278239, 0.991563, 0.0189067, 0, 0.0348585, 0.989298, 0.0191577, 0, 0.0425544, 0.986036, 0.0192522, 0, 0.050881, 0.982558, 0.0194063, 0, 0.059811, 0.978531, 0.019486, 0, 0.0693209, 0.974198, 0.0195847, 0, 0.0793895, 0.968148, 0.0194749, 0, 0.0899984, 0.962565, 0.0194277, 0, 0.101132, 0.956041, 0.0192991, 0, 0.112775, 0.947749, 0.0189893, 0, 0.124917, 0.94018, 0.018704, 0, 0.137547, 0.93165, 0.0183458, 0, 0.150655, 0.921798, 0.0178775, 0, 0.164236, 0.911573, 0.0173618, 0, 0.178281, 0.901569, 0.0168482, 0, 0.192788, 0.890341, 0.016265, 0, 0.207752, 0.877835, 0.0156199, 0, 0.223171, 0.865472, 0.0149516, 0, 0.239044, 0.852905, 0.0143274, 0, 0.255371, 0.838906, 0.0136643, 0, 0.272153, 0.824888, 0.0129903, 0, 0.289393, 0.809977, 0.0123218, 0, 0.307093, 0.794697, 0.0116572, 0, 0.325259, 0.780028, 0.0110307, 0, 0.343896, 0.765124, 0.0104236, 0, 0.363012, 0.750411, 98219e-7, 0, 0.382617, 0.737264, 924397e-8, 0, 0.402719, 0.724799, 868719e-8, 0, 0.423332, 0.712253, 816476e-8, 0, 0.444469, 0.699267, 767262e-8, 0, 0.466146, 0.685618, 719746e-8, 0, 0.488383, 0.671736, 673916e-8, 0, 0.511199, 0.657777, 631937e-8, 0, 0.534618, 0.643497, 592411e-8, 0, 0.558668, 0.62889, 553928e-8, 0, 0.58338, 0.614299, 51934e-7, 0, 0.608787, 0.599197, 485985e-8, 0, 0.634929, 0.584175, 454357e-8, 0, 0.661849, 0.569541, 425787e-8, 0, 0.689594, 0.555193, 397905e-8, 0, 0.718211, 0.540947, 372364e-8, 0, 0.747742, 0.526593, 348599e-8, 0, 0.778205, 0.512335, 326103e-8, 0, 0.80953, 0.498017, 305137e-8, 0, 0.84127, 0.483609, 285485e-8, 0, 0.873016, 0.469368, 267472e-8, 0, 0.904762, 0.455037, 249945e-8, 0, 0.936508, 0.441493, 234792e-8, 0, 0.968254, 0.428147, 219936e-8, 0, 1, 1, 0.0219422, 0, 0, 1, 0.0219423, 0, 0, 0.999998, 0.0219434, 0, 0, 0.999993, 0.0219481, 0, 0, 0.999981, 0.021961, 0, 0, 0.999949, 0.0219879, 0, 0, 0.999896, 0.0220367, 0, 593194e-10, 0.999808, 0.0221167, 0, 75364e-8, 0.99967, 0.0222383, 0, 237884e-8, 0.999466, 0.0224125, 0, 495612e-8, 0.999174, 0.0226495, 0, 844887e-8, 0.998725, 0.0229525, 0, 0.0128058, 0.996979, 0.0231123, 0, 0.0179742, 0.994317, 0.0230742, 0, 0.0239047, 0.992781, 0.0232895, 0, 0.0305526, 0.991191, 0.0235734, 0, 0.0378786, 0.987787, 0.0236152, 0, 0.0458475, 0.985092, 0.0237994, 0, 0.0544287, 0.981121, 0.0238553, 0, 0.0635952, 0.976924, 0.0238706, 0, 0.0733233, 0.97218, 0.0238704, 0, 0.0835922, 0.965956, 0.0236598, 0, 0.0943839, 0.959998, 0.0234735, 0, 0.105682, 0.953245, 0.0232277, 0, 0.117474, 0.944445, 0.0226973, 0, 0.129747, 0.937087, 0.0223527, 0, 0.142491, 0.928341, 0.0218144, 0, 0.155697, 0.9184, 0.0211516, 0, 0.169358, 0.907959, 0.0204553, 0, 0.183469, 0.89808, 0.0197673, 0, 0.198024, 0.887047, 0.0189915, 0, 0.21302, 0.875221, 0.0182082, 0, 0.228455, 0.86269, 0.0173584, 0, 0.244329, 0.850735, 0.0165718, 0, 0.260639, 0.837545, 0.0157524, 0, 0.277389, 0.823639, 0.0149482, 0, 0.29458, 0.809699, 0.0141431, 0, 0.312216, 0.794797, 0.0133527, 0, 0.3303, 0.780578, 0.0126193, 0, 0.34884, 0.766019, 0.0118914, 0, 0.367842, 0.751447, 0.0111839, 0, 0.387315, 0.737275, 0.010514, 0, 0.40727, 0.724545, 987277e-8, 0, 0.427717, 0.712644, 926569e-8, 0, 0.448671, 0.700432, 869029e-8, 0, 0.470149, 0.687664, 814691e-8, 0, 0.492167, 0.674288, 763012e-8, 0, 0.514746, 0.660966, 714437e-8, 0, 0.537911, 0.647264, 668457e-8, 0, 0.561688, 0.633431, 626581e-8, 0, 0.586108, 0.619133, 585593e-8, 0, 0.611206, 0.604935, 548188e-8, 0, 0.637022, 0.590236, 513288e-8, 0, 0.663599, 0.575473, 47906e-7, 0, 0.690989, 0.561228, 448895e-8, 0, 0.719242, 0.547054, 420233e-8, 0, 0.748411, 0.533175, 392869e-8, 0, 0.778531, 0.519163, 367445e-8, 0, 0.809583, 0.505328, 344097e-8, 0, 0.84127, 0.491446, 322003e-8, 0, 0.873016, 0.477356, 301283e-8, 0, 0.904762, 0.46356, 282592e-8, 0, 0.936508, 0.449623, 264956e-8, 0, 0.968254, 0.436068, 246956e-8, 0, 1, 1, 0.0276135, 0, 0, 1, 0.0276136, 0, 0, 0.999998, 0.0276148, 0, 0, 0.999993, 0.0276201, 0, 0, 0.999976, 0.0276342, 0, 0, 0.999945, 0.027664, 0, 0, 0.999884, 0.0277179, 0, 18679e-8, 0.999784, 0.027806, 0, 119607e-8, 0.99963, 0.0279394, 0, 318407e-8, 0.999401, 0.0281295, 0, 613601e-8, 0.999066, 0.0283858, 0, 999963e-8, 0.998524, 0.0287027, 0, 0.0147164, 0.995702, 0.0286256, 0, 0.0202295, 0.993593, 0.0286733, 0, 0.0264876, 0.992067, 0.0288989, 0, 0.0334452, 0.990548, 0.0292135, 0, 0.0410621, 0.986775, 0.0291296, 0, 0.0493032, 0.984054, 0.0293099, 0, 0.0581381, 0.979481, 0.0291881, 0, 0.0675397, 0.975297, 0.0291598, 0, 0.0774848, 0.96981, 0.028954, 0, 0.0879528, 0.963524, 0.028628, 0, 0.0989258, 0.957398, 0.0283135, 0, 0.110388, 0.950088, 0.0278469, 0, 0.122327, 0.941538, 0.0271798, 0, 0.134729, 0.933332, 0.0265388, 0, 0.147587, 0.924392, 0.0257776, 0, 0.160889, 0.914581, 0.024916, 0, 0.174631, 0.904347, 0.0240242, 0, 0.188806, 0.894324, 0.0231229, 0, 0.203409, 0.883724, 0.022153, 0, 0.218437, 0.872207, 0.0211355, 0, 0.233888, 0.859927, 0.0201048, 0, 0.249761, 0.848373, 0.0191263, 0, 0.266056, 0.836023, 0.0181306, 0, 0.282774, 0.82289, 0.0171718, 0, 0.299917, 0.809324, 0.0162196, 0, 0.317488, 0.795361, 0.0152622, 0, 0.335493, 0.781253, 0.01439, 0, 0.353936, 0.767338, 0.013533, 0, 0.372825, 0.753156, 0.0127244, 0, 0.392168, 0.739122, 0.0119454, 0, 0.411976, 0.725358, 0.0112054, 0, 0.432259, 0.712949, 0.010487, 0, 0.453032, 0.701621, 984032e-8, 0, 0.47431, 0.689703, 921495e-8, 0, 0.496111, 0.677216, 862492e-8, 0, 0.518456, 0.664217, 806882e-8, 0, 0.541367, 0.65137, 755922e-8, 0, 0.564872, 0.638, 705705e-8, 0, 0.589001, 0.62453, 661266e-8, 0, 0.613789, 0.610601, 618432e-8, 0, 0.639277, 0.59676, 578033e-8, 0, 0.66551, 0.582433, 540927e-8, 0, 0.692539, 0.568026, 506104e-8, 0, 0.720422, 0.55414, 47353e-7, 0, 0.749216, 0.540178, 442889e-8, 0, 0.778974, 0.526513, 414363e-8, 0, 0.809711, 0.512954, 388237e-8, 0, 0.84127, 0.499403, 362875e-8, 0, 0.873016, 0.486026, 340827e-8, 0, 0.904762, 0.472345, 318598e-8, 0, 0.936508, 0.458828, 297635e-8, 0, 0.968254, 0.445379, 279447e-8, 0, 1, 1, 0.0345716, 0, 0, 1, 0.0345717, 0, 0, 0.999999, 0.034573, 0, 0, 0.999991, 0.0345787, 0, 0, 0.999974, 0.0345941, 0, 0, 0.999937, 0.0346263, 0, 188589e-11, 0.999869, 0.0346847, 0, 409238e-9, 0.999757, 0.0347798, 0, 17674e-7, 0.999582, 0.0349233, 0, 413658e-8, 0.999322, 0.0351265, 0, 747408e-8, 0.998939, 0.0353967, 0, 0.0117157, 0.998219, 0.0357018, 0, 0.0167966, 0.994974, 0.0354726, 0, 0.0226572, 0.993201, 0.0355621, 0, 0.0292445, 0.991573, 0.0357641, 0, 0.0365123, 0.989301, 0.0359252, 0, 0.0444203, 0.985712, 0.0358017, 0, 0.0529334, 0.982411, 0.0358353, 0, 0.0620214, 0.977827, 0.035617, 0, 0.0716574, 0.973278, 0.0354398, 0, 0.0818186, 0.967397, 0.0350483, 0, 0.0924846, 0.960696, 0.0344795, 0, 0.103638, 0.954349, 0.0339861, 0, 0.115263, 0.946066, 0.0331323, 0, 0.127348, 0.938012, 0.032359, 0, 0.13988, 0.929413, 0.0314413, 0, 0.152849, 0.920355, 0.0304103, 0, 0.166248, 0.910586, 0.0292785, 0, 0.18007, 0.900609, 0.0281391, 0, 0.194308, 0.890093, 0.0269103, 0, 0.208958, 0.880013, 0.0257269, 0, 0.224018, 0.869001, 0.0244671, 0, 0.239485, 0.85751, 0.0232252, 0, 0.255359, 0.84582, 0.0220117, 0, 0.271638, 0.834383, 0.0208274, 0, 0.288324, 0.822158, 0.0196628, 0, 0.305419, 0.809056, 0.0185306, 0, 0.322927, 0.795832, 0.0174174, 0, 0.340851, 0.782547, 0.0163758, 0, 0.359199, 0.7689, 0.015391, 0, 0.377975, 0.755526, 0.0144488, 0, 0.397189, 0.741681, 0.0135372, 0, 0.416851, 0.728178, 0.0126957, 0, 0.436971, 0.714642, 0.0118812, 0, 0.457564, 0.702756, 0.0111165, 0, 0.478644, 0.69175, 0.0104145, 0, 0.500229, 0.680159, 974439e-8, 0, 0.522339, 0.668073, 911926e-8, 0, 0.544997, 0.655405, 851393e-8, 0, 0.56823, 0.642921, 797637e-8, 0, 0.592068, 0.629993, 745119e-8, 0, 0.616546, 0.616828, 696972e-8, 0, 0.641705, 0.603305, 652425e-8, 0, 0.66759, 0.589833, 610188e-8, 0, 0.694255, 0.575945, 570834e-8, 0, 0.72176, 0.561745, 533384e-8, 0, 0.750168, 0.548277, 500001e-8, 0, 0.779545, 0.534467, 467582e-8, 0, 0.809933, 0.521032, 438092e-8, 0, 0.841272, 0.507877, 410348e-8, 0, 0.873016, 0.494654, 383618e-8, 0, 0.904762, 0.481592, 358699e-8, 0, 0.936508, 0.468509, 337281e-8, 0, 0.968254, 0.455293, 316196e-8, 0, 1, 1, 0.0430698, 0, 0, 1, 0.0430699, 0, 0, 0.999998, 0.0430713, 0, 0, 0.999991, 0.0430773, 0, 0, 0.99997, 0.0430936, 0, 0, 0.999928, 0.0431277, 0, 406396e-10, 0.999852, 0.0431893, 0, 744376e-9, 0.999724, 0.0432895, 0, 24806e-7, 0.999527, 0.0434397, 0, 524779e-8, 0.99923, 0.0436507, 0, 898164e-8, 0.998783, 0.0439255, 0, 0.0136083, 0.997507, 0.0441104, 0, 0.0190582, 0.994418, 0.0438225, 0, 0.0252694, 0.992864, 0.0439396, 0, 0.0321879, 0.991127, 0.0440962, 0, 0.039767, 0.987331, 0.0438408, 0, 0.0479667, 0.984819, 0.0438991, 0, 0.056752, 0.980384, 0.0435906, 0, 0.0660929, 0.975846, 0.0432543, 0, 0.075963, 0.970748, 0.0428293, 0, 0.0863398, 0.964303, 0.042153, 0, 0.0972035, 0.95772, 0.0414111, 0, 0.108537, 0.950747, 0.0405893, 0, 0.120325, 0.942533, 0.0394887, 0, 0.132554, 0.934045, 0.0383544, 0, 0.145215, 0.924942, 0.037057, 0, 0.158296, 0.915811, 0.0356993, 0, 0.17179, 0.90612, 0.0342401, 0, 0.185691, 0.896434, 0.0328078, 0, 0.199993, 0.886021, 0.031288, 0, 0.214691, 0.876081, 0.0297776, 0, 0.229782, 0.865608, 0.0282334, 0, 0.245265, 0.854924, 0.026749, 0, 0.261138, 0.843607, 0.02526, 0, 0.277401, 0.832456, 0.0238214, 0, 0.294056, 0.821342, 0.0224682, 0, 0.311104, 0.809303, 0.0211297, 0, 0.328548, 0.796468, 0.0198387, 0, 0.346394, 0.784046, 0.0186227, 0, 0.364645, 0.771262, 0.0174561, 0, 0.38331, 0.758118, 0.0163806, 0, 0.402396, 0.745075, 0.0153287, 0, 0.421912, 0.731926, 0.0143647, 0, 0.44187, 0.71863, 0.0134363, 0, 0.462283, 0.705414, 0.0125603, 0, 0.483165, 0.693792, 0.0117508, 0, 0.504535, 0.683108, 0.0110016, 0, 0.52641, 0.67183, 0.0102757, 0, 0.548816, 0.66015, 962044e-8, 0, 0.571776, 0.647907, 898031e-8, 0, 0.595323, 0.635734, 840811e-8, 0, 0.619489, 0.623208, 786211e-8, 0, 0.644317, 0.610438, 734953e-8, 0, 0.669852, 0.597345, 687688e-8, 0, 0.696148, 0.584138, 643469e-8, 0, 0.723267, 0.5707, 602236e-8, 0, 0.75128, 0.556966, 56324e-7, 0, 0.780258, 0.543607, 528277e-8, 0, 0.810268, 0.530213, 493999e-8, 0, 0.841311, 0.516912, 462265e-8, 0, 0.873016, 0.503916, 43307e-7, 0, 0.904762, 0.491146, 406858e-8, 0, 0.936508, 0.478439, 381436e-8, 0, 0.968254, 0.465834, 358003e-8, 0, 1, 1, 0.0534039, 0, 0, 1, 0.053404, 0, 0, 0.999998, 0.0534055, 0, 0, 0.999989, 0.0534116, 0, 0, 0.999968, 0.0534283, 0, 0, 0.999918, 0.0534633, 0, 155895e-9, 0.99983, 0.0535262, 0, 120914e-8, 0.999685, 0.0536281, 0, 334944e-8, 0.999461, 0.0537799, 0, 653077e-8, 0.999119, 0.0539902, 0, 0.0106718, 0.998582, 0.0542524, 0, 0.0156907, 0.995919, 0.0540318, 0, 0.0215147, 0.993735, 0.0538914, 0, 0.0280801, 0.992126, 0.0539557, 0, 0.0353323, 0.990266, 0.0540401, 0, 0.0432247, 0.986317, 0.0536064, 0, 0.0517172, 0.983213, 0.0534425, 0, 0.0607754, 0.978303, 0.0528622, 0, 0.0703698, 0.973665, 0.0523363, 0, 0.0804742, 0.968091, 0.0516165, 0, 0.0910667, 0.961026, 0.0505434, 0, 0.102128, 0.954333, 0.049523, 0, 0.113641, 0.946372, 0.0481698, 0, 0.125591, 0.938254, 0.0467674, 0, 0.137965, 0.929516, 0.0452341, 0, 0.150754, 0.920106, 0.0435083, 0, 0.163947, 0.910899, 0.0417399, 0, 0.177537, 0.901532, 0.0399389, 0, 0.191516, 0.891919, 0.0380901, 0, 0.205881, 0.882006, 0.0362341, 0, 0.220626, 0.871965, 0.0343444, 0, 0.235749, 0.862145, 0.0324832, 0, 0.251248, 0.852058, 0.0306681, 0, 0.267121, 0.84161, 0.0289097, 0, 0.283368, 0.830806, 0.0272079, 0, 0.299992, 0.820476, 0.0256089, 0, 0.316992, 0.809514, 0.0240394, 0, 0.334374, 0.797865, 0.0225379, 0, 0.35214, 0.785621, 0.0211235, 0, 0.370296, 0.773765, 0.0197908, 0, 0.388849, 0.761629, 0.0185235, 0, 0.407807, 0.748891, 0.0173358, 0, 0.427178, 0.736437, 0.0162305, 0, 0.446974, 0.723707, 0.0151778, 0, 0.467207, 0.710606, 0.0141791, 0, 0.487892, 0.698019, 0.0132592, 0, 0.509046, 0.686203, 0.0123887, 0, 0.530687, 0.675692, 0.0115976, 0, 0.552839, 0.664826, 0.0108325, 0, 0.575527, 0.65349, 0.0101348, 0, 0.59878, 0.641774, 947756e-8, 0, 0.622634, 0.629794, 886058e-8, 0, 0.647128, 0.617647, 828526e-8, 0, 0.672308, 0.60534, 775312e-8, 0, 0.698231, 0.592718, 726033e-8, 0, 0.724958, 0.579746, 679731e-8, 0, 0.752563, 0.566763, 636111e-8, 0, 0.781127, 0.553515, 595228e-8, 0, 0.810733, 0.540118, 556876e-8, 0, 0.841426, 0.527325, 523051e-8, 0, 0.873016, 0.514265, 490712e-8, 0, 0.904762, 0.501406, 460297e-8, 0, 0.936508, 0.488922, 431247e-8, 0, 0.968254, 0.476541, 40472e-7, 0, 1, 1, 0.0659184, 0, 0, 1, 0.0659185, 0, 0, 0.999998, 0.06592, 0, 0, 0.999988, 0.0659259, 0, 0, 0.999963, 0.0659423, 0, 0, 0.999907, 0.0659764, 0, 374198e-9, 0.999806, 0.0660376, 0, 182071e-8, 0.999639, 0.0661361, 0, 43894e-7, 0.999378, 0.0662814, 0, 800055e-8, 0.998985, 0.0664779, 0, 0.0125594, 0.998285, 0.0666914, 0, 0.0179786, 0.995071, 0.0661989, 0, 0.0241822, 0.993172, 0.0660454, 0, 0.031106, 0.991438, 0.0660105, 0, 0.0386952, 0.988428, 0.0656875, 0, 0.0469032, 0.985218, 0.0652913, 0, 0.0556905, 0.981128, 0.0647107, 0, 0.065023, 0.976015, 0.0638491, 0, 0.0748717, 0.97097, 0.062993, 0, 0.0852112, 0.964582, 0.0617927, 0, 0.0960199, 0.957383, 0.0603626, 0, 0.107279, 0.949969, 0.0588128, 0, 0.118971, 0.941843, 0.0570274, 0, 0.131084, 0.933624, 0.0551885, 0, 0.143604, 0.924543, 0.053122, 0, 0.156521, 0.914919, 0.0508897, 0, 0.169825, 0.905773, 0.0486418, 0, 0.18351, 0.896434, 0.0463364, 0, 0.197569, 0.887195, 0.0440623, 0, 0.211997, 0.877706, 0.0417799, 0, 0.226789, 0.867719, 0.03945, 0, 0.241944, 0.858587, 0.037243, 0, 0.257458, 0.849317, 0.0350956, 0, 0.273331, 0.839585, 0.0329852, 0, 0.289563, 0.829856, 0.0310028, 0, 0.306154, 0.819589, 0.0290953, 0, 0.323108, 0.809714, 0.0272738, 0, 0.340426, 0.79934, 0.0255631, 0, 0.358113, 0.788224, 0.0239175, 0, 0.376175, 0.776619, 0.0223831, 0, 0.394616, 0.76521, 0.0209298, 0, 0.413445, 0.753716, 0.0195786, 0, 0.432671, 0.741564, 0.0183001, 0, 0.452305, 0.729413, 0.0171259, 0, 0.472358, 0.717146, 0.0159933, 0, 0.492845, 0.70436, 0.0149495, 0, 0.513783, 0.69219, 0.0139681, 0, 0.535189, 0.680289, 0.0130577, 0, 0.557087, 0.669611, 0.0122198, 0, 0.5795, 0.659113, 0.0114174, 0, 0.602459, 0.648148, 0.0106729, 0, 0.625997, 0.636905, 998997e-8, 0, 0.650154, 0.625154, 934313e-8, 0, 0.674976, 0.613481, 874839e-8, 0, 0.700518, 0.60154, 818265e-8, 0, 0.726845, 0.58943, 766889e-8, 0, 0.754032, 0.576828, 717153e-8, 0, 0.782167, 0.564194, 672696e-8, 0, 0.811344, 0.551501, 630863e-8, 0, 0.841644, 0.538635, 592177e-8, 0, 0.873016, 0.525724, 554888e-8, 0, 0.904762, 0.513209, 520225e-8, 0, 0.936508, 0.500457, 488231e-8, 0, 0.968254, 0.48799, 457153e-8, 0, 1, 1, 0.0810131, 0, 0, 1, 0.0810133, 0, 0, 0.999997, 0.0810145, 0, 0, 0.999985, 0.08102, 0, 0, 0.999956, 0.0810347, 0, 195026e-10, 0.999893, 0.0810656, 0, 719316e-9, 0.999777, 0.0811205, 0, 259774e-8, 0.999583, 0.081208, 0, 561807e-8, 0.999281, 0.0813343, 0, 967472e-8, 0.998813, 0.0814969, 0, 0.0146627, 0.997597, 0.0815217, 0, 0.0204902, 0.994379, 0.0808502, 0, 0.0270802, 0.992744, 0.0806792, 0, 0.0343674, 0.990745, 0.0804589, 0, 0.0422974, 0.986646, 0.0796107, 0, 0.0508242, 0.983611, 0.0790913, 0, 0.0599087, 0.978869, 0.0780746, 0, 0.0695175, 0.973475, 0.0768218, 0, 0.0796223, 0.967845, 0.0754926, 0, 0.0901983, 0.960778, 0.0737063, 0, 0.101224, 0.953333, 0.0718052, 0, 0.112682, 0.945274, 0.0695946, 0, 0.124555, 0.936955, 0.0672492, 0, 0.136831, 0.928319, 0.0647732, 0, 0.149496, 0.919075, 0.0620947, 0, 0.162542, 0.909114, 0.0591816, 0, 0.175958, 0.900137, 0.0563917, 0, 0.189739, 0.891069, 0.0535392, 0, 0.203877, 0.882262, 0.0507642, 0, 0.218368, 0.873232, 0.0479793, 0, 0.233208, 0.864042, 0.045226, 0, 0.248393, 0.855002, 0.0425413, 0, 0.263923, 0.846569, 0.0400126, 0, 0.279796, 0.837714, 0.0375269, 0, 0.296012, 0.828918, 0.0352027, 0, 0.312573, 0.819783, 0.0330011, 0, 0.329479, 0.810129, 0.0308908, 0, 0.346734, 0.800866, 0.0289112, 0, 0.364342, 0.79093, 0.0270255, 0, 0.382307, 0.780593, 0.0252758, 0, 0.400637, 0.769511, 0.0236178, 0, 0.419337, 0.758558, 0.0220652, 0, 0.438418, 0.747632, 0.0206289, 0, 0.457889, 0.736146, 0.0192873, 0, 0.477761, 0.724093, 0.0180333, 0, 0.49805, 0.71234, 0.0168264, 0, 0.51877, 0.700201, 0.015746, 0, 0.53994, 0.687949, 0.0147027, 0, 0.561581, 0.676163, 0.0137512, 0, 0.583718, 0.665001, 0.0128655, 0, 0.60638, 0.65472, 0.0120366, 0, 0.629599, 0.644213, 0.0112604, 0, 0.653415, 0.633382, 0.0105413, 0, 0.677874, 0.62212, 986498e-8, 0, 0.70303, 0.610631, 923308e-8, 0, 0.728948, 0.599078, 864206e-8, 0, 0.755706, 0.587519, 811784e-8, 0, 0.783396, 0.575505, 761237e-8, 0, 0.812121, 0.563148, 713949e-8, 0, 0.841989, 0.550828, 668379e-8, 0, 0.873035, 0.538458, 627715e-8, 0, 0.904762, 0.525905, 588336e-8, 0, 0.936508, 0.513517, 552687e-8, 0, 0.968254, 0.501395, 519681e-8, 0, 1, 1, 0.0991506, 0, 0, 1, 0.0991504, 0, 0, 0.999996, 0.0991515, 0, 0, 0.999984, 0.0991558, 0, 0, 0.999947, 0.0991672, 0, 114389e-9, 0.999874, 0.0991912, 0, 121503e-8, 0.999739, 0.0992331, 0, 356108e-8, 0.999514, 0.0992983, 0, 705578e-8, 0.999159, 0.0993877, 0, 0.011574, 0.998586, 0.0994837, 0, 0.017003, 0.995731, 0.0988425, 0, 0.0232484, 0.993384, 0.098276, 0, 0.0302318, 0.991615, 0.0979269, 0, 0.0378884, 0.989029, 0.0973432, 0, 0.0461641, 0.985373, 0.0963539, 0, 0.0550136, 0.981278, 0.0952306, 0, 0.0643988, 0.975777, 0.0936233, 0, 0.0742868, 0.970526, 0.0920219, 0, 0.0846501, 0.963755, 0.0898912, 0, 0.0954644, 0.956676, 0.0876064, 0, 0.106709, 0.948099, 0.0847751, 0, 0.118367, 0.939718, 0.0818638, 0, 0.130423, 0.931305, 0.078857, 0, 0.142862, 0.922342, 0.0756127, 0, 0.155674, 0.912842, 0.0721473, 0, 0.168849, 0.903304, 0.0686195, 0, 0.182378, 0.89411, 0.0650589, 0, 0.196255, 0.885512, 0.0616022, 0, 0.210473, 0.877193, 0.0582434, 0, 0.225027, 0.86877, 0.0548979, 0, 0.239915, 0.860267, 0.0516095, 0, 0.255132, 0.851915, 0.048468, 0, 0.270678, 0.843912, 0.0454447, 0, 0.286551, 0.83604, 0.0425612, 0, 0.302751, 0.828245, 0.0398752, 0, 0.31928, 0.820159, 0.0373198, 0, 0.336138, 0.81167, 0.034916, 0, 0.35333, 0.802659, 0.0326402, 0, 0.370858, 0.793921, 0.0304901, 0, 0.388728, 0.784713, 0.0284857, 0, 0.406944, 0.774946, 0.0266186, 0, 0.425515, 0.76448, 0.0248593, 0, 0.444449, 0.753793, 0.0232114, 0, 0.463756, 0.743506, 0.0217039, 0, 0.483447, 0.732555, 0.0202841, 0, 0.503535, 0.720965, 0.0189648, 0, 0.524036, 0.709422, 0.0177189, 0, 0.544968, 0.697756, 0.0165626, 0, 0.56635, 0.685565, 0.015483, 0, 0.588208, 0.673987, 0.0144892, 0, 0.610569, 0.66244, 0.0135607, 0, 0.633466, 0.651675, 0.0126956, 0, 0.656936, 0.641598, 0.0118788, 0, 0.681025, 0.63121, 0.0111261, 0, 0.705788, 0.620514, 0.010437, 0, 0.731289, 0.609366, 978747e-8, 0, 0.757606, 0.598137, 917257e-8, 0, 0.784834, 0.586966, 859778e-8, 0, 0.813085, 0.575549, 806803e-8, 0, 0.842485, 0.563797, 757294e-8, 0, 0.87313, 0.551758, 710592e-8, 0, 0.904762, 0.539894, 66841e-7, 0, 0.936508, 0.527901, 627901e-8, 0, 0.968254, 0.515819, 590506e-8, 0, 1, 1, 0.120864, 0, 0, 1, 0.120864, 0, 0, 0.999996, 0.120864, 0, 0, 0.99998, 0.120867, 0, 0, 0.99994, 0.120872, 0, 323781e-9, 0.999852, 0.120884, 0, 188693e-8, 0.999693, 0.120903, 0, 473489e-8, 0.999426, 0.120929, 0, 872704e-8, 0.999002, 0.120955, 0, 0.0137237, 0.998235, 0.120918, 0, 0.0196068, 0.994608, 0.119764, 0, 0.0262803, 0.992997, 0.119265, 0, 0.0336657, 0.990968, 0.11863, 0, 0.0416987, 0.987002, 0.117261, 0, 0.0503261, 0.983524, 0.116009, 0, 0.0595035, 0.97875, 0.114252, 0, 0.0691935, 0.972652, 0.11193, 0, 0.0793645, 0.966613, 0.109555, 0, 0.0899894, 0.959275, 0.106612, 0, 0.101045, 0.951272, 0.103375, 0, 0.112512, 0.942323, 0.0996594, 0, 0.124372, 0.933679, 0.0958841, 0, 0.136611, 0.924822, 0.0919265, 0, 0.149216, 0.915742, 0.0878061, 0, 0.162176, 0.906348, 0.0834894, 0, 0.175482, 0.896883, 0.079085, 0, 0.189125, 0.88774, 0.0746745, 0, 0.203098, 0.87986, 0.0705773, 0, 0.217396, 0.871998, 0.0665005, 0, 0.232015, 0.864325, 0.0625413, 0, 0.24695, 0.856685, 0.0586781, 0, 0.2622, 0.84925, 0.0550063, 0, 0.277761, 0.841719, 0.0514727, 0, 0.293634, 0.834755, 0.0481398, 0, 0.309819, 0.827853, 0.0450172, 0, 0.326315, 0.820888, 0.0420969, 0, 0.343126, 0.813616, 0.0393702, 0, 0.360254, 0.805767, 0.0367771, 0, 0.377701, 0.797338, 0.0343274, 0, 0.395474, 0.789122, 0.0320529, 0, 0.413577, 0.780601, 0.0299485, 0, 0.432018, 0.771424, 0.0279812, 0, 0.450804, 0.761502, 0.0261054, 0, 0.469944, 0.751166, 0.0243942, 0, 0.489451, 0.741276, 0.0228087, 0, 0.509337, 0.730898, 0.0213265, 0, 0.529617, 0.719878, 0.0199307, 0, 0.550307, 0.708379, 0.0186574, 0, 0.571428, 0.697165, 0.0174446, 0, 0.593003, 0.685554, 0.0163144, 0, 0.615059, 0.673631, 0.015276, 0, 0.637628, 0.662385, 0.0143003, 0, 0.660746, 0.651059, 0.0134112, 0, 0.68446, 0.640451, 0.0125794, 0, 0.70882, 0.630536, 0.011793, 0, 0.733893, 0.620316, 0.0110547, 0, 0.759756, 0.609722, 0.0103668, 0, 0.786505, 0.598804, 973009e-8, 0, 0.814259, 0.587871, 912812e-8, 0, 0.843157, 0.577121, 858916e-8, 0, 0.87334, 0.566019, 807333e-8, 0, 0.904762, 0.554664, 759687e-8, 0, 0.936508, 0.543101, 714759e-8, 0, 0.968254, 0.531558, 673418e-8, 0, 1, 1, 0.146767, 0, 0, 1, 0.146767, 0, 0, 0.999997, 0.146767, 0, 0, 0.999977, 0.146765, 0, 320658e-11, 0.999929, 0.146762, 0, 682576e-9, 0.999823, 0.146753, 0, 276402e-8, 0.999633, 0.146735, 0, 614771e-8, 0.999314, 0.146699, 0, 0.0106613, 0.998796, 0.14662, 0, 0.0161546, 0.997124, 0.146107, 0, 0.0225063, 0.994062, 0.144857, 0, 0.0296198, 0.992154, 0.144011, 0, 0.037417, 0.989186, 0.142712, 0, 0.0458348, 0.985279, 0.140926, 0, 0.0548211, 0.980826, 0.13885, 0, 0.0643326, 0.975056, 0.136168, 0, 0.074333, 0.969005, 0.133217, 0, 0.0847917, 0.961554, 0.12959, 0, 0.0956828, 0.954206, 0.125886, 0, 0.106984, 0.945046, 0.121335, 0, 0.118675, 0.935678, 0.116492, 0, 0.130741, 0.926748, 0.111635, 0, 0.143166, 0.917764, 0.106625, 0, 0.155939, 0.908358, 0.101325, 0, 0.169049, 0.899219, 0.0960249, 0, 0.182487, 0.890089, 0.0906527, 0, 0.196245, 0.881488, 0.0853905, 0, 0.210317, 0.874031, 0.0804177, 0, 0.224697, 0.866932, 0.0756005, 0, 0.23938, 0.859976, 0.0709019, 0, 0.254364, 0.853375, 0.0664391, 0, 0.269646, 0.846971, 0.0622012, 0, 0.285223, 0.840483, 0.058129, 0, 0.301096, 0.833969, 0.0542762, 0, 0.317265, 0.82806, 0.0507042, 0, 0.333729, 0.822128, 0.047368, 0, 0.350491, 0.815989, 0.044272, 0, 0.367554, 0.809336, 0.0413444, 0, 0.38492, 0.802177, 0.038601, 0, 0.402594, 0.79441, 0.0360227, 0, 0.420582, 0.786573, 0.0336383, 0, 0.438891, 0.778619, 0.0314321, 0, 0.457527, 0.77, 0.029362, 0, 0.476499, 0.760698, 0.0274102, 0, 0.49582, 0.750932, 0.0256146, 0, 0.5155, 0.740993, 0.023974, 0, 0.535555, 0.731159, 0.0224182, 0, 0.556, 0.720836, 0.0209889, 0, 0.576855, 0.709913, 0.0196411, 0, 0.598143, 0.698415, 0.0183824, 0, 0.619888, 0.68745, 0.0172222, 0, 0.642123, 0.676154, 0.0161509, 0, 0.664883, 0.664383, 0.0151397, 0, 0.688211, 0.6533, 0.0141873, 0, 0.71216, 0.642072, 0.0133105, 0, 0.736792, 0.631412, 0.0124932, 0, 0.762186, 0.621622, 0.0117408, 0, 0.788439, 0.611681, 0.0110358, 0, 0.815672, 0.60142, 0.0103775, 0, 0.844034, 0.59083, 975623e-8, 0, 0.873699, 0.580254, 918084e-8, 0, 0.904765, 0.569841, 864721e-8, 0, 0.936508, 0.559224, 815731e-8, 0, 0.968254, 0.548315, 767924e-8, 0, 1, 1, 0.177563, 0, 0, 1, 0.177563, 0, 0, 0.999994, 0.177562, 0, 0, 0.999972, 0.177555, 0, 664171e-10, 0.999914, 0.177536, 0, 12276e-7, 0.999787, 0.177496, 0, 388025e-8, 0.999556, 0.17742, 0, 783463e-8, 0.999165, 0.177285, 0, 0.0128953, 0.9985, 0.177037, 0, 0.0189053, 0.995388, 0.175634, 0, 0.025742, 0.993102, 0.174375, 0, 0.033309, 0.990992, 0.173121, 0, 0.0415298, 0.986932, 0.170896, 0, 0.0503425, 0.982786, 0.16847, 0, 0.0596964, 0.977592, 0.165455, 0, 0.0695498, 0.971075, 0.161676, 0, 0.0798676, 0.963967, 0.157458, 0, 0.0906201, 0.956397, 0.152836, 0, 0.101783, 0.947489, 0.147467, 0, 0.113333, 0.937564, 0.14145, 0, 0.125254, 0.928182, 0.135383, 0, 0.137529, 0.919027, 0.129212, 0, 0.150144, 0.909618, 0.12276, 0, 0.163088, 0.900492, 0.116273, 0, 0.176351, 0.891671, 0.1098, 0, 0.189924, 0.883146, 0.103362, 0, 0.203799, 0.875151, 0.0970799, 0, 0.21797, 0.868338, 0.0911732, 0, 0.232433, 0.862033, 0.0854966, 0, 0.247182, 0.856107, 0.0800691, 0, 0.262216, 0.850644, 0.0749618, 0, 0.27753, 0.845261, 0.070079, 0, 0.293124, 0.839885, 0.0654321, 0, 0.308997, 0.834609, 0.0610975, 0, 0.325149, 0.829083, 0.0569741, 0, 0.341581, 0.82404, 0.0531736, 0, 0.358294, 0.818968, 0.049665, 0, 0.37529, 0.813496, 0.0463856, 0, 0.392573, 0.807533, 0.0433217, 0, 0.410148, 0.80099, 0.0404402, 0, 0.428019, 0.793891, 0.0377578, 0, 0.446192, 0.786281, 0.0352616, 0, 0.464676, 0.778773, 0.0329577, 0, 0.483478, 0.770737, 0.030808, 0, 0.502608, 0.762094, 0.0287964, 0, 0.522079, 0.752898, 0.0269254, 0, 0.541905, 0.743306, 0.0251926, 0, 0.5621, 0.733416, 0.023595, 0, 0.582684, 0.723742, 0.0221155, 0, 0.603677, 0.713542, 0.0207435, 0, 0.625106, 0.702755, 0.019434, 0, 0.646998, 0.691484, 0.0182046, 0, 0.66939, 0.680531, 0.0170771, 0, 0.692324, 0.66953, 0.0160339, 0, 0.715849, 0.658126, 0.0150677, 0, 0.740028, 0.646933, 0.0141551, 0, 0.764937, 0.636107, 0.0133179, 0, 0.790673, 0.625271, 0.0125284, 0, 0.817358, 0.615225, 0.0117937, 0, 0.84515, 0.605678, 0.0111181, 0, 0.874244, 0.59583, 0.0104759, 0, 0.904828, 0.585704, 986672e-8, 0, 0.936508, 0.575413, 929712e-8, 0, 0.968254, 0.565373, 876713e-8, 0, 1, 1, 0.214058, 0, 0, 0.999999, 0.214058, 0, 0, 0.999994, 0.214055, 0, 0, 0.999966, 0.214039, 0, 259642e-9, 0.999893, 0.213998, 0, 200075e-8, 0.999737, 0.21391, 0, 527775e-8, 0.999449, 0.213745, 0, 983959e-8, 0.99896, 0.213458, 0, 0.0154755, 0.9979, 0.212855, 0, 0.0220249, 0.994278, 0.210779, 0, 0.0293654, 0.992254, 0.20926, 0, 0.0374021, 0.98881, 0.206908, 0, 0.0460604, 0.984715, 0.204009, 0, 0.0552802, 0.979738, 0.200471, 0, 0.0650127, 0.972884, 0.195813, 0, 0.0752175, 0.965996, 0.190856, 0, 0.0858612, 0.957974, 0.185077, 0, 0.0969155, 0.949155, 0.17868, 0, 0.108356, 0.939288, 0.171513, 0, 0.120163, 0.928996, 0.163838, 0, 0.132319, 0.919563, 0.156246, 0, 0.144808, 0.910004, 0.148359, 0, 0.157618, 0.900791, 0.140417, 0, 0.170737, 0.892135, 0.132569, 0, 0.184155, 0.883803, 0.124741, 0, 0.197866, 0.876034, 0.117091, 0, 0.211861, 0.869219, 0.109835, 0, 0.226134, 0.863062, 0.102859, 0, 0.240682, 0.857795, 0.0962928, 0, 0.255499, 0.853009, 0.0900725, 0, 0.270583, 0.848603, 0.0842101, 0, 0.285931, 0.844335, 0.0786527, 0, 0.301542, 0.840208, 0.0734397, 0, 0.317415, 0.836035, 0.0685334, 0, 0.33355, 0.83172, 0.0639275, 0, 0.349948, 0.827135, 0.0595909, 0, 0.36661, 0.822797, 0.0556204, 0, 0.383539, 0.818387, 0.0519394, 0, 0.400738, 0.813565, 0.0485317, 0, 0.41821, 0.808142, 0.0453138, 0, 0.435961, 0.802212, 0.0423354, 0, 0.453997, 0.79573, 0.0395553, 0, 0.472324, 0.788741, 0.036988, 0, 0.490951, 0.781093, 0.0345688, 0, 0.509887, 0.773597, 0.0323297, 0, 0.529144, 0.765622, 0.0302719, 0, 0.548735, 0.757083, 0.0283477, 0, 0.568674, 0.747992, 0.0265562, 0, 0.588979, 0.738591, 0.0248844, 0, 0.609671, 0.728719, 0.0233342, 0, 0.630773, 0.719146, 0.0219081, 0, 0.652314, 0.709165, 0.0205711, 0, 0.674328, 0.69875, 0.0193248, 0, 0.696854, 0.687884, 0.0181582, 0, 0.719942, 0.676818, 0.0170746, 0, 0.743651, 0.666247, 0.0160718, 0, 0.768057, 0.655284, 0.0151262, 0, 0.793253, 0.64401, 0.0142561, 0, 0.819363, 0.633353, 0.0134327, 0, 0.846547, 0.622674, 0.012653, 0, 0.875017, 0.612265, 0.0119354, 0, 0.905021, 0.602455, 0.0112533, 0, 0.936508, 0.593147, 0.0106234, 0, 0.968254, 0.583592, 0.0100213, 0, 1, 1, 0.25717, 0, 0, 1, 0.25717, 0, 0, 0.999992, 0.257164, 0, 0, 0.999958, 0.257135, 0, 641715e-9, 0.999864, 0.25706, 0, 305314e-8, 0.999666, 0.256897, 0, 700975e-8, 0.999302, 0.256596, 0, 0.0122194, 0.998663, 0.25607, 0, 0.0184622, 0.995607, 0.254123, 0, 0.0255773, 0.993094, 0.252081, 0, 0.0334439, 0.9907, 0.249867, 0, 0.0419696, 0.98594, 0.246118, 0, 0.0510823, 0.981214, 0.242049, 0, 0.0607242, 0.974966, 0.236869, 0, 0.0708486, 0.967589, 0.230724, 0, 0.081417, 0.95915, 0.223635, 0, 0.0923974, 0.950257, 0.21596, 0, 0.103763, 0.940165, 0.207296, 0, 0.115491, 0.929396, 0.197901, 0, 0.127562, 0.919288, 0.188437, 0, 0.13996, 0.909428, 0.178762, 0, 0.15267, 0.900105, 0.169072, 0, 0.165679, 0.891418, 0.159478, 0, 0.178979, 0.883347, 0.15002, 0, 0.192558, 0.875992, 0.140813, 0, 0.20641, 0.869466, 0.13196, 0, 0.220529, 0.863699, 0.123501, 0, 0.234907, 0.858553, 0.115436, 0, 0.249542, 0.854379, 0.107901, 0, 0.264428, 0.850894, 0.10088, 0, 0.279564, 0.847632, 0.0942296, 0, 0.294947, 0.844571, 0.0879861, 0, 0.310575, 0.84163, 0.0821534, 0, 0.326448, 0.838542, 0.0766409, 0, 0.342566, 0.835412, 0.0715322, 0, 0.358929, 0.831899, 0.0666883, 0, 0.37554, 0.828177, 0.0622175, 0, 0.392399, 0.82416, 0.0580452, 0, 0.409511, 0.820393, 0.054267, 0, 0.426878, 0.816068, 0.0507172, 0, 0.444506, 0.811201, 0.0474041, 0, 0.4624, 0.805785, 0.0443174, 0, 0.480566, 0.799878, 0.0414562, 0, 0.499013, 0.793469, 0.0388147, 0, 0.517749, 0.786473, 0.0363453, 0, 0.536785, 0.778874, 0.0340225, 0, 0.556134, 0.771277, 0.0318599, 0, 0.575809, 0.763426, 0.0298859, 0, 0.595827, 0.755044, 0.0280357, 0, 0.616207, 0.746161, 0.0262979, 0, 0.636973, 0.737124, 0.0247295, 0, 0.65815, 0.72761, 0.0232514, 0, 0.679772, 0.717822, 0.0218755, 0, 0.701876, 0.708279, 0.0205942, 0, 0.724509, 0.698333, 0.0193947, 0, 0.74773, 0.68802, 0.0182717, 0, 0.771609, 0.677321, 0.0172044, 0, 0.79624, 0.666504, 0.0162122, 0, 0.821743, 0.656184, 0.0152924, 0, 0.84828, 0.64556, 0.0144326, 0, 0.876069, 0.634636, 0.0136157, 0, 0.905404, 0.624124, 0.0128612, 0, 0.936508, 0.613914, 0.0121435, 0, 0.968254, 0.603589, 0.0114887, 0, 1, 1, 0.307946, 0, 0, 0.999999, 0.307945, 0, 0, 0.999988, 0.307934, 0, 204479e-10, 0.999944, 0.307886, 0, 127833e-8, 0.999824, 0.307756, 0, 445047e-8, 0.999565, 0.30748, 0, 914673e-8, 0.999085, 0.306966, 0, 0.0150498, 0.998103, 0.306004, 0, 0.0219367, 0.994249, 0.303028, 0, 0.0296485, 0.991807, 0.300435, 0, 0.038068, 0.987773, 0.296554, 0, 0.0471062, 0.982673, 0.2916, 0, 0.0566942, 0.976623, 0.285641, 0, 0.0667768, 0.968757, 0.27815, 0, 0.0773099, 0.959849, 0.269529, 0, 0.088257, 0.950663, 0.260248, 0, 0.0995879, 0.940129, 0.249704, 0, 0.111277, 0.92895, 0.238291, 0, 0.123304, 0.917996, 0.226501, 0, 0.13565, 0.907813, 0.214669, 0, 0.148299, 0.898305, 0.202835, 0, 0.161237, 0.889626, 0.191158, 0, 0.174455, 0.88175, 0.179695, 0, 0.187941, 0.874715, 0.168548, 0, 0.201687, 0.868746, 0.15792, 0, 0.215687, 0.863703, 0.147807, 0, 0.229933, 0.859315, 0.138149, 0, 0.24442, 0.855538, 0.128993, 0, 0.259145, 0.852428, 0.120414, 0, 0.274103, 0.850168, 0.112498, 0, 0.289293, 0.848132, 0.105054, 0, 0.304711, 0.846291, 0.0981087, 0, 0.320357, 0.844431, 0.0915942, 0, 0.33623, 0.842493, 0.0855056, 0, 0.35233, 0.840368, 0.0798204, 0, 0.368658, 0.83798, 0.0745097, 0, 0.385214, 0.83523, 0.0695424, 0, 0.402002, 0.832091, 0.0649092, 0, 0.419023, 0.828667, 0.0606291, 0, 0.436282, 0.824805, 0.0566523, 0, 0.453782, 0.820988, 0.0530229, 0, 0.471529, 0.816635, 0.0496364, 0, 0.489528, 0.811725, 0.0464658, 0, 0.507788, 0.806316, 0.0435082, 0, 0.526317, 0.800469, 0.0407873, 0, 0.545124, 0.794107, 0.038255, 0, 0.564221, 0.787218, 0.0358825, 0, 0.583621, 0.779872, 0.0336785, 0, 0.603341, 0.772097, 0.0316379, 0, 0.623397, 0.764484, 0.0297379, 0, 0.643812, 0.756428, 0.0279581, 0, 0.664611, 0.748022, 0.0263153, 0, 0.685824, 0.739268, 0.0247799, 0, 0.707488, 0.73024, 0.0233385, 0, 0.729646, 0.720893, 0.0220035, 0, 0.752354, 0.71119, 0.0207555, 0, 0.77568, 0.701791, 0.0195843, 0, 0.799715, 0.692184, 0.0184891, 0, 0.824574, 0.682258, 0.0174541, 0, 0.850417, 0.67206, 0.0164873, 0, 0.877466, 0.661717, 0.0155959, 0, 0.90604, 0.651462, 0.0147519, 0, 0.936528, 0.641467, 0.0139727, 0, 0.968254, 0.631229, 0.0132363, 0, 1, 1, 0.367573, 0, 0, 0.999999, 0.367571, 0, 0, 0.999984, 0.367553, 0, 183382e-9, 0.999925, 0.367473, 0, 225254e-8, 0.999759, 0.367259, 0, 628165e-8, 0.99941, 0.366801, 0, 0.0117858, 0.998739, 0.365946, 0, 0.0184359, 0.995529, 0.363191, 0, 0.0260114, 0.992875, 0.360171, 0, 0.0343581, 0.989135, 0.355981, 0, 0.0433637, 0.984166, 0.350401, 0, 0.0529438, 0.977871, 0.343348, 0, 0.0630334, 0.96951, 0.334341, 0, 0.0735805, 0.959964, 0.323862, 0, 0.0845437, 0.950162, 0.312521, 0, 0.095889, 0.938882, 0.299577, 0, 0.107588, 0.926992, 0.285573, 0, 0.119617, 0.915589, 0.271212, 0, 0.131957, 0.904791, 0.256611, 0, 0.144591, 0.895177, 0.242224, 0, 0.157503, 0.886403, 0.227952, 0, 0.170682, 0.878957, 0.214192, 0, 0.184117, 0.872418, 0.200795, 0, 0.197799, 0.867029, 0.188015, 0, 0.21172, 0.862835, 0.175975, 0, 0.225873, 0.859411, 0.164526, 0, 0.240253, 0.856655, 0.153693, 0, 0.254854, 0.854519, 0.14352, 0, 0.269673, 0.852828, 0.13397, 0, 0.284707, 0.851412, 0.124984, 0, 0.299953, 0.850609, 0.116748, 0, 0.315408, 0.849855, 0.10905, 0, 0.331073, 0.849017, 0.101839, 0, 0.346946, 0.848079, 0.0951359, 0, 0.363028, 0.846911, 0.0888774, 0, 0.379318, 0.845445, 0.0830375, 0, 0.395818, 0.84362, 0.0775844, 0, 0.41253, 0.841411, 0.0725054, 0, 0.429457, 0.838768, 0.0677691, 0, 0.446602, 0.835801, 0.0634016, 0, 0.463968, 0.832341, 0.0593095, 0, 0.481561, 0.828424, 0.0555121, 0, 0.499386, 0.824312, 0.052024, 0, 0.51745, 0.819918, 0.0487865, 0, 0.535761, 0.815072, 0.0457801, 0, 0.554328, 0.809863, 0.0430184, 0, 0.573162, 0.804164, 0.0404245, 0, 0.592275, 0.798034, 0.0380146, 0, 0.611681, 0.791436, 0.0357436, 0, 0.631398, 0.784498, 0.0336475, 0, 0.651445, 0.777125, 0.0316666, 0, 0.671845, 0.769365, 0.0298122, 0, 0.692628, 0.761579, 0.0281001, 0, 0.713827, 0.753746, 0.0265049, 0, 0.735484, 0.745573, 0.0250067, 0, 0.75765, 0.737083, 0.0236026, 0, 0.78039, 0.728545, 0.0223302, 0, 0.803789, 0.719691, 0.0211243, 0, 0.82796, 0.710569, 0.0199983, 0, 0.853056, 0.701216, 0.0189569, 0, 0.879298, 0.692094, 0.0179702, 0, 0.907014, 0.682909, 0.0170418, 0, 0.936691, 0.673509, 0.0161732, 0, 0.968254, 0.663863, 0.0153406, 0, 1, 1, 0.437395, 0, 0, 0.999998, 0.437394, 0, 0, 0.99998, 0.437363, 0, 616704e-9, 0.999891, 0.437232, 0, 367925e-8, 0.999656, 0.436877, 0, 867446e-8, 0.999148, 0.436121, 0, 0.0150679, 0.997959, 0.434564, 0, 0.022531, 0.993464, 0.430134, 0, 0.0308507, 0.990606, 0.426077, 0, 0.0398805, 0.985027, 0.419397, 0, 0.0495148, 0.978491, 0.41118, 0, 0.0596749, 0.969643, 0.40048, 0, 0.0703001, 0.959189, 0.38769, 0, 0.0813427, 0.948223, 0.373575, 0, 0.0927641, 0.935955, 0.357622, 0, 0.104533, 0.923237, 0.34043, 0, 0.116624, 0.911074, 0.322735, 0, 0.129015, 0.899724, 0.30479, 0, 0.141687, 0.890189, 0.287392, 0, 0.154626, 0.881796, 0.270248, 0, 0.167818, 0.874781, 0.253659, 0, 0.181252, 0.869166, 0.237786, 0, 0.194918, 0.864725, 0.222618, 0, 0.208807, 0.861565, 0.208356, 0, 0.222913, 0.859284, 0.194867, 0, 0.237229, 0.857677, 0.18212, 0, 0.25175, 0.856714, 0.17018, 0, 0.266473, 0.856155, 0.158969, 0, 0.281392, 0.8558, 0.148413, 0, 0.296505, 0.855672, 0.138578, 0, 0.311811, 0.855538, 0.129345, 0, 0.327306, 0.855689, 0.120861, 0, 0.342991, 0.855767, 0.112969, 0, 0.358864, 0.855618, 0.105593, 0, 0.374925, 0.85525, 0.0987451, 0, 0.391176, 0.854583, 0.0923727, 0, 0.407616, 0.853534, 0.0864143, 0, 0.424249, 0.852061, 0.0808338, 0, 0.441076, 0.850253, 0.0756771, 0, 0.4581, 0.848004, 0.0708612, 0, 0.475324, 0.845333, 0.0663784, 0, 0.492754, 0.842376, 0.0622631, 0, 0.510394, 0.838956, 0.0584112, 0, 0.528251, 0.835121, 0.0548328, 0, 0.546331, 0.830842, 0.0514838, 0, 0.564644, 0.826212, 0.048355, 0, 0.583198, 0.821522, 0.0454714, 0, 0.602005, 0.816551, 0.0428263, 0, 0.621078, 0.811211, 0.0403612, 0, 0.640434, 0.805479, 0.038039, 0, 0.660089, 0.799409, 0.0358739, 0, 0.680066, 0.79306, 0.0338727, 0, 0.70039, 0.786395, 0.0319985, 0, 0.721094, 0.779416, 0.030241, 0, 0.742215, 0.77214, 0.0285951, 0, 0.7638, 0.764636, 0.0270747, 0, 0.785912, 0.756836, 0.0256354, 0, 0.808628, 0.749315, 0.0243027, 0, 0.832055, 0.741561, 0.0230497, 0, 0.856338, 0.733589, 0.0218801, 0, 0.88169, 0.725479, 0.020784, 0, 0.908441, 0.717255, 0.0197702, 0, 0.937125, 0.708829, 0.0188168, 0, 0.968254, 0.700191, 0.0179113, 0, 1, 1, 0.518937, 0, 0, 0.999998, 0.518933, 0, 0, 0.999967, 0.518883, 0, 147741e-8, 0.999832, 0.51866, 0, 573221e-8, 0.999466, 0.518057, 0, 0.011826, 0.998644, 0.516752, 0, 0.0192116, 0.994458, 0.512347, 0, 0.027573, 0.991223, 0.507675, 0, 0.0367099, 0.985515, 0.500188, 0, 0.046487, 0.978308, 0.490408, 0, 0.0568071, 0.968359, 0.477357, 0, 0.0675984, 0.95682, 0.461752, 0, 0.0788059, 0.943929, 0.443796, 0, 0.090386, 0.930224, 0.423893, 0, 0.102304, 0.916514, 0.402682, 0, 0.114532, 0.903653, 0.380914, 0, 0.127047, 0.892315, 0.359212, 0, 0.139828, 0.882942, 0.338102, 0, 0.152861, 0.875438, 0.31773, 0, 0.16613, 0.869642, 0.298186, 0, 0.179624, 0.865304, 0.279491, 0, 0.193332, 0.862382, 0.261804, 0, 0.207247, 0.860666, 0.245146, 0, 0.22136, 0.859788, 0.229406, 0, 0.235666, 0.859608, 0.214605, 0, 0.250158, 0.859912, 0.200691, 0, 0.264832, 0.86053, 0.187623, 0, 0.279684, 0.861368, 0.17539, 0, 0.294711, 0.862237, 0.163901, 0, 0.309911, 0.863127, 0.153175, 0, 0.32528, 0.863923, 0.143147, 0, 0.340819, 0.864567, 0.133781, 0, 0.356524, 0.865013, 0.125042, 0, 0.372397, 0.86539, 0.116952, 0, 0.388438, 0.865591, 0.109476, 0, 0.404645, 0.865517, 0.102542, 0, 0.421022, 0.865084, 0.0960688, 0, 0.437569, 0.864309, 0.0900499, 0, 0.454287, 0.863151, 0.0844328, 0, 0.471181, 0.861649, 0.0792218, 0, 0.488253, 0.859742, 0.0743482, 0, 0.505507, 0.857446, 0.0697963, 0, 0.522947, 0.854757, 0.0655364, 0, 0.54058, 0.851783, 0.061608, 0, 0.558412, 0.848516, 0.0579701, 0, 0.576449, 0.844897, 0.0545742, 0, 0.594701, 0.840956, 0.0514167, 0, 0.613178, 0.836676, 0.0484598, 0, 0.631892, 0.832075, 0.0456934, 0, 0.650856, 0.827191, 0.0431178, 0, 0.670088, 0.822295, 0.0407718, 0, 0.689606, 0.817294, 0.0386032, 0, 0.709434, 0.812013, 0.0365675, 0, 0.7296, 0.806465, 0.0346547, 0, 0.750138, 0.800691, 0.0328717, 0, 0.771093, 0.794709, 0.031211, 0, 0.792519, 0.788493, 0.0296504, 0, 0.814488, 0.782049, 0.0281782, 0, 0.837097, 0.775403, 0.0267965, 0, 0.860481, 0.76857, 0.0255002, 0, 0.884842, 0.761536, 0.0242759, 0, 0.910494, 0.754303, 0.0231142, 0, 0.937985, 0.74692, 0.0220305, 0, 0.968254, 0.739745, 0.0210192, 0, 1, 1, 0.613914, 0, 0, 0.999996, 0.613907, 0, 963597e-10, 0.999942, 0.613814, 0, 301247e-8, 0.999704, 0.613407, 0, 870385e-8, 0.999046, 0.612302, 0, 0.0160714, 0.995516, 0.608266, 0, 0.0245899, 0.991726, 0.602863, 0, 0.0339681, 0.985157, 0.593956, 0, 0.0440254, 0.97642, 0.581748, 0, 0.0546409, 0.964404, 0.565183, 0, 0.0657284, 0.950601, 0.545273, 0, 0.0772246, 0.935158, 0.522129, 0, 0.0890812, 0.919364, 0.496782, 0, 0.10126, 0.904754, 0.470571, 0, 0.113731, 0.89176, 0.444037, 0, 0.126469, 0.881492, 0.418322, 0, 0.139454, 0.873656, 0.393522, 0, 0.15267, 0.868053, 0.369795, 0, 0.166101, 0.864336, 0.347171, 0, 0.179736, 0.862259, 0.325737, 0, 0.193565, 0.861556, 0.305532, 0, 0.207578, 0.861776, 0.286416, 0, 0.221769, 0.862661, 0.268355, 0, 0.23613, 0.864015, 0.251334, 0, 0.250656, 0.865711, 0.235352, 0, 0.265343, 0.867519, 0.220302, 0, 0.280187, 0.869351, 0.206161, 0, 0.295183, 0.871144, 0.192908, 0, 0.31033, 0.872839, 0.180505, 0, 0.325624, 0.874307, 0.168848, 0, 0.341065, 0.875667, 0.158021, 0, 0.35665, 0.876758, 0.147877, 0, 0.37238, 0.87764, 0.138441, 0, 0.388253, 0.878237, 0.129627, 0, 0.404269, 0.878563, 0.121415, 0, 0.42043, 0.878572, 0.113741, 0, 0.436735, 0.87842, 0.106652, 0, 0.453187, 0.878057, 0.100097, 0, 0.469786, 0.877413, 0.0940128, 0, 0.486536, 0.87646, 0.0883462, 0, 0.503439, 0.875233, 0.0830924, 0, 0.520498, 0.8737, 0.0781975, 0, 0.537717, 0.871873, 0.07364, 0, 0.555102, 0.86978, 0.0694103, 0, 0.572657, 0.867405, 0.0654696, 0, 0.59039, 0.864751, 0.0617914, 0, 0.608307, 0.861818, 0.0583491, 0, 0.626419, 0.858645, 0.0551443, 0, 0.644733, 0.855307, 0.0521894, 0, 0.663264, 0.851736, 0.0494334, 0, 0.682025, 0.847927, 0.0468504, 0, 0.701032, 0.843888, 0.0444261, 0, 0.720308, 0.839629, 0.0421497, 0, 0.739875, 0.835158, 0.0400082, 0, 0.759764, 0.830509, 0.0380076, 0, 0.780014, 0.825714, 0.0361488, 0, 0.800673, 0.820729, 0.0343956, 0, 0.821803, 0.815751, 0.0327781, 0, 0.843492, 0.810752, 0.031275, 0, 0.86586, 0.805587, 0.0298542, 0, 0.889087, 0.800317, 0.0285397, 0, 0.913466, 0.79489, 0.0272948, 0, 0.93952, 0.789314, 0.0261139, 0, 0.96835, 0.783593, 0.0249938, 0, 1, 1, 0.724258, 0, 0, 0.999992, 0.724243, 0, 726889e-9, 0.99987, 0.724044, 0, 569574e-8, 0.999336, 0.72317, 0, 0.0131702, 0.996271, 0.719432, 0, 0.0220738, 0.991159, 0.712576, 0, 0.0319405, 0.982465, 0.700927, 0, 0.0425202, 0.97049, 0.684297, 0, 0.0536599, 0.953973, 0.661244, 0, 0.065258, 0.935546, 0.633804, 0, 0.0772427, 0.916596, 0.603071, 0, 0.0895616, 0.899353, 0.57105, 0, 0.102175, 0.885216, 0.539206, 0, 0.11505, 0.875076, 0.508714, 0, 0.128164, 0.868334, 0.479571, 0, 0.141495, 0.864414, 0.451796, 0, 0.155026, 0.862678, 0.425328, 0, 0.168745, 0.862835, 0.400352, 0, 0.182639, 0.864067, 0.376532, 0, 0.196699, 0.866086, 0.35391, 0, 0.210915, 0.868557, 0.332424, 0, 0.225282, 0.871271, 0.312053, 0, 0.239792, 0.874058, 0.292764, 0, 0.25444, 0.8768, 0.27453, 0, 0.269223, 0.87939, 0.257297, 0, 0.284135, 0.8819, 0.24114, 0, 0.299174, 0.884187, 0.225934, 0, 0.314337, 0.886262, 0.211669, 0, 0.329622, 0.888119, 0.198311, 0, 0.345026, 0.889709, 0.185783, 0, 0.360549, 0.891054, 0.174063, 0, 0.376189, 0.892196, 0.163143, 0, 0.391946, 0.893101, 0.152952, 0, 0.407819, 0.893803, 0.143475, 0, 0.423808, 0.894277, 0.134647, 0, 0.439914, 0.894532, 0.126434, 0, 0.456137, 0.894576, 0.1188, 0, 0.472479, 0.894393, 0.111694, 0, 0.48894, 0.893976, 0.105069, 0, 0.505523, 0.893346, 0.0989077, 0, 0.52223, 0.892502, 0.0931724, 0, 0.539064, 0.891441, 0.0878276, 0, 0.556028, 0.890276, 0.082903, 0, 0.573125, 0.888972, 0.0783505, 0, 0.590361, 0.887469, 0.0741083, 0, 0.607741, 0.885785, 0.0701633, 0, 0.62527, 0.883914, 0.0664835, 0, 0.642957, 0.881872, 0.0630567, 0, 0.660809, 0.879651, 0.0598527, 0, 0.678836, 0.877267, 0.0568615, 0, 0.69705, 0.874717, 0.05406, 0, 0.715465, 0.872012, 0.0514378, 0, 0.734098, 0.869157, 0.0489805, 0, 0.752968, 0.866155, 0.0466727, 0, 0.772101, 0.863014, 0.0445056, 0, 0.791529, 0.859748, 0.0424733, 0, 0.81129, 0.856416, 0.0405957, 0, 0.831438, 0.852958, 0.0388273, 0, 0.852044, 0.849382, 0.0371619, 0, 0.87321, 0.845694, 0.0355959, 0, 0.89509, 0.841893, 0.0341155, 0, 0.917932, 0.837981, 0.0327141, 0, 0.942204, 0.833963, 0.0313856, 0, 0.968981, 0.829847, 0.0301275, 0, 1, 1, 0.85214, 0, 0, 0.999969, 0.852095, 0, 279627e-8, 0.999483, 0.851408, 0, 0.0107635, 0.994545, 0.84579, 0, 0.0206454, 0.986188, 0.835231, 0, 0.0315756, 0.969847, 0.814687, 0, 0.0432021, 0.945951, 0.783735, 0, 0.0553396, 0.91917, 0.746074, 0, 0.0678766, 0.895488, 0.706938, 0, 0.0807395, 0.878232, 0.669534, 0, 0.0938767, 0.868252, 0.635168, 0, 0.10725, 0.863873, 0.603069, 0, 0.120832, 0.863369, 0.572514, 0, 0.134598, 0.86545, 0.543169, 0, 0.148533, 0.868803, 0.514578, 0, 0.16262, 0.872794, 0.486762, 0, 0.176849, 0.87702, 0.459811, 0, 0.19121, 0.881054, 0.433654, 0, 0.205694, 0.884974, 0.408574, 0, 0.220294, 0.888587, 0.384525, 0, 0.235005, 0.891877, 0.36156, 0, 0.24982, 0.894793, 0.339661, 0, 0.264737, 0.89743, 0.318913, 0, 0.279751, 0.899796, 0.299302, 0, 0.294859, 0.901943, 0.280843, 0, 0.310058, 0.903858, 0.263481, 0, 0.325346, 0.905574, 0.247197, 0, 0.340721, 0.907069, 0.231915, 0, 0.356181, 0.908379, 0.217614, 0, 0.371725, 0.90952, 0.20425, 0, 0.387353, 0.910483, 0.191758, 0, 0.403063, 0.91128, 0.180092, 0, 0.418854, 0.911936, 0.169222, 0, 0.434727, 0.912454, 0.159098, 0, 0.450682, 0.912835, 0.149668, 0, 0.466718, 0.913078, 0.140884, 0, 0.482837, 0.913192, 0.132709, 0, 0.499038, 0.913175, 0.125095, 0, 0.515324, 0.91304, 0.118012, 0, 0.531695, 0.912781, 0.111417, 0, 0.548153, 0.91241, 0.105281, 0, 0.5647, 0.911924, 0.0995691, 0, 0.581338, 0.911331, 0.0942531, 0, 0.59807, 0.910637, 0.0893076, 0, 0.6149, 0.90984, 0.0846998, 0, 0.63183, 0.908941, 0.0804044, 0, 0.648865, 0.907944, 0.0763984, 0, 0.666011, 0.906857, 0.0726638, 0, 0.683273, 0.90568, 0.0691783, 0, 0.700659, 0.904416, 0.0659222, 0, 0.718176, 0.903067, 0.0628782, 0, 0.735834, 0.901637, 0.0600307, 0, 0.753646, 0.900128, 0.0573647, 0, 0.771625, 0.898544, 0.0548668, 0, 0.78979, 0.89689, 0.052527, 0, 0.808162, 0.895165, 0.0503306, 0, 0.826771, 0.893371, 0.0482668, 0, 0.845654, 0.891572, 0.0463605, 0, 0.864863, 0.889763, 0.0445998, 0, 0.884472, 0.887894, 0.0429451, 0, 0.904592, 0.885967, 0.0413884, 0, 0.925407, 0.883984, 0.0399225, 0, 0.947271, 0.881945, 0.0385405, 0, 0.97105, 0.879854, 0.0372362, 0, 1, 0.999804, 0.995833, 0, 0, 0.938155, 0.933611, 0, 0.0158731, 0.864755, 0.854311, 0, 0.0317461, 0.888594, 0.865264, 0, 0.0476191, 0.905575, 0.863922, 0, 0.0634921, 0.915125, 0.850558, 0, 0.0793651, 0.920665, 0.829254, 0, 0.0952381, 0.924073, 0.802578, 0, 0.111111, 0.926304, 0.772211, 0, 0.126984, 0.927829, 0.739366, 0, 0.142857, 0.928924, 0.705033, 0, 0.15873, 0.92973, 0.670019, 0, 0.174603, 0.930339, 0.634993, 0, 0.190476, 0.930811, 0.600485, 0, 0.206349, 0.931191, 0.566897, 0, 0.222222, 0.93149, 0.534485, 0, 0.238095, 0.931737, 0.503429, 0, 0.253968, 0.931939, 0.473811, 0, 0.269841, 0.932108, 0.445668, 0, 0.285714, 0.93225, 0.418993, 0, 0.301587, 0.932371, 0.393762, 0, 0.31746, 0.932474, 0.369939, 0, 0.333333, 0.932562, 0.347479, 0, 0.349206, 0.932638, 0.326336, 0, 0.365079, 0.932703, 0.306462, 0, 0.380952, 0.93276, 0.287805, 0, 0.396825, 0.932809, 0.270313, 0, 0.412698, 0.932851, 0.253933, 0, 0.428571, 0.932887, 0.23861, 0, 0.444444, 0.932917, 0.224289, 0, 0.460317, 0.932943, 0.210917, 0, 0.47619, 0.932965, 0.19844, 0, 0.492063, 0.932982, 0.186807, 0, 0.507937, 0.932995, 0.175966, 0, 0.52381, 0.933005, 0.165869, 0, 0.539683, 0.933011, 0.156468, 0, 0.555556, 0.933013, 0.147719, 0, 0.571429, 0.933013, 0.139579, 0, 0.587302, 0.93301, 0.132007, 0, 0.603175, 0.933004, 0.124965, 0, 0.619048, 0.932994, 0.118416, 0, 0.634921, 0.932982, 0.112326, 0, 0.650794, 0.932968, 0.106663, 0, 0.666667, 0.93295, 0.101397, 0, 0.68254, 0.932931, 0.0964993, 0, 0.698413, 0.932908, 0.0919438, 0, 0.714286, 0.932883, 0.0877057, 0, 0.730159, 0.932856, 0.0837623, 0, 0.746032, 0.932827, 0.0800921, 0, 0.761905, 0.932796, 0.0766754, 0, 0.777778, 0.932762, 0.0734936, 0, 0.793651, 0.932727, 0.0705296, 0, 0.809524, 0.932689, 0.0677676, 0, 0.825397, 0.93265, 0.0651929, 0, 0.84127, 0.932609, 0.0627917, 0, 0.857143, 0.932565, 0.0605515, 0, 0.873016, 0.932521, 0.0584606, 0, 0.888889, 0.932474, 0.0565082, 0, 0.904762, 0.932427, 0.0546841, 0, 0.920635, 0.932377, 0.0529793, 0, 0.936508, 0.932326, 0.0513851, 0, 0.952381, 0.932274, 0.0498936, 0, 0.968254, 0.93222, 0.0484975, 0, 0.984127, 0.932164, 0.0471899, 0, 1];
    const ltc_float_1 = new Float32Array(LTC_MAT_1);
    const ltc_float_2 = new Float32Array(LTC_MAT_2);
    const LTC_FLOAT_1 = new DataTexture(ltc_float_1, 64, 64, RGBAFormat, FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1);
    const LTC_FLOAT_2 = new DataTexture(ltc_float_2, 64, 64, RGBAFormat, FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1);
    LTC_FLOAT_1.needsUpdate = true;
    LTC_FLOAT_2.needsUpdate = true;
    const ltc_half_1 = new Uint16Array(LTC_MAT_1.length);
    LTC_MAT_1.forEach(function(x2, index2) {
      ltc_half_1[index2] = DataUtils.toHalfFloat(x2);
    });
    const ltc_half_2 = new Uint16Array(LTC_MAT_2.length);
    LTC_MAT_2.forEach(function(x2, index2) {
      ltc_half_2[index2] = DataUtils.toHalfFloat(x2);
    });
    const LTC_HALF_1 = new DataTexture(ltc_half_1, 64, 64, RGBAFormat, HalfFloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1);
    const LTC_HALF_2 = new DataTexture(ltc_half_2, 64, 64, RGBAFormat, HalfFloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1);
    LTC_HALF_1.needsUpdate = true;
    LTC_HALF_2.needsUpdate = true;
    this.LTC_HALF_1 = LTC_HALF_1;
    this.LTC_HALF_2 = LTC_HALF_2;
    this.LTC_FLOAT_1 = LTC_FLOAT_1;
    this.LTC_FLOAT_2 = LTC_FLOAT_2;
    return this;
  }
};
RectAreaLightTexturesLib.LTC_HALF_1 = null;
RectAreaLightTexturesLib.LTC_HALF_2 = null;
RectAreaLightTexturesLib.LTC_FLOAT_1 = null;
RectAreaLightTexturesLib.LTC_FLOAT_2 = null;

// node_modules/three/examples/jsm/lights/RectAreaLightUniformsLib.js
var RectAreaLightUniformsLib = class {
  /**
   * Inits the uniform library required when using rect area lights.
   */
  static init() {
    RectAreaLightTexturesLib.init();
    const { LTC_FLOAT_1, LTC_FLOAT_2, LTC_HALF_1, LTC_HALF_2 } = RectAreaLightTexturesLib;
    UniformsLib.LTC_FLOAT_1 = LTC_FLOAT_1;
    UniformsLib.LTC_FLOAT_2 = LTC_FLOAT_2;
    UniformsLib.LTC_HALF_1 = LTC_HALF_1;
    UniformsLib.LTC_HALF_2 = LTC_HALF_2;
  }
};

// node_modules/three/examples/jsm/lines/LineSegmentsGeometry.js
var _box = new Box3();
var _vector3 = new Vector3();
var LineSegmentsGeometry = class extends InstancedBufferGeometry {
  /**
   * Constructs a new line segments geometry.
   */
  constructor() {
    super();
    this.isLineSegmentsGeometry = true;
    this.type = "LineSegmentsGeometry";
    const positions = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0];
    const uvs = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2];
    const index2 = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5];
    this.setIndex(index2);
    this.setAttribute("position", new Float32BufferAttribute(positions, 3));
    this.setAttribute("uv", new Float32BufferAttribute(uvs, 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(matrix2) {
    const start = this.attributes.instanceStart;
    const end = this.attributes.instanceEnd;
    if (start !== void 0) {
      start.applyMatrix4(matrix2);
      end.applyMatrix4(matrix2);
      start.needsUpdate = true;
    }
    if (this.boundingBox !== null) {
      this.computeBoundingBox();
    }
    if (this.boundingSphere !== null) {
      this.computeBoundingSphere();
    }
    return 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(array) {
    let lineSegments;
    if (array instanceof Float32Array) {
      lineSegments = array;
    } else if (Array.isArray(array)) {
      lineSegments = new Float32Array(array);
    }
    const instanceBuffer = new InstancedInterleavedBuffer(lineSegments, 6, 1);
    this.setAttribute("instanceStart", new InterleavedBufferAttribute(instanceBuffer, 3, 0));
    this.setAttribute("instanceEnd", new InterleavedBufferAttribute(instanceBuffer, 3, 3));
    this.instanceCount = this.attributes.instanceStart.count;
    this.computeBoundingBox();
    this.computeBoundingSphere();
    return 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(array) {
    let colors;
    if (array instanceof Float32Array) {
      colors = array;
    } else if (Array.isArray(array)) {
      colors = new Float32Array(array);
    }
    const instanceColorBuffer = new InstancedInterleavedBuffer(colors, 6, 1);
    this.setAttribute("instanceColorStart", new InterleavedBufferAttribute(instanceColorBuffer, 3, 0));
    this.setAttribute("instanceColorEnd", new InterleavedBufferAttribute(instanceColorBuffer, 3, 3));
    return 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(geometry) {
    this.setPositions(geometry.attributes.position.array);
    return 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(geometry) {
    this.setPositions(geometry.attributes.position.array);
    return 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(mesh) {
    this.fromWireframeGeometry(new WireframeGeometry(mesh.geometry));
    return 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(lineSegments) {
    const geometry = lineSegments.geometry;
    this.setPositions(geometry.attributes.position.array);
    return this;
  }
  computeBoundingBox() {
    if (this.boundingBox === null) {
      this.boundingBox = new Box3();
    }
    const start = this.attributes.instanceStart;
    const end = this.attributes.instanceEnd;
    if (start !== void 0 && end !== void 0) {
      this.boundingBox.setFromBufferAttribute(start);
      _box.setFromBufferAttribute(end);
      this.boundingBox.union(_box);
    }
  }
  computeBoundingSphere() {
    if (this.boundingSphere === null) {
      this.boundingSphere = new Sphere();
    }
    if (this.boundingBox === null) {
      this.computeBoundingBox();
    }
    const start = this.attributes.instanceStart;
    const end = this.attributes.instanceEnd;
    if (start !== void 0 && end !== void 0) {
      const center = this.boundingSphere.center;
      this.boundingBox.getCenter(center);
      let maxRadiusSq = 0;
      for (let i = 0, il = start.count; i < il; i++) {
        _vector3.fromBufferAttribute(start, i);
        maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector3));
        _vector3.fromBufferAttribute(end, i);
        maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector3));
      }
      this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
      if (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() {
  }
};

// node_modules/three/examples/jsm/lines/LineMaterial.js
UniformsLib.line = {
  worldUnits: { value: 1 },
  linewidth: { value: 1 },
  resolution: { value: new Vector2(1, 1) },
  dashOffset: { value: 0 },
  dashScale: { value: 1 },
  dashSize: { value: 1 },
  gapSize: { value: 1 }
  // todo FIX - maybe change to totalSize
};
ShaderLib["line"] = {
  uniforms: UniformsUtils.merge([
    UniformsLib.common,
    UniformsLib.fog,
    UniformsLib.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>

		}
		`
  )
};
var LineMaterial = class extends ShaderMaterial {
  /**
   * 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(parameters) {
    super({
      type: "LineMaterial",
      uniforms: UniformsUtils.clone(ShaderLib["line"].uniforms),
      vertexShader: ShaderLib["line"].vertexShader,
      fragmentShader: ShaderLib["line"].fragmentShader,
      clipping: true
      // required for clipping support
    });
    this.isLineMaterial = true;
    this.setValues(parameters);
  }
  /**
   * The material's color.
   *
   * @type {Color}
   * @default (1,1,1)
   */
  get color() {
    return this.uniforms.diffuse.value;
  }
  set color(value2) {
    this.uniforms.diffuse.value = value2;
  }
  /**
   * 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(value2) {
    if (value2 === true) {
      this.defines.WORLD_UNITS = "";
    } else {
      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(value2) {
    if (!this.uniforms.linewidth) return;
    this.uniforms.linewidth.value = value2;
  }
  /**
   * Whether the line is dashed, or solid.
   *
   * @type {boolean}
   * @default false
   */
  get dashed() {
    return "USE_DASH" in this.defines;
  }
  set dashed(value2) {
    if (value2 === true !== this.dashed) {
      this.needsUpdate = true;
    }
    if (value2 === true) {
      this.defines.USE_DASH = "";
    } else {
      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(value2) {
    this.uniforms.dashScale.value = value2;
  }
  /**
   * The size of the dash.
   *
   * @type {number}
   * @default 1
   */
  get dashSize() {
    return this.uniforms.dashSize.value;
  }
  set dashSize(value2) {
    this.uniforms.dashSize.value = value2;
  }
  /**
   * Where in the dash cycle the dash starts.
   *
   * @type {number}
   * @default 0
   */
  get dashOffset() {
    return this.uniforms.dashOffset.value;
  }
  set dashOffset(value2) {
    this.uniforms.dashOffset.value = value2;
  }
  /**
   * The size of the gap.
   *
   * @type {number}
   * @default 0
   */
  get gapSize() {
    return this.uniforms.gapSize.value;
  }
  set gapSize(value2) {
    this.uniforms.gapSize.value = value2;
  }
  /**
   * The opacity.
   *
   * @type {number}
   * @default 1
   */
  get opacity() {
    return this.uniforms.opacity.value;
  }
  set opacity(value2) {
    if (!this.uniforms) return;
    this.uniforms.opacity.value = value2;
  }
  /**
   * 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(value2) {
    this.uniforms.resolution.value.copy(value2);
  }
  /**
   * 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(value2) {
    if (!this.defines) return;
    if (value2 === true !== this.alphaToCoverage) {
      this.needsUpdate = true;
    }
    if (value2 === true) {
      this.defines.USE_ALPHA_TO_COVERAGE = "";
    } else {
      delete this.defines.USE_ALPHA_TO_COVERAGE;
    }
  }
};

// node_modules/three/examples/jsm/lines/LineSegments2.js
var _viewport = new Vector4();
var _start = new Vector3();
var _end = new Vector3();
var _start4 = new Vector4();
var _end4 = new Vector4();
var _ssOrigin = new Vector4();
var _ssOrigin3 = new Vector3();
var _mvMatrix = new Matrix4();
var _line = new Line3();
var _closestPoint2 = new Vector3();
var _box2 = new Box3();
var _sphere = new Sphere();
var _clipToWorldVector = new Vector4();
var _ray2;
var _lineWidth;
function getWorldSpaceHalfWidth(camera, distance, resolution) {
  _clipToWorldVector.set(0, 0, -distance, 1).applyMatrix4(camera.projectionMatrix);
  _clipToWorldVector.multiplyScalar(1 / _clipToWorldVector.w);
  _clipToWorldVector.x = _lineWidth / resolution.width;
  _clipToWorldVector.y = _lineWidth / resolution.height;
  _clipToWorldVector.applyMatrix4(camera.projectionMatrixInverse);
  _clipToWorldVector.multiplyScalar(1 / _clipToWorldVector.w);
  return Math.abs(Math.max(_clipToWorldVector.x, _clipToWorldVector.y));
}
function raycastWorldUnits(lineSegments, intersects) {
  const matrixWorld = lineSegments.matrixWorld;
  const geometry = lineSegments.geometry;
  const instanceStart = geometry.attributes.instanceStart;
  const instanceEnd = geometry.attributes.instanceEnd;
  const segmentCount = Math.min(geometry.instanceCount, instanceStart.count);
  for (let i = 0, l2 = segmentCount; i < l2; i++) {
    _line.start.fromBufferAttribute(instanceStart, i);
    _line.end.fromBufferAttribute(instanceEnd, i);
    _line.applyMatrix4(matrixWorld);
    const pointOnLine = new Vector3();
    const point = new Vector3();
    _ray2.distanceSqToSegment(_line.start, _line.end, point, pointOnLine);
    const isInside = point.distanceTo(pointOnLine) < _lineWidth * 0.5;
    if (isInside) {
      intersects.push({
        point,
        pointOnLine,
        distance: _ray2.origin.distanceTo(point),
        object: lineSegments,
        face: null,
        faceIndex: i,
        uv: null,
        uv1: null
      });
    }
  }
}
function raycastScreenSpace(lineSegments, camera, intersects) {
  const projectionMatrix = camera.projectionMatrix;
  const material = lineSegments.material;
  const resolution = material.resolution;
  const matrixWorld = lineSegments.matrixWorld;
  const geometry = lineSegments.geometry;
  const instanceStart = geometry.attributes.instanceStart;
  const instanceEnd = geometry.attributes.instanceEnd;
  const segmentCount = Math.min(geometry.instanceCount, instanceStart.count);
  const near = -camera.near;
  _ray2.at(1, _ssOrigin);
  _ssOrigin.w = 1;
  _ssOrigin.applyMatrix4(camera.matrixWorldInverse);
  _ssOrigin.applyMatrix4(projectionMatrix);
  _ssOrigin.multiplyScalar(1 / _ssOrigin.w);
  _ssOrigin.x *= resolution.x / 2;
  _ssOrigin.y *= resolution.y / 2;
  _ssOrigin.z = 0;
  _ssOrigin3.copy(_ssOrigin);
  _mvMatrix.multiplyMatrices(camera.matrixWorldInverse, matrixWorld);
  for (let i = 0, l2 = segmentCount; i < l2; i++) {
    _start4.fromBufferAttribute(instanceStart, i);
    _end4.fromBufferAttribute(instanceEnd, i);
    _start4.w = 1;
    _end4.w = 1;
    _start4.applyMatrix4(_mvMatrix);
    _end4.applyMatrix4(_mvMatrix);
    const isBehindCameraNear = _start4.z > near && _end4.z > near;
    if (isBehindCameraNear) {
      continue;
    }
    if (_start4.z > near) {
      const deltaDist = _start4.z - _end4.z;
      const t3 = (_start4.z - near) / deltaDist;
      _start4.lerp(_end4, t3);
    } else if (_end4.z > near) {
      const deltaDist = _end4.z - _start4.z;
      const t3 = (_end4.z - near) / deltaDist;
      _end4.lerp(_start4, t3);
    }
    _start4.applyMatrix4(projectionMatrix);
    _end4.applyMatrix4(projectionMatrix);
    _start4.multiplyScalar(1 / _start4.w);
    _end4.multiplyScalar(1 / _end4.w);
    _start4.x *= resolution.x / 2;
    _start4.y *= resolution.y / 2;
    _end4.x *= resolution.x / 2;
    _end4.y *= resolution.y / 2;
    _line.start.copy(_start4);
    _line.start.z = 0;
    _line.end.copy(_end4);
    _line.end.z = 0;
    const param = _line.closestPointToPointParameter(_ssOrigin3, true);
    _line.at(param, _closestPoint2);
    const zPos = MathUtils.lerp(_start4.z, _end4.z, param);
    const isInClipSpace = zPos >= -1 && zPos <= 1;
    const isInside = _ssOrigin3.distanceTo(_closestPoint2) < _lineWidth * 0.5;
    if (isInClipSpace && isInside) {
      _line.start.fromBufferAttribute(instanceStart, i);
      _line.end.fromBufferAttribute(instanceEnd, i);
      _line.start.applyMatrix4(matrixWorld);
      _line.end.applyMatrix4(matrixWorld);
      const pointOnLine = new Vector3();
      const point = new Vector3();
      _ray2.distanceSqToSegment(_line.start, _line.end, point, pointOnLine);
      intersects.push({
        point,
        pointOnLine,
        distance: _ray2.origin.distanceTo(point),
        object: lineSegments,
        face: null,
        faceIndex: i,
        uv: null,
        uv1: null
      });
    }
  }
}
var LineSegments2 = class extends Mesh {
  /**
   * Constructs a new wide line.
   *
   * @param {LineSegmentsGeometry} [geometry] - The line geometry.
   * @param {LineMaterial} [material] - The line material.
   */
  constructor(geometry = new LineSegmentsGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) {
    super(geometry, material);
    this.isLineSegments2 = true;
    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 geometry = this.geometry;
    const instanceStart = geometry.attributes.instanceStart;
    const instanceEnd = geometry.attributes.instanceEnd;
    const lineDistances = new Float32Array(2 * instanceStart.count);
    for (let i = 0, j2 = 0, l2 = instanceStart.count; i < l2; i++, j2 += 2) {
      _start.fromBufferAttribute(instanceStart, i);
      _end.fromBufferAttribute(instanceEnd, i);
      lineDistances[j2] = j2 === 0 ? 0 : lineDistances[j2 - 1];
      lineDistances[j2 + 1] = lineDistances[j2] + _start.distanceTo(_end);
    }
    const instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1);
    geometry.setAttribute("instanceDistanceStart", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0));
    geometry.setAttribute("instanceDistanceEnd", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1));
    return 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(raycaster, intersects) {
    const worldUnits = this.material.worldUnits;
    const camera = raycaster.camera;
    if (camera === null && !worldUnits) {
      console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');
    }
    const threshold = raycaster.params.Line2 !== void 0 ? raycaster.params.Line2.threshold || 0 : 0;
    _ray2 = raycaster.ray;
    const matrixWorld = this.matrixWorld;
    const geometry = this.geometry;
    const material = this.material;
    _lineWidth = material.linewidth + threshold;
    if (geometry.boundingSphere === null) {
      geometry.computeBoundingSphere();
    }
    _sphere.copy(geometry.boundingSphere).applyMatrix4(matrixWorld);
    let sphereMargin;
    if (worldUnits) {
      sphereMargin = _lineWidth * 0.5;
    } else {
      const distanceToSphere = Math.max(camera.near, _sphere.distanceToPoint(_ray2.origin));
      sphereMargin = getWorldSpaceHalfWidth(camera, distanceToSphere, material.resolution);
    }
    _sphere.radius += sphereMargin;
    if (_ray2.intersectsSphere(_sphere) === false) {
      return;
    }
    if (geometry.boundingBox === null) {
      geometry.computeBoundingBox();
    }
    _box2.copy(geometry.boundingBox).applyMatrix4(matrixWorld);
    let boxMargin;
    if (worldUnits) {
      boxMargin = _lineWidth * 0.5;
    } else {
      const distanceToBox = Math.max(camera.near, _box2.distanceToPoint(_ray2.origin));
      boxMargin = getWorldSpaceHalfWidth(camera, distanceToBox, material.resolution);
    }
    _box2.expandByScalar(boxMargin);
    if (_ray2.intersectsBox(_box2) === false) {
      return;
    }
    if (worldUnits) {
      raycastWorldUnits(this, intersects);
    } else {
      raycastScreenSpace(this, camera, intersects);
    }
  }
  onBeforeRender(renderer2) {
    const uniforms = this.material.uniforms;
    if (uniforms && uniforms.resolution) {
      renderer2.getViewport(_viewport);
      this.material.uniforms.resolution.value.set(_viewport.z, _viewport.w);
    }
  }
};

// node_modules/three/examples/jsm/lines/LineGeometry.js
var LineGeometry = class extends LineSegmentsGeometry {
  /**
   * Constructs a new line geometry.
   */
  constructor() {
    super();
    this.isLineGeometry = true;
    this.type = "LineGeometry";
  }
  /**
   * Sets the given line positions for this geometry.
   *
   * @param {Float32Array|Array<number>} array - The position data to set.
   * @return {LineGeometry} A reference to this geometry.
   */
  setPositions(array) {
    const length2 = array.length - 3;
    const points = new Float32Array(2 * length2);
    for (let i = 0; i < length2; i += 3) {
      points[2 * i] = array[i];
      points[2 * i + 1] = array[i + 1];
      points[2 * i + 2] = array[i + 2];
      points[2 * i + 3] = array[i + 3];
      points[2 * i + 4] = array[i + 4];
      points[2 * i + 5] = array[i + 5];
    }
    super.setPositions(points);
    return this;
  }
  /**
   * Sets the given line colors for this geometry.
   *
   * @param {Float32Array|Array<number>} array - The position data to set.
   * @return {LineGeometry} A reference to this geometry.
   */
  setColors(array) {
    const length2 = array.length - 3;
    const colors = new Float32Array(2 * length2);
    for (let i = 0; i < length2; i += 3) {
      colors[2 * i] = array[i];
      colors[2 * i + 1] = array[i + 1];
      colors[2 * i + 2] = array[i + 2];
      colors[2 * i + 3] = array[i + 3];
      colors[2 * i + 4] = array[i + 4];
      colors[2 * i + 5] = array[i + 5];
    }
    super.setColors(colors);
    return this;
  }
  /**
   * Setups this line segments geometry from the given sequence of points.
   *
   * @param {Array<Vector3|Vector2>} points - An array of points in 2D or 3D space.
   * @return {LineGeometry} A reference to this geometry.
   */
  setFromPoints(points) {
    const length2 = points.length - 1;
    const positions = new Float32Array(6 * length2);
    for (let i = 0; i < length2; i++) {
      positions[6 * i] = points[i].x;
      positions[6 * i + 1] = points[i].y;
      positions[6 * i + 2] = points[i].z || 0;
      positions[6 * i + 3] = points[i + 1].x;
      positions[6 * i + 4] = points[i + 1].y;
      positions[6 * i + 5] = points[i + 1].z || 0;
    }
    super.setPositions(positions);
    return this;
  }
  /**
   * Setups this line segments geometry from the given line.
   *
   * @param {Line} line - The line that should be used as a data source for this geometry.
   * @return {LineGeometry} A reference to this geometry.
   */
  fromLine(line2) {
    const geometry = line2.geometry;
    this.setPositions(geometry.attributes.position.array);
    return this;
  }
};

// node_modules/three/examples/jsm/lines/Line2.js
var Line2 = class extends LineSegments2 {
  /**
   * Constructs a new wide line.
   *
   * @param {LineGeometry} [geometry] - The line geometry.
   * @param {LineMaterial} [material] - The line material.
   */
  constructor(geometry = new LineGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) {
    super(geometry, material);
    this.isLine2 = true;
    this.type = "Line2";
  }
};

// node_modules/three/examples/jsm/lines/Wireframe.js
var _start2 = new Vector3();
var _end2 = new Vector3();
var _viewport2 = new Vector4();
var Wireframe = class extends Mesh {
  /**
   * Constructs a new wireframe.
   *
   * @param {LineSegmentsGeometry} [geometry] - The line geometry.
   * @param {LineMaterial} [material] - The line material.
   */
  constructor(geometry = new LineSegmentsGeometry(), material = new LineMaterial({ color: Math.random() * 16777215 })) {
    super(geometry, material);
    this.isWireframe = true;
    this.type = "Wireframe";
  }
  /**
   * 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 {Wireframe} A reference to this instance.
   */
  computeLineDistances() {
    const geometry = this.geometry;
    const instanceStart = geometry.attributes.instanceStart;
    const instanceEnd = geometry.attributes.instanceEnd;
    const lineDistances = new Float32Array(2 * instanceStart.count);
    for (let i = 0, j2 = 0, l2 = instanceStart.count; i < l2; i++, j2 += 2) {
      _start2.fromBufferAttribute(instanceStart, i);
      _end2.fromBufferAttribute(instanceEnd, i);
      lineDistances[j2] = j2 === 0 ? 0 : lineDistances[j2 - 1];
      lineDistances[j2 + 1] = lineDistances[j2] + _start2.distanceTo(_end2);
    }
    const instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1);
    geometry.setAttribute("instanceDistanceStart", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0));
    geometry.setAttribute("instanceDistanceEnd", new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1));
    return this;
  }
  onBeforeRender(renderer2) {
    const uniforms = this.material.uniforms;
    if (uniforms && uniforms.resolution) {
      renderer2.getViewport(_viewport2);
      this.material.uniforms.resolution.value.set(_viewport2.z, _viewport2.w);
    }
  }
};

// node_modules/three/examples/jsm/lines/WireframeGeometry2.js
var WireframeGeometry2 = class extends LineSegmentsGeometry {
  /**
   * Constructs a new wireframe geometry.
   *
   * @param {BufferGeometry} [geometry] - The geometry to render the wireframe for.
   */
  constructor(geometry) {
    super();
    this.isWireframeGeometry2 = true;
    this.type = "WireframeGeometry2";
    this.fromWireframeGeometry(new WireframeGeometry(geometry));
  }
};

// node_modules/three/examples/jsm/loaders/EXRLoader.js
var EXRLoader = class extends DataTextureLoader {
  /**
   * Constructs a new EXR loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.type = HalfFloatType;
  }
  /**
   * Parses the given EXR texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @return {DataTextureLoader~TexData} An object representing the parsed texture data.
   */
  parse(buffer) {
    const USHORT_RANGE = 1 << 16;
    const BITMAP_SIZE = USHORT_RANGE >> 3;
    const HUF_ENCBITS = 16;
    const HUF_DECBITS = 14;
    const HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1;
    const HUF_DECSIZE = 1 << HUF_DECBITS;
    const HUF_DECMASK = HUF_DECSIZE - 1;
    const NBITS = 16;
    const A_OFFSET = 1 << NBITS - 1;
    const MOD_MASK = (1 << NBITS) - 1;
    const SHORT_ZEROCODE_RUN = 59;
    const LONG_ZEROCODE_RUN = 63;
    const SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
    const ULONG_SIZE = 8;
    const FLOAT32_SIZE = 4;
    const INT32_SIZE = 4;
    const INT16_SIZE = 2;
    const INT8_SIZE = 1;
    const STATIC_HUFFMAN = 0;
    const DEFLATE = 1;
    const UNKNOWN = 0;
    const LOSSY_DCT = 1;
    const RLE = 2;
    const logBase = Math.pow(2.7182818, 2.2);
    function reverseLutFromBitmap(bitmap, lut) {
      let k2 = 0;
      for (let i = 0; i < USHORT_RANGE; ++i) {
        if (i == 0 || bitmap[i >> 3] & 1 << (i & 7)) {
          lut[k2++] = i;
        }
      }
      const n2 = k2 - 1;
      while (k2 < USHORT_RANGE) lut[k2++] = 0;
      return n2;
    }
    function hufClearDecTable(hdec) {
      for (let i = 0; i < HUF_DECSIZE; i++) {
        hdec[i] = {};
        hdec[i].len = 0;
        hdec[i].lit = 0;
        hdec[i].p = null;
      }
    }
    const getBitsReturn = { l: 0, c: 0, lc: 0 };
    function getBits(nBits, c2, lc2, uInt8Array2, inOffset) {
      while (lc2 < nBits) {
        c2 = c2 << 8 | parseUint8Array(uInt8Array2, inOffset);
        lc2 += 8;
      }
      lc2 -= nBits;
      getBitsReturn.l = c2 >> lc2 & (1 << nBits) - 1;
      getBitsReturn.c = c2;
      getBitsReturn.lc = lc2;
    }
    const hufTableBuffer = new Array(59);
    function hufCanonicalCodeTable(hcode) {
      for (let i = 0; i <= 58; ++i) hufTableBuffer[i] = 0;
      for (let i = 0; i < HUF_ENCSIZE; ++i) hufTableBuffer[hcode[i]] += 1;
      let c2 = 0;
      for (let i = 58; i > 0; --i) {
        const nc = c2 + hufTableBuffer[i] >> 1;
        hufTableBuffer[i] = c2;
        c2 = nc;
      }
      for (let i = 0; i < HUF_ENCSIZE; ++i) {
        const l2 = hcode[i];
        if (l2 > 0) hcode[i] = l2 | hufTableBuffer[l2]++ << 6;
      }
    }
    function hufUnpackEncTable(uInt8Array2, inOffset, ni, im, iM, hcode) {
      const p = inOffset;
      let c2 = 0;
      let lc2 = 0;
      for (; im <= iM; im++) {
        if (p.value - inOffset.value > ni) return false;
        getBits(6, c2, lc2, uInt8Array2, p);
        const l2 = getBitsReturn.l;
        c2 = getBitsReturn.c;
        lc2 = getBitsReturn.lc;
        hcode[im] = l2;
        if (l2 == LONG_ZEROCODE_RUN) {
          if (p.value - inOffset.value > ni) {
            throw new Error("Something wrong with hufUnpackEncTable");
          }
          getBits(8, c2, lc2, uInt8Array2, p);
          let zerun = getBitsReturn.l + SHORTEST_LONG_RUN;
          c2 = getBitsReturn.c;
          lc2 = getBitsReturn.lc;
          if (im + zerun > iM + 1) {
            throw new Error("Something wrong with hufUnpackEncTable");
          }
          while (zerun--) hcode[im++] = 0;
          im--;
        } else if (l2 >= SHORT_ZEROCODE_RUN) {
          let zerun = l2 - SHORT_ZEROCODE_RUN + 2;
          if (im + zerun > iM + 1) {
            throw new Error("Something wrong with hufUnpackEncTable");
          }
          while (zerun--) hcode[im++] = 0;
          im--;
        }
      }
      hufCanonicalCodeTable(hcode);
    }
    function hufLength(code) {
      return code & 63;
    }
    function hufCode(code) {
      return code >> 6;
    }
    function hufBuildDecTable(hcode, im, iM, hdecod) {
      for (; im <= iM; im++) {
        const c2 = hufCode(hcode[im]);
        const l2 = hufLength(hcode[im]);
        if (c2 >> l2) {
          throw new Error("Invalid table entry");
        }
        if (l2 > HUF_DECBITS) {
          const pl = hdecod[c2 >> l2 - HUF_DECBITS];
          if (pl.len) {
            throw new Error("Invalid table entry");
          }
          pl.lit++;
          if (pl.p) {
            const p = pl.p;
            pl.p = new Array(pl.lit);
            for (let i = 0; i < pl.lit - 1; ++i) {
              pl.p[i] = p[i];
            }
          } else {
            pl.p = new Array(1);
          }
          pl.p[pl.lit - 1] = im;
        } else if (l2) {
          let plOffset = 0;
          for (let i = 1 << HUF_DECBITS - l2; i > 0; i--) {
            const pl = hdecod[(c2 << HUF_DECBITS - l2) + plOffset];
            if (pl.len || pl.p) {
              throw new Error("Invalid table entry");
            }
            pl.len = l2;
            pl.lit = im;
            plOffset++;
          }
        }
      }
      return true;
    }
    const getCharReturn = { c: 0, lc: 0 };
    function getChar(c2, lc2, uInt8Array2, inOffset) {
      c2 = c2 << 8 | parseUint8Array(uInt8Array2, inOffset);
      lc2 += 8;
      getCharReturn.c = c2;
      getCharReturn.lc = lc2;
    }
    const getCodeReturn = { c: 0, lc: 0 };
    function getCode(po, rlc, c2, lc2, uInt8Array2, inOffset, outBuffer, outBufferOffset, outBufferEndOffset) {
      if (po == rlc) {
        if (lc2 < 8) {
          getChar(c2, lc2, uInt8Array2, inOffset);
          c2 = getCharReturn.c;
          lc2 = getCharReturn.lc;
        }
        lc2 -= 8;
        let cs = c2 >> lc2;
        cs = new Uint8Array([cs])[0];
        if (outBufferOffset.value + cs > outBufferEndOffset) {
          return false;
        }
        const s = outBuffer[outBufferOffset.value - 1];
        while (cs-- > 0) {
          outBuffer[outBufferOffset.value++] = s;
        }
      } else if (outBufferOffset.value < outBufferEndOffset) {
        outBuffer[outBufferOffset.value++] = po;
      } else {
        return false;
      }
      getCodeReturn.c = c2;
      getCodeReturn.lc = lc2;
    }
    function UInt16(value2) {
      return value2 & 65535;
    }
    function Int16(value2) {
      const ref = UInt16(value2);
      return ref > 32767 ? ref - 65536 : ref;
    }
    const wdec14Return = { a: 0, b: 0 };
    function wdec14(l2, h) {
      const ls = Int16(l2);
      const hs = Int16(h);
      const hi = hs;
      const ai = ls + (hi & 1) + (hi >> 1);
      const as = ai;
      const bs = ai - hi;
      wdec14Return.a = as;
      wdec14Return.b = bs;
    }
    function wdec16(l2, h) {
      const m = UInt16(l2);
      const d = UInt16(h);
      const bb = m - (d >> 1) & MOD_MASK;
      const aa = d + bb - A_OFFSET & MOD_MASK;
      wdec14Return.a = aa;
      wdec14Return.b = bb;
    }
    function wav2Decode(buffer2, j2, nx, ox, ny, oy, mx) {
      const w14 = mx < 1 << 14;
      const n2 = nx > ny ? ny : nx;
      let p = 1;
      let p2;
      let py;
      while (p <= n2) p <<= 1;
      p >>= 1;
      p2 = p;
      p >>= 1;
      while (p >= 1) {
        py = 0;
        const ey = py + oy * (ny - p2);
        const oy1 = oy * p;
        const oy2 = oy * p2;
        const ox1 = ox * p;
        const ox2 = ox * p2;
        let i00, i01, i10, i11;
        for (; py <= ey; py += oy2) {
          let px = py;
          const ex = py + ox * (nx - p2);
          for (; px <= ex; px += ox2) {
            const p01 = px + ox1;
            const p10 = px + oy1;
            const p11 = p10 + ox1;
            if (w14) {
              wdec14(buffer2[px + j2], buffer2[p10 + j2]);
              i00 = wdec14Return.a;
              i10 = wdec14Return.b;
              wdec14(buffer2[p01 + j2], buffer2[p11 + j2]);
              i01 = wdec14Return.a;
              i11 = wdec14Return.b;
              wdec14(i00, i01);
              buffer2[px + j2] = wdec14Return.a;
              buffer2[p01 + j2] = wdec14Return.b;
              wdec14(i10, i11);
              buffer2[p10 + j2] = wdec14Return.a;
              buffer2[p11 + j2] = wdec14Return.b;
            } else {
              wdec16(buffer2[px + j2], buffer2[p10 + j2]);
              i00 = wdec14Return.a;
              i10 = wdec14Return.b;
              wdec16(buffer2[p01 + j2], buffer2[p11 + j2]);
              i01 = wdec14Return.a;
              i11 = wdec14Return.b;
              wdec16(i00, i01);
              buffer2[px + j2] = wdec14Return.a;
              buffer2[p01 + j2] = wdec14Return.b;
              wdec16(i10, i11);
              buffer2[p10 + j2] = wdec14Return.a;
              buffer2[p11 + j2] = wdec14Return.b;
            }
          }
          if (nx & p) {
            const p10 = px + oy1;
            if (w14)
              wdec14(buffer2[px + j2], buffer2[p10 + j2]);
            else
              wdec16(buffer2[px + j2], buffer2[p10 + j2]);
            i00 = wdec14Return.a;
            buffer2[p10 + j2] = wdec14Return.b;
            buffer2[px + j2] = i00;
          }
        }
        if (ny & p) {
          let px = py;
          const ex = py + ox * (nx - p2);
          for (; px <= ex; px += ox2) {
            const p01 = px + ox1;
            if (w14)
              wdec14(buffer2[px + j2], buffer2[p01 + j2]);
            else
              wdec16(buffer2[px + j2], buffer2[p01 + j2]);
            i00 = wdec14Return.a;
            buffer2[p01 + j2] = wdec14Return.b;
            buffer2[px + j2] = i00;
          }
        }
        p2 = p;
        p >>= 1;
      }
      return py;
    }
    function hufDecode(encodingTable, decodingTable, uInt8Array2, inOffset, ni, rlc, no, outBuffer, outOffset) {
      let c2 = 0;
      let lc2 = 0;
      const outBufferEndOffset = no;
      const inOffsetEnd = Math.trunc(inOffset.value + (ni + 7) / 8);
      while (inOffset.value < inOffsetEnd) {
        getChar(c2, lc2, uInt8Array2, inOffset);
        c2 = getCharReturn.c;
        lc2 = getCharReturn.lc;
        while (lc2 >= HUF_DECBITS) {
          const index2 = c2 >> lc2 - HUF_DECBITS & HUF_DECMASK;
          const pl = decodingTable[index2];
          if (pl.len) {
            lc2 -= pl.len;
            getCode(pl.lit, rlc, c2, lc2, uInt8Array2, inOffset, outBuffer, outOffset, outBufferEndOffset);
            c2 = getCodeReturn.c;
            lc2 = getCodeReturn.lc;
          } else {
            if (!pl.p) {
              throw new Error("hufDecode issues");
            }
            let j2;
            for (j2 = 0; j2 < pl.lit; j2++) {
              const l2 = hufLength(encodingTable[pl.p[j2]]);
              while (lc2 < l2 && inOffset.value < inOffsetEnd) {
                getChar(c2, lc2, uInt8Array2, inOffset);
                c2 = getCharReturn.c;
                lc2 = getCharReturn.lc;
              }
              if (lc2 >= l2) {
                if (hufCode(encodingTable[pl.p[j2]]) == (c2 >> lc2 - l2 & (1 << l2) - 1)) {
                  lc2 -= l2;
                  getCode(pl.p[j2], rlc, c2, lc2, uInt8Array2, inOffset, outBuffer, outOffset, outBufferEndOffset);
                  c2 = getCodeReturn.c;
                  lc2 = getCodeReturn.lc;
                  break;
                }
              }
            }
            if (j2 == pl.lit) {
              throw new Error("hufDecode issues");
            }
          }
        }
      }
      const i = 8 - ni & 7;
      c2 >>= i;
      lc2 -= i;
      while (lc2 > 0) {
        const pl = decodingTable[c2 << HUF_DECBITS - lc2 & HUF_DECMASK];
        if (pl.len) {
          lc2 -= pl.len;
          getCode(pl.lit, rlc, c2, lc2, uInt8Array2, inOffset, outBuffer, outOffset, outBufferEndOffset);
          c2 = getCodeReturn.c;
          lc2 = getCodeReturn.lc;
        } else {
          throw new Error("hufDecode issues");
        }
      }
      return true;
    }
    function hufUncompress(uInt8Array2, inDataView, inOffset, nCompressed, outBuffer, nRaw) {
      const outOffset = { value: 0 };
      const initialInOffset = inOffset.value;
      const im = parseUint32(inDataView, inOffset);
      const iM = parseUint32(inDataView, inOffset);
      inOffset.value += 4;
      const nBits = parseUint32(inDataView, inOffset);
      inOffset.value += 4;
      if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) {
        throw new Error("Something wrong with HUF_ENCSIZE");
      }
      const freq = new Array(HUF_ENCSIZE);
      const hdec = new Array(HUF_DECSIZE);
      hufClearDecTable(hdec);
      const ni = nCompressed - (inOffset.value - initialInOffset);
      hufUnpackEncTable(uInt8Array2, inOffset, ni, im, iM, freq);
      if (nBits > 8 * (nCompressed - (inOffset.value - initialInOffset))) {
        throw new Error("Something wrong with hufUncompress");
      }
      hufBuildDecTable(freq, im, iM, hdec);
      hufDecode(freq, hdec, uInt8Array2, inOffset, nBits, iM, nRaw, outBuffer, outOffset);
    }
    function applyLut(lut, data2, nData) {
      for (let i = 0; i < nData; ++i) {
        data2[i] = lut[data2[i]];
      }
    }
    function predictor(source) {
      for (let t3 = 1; t3 < source.length; t3++) {
        const d = source[t3 - 1] + source[t3] - 128;
        source[t3] = d;
      }
    }
    function interleaveScalar(source, out) {
      let t1 = 0;
      let t22 = Math.floor((source.length + 1) / 2);
      let s = 0;
      const stop = source.length - 1;
      while (true) {
        if (s > stop) break;
        out[s++] = source[t1++];
        if (s > stop) break;
        out[s++] = source[t22++];
      }
    }
    function decodeRunLength(source) {
      let size2 = source.byteLength;
      const out = new Array();
      let p = 0;
      const reader = new DataView(source);
      while (size2 > 0) {
        const l2 = reader.getInt8(p++);
        if (l2 < 0) {
          const count = -l2;
          size2 -= count + 1;
          for (let i = 0; i < count; i++) {
            out.push(reader.getUint8(p++));
          }
        } else {
          const count = l2;
          size2 -= 2;
          const value2 = reader.getUint8(p++);
          for (let i = 0; i < count + 1; i++) {
            out.push(value2);
          }
        }
      }
      return out;
    }
    function lossyDctDecode(cscSet, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer) {
      let dataView = new DataView(outBuffer.buffer);
      const width2 = channelData[cscSet.idx[0]].width;
      const height2 = channelData[cscSet.idx[0]].height;
      const numComp = 3;
      const numFullBlocksX = Math.floor(width2 / 8);
      const numBlocksX = Math.ceil(width2 / 8);
      const numBlocksY = Math.ceil(height2 / 8);
      const leftoverX = width2 - (numBlocksX - 1) * 8;
      const leftoverY = height2 - (numBlocksY - 1) * 8;
      const currAcComp = { value: 0 };
      const currDcComp = new Array(numComp);
      const dctData = new Array(numComp);
      const halfZigBlock = new Array(numComp);
      const rowBlock = new Array(numComp);
      const rowOffsets = new Array(numComp);
      for (let comp2 = 0; comp2 < numComp; ++comp2) {
        rowOffsets[comp2] = rowPtrs[cscSet.idx[comp2]];
        currDcComp[comp2] = comp2 < 1 ? 0 : currDcComp[comp2 - 1] + numBlocksX * numBlocksY;
        dctData[comp2] = new Float32Array(64);
        halfZigBlock[comp2] = new Uint16Array(64);
        rowBlock[comp2] = new Uint16Array(numBlocksX * 64);
      }
      for (let blocky = 0; blocky < numBlocksY; ++blocky) {
        let maxY = 8;
        if (blocky == numBlocksY - 1)
          maxY = leftoverY;
        let maxX = 8;
        for (let blockx = 0; blockx < numBlocksX; ++blockx) {
          if (blockx == numBlocksX - 1)
            maxX = leftoverX;
          for (let comp2 = 0; comp2 < numComp; ++comp2) {
            halfZigBlock[comp2].fill(0);
            halfZigBlock[comp2][0] = dcBuffer[currDcComp[comp2]++];
            unRleAC(currAcComp, acBuffer, halfZigBlock[comp2]);
            unZigZag(halfZigBlock[comp2], dctData[comp2]);
            dctInverse(dctData[comp2]);
          }
          if (numComp == 3) {
            csc709Inverse(dctData);
          }
          for (let comp2 = 0; comp2 < numComp; ++comp2) {
            convertToHalf(dctData[comp2], rowBlock[comp2], blockx * 64);
          }
        }
        let offset2 = 0;
        for (let comp2 = 0; comp2 < numComp; ++comp2) {
          const type = channelData[cscSet.idx[comp2]].type;
          for (let y = 8 * blocky; y < 8 * blocky + maxY; ++y) {
            offset2 = rowOffsets[comp2][y];
            for (let blockx = 0; blockx < numFullBlocksX; ++blockx) {
              const src = blockx * 64 + (y & 7) * 8;
              dataView.setUint16(offset2 + 0 * INT16_SIZE * type, rowBlock[comp2][src + 0], true);
              dataView.setUint16(offset2 + 1 * INT16_SIZE * type, rowBlock[comp2][src + 1], true);
              dataView.setUint16(offset2 + 2 * INT16_SIZE * type, rowBlock[comp2][src + 2], true);
              dataView.setUint16(offset2 + 3 * INT16_SIZE * type, rowBlock[comp2][src + 3], true);
              dataView.setUint16(offset2 + 4 * INT16_SIZE * type, rowBlock[comp2][src + 4], true);
              dataView.setUint16(offset2 + 5 * INT16_SIZE * type, rowBlock[comp2][src + 5], true);
              dataView.setUint16(offset2 + 6 * INT16_SIZE * type, rowBlock[comp2][src + 6], true);
              dataView.setUint16(offset2 + 7 * INT16_SIZE * type, rowBlock[comp2][src + 7], true);
              offset2 += 8 * INT16_SIZE * type;
            }
          }
          if (numFullBlocksX != numBlocksX) {
            for (let y = 8 * blocky; y < 8 * blocky + maxY; ++y) {
              const offset3 = rowOffsets[comp2][y] + 8 * numFullBlocksX * INT16_SIZE * type;
              const src = numFullBlocksX * 64 + (y & 7) * 8;
              for (let x2 = 0; x2 < maxX; ++x2) {
                dataView.setUint16(offset3 + x2 * INT16_SIZE * type, rowBlock[comp2][src + x2], true);
              }
            }
          }
        }
      }
      const halfRow = new Uint16Array(width2);
      dataView = new DataView(outBuffer.buffer);
      for (let comp2 = 0; comp2 < numComp; ++comp2) {
        channelData[cscSet.idx[comp2]].decoded = true;
        const type = channelData[cscSet.idx[comp2]].type;
        if (channelData[comp2].type != 2) continue;
        for (let y = 0; y < height2; ++y) {
          const offset2 = rowOffsets[comp2][y];
          for (let x2 = 0; x2 < width2; ++x2) {
            halfRow[x2] = dataView.getUint16(offset2 + x2 * INT16_SIZE * type, true);
          }
          for (let x2 = 0; x2 < width2; ++x2) {
            dataView.setFloat32(offset2 + x2 * INT16_SIZE * type, decodeFloat162(halfRow[x2]), true);
          }
        }
      }
    }
    function unRleAC(currAcComp, acBuffer, halfZigBlock) {
      let acValue;
      let dctComp = 1;
      while (dctComp < 64) {
        acValue = acBuffer[currAcComp.value];
        if (acValue == 65280) {
          dctComp = 64;
        } else if (acValue >> 8 == 255) {
          dctComp += acValue & 255;
        } else {
          halfZigBlock[dctComp] = acValue;
          dctComp++;
        }
        currAcComp.value++;
      }
    }
    function unZigZag(src, dst) {
      dst[0] = decodeFloat162(src[0]);
      dst[1] = decodeFloat162(src[1]);
      dst[2] = decodeFloat162(src[5]);
      dst[3] = decodeFloat162(src[6]);
      dst[4] = decodeFloat162(src[14]);
      dst[5] = decodeFloat162(src[15]);
      dst[6] = decodeFloat162(src[27]);
      dst[7] = decodeFloat162(src[28]);
      dst[8] = decodeFloat162(src[2]);
      dst[9] = decodeFloat162(src[4]);
      dst[10] = decodeFloat162(src[7]);
      dst[11] = decodeFloat162(src[13]);
      dst[12] = decodeFloat162(src[16]);
      dst[13] = decodeFloat162(src[26]);
      dst[14] = decodeFloat162(src[29]);
      dst[15] = decodeFloat162(src[42]);
      dst[16] = decodeFloat162(src[3]);
      dst[17] = decodeFloat162(src[8]);
      dst[18] = decodeFloat162(src[12]);
      dst[19] = decodeFloat162(src[17]);
      dst[20] = decodeFloat162(src[25]);
      dst[21] = decodeFloat162(src[30]);
      dst[22] = decodeFloat162(src[41]);
      dst[23] = decodeFloat162(src[43]);
      dst[24] = decodeFloat162(src[9]);
      dst[25] = decodeFloat162(src[11]);
      dst[26] = decodeFloat162(src[18]);
      dst[27] = decodeFloat162(src[24]);
      dst[28] = decodeFloat162(src[31]);
      dst[29] = decodeFloat162(src[40]);
      dst[30] = decodeFloat162(src[44]);
      dst[31] = decodeFloat162(src[53]);
      dst[32] = decodeFloat162(src[10]);
      dst[33] = decodeFloat162(src[19]);
      dst[34] = decodeFloat162(src[23]);
      dst[35] = decodeFloat162(src[32]);
      dst[36] = decodeFloat162(src[39]);
      dst[37] = decodeFloat162(src[45]);
      dst[38] = decodeFloat162(src[52]);
      dst[39] = decodeFloat162(src[54]);
      dst[40] = decodeFloat162(src[20]);
      dst[41] = decodeFloat162(src[22]);
      dst[42] = decodeFloat162(src[33]);
      dst[43] = decodeFloat162(src[38]);
      dst[44] = decodeFloat162(src[46]);
      dst[45] = decodeFloat162(src[51]);
      dst[46] = decodeFloat162(src[55]);
      dst[47] = decodeFloat162(src[60]);
      dst[48] = decodeFloat162(src[21]);
      dst[49] = decodeFloat162(src[34]);
      dst[50] = decodeFloat162(src[37]);
      dst[51] = decodeFloat162(src[47]);
      dst[52] = decodeFloat162(src[50]);
      dst[53] = decodeFloat162(src[56]);
      dst[54] = decodeFloat162(src[59]);
      dst[55] = decodeFloat162(src[61]);
      dst[56] = decodeFloat162(src[35]);
      dst[57] = decodeFloat162(src[36]);
      dst[58] = decodeFloat162(src[48]);
      dst[59] = decodeFloat162(src[49]);
      dst[60] = decodeFloat162(src[57]);
      dst[61] = decodeFloat162(src[58]);
      dst[62] = decodeFloat162(src[62]);
      dst[63] = decodeFloat162(src[63]);
    }
    function dctInverse(data2) {
      const a2 = 0.5 * Math.cos(3.14159 / 4);
      const b3 = 0.5 * Math.cos(3.14159 / 16);
      const c2 = 0.5 * Math.cos(3.14159 / 8);
      const d = 0.5 * Math.cos(3 * 3.14159 / 16);
      const e = 0.5 * Math.cos(5 * 3.14159 / 16);
      const f = 0.5 * Math.cos(3 * 3.14159 / 8);
      const g3 = 0.5 * Math.cos(7 * 3.14159 / 16);
      const alpha = new Array(4);
      const beta = new Array(4);
      const theta = new Array(4);
      const gamma = new Array(4);
      for (let row = 0; row < 8; ++row) {
        const rowPtr = row * 8;
        alpha[0] = c2 * data2[rowPtr + 2];
        alpha[1] = f * data2[rowPtr + 2];
        alpha[2] = c2 * data2[rowPtr + 6];
        alpha[3] = f * data2[rowPtr + 6];
        beta[0] = b3 * data2[rowPtr + 1] + d * data2[rowPtr + 3] + e * data2[rowPtr + 5] + g3 * data2[rowPtr + 7];
        beta[1] = d * data2[rowPtr + 1] - g3 * data2[rowPtr + 3] - b3 * data2[rowPtr + 5] - e * data2[rowPtr + 7];
        beta[2] = e * data2[rowPtr + 1] - b3 * data2[rowPtr + 3] + g3 * data2[rowPtr + 5] + d * data2[rowPtr + 7];
        beta[3] = g3 * data2[rowPtr + 1] - e * data2[rowPtr + 3] + d * data2[rowPtr + 5] - b3 * data2[rowPtr + 7];
        theta[0] = a2 * (data2[rowPtr + 0] + data2[rowPtr + 4]);
        theta[3] = a2 * (data2[rowPtr + 0] - data2[rowPtr + 4]);
        theta[1] = alpha[0] + alpha[3];
        theta[2] = alpha[1] - alpha[2];
        gamma[0] = theta[0] + theta[1];
        gamma[1] = theta[3] + theta[2];
        gamma[2] = theta[3] - theta[2];
        gamma[3] = theta[0] - theta[1];
        data2[rowPtr + 0] = gamma[0] + beta[0];
        data2[rowPtr + 1] = gamma[1] + beta[1];
        data2[rowPtr + 2] = gamma[2] + beta[2];
        data2[rowPtr + 3] = gamma[3] + beta[3];
        data2[rowPtr + 4] = gamma[3] - beta[3];
        data2[rowPtr + 5] = gamma[2] - beta[2];
        data2[rowPtr + 6] = gamma[1] - beta[1];
        data2[rowPtr + 7] = gamma[0] - beta[0];
      }
      for (let column = 0; column < 8; ++column) {
        alpha[0] = c2 * data2[16 + column];
        alpha[1] = f * data2[16 + column];
        alpha[2] = c2 * data2[48 + column];
        alpha[3] = f * data2[48 + column];
        beta[0] = b3 * data2[8 + column] + d * data2[24 + column] + e * data2[40 + column] + g3 * data2[56 + column];
        beta[1] = d * data2[8 + column] - g3 * data2[24 + column] - b3 * data2[40 + column] - e * data2[56 + column];
        beta[2] = e * data2[8 + column] - b3 * data2[24 + column] + g3 * data2[40 + column] + d * data2[56 + column];
        beta[3] = g3 * data2[8 + column] - e * data2[24 + column] + d * data2[40 + column] - b3 * data2[56 + column];
        theta[0] = a2 * (data2[column] + data2[32 + column]);
        theta[3] = a2 * (data2[column] - data2[32 + column]);
        theta[1] = alpha[0] + alpha[3];
        theta[2] = alpha[1] - alpha[2];
        gamma[0] = theta[0] + theta[1];
        gamma[1] = theta[3] + theta[2];
        gamma[2] = theta[3] - theta[2];
        gamma[3] = theta[0] - theta[1];
        data2[0 + column] = gamma[0] + beta[0];
        data2[8 + column] = gamma[1] + beta[1];
        data2[16 + column] = gamma[2] + beta[2];
        data2[24 + column] = gamma[3] + beta[3];
        data2[32 + column] = gamma[3] - beta[3];
        data2[40 + column] = gamma[2] - beta[2];
        data2[48 + column] = gamma[1] - beta[1];
        data2[56 + column] = gamma[0] - beta[0];
      }
    }
    function csc709Inverse(data2) {
      for (let i = 0; i < 64; ++i) {
        const y = data2[0][i];
        const cb = data2[1][i];
        const cr = data2[2][i];
        data2[0][i] = y + 1.5747 * cr;
        data2[1][i] = y - 0.1873 * cb - 0.4682 * cr;
        data2[2][i] = y + 1.8556 * cb;
      }
    }
    function convertToHalf(src, dst, idx) {
      for (let i = 0; i < 64; ++i) {
        dst[idx + i] = DataUtils.toHalfFloat(toLinear(src[i]));
      }
    }
    function toLinear(float) {
      if (float <= 1) {
        return Math.sign(float) * Math.pow(Math.abs(float), 2.2);
      } else {
        return Math.sign(float) * Math.pow(logBase, Math.abs(float) - 1);
      }
    }
    function uncompressRAW(info) {
      return new DataView(info.array.buffer, info.offset.value, info.size);
    }
    function uncompressRLE(info) {
      const compressed = info.viewer.buffer.slice(info.offset.value, info.offset.value + info.size);
      const rawBuffer = new Uint8Array(decodeRunLength(compressed));
      const tmpBuffer = new Uint8Array(rawBuffer.length);
      predictor(rawBuffer);
      interleaveScalar(rawBuffer, tmpBuffer);
      return new DataView(tmpBuffer.buffer);
    }
    function uncompressZIP(info) {
      const compressed = info.array.slice(info.offset.value, info.offset.value + info.size);
      const rawBuffer = unzlibSync(compressed);
      const tmpBuffer = new Uint8Array(rawBuffer.length);
      predictor(rawBuffer);
      interleaveScalar(rawBuffer, tmpBuffer);
      return new DataView(tmpBuffer.buffer);
    }
    function uncompressPIZ(info) {
      const inDataView = info.viewer;
      const inOffset = { value: info.offset.value };
      const outBuffer = new Uint16Array(info.columns * info.lines * (info.inputChannels.length * info.type));
      const bitmap = new Uint8Array(BITMAP_SIZE);
      let outBufferEnd = 0;
      const pizChannelData = new Array(info.inputChannels.length);
      for (let i = 0, il = info.inputChannels.length; i < il; i++) {
        pizChannelData[i] = {};
        pizChannelData[i]["start"] = outBufferEnd;
        pizChannelData[i]["end"] = pizChannelData[i]["start"];
        pizChannelData[i]["nx"] = info.columns;
        pizChannelData[i]["ny"] = info.lines;
        pizChannelData[i]["size"] = info.type;
        outBufferEnd += pizChannelData[i].nx * pizChannelData[i].ny * pizChannelData[i].size;
      }
      const minNonZero = parseUint16(inDataView, inOffset);
      const maxNonZero = parseUint16(inDataView, inOffset);
      if (maxNonZero >= BITMAP_SIZE) {
        throw new Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");
      }
      if (minNonZero <= maxNonZero) {
        for (let i = 0; i < maxNonZero - minNonZero + 1; i++) {
          bitmap[i + minNonZero] = parseUint8(inDataView, inOffset);
        }
      }
      const lut = new Uint16Array(USHORT_RANGE);
      const maxValue = reverseLutFromBitmap(bitmap, lut);
      const length2 = parseUint32(inDataView, inOffset);
      hufUncompress(info.array, inDataView, inOffset, length2, outBuffer, outBufferEnd);
      for (let i = 0; i < info.inputChannels.length; ++i) {
        const cd = pizChannelData[i];
        for (let j2 = 0; j2 < pizChannelData[i].size; ++j2) {
          wav2Decode(
            outBuffer,
            cd.start + j2,
            cd.nx,
            cd.size,
            cd.ny,
            cd.nx * cd.size,
            maxValue
          );
        }
      }
      applyLut(lut, outBuffer, outBufferEnd);
      let tmpOffset = 0;
      const tmpBuffer = new Uint8Array(outBuffer.buffer.byteLength);
      for (let y = 0; y < info.lines; y++) {
        for (let c2 = 0; c2 < info.inputChannels.length; c2++) {
          const cd = pizChannelData[c2];
          const n2 = cd.nx * cd.size;
          const cp = new Uint8Array(outBuffer.buffer, cd.end * INT16_SIZE, n2 * INT16_SIZE);
          tmpBuffer.set(cp, tmpOffset);
          tmpOffset += n2 * INT16_SIZE;
          cd.end += n2;
        }
      }
      return new DataView(tmpBuffer.buffer);
    }
    function uncompressPXR(info) {
      const compressed = info.array.slice(info.offset.value, info.offset.value + info.size);
      const rawBuffer = unzlibSync(compressed);
      const byteSize = info.inputChannels.length * info.lines * info.columns * info.totalBytes;
      const tmpBuffer = new ArrayBuffer(byteSize);
      const viewer = new DataView(tmpBuffer);
      let tmpBufferEnd = 0;
      let writePtr = 0;
      const ptr = new Array(4);
      for (let y = 0; y < info.lines; y++) {
        for (let c2 = 0; c2 < info.inputChannels.length; c2++) {
          let pixel = 0;
          const type = info.inputChannels[c2].pixelType;
          switch (type) {
            case 1:
              ptr[0] = tmpBufferEnd;
              ptr[1] = ptr[0] + info.columns;
              tmpBufferEnd = ptr[1] + info.columns;
              for (let j2 = 0; j2 < info.columns; ++j2) {
                const diff = rawBuffer[ptr[0]++] << 8 | rawBuffer[ptr[1]++];
                pixel += diff;
                viewer.setUint16(writePtr, pixel, true);
                writePtr += 2;
              }
              break;
            case 2:
              ptr[0] = tmpBufferEnd;
              ptr[1] = ptr[0] + info.columns;
              ptr[2] = ptr[1] + info.columns;
              tmpBufferEnd = ptr[2] + info.columns;
              for (let j2 = 0; j2 < info.columns; ++j2) {
                const diff = rawBuffer[ptr[0]++] << 24 | rawBuffer[ptr[1]++] << 16 | rawBuffer[ptr[2]++] << 8;
                pixel += diff;
                viewer.setUint32(writePtr, pixel, true);
                writePtr += 4;
              }
              break;
          }
        }
      }
      return viewer;
    }
    function uncompressDWA(info) {
      const inDataView = info.viewer;
      const inOffset = { value: info.offset.value };
      const outBuffer = new Uint8Array(info.columns * info.lines * (info.inputChannels.length * info.type * INT16_SIZE));
      const dwaHeader = {
        version: parseInt64(inDataView, inOffset),
        unknownUncompressedSize: parseInt64(inDataView, inOffset),
        unknownCompressedSize: parseInt64(inDataView, inOffset),
        acCompressedSize: parseInt64(inDataView, inOffset),
        dcCompressedSize: parseInt64(inDataView, inOffset),
        rleCompressedSize: parseInt64(inDataView, inOffset),
        rleUncompressedSize: parseInt64(inDataView, inOffset),
        rleRawSize: parseInt64(inDataView, inOffset),
        totalAcUncompressedCount: parseInt64(inDataView, inOffset),
        totalDcUncompressedCount: parseInt64(inDataView, inOffset),
        acCompression: parseInt64(inDataView, inOffset)
      };
      if (dwaHeader.version < 2)
        throw new Error("EXRLoader.parse: " + EXRHeader.compression + " version " + dwaHeader.version + " is unsupported");
      const channelRules = new Array();
      let ruleSize = parseUint16(inDataView, inOffset) - INT16_SIZE;
      while (ruleSize > 0) {
        const name2 = parseNullTerminatedString(inDataView.buffer, inOffset);
        const value2 = parseUint8(inDataView, inOffset);
        const compression = value2 >> 2 & 3;
        const csc = (value2 >> 4) - 1;
        const index2 = new Int8Array([csc])[0];
        const type = parseUint8(inDataView, inOffset);
        channelRules.push({
          name: name2,
          index: index2,
          type,
          compression
        });
        ruleSize -= name2.length + 3;
      }
      const channels = EXRHeader.channels;
      const channelData = new Array(info.inputChannels.length);
      for (let i = 0; i < info.inputChannels.length; ++i) {
        const cd = channelData[i] = {};
        const channel = channels[i];
        cd.name = channel.name;
        cd.compression = UNKNOWN;
        cd.decoded = false;
        cd.type = channel.pixelType;
        cd.pLinear = channel.pLinear;
        cd.width = info.columns;
        cd.height = info.lines;
      }
      const cscSet = {
        idx: new Array(3)
      };
      for (let offset2 = 0; offset2 < info.inputChannels.length; ++offset2) {
        const cd = channelData[offset2];
        for (let i = 0; i < channelRules.length; ++i) {
          const rule = channelRules[i];
          if (cd.name == rule.name) {
            cd.compression = rule.compression;
            if (rule.index >= 0) {
              cscSet.idx[rule.index] = offset2;
            }
            cd.offset = offset2;
          }
        }
      }
      let acBuffer, dcBuffer, rleBuffer;
      if (dwaHeader.acCompressedSize > 0) {
        switch (dwaHeader.acCompression) {
          case STATIC_HUFFMAN:
            acBuffer = new Uint16Array(dwaHeader.totalAcUncompressedCount);
            hufUncompress(info.array, inDataView, inOffset, dwaHeader.acCompressedSize, acBuffer, dwaHeader.totalAcUncompressedCount);
            break;
          case DEFLATE:
            const compressed = info.array.slice(inOffset.value, inOffset.value + dwaHeader.totalAcUncompressedCount);
            const data2 = unzlibSync(compressed);
            acBuffer = new Uint16Array(data2.buffer);
            inOffset.value += dwaHeader.totalAcUncompressedCount;
            break;
        }
      }
      if (dwaHeader.dcCompressedSize > 0) {
        const zlibInfo = {
          array: info.array,
          offset: inOffset,
          size: dwaHeader.dcCompressedSize
        };
        dcBuffer = new Uint16Array(uncompressZIP(zlibInfo).buffer);
        inOffset.value += dwaHeader.dcCompressedSize;
      }
      if (dwaHeader.rleRawSize > 0) {
        const compressed = info.array.slice(inOffset.value, inOffset.value + dwaHeader.rleCompressedSize);
        const data2 = unzlibSync(compressed);
        rleBuffer = decodeRunLength(data2.buffer);
        inOffset.value += dwaHeader.rleCompressedSize;
      }
      let outBufferEnd = 0;
      const rowOffsets = new Array(channelData.length);
      for (let i = 0; i < rowOffsets.length; ++i) {
        rowOffsets[i] = new Array();
      }
      for (let y = 0; y < info.lines; ++y) {
        for (let chan = 0; chan < channelData.length; ++chan) {
          rowOffsets[chan].push(outBufferEnd);
          outBufferEnd += channelData[chan].width * info.type * INT16_SIZE;
        }
      }
      lossyDctDecode(cscSet, rowOffsets, channelData, acBuffer, dcBuffer, outBuffer);
      for (let i = 0; i < channelData.length; ++i) {
        const cd = channelData[i];
        if (cd.decoded) continue;
        switch (cd.compression) {
          case RLE:
            let row = 0;
            let rleOffset = 0;
            for (let y = 0; y < info.lines; ++y) {
              let rowOffsetBytes = rowOffsets[i][row];
              for (let x2 = 0; x2 < cd.width; ++x2) {
                for (let byte = 0; byte < INT16_SIZE * cd.type; ++byte) {
                  outBuffer[rowOffsetBytes++] = rleBuffer[rleOffset + byte * cd.width * cd.height];
                }
                rleOffset++;
              }
              row++;
            }
            break;
          case LOSSY_DCT:
          // skip
          default:
            throw new Error("EXRLoader.parse: unsupported channel compression");
        }
      }
      return new DataView(outBuffer.buffer);
    }
    function parseNullTerminatedString(buffer2, offset2) {
      const uintBuffer = new Uint8Array(buffer2);
      let endOffset = 0;
      while (uintBuffer[offset2.value + endOffset] != 0) {
        endOffset += 1;
      }
      const stringValue = new TextDecoder().decode(
        uintBuffer.slice(offset2.value, offset2.value + endOffset)
      );
      offset2.value = offset2.value + endOffset + 1;
      return stringValue;
    }
    function parseFixedLengthString(buffer2, offset2, size2) {
      const stringValue = new TextDecoder().decode(
        new Uint8Array(buffer2).slice(offset2.value, offset2.value + size2)
      );
      offset2.value = offset2.value + size2;
      return stringValue;
    }
    function parseRational(dataView, offset2) {
      const x2 = parseInt32(dataView, offset2);
      const y = parseUint32(dataView, offset2);
      return [x2, y];
    }
    function parseTimecode(dataView, offset2) {
      const x2 = parseUint32(dataView, offset2);
      const y = parseUint32(dataView, offset2);
      return [x2, y];
    }
    function parseInt32(dataView, offset2) {
      const Int32 = dataView.getInt32(offset2.value, true);
      offset2.value = offset2.value + INT32_SIZE;
      return Int32;
    }
    function parseUint32(dataView, offset2) {
      const Uint32 = dataView.getUint32(offset2.value, true);
      offset2.value = offset2.value + INT32_SIZE;
      return Uint32;
    }
    function parseUint8Array(uInt8Array2, offset2) {
      const Uint8 = uInt8Array2[offset2.value];
      offset2.value = offset2.value + INT8_SIZE;
      return Uint8;
    }
    function parseUint8(dataView, offset2) {
      const Uint8 = dataView.getUint8(offset2.value);
      offset2.value = offset2.value + INT8_SIZE;
      return Uint8;
    }
    const parseInt64 = function(dataView, offset2) {
      let int;
      if ("getBigInt64" in DataView.prototype) {
        int = Number(dataView.getBigInt64(offset2.value, true));
      } else {
        int = dataView.getUint32(offset2.value + 4, true) + Number(dataView.getUint32(offset2.value, true) << 32);
      }
      offset2.value += ULONG_SIZE;
      return int;
    };
    function parseFloat32(dataView, offset2) {
      const float = dataView.getFloat32(offset2.value, true);
      offset2.value += FLOAT32_SIZE;
      return float;
    }
    function decodeFloat32(dataView, offset2) {
      return DataUtils.toHalfFloat(parseFloat32(dataView, offset2));
    }
    function decodeFloat162(binary) {
      const exponent = (binary & 31744) >> 10, fraction = binary & 1023;
      return (binary >> 15 ? -1 : 1) * (exponent ? exponent === 31 ? fraction ? NaN : Infinity : Math.pow(2, exponent - 15) * (1 + fraction / 1024) : 6103515625e-14 * (fraction / 1024));
    }
    function parseUint16(dataView, offset2) {
      const Uint16 = dataView.getUint16(offset2.value, true);
      offset2.value += INT16_SIZE;
      return Uint16;
    }
    function parseFloat16(buffer2, offset2) {
      return decodeFloat162(parseUint16(buffer2, offset2));
    }
    function parseChlist(dataView, buffer2, offset2, size2) {
      const startOffset = offset2.value;
      const channels = [];
      while (offset2.value < startOffset + size2 - 1) {
        const name2 = parseNullTerminatedString(buffer2, offset2);
        const pixelType = parseInt32(dataView, offset2);
        const pLinear = parseUint8(dataView, offset2);
        offset2.value += 3;
        const xSampling = parseInt32(dataView, offset2);
        const ySampling = parseInt32(dataView, offset2);
        channels.push({
          name: name2,
          pixelType,
          pLinear,
          xSampling,
          ySampling
        });
      }
      offset2.value += 1;
      return channels;
    }
    function parseChromaticities(dataView, offset2) {
      const redX = parseFloat32(dataView, offset2);
      const redY = parseFloat32(dataView, offset2);
      const greenX = parseFloat32(dataView, offset2);
      const greenY = parseFloat32(dataView, offset2);
      const blueX = parseFloat32(dataView, offset2);
      const blueY = parseFloat32(dataView, offset2);
      const whiteX = parseFloat32(dataView, offset2);
      const whiteY = parseFloat32(dataView, offset2);
      return { redX, redY, greenX, greenY, blueX, blueY, whiteX, whiteY };
    }
    function parseCompression(dataView, offset2) {
      const compressionCodes = [
        "NO_COMPRESSION",
        "RLE_COMPRESSION",
        "ZIPS_COMPRESSION",
        "ZIP_COMPRESSION",
        "PIZ_COMPRESSION",
        "PXR24_COMPRESSION",
        "B44_COMPRESSION",
        "B44A_COMPRESSION",
        "DWAA_COMPRESSION",
        "DWAB_COMPRESSION"
      ];
      const compression = parseUint8(dataView, offset2);
      return compressionCodes[compression];
    }
    function parseBox2i(dataView, offset2) {
      const xMin = parseInt32(dataView, offset2);
      const yMin = parseInt32(dataView, offset2);
      const xMax = parseInt32(dataView, offset2);
      const yMax = parseInt32(dataView, offset2);
      return { xMin, yMin, xMax, yMax };
    }
    function parseLineOrder(dataView, offset2) {
      const lineOrders = [
        "INCREASING_Y",
        "DECREASING_Y",
        "RANDOM_Y"
      ];
      const lineOrder = parseUint8(dataView, offset2);
      return lineOrders[lineOrder];
    }
    function parseEnvmap(dataView, offset2) {
      const envmaps = [
        "ENVMAP_LATLONG",
        "ENVMAP_CUBE"
      ];
      const envmap = parseUint8(dataView, offset2);
      return envmaps[envmap];
    }
    function parseTiledesc(dataView, offset2) {
      const levelModes = [
        "ONE_LEVEL",
        "MIPMAP_LEVELS",
        "RIPMAP_LEVELS"
      ];
      const roundingModes = [
        "ROUND_DOWN",
        "ROUND_UP"
      ];
      const xSize = parseUint32(dataView, offset2);
      const ySize = parseUint32(dataView, offset2);
      const modes = parseUint8(dataView, offset2);
      return {
        xSize,
        ySize,
        levelMode: levelModes[modes & 15],
        roundingMode: roundingModes[modes >> 4]
      };
    }
    function parseV2f(dataView, offset2) {
      const x2 = parseFloat32(dataView, offset2);
      const y = parseFloat32(dataView, offset2);
      return [x2, y];
    }
    function parseV3f(dataView, offset2) {
      const x2 = parseFloat32(dataView, offset2);
      const y = parseFloat32(dataView, offset2);
      const z = parseFloat32(dataView, offset2);
      return [x2, y, z];
    }
    function parseValue(dataView, buffer2, offset2, type, size2) {
      if (type === "string" || type === "stringvector" || type === "iccProfile") {
        return parseFixedLengthString(buffer2, offset2, size2);
      } else if (type === "chlist") {
        return parseChlist(dataView, buffer2, offset2, size2);
      } else if (type === "chromaticities") {
        return parseChromaticities(dataView, offset2);
      } else if (type === "compression") {
        return parseCompression(dataView, offset2);
      } else if (type === "box2i") {
        return parseBox2i(dataView, offset2);
      } else if (type === "envmap") {
        return parseEnvmap(dataView, offset2);
      } else if (type === "tiledesc") {
        return parseTiledesc(dataView, offset2);
      } else if (type === "lineOrder") {
        return parseLineOrder(dataView, offset2);
      } else if (type === "float") {
        return parseFloat32(dataView, offset2);
      } else if (type === "v2f") {
        return parseV2f(dataView, offset2);
      } else if (type === "v3f") {
        return parseV3f(dataView, offset2);
      } else if (type === "int") {
        return parseInt32(dataView, offset2);
      } else if (type === "rational") {
        return parseRational(dataView, offset2);
      } else if (type === "timecode") {
        return parseTimecode(dataView, offset2);
      } else if (type === "preview") {
        offset2.value += size2;
        return "skipped";
      } else {
        offset2.value += size2;
        return void 0;
      }
    }
    function roundLog2(x2, mode) {
      const log22 = Math.log2(x2);
      return mode == "ROUND_DOWN" ? Math.floor(log22) : Math.ceil(log22);
    }
    function calculateTileLevels(tiledesc, w, h) {
      let num = 0;
      switch (tiledesc.levelMode) {
        case "ONE_LEVEL":
          num = 1;
          break;
        case "MIPMAP_LEVELS":
          num = roundLog2(Math.max(w, h), tiledesc.roundingMode) + 1;
          break;
        case "RIPMAP_LEVELS":
          throw new Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.");
      }
      return num;
    }
    function calculateTiles(count, dataSize, size2, roundingMode) {
      const tiles = new Array(count);
      for (let i = 0; i < count; i++) {
        const b3 = 1 << i;
        let s = dataSize / b3 | 0;
        if (roundingMode == "ROUND_UP" && s * b3 < dataSize) s += 1;
        const l2 = Math.max(s, 1);
        tiles[i] = (l2 + size2 - 1) / size2 | 0;
      }
      return tiles;
    }
    function parseTiles() {
      const EXRDecoder2 = this;
      const offset2 = EXRDecoder2.offset;
      const tmpOffset = { value: 0 };
      for (let tile = 0; tile < EXRDecoder2.tileCount; tile++) {
        const tileX = parseInt32(EXRDecoder2.viewer, offset2);
        const tileY = parseInt32(EXRDecoder2.viewer, offset2);
        offset2.value += 8;
        EXRDecoder2.size = parseUint32(EXRDecoder2.viewer, offset2);
        const startX = tileX * EXRDecoder2.blockWidth;
        const startY = tileY * EXRDecoder2.blockHeight;
        EXRDecoder2.columns = startX + EXRDecoder2.blockWidth > EXRDecoder2.width ? EXRDecoder2.width - startX : EXRDecoder2.blockWidth;
        EXRDecoder2.lines = startY + EXRDecoder2.blockHeight > EXRDecoder2.height ? EXRDecoder2.height - startY : EXRDecoder2.blockHeight;
        const bytesBlockLine = EXRDecoder2.columns * EXRDecoder2.totalBytes;
        const isCompressed = EXRDecoder2.size < EXRDecoder2.lines * bytesBlockLine;
        const viewer = isCompressed ? EXRDecoder2.uncompress(EXRDecoder2) : uncompressRAW(EXRDecoder2);
        offset2.value += EXRDecoder2.size;
        for (let line2 = 0; line2 < EXRDecoder2.lines; line2++) {
          const lineOffset = line2 * EXRDecoder2.columns * EXRDecoder2.totalBytes;
          for (let channelID = 0; channelID < EXRDecoder2.inputChannels.length; channelID++) {
            const name2 = EXRHeader.channels[channelID].name;
            const lOff = EXRDecoder2.channelByteOffsets[name2] * EXRDecoder2.columns;
            const cOff = EXRDecoder2.decodeChannels[name2];
            if (cOff === void 0) continue;
            tmpOffset.value = lineOffset + lOff;
            const outLineOffset = (EXRDecoder2.height - (1 + startY + line2)) * EXRDecoder2.outLineWidth;
            for (let x2 = 0; x2 < EXRDecoder2.columns; x2++) {
              const outIndex = outLineOffset + (x2 + startX) * EXRDecoder2.outputChannels + cOff;
              EXRDecoder2.byteArray[outIndex] = EXRDecoder2.getter(viewer, tmpOffset);
            }
          }
        }
      }
    }
    function parseScanline() {
      const EXRDecoder2 = this;
      const offset2 = EXRDecoder2.offset;
      const tmpOffset = { value: 0 };
      for (let scanlineBlockIdx = 0; scanlineBlockIdx < EXRDecoder2.height / EXRDecoder2.blockHeight; scanlineBlockIdx++) {
        const line2 = parseInt32(EXRDecoder2.viewer, offset2) - EXRHeader.dataWindow.yMin;
        EXRDecoder2.size = parseUint32(EXRDecoder2.viewer, offset2);
        EXRDecoder2.lines = line2 + EXRDecoder2.blockHeight > EXRDecoder2.height ? EXRDecoder2.height - line2 : EXRDecoder2.blockHeight;
        const bytesPerLine = EXRDecoder2.columns * EXRDecoder2.totalBytes;
        const isCompressed = EXRDecoder2.size < EXRDecoder2.lines * bytesPerLine;
        const viewer = isCompressed ? EXRDecoder2.uncompress(EXRDecoder2) : uncompressRAW(EXRDecoder2);
        offset2.value += EXRDecoder2.size;
        for (let line_y = 0; line_y < EXRDecoder2.blockHeight; line_y++) {
          const scan_y = scanlineBlockIdx * EXRDecoder2.blockHeight;
          const true_y = line_y + EXRDecoder2.scanOrder(scan_y);
          if (true_y >= EXRDecoder2.height) continue;
          const lineOffset = line_y * bytesPerLine;
          const outLineOffset = (EXRDecoder2.height - 1 - true_y) * EXRDecoder2.outLineWidth;
          for (let channelID = 0; channelID < EXRDecoder2.inputChannels.length; channelID++) {
            const name2 = EXRHeader.channels[channelID].name;
            const lOff = EXRDecoder2.channelByteOffsets[name2] * EXRDecoder2.columns;
            const cOff = EXRDecoder2.decodeChannels[name2];
            if (cOff === void 0) continue;
            tmpOffset.value = lineOffset + lOff;
            for (let x2 = 0; x2 < EXRDecoder2.columns; x2++) {
              const outIndex = outLineOffset + x2 * EXRDecoder2.outputChannels + cOff;
              EXRDecoder2.byteArray[outIndex] = EXRDecoder2.getter(viewer, tmpOffset);
            }
          }
        }
      }
    }
    function parseHeader(dataView, buffer2, offset2) {
      const EXRHeader2 = {};
      if (dataView.getUint32(0, true) != 20000630) {
        throw new Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");
      }
      EXRHeader2.version = dataView.getUint8(4);
      const spec = dataView.getUint8(5);
      EXRHeader2.spec = {
        singleTile: !!(spec & 2),
        longName: !!(spec & 4),
        deepFormat: !!(spec & 8),
        multiPart: !!(spec & 16)
      };
      offset2.value = 8;
      let keepReading = true;
      while (keepReading) {
        const attributeName = parseNullTerminatedString(buffer2, offset2);
        if (attributeName === "") {
          keepReading = false;
        } else {
          const attributeType = parseNullTerminatedString(buffer2, offset2);
          const attributeSize = parseUint32(dataView, offset2);
          const attributeValue = parseValue(dataView, buffer2, offset2, attributeType, attributeSize);
          if (attributeValue === void 0) {
            console.warn(`THREE.EXRLoader: Skipped unknown header attribute type '${attributeType}'.`);
          } else {
            EXRHeader2[attributeName] = attributeValue;
          }
        }
      }
      if ((spec & ~6) != 0) {
        console.error("THREE.EXRHeader:", EXRHeader2);
        throw new Error("THREE.EXRLoader: Provided file is currently unsupported.");
      }
      return EXRHeader2;
    }
    function setupDecoder(EXRHeader2, dataView, uInt8Array2, offset2, outputType) {
      const EXRDecoder2 = {
        size: 0,
        viewer: dataView,
        array: uInt8Array2,
        offset: offset2,
        width: EXRHeader2.dataWindow.xMax - EXRHeader2.dataWindow.xMin + 1,
        height: EXRHeader2.dataWindow.yMax - EXRHeader2.dataWindow.yMin + 1,
        inputChannels: EXRHeader2.channels,
        channelByteOffsets: {},
        scanOrder: null,
        totalBytes: null,
        columns: null,
        lines: null,
        type: null,
        uncompress: null,
        getter: null,
        format: null,
        colorSpace: LinearSRGBColorSpace
      };
      switch (EXRHeader2.compression) {
        case "NO_COMPRESSION":
          EXRDecoder2.blockHeight = 1;
          EXRDecoder2.uncompress = uncompressRAW;
          break;
        case "RLE_COMPRESSION":
          EXRDecoder2.blockHeight = 1;
          EXRDecoder2.uncompress = uncompressRLE;
          break;
        case "ZIPS_COMPRESSION":
          EXRDecoder2.blockHeight = 1;
          EXRDecoder2.uncompress = uncompressZIP;
          break;
        case "ZIP_COMPRESSION":
          EXRDecoder2.blockHeight = 16;
          EXRDecoder2.uncompress = uncompressZIP;
          break;
        case "PIZ_COMPRESSION":
          EXRDecoder2.blockHeight = 32;
          EXRDecoder2.uncompress = uncompressPIZ;
          break;
        case "PXR24_COMPRESSION":
          EXRDecoder2.blockHeight = 16;
          EXRDecoder2.uncompress = uncompressPXR;
          break;
        case "DWAA_COMPRESSION":
          EXRDecoder2.blockHeight = 32;
          EXRDecoder2.uncompress = uncompressDWA;
          break;
        case "DWAB_COMPRESSION":
          EXRDecoder2.blockHeight = 256;
          EXRDecoder2.uncompress = uncompressDWA;
          break;
        default:
          throw new Error("EXRLoader.parse: " + EXRHeader2.compression + " is unsupported");
      }
      const channels = {};
      for (const channel of EXRHeader2.channels) {
        switch (channel.name) {
          case "Y":
          case "R":
          case "G":
          case "B":
          case "A":
            channels[channel.name] = true;
            EXRDecoder2.type = channel.pixelType;
        }
      }
      let fillAlpha = false;
      if (channels.R && channels.G && channels.B) {
        fillAlpha = !channels.A;
        EXRDecoder2.outputChannels = 4;
        EXRDecoder2.decodeChannels = { R: 0, G: 1, B: 2, A: 3 };
      } else if (channels.Y) {
        EXRDecoder2.outputChannels = 1;
        EXRDecoder2.decodeChannels = { Y: 0 };
      } else {
        throw new Error("EXRLoader.parse: file contains unsupported data channels.");
      }
      if (EXRDecoder2.type == 1) {
        switch (outputType) {
          case FloatType:
            EXRDecoder2.getter = parseFloat16;
            break;
          case HalfFloatType:
            EXRDecoder2.getter = parseUint16;
            break;
        }
      } else if (EXRDecoder2.type == 2) {
        switch (outputType) {
          case FloatType:
            EXRDecoder2.getter = parseFloat32;
            break;
          case HalfFloatType:
            EXRDecoder2.getter = decodeFloat32;
        }
      } else {
        throw new Error("EXRLoader.parse: unsupported pixelType " + EXRDecoder2.type + " for " + EXRHeader2.compression + ".");
      }
      EXRDecoder2.columns = EXRDecoder2.width;
      const size2 = EXRDecoder2.width * EXRDecoder2.height * EXRDecoder2.outputChannels;
      switch (outputType) {
        case FloatType:
          EXRDecoder2.byteArray = new Float32Array(size2);
          if (fillAlpha)
            EXRDecoder2.byteArray.fill(1, 0, size2);
          break;
        case HalfFloatType:
          EXRDecoder2.byteArray = new Uint16Array(size2);
          if (fillAlpha)
            EXRDecoder2.byteArray.fill(15360, 0, size2);
          break;
        default:
          console.error("THREE.EXRLoader: unsupported type: ", outputType);
          break;
      }
      let byteOffset = 0;
      for (const channel of EXRHeader2.channels) {
        if (EXRDecoder2.decodeChannels[channel.name] !== void 0) {
          EXRDecoder2.channelByteOffsets[channel.name] = byteOffset;
        }
        byteOffset += channel.pixelType * 2;
      }
      EXRDecoder2.totalBytes = byteOffset;
      EXRDecoder2.outLineWidth = EXRDecoder2.width * EXRDecoder2.outputChannels;
      if (EXRHeader2.lineOrder === "INCREASING_Y") {
        EXRDecoder2.scanOrder = (y) => y;
      } else {
        EXRDecoder2.scanOrder = (y) => EXRDecoder2.height - 1 - y;
      }
      if (EXRDecoder2.outputChannels == 4) {
        EXRDecoder2.format = RGBAFormat;
        EXRDecoder2.colorSpace = LinearSRGBColorSpace;
      } else {
        EXRDecoder2.format = RedFormat;
        EXRDecoder2.colorSpace = NoColorSpace;
      }
      if (EXRHeader2.spec.singleTile) {
        EXRDecoder2.blockHeight = EXRHeader2.tiles.ySize;
        EXRDecoder2.blockWidth = EXRHeader2.tiles.xSize;
        const numXLevels = calculateTileLevels(EXRHeader2.tiles, EXRDecoder2.width, EXRDecoder2.height);
        const numXTiles = calculateTiles(numXLevels, EXRDecoder2.width, EXRHeader2.tiles.xSize, EXRHeader2.tiles.roundingMode);
        const numYTiles = calculateTiles(numXLevels, EXRDecoder2.height, EXRHeader2.tiles.ySize, EXRHeader2.tiles.roundingMode);
        EXRDecoder2.tileCount = numXTiles[0] * numYTiles[0];
        for (let l2 = 0; l2 < numXLevels; l2++)
          for (let y = 0; y < numYTiles[l2]; y++)
            for (let x2 = 0; x2 < numXTiles[l2]; x2++)
              parseInt64(dataView, offset2);
        EXRDecoder2.decode = parseTiles.bind(EXRDecoder2);
      } else {
        EXRDecoder2.blockWidth = EXRDecoder2.width;
        const blockCount = Math.ceil(EXRDecoder2.height / EXRDecoder2.blockHeight);
        for (let i = 0; i < blockCount; i++)
          parseInt64(dataView, offset2);
        EXRDecoder2.decode = parseScanline.bind(EXRDecoder2);
      }
      return EXRDecoder2;
    }
    const offset = { value: 0 };
    const bufferDataView = new DataView(buffer);
    const uInt8Array = new Uint8Array(buffer);
    const EXRHeader = parseHeader(bufferDataView, buffer, offset);
    const EXRDecoder = setupDecoder(EXRHeader, bufferDataView, uInt8Array, offset, this.type);
    EXRDecoder.decode();
    return {
      header: EXRHeader,
      width: EXRDecoder.width,
      height: EXRDecoder.height,
      data: EXRDecoder.byteArray,
      format: EXRDecoder.format,
      colorSpace: EXRDecoder.colorSpace,
      type: this.type
    };
  }
  /**
   * Sets the texture type.
   *
   * @param {(HalfFloatType|FloatType)} value - The texture type to set.
   * @return {RGBMLoader} A reference to this loader.
   */
  setDataType(value2) {
    this.type = value2;
    return this;
  }
  load(url, onLoad, onProgress, onError) {
    function onLoadCallback(texture, texData) {
      texture.colorSpace = texData.colorSpace;
      texture.minFilter = LinearFilter;
      texture.magFilter = LinearFilter;
      texture.generateMipmaps = false;
      texture.flipY = false;
      if (onLoad) onLoad(texture, texData);
    }
    return super.load(url, onLoadCallback, onProgress, onError);
  }
};

// node_modules/three/examples/jsm/loaders/3DMLoader.js
var _taskCache = /* @__PURE__ */ new WeakMap();
var Rhino3dmLoader = class extends Loader {
  /**
   * Constructs a new Rhino 3DM loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.libraryPath = "";
    this.libraryPending = null;
    this.libraryBinary = null;
    this.libraryConfig = {};
    this.url = "";
    this.workerLimit = 4;
    this.workerPool = [];
    this.workerNextTaskID = 1;
    this.workerSourceURL = "";
    this.workerConfig = {};
    this.materials = [];
    this.warnings = [];
  }
  /**
   * Path to a folder containing the JS and WASM libraries.
   *
   * @param {string} path - The library path to set.
   * @return {Rhino3dmLoader} A reference to this loader.
   */
  setLibraryPath(path) {
    this.libraryPath = path;
    return this;
  }
  /**
   * Sets the maximum number of Web Workers to be used during decoding.
   * A lower limit may be preferable if workers are also for other
   * tasks in the application.
   *
   * @param {number} workerLimit - The worker limit.
   * @return {Rhino3dmLoader} A reference to this loader.
   */
  setWorkerLimit(workerLimit) {
    this.workerLimit = workerLimit;
    return this;
  }
  /**
   * Starts loading from the given URL and passes the loaded 3DM asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(this.requestHeader);
    this.url = url;
    loader.load(url, (buffer) => {
      if (_taskCache.has(buffer)) {
        const cachedTask = _taskCache.get(buffer);
        return cachedTask.promise.then(onLoad).catch(onError);
      }
      this.decodeObjects(buffer, url).then((result) => {
        result.userData.warnings = this.warnings;
        onLoad(result);
      }).catch((e) => onError(e));
    }, onProgress, onError);
  }
  /**
   * Prints debug messages to the browser console.
   */
  debug() {
    console.log("Task load: ", this.workerPool.map((worker) => worker._taskLoad));
  }
  /**
   * Decodes the 3DM asset data with a Web Worker.
   *
   * @param {ArrayBuffer} buffer - The raw 3DM asset data as an array buffer.
   * @param {string} url - The asset URL.
   * @return {Promise<Object3D>} A Promise that resolved with the decoded 3D object.
   */
  decodeObjects(buffer, url) {
    let worker;
    let taskID;
    const taskCost = buffer.byteLength;
    const objectPending = this._getWorker(taskCost).then((_worker) => {
      worker = _worker;
      taskID = this.workerNextTaskID++;
      return new Promise((resolve, reject2) => {
        worker._callbacks[taskID] = { resolve, reject: reject2 };
        worker.postMessage({ type: "decode", id: taskID, buffer }, [buffer]);
      });
    }).then((message) => this._createGeometry(message.data)).catch((e) => {
      throw e;
    });
    objectPending.catch(() => true).then(() => {
      if (worker && taskID) {
        this._releaseTask(worker, taskID);
      }
    });
    _taskCache.set(buffer, {
      url,
      promise: objectPending
    });
    return objectPending;
  }
  /**
   * Parses the given 3DM data and passes the loaded 3DM asset
   * to the `onLoad()` callback.
   *
   * @param {ArrayBuffer} data - The raw 3DM asset data as an array buffer.
   * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  parse(data2, onLoad, onError) {
    this.decodeObjects(data2, "").then((result) => {
      result.userData.warnings = this.warnings;
      onLoad(result);
    }).catch((e) => onError(e));
  }
  _compareMaterials(material) {
    const mat = {};
    mat.name = material.name;
    mat.color = {};
    mat.color.r = material.color.r;
    mat.color.g = material.color.g;
    mat.color.b = material.color.b;
    mat.type = material.type;
    mat.vertexColors = material.vertexColors;
    const json = JSON.stringify(mat);
    for (let i = 0; i < this.materials.length; i++) {
      const m = this.materials[i];
      const _mat = {};
      _mat.name = m.name;
      _mat.color = {};
      _mat.color.r = m.color.r;
      _mat.color.g = m.color.g;
      _mat.color.b = m.color.b;
      _mat.type = m.type;
      _mat.vertexColors = m.vertexColors;
      if (JSON.stringify(_mat) === json) {
        return m;
      }
    }
    this.materials.push(material);
    return material;
  }
  _createMaterial(material, renderEnvironment) {
    if (material === void 0) {
      return new MeshStandardMaterial({
        color: new Color(1, 1, 1),
        metalness: 0.8,
        name: Loader.DEFAULT_MATERIAL_NAME,
        side: DoubleSide
      });
    }
    const mat = new MeshPhysicalMaterial({
      color: new Color(material.diffuseColor.r / 255, material.diffuseColor.g / 255, material.diffuseColor.b / 255),
      emissive: new Color(material.emissionColor.r, material.emissionColor.g, material.emissionColor.b),
      flatShading: material.disableLighting,
      ior: material.indexOfRefraction,
      name: material.name,
      reflectivity: material.reflectivity,
      opacity: 1 - material.transparency,
      side: DoubleSide,
      specularColor: material.specularColor,
      transparent: material.transparency > 0 ? true : false
    });
    mat.userData.id = material.id;
    if (material.pbrSupported) {
      const pbr = material.pbr;
      mat.anisotropy = pbr.anisotropic;
      mat.anisotropyRotation = pbr.anisotropicRotation;
      mat.color = new Color(pbr.baseColor.r, pbr.baseColor.g, pbr.baseColor.b);
      mat.clearcoat = pbr.clearcoat;
      mat.clearcoatRoughness = pbr.clearcoatRoughness;
      mat.metalness = pbr.metallic;
      mat.transmission = 1 - pbr.opacity;
      mat.roughness = pbr.roughness;
      mat.sheen = pbr.sheen;
      mat.specularIntensity = pbr.specular;
      mat.thickness = pbr.subsurface;
    }
    if (material.pbrSupported && material.pbr.opacity === 0 && material.transparency === 1) {
      mat.opacity = 0.2;
      mat.transmission = 1;
    }
    const textureLoader = new TextureLoader();
    for (let i = 0; i < material.textures.length; i++) {
      const texture = material.textures[i];
      if (texture.image !== null) {
        const map2 = textureLoader.load(texture.image);
        switch (texture.type) {
          case "Bump":
            mat.bumpMap = map2;
            break;
          case "Diffuse":
            mat.map = map2;
            break;
          case "Emap":
            mat.envMap = map2;
            break;
          case "Opacity":
            mat.transmissionMap = map2;
            break;
          case "Transparency":
            mat.alphaMap = map2;
            mat.transparent = true;
            break;
          case "PBR_Alpha":
            mat.alphaMap = map2;
            mat.transparent = true;
            break;
          case "PBR_AmbientOcclusion":
            mat.aoMap = map2;
            break;
          case "PBR_Anisotropic":
            mat.anisotropyMap = map2;
            break;
          case "PBR_BaseColor":
            mat.map = map2;
            break;
          case "PBR_Clearcoat":
            mat.clearcoatMap = map2;
            break;
          case "PBR_ClearcoatBump":
            mat.clearcoatNormalMap = map2;
            break;
          case "PBR_ClearcoatRoughness":
            mat.clearcoatRoughnessMap = map2;
            break;
          case "PBR_Displacement":
            mat.displacementMap = map2;
            break;
          case "PBR_Emission":
            mat.emissiveMap = map2;
            break;
          case "PBR_Metallic":
            mat.metalnessMap = map2;
            break;
          case "PBR_Roughness":
            mat.roughnessMap = map2;
            break;
          case "PBR_Sheen":
            mat.sheenColorMap = map2;
            break;
          case "PBR_Specular":
            mat.specularColorMap = map2;
            break;
          case "PBR_Subsurface":
            mat.thicknessMap = map2;
            break;
          default:
            this.warnings.push({
              message: `THREE.3DMLoader: No conversion exists for 3dm ${texture.type}.`,
              type: "no conversion"
            });
            break;
        }
        map2.wrapS = texture.wrapU === 0 ? RepeatWrapping : ClampToEdgeWrapping;
        map2.wrapT = texture.wrapV === 0 ? RepeatWrapping : ClampToEdgeWrapping;
        if (texture.repeat) {
          map2.repeat.set(texture.repeat[0], texture.repeat[1]);
        }
      }
    }
    if (renderEnvironment) {
      new EXRLoader().load(renderEnvironment.image, function(texture) {
        texture.mapping = THREE.EquirectangularReflectionMapping;
        mat.envMap = texture;
      });
    }
    return mat;
  }
  _createGeometry(data2) {
    const object = new Object3D();
    const instanceDefinitionObjects = [];
    const instanceDefinitions = [];
    const instanceReferences = [];
    object.userData["layers"] = data2.layers;
    object.userData["groups"] = data2.groups;
    object.userData["settings"] = data2.settings;
    object.userData.settings["renderSettings"] = data2.renderSettings;
    object.userData["objectType"] = "File3dm";
    object.userData["materials"] = null;
    object.name = this.url;
    let objects = data2.objects;
    const materials = data2.materials;
    for (let i = 0; i < objects.length; i++) {
      const obj = objects[i];
      const attributes = obj.attributes;
      switch (obj.objectType) {
        case "InstanceDefinition":
          instanceDefinitions.push(obj);
          break;
        case "InstanceReference":
          instanceReferences.push(obj);
          break;
        default:
          let matId = null;
          switch (attributes.materialSource.name) {
            case "ObjectMaterialSource_MaterialFromLayer":
              if (attributes.layerIndex >= 0) {
                matId = data2.layers[attributes.layerIndex].renderMaterialIndex;
              }
              break;
            case "ObjectMaterialSource_MaterialFromObject":
              if (attributes.materialIndex >= 0) {
                matId = attributes.materialIndex;
              }
              break;
          }
          let material = null;
          if (matId >= 0) {
            const rMaterial = materials[matId];
            material = this._createMaterial(rMaterial, data2.renderEnvironment);
          }
          const _object = this._createObject(obj, material);
          if (_object === void 0) {
            continue;
          }
          const layer = data2.layers[attributes.layerIndex];
          _object.visible = layer ? data2.layers[attributes.layerIndex].visible : true;
          if (attributes.isInstanceDefinitionObject) {
            instanceDefinitionObjects.push(_object);
          } else {
            object.add(_object);
          }
          break;
      }
    }
    for (let i = 0; i < instanceDefinitions.length; i++) {
      const iDef = instanceDefinitions[i];
      objects = [];
      for (let j2 = 0; j2 < iDef.attributes.objectIds.length; j2++) {
        const objId = iDef.attributes.objectIds[j2];
        for (let p = 0; p < instanceDefinitionObjects.length; p++) {
          const idoId = instanceDefinitionObjects[p].userData.attributes.id;
          if (objId === idoId) {
            objects.push(instanceDefinitionObjects[p]);
          }
        }
      }
      for (let j2 = 0; j2 < instanceReferences.length; j2++) {
        const iRef = instanceReferences[j2];
        if (iRef.geometry.parentIdefId === iDef.attributes.id) {
          const iRefObject = new Object3D();
          const xf = iRef.geometry.xform.array;
          const matrix2 = new Matrix4();
          matrix2.set(...xf);
          iRefObject.applyMatrix4(matrix2);
          for (let p = 0; p < objects.length; p++) {
            iRefObject.add(objects[p].clone(true));
          }
          object.add(iRefObject);
        }
      }
    }
    object.userData["materials"] = this.materials;
    object.name = "";
    return object;
  }
  _createObject(obj, mat) {
    const loader = new BufferGeometryLoader();
    const attributes = obj.attributes;
    let geometry, material, _color5, color;
    switch (obj.objectType) {
      case "Point":
      case "PointSet":
        geometry = loader.parse(obj.geometry);
        if (geometry.attributes.hasOwnProperty("color")) {
          material = new PointsMaterial({ vertexColors: true, sizeAttenuation: false, size: 2 });
        } else {
          _color5 = attributes.drawColor;
          color = new Color(_color5.r / 255, _color5.g / 255, _color5.b / 255);
          material = new PointsMaterial({ color, sizeAttenuation: false, size: 2 });
        }
        material = this._compareMaterials(material);
        const points = new Points(geometry, material);
        points.userData["attributes"] = attributes;
        points.userData["objectType"] = obj.objectType;
        if (attributes.name) {
          points.name = attributes.name;
        }
        return points;
      case "Mesh":
      case "Extrusion":
      case "SubD":
      case "Brep":
        if (obj.geometry === null) return;
        geometry = loader.parse(obj.geometry);
        if (mat === null) {
          mat = this._createMaterial();
        }
        if (geometry.attributes.hasOwnProperty("color")) {
          mat.vertexColors = true;
        }
        mat = this._compareMaterials(mat);
        const mesh = new Mesh(geometry, mat);
        mesh.castShadow = attributes.castsShadows;
        mesh.receiveShadow = attributes.receivesShadows;
        mesh.userData["attributes"] = attributes;
        mesh.userData["objectType"] = obj.objectType;
        if (attributes.name) {
          mesh.name = attributes.name;
        }
        return mesh;
      case "Curve":
        geometry = loader.parse(obj.geometry);
        _color5 = attributes.drawColor;
        color = new Color(_color5.r / 255, _color5.g / 255, _color5.b / 255);
        material = new LineBasicMaterial({ color });
        material = this._compareMaterials(material);
        const lines = new Line(geometry, material);
        lines.userData["attributes"] = attributes;
        lines.userData["objectType"] = obj.objectType;
        if (attributes.name) {
          lines.name = attributes.name;
        }
        return lines;
      case "TextDot":
        geometry = obj.geometry;
        const ctx = document.createElement("canvas").getContext("2d");
        const font = `${geometry.fontHeight}px ${geometry.fontFace}`;
        ctx.font = font;
        const width2 = ctx.measureText(geometry.text).width + 10;
        const height2 = geometry.fontHeight + 10;
        const r = window.devicePixelRatio;
        ctx.canvas.width = width2 * r;
        ctx.canvas.height = height2 * r;
        ctx.canvas.style.width = width2 + "px";
        ctx.canvas.style.height = height2 + "px";
        ctx.setTransform(r, 0, 0, r, 0, 0);
        ctx.font = font;
        ctx.textBaseline = "middle";
        ctx.textAlign = "center";
        color = attributes.drawColor;
        ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`;
        ctx.fillRect(0, 0, width2, height2);
        ctx.fillStyle = "white";
        ctx.fillText(geometry.text, width2 / 2, height2 / 2);
        const texture = new CanvasTexture(ctx.canvas);
        texture.minFilter = LinearFilter;
        texture.generateMipmaps = false;
        texture.wrapS = ClampToEdgeWrapping;
        texture.wrapT = ClampToEdgeWrapping;
        material = new SpriteMaterial({ map: texture, depthTest: false });
        const sprite = new Sprite(material);
        sprite.position.set(geometry.point[0], geometry.point[1], geometry.point[2]);
        sprite.scale.set(width2 / 10, height2 / 10, 1);
        sprite.userData["attributes"] = attributes;
        sprite.userData["objectType"] = obj.objectType;
        if (attributes.name) {
          sprite.name = attributes.name;
        }
        return sprite;
      case "Light":
        geometry = obj.geometry;
        let light;
        switch (geometry.lightStyle.name) {
          case "LightStyle_WorldPoint":
            light = new PointLight();
            light.castShadow = attributes.castsShadows;
            light.position.set(geometry.location[0], geometry.location[1], geometry.location[2]);
            light.shadow.normalBias = 0.1;
            break;
          case "LightStyle_WorldSpot":
            light = new SpotLight();
            light.castShadow = attributes.castsShadows;
            light.position.set(geometry.location[0], geometry.location[1], geometry.location[2]);
            light.target.position.set(geometry.direction[0], geometry.direction[1], geometry.direction[2]);
            light.angle = geometry.spotAngleRadians;
            light.shadow.normalBias = 0.1;
            break;
          case "LightStyle_WorldRectangular":
            light = new RectAreaLight();
            const width3 = Math.abs(geometry.width[2]);
            const height3 = Math.abs(geometry.length[0]);
            light.position.set(geometry.location[0] - height3 / 2, geometry.location[1], geometry.location[2] - width3 / 2);
            light.height = height3;
            light.width = width3;
            light.lookAt(geometry.direction[0], geometry.direction[1], geometry.direction[2]);
            break;
          case "LightStyle_WorldDirectional":
            light = new DirectionalLight();
            light.castShadow = attributes.castsShadows;
            light.position.set(geometry.location[0], geometry.location[1], geometry.location[2]);
            light.target.position.set(geometry.direction[0], geometry.direction[1], geometry.direction[2]);
            light.shadow.normalBias = 0.1;
            break;
          case "LightStyle_WorldLinear":
            break;
          default:
            break;
        }
        if (light) {
          light.intensity = geometry.intensity;
          _color5 = geometry.diffuse;
          color = new Color(_color5.r / 255, _color5.g / 255, _color5.b / 255);
          light.color = color;
          light.userData["attributes"] = attributes;
          light.userData["objectType"] = obj.objectType;
        }
        return light;
    }
  }
  _initLibrary() {
    if (!this.libraryPending) {
      const jsLoader = new FileLoader(this.manager);
      jsLoader.setPath(this.libraryPath);
      const jsContent = new Promise((resolve, reject2) => {
        jsLoader.load("rhino3dm.js", resolve, void 0, reject2);
      });
      const binaryLoader = new FileLoader(this.manager);
      binaryLoader.setPath(this.libraryPath);
      binaryLoader.setResponseType("arraybuffer");
      const binaryContent = new Promise((resolve, reject2) => {
        binaryLoader.load("rhino3dm.wasm", resolve, void 0, reject2);
      });
      this.libraryPending = Promise.all([jsContent, binaryContent]).then(([jsContent2, binaryContent2]) => {
        this.libraryConfig.wasmBinary = binaryContent2;
        const fn = Rhino3dmWorker.toString();
        const body = [
          "/* rhino3dm.js */",
          jsContent2,
          "/* worker */",
          fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}"))
        ].join("\n");
        this.workerSourceURL = URL.createObjectURL(new Blob([body]));
      });
    }
    return this.libraryPending;
  }
  _getWorker(taskCost) {
    return this._initLibrary().then(() => {
      if (this.workerPool.length < this.workerLimit) {
        const worker2 = new Worker(this.workerSourceURL);
        worker2._callbacks = {};
        worker2._taskCosts = {};
        worker2._taskLoad = 0;
        worker2.postMessage({
          type: "init",
          libraryConfig: this.libraryConfig
        });
        worker2.onmessage = (e) => {
          const message = e.data;
          switch (message.type) {
            case "warning":
              this.warnings.push(message.data);
              console.warn(message.data);
              break;
            case "decode":
              worker2._callbacks[message.id].resolve(message);
              break;
            case "error":
              worker2._callbacks[message.id].reject(message);
              break;
            default:
              console.error('THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"');
          }
        };
        this.workerPool.push(worker2);
      } else {
        this.workerPool.sort(function(a2, b3) {
          return a2._taskLoad > b3._taskLoad ? -1 : 1;
        });
      }
      const worker = this.workerPool[this.workerPool.length - 1];
      worker._taskLoad += taskCost;
      return worker;
    });
  }
  _releaseTask(worker, taskID) {
    worker._taskLoad -= worker._taskCosts[taskID];
    delete worker._callbacks[taskID];
    delete worker._taskCosts[taskID];
  }
  /**
   * Frees internal resources. This method should be called
   * when the loader is no longer required.
   */
  dispose() {
    for (let i = 0; i < this.workerPool.length; ++i) {
      this.workerPool[i].terminate();
    }
    this.workerPool.length = 0;
  }
};
function Rhino3dmWorker() {
  let libraryPending;
  let libraryConfig;
  let rhino;
  let taskID;
  onmessage = function(e) {
    const message = e.data;
    switch (message.type) {
      case "init":
        libraryConfig = message.libraryConfig;
        const wasmBinary = libraryConfig.wasmBinary;
        let RhinoModule;
        libraryPending = new Promise(function(resolve) {
          RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
          rhino3dm(RhinoModule);
        }).then(() => {
          rhino = RhinoModule;
        });
        break;
      case "decode":
        taskID = message.id;
        const buffer = message.buffer;
        libraryPending.then(() => {
          try {
            const data2 = decodeObjects(rhino, buffer);
            self.postMessage({ type: "decode", id: message.id, data: data2 });
          } catch (error) {
            self.postMessage({ type: "error", id: message.id, error });
          }
        });
        break;
    }
  };
  function decodeObjects(rhino2, buffer) {
    const arr = new Uint8Array(buffer);
    const doc = rhino2.File3dm.fromByteArray(arr);
    const objects = [];
    const materials = [];
    const layers = [];
    const views = [];
    const namedViews = [];
    const groups = [];
    const strings = [];
    const objs = doc.objects();
    const cnt = objs.count;
    for (let i = 0; i < cnt; i++) {
      const _object = objs.get(i);
      const object = extractObjectData(_object, doc);
      _object.delete();
      if (object) {
        objects.push(object);
      }
    }
    for (let i = 0; i < doc.instanceDefinitions().count; i++) {
      const idef = doc.instanceDefinitions().get(i);
      const idefAttributes = extractProperties(idef);
      idefAttributes.objectIds = idef.getObjectIds();
      objects.push({ geometry: null, attributes: idefAttributes, objectType: "InstanceDefinition" });
    }
    const textureTypes = [
      // rhino.TextureType.Bitmap,
      rhino2.TextureType.Diffuse,
      rhino2.TextureType.Bump,
      rhino2.TextureType.Transparency,
      rhino2.TextureType.Opacity,
      rhino2.TextureType.Emap
    ];
    const pbrTextureTypes = [
      rhino2.TextureType.PBR_BaseColor,
      rhino2.TextureType.PBR_Subsurface,
      rhino2.TextureType.PBR_SubsurfaceScattering,
      rhino2.TextureType.PBR_SubsurfaceScatteringRadius,
      rhino2.TextureType.PBR_Metallic,
      rhino2.TextureType.PBR_Specular,
      rhino2.TextureType.PBR_SpecularTint,
      rhino2.TextureType.PBR_Roughness,
      rhino2.TextureType.PBR_Anisotropic,
      rhino2.TextureType.PBR_Anisotropic_Rotation,
      rhino2.TextureType.PBR_Sheen,
      rhino2.TextureType.PBR_SheenTint,
      rhino2.TextureType.PBR_Clearcoat,
      rhino2.TextureType.PBR_ClearcoatBump,
      rhino2.TextureType.PBR_ClearcoatRoughness,
      rhino2.TextureType.PBR_OpacityIor,
      rhino2.TextureType.PBR_OpacityRoughness,
      rhino2.TextureType.PBR_Emission,
      rhino2.TextureType.PBR_AmbientOcclusion,
      rhino2.TextureType.PBR_Displacement
    ];
    for (let i = 0; i < doc.materials().count; i++) {
      const _material = doc.materials().get(i);
      const material = extractProperties(_material);
      const textures = [];
      textures.push(...extractTextures(_material, textureTypes, doc));
      material.pbrSupported = _material.physicallyBased().supported;
      if (material.pbrSupported) {
        textures.push(...extractTextures(_material, pbrTextureTypes, doc));
        material.pbr = extractProperties(_material.physicallyBased());
      }
      material.textures = textures;
      materials.push(material);
      _material.delete();
    }
    for (let i = 0; i < doc.layers().count; i++) {
      const _layer = doc.layers().get(i);
      const layer = extractProperties(_layer);
      layers.push(layer);
      _layer.delete();
    }
    for (let i = 0; i < doc.views().count; i++) {
      const _view = doc.views().get(i);
      const view = extractProperties(_view);
      views.push(view);
      _view.delete();
    }
    for (let i = 0; i < doc.namedViews().count; i++) {
      const _namedView = doc.namedViews().get(i);
      const namedView = extractProperties(_namedView);
      namedViews.push(namedView);
      _namedView.delete();
    }
    for (let i = 0; i < doc.groups().count; i++) {
      const _group = doc.groups().get(i);
      const group = extractProperties(_group);
      groups.push(group);
      _group.delete();
    }
    const settings = extractProperties(doc.settings());
    const strings_count = doc.strings().count;
    for (let i = 0; i < strings_count; i++) {
      strings.push(doc.strings().get(i));
    }
    const reflectionId = doc.settings().renderSettings().renderEnvironments.reflectionId;
    const rc = doc.renderContent();
    let renderEnvironment = null;
    for (let i = 0; i < rc.count; i++) {
      const content2 = rc.get(i);
      switch (content2.kind) {
        case "environment":
          const id = content2.id;
          if (id !== reflectionId) break;
          const renderTexture = content2.findChild("texture");
          const fileName = renderTexture.fileName;
          for (let j2 = 0; j2 < doc.embeddedFiles().count; j2++) {
            const _fileName = doc.embeddedFiles().get(j2).fileName;
            if (fileName === _fileName) {
              const background = doc.getEmbeddedFileAsBase64(fileName);
              const backgroundImage = "data:image/png;base64," + background;
              renderEnvironment = { type: "renderEnvironment", image: backgroundImage, name: fileName };
            }
          }
          break;
      }
    }
    const renderSettings = {
      ambientLight: doc.settings().renderSettings().ambientLight,
      backgroundColorTop: doc.settings().renderSettings().backgroundColorTop,
      backgroundColorBottom: doc.settings().renderSettings().backgroundColorBottom,
      useHiddenLights: doc.settings().renderSettings().useHiddenLights,
      depthCue: doc.settings().renderSettings().depthCue,
      flatShade: doc.settings().renderSettings().flatShade,
      renderBackFaces: doc.settings().renderSettings().renderBackFaces,
      renderPoints: doc.settings().renderSettings().renderPoints,
      renderCurves: doc.settings().renderSettings().renderCurves,
      renderIsoParams: doc.settings().renderSettings().renderIsoParams,
      renderMeshEdges: doc.settings().renderSettings().renderMeshEdges,
      renderAnnotations: doc.settings().renderSettings().renderAnnotations,
      useViewportSize: doc.settings().renderSettings().useViewportSize,
      scaleBackgroundToFit: doc.settings().renderSettings().scaleBackgroundToFit,
      transparentBackground: doc.settings().renderSettings().transparentBackground,
      imageDpi: doc.settings().renderSettings().imageDpi,
      shadowMapLevel: doc.settings().renderSettings().shadowMapLevel,
      namedView: doc.settings().renderSettings().namedView,
      snapShot: doc.settings().renderSettings().snapShot,
      specificViewport: doc.settings().renderSettings().specificViewport,
      groundPlane: extractProperties(doc.settings().renderSettings().groundPlane),
      safeFrame: extractProperties(doc.settings().renderSettings().safeFrame),
      dithering: extractProperties(doc.settings().renderSettings().dithering),
      skylight: extractProperties(doc.settings().renderSettings().skylight),
      linearWorkflow: extractProperties(doc.settings().renderSettings().linearWorkflow),
      renderChannels: extractProperties(doc.settings().renderSettings().renderChannels),
      sun: extractProperties(doc.settings().renderSettings().sun),
      renderEnvironments: extractProperties(doc.settings().renderSettings().renderEnvironments),
      postEffects: extractProperties(doc.settings().renderSettings().postEffects)
    };
    doc.delete();
    return { objects, materials, layers, views, namedViews, groups, strings, settings, renderSettings, renderEnvironment };
  }
  function extractTextures(m, tTypes, d) {
    const textures = [];
    for (let i = 0; i < tTypes.length; i++) {
      const _texture = m.getTexture(tTypes[i]);
      if (_texture) {
        let textureType = tTypes[i].constructor.name;
        textureType = textureType.substring(12, textureType.length);
        const texture = extractTextureData(_texture, textureType, d);
        textures.push(texture);
        _texture.delete();
      }
    }
    return textures;
  }
  function extractTextureData(t3, tType, d) {
    const texture = { type: tType };
    const image = d.getEmbeddedFileAsBase64(t3.fileName);
    texture.wrapU = t3.wrapU;
    texture.wrapV = t3.wrapV;
    texture.wrapW = t3.wrapW;
    const uvw = t3.uvwTransform.toFloatArray(true);
    texture.repeat = [uvw[0], uvw[5]];
    if (image) {
      texture.image = "data:image/png;base64," + image;
    } else {
      self.postMessage({
        type: "warning",
        id: taskID,
        data: {
          message: `THREE.3DMLoader: Image for ${tType} texture not embedded in file.`,
          type: "missing resource"
        }
      });
      texture.image = null;
    }
    return texture;
  }
  function extractObjectData(object, doc) {
    const _geometry2 = object.geometry();
    const _attributes = object.attributes();
    let objectType = _geometry2.objectType;
    let geometry, attributes, position2, data2, mesh;
    switch (objectType) {
      case rhino.ObjectType.Curve:
        const pts = curveToPoints(_geometry2, 100);
        position2 = {};
        attributes = {};
        data2 = {};
        position2.itemSize = 3;
        position2.type = "Float32Array";
        position2.array = [];
        for (let j2 = 0; j2 < pts.length; j2++) {
          position2.array.push(pts[j2][0]);
          position2.array.push(pts[j2][1]);
          position2.array.push(pts[j2][2]);
        }
        attributes.position = position2;
        data2.attributes = attributes;
        geometry = { data: data2 };
        break;
      case rhino.ObjectType.Point:
        const pt = _geometry2.location;
        position2 = {};
        const color = {};
        attributes = {};
        data2 = {};
        position2.itemSize = 3;
        position2.type = "Float32Array";
        position2.array = [pt[0], pt[1], pt[2]];
        const _color5 = _attributes.drawColor(doc);
        color.itemSize = 3;
        color.type = "Float32Array";
        color.array = [_color5.r / 255, _color5.g / 255, _color5.b / 255];
        attributes.position = position2;
        attributes.color = color;
        data2.attributes = attributes;
        geometry = { data: data2 };
        break;
      case rhino.ObjectType.PointSet:
      case rhino.ObjectType.Mesh:
        geometry = _geometry2.toThreejsJSON();
        break;
      case rhino.ObjectType.Brep:
        const faces = _geometry2.faces();
        mesh = new rhino.Mesh();
        for (let faceIndex = 0; faceIndex < faces.count; faceIndex++) {
          const face = faces.get(faceIndex);
          const _mesh = face.getMesh(rhino.MeshType.Any);
          if (_mesh) {
            mesh.append(_mesh);
            _mesh.delete();
          }
          face.delete();
        }
        if (mesh.faces().count > 0) {
          mesh.compact();
          geometry = mesh.toThreejsJSON();
          faces.delete();
        }
        mesh.delete();
        break;
      case rhino.ObjectType.Extrusion:
        mesh = _geometry2.getMesh(rhino.MeshType.Any);
        if (mesh) {
          geometry = mesh.toThreejsJSON();
          mesh.delete();
        }
        break;
      case rhino.ObjectType.TextDot:
        geometry = extractProperties(_geometry2);
        break;
      case rhino.ObjectType.Light:
        geometry = extractProperties(_geometry2);
        if (geometry.lightStyle.name === "LightStyle_WorldLinear") {
          self.postMessage({
            type: "warning",
            id: taskID,
            data: {
              message: `THREE.3DMLoader: No conversion exists for ${objectType.constructor.name} ${geometry.lightStyle.name}`,
              type: "no conversion",
              guid: _attributes.id
            }
          });
        }
        break;
      case rhino.ObjectType.InstanceReference:
        geometry = extractProperties(_geometry2);
        geometry.xform = extractProperties(_geometry2.xform);
        geometry.xform.array = _geometry2.xform.toFloatArray(true);
        break;
      case rhino.ObjectType.SubD:
        _geometry2.subdivide(3);
        mesh = rhino.Mesh.createFromSubDControlNet(_geometry2, false);
        if (mesh) {
          geometry = mesh.toThreejsJSON();
          mesh.delete();
        }
        break;
      /*
      case rhino.ObjectType.Annotation:
      case rhino.ObjectType.Hatch:
      case rhino.ObjectType.ClipPlane:
      */
      default:
        self.postMessage({
          type: "warning",
          id: taskID,
          data: {
            message: `THREE.3DMLoader: Conversion not implemented for ${objectType.constructor.name}`,
            type: "not implemented",
            guid: _attributes.id
          }
        });
        break;
    }
    if (geometry) {
      attributes = extractProperties(_attributes);
      attributes.geometry = extractProperties(_geometry2);
      if (_attributes.groupCount > 0) {
        attributes.groupIds = _attributes.getGroupList();
      }
      if (_attributes.userStringCount > 0) {
        attributes.userStrings = _attributes.getUserStrings();
      }
      if (_geometry2.userStringCount > 0) {
        attributes.geometry.userStrings = _geometry2.getUserStrings();
      }
      if (_attributes.decals().count > 0) {
        self.postMessage({
          type: "warning",
          id: taskID,
          data: {
            message: "THREE.3DMLoader: No conversion exists for the decals associated with this object.",
            type: "no conversion",
            guid: _attributes.id
          }
        });
      }
      attributes.drawColor = _attributes.drawColor(doc);
      objectType = objectType.constructor.name;
      objectType = objectType.substring(11, objectType.length);
      return { geometry, attributes, objectType };
    } else {
      self.postMessage({
        type: "warning",
        id: taskID,
        data: {
          message: `THREE.3DMLoader: ${objectType.constructor.name} has no associated mesh geometry.`,
          type: "missing mesh",
          guid: _attributes.id
        }
      });
    }
  }
  function extractProperties(object) {
    const result = {};
    for (const property2 in object) {
      const value2 = object[property2];
      if (typeof value2 !== "function") {
        if (typeof value2 === "object" && value2 !== null && value2.hasOwnProperty("constructor")) {
          result[property2] = { name: value2.constructor.name, value: value2.value };
        } else if (typeof value2 === "object" && value2 !== null) {
          result[property2] = extractProperties(value2);
        } else {
          result[property2] = value2;
        }
      } else {
      }
    }
    return result;
  }
  function curveToPoints(curve, pointLimit) {
    let pointCount = pointLimit;
    let rc = [];
    const ts = [];
    if (curve instanceof rhino.LineCurve) {
      return [curve.pointAtStart, curve.pointAtEnd];
    }
    if (curve instanceof rhino.PolylineCurve) {
      pointCount = curve.pointCount;
      for (let i = 0; i < pointCount; i++) {
        rc.push(curve.point(i));
      }
      return rc;
    }
    if (curve instanceof rhino.PolyCurve) {
      const segmentCount = curve.segmentCount;
      for (let i = 0; i < segmentCount; i++) {
        const segment = curve.segmentCurve(i);
        const segmentArray = curveToPoints(segment, pointCount);
        rc = rc.concat(segmentArray);
        segment.delete();
      }
      return rc;
    }
    if (curve instanceof rhino.ArcCurve) {
      pointCount = Math.floor(curve.angleDegrees / 5);
      pointCount = pointCount < 2 ? 2 : pointCount;
    }
    if (curve instanceof rhino.NurbsCurve && curve.degree === 1) {
      const pLine = curve.tryGetPolyline();
      for (let i = 0; i < pLine.count; i++) {
        rc.push(pLine.get(i));
      }
      pLine.delete();
      return rc;
    }
    const domain = curve.domain;
    const divisions = pointCount - 1;
    for (let j2 = 0; j2 < pointCount; j2++) {
      const t3 = domain[0] + j2 / divisions * (domain[1] - domain[0]);
      if (t3 === domain[0] || t3 === domain[1]) {
        ts.push(t3);
        continue;
      }
      const tan = curve.tangentAt(t3);
      const prevTan = curve.tangentAt(ts.slice(-1)[0]);
      const tS = tan[0] * tan[0] + tan[1] * tan[1] + tan[2] * tan[2];
      const ptS = prevTan[0] * prevTan[0] + prevTan[1] * prevTan[1] + prevTan[2] * prevTan[2];
      const denominator = Math.sqrt(tS * ptS);
      let angle;
      if (denominator === 0) {
        angle = Math.PI / 2;
      } else {
        const theta = (tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z) / denominator;
        angle = Math.acos(Math.max(-1, Math.min(1, theta)));
      }
      if (angle < 0.1) continue;
      ts.push(t3);
    }
    rc = ts.map((t3) => curve.pointAt(t3));
    return rc;
  }
}

// node_modules/three/examples/jsm/loaders/3MFLoader.js
var COLOR_SPACE_3MF = SRGBColorSpace;
var ThreeMFLoader = class extends Loader {
  /**
   * Constructs a new 3MF loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.availableExtensions = [];
  }
  /**
   * Starts loading from the given URL and passes the loaded 3MF asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Group)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(buffer) {
      try {
        onLoad(scope.parse(buffer));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given 3MF data and returns the resulting group.
   *
   * @param {ArrayBuffer} data - The raw 3MF asset data as an array buffer.
   * @return {Group} A group representing the parsed asset.
   */
  parse(data2) {
    const scope = this;
    const textureLoader = new TextureLoader(this.manager);
    function loadDocument(data3) {
      let zip = null;
      let file = null;
      let relsName;
      let modelRelsName;
      const modelPartNames = [];
      const texturesPartNames = [];
      let modelRels;
      const modelParts = {};
      const printTicketParts = {};
      const texturesParts = {};
      const textDecoder = new TextDecoder();
      try {
        zip = unzipSync(new Uint8Array(data3));
      } catch (e) {
        if (e instanceof ReferenceError) {
          console.error("THREE.3MFLoader: fflate missing and file is compressed.");
          return null;
        }
      }
      let rootModelFile = null;
      for (file in zip) {
        if (file.match(/\_rels\/.rels$/)) {
          relsName = file;
        } else if (file.match(/3D\/_rels\/.*\.model\.rels$/)) {
          modelRelsName = file;
        } else if (file.match(/^3D\/[^\/]*\.model$/)) {
          rootModelFile = file;
        } else if (file.match(/^3D\/.*\/.*\.model$/)) {
          modelPartNames.push(file);
        } else if (file.match(/^3D\/Textures?\/.*/)) {
          texturesPartNames.push(file);
        }
      }
      modelPartNames.push(rootModelFile);
      if (relsName === void 0) throw new Error("THREE.ThreeMFLoader: Cannot find relationship file `rels` in 3MF archive.");
      const relsView = zip[relsName];
      const relsFileText = textDecoder.decode(relsView);
      const rels = parseRelsXml(relsFileText);
      if (modelRelsName) {
        const relsView2 = zip[modelRelsName];
        const relsFileText2 = textDecoder.decode(relsView2);
        modelRels = parseRelsXml(relsFileText2);
      }
      for (let i = 0; i < modelPartNames.length; i++) {
        const modelPart = modelPartNames[i];
        const view = zip[modelPart];
        const fileText = textDecoder.decode(view);
        const xmlData = new DOMParser().parseFromString(fileText, "application/xml");
        if (xmlData.documentElement.nodeName.toLowerCase() !== "model") {
          console.error("THREE.3MFLoader: Error loading 3MF - no 3MF document found: ", modelPart);
        }
        const modelNode = xmlData.querySelector("model");
        const extensions = {};
        for (let i2 = 0; i2 < modelNode.attributes.length; i2++) {
          const attr = modelNode.attributes[i2];
          if (attr.name.match(/^xmlns:(.+)$/)) {
            extensions[attr.value] = RegExp.$1;
          }
        }
        const modelData = parseModelNode(modelNode);
        modelData["xml"] = modelNode;
        if (0 < Object.keys(extensions).length) {
          modelData["extensions"] = extensions;
        }
        modelParts[modelPart] = modelData;
      }
      for (let i = 0; i < texturesPartNames.length; i++) {
        const texturesPartName = texturesPartNames[i];
        texturesParts[texturesPartName] = zip[texturesPartName].buffer;
      }
      return {
        rels,
        modelRels,
        model: modelParts,
        printTicket: printTicketParts,
        texture: texturesParts
      };
    }
    function parseRelsXml(relsFileText) {
      const relationships = [];
      const relsXmlData = new DOMParser().parseFromString(relsFileText, "application/xml");
      const relsNodes = relsXmlData.querySelectorAll("Relationship");
      for (let i = 0; i < relsNodes.length; i++) {
        const relsNode = relsNodes[i];
        const relationship = {
          target: relsNode.getAttribute("Target"),
          //required
          id: relsNode.getAttribute("Id"),
          //required
          type: relsNode.getAttribute("Type")
          //required
        };
        relationships.push(relationship);
      }
      return relationships;
    }
    function parseMetadataNodes(metadataNodes) {
      const metadataData = {};
      for (let i = 0; i < metadataNodes.length; i++) {
        const metadataNode = metadataNodes[i];
        const name2 = metadataNode.getAttribute("name");
        const validNames = [
          "Title",
          "Designer",
          "Description",
          "Copyright",
          "LicenseTerms",
          "Rating",
          "CreationDate",
          "ModificationDate"
        ];
        if (0 <= validNames.indexOf(name2)) {
          metadataData[name2] = metadataNode.textContent;
        }
      }
      return metadataData;
    }
    function parseBasematerialsNode(basematerialsNode) {
      const basematerialsData = {
        id: basematerialsNode.getAttribute("id"),
        // required
        basematerials: []
      };
      const basematerialNodes = basematerialsNode.querySelectorAll("base");
      for (let i = 0; i < basematerialNodes.length; i++) {
        const basematerialNode = basematerialNodes[i];
        const basematerialData = parseBasematerialNode(basematerialNode);
        basematerialData.index = i;
        basematerialsData.basematerials.push(basematerialData);
      }
      return basematerialsData;
    }
    function parseTexture2DNode(texture2DNode) {
      const texture2dData = {
        id: texture2DNode.getAttribute("id"),
        // required
        path: texture2DNode.getAttribute("path"),
        // required
        contenttype: texture2DNode.getAttribute("contenttype"),
        // required
        tilestyleu: texture2DNode.getAttribute("tilestyleu"),
        tilestylev: texture2DNode.getAttribute("tilestylev"),
        filter: texture2DNode.getAttribute("filter")
      };
      return texture2dData;
    }
    function parseTextures2DGroupNode(texture2DGroupNode) {
      const texture2DGroupData = {
        id: texture2DGroupNode.getAttribute("id"),
        // required
        texid: texture2DGroupNode.getAttribute("texid"),
        // required
        displaypropertiesid: texture2DGroupNode.getAttribute("displaypropertiesid")
      };
      const tex2coordNodes = texture2DGroupNode.querySelectorAll("tex2coord");
      const uvs = [];
      for (let i = 0; i < tex2coordNodes.length; i++) {
        const tex2coordNode = tex2coordNodes[i];
        const u2 = tex2coordNode.getAttribute("u");
        const v = tex2coordNode.getAttribute("v");
        uvs.push(parseFloat(u2), parseFloat(v));
      }
      texture2DGroupData["uvs"] = new Float32Array(uvs);
      return texture2DGroupData;
    }
    function parseColorGroupNode(colorGroupNode) {
      const colorGroupData = {
        id: colorGroupNode.getAttribute("id"),
        // required
        displaypropertiesid: colorGroupNode.getAttribute("displaypropertiesid")
      };
      const colorNodes = colorGroupNode.querySelectorAll("color");
      const colors = [];
      const colorObject = new Color();
      for (let i = 0; i < colorNodes.length; i++) {
        const colorNode = colorNodes[i];
        const color = colorNode.getAttribute("color");
        colorObject.setStyle(color.substring(0, 7), COLOR_SPACE_3MF);
        colors.push(colorObject.r, colorObject.g, colorObject.b);
      }
      colorGroupData["colors"] = new Float32Array(colors);
      return colorGroupData;
    }
    function parseImplicitIONode(implicitIONode) {
      const portNodes = implicitIONode.children;
      const portArguments = {};
      for (let i = 0; i < portNodes.length; i++) {
        const args = { type: portNodes[i].nodeName.substring(2) };
        for (let j2 = 0; j2 < portNodes[i].attributes.length; j2++) {
          const attrib = portNodes[i].attributes[j2];
          if (attrib.specified) {
            args[attrib.name] = attrib.value;
          }
        }
        portArguments[portNodes[i].getAttribute("identifier")] = args;
      }
      return portArguments;
    }
    function parseImplicitFunctionNode(implicitFunctionNode) {
      const implicitFunctionData = {
        id: implicitFunctionNode.getAttribute("id"),
        displayname: implicitFunctionNode.getAttribute("displayname")
      };
      const functionNodes = implicitFunctionNode.children;
      const operations = {};
      for (let i = 0; i < functionNodes.length; i++) {
        const operatorNode = functionNodes[i];
        if (operatorNode.nodeName === "i:in" || operatorNode.nodeName === "i:out") {
          operations[operatorNode.nodeName === "i:in" ? "inputs" : "outputs"] = parseImplicitIONode(operatorNode);
        } else {
          const inputNodes = operatorNode.children;
          const portArguments = { "op": operatorNode.nodeName.substring(2), "identifier": operatorNode.getAttribute("identifier") };
          for (let i2 = 0; i2 < inputNodes.length; i2++) {
            portArguments[inputNodes[i2].nodeName.substring(2)] = parseImplicitIONode(inputNodes[i2]);
          }
          operations[portArguments["identifier"]] = portArguments;
        }
      }
      implicitFunctionData["operations"] = operations;
      return implicitFunctionData;
    }
    function parseMetallicDisplaypropertiesNode(metallicDisplaypropetiesNode) {
      const metallicDisplaypropertiesData = {
        id: metallicDisplaypropetiesNode.getAttribute("id")
        // required
      };
      const metallicNodes = metallicDisplaypropetiesNode.querySelectorAll("pbmetallic");
      const metallicData = [];
      for (let i = 0; i < metallicNodes.length; i++) {
        const metallicNode = metallicNodes[i];
        metallicData.push({
          name: metallicNode.getAttribute("name"),
          // required
          metallicness: parseFloat(metallicNode.getAttribute("metallicness")),
          // required
          roughness: parseFloat(metallicNode.getAttribute("roughness"))
          // required
        });
      }
      metallicDisplaypropertiesData.data = metallicData;
      return metallicDisplaypropertiesData;
    }
    function parseBasematerialNode(basematerialNode) {
      const basematerialData = {};
      basematerialData["name"] = basematerialNode.getAttribute("name");
      basematerialData["displaycolor"] = basematerialNode.getAttribute("displaycolor");
      basematerialData["displaypropertiesid"] = basematerialNode.getAttribute("displaypropertiesid");
      return basematerialData;
    }
    function parseMeshNode(meshNode) {
      const meshData = {};
      const vertices = [];
      const vertexNodes = meshNode.querySelectorAll("vertices vertex");
      for (let i = 0; i < vertexNodes.length; i++) {
        const vertexNode = vertexNodes[i];
        const x2 = vertexNode.getAttribute("x");
        const y = vertexNode.getAttribute("y");
        const z = vertexNode.getAttribute("z");
        vertices.push(parseFloat(x2), parseFloat(y), parseFloat(z));
      }
      meshData["vertices"] = new Float32Array(vertices);
      const triangleProperties = [];
      const triangles = [];
      const triangleNodes = meshNode.querySelectorAll("triangles triangle");
      for (let i = 0; i < triangleNodes.length; i++) {
        const triangleNode = triangleNodes[i];
        const v12 = triangleNode.getAttribute("v1");
        const v2 = triangleNode.getAttribute("v2");
        const v3 = triangleNode.getAttribute("v3");
        const p1 = triangleNode.getAttribute("p1");
        const p2 = triangleNode.getAttribute("p2");
        const p3 = triangleNode.getAttribute("p3");
        const pid = triangleNode.getAttribute("pid");
        const triangleProperty = {};
        triangleProperty["v1"] = parseInt(v12, 10);
        triangleProperty["v2"] = parseInt(v2, 10);
        triangleProperty["v3"] = parseInt(v3, 10);
        triangles.push(triangleProperty["v1"], triangleProperty["v2"], triangleProperty["v3"]);
        if (p1) {
          triangleProperty["p1"] = parseInt(p1, 10);
        }
        if (p2) {
          triangleProperty["p2"] = parseInt(p2, 10);
        }
        if (p3) {
          triangleProperty["p3"] = parseInt(p3, 10);
        }
        if (pid) {
          triangleProperty["pid"] = pid;
        }
        if (0 < Object.keys(triangleProperty).length) {
          triangleProperties.push(triangleProperty);
        }
      }
      meshData["triangleProperties"] = triangleProperties;
      meshData["triangles"] = new Uint32Array(triangles);
      return meshData;
    }
    function parseComponentsNode(componentsNode) {
      const components = [];
      const componentNodes = componentsNode.querySelectorAll("component");
      for (let i = 0; i < componentNodes.length; i++) {
        const componentNode = componentNodes[i];
        const componentData = parseComponentNode(componentNode);
        components.push(componentData);
      }
      return components;
    }
    function parseComponentNode(componentNode) {
      const componentData = {};
      componentData["objectId"] = componentNode.getAttribute("objectid");
      const transform2 = componentNode.getAttribute("transform");
      if (transform2) {
        componentData["transform"] = parseTransform(transform2);
      }
      return componentData;
    }
    function parseTransform(transform2) {
      const t3 = [];
      transform2.split(" ").forEach(function(s) {
        t3.push(parseFloat(s));
      });
      const matrix2 = new Matrix4();
      matrix2.set(
        t3[0],
        t3[3],
        t3[6],
        t3[9],
        t3[1],
        t3[4],
        t3[7],
        t3[10],
        t3[2],
        t3[5],
        t3[8],
        t3[11],
        0,
        0,
        0,
        1
      );
      return matrix2;
    }
    function parseObjectNode(objectNode) {
      const objectData = {
        type: objectNode.getAttribute("type")
      };
      const id = objectNode.getAttribute("id");
      if (id) {
        objectData["id"] = id;
      }
      const pid = objectNode.getAttribute("pid");
      if (pid) {
        objectData["pid"] = pid;
      }
      const pindex = objectNode.getAttribute("pindex");
      if (pindex) {
        objectData["pindex"] = pindex;
      }
      const thumbnail = objectNode.getAttribute("thumbnail");
      if (thumbnail) {
        objectData["thumbnail"] = thumbnail;
      }
      const partnumber = objectNode.getAttribute("partnumber");
      if (partnumber) {
        objectData["partnumber"] = partnumber;
      }
      const name2 = objectNode.getAttribute("name");
      if (name2) {
        objectData["name"] = name2;
      }
      const meshNode = objectNode.querySelector("mesh");
      if (meshNode) {
        objectData["mesh"] = parseMeshNode(meshNode);
      }
      const componentsNode = objectNode.querySelector("components");
      if (componentsNode) {
        objectData["components"] = parseComponentsNode(componentsNode);
      }
      return objectData;
    }
    function parseResourcesNode(resourcesNode) {
      const resourcesData = {};
      resourcesData["basematerials"] = {};
      const basematerialsNodes = resourcesNode.querySelectorAll("basematerials");
      for (let i = 0; i < basematerialsNodes.length; i++) {
        const basematerialsNode = basematerialsNodes[i];
        const basematerialsData = parseBasematerialsNode(basematerialsNode);
        resourcesData["basematerials"][basematerialsData["id"]] = basematerialsData;
      }
      resourcesData["texture2d"] = {};
      const textures2DNodes = resourcesNode.querySelectorAll("texture2d");
      for (let i = 0; i < textures2DNodes.length; i++) {
        const textures2DNode = textures2DNodes[i];
        const texture2DData = parseTexture2DNode(textures2DNode);
        resourcesData["texture2d"][texture2DData["id"]] = texture2DData;
      }
      resourcesData["colorgroup"] = {};
      const colorGroupNodes = resourcesNode.querySelectorAll("colorgroup");
      for (let i = 0; i < colorGroupNodes.length; i++) {
        const colorGroupNode = colorGroupNodes[i];
        const colorGroupData = parseColorGroupNode(colorGroupNode);
        resourcesData["colorgroup"][colorGroupData["id"]] = colorGroupData;
      }
      const implicitFunctionNodes = resourcesNode.querySelectorAll("implicitfunction");
      if (implicitFunctionNodes.length > 0) {
        resourcesData["implicitfunction"] = {};
      }
      for (let i = 0; i < implicitFunctionNodes.length; i++) {
        const implicitFunctionNode = implicitFunctionNodes[i];
        const implicitFunctionData = parseImplicitFunctionNode(implicitFunctionNode);
        resourcesData["implicitfunction"][implicitFunctionData["id"]] = implicitFunctionData;
      }
      resourcesData["pbmetallicdisplayproperties"] = {};
      const pbmetallicdisplaypropertiesNodes = resourcesNode.querySelectorAll("pbmetallicdisplayproperties");
      for (let i = 0; i < pbmetallicdisplaypropertiesNodes.length; i++) {
        const pbmetallicdisplaypropertiesNode = pbmetallicdisplaypropertiesNodes[i];
        const pbmetallicdisplaypropertiesData = parseMetallicDisplaypropertiesNode(pbmetallicdisplaypropertiesNode);
        resourcesData["pbmetallicdisplayproperties"][pbmetallicdisplaypropertiesData["id"]] = pbmetallicdisplaypropertiesData;
      }
      resourcesData["texture2dgroup"] = {};
      const textures2DGroupNodes = resourcesNode.querySelectorAll("texture2dgroup");
      for (let i = 0; i < textures2DGroupNodes.length; i++) {
        const textures2DGroupNode = textures2DGroupNodes[i];
        const textures2DGroupData = parseTextures2DGroupNode(textures2DGroupNode);
        resourcesData["texture2dgroup"][textures2DGroupData["id"]] = textures2DGroupData;
      }
      resourcesData["object"] = {};
      const objectNodes = resourcesNode.querySelectorAll("object");
      for (let i = 0; i < objectNodes.length; i++) {
        const objectNode = objectNodes[i];
        const objectData = parseObjectNode(objectNode);
        resourcesData["object"][objectData["id"]] = objectData;
      }
      return resourcesData;
    }
    function parseBuildNode(buildNode) {
      const buildData = [];
      const itemNodes = buildNode.querySelectorAll("item");
      for (let i = 0; i < itemNodes.length; i++) {
        const itemNode = itemNodes[i];
        const buildItem = {
          objectId: itemNode.getAttribute("objectid")
        };
        const transform2 = itemNode.getAttribute("transform");
        if (transform2) {
          buildItem["transform"] = parseTransform(transform2);
        }
        buildData.push(buildItem);
      }
      return buildData;
    }
    function parseModelNode(modelNode) {
      const modelData = { unit: modelNode.getAttribute("unit") || "millimeter" };
      const metadataNodes = modelNode.querySelectorAll("metadata");
      if (metadataNodes) {
        modelData["metadata"] = parseMetadataNodes(metadataNodes);
      }
      const resourcesNode = modelNode.querySelector("resources");
      if (resourcesNode) {
        modelData["resources"] = parseResourcesNode(resourcesNode);
      }
      const buildNode = modelNode.querySelector("build");
      if (buildNode) {
        modelData["build"] = parseBuildNode(buildNode);
      }
      return modelData;
    }
    function buildTexture(texture2dgroup, objects2, modelData, textureData) {
      const texid = texture2dgroup.texid;
      const texture2ds = modelData.resources.texture2d;
      const texture2d = texture2ds[texid];
      if (texture2d) {
        const data3 = textureData[texture2d.path];
        const type = texture2d.contenttype;
        const blob = new Blob([data3], { type });
        const sourceURI = URL.createObjectURL(blob);
        const texture = textureLoader.load(sourceURI, function() {
          URL.revokeObjectURL(sourceURI);
        });
        texture.colorSpace = COLOR_SPACE_3MF;
        switch (texture2d.tilestyleu) {
          case "wrap":
            texture.wrapS = RepeatWrapping;
            break;
          case "mirror":
            texture.wrapS = MirroredRepeatWrapping;
            break;
          case "none":
          case "clamp":
            texture.wrapS = ClampToEdgeWrapping;
            break;
          default:
            texture.wrapS = RepeatWrapping;
        }
        switch (texture2d.tilestylev) {
          case "wrap":
            texture.wrapT = RepeatWrapping;
            break;
          case "mirror":
            texture.wrapT = MirroredRepeatWrapping;
            break;
          case "none":
          case "clamp":
            texture.wrapT = ClampToEdgeWrapping;
            break;
          default:
            texture.wrapT = RepeatWrapping;
        }
        switch (texture2d.filter) {
          case "auto":
            texture.magFilter = LinearFilter;
            texture.minFilter = LinearMipmapLinearFilter;
            break;
          case "linear":
            texture.magFilter = LinearFilter;
            texture.minFilter = LinearFilter;
            texture.generateMipmaps = false;
            break;
          case "nearest":
            texture.magFilter = NearestFilter;
            texture.minFilter = NearestFilter;
            texture.generateMipmaps = false;
            break;
          default:
            texture.magFilter = LinearFilter;
            texture.minFilter = LinearMipmapLinearFilter;
        }
        return texture;
      } else {
        return null;
      }
    }
    function buildBasematerialsMeshes(basematerials, triangleProperties, meshData, objects2, modelData, textureData, objectData) {
      const objectPindex = objectData.pindex;
      const materialMap = {};
      for (let i = 0, l2 = triangleProperties.length; i < l2; i++) {
        const triangleProperty = triangleProperties[i];
        const pindex = triangleProperty.p1 !== void 0 ? triangleProperty.p1 : objectPindex;
        if (materialMap[pindex] === void 0) materialMap[pindex] = [];
        materialMap[pindex].push(triangleProperty);
      }
      const keys2 = Object.keys(materialMap);
      const meshes = [];
      for (let i = 0, l2 = keys2.length; i < l2; i++) {
        const materialIndex = keys2[i];
        const trianglePropertiesProps = materialMap[materialIndex];
        const basematerialData = basematerials.basematerials[materialIndex];
        const material = getBuild(basematerialData, objects2, modelData, textureData, objectData, buildBasematerial);
        const geometry = new BufferGeometry();
        const positionData = [];
        const vertices = meshData.vertices;
        for (let j2 = 0, jl = trianglePropertiesProps.length; j2 < jl; j2++) {
          const triangleProperty = trianglePropertiesProps[j2];
          positionData.push(vertices[triangleProperty.v1 * 3 + 0]);
          positionData.push(vertices[triangleProperty.v1 * 3 + 1]);
          positionData.push(vertices[triangleProperty.v1 * 3 + 2]);
          positionData.push(vertices[triangleProperty.v2 * 3 + 0]);
          positionData.push(vertices[triangleProperty.v2 * 3 + 1]);
          positionData.push(vertices[triangleProperty.v2 * 3 + 2]);
          positionData.push(vertices[triangleProperty.v3 * 3 + 0]);
          positionData.push(vertices[triangleProperty.v3 * 3 + 1]);
          positionData.push(vertices[triangleProperty.v3 * 3 + 2]);
        }
        geometry.setAttribute("position", new Float32BufferAttribute(positionData, 3));
        const mesh = new Mesh(geometry, material);
        meshes.push(mesh);
      }
      return meshes;
    }
    function buildTexturedMesh(texture2dgroup, triangleProperties, meshData, objects2, modelData, textureData, objectData) {
      const geometry = new BufferGeometry();
      const positionData = [];
      const uvData = [];
      const vertices = meshData.vertices;
      const uvs = texture2dgroup.uvs;
      for (let i = 0, l2 = triangleProperties.length; i < l2; i++) {
        const triangleProperty = triangleProperties[i];
        positionData.push(vertices[triangleProperty.v1 * 3 + 0]);
        positionData.push(vertices[triangleProperty.v1 * 3 + 1]);
        positionData.push(vertices[triangleProperty.v1 * 3 + 2]);
        positionData.push(vertices[triangleProperty.v2 * 3 + 0]);
        positionData.push(vertices[triangleProperty.v2 * 3 + 1]);
        positionData.push(vertices[triangleProperty.v2 * 3 + 2]);
        positionData.push(vertices[triangleProperty.v3 * 3 + 0]);
        positionData.push(vertices[triangleProperty.v3 * 3 + 1]);
        positionData.push(vertices[triangleProperty.v3 * 3 + 2]);
        uvData.push(uvs[triangleProperty.p1 * 2 + 0]);
        uvData.push(uvs[triangleProperty.p1 * 2 + 1]);
        uvData.push(uvs[triangleProperty.p2 * 2 + 0]);
        uvData.push(uvs[triangleProperty.p2 * 2 + 1]);
        uvData.push(uvs[triangleProperty.p3 * 2 + 0]);
        uvData.push(uvs[triangleProperty.p3 * 2 + 1]);
      }
      geometry.setAttribute("position", new Float32BufferAttribute(positionData, 3));
      geometry.setAttribute("uv", new Float32BufferAttribute(uvData, 2));
      const texture = getBuild(texture2dgroup, objects2, modelData, textureData, objectData, buildTexture);
      const material = new MeshPhongMaterial({ map: texture, flatShading: true });
      const mesh = new Mesh(geometry, material);
      return mesh;
    }
    function buildVertexColorMesh(colorgroup, triangleProperties, meshData, objectData) {
      const geometry = new BufferGeometry();
      const positionData = [];
      const colorData = [];
      const vertices = meshData.vertices;
      const colors = colorgroup.colors;
      for (let i = 0, l2 = triangleProperties.length; i < l2; i++) {
        const triangleProperty = triangleProperties[i];
        const v12 = triangleProperty.v1;
        const v2 = triangleProperty.v2;
        const v3 = triangleProperty.v3;
        positionData.push(vertices[v12 * 3 + 0]);
        positionData.push(vertices[v12 * 3 + 1]);
        positionData.push(vertices[v12 * 3 + 2]);
        positionData.push(vertices[v2 * 3 + 0]);
        positionData.push(vertices[v2 * 3 + 1]);
        positionData.push(vertices[v2 * 3 + 2]);
        positionData.push(vertices[v3 * 3 + 0]);
        positionData.push(vertices[v3 * 3 + 1]);
        positionData.push(vertices[v3 * 3 + 2]);
        const p1 = triangleProperty.p1 !== void 0 ? triangleProperty.p1 : objectData.pindex;
        const p2 = triangleProperty.p2 !== void 0 ? triangleProperty.p2 : p1;
        const p3 = triangleProperty.p3 !== void 0 ? triangleProperty.p3 : p1;
        colorData.push(colors[p1 * 3 + 0]);
        colorData.push(colors[p1 * 3 + 1]);
        colorData.push(colors[p1 * 3 + 2]);
        colorData.push(colors[p2 * 3 + 0]);
        colorData.push(colors[p2 * 3 + 1]);
        colorData.push(colors[p2 * 3 + 2]);
        colorData.push(colors[p3 * 3 + 0]);
        colorData.push(colors[p3 * 3 + 1]);
        colorData.push(colors[p3 * 3 + 2]);
      }
      geometry.setAttribute("position", new Float32BufferAttribute(positionData, 3));
      geometry.setAttribute("color", new Float32BufferAttribute(colorData, 3));
      const material = new MeshPhongMaterial({ vertexColors: true, flatShading: true });
      const mesh = new Mesh(geometry, material);
      return mesh;
    }
    function buildDefaultMesh(meshData) {
      const geometry = new BufferGeometry();
      geometry.setIndex(new BufferAttribute(meshData["triangles"], 1));
      geometry.setAttribute("position", new BufferAttribute(meshData["vertices"], 3));
      const material = new MeshPhongMaterial({
        name: Loader.DEFAULT_MATERIAL_NAME,
        color: 16777215,
        flatShading: true
      });
      const mesh = new Mesh(geometry, material);
      return mesh;
    }
    function buildMeshes(resourceMap, meshData, objects2, modelData, textureData, objectData) {
      const keys2 = Object.keys(resourceMap);
      const meshes = [];
      for (let i = 0, il = keys2.length; i < il; i++) {
        const resourceId = keys2[i];
        const triangleProperties = resourceMap[resourceId];
        const resourceType = getResourceType(resourceId, modelData);
        switch (resourceType) {
          case "material":
            const basematerials = modelData.resources.basematerials[resourceId];
            const newMeshes = buildBasematerialsMeshes(basematerials, triangleProperties, meshData, objects2, modelData, textureData, objectData);
            for (let j2 = 0, jl = newMeshes.length; j2 < jl; j2++) {
              meshes.push(newMeshes[j2]);
            }
            break;
          case "texture":
            const texture2dgroup = modelData.resources.texture2dgroup[resourceId];
            meshes.push(buildTexturedMesh(texture2dgroup, triangleProperties, meshData, objects2, modelData, textureData, objectData));
            break;
          case "vertexColors":
            const colorgroup = modelData.resources.colorgroup[resourceId];
            meshes.push(buildVertexColorMesh(colorgroup, triangleProperties, meshData, objectData));
            break;
          case "default":
            meshes.push(buildDefaultMesh(meshData));
            break;
          default:
            console.error("THREE.3MFLoader: Unsupported resource type.");
        }
      }
      if (objectData.name) {
        for (let i = 0; i < meshes.length; i++) {
          meshes[i].name = objectData.name;
        }
      }
      return meshes;
    }
    function getResourceType(pid, modelData) {
      if (modelData.resources.texture2dgroup[pid] !== void 0) {
        return "texture";
      } else if (modelData.resources.basematerials[pid] !== void 0) {
        return "material";
      } else if (modelData.resources.colorgroup[pid] !== void 0) {
        return "vertexColors";
      } else if (pid === "default") {
        return "default";
      } else {
        return void 0;
      }
    }
    function analyzeObject(meshData, objectData) {
      const resourceMap = {};
      const triangleProperties = meshData["triangleProperties"];
      const objectPid = objectData.pid;
      for (let i = 0, l2 = triangleProperties.length; i < l2; i++) {
        const triangleProperty = triangleProperties[i];
        let pid = triangleProperty.pid !== void 0 ? triangleProperty.pid : objectPid;
        if (pid === void 0) pid = "default";
        if (resourceMap[pid] === void 0) resourceMap[pid] = [];
        resourceMap[pid].push(triangleProperty);
      }
      return resourceMap;
    }
    function buildGroup(meshData, objects2, modelData, textureData, objectData) {
      const group = new Group();
      const resourceMap = analyzeObject(meshData, objectData);
      const meshes = buildMeshes(resourceMap, meshData, objects2, modelData, textureData, objectData);
      for (let i = 0, l2 = meshes.length; i < l2; i++) {
        group.add(meshes[i]);
      }
      return group;
    }
    function applyExtensions(extensions, meshData, modelXml) {
      if (!extensions) {
        return;
      }
      const availableExtensions = [];
      const keys2 = Object.keys(extensions);
      for (let i = 0; i < keys2.length; i++) {
        const ns = keys2[i];
        for (let j2 = 0; j2 < scope.availableExtensions.length; j2++) {
          const extension = scope.availableExtensions[j2];
          if (extension.ns === ns) {
            availableExtensions.push(extension);
          }
        }
      }
      for (let i = 0; i < availableExtensions.length; i++) {
        const extension = availableExtensions[i];
        extension.apply(modelXml, extensions[extension["ns"]], meshData);
      }
    }
    function getBuild(data3, objects2, modelData, textureData, objectData, builder) {
      if (data3.build !== void 0) return data3.build;
      data3.build = builder(data3, objects2, modelData, textureData, objectData);
      return data3.build;
    }
    function buildBasematerial(materialData, objects2, modelData) {
      let material;
      const displaypropertiesid = materialData.displaypropertiesid;
      const pbmetallicdisplayproperties = modelData.resources.pbmetallicdisplayproperties;
      if (displaypropertiesid !== null && pbmetallicdisplayproperties[displaypropertiesid] !== void 0) {
        const pbmetallicdisplayproperty = pbmetallicdisplayproperties[displaypropertiesid];
        const metallicData = pbmetallicdisplayproperty.data[materialData.index];
        material = new MeshStandardMaterial({ flatShading: true, roughness: metallicData.roughness, metalness: metallicData.metallicness });
      } else {
        material = new MeshPhongMaterial({ flatShading: true });
      }
      material.name = materialData.name;
      const displaycolor = materialData.displaycolor;
      const color = displaycolor.substring(0, 7);
      material.color.setStyle(color, COLOR_SPACE_3MF);
      if (displaycolor.length === 9) {
        material.opacity = parseInt(displaycolor.charAt(7) + displaycolor.charAt(8), 16) / 255;
      }
      return material;
    }
    function buildComposite(compositeData, objects2, modelData, textureData) {
      const composite = new Group();
      for (let j2 = 0; j2 < compositeData.length; j2++) {
        const component = compositeData[j2];
        let build2 = objects2[component.objectId];
        if (build2 === void 0) {
          buildObject(component.objectId, objects2, modelData, textureData);
          build2 = objects2[component.objectId];
        }
        const object3D = build2.clone();
        const transform2 = component.transform;
        if (transform2) {
          object3D.applyMatrix4(transform2);
        }
        composite.add(object3D);
      }
      return composite;
    }
    function buildObject(objectId, objects2, modelData, textureData) {
      const objectData = modelData["resources"]["object"][objectId];
      if (objectData["mesh"]) {
        const meshData = objectData["mesh"];
        const extensions = modelData["extensions"];
        const modelXml = modelData["xml"];
        applyExtensions(extensions, meshData, modelXml);
        objects2[objectData.id] = getBuild(meshData, objects2, modelData, textureData, objectData, buildGroup);
      } else {
        const compositeData = objectData["components"];
        objects2[objectData.id] = getBuild(compositeData, objects2, modelData, textureData, objectData, buildComposite);
      }
      if (objectData.name) {
        objects2[objectData.id].name = objectData.name;
      }
      if (modelData.resources.implicitfunction) {
        console.warn("THREE.ThreeMFLoader: Implicit Functions are implemented in data-only.", modelData.resources.implicitfunction);
      }
    }
    function buildObjects(data3mf2) {
      const modelsData = data3mf2.model;
      const modelRels = data3mf2.modelRels;
      const objects2 = {};
      const modelsKeys = Object.keys(modelsData);
      const textureData = {};
      if (modelRels) {
        for (let i = 0, l2 = modelRels.length; i < l2; i++) {
          const modelRel = modelRels[i];
          const textureKey = modelRel.target.substring(1);
          if (data3mf2.texture[textureKey]) {
            textureData[modelRel.target] = data3mf2.texture[textureKey];
          }
        }
      }
      for (let i = 0; i < modelsKeys.length; i++) {
        const modelsKey = modelsKeys[i];
        const modelData = modelsData[modelsKey];
        const objectIds = Object.keys(modelData["resources"]["object"]);
        for (let j2 = 0; j2 < objectIds.length; j2++) {
          const objectId = objectIds[j2];
          buildObject(objectId, objects2, modelData, textureData);
        }
      }
      return objects2;
    }
    function fetch3DModelPart(rels) {
      for (let i = 0; i < rels.length; i++) {
        const rel = rels[i];
        const extension = rel.target.split(".").pop();
        if (extension.toLowerCase() === "model") return rel;
      }
    }
    function build(objects2, data3mf2) {
      const group = new Group();
      const relationship = fetch3DModelPart(data3mf2["rels"]);
      const buildData = data3mf2.model[relationship["target"].substring(1)]["build"];
      for (let i = 0; i < buildData.length; i++) {
        const buildItem = buildData[i];
        const object3D = objects2[buildItem["objectId"]].clone();
        const transform2 = buildItem["transform"];
        if (transform2) {
          object3D.applyMatrix4(transform2);
        }
        group.add(object3D);
      }
      return group;
    }
    const data3mf = loadDocument(data2);
    const objects = buildObjects(data3mf);
    return build(objects, data3mf);
  }
  /**
   * Adds a 3MF extension.
   *
   * @param {Object} extension - The extension to add.
   */
  addExtension(extension) {
    this.availableExtensions.push(extension);
  }
};

// node_modules/three/examples/jsm/loaders/AMFLoader.js
var AMFLoader = class extends Loader {
  /**
   * Constructs a new AMF loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded AMF asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Group)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given AMF data and returns the resulting group.
   *
   * @param {ArrayBuffer} data - The raw AMF asset data as an array buffer.
   * @return {Group} A group representing the parsed asset.
   */
  parse(data2) {
    function loadDocument(data3) {
      let view = new DataView(data3);
      const magic = String.fromCharCode(view.getUint8(0), view.getUint8(1));
      if (magic === "PK") {
        let zip = null;
        let file = null;
        console.log("THREE.AMFLoader: Loading Zip");
        try {
          zip = unzipSync(new Uint8Array(data3));
        } catch (e) {
          if (e instanceof ReferenceError) {
            console.log("THREE.AMFLoader: fflate missing and file is compressed.");
            return null;
          }
        }
        for (file in zip) {
          if (file.toLowerCase().slice(-4) === ".amf") {
            break;
          }
        }
        console.log("THREE.AMFLoader: Trying to load file asset: " + file);
        view = new DataView(zip[file].buffer);
      }
      const fileText = new TextDecoder().decode(view);
      const xmlData2 = new DOMParser().parseFromString(fileText, "application/xml");
      if (xmlData2.documentElement.nodeName.toLowerCase() !== "amf") {
        console.log("THREE.AMFLoader: Error loading AMF - no AMF document found.");
        return null;
      }
      return xmlData2;
    }
    function loadDocumentScale(node) {
      let scale2 = 1;
      let unit = "millimeter";
      if (node.documentElement.attributes.unit !== void 0) {
        unit = node.documentElement.attributes.unit.value.toLowerCase();
      }
      const scaleUnits = {
        millimeter: 1,
        inch: 25.4,
        feet: 304.8,
        meter: 1e3,
        micron: 1e-3
      };
      if (scaleUnits[unit] !== void 0) {
        scale2 = scaleUnits[unit];
      }
      console.log("THREE.AMFLoader: Unit scale: " + scale2);
      return scale2;
    }
    function loadMaterials(node) {
      let matName = "AMF Material";
      const matId = node.attributes.id.textContent;
      let color = { r: 1, g: 1, b: 1, a: 1 };
      let loadedMaterial = null;
      for (let i2 = 0; i2 < node.childNodes.length; i2++) {
        const matChildEl = node.childNodes[i2];
        if (matChildEl.nodeName === "metadata" && matChildEl.attributes.type !== void 0) {
          if (matChildEl.attributes.type.value === "name") {
            matName = matChildEl.textContent;
          }
        } else if (matChildEl.nodeName === "color") {
          color = loadColor(matChildEl);
        }
      }
      loadedMaterial = new MeshPhongMaterial({
        flatShading: true,
        color: new Color(color.r, color.g, color.b),
        name: matName
      });
      if (color.a !== 1) {
        loadedMaterial.transparent = true;
        loadedMaterial.opacity = color.a;
      }
      return { id: matId, material: loadedMaterial };
    }
    function loadColor(node) {
      const color = { r: 1, g: 1, b: 1, a: 1 };
      for (let i2 = 0; i2 < node.childNodes.length; i2++) {
        const matColor = node.childNodes[i2];
        if (matColor.nodeName === "r") {
          color.r = matColor.textContent;
        } else if (matColor.nodeName === "g") {
          color.g = matColor.textContent;
        } else if (matColor.nodeName === "b") {
          color.b = matColor.textContent;
        } else if (matColor.nodeName === "a") {
          color.a = matColor.textContent;
        }
      }
      return color;
    }
    function loadMeshVolume(node) {
      const volume = { name: "", triangles: [], materialId: null };
      let currVolumeNode = node.firstElementChild;
      if (node.attributes.materialid !== void 0) {
        volume.materialId = node.attributes.materialid.nodeValue;
      }
      while (currVolumeNode) {
        if (currVolumeNode.nodeName === "metadata") {
          if (currVolumeNode.attributes.type !== void 0) {
            if (currVolumeNode.attributes.type.value === "name") {
              volume.name = currVolumeNode.textContent;
            }
          }
        } else if (currVolumeNode.nodeName === "triangle") {
          const v12 = currVolumeNode.getElementsByTagName("v1")[0].textContent;
          const v2 = currVolumeNode.getElementsByTagName("v2")[0].textContent;
          const v3 = currVolumeNode.getElementsByTagName("v3")[0].textContent;
          volume.triangles.push(v12, v2, v3);
        }
        currVolumeNode = currVolumeNode.nextElementSibling;
      }
      return volume;
    }
    function loadMeshVertices(node) {
      const vertArray = [];
      const normalArray = [];
      let currVerticesNode = node.firstElementChild;
      while (currVerticesNode) {
        if (currVerticesNode.nodeName === "vertex") {
          let vNode = currVerticesNode.firstElementChild;
          while (vNode) {
            if (vNode.nodeName === "coordinates") {
              const x2 = vNode.getElementsByTagName("x")[0].textContent;
              const y = vNode.getElementsByTagName("y")[0].textContent;
              const z = vNode.getElementsByTagName("z")[0].textContent;
              vertArray.push(x2, y, z);
            } else if (vNode.nodeName === "normal") {
              const nx = vNode.getElementsByTagName("nx")[0].textContent;
              const ny = vNode.getElementsByTagName("ny")[0].textContent;
              const nz = vNode.getElementsByTagName("nz")[0].textContent;
              normalArray.push(nx, ny, nz);
            }
            vNode = vNode.nextElementSibling;
          }
        }
        currVerticesNode = currVerticesNode.nextElementSibling;
      }
      return { "vertices": vertArray, "normals": normalArray };
    }
    function loadObject(node) {
      const objId = node.attributes.id.textContent;
      const loadedObject = { name: "amfobject", meshes: [] };
      let currColor = null;
      let currObjNode = node.firstElementChild;
      while (currObjNode) {
        if (currObjNode.nodeName === "metadata") {
          if (currObjNode.attributes.type !== void 0) {
            if (currObjNode.attributes.type.value === "name") {
              loadedObject.name = currObjNode.textContent;
            }
          }
        } else if (currObjNode.nodeName === "color") {
          currColor = loadColor(currObjNode);
        } else if (currObjNode.nodeName === "mesh") {
          let currMeshNode = currObjNode.firstElementChild;
          const mesh = { vertices: [], normals: [], volumes: [], color: currColor };
          while (currMeshNode) {
            if (currMeshNode.nodeName === "vertices") {
              const loadedVertices = loadMeshVertices(currMeshNode);
              mesh.normals = mesh.normals.concat(loadedVertices.normals);
              mesh.vertices = mesh.vertices.concat(loadedVertices.vertices);
            } else if (currMeshNode.nodeName === "volume") {
              mesh.volumes.push(loadMeshVolume(currMeshNode));
            }
            currMeshNode = currMeshNode.nextElementSibling;
          }
          loadedObject.meshes.push(mesh);
        }
        currObjNode = currObjNode.nextElementSibling;
      }
      return { "id": objId, "obj": loadedObject };
    }
    const xmlData = loadDocument(data2);
    let amfName = "";
    let amfAuthor = "";
    const amfScale = loadDocumentScale(xmlData);
    const amfMaterials = {};
    const amfObjects = {};
    const childNodes = xmlData.documentElement.childNodes;
    let i, j2;
    for (i = 0; i < childNodes.length; i++) {
      const child = childNodes[i];
      if (child.nodeName === "metadata") {
        if (child.attributes.type !== void 0) {
          if (child.attributes.type.value === "name") {
            amfName = child.textContent;
          } else if (child.attributes.type.value === "author") {
            amfAuthor = child.textContent;
          }
        }
      } else if (child.nodeName === "material") {
        const loadedMaterial = loadMaterials(child);
        amfMaterials[loadedMaterial.id] = loadedMaterial.material;
      } else if (child.nodeName === "object") {
        const loadedObject = loadObject(child);
        amfObjects[loadedObject.id] = loadedObject.obj;
      }
    }
    const sceneObject = new Group();
    const defaultMaterial = new MeshPhongMaterial({
      name: Loader.DEFAULT_MATERIAL_NAME,
      color: 11184895,
      flatShading: true
    });
    sceneObject.name = amfName;
    sceneObject.userData.author = amfAuthor;
    sceneObject.userData.loader = "AMF";
    for (const id in amfObjects) {
      const part = amfObjects[id];
      const meshes = part.meshes;
      const newObject = new Group();
      newObject.name = part.name || "";
      for (i = 0; i < meshes.length; i++) {
        let objDefaultMaterial = defaultMaterial;
        const mesh = meshes[i];
        const vertices = new Float32BufferAttribute(mesh.vertices, 3);
        let normals = null;
        if (mesh.normals.length) {
          normals = new Float32BufferAttribute(mesh.normals, 3);
        }
        if (mesh.color) {
          const color = mesh.color;
          objDefaultMaterial = defaultMaterial.clone();
          objDefaultMaterial.color = new Color(color.r, color.g, color.b);
          if (color.a !== 1) {
            objDefaultMaterial.transparent = true;
            objDefaultMaterial.opacity = color.a;
          }
        }
        const volumes = mesh.volumes;
        for (j2 = 0; j2 < volumes.length; j2++) {
          const volume = volumes[j2];
          const newGeometry = new BufferGeometry();
          let material = objDefaultMaterial;
          newGeometry.setIndex(volume.triangles);
          newGeometry.setAttribute("position", vertices.clone());
          if (normals) {
            newGeometry.setAttribute("normal", normals.clone());
          }
          if (amfMaterials[volume.materialId] !== void 0) {
            material = amfMaterials[volume.materialId];
          }
          newGeometry.scale(amfScale, amfScale, amfScale);
          newObject.add(new Mesh(newGeometry, material.clone()));
        }
      }
      sceneObject.add(newObject);
    }
    return sceneObject;
  }
};

// node_modules/three/examples/jsm/loaders/BVHLoader.js
var BVHLoader = class extends Loader {
  /**
   * Constructs a new BVH loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.animateBonePositions = true;
    this.animateBoneRotations = true;
  }
  /**
   * Starts loading from the given URL and passes the loaded BVH asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function({skeleton:Skeleton,clip:AnimationClip})} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given BVH data and returns the resulting data.
   *
   * @param {string} text - The raw BVH data as a string.
   * @return {{skeleton:Skeleton,clip:AnimationClip}} An object representing the parsed asset.
   */
  parse(text2) {
    function readBvh(lines2) {
      if (nextLine(lines2) !== "HIERARCHY") {
        console.error("THREE.BVHLoader: HIERARCHY expected.");
      }
      const list = [];
      const root = readNode(lines2, nextLine(lines2), list);
      if (nextLine(lines2) !== "MOTION") {
        console.error("THREE.BVHLoader: MOTION expected.");
      }
      let tokens = nextLine(lines2).split(/[\s]+/);
      const numFrames = parseInt(tokens[1]);
      if (isNaN(numFrames)) {
        console.error("THREE.BVHLoader: Failed to read number of frames.");
      }
      tokens = nextLine(lines2).split(/[\s]+/);
      const frameTime = parseFloat(tokens[2]);
      if (isNaN(frameTime)) {
        console.error("THREE.BVHLoader: Failed to read frame time.");
      }
      for (let i = 0; i < numFrames; i++) {
        tokens = nextLine(lines2).split(/[\s]+/);
        readFrameData(tokens, i * frameTime, root);
      }
      return list;
    }
    function readFrameData(data2, frameTime, bone) {
      if (bone.type === "ENDSITE") return;
      const keyframe = {
        time: frameTime,
        position: new Vector3(),
        rotation: new Quaternion()
      };
      bone.frames.push(keyframe);
      const quat = new Quaternion();
      const vx = new Vector3(1, 0, 0);
      const vy = new Vector3(0, 1, 0);
      const vz = new Vector3(0, 0, 1);
      for (let i = 0; i < bone.channels.length; i++) {
        switch (bone.channels[i]) {
          case "Xposition":
            keyframe.position.x = parseFloat(data2.shift().trim());
            break;
          case "Yposition":
            keyframe.position.y = parseFloat(data2.shift().trim());
            break;
          case "Zposition":
            keyframe.position.z = parseFloat(data2.shift().trim());
            break;
          case "Xrotation":
            quat.setFromAxisAngle(vx, parseFloat(data2.shift().trim()) * Math.PI / 180);
            keyframe.rotation.multiply(quat);
            break;
          case "Yrotation":
            quat.setFromAxisAngle(vy, parseFloat(data2.shift().trim()) * Math.PI / 180);
            keyframe.rotation.multiply(quat);
            break;
          case "Zrotation":
            quat.setFromAxisAngle(vz, parseFloat(data2.shift().trim()) * Math.PI / 180);
            keyframe.rotation.multiply(quat);
            break;
          default:
            console.warn("THREE.BVHLoader: Invalid channel type.");
        }
      }
      for (let i = 0; i < bone.children.length; i++) {
        readFrameData(data2, frameTime, bone.children[i]);
      }
    }
    function readNode(lines2, firstline, list) {
      const node = { name: "", type: "", frames: [] };
      list.push(node);
      let tokens = firstline.split(/[\s]+/);
      if (tokens[0].toUpperCase() === "END" && tokens[1].toUpperCase() === "SITE") {
        node.type = "ENDSITE";
        node.name = "ENDSITE";
      } else {
        node.name = tokens[1];
        node.type = tokens[0].toUpperCase();
      }
      if (nextLine(lines2) !== "{") {
        console.error("THREE.BVHLoader: Expected opening { after type & name");
      }
      tokens = nextLine(lines2).split(/[\s]+/);
      if (tokens[0] !== "OFFSET") {
        console.error("THREE.BVHLoader: Expected OFFSET but got: " + tokens[0]);
      }
      if (tokens.length !== 4) {
        console.error("THREE.BVHLoader: Invalid number of values for OFFSET.");
      }
      const offset = new Vector3(
        parseFloat(tokens[1]),
        parseFloat(tokens[2]),
        parseFloat(tokens[3])
      );
      if (isNaN(offset.x) || isNaN(offset.y) || isNaN(offset.z)) {
        console.error("THREE.BVHLoader: Invalid values of OFFSET.");
      }
      node.offset = offset;
      if (node.type !== "ENDSITE") {
        tokens = nextLine(lines2).split(/[\s]+/);
        if (tokens[0] !== "CHANNELS") {
          console.error("THREE.BVHLoader: Expected CHANNELS definition.");
        }
        const numChannels = parseInt(tokens[1]);
        node.channels = tokens.splice(2, numChannels);
        node.children = [];
      }
      while (true) {
        const line2 = nextLine(lines2);
        if (line2 === "}") {
          return node;
        } else {
          node.children.push(readNode(lines2, line2, list));
        }
      }
    }
    function toTHREEBone(source, list) {
      const bone = new Bone();
      list.push(bone);
      bone.position.add(source.offset);
      bone.name = source.name;
      if (source.type !== "ENDSITE") {
        for (let i = 0; i < source.children.length; i++) {
          bone.add(toTHREEBone(source.children[i], list));
        }
      }
      return bone;
    }
    function toTHREEAnimation(bones2) {
      const tracks = [];
      for (let i = 0; i < bones2.length; i++) {
        const bone = bones2[i];
        if (bone.type === "ENDSITE")
          continue;
        const times = [];
        const positions = [];
        const rotations = [];
        for (let j2 = 0; j2 < bone.frames.length; j2++) {
          const frame = bone.frames[j2];
          times.push(frame.time);
          positions.push(frame.position.x + bone.offset.x);
          positions.push(frame.position.y + bone.offset.y);
          positions.push(frame.position.z + bone.offset.z);
          rotations.push(frame.rotation.x);
          rotations.push(frame.rotation.y);
          rotations.push(frame.rotation.z);
          rotations.push(frame.rotation.w);
        }
        if (scope.animateBonePositions) {
          tracks.push(new VectorKeyframeTrack(bone.name + ".position", times, positions));
        }
        if (scope.animateBoneRotations) {
          tracks.push(new QuaternionKeyframeTrack(bone.name + ".quaternion", times, rotations));
        }
      }
      return new AnimationClip("animation", -1, tracks);
    }
    function nextLine(lines2) {
      let line2;
      while ((line2 = lines2.shift().trim()).length === 0) {
      }
      return line2;
    }
    const scope = this;
    const lines = text2.split(/[\r\n]+/g);
    const bones = readBvh(lines);
    const threeBones = [];
    toTHREEBone(bones[0], threeBones);
    const threeClip = toTHREEAnimation(bones);
    return {
      skeleton: new Skeleton(threeBones),
      clip: threeClip
    };
  }
};

// node_modules/three/examples/jsm/loaders/TGALoader.js
var TGALoader = class extends DataTextureLoader {
  /**
   * Constructs a new TGA loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Parses the given TGA texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @return {DataTextureLoader~TexData} An object representing the parsed texture data.
   */
  parse(buffer) {
    function tgaCheckHeader(header2) {
      switch (header2.image_type) {
        // check indexed type
        case TGA_TYPE_INDEXED:
        case TGA_TYPE_RLE_INDEXED:
          if (header2.colormap_length > 256 || header2.colormap_size !== 24 || header2.colormap_type !== 1) {
            throw new Error("THREE.TGALoader: Invalid type colormap data for indexed type.");
          }
          break;
        // check colormap type
        case TGA_TYPE_RGB:
        case TGA_TYPE_GREY:
        case TGA_TYPE_RLE_RGB:
        case TGA_TYPE_RLE_GREY:
          if (header2.colormap_type) {
            throw new Error("THREE.TGALoader: Invalid type colormap data for colormap type.");
          }
          break;
        // What the need of a file without data ?
        case TGA_TYPE_NO_DATA:
          throw new Error("THREE.TGALoader: No data.");
        // Invalid type ?
        default:
          throw new Error("THREE.TGALoader: Invalid type " + header2.image_type);
      }
      if (header2.width <= 0 || header2.height <= 0) {
        throw new Error("THREE.TGALoader: Invalid image size.");
      }
      if (header2.pixel_size !== 8 && header2.pixel_size !== 16 && header2.pixel_size !== 24 && header2.pixel_size !== 32) {
        throw new Error("THREE.TGALoader: Invalid pixel size " + header2.pixel_size);
      }
    }
    function tgaParse(use_rle2, use_pal2, header2, offset2, data2) {
      let pixel_data, palettes;
      const pixel_size = header2.pixel_size >> 3;
      const pixel_total = header2.width * header2.height * pixel_size;
      if (use_pal2) {
        palettes = data2.subarray(offset2, offset2 += header2.colormap_length * (header2.colormap_size >> 3));
      }
      if (use_rle2) {
        pixel_data = new Uint8Array(pixel_total);
        let c2, count, i;
        let shift = 0;
        const pixels = new Uint8Array(pixel_size);
        while (shift < pixel_total) {
          c2 = data2[offset2++];
          count = (c2 & 127) + 1;
          if (c2 & 128) {
            for (i = 0; i < pixel_size; ++i) {
              pixels[i] = data2[offset2++];
            }
            for (i = 0; i < count; ++i) {
              pixel_data.set(pixels, shift + i * pixel_size);
            }
            shift += pixel_size * count;
          } else {
            count *= pixel_size;
            for (i = 0; i < count; ++i) {
              pixel_data[shift + i] = data2[offset2++];
            }
            shift += count;
          }
        }
      } else {
        pixel_data = data2.subarray(
          offset2,
          offset2 += use_pal2 ? header2.width * header2.height : pixel_total
        );
      }
      return {
        pixel_data,
        palettes
      };
    }
    function tgaGetImageData8bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image, palettes) {
      const colormap = palettes;
      let color, i = 0, x2, y;
      const width2 = header.width;
      for (y = y_start; y !== y_end; y += y_step) {
        for (x2 = x_start; x2 !== x_end; x2 += x_step, i++) {
          color = image[i];
          imageData2[(x2 + width2 * y) * 4 + 3] = 255;
          imageData2[(x2 + width2 * y) * 4 + 2] = colormap[color * 3 + 0];
          imageData2[(x2 + width2 * y) * 4 + 1] = colormap[color * 3 + 1];
          imageData2[(x2 + width2 * y) * 4 + 0] = colormap[color * 3 + 2];
        }
      }
      return imageData2;
    }
    function tgaGetImageData16bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) {
      let color, i = 0, x2, y;
      const width2 = header.width;
      for (y = y_start; y !== y_end; y += y_step) {
        for (x2 = x_start; x2 !== x_end; x2 += x_step, i += 2) {
          color = image[i + 0] + (image[i + 1] << 8);
          imageData2[(x2 + width2 * y) * 4 + 0] = (color & 31744) >> 7;
          imageData2[(x2 + width2 * y) * 4 + 1] = (color & 992) >> 2;
          imageData2[(x2 + width2 * y) * 4 + 2] = (color & 31) << 3;
          imageData2[(x2 + width2 * y) * 4 + 3] = color & 32768 ? 0 : 255;
        }
      }
      return imageData2;
    }
    function tgaGetImageData24bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) {
      let i = 0, x2, y;
      const width2 = header.width;
      for (y = y_start; y !== y_end; y += y_step) {
        for (x2 = x_start; x2 !== x_end; x2 += x_step, i += 3) {
          imageData2[(x2 + width2 * y) * 4 + 3] = 255;
          imageData2[(x2 + width2 * y) * 4 + 2] = image[i + 0];
          imageData2[(x2 + width2 * y) * 4 + 1] = image[i + 1];
          imageData2[(x2 + width2 * y) * 4 + 0] = image[i + 2];
        }
      }
      return imageData2;
    }
    function tgaGetImageData32bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) {
      let i = 0, x2, y;
      const width2 = header.width;
      for (y = y_start; y !== y_end; y += y_step) {
        for (x2 = x_start; x2 !== x_end; x2 += x_step, i += 4) {
          imageData2[(x2 + width2 * y) * 4 + 2] = image[i + 0];
          imageData2[(x2 + width2 * y) * 4 + 1] = image[i + 1];
          imageData2[(x2 + width2 * y) * 4 + 0] = image[i + 2];
          imageData2[(x2 + width2 * y) * 4 + 3] = image[i + 3];
        }
      }
      return imageData2;
    }
    function tgaGetImageDataGrey8bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) {
      let color, i = 0, x2, y;
      const width2 = header.width;
      for (y = y_start; y !== y_end; y += y_step) {
        for (x2 = x_start; x2 !== x_end; x2 += x_step, i++) {
          color = image[i];
          imageData2[(x2 + width2 * y) * 4 + 0] = color;
          imageData2[(x2 + width2 * y) * 4 + 1] = color;
          imageData2[(x2 + width2 * y) * 4 + 2] = color;
          imageData2[(x2 + width2 * y) * 4 + 3] = 255;
        }
      }
      return imageData2;
    }
    function tgaGetImageDataGrey16bits(imageData2, y_start, y_step, y_end, x_start, x_step, x_end, image) {
      let i = 0, x2, y;
      const width2 = header.width;
      for (y = y_start; y !== y_end; y += y_step) {
        for (x2 = x_start; x2 !== x_end; x2 += x_step, i += 2) {
          imageData2[(x2 + width2 * y) * 4 + 0] = image[i + 0];
          imageData2[(x2 + width2 * y) * 4 + 1] = image[i + 0];
          imageData2[(x2 + width2 * y) * 4 + 2] = image[i + 0];
          imageData2[(x2 + width2 * y) * 4 + 3] = image[i + 1];
        }
      }
      return imageData2;
    }
    function getTgaRGBA(data2, width2, height2, image, palette) {
      let x_start, y_start, x_step, y_step, x_end, y_end;
      switch ((header.flags & TGA_ORIGIN_MASK) >> TGA_ORIGIN_SHIFT) {
        default:
        case TGA_ORIGIN_UL:
          x_start = 0;
          x_step = 1;
          x_end = width2;
          y_start = 0;
          y_step = 1;
          y_end = height2;
          break;
        case TGA_ORIGIN_BL:
          x_start = 0;
          x_step = 1;
          x_end = width2;
          y_start = height2 - 1;
          y_step = -1;
          y_end = -1;
          break;
        case TGA_ORIGIN_UR:
          x_start = width2 - 1;
          x_step = -1;
          x_end = -1;
          y_start = 0;
          y_step = 1;
          y_end = height2;
          break;
        case TGA_ORIGIN_BR:
          x_start = width2 - 1;
          x_step = -1;
          x_end = -1;
          y_start = height2 - 1;
          y_step = -1;
          y_end = -1;
          break;
      }
      if (use_grey) {
        switch (header.pixel_size) {
          case 8:
            tgaGetImageDataGrey8bits(data2, y_start, y_step, y_end, x_start, x_step, x_end, image);
            break;
          case 16:
            tgaGetImageDataGrey16bits(data2, y_start, y_step, y_end, x_start, x_step, x_end, image);
            break;
          default:
            throw new Error("THREE.TGALoader: Format not supported.");
            break;
        }
      } else {
        switch (header.pixel_size) {
          case 8:
            tgaGetImageData8bits(data2, y_start, y_step, y_end, x_start, x_step, x_end, image, palette);
            break;
          case 16:
            tgaGetImageData16bits(data2, y_start, y_step, y_end, x_start, x_step, x_end, image);
            break;
          case 24:
            tgaGetImageData24bits(data2, y_start, y_step, y_end, x_start, x_step, x_end, image);
            break;
          case 32:
            tgaGetImageData32bits(data2, y_start, y_step, y_end, x_start, x_step, x_end, image);
            break;
          default:
            throw new Error("THREE.TGALoader: Format not supported.");
            break;
        }
      }
      return data2;
    }
    const TGA_TYPE_NO_DATA = 0, TGA_TYPE_INDEXED = 1, TGA_TYPE_RGB = 2, TGA_TYPE_GREY = 3, TGA_TYPE_RLE_INDEXED = 9, TGA_TYPE_RLE_RGB = 10, TGA_TYPE_RLE_GREY = 11, TGA_ORIGIN_MASK = 48, TGA_ORIGIN_SHIFT = 4, TGA_ORIGIN_BL = 0, TGA_ORIGIN_BR = 1, TGA_ORIGIN_UL = 2, TGA_ORIGIN_UR = 3;
    if (buffer.length < 19) throw new Error("THREE.TGALoader: Not enough data to contain header.");
    let offset = 0;
    const content2 = new Uint8Array(buffer), header = {
      id_length: content2[offset++],
      colormap_type: content2[offset++],
      image_type: content2[offset++],
      colormap_index: content2[offset++] | content2[offset++] << 8,
      colormap_length: content2[offset++] | content2[offset++] << 8,
      colormap_size: content2[offset++],
      origin: [
        content2[offset++] | content2[offset++] << 8,
        content2[offset++] | content2[offset++] << 8
      ],
      width: content2[offset++] | content2[offset++] << 8,
      height: content2[offset++] | content2[offset++] << 8,
      pixel_size: content2[offset++],
      flags: content2[offset++]
    };
    tgaCheckHeader(header);
    if (header.id_length + offset > buffer.length) {
      throw new Error("THREE.TGALoader: No data.");
    }
    offset += header.id_length;
    let use_rle = false, use_pal = false, use_grey = false;
    switch (header.image_type) {
      case TGA_TYPE_RLE_INDEXED:
        use_rle = true;
        use_pal = true;
        break;
      case TGA_TYPE_INDEXED:
        use_pal = true;
        break;
      case TGA_TYPE_RLE_RGB:
        use_rle = true;
        break;
      case TGA_TYPE_RGB:
        break;
      case TGA_TYPE_RLE_GREY:
        use_rle = true;
        use_grey = true;
        break;
      case TGA_TYPE_GREY:
        use_grey = true;
        break;
    }
    const imageData = new Uint8Array(header.width * header.height * 4);
    const result = tgaParse(use_rle, use_pal, header, offset, content2);
    getTgaRGBA(imageData, header.width, header.height, result.pixel_data, result.palettes);
    return {
      data: imageData,
      width: header.width,
      height: header.height,
      flipY: true,
      generateMipmaps: true,
      minFilter: LinearMipmapLinearFilter
    };
  }
};

// node_modules/three/examples/jsm/loaders/ColladaLoader.js
var ColladaLoader = class extends Loader {
  /**
   * Starts loading from the given URL and passes the loaded Collada asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function({scene:Group,animations:Array<AnimationClip>,kinematics:Object})} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const path = scope.path === "" ? LoaderUtils.extractUrlBase(url) : scope.path;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2, path));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given Collada data and returns a result object holding the parsed scene,
   * an array of animation clips and kinematics.
   *
   * @param {string} text - The raw Collada data as a string.
   * @param {string} path - The asset path.
   * @return {{scene:Group,animations:Array<AnimationClip>,kinematics:Object}} An object representing the parsed asset.
   */
  parse(text2, path) {
    function getElementsByTagName(xml2, name2) {
      const array = [];
      const childNodes = xml2.childNodes;
      for (let i = 0, l2 = childNodes.length; i < l2; i++) {
        const child = childNodes[i];
        if (child.nodeName === name2) {
          array.push(child);
        }
      }
      return array;
    }
    function parseStrings(text3) {
      if (text3.length === 0) return [];
      const parts = text3.trim().split(/\s+/);
      const array = new Array(parts.length);
      for (let i = 0, l2 = parts.length; i < l2; i++) {
        array[i] = parts[i];
      }
      return array;
    }
    function parseFloats(text3) {
      if (text3.length === 0) return [];
      const parts = text3.trim().split(/\s+/);
      const array = new Array(parts.length);
      for (let i = 0, l2 = parts.length; i < l2; i++) {
        array[i] = parseFloat(parts[i]);
      }
      return array;
    }
    function parseInts(text3) {
      if (text3.length === 0) return [];
      const parts = text3.trim().split(/\s+/);
      const array = new Array(parts.length);
      for (let i = 0, l2 = parts.length; i < l2; i++) {
        array[i] = parseInt(parts[i]);
      }
      return array;
    }
    function parseId(text3) {
      return text3.substring(1);
    }
    function generateId() {
      return "three_default_" + count++;
    }
    function isEmpty2(object) {
      return Object.keys(object).length === 0;
    }
    function parseAsset(xml2) {
      return {
        unit: parseAssetUnit(getElementsByTagName(xml2, "unit")[0]),
        upAxis: parseAssetUpAxis(getElementsByTagName(xml2, "up_axis")[0])
      };
    }
    function parseAssetUnit(xml2) {
      if (xml2 !== void 0 && xml2.hasAttribute("meter") === true) {
        return parseFloat(xml2.getAttribute("meter"));
      } else {
        return 1;
      }
    }
    function parseAssetUpAxis(xml2) {
      return xml2 !== void 0 ? xml2.textContent : "Y_UP";
    }
    function parseLibrary(xml2, libraryName, nodeName, parser) {
      const library2 = getElementsByTagName(xml2, libraryName)[0];
      if (library2 !== void 0) {
        const elements = getElementsByTagName(library2, nodeName);
        for (let i = 0; i < elements.length; i++) {
          parser(elements[i]);
        }
      }
    }
    function buildLibrary(data2, builder) {
      for (const name2 in data2) {
        const object = data2[name2];
        object.build = builder(data2[name2]);
      }
    }
    function getBuild(data2, builder) {
      if (data2.build !== void 0) return data2.build;
      data2.build = builder(data2);
      return data2.build;
    }
    function parseAnimation(xml2) {
      const data2 = {
        sources: {},
        samplers: {},
        channels: {}
      };
      let hasChildren = false;
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        let id;
        switch (child.nodeName) {
          case "source":
            id = child.getAttribute("id");
            data2.sources[id] = parseSource(child);
            break;
          case "sampler":
            id = child.getAttribute("id");
            data2.samplers[id] = parseAnimationSampler(child);
            break;
          case "channel":
            id = child.getAttribute("target");
            data2.channels[id] = parseAnimationChannel(child);
            break;
          case "animation":
            parseAnimation(child);
            hasChildren = true;
            break;
          default:
            console.log(child);
        }
      }
      if (hasChildren === false) {
        library.animations[xml2.getAttribute("id") || MathUtils.generateUUID()] = data2;
      }
    }
    function parseAnimationSampler(xml2) {
      const data2 = {
        inputs: {}
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "input":
            const id = parseId(child.getAttribute("source"));
            const semantic = child.getAttribute("semantic");
            data2.inputs[semantic] = id;
            break;
        }
      }
      return data2;
    }
    function parseAnimationChannel(xml2) {
      const data2 = {};
      const target = xml2.getAttribute("target");
      let parts = target.split("/");
      const id = parts.shift();
      let sid = parts.shift();
      const arraySyntax = sid.indexOf("(") !== -1;
      const memberSyntax = sid.indexOf(".") !== -1;
      if (memberSyntax) {
        parts = sid.split(".");
        sid = parts.shift();
        data2.member = parts.shift();
      } else if (arraySyntax) {
        const indices = sid.split("(");
        sid = indices.shift();
        for (let i = 0; i < indices.length; i++) {
          indices[i] = parseInt(indices[i].replace(/\)/, ""));
        }
        data2.indices = indices;
      }
      data2.id = id;
      data2.sid = sid;
      data2.arraySyntax = arraySyntax;
      data2.memberSyntax = memberSyntax;
      data2.sampler = parseId(xml2.getAttribute("source"));
      return data2;
    }
    function buildAnimation(data2) {
      const tracks = [];
      const channels = data2.channels;
      const samplers = data2.samplers;
      const sources = data2.sources;
      for (const target in channels) {
        if (channels.hasOwnProperty(target)) {
          const channel = channels[target];
          const sampler = samplers[channel.sampler];
          const inputId = sampler.inputs.INPUT;
          const outputId = sampler.inputs.OUTPUT;
          const inputSource = sources[inputId];
          const outputSource = sources[outputId];
          const animation = buildAnimationChannel(channel, inputSource, outputSource);
          createKeyframeTracks(animation, tracks);
        }
      }
      return tracks;
    }
    function getAnimation(id) {
      return getBuild(library.animations[id], buildAnimation);
    }
    function buildAnimationChannel(channel, inputSource, outputSource) {
      const node = library.nodes[channel.id];
      const object3D = getNode(node.id);
      const transform2 = node.transforms[channel.sid];
      const defaultMatrix = node.matrix.clone().transpose();
      let time2, stride;
      let i, il, j2, jl;
      const data2 = {};
      switch (transform2) {
        case "matrix":
          for (i = 0, il = inputSource.array.length; i < il; i++) {
            time2 = inputSource.array[i];
            stride = i * outputSource.stride;
            if (data2[time2] === void 0) data2[time2] = {};
            if (channel.arraySyntax === true) {
              const value2 = outputSource.array[stride];
              const index2 = channel.indices[0] + 4 * channel.indices[1];
              data2[time2][index2] = value2;
            } else {
              for (j2 = 0, jl = outputSource.stride; j2 < jl; j2++) {
                data2[time2][j2] = outputSource.array[stride + j2];
              }
            }
          }
          break;
        case "translate":
          console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform2);
          break;
        case "rotate":
          console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform2);
          break;
        case "scale":
          console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform2);
          break;
      }
      const keyframes = prepareAnimationData(data2, defaultMatrix);
      const animation = {
        name: object3D.uuid,
        keyframes
      };
      return animation;
    }
    function prepareAnimationData(data2, defaultMatrix) {
      const keyframes = [];
      for (const time2 in data2) {
        keyframes.push({ time: parseFloat(time2), value: data2[time2] });
      }
      keyframes.sort(ascending);
      for (let i = 0; i < 16; i++) {
        transformAnimationData(keyframes, i, defaultMatrix.elements[i]);
      }
      return keyframes;
      function ascending(a2, b3) {
        return a2.time - b3.time;
      }
    }
    const position2 = new Vector3();
    const scale2 = new Vector3();
    const quaternion = new Quaternion();
    function createKeyframeTracks(animation, tracks) {
      const keyframes = animation.keyframes;
      const name2 = animation.name;
      const times = [];
      const positionData = [];
      const quaternionData = [];
      const scaleData = [];
      for (let i = 0, l2 = keyframes.length; i < l2; i++) {
        const keyframe = keyframes[i];
        const time2 = keyframe.time;
        const value2 = keyframe.value;
        matrix2.fromArray(value2).transpose();
        matrix2.decompose(position2, quaternion, scale2);
        times.push(time2);
        positionData.push(position2.x, position2.y, position2.z);
        quaternionData.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
        scaleData.push(scale2.x, scale2.y, scale2.z);
      }
      if (positionData.length > 0) tracks.push(new VectorKeyframeTrack(name2 + ".position", times, positionData));
      if (quaternionData.length > 0) tracks.push(new QuaternionKeyframeTrack(name2 + ".quaternion", times, quaternionData));
      if (scaleData.length > 0) tracks.push(new VectorKeyframeTrack(name2 + ".scale", times, scaleData));
      return tracks;
    }
    function transformAnimationData(keyframes, property2, defaultValue) {
      let keyframe;
      let empty = true;
      let i, l2;
      for (i = 0, l2 = keyframes.length; i < l2; i++) {
        keyframe = keyframes[i];
        if (keyframe.value[property2] === void 0) {
          keyframe.value[property2] = null;
        } else {
          empty = false;
        }
      }
      if (empty === true) {
        for (i = 0, l2 = keyframes.length; i < l2; i++) {
          keyframe = keyframes[i];
          keyframe.value[property2] = defaultValue;
        }
      } else {
        createMissingKeyframes(keyframes, property2);
      }
    }
    function createMissingKeyframes(keyframes, property2) {
      let prev, next;
      for (let i = 0, l2 = keyframes.length; i < l2; i++) {
        const keyframe = keyframes[i];
        if (keyframe.value[property2] === null) {
          prev = getPrev(keyframes, i, property2);
          next = getNext(keyframes, i, property2);
          if (prev === null) {
            keyframe.value[property2] = next.value[property2];
            continue;
          }
          if (next === null) {
            keyframe.value[property2] = prev.value[property2];
            continue;
          }
          interpolate(keyframe, prev, next, property2);
        }
      }
    }
    function getPrev(keyframes, i, property2) {
      while (i >= 0) {
        const keyframe = keyframes[i];
        if (keyframe.value[property2] !== null) return keyframe;
        i--;
      }
      return null;
    }
    function getNext(keyframes, i, property2) {
      while (i < keyframes.length) {
        const keyframe = keyframes[i];
        if (keyframe.value[property2] !== null) return keyframe;
        i++;
      }
      return null;
    }
    function interpolate(key2, prev, next, property2) {
      if (next.time - prev.time === 0) {
        key2.value[property2] = prev.value[property2];
        return;
      }
      key2.value[property2] = (key2.time - prev.time) * (next.value[property2] - prev.value[property2]) / (next.time - prev.time) + prev.value[property2];
    }
    function parseAnimationClip(xml2) {
      const data2 = {
        name: xml2.getAttribute("id") || "default",
        start: parseFloat(xml2.getAttribute("start") || 0),
        end: parseFloat(xml2.getAttribute("end") || 0),
        animations: []
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "instance_animation":
            data2.animations.push(parseId(child.getAttribute("url")));
            break;
        }
      }
      library.clips[xml2.getAttribute("id")] = data2;
    }
    function buildAnimationClip(data2) {
      const tracks = [];
      const name2 = data2.name;
      const duration = data2.end - data2.start || -1;
      const animations2 = data2.animations;
      for (let i = 0, il = animations2.length; i < il; i++) {
        const animationTracks = getAnimation(animations2[i]);
        for (let j2 = 0, jl = animationTracks.length; j2 < jl; j2++) {
          tracks.push(animationTracks[j2]);
        }
      }
      return new AnimationClip(name2, duration, tracks);
    }
    function getAnimationClip(id) {
      return getBuild(library.clips[id], buildAnimationClip);
    }
    function parseController(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "skin":
            data2.id = parseId(child.getAttribute("source"));
            data2.skin = parseSkin(child);
            break;
          case "morph":
            data2.id = parseId(child.getAttribute("source"));
            console.warn("THREE.ColladaLoader: Morph target animation not supported yet.");
            break;
        }
      }
      library.controllers[xml2.getAttribute("id")] = data2;
    }
    function parseSkin(xml2) {
      const data2 = {
        sources: {}
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "bind_shape_matrix":
            data2.bindShapeMatrix = parseFloats(child.textContent);
            break;
          case "source":
            const id = child.getAttribute("id");
            data2.sources[id] = parseSource(child);
            break;
          case "joints":
            data2.joints = parseJoints(child);
            break;
          case "vertex_weights":
            data2.vertexWeights = parseVertexWeights(child);
            break;
        }
      }
      return data2;
    }
    function parseJoints(xml2) {
      const data2 = {
        inputs: {}
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "input":
            const semantic = child.getAttribute("semantic");
            const id = parseId(child.getAttribute("source"));
            data2.inputs[semantic] = id;
            break;
        }
      }
      return data2;
    }
    function parseVertexWeights(xml2) {
      const data2 = {
        inputs: {}
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "input":
            const semantic = child.getAttribute("semantic");
            const id = parseId(child.getAttribute("source"));
            const offset = parseInt(child.getAttribute("offset"));
            data2.inputs[semantic] = { id, offset };
            break;
          case "vcount":
            data2.vcount = parseInts(child.textContent);
            break;
          case "v":
            data2.v = parseInts(child.textContent);
            break;
        }
      }
      return data2;
    }
    function buildController(data2) {
      const build = {
        id: data2.id
      };
      const geometry = library.geometries[build.id];
      if (data2.skin !== void 0) {
        build.skin = buildSkin(data2.skin);
        geometry.sources.skinIndices = build.skin.indices;
        geometry.sources.skinWeights = build.skin.weights;
      }
      return build;
    }
    function buildSkin(data2) {
      const BONE_LIMIT = 4;
      const build = {
        joints: [],
        // this must be an array to preserve the joint order
        indices: {
          array: [],
          stride: BONE_LIMIT
        },
        weights: {
          array: [],
          stride: BONE_LIMIT
        }
      };
      const sources = data2.sources;
      const vertexWeights = data2.vertexWeights;
      const vcount = vertexWeights.vcount;
      const v = vertexWeights.v;
      const jointOffset = vertexWeights.inputs.JOINT.offset;
      const weightOffset = vertexWeights.inputs.WEIGHT.offset;
      const jointSource = data2.sources[data2.joints.inputs.JOINT];
      const inverseSource = data2.sources[data2.joints.inputs.INV_BIND_MATRIX];
      const weights = sources[vertexWeights.inputs.WEIGHT.id].array;
      let stride = 0;
      let i, j2, l2;
      for (i = 0, l2 = vcount.length; i < l2; i++) {
        const jointCount = vcount[i];
        const vertexSkinData = [];
        for (j2 = 0; j2 < jointCount; j2++) {
          const skinIndex = v[stride + jointOffset];
          const weightId = v[stride + weightOffset];
          const skinWeight = weights[weightId];
          vertexSkinData.push({ index: skinIndex, weight: skinWeight });
          stride += 2;
        }
        vertexSkinData.sort(descending);
        for (j2 = 0; j2 < BONE_LIMIT; j2++) {
          const d = vertexSkinData[j2];
          if (d !== void 0) {
            build.indices.array.push(d.index);
            build.weights.array.push(d.weight);
          } else {
            build.indices.array.push(0);
            build.weights.array.push(0);
          }
        }
      }
      if (data2.bindShapeMatrix) {
        build.bindMatrix = new Matrix4().fromArray(data2.bindShapeMatrix).transpose();
      } else {
        build.bindMatrix = new Matrix4().identity();
      }
      for (i = 0, l2 = jointSource.array.length; i < l2; i++) {
        const name2 = jointSource.array[i];
        const boneInverse = new Matrix4().fromArray(inverseSource.array, i * inverseSource.stride).transpose();
        build.joints.push({ name: name2, boneInverse });
      }
      return build;
      function descending(a2, b3) {
        return b3.weight - a2.weight;
      }
    }
    function getController(id) {
      return getBuild(library.controllers[id], buildController);
    }
    function parseImage(xml2) {
      const data2 = {
        init_from: getElementsByTagName(xml2, "init_from")[0].textContent
      };
      library.images[xml2.getAttribute("id")] = data2;
    }
    function buildImage(data2) {
      if (data2.build !== void 0) return data2.build;
      return data2.init_from;
    }
    function getImage(id) {
      const data2 = library.images[id];
      if (data2 !== void 0) {
        return getBuild(data2, buildImage);
      }
      console.warn("THREE.ColladaLoader: Couldn't find image with ID:", id);
      return null;
    }
    function parseEffect(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "profile_COMMON":
            data2.profile = parseEffectProfileCOMMON(child);
            break;
        }
      }
      library.effects[xml2.getAttribute("id")] = data2;
    }
    function parseEffectProfileCOMMON(xml2) {
      const data2 = {
        surfaces: {},
        samplers: {}
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "newparam":
            parseEffectNewparam(child, data2);
            break;
          case "technique":
            data2.technique = parseEffectTechnique(child);
            break;
          case "extra":
            data2.extra = parseEffectExtra(child);
            break;
        }
      }
      return data2;
    }
    function parseEffectNewparam(xml2, data2) {
      const sid = xml2.getAttribute("sid");
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "surface":
            data2.surfaces[sid] = parseEffectSurface(child);
            break;
          case "sampler2D":
            data2.samplers[sid] = parseEffectSampler(child);
            break;
        }
      }
    }
    function parseEffectSurface(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "init_from":
            data2.init_from = child.textContent;
            break;
        }
      }
      return data2;
    }
    function parseEffectSampler(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "source":
            data2.source = child.textContent;
            break;
        }
      }
      return data2;
    }
    function parseEffectTechnique(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "constant":
          case "lambert":
          case "blinn":
          case "phong":
            data2.type = child.nodeName;
            data2.parameters = parseEffectParameters(child);
            break;
          case "extra":
            data2.extra = parseEffectExtra(child);
            break;
        }
      }
      return data2;
    }
    function parseEffectParameters(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "emission":
          case "diffuse":
          case "specular":
          case "bump":
          case "ambient":
          case "shininess":
          case "transparency":
            data2[child.nodeName] = parseEffectParameter(child);
            break;
          case "transparent":
            data2[child.nodeName] = {
              opaque: child.hasAttribute("opaque") ? child.getAttribute("opaque") : "A_ONE",
              data: parseEffectParameter(child)
            };
            break;
        }
      }
      return data2;
    }
    function parseEffectParameter(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "color":
            data2[child.nodeName] = parseFloats(child.textContent);
            break;
          case "float":
            data2[child.nodeName] = parseFloat(child.textContent);
            break;
          case "texture":
            data2[child.nodeName] = { id: child.getAttribute("texture"), extra: parseEffectParameterTexture(child) };
            break;
        }
      }
      return data2;
    }
    function parseEffectParameterTexture(xml2) {
      const data2 = {
        technique: {}
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "extra":
            parseEffectParameterTextureExtra(child, data2);
            break;
        }
      }
      return data2;
    }
    function parseEffectParameterTextureExtra(xml2, data2) {
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "technique":
            parseEffectParameterTextureExtraTechnique(child, data2);
            break;
        }
      }
    }
    function parseEffectParameterTextureExtraTechnique(xml2, data2) {
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "repeatU":
          case "repeatV":
          case "offsetU":
          case "offsetV":
            data2.technique[child.nodeName] = parseFloat(child.textContent);
            break;
          case "wrapU":
          case "wrapV":
            if (child.textContent.toUpperCase() === "TRUE") {
              data2.technique[child.nodeName] = 1;
            } else if (child.textContent.toUpperCase() === "FALSE") {
              data2.technique[child.nodeName] = 0;
            } else {
              data2.technique[child.nodeName] = parseInt(child.textContent);
            }
            break;
          case "bump":
            data2[child.nodeName] = parseEffectExtraTechniqueBump(child);
            break;
        }
      }
    }
    function parseEffectExtra(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "technique":
            data2.technique = parseEffectExtraTechnique(child);
            break;
        }
      }
      return data2;
    }
    function parseEffectExtraTechnique(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "double_sided":
            data2[child.nodeName] = parseInt(child.textContent);
            break;
          case "bump":
            data2[child.nodeName] = parseEffectExtraTechniqueBump(child);
            break;
        }
      }
      return data2;
    }
    function parseEffectExtraTechniqueBump(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "texture":
            data2[child.nodeName] = { id: child.getAttribute("texture"), texcoord: child.getAttribute("texcoord"), extra: parseEffectParameterTexture(child) };
            break;
        }
      }
      return data2;
    }
    function buildEffect(data2) {
      return data2;
    }
    function getEffect(id) {
      return getBuild(library.effects[id], buildEffect);
    }
    function parseMaterial(xml2) {
      const data2 = {
        name: xml2.getAttribute("name")
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "instance_effect":
            data2.url = parseId(child.getAttribute("url"));
            break;
        }
      }
      library.materials[xml2.getAttribute("id")] = data2;
    }
    function getTextureLoader(image) {
      let loader;
      let extension = image.slice((image.lastIndexOf(".") - 1 >>> 0) + 2);
      extension = extension.toLowerCase();
      switch (extension) {
        case "tga":
          loader = tgaLoader;
          break;
        default:
          loader = textureLoader;
      }
      return loader;
    }
    function buildMaterial2(data2) {
      const effect2 = getEffect(data2.url);
      const technique = effect2.profile.technique;
      let material;
      switch (technique.type) {
        case "phong":
        case "blinn":
          material = new MeshPhongMaterial();
          break;
        case "lambert":
          material = new MeshLambertMaterial();
          break;
        default:
          material = new MeshBasicMaterial();
          break;
      }
      material.name = data2.name || "";
      function getTexture(textureObject, colorSpace = null) {
        const sampler = effect2.profile.samplers[textureObject.id];
        let image = null;
        if (sampler !== void 0) {
          const surface = effect2.profile.surfaces[sampler.source];
          image = getImage(surface.init_from);
        } else {
          console.warn("THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).");
          image = getImage(textureObject.id);
        }
        if (image !== null) {
          const loader = getTextureLoader(image);
          if (loader !== void 0) {
            const texture = loader.load(image);
            const extra = textureObject.extra;
            if (extra !== void 0 && extra.technique !== void 0 && isEmpty2(extra.technique) === false) {
              const technique2 = extra.technique;
              texture.wrapS = technique2.wrapU ? RepeatWrapping : ClampToEdgeWrapping;
              texture.wrapT = technique2.wrapV ? RepeatWrapping : ClampToEdgeWrapping;
              texture.offset.set(technique2.offsetU || 0, technique2.offsetV || 0);
              texture.repeat.set(technique2.repeatU || 1, technique2.repeatV || 1);
            } else {
              texture.wrapS = RepeatWrapping;
              texture.wrapT = RepeatWrapping;
            }
            if (colorSpace !== null) {
              texture.colorSpace = colorSpace;
            }
            return texture;
          } else {
            console.warn("THREE.ColladaLoader: Loader for texture %s not found.", image);
            return null;
          }
        } else {
          console.warn("THREE.ColladaLoader: Couldn't create texture with ID:", textureObject.id);
          return null;
        }
      }
      const parameters = technique.parameters;
      for (const key2 in parameters) {
        const parameter = parameters[key2];
        switch (key2) {
          case "diffuse":
            if (parameter.color) material.color.fromArray(parameter.color);
            if (parameter.texture) material.map = getTexture(parameter.texture, SRGBColorSpace);
            break;
          case "specular":
            if (parameter.color && material.specular) material.specular.fromArray(parameter.color);
            if (parameter.texture) material.specularMap = getTexture(parameter.texture);
            break;
          case "bump":
            if (parameter.texture) material.normalMap = getTexture(parameter.texture);
            break;
          case "ambient":
            if (parameter.texture) material.lightMap = getTexture(parameter.texture, SRGBColorSpace);
            break;
          case "shininess":
            if (parameter.float && material.shininess) material.shininess = parameter.float;
            break;
          case "emission":
            if (parameter.color && material.emissive) material.emissive.fromArray(parameter.color);
            if (parameter.texture) material.emissiveMap = getTexture(parameter.texture, SRGBColorSpace);
            break;
        }
      }
      ColorManagement.colorSpaceToWorking(material.color, SRGBColorSpace);
      if (material.specular) ColorManagement.colorSpaceToWorking(material.specular, SRGBColorSpace);
      if (material.emissive) ColorManagement.colorSpaceToWorking(material.emissive, SRGBColorSpace);
      let transparent = parameters["transparent"];
      let transparency = parameters["transparency"];
      if (transparency === void 0 && transparent) {
        transparency = {
          float: 1
        };
      }
      if (transparent === void 0 && transparency) {
        transparent = {
          opaque: "A_ONE",
          data: {
            color: [1, 1, 1, 1]
          }
        };
      }
      if (transparent && transparency) {
        if (transparent.data.texture) {
          material.transparent = true;
        } else {
          const color = transparent.data.color;
          switch (transparent.opaque) {
            case "A_ONE":
              material.opacity = color[3] * transparency.float;
              break;
            case "RGB_ZERO":
              material.opacity = 1 - color[0] * transparency.float;
              break;
            case "A_ZERO":
              material.opacity = 1 - color[3] * transparency.float;
              break;
            case "RGB_ONE":
              material.opacity = color[0] * transparency.float;
              break;
            default:
              console.warn('THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque);
          }
          if (material.opacity < 1) material.transparent = true;
        }
      }
      if (technique.extra !== void 0 && technique.extra.technique !== void 0) {
        const techniques = technique.extra.technique;
        for (const k2 in techniques) {
          const v = techniques[k2];
          switch (k2) {
            case "double_sided":
              material.side = v === 1 ? DoubleSide : FrontSide;
              break;
            case "bump":
              material.normalMap = getTexture(v.texture);
              material.normalScale = new Vector2(1, 1);
              break;
          }
        }
      }
      return material;
    }
    function getMaterial(id) {
      return getBuild(library.materials[id], buildMaterial2);
    }
    function parseCamera(xml2) {
      const data2 = {
        name: xml2.getAttribute("name")
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "optics":
            data2.optics = parseCameraOptics(child);
            break;
        }
      }
      library.cameras[xml2.getAttribute("id")] = data2;
    }
    function parseCameraOptics(xml2) {
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        switch (child.nodeName) {
          case "technique_common":
            return parseCameraTechnique(child);
        }
      }
      return {};
    }
    function parseCameraTechnique(xml2) {
      const data2 = {};
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        switch (child.nodeName) {
          case "perspective":
          case "orthographic":
            data2.technique = child.nodeName;
            data2.parameters = parseCameraParameters(child);
            break;
        }
      }
      return data2;
    }
    function parseCameraParameters(xml2) {
      const data2 = {};
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        switch (child.nodeName) {
          case "xfov":
          case "yfov":
          case "xmag":
          case "ymag":
          case "znear":
          case "zfar":
          case "aspect_ratio":
            data2[child.nodeName] = parseFloat(child.textContent);
            break;
        }
      }
      return data2;
    }
    function buildCamera2(data2) {
      let camera;
      switch (data2.optics.technique) {
        case "perspective":
          camera = new PerspectiveCamera(
            data2.optics.parameters.yfov,
            data2.optics.parameters.aspect_ratio,
            data2.optics.parameters.znear,
            data2.optics.parameters.zfar
          );
          break;
        case "orthographic":
          let ymag = data2.optics.parameters.ymag;
          let xmag = data2.optics.parameters.xmag;
          const aspectRatio = data2.optics.parameters.aspect_ratio;
          xmag = xmag === void 0 ? ymag * aspectRatio : xmag;
          ymag = ymag === void 0 ? xmag / aspectRatio : ymag;
          xmag *= 0.5;
          ymag *= 0.5;
          camera = new OrthographicCamera(
            -xmag,
            xmag,
            ymag,
            -ymag,
            // left, right, top, bottom
            data2.optics.parameters.znear,
            data2.optics.parameters.zfar
          );
          break;
        default:
          camera = new PerspectiveCamera();
          break;
      }
      camera.name = data2.name || "";
      return camera;
    }
    function getCamera(id) {
      const data2 = library.cameras[id];
      if (data2 !== void 0) {
        return getBuild(data2, buildCamera2);
      }
      console.warn("THREE.ColladaLoader: Couldn't find camera with ID:", id);
      return null;
    }
    function parseLight(xml2) {
      let data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "technique_common":
            data2 = parseLightTechnique(child);
            break;
        }
      }
      library.lights[xml2.getAttribute("id")] = data2;
    }
    function parseLightTechnique(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "directional":
          case "point":
          case "spot":
          case "ambient":
            data2.technique = child.nodeName;
            data2.parameters = parseLightParameters(child);
        }
      }
      return data2;
    }
    function parseLightParameters(xml2) {
      const data2 = {};
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "color":
            const array = parseFloats(child.textContent);
            data2.color = new Color().fromArray(array);
            ColorManagement.colorSpaceToWorking(data2.color, SRGBColorSpace);
            break;
          case "falloff_angle":
            data2.falloffAngle = parseFloat(child.textContent);
            break;
          case "quadratic_attenuation":
            const f = parseFloat(child.textContent);
            data2.distance = f ? Math.sqrt(1 / f) : 0;
            break;
        }
      }
      return data2;
    }
    function buildLight(data2) {
      let light;
      switch (data2.technique) {
        case "directional":
          light = new DirectionalLight();
          break;
        case "point":
          light = new PointLight();
          break;
        case "spot":
          light = new SpotLight();
          break;
        case "ambient":
          light = new AmbientLight();
          break;
      }
      if (data2.parameters.color) light.color.copy(data2.parameters.color);
      if (data2.parameters.distance) light.distance = data2.parameters.distance;
      return light;
    }
    function getLight(id) {
      const data2 = library.lights[id];
      if (data2 !== void 0) {
        return getBuild(data2, buildLight);
      }
      console.warn("THREE.ColladaLoader: Couldn't find light with ID:", id);
      return null;
    }
    function parseGeometry(xml2) {
      const data2 = {
        name: xml2.getAttribute("name"),
        sources: {},
        vertices: {},
        primitives: []
      };
      const mesh = getElementsByTagName(xml2, "mesh")[0];
      if (mesh === void 0) return;
      for (let i = 0; i < mesh.childNodes.length; i++) {
        const child = mesh.childNodes[i];
        if (child.nodeType !== 1) continue;
        const id = child.getAttribute("id");
        switch (child.nodeName) {
          case "source":
            data2.sources[id] = parseSource(child);
            break;
          case "vertices":
            data2.vertices = parseGeometryVertices(child);
            break;
          case "polygons":
            console.warn("THREE.ColladaLoader: Unsupported primitive type: ", child.nodeName);
            break;
          case "lines":
          case "linestrips":
          case "polylist":
          case "triangles":
            data2.primitives.push(parseGeometryPrimitive(child));
            break;
          default:
            console.log(child);
        }
      }
      library.geometries[xml2.getAttribute("id")] = data2;
    }
    function parseSource(xml2) {
      const data2 = {
        array: [],
        stride: 3
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "float_array":
            data2.array = parseFloats(child.textContent);
            break;
          case "Name_array":
            data2.array = parseStrings(child.textContent);
            break;
          case "technique_common":
            const accessor = getElementsByTagName(child, "accessor")[0];
            if (accessor !== void 0) {
              data2.stride = parseInt(accessor.getAttribute("stride"));
            }
            break;
        }
      }
      return data2;
    }
    function parseGeometryVertices(xml2) {
      const data2 = {};
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        data2[child.getAttribute("semantic")] = parseId(child.getAttribute("source"));
      }
      return data2;
    }
    function parseGeometryPrimitive(xml2) {
      const primitive = {
        type: xml2.nodeName,
        material: xml2.getAttribute("material"),
        count: parseInt(xml2.getAttribute("count")),
        inputs: {},
        stride: 0,
        hasUV: false
      };
      for (let i = 0, l2 = xml2.childNodes.length; i < l2; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "input":
            const id = parseId(child.getAttribute("source"));
            const semantic = child.getAttribute("semantic");
            const offset = parseInt(child.getAttribute("offset"));
            const set = parseInt(child.getAttribute("set"));
            const inputname = set > 0 ? semantic + set : semantic;
            primitive.inputs[inputname] = { id, offset };
            primitive.stride = Math.max(primitive.stride, offset + 1);
            if (semantic === "TEXCOORD") primitive.hasUV = true;
            break;
          case "vcount":
            primitive.vcount = parseInts(child.textContent);
            break;
          case "p":
            primitive.p = parseInts(child.textContent);
            break;
        }
      }
      return primitive;
    }
    function groupPrimitives(primitives) {
      const build = {};
      for (let i = 0; i < primitives.length; i++) {
        const primitive = primitives[i];
        if (build[primitive.type] === void 0) build[primitive.type] = [];
        build[primitive.type].push(primitive);
      }
      return build;
    }
    function checkUVCoordinates(primitives) {
      let count2 = 0;
      for (let i = 0, l2 = primitives.length; i < l2; i++) {
        const primitive = primitives[i];
        if (primitive.hasUV === true) {
          count2++;
        }
      }
      if (count2 > 0 && count2 < primitives.length) {
        primitives.uvsNeedsFix = true;
      }
    }
    function buildGeometry(data2) {
      const build = {};
      const sources = data2.sources;
      const vertices = data2.vertices;
      const primitives = data2.primitives;
      if (primitives.length === 0) return {};
      const groupedPrimitives = groupPrimitives(primitives);
      for (const type in groupedPrimitives) {
        const primitiveType = groupedPrimitives[type];
        checkUVCoordinates(primitiveType);
        build[type] = buildGeometryType(primitiveType, sources, vertices);
      }
      return build;
    }
    function buildGeometryType(primitives, sources, vertices) {
      const build = {};
      const position3 = { array: [], stride: 0 };
      const normal = { array: [], stride: 0 };
      const uv = { array: [], stride: 0 };
      const uv1 = { array: [], stride: 0 };
      const color = { array: [], stride: 0 };
      const skinIndex = { array: [], stride: 4 };
      const skinWeight = { array: [], stride: 4 };
      const geometry = new BufferGeometry();
      const materialKeys = [];
      let start = 0;
      for (let p = 0; p < primitives.length; p++) {
        const primitive = primitives[p];
        const inputs = primitive.inputs;
        let count2 = 0;
        switch (primitive.type) {
          case "lines":
          case "linestrips":
            count2 = primitive.count * 2;
            break;
          case "triangles":
            count2 = primitive.count * 3;
            break;
          case "polylist":
            for (let g3 = 0; g3 < primitive.count; g3++) {
              const vc = primitive.vcount[g3];
              switch (vc) {
                case 3:
                  count2 += 3;
                  break;
                case 4:
                  count2 += 6;
                  break;
                default:
                  count2 += (vc - 2) * 3;
                  break;
              }
            }
            break;
          default:
            console.warn("THREE.ColladaLoader: Unknown primitive type:", primitive.type);
        }
        geometry.addGroup(start, count2, p);
        start += count2;
        if (primitive.material) {
          materialKeys.push(primitive.material);
        }
        for (const name2 in inputs) {
          const input = inputs[name2];
          switch (name2) {
            case "VERTEX":
              for (const key2 in vertices) {
                const id = vertices[key2];
                switch (key2) {
                  case "POSITION":
                    const prevLength = position3.array.length;
                    buildGeometryData(primitive, sources[id], input.offset, position3.array);
                    position3.stride = sources[id].stride;
                    if (sources.skinWeights && sources.skinIndices) {
                      buildGeometryData(primitive, sources.skinIndices, input.offset, skinIndex.array);
                      buildGeometryData(primitive, sources.skinWeights, input.offset, skinWeight.array);
                    }
                    if (primitive.hasUV === false && primitives.uvsNeedsFix === true) {
                      const count3 = (position3.array.length - prevLength) / position3.stride;
                      for (let i = 0; i < count3; i++) {
                        uv.array.push(0, 0);
                      }
                    }
                    break;
                  case "NORMAL":
                    buildGeometryData(primitive, sources[id], input.offset, normal.array);
                    normal.stride = sources[id].stride;
                    break;
                  case "COLOR":
                    buildGeometryData(primitive, sources[id], input.offset, color.array);
                    color.stride = sources[id].stride;
                    break;
                  case "TEXCOORD":
                    buildGeometryData(primitive, sources[id], input.offset, uv.array);
                    uv.stride = sources[id].stride;
                    break;
                  case "TEXCOORD1":
                    buildGeometryData(primitive, sources[id], input.offset, uv1.array);
                    uv.stride = sources[id].stride;
                    break;
                  default:
                    console.warn('THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key2);
                }
              }
              break;
            case "NORMAL":
              buildGeometryData(primitive, sources[input.id], input.offset, normal.array);
              normal.stride = sources[input.id].stride;
              break;
            case "COLOR":
              buildGeometryData(primitive, sources[input.id], input.offset, color.array, true);
              color.stride = sources[input.id].stride;
              break;
            case "TEXCOORD":
              buildGeometryData(primitive, sources[input.id], input.offset, uv.array);
              uv.stride = sources[input.id].stride;
              break;
            case "TEXCOORD1":
              buildGeometryData(primitive, sources[input.id], input.offset, uv1.array);
              uv1.stride = sources[input.id].stride;
              break;
          }
        }
      }
      if (position3.array.length > 0) geometry.setAttribute("position", new Float32BufferAttribute(position3.array, position3.stride));
      if (normal.array.length > 0) geometry.setAttribute("normal", new Float32BufferAttribute(normal.array, normal.stride));
      if (color.array.length > 0) geometry.setAttribute("color", new Float32BufferAttribute(color.array, color.stride));
      if (uv.array.length > 0) geometry.setAttribute("uv", new Float32BufferAttribute(uv.array, uv.stride));
      if (uv1.array.length > 0) geometry.setAttribute("uv1", new Float32BufferAttribute(uv1.array, uv1.stride));
      if (skinIndex.array.length > 0) geometry.setAttribute("skinIndex", new Float32BufferAttribute(skinIndex.array, skinIndex.stride));
      if (skinWeight.array.length > 0) geometry.setAttribute("skinWeight", new Float32BufferAttribute(skinWeight.array, skinWeight.stride));
      build.data = geometry;
      build.type = primitives[0].type;
      build.materialKeys = materialKeys;
      return build;
    }
    function buildGeometryData(primitive, source, offset, array, isColor = false) {
      const indices = primitive.p;
      const stride = primitive.stride;
      const vcount = primitive.vcount;
      function pushVector(i) {
        let index2 = indices[i + offset] * sourceStride;
        const length2 = index2 + sourceStride;
        for (; index2 < length2; index2++) {
          array.push(sourceArray[index2]);
        }
        if (isColor) {
          const startIndex = array.length - sourceStride - 1;
          tempColor.setRGB(
            array[startIndex + 0],
            array[startIndex + 1],
            array[startIndex + 2],
            SRGBColorSpace
          );
          array[startIndex + 0] = tempColor.r;
          array[startIndex + 1] = tempColor.g;
          array[startIndex + 2] = tempColor.b;
        }
      }
      const sourceArray = source.array;
      const sourceStride = source.stride;
      if (primitive.vcount !== void 0) {
        let index2 = 0;
        for (let i = 0, l2 = vcount.length; i < l2; i++) {
          const count2 = vcount[i];
          if (count2 === 4) {
            const a2 = index2 + stride * 0;
            const b3 = index2 + stride * 1;
            const c2 = index2 + stride * 2;
            const d = index2 + stride * 3;
            pushVector(a2);
            pushVector(b3);
            pushVector(d);
            pushVector(b3);
            pushVector(c2);
            pushVector(d);
          } else if (count2 === 3) {
            const a2 = index2 + stride * 0;
            const b3 = index2 + stride * 1;
            const c2 = index2 + stride * 2;
            pushVector(a2);
            pushVector(b3);
            pushVector(c2);
          } else if (count2 > 4) {
            for (let k2 = 1, kl = count2 - 2; k2 <= kl; k2++) {
              const a2 = index2 + stride * 0;
              const b3 = index2 + stride * k2;
              const c2 = index2 + stride * (k2 + 1);
              pushVector(a2);
              pushVector(b3);
              pushVector(c2);
            }
          }
          index2 += stride * count2;
        }
      } else {
        for (let i = 0, l2 = indices.length; i < l2; i += stride) {
          pushVector(i);
        }
      }
    }
    function getGeometry(id) {
      return getBuild(library.geometries[id], buildGeometry);
    }
    function parseKinematicsModel(xml2) {
      const data2 = {
        name: xml2.getAttribute("name") || "",
        joints: {},
        links: []
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "technique_common":
            parseKinematicsTechniqueCommon(child, data2);
            break;
        }
      }
      library.kinematicsModels[xml2.getAttribute("id")] = data2;
    }
    function buildKinematicsModel(data2) {
      if (data2.build !== void 0) return data2.build;
      return data2;
    }
    function getKinematicsModel(id) {
      return getBuild(library.kinematicsModels[id], buildKinematicsModel);
    }
    function parseKinematicsTechniqueCommon(xml2, data2) {
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "joint":
            data2.joints[child.getAttribute("sid")] = parseKinematicsJoint(child);
            break;
          case "link":
            data2.links.push(parseKinematicsLink(child));
            break;
        }
      }
    }
    function parseKinematicsJoint(xml2) {
      let data2;
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "prismatic":
          case "revolute":
            data2 = parseKinematicsJointParameter(child);
            break;
        }
      }
      return data2;
    }
    function parseKinematicsJointParameter(xml2) {
      const data2 = {
        sid: xml2.getAttribute("sid"),
        name: xml2.getAttribute("name") || "",
        axis: new Vector3(),
        limits: {
          min: 0,
          max: 0
        },
        type: xml2.nodeName,
        static: false,
        zeroPosition: 0,
        middlePosition: 0
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "axis":
            const array = parseFloats(child.textContent);
            data2.axis.fromArray(array);
            break;
          case "limits":
            const max2 = child.getElementsByTagName("max")[0];
            const min = child.getElementsByTagName("min")[0];
            data2.limits.max = parseFloat(max2.textContent);
            data2.limits.min = parseFloat(min.textContent);
            break;
        }
      }
      if (data2.limits.min >= data2.limits.max) {
        data2.static = true;
      }
      data2.middlePosition = (data2.limits.min + data2.limits.max) / 2;
      return data2;
    }
    function parseKinematicsLink(xml2) {
      const data2 = {
        sid: xml2.getAttribute("sid"),
        name: xml2.getAttribute("name") || "",
        attachments: [],
        transforms: []
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "attachment_full":
            data2.attachments.push(parseKinematicsAttachment(child));
            break;
          case "matrix":
          case "translate":
          case "rotate":
            data2.transforms.push(parseKinematicsTransform(child));
            break;
        }
      }
      return data2;
    }
    function parseKinematicsAttachment(xml2) {
      const data2 = {
        joint: xml2.getAttribute("joint").split("/").pop(),
        transforms: [],
        links: []
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "link":
            data2.links.push(parseKinematicsLink(child));
            break;
          case "matrix":
          case "translate":
          case "rotate":
            data2.transforms.push(parseKinematicsTransform(child));
            break;
        }
      }
      return data2;
    }
    function parseKinematicsTransform(xml2) {
      const data2 = {
        type: xml2.nodeName
      };
      const array = parseFloats(xml2.textContent);
      switch (data2.type) {
        case "matrix":
          data2.obj = new Matrix4();
          data2.obj.fromArray(array).transpose();
          break;
        case "translate":
          data2.obj = new Vector3();
          data2.obj.fromArray(array);
          break;
        case "rotate":
          data2.obj = new Vector3();
          data2.obj.fromArray(array);
          data2.angle = MathUtils.degToRad(array[3]);
          break;
      }
      return data2;
    }
    function parsePhysicsModel(xml2) {
      const data2 = {
        name: xml2.getAttribute("name") || "",
        rigidBodies: {}
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "rigid_body":
            data2.rigidBodies[child.getAttribute("name")] = {};
            parsePhysicsRigidBody(child, data2.rigidBodies[child.getAttribute("name")]);
            break;
        }
      }
      library.physicsModels[xml2.getAttribute("id")] = data2;
    }
    function parsePhysicsRigidBody(xml2, data2) {
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "technique_common":
            parsePhysicsTechniqueCommon(child, data2);
            break;
        }
      }
    }
    function parsePhysicsTechniqueCommon(xml2, data2) {
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "inertia":
            data2.inertia = parseFloats(child.textContent);
            break;
          case "mass":
            data2.mass = parseFloats(child.textContent)[0];
            break;
        }
      }
    }
    function parseKinematicsScene(xml2) {
      const data2 = {
        bindJointAxis: []
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "bind_joint_axis":
            data2.bindJointAxis.push(parseKinematicsBindJointAxis(child));
            break;
        }
      }
      library.kinematicsScenes[parseId(xml2.getAttribute("url"))] = data2;
    }
    function parseKinematicsBindJointAxis(xml2) {
      const data2 = {
        target: xml2.getAttribute("target").split("/").pop()
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        switch (child.nodeName) {
          case "axis":
            const param = child.getElementsByTagName("param")[0];
            data2.axis = param.textContent;
            const tmpJointIndex = data2.axis.split("inst_").pop().split("axis")[0];
            data2.jointIndex = tmpJointIndex.substring(0, tmpJointIndex.length - 1);
            break;
        }
      }
      return data2;
    }
    function buildKinematicsScene(data2) {
      if (data2.build !== void 0) return data2.build;
      return data2;
    }
    function getKinematicsScene(id) {
      return getBuild(library.kinematicsScenes[id], buildKinematicsScene);
    }
    function setupKinematics() {
      const kinematicsModelId = Object.keys(library.kinematicsModels)[0];
      const kinematicsSceneId = Object.keys(library.kinematicsScenes)[0];
      const visualSceneId = Object.keys(library.visualScenes)[0];
      if (kinematicsModelId === void 0 || kinematicsSceneId === void 0) return;
      const kinematicsModel = getKinematicsModel(kinematicsModelId);
      const kinematicsScene = getKinematicsScene(kinematicsSceneId);
      const visualScene = getVisualScene(visualSceneId);
      const bindJointAxis = kinematicsScene.bindJointAxis;
      const jointMap = {};
      for (let i = 0, l2 = bindJointAxis.length; i < l2; i++) {
        const axis = bindJointAxis[i];
        const targetElement = collada.querySelector('[sid="' + axis.target + '"]');
        if (targetElement) {
          const parentVisualElement = targetElement.parentElement;
          connect(axis.jointIndex, parentVisualElement);
        }
      }
      function connect(jointIndex, visualElement) {
        const visualElementName = visualElement.getAttribute("name");
        const joint = kinematicsModel.joints[jointIndex];
        visualScene.traverse(function(object) {
          if (object.name === visualElementName) {
            jointMap[jointIndex] = {
              object,
              transforms: buildTransformList(visualElement),
              joint,
              position: joint.zeroPosition
            };
          }
        });
      }
      const m0 = new Matrix4();
      kinematics = {
        joints: kinematicsModel && kinematicsModel.joints,
        getJointValue: function(jointIndex) {
          const jointData = jointMap[jointIndex];
          if (jointData) {
            return jointData.position;
          } else {
            console.warn("THREE.ColladaLoader: Joint " + jointIndex + " doesn't exist.");
          }
        },
        setJointValue: function(jointIndex, value2) {
          const jointData = jointMap[jointIndex];
          if (jointData) {
            const joint = jointData.joint;
            if (value2 > joint.limits.max || value2 < joint.limits.min) {
              console.warn("THREE.ColladaLoader: Joint " + jointIndex + " value " + value2 + " outside of limits (min: " + joint.limits.min + ", max: " + joint.limits.max + ").");
            } else if (joint.static) {
              console.warn("THREE.ColladaLoader: Joint " + jointIndex + " is static.");
            } else {
              const object = jointData.object;
              const axis = joint.axis;
              const transforms = jointData.transforms;
              matrix2.identity();
              for (let i = 0; i < transforms.length; i++) {
                const transform2 = transforms[i];
                if (transform2.sid && transform2.sid.indexOf(jointIndex) !== -1) {
                  switch (joint.type) {
                    case "revolute":
                      matrix2.multiply(m0.makeRotationAxis(axis, MathUtils.degToRad(value2)));
                      break;
                    case "prismatic":
                      matrix2.multiply(m0.makeTranslation(axis.x * value2, axis.y * value2, axis.z * value2));
                      break;
                    default:
                      console.warn("THREE.ColladaLoader: Unknown joint type: " + joint.type);
                      break;
                  }
                } else {
                  switch (transform2.type) {
                    case "matrix":
                      matrix2.multiply(transform2.obj);
                      break;
                    case "translate":
                      matrix2.multiply(m0.makeTranslation(transform2.obj.x, transform2.obj.y, transform2.obj.z));
                      break;
                    case "scale":
                      matrix2.scale(transform2.obj);
                      break;
                    case "rotate":
                      matrix2.multiply(m0.makeRotationAxis(transform2.obj, transform2.angle));
                      break;
                  }
                }
              }
              object.matrix.copy(matrix2);
              object.matrix.decompose(object.position, object.quaternion, object.scale);
              jointMap[jointIndex].position = value2;
            }
          } else {
            console.log("THREE.ColladaLoader: " + jointIndex + " does not exist.");
          }
        }
      };
    }
    function buildTransformList(node) {
      const transforms = [];
      const xml2 = collada.querySelector('[id="' + node.id + '"]');
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        let array, vector2;
        switch (child.nodeName) {
          case "matrix":
            array = parseFloats(child.textContent);
            const matrix3 = new Matrix4().fromArray(array).transpose();
            transforms.push({
              sid: child.getAttribute("sid"),
              type: child.nodeName,
              obj: matrix3
            });
            break;
          case "translate":
          case "scale":
            array = parseFloats(child.textContent);
            vector2 = new Vector3().fromArray(array);
            transforms.push({
              sid: child.getAttribute("sid"),
              type: child.nodeName,
              obj: vector2
            });
            break;
          case "rotate":
            array = parseFloats(child.textContent);
            vector2 = new Vector3().fromArray(array);
            const angle = MathUtils.degToRad(array[3]);
            transforms.push({
              sid: child.getAttribute("sid"),
              type: child.nodeName,
              obj: vector2,
              angle
            });
            break;
        }
      }
      return transforms;
    }
    function prepareNodes(xml2) {
      const elements = xml2.getElementsByTagName("node");
      for (let i = 0; i < elements.length; i++) {
        const element = elements[i];
        if (element.hasAttribute("id") === false) {
          element.setAttribute("id", generateId());
        }
      }
    }
    const matrix2 = new Matrix4();
    const vector = new Vector3();
    function parseNode(xml2) {
      const data2 = {
        name: xml2.getAttribute("name") || "",
        type: xml2.getAttribute("type"),
        id: xml2.getAttribute("id"),
        sid: xml2.getAttribute("sid"),
        matrix: new Matrix4(),
        nodes: [],
        instanceCameras: [],
        instanceControllers: [],
        instanceLights: [],
        instanceGeometries: [],
        instanceNodes: [],
        transforms: {}
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        if (child.nodeType !== 1) continue;
        let array;
        switch (child.nodeName) {
          case "node":
            data2.nodes.push(child.getAttribute("id"));
            parseNode(child);
            break;
          case "instance_camera":
            data2.instanceCameras.push(parseId(child.getAttribute("url")));
            break;
          case "instance_controller":
            data2.instanceControllers.push(parseNodeInstance(child));
            break;
          case "instance_light":
            data2.instanceLights.push(parseId(child.getAttribute("url")));
            break;
          case "instance_geometry":
            data2.instanceGeometries.push(parseNodeInstance(child));
            break;
          case "instance_node":
            data2.instanceNodes.push(parseId(child.getAttribute("url")));
            break;
          case "matrix":
            array = parseFloats(child.textContent);
            data2.matrix.multiply(matrix2.fromArray(array).transpose());
            data2.transforms[child.getAttribute("sid")] = child.nodeName;
            break;
          case "translate":
            array = parseFloats(child.textContent);
            vector.fromArray(array);
            data2.matrix.multiply(matrix2.makeTranslation(vector.x, vector.y, vector.z));
            data2.transforms[child.getAttribute("sid")] = child.nodeName;
            break;
          case "rotate":
            array = parseFloats(child.textContent);
            const angle = MathUtils.degToRad(array[3]);
            data2.matrix.multiply(matrix2.makeRotationAxis(vector.fromArray(array), angle));
            data2.transforms[child.getAttribute("sid")] = child.nodeName;
            break;
          case "scale":
            array = parseFloats(child.textContent);
            data2.matrix.scale(vector.fromArray(array));
            data2.transforms[child.getAttribute("sid")] = child.nodeName;
            break;
          case "extra":
            break;
          default:
            console.log(child);
        }
      }
      if (hasNode(data2.id)) {
        console.warn("THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.", data2.id);
      } else {
        library.nodes[data2.id] = data2;
      }
      return data2;
    }
    function parseNodeInstance(xml2) {
      const data2 = {
        id: parseId(xml2.getAttribute("url")),
        materials: {},
        skeletons: []
      };
      for (let i = 0; i < xml2.childNodes.length; i++) {
        const child = xml2.childNodes[i];
        switch (child.nodeName) {
          case "bind_material":
            const instances = child.getElementsByTagName("instance_material");
            for (let j2 = 0; j2 < instances.length; j2++) {
              const instance = instances[j2];
              const symbol = instance.getAttribute("symbol");
              const target = instance.getAttribute("target");
              data2.materials[symbol] = parseId(target);
            }
            break;
          case "skeleton":
            data2.skeletons.push(parseId(child.textContent));
            break;
          default:
            break;
        }
      }
      return data2;
    }
    function buildSkeleton(skeletons, joints) {
      const boneData = [];
      const sortedBoneData = [];
      let i, j2, data2;
      for (i = 0; i < skeletons.length; i++) {
        const skeleton = skeletons[i];
        let root;
        if (hasNode(skeleton)) {
          root = getNode(skeleton);
          buildBoneHierarchy(root, joints, boneData);
        } else if (hasVisualScene(skeleton)) {
          const visualScene = library.visualScenes[skeleton];
          const children = visualScene.children;
          for (let j3 = 0; j3 < children.length; j3++) {
            const child = children[j3];
            if (child.type === "JOINT") {
              const root2 = getNode(child.id);
              buildBoneHierarchy(root2, joints, boneData);
            }
          }
        } else {
          console.error("THREE.ColladaLoader: Unable to find root bone of skeleton with ID:", skeleton);
        }
      }
      for (i = 0; i < joints.length; i++) {
        for (j2 = 0; j2 < boneData.length; j2++) {
          data2 = boneData[j2];
          if (data2.bone.name === joints[i].name) {
            sortedBoneData[i] = data2;
            data2.processed = true;
            break;
          }
        }
      }
      for (i = 0; i < boneData.length; i++) {
        data2 = boneData[i];
        if (data2.processed === false) {
          sortedBoneData.push(data2);
          data2.processed = true;
        }
      }
      const bones = [];
      const boneInverses = [];
      for (i = 0; i < sortedBoneData.length; i++) {
        data2 = sortedBoneData[i];
        bones.push(data2.bone);
        boneInverses.push(data2.boneInverse);
      }
      return new Skeleton(bones, boneInverses);
    }
    function buildBoneHierarchy(root, joints, boneData) {
      root.traverse(function(object) {
        if (object.isBone === true) {
          let boneInverse;
          for (let i = 0; i < joints.length; i++) {
            const joint = joints[i];
            if (joint.name === object.name) {
              boneInverse = joint.boneInverse;
              break;
            }
          }
          if (boneInverse === void 0) {
            boneInverse = new Matrix4();
          }
          boneData.push({ bone: object, boneInverse, processed: false });
        }
      });
    }
    function buildNode(data2) {
      const objects = [];
      const matrix3 = data2.matrix;
      const nodes = data2.nodes;
      const type = data2.type;
      const instanceCameras = data2.instanceCameras;
      const instanceControllers = data2.instanceControllers;
      const instanceLights = data2.instanceLights;
      const instanceGeometries = data2.instanceGeometries;
      const instanceNodes = data2.instanceNodes;
      for (let i = 0, l2 = nodes.length; i < l2; i++) {
        objects.push(getNode(nodes[i]));
      }
      for (let i = 0, l2 = instanceCameras.length; i < l2; i++) {
        const instanceCamera = getCamera(instanceCameras[i]);
        if (instanceCamera !== null) {
          objects.push(instanceCamera.clone());
        }
      }
      for (let i = 0, l2 = instanceControllers.length; i < l2; i++) {
        const instance = instanceControllers[i];
        const controller = getController(instance.id);
        const geometries = getGeometry(controller.id);
        const newObjects = buildObjects(geometries, instance.materials);
        const skeletons = instance.skeletons;
        const joints = controller.skin.joints;
        const skeleton = buildSkeleton(skeletons, joints);
        for (let j2 = 0, jl = newObjects.length; j2 < jl; j2++) {
          const object2 = newObjects[j2];
          if (object2.isSkinnedMesh) {
            object2.bind(skeleton, controller.skin.bindMatrix);
            object2.normalizeSkinWeights();
          }
          objects.push(object2);
        }
      }
      for (let i = 0, l2 = instanceLights.length; i < l2; i++) {
        const instanceLight = getLight(instanceLights[i]);
        if (instanceLight !== null) {
          objects.push(instanceLight.clone());
        }
      }
      for (let i = 0, l2 = instanceGeometries.length; i < l2; i++) {
        const instance = instanceGeometries[i];
        const geometries = getGeometry(instance.id);
        const newObjects = buildObjects(geometries, instance.materials);
        for (let j2 = 0, jl = newObjects.length; j2 < jl; j2++) {
          objects.push(newObjects[j2]);
        }
      }
      for (let i = 0, l2 = instanceNodes.length; i < l2; i++) {
        objects.push(getNode(instanceNodes[i]).clone());
      }
      let object;
      if (nodes.length === 0 && objects.length === 1) {
        object = objects[0];
      } else {
        object = type === "JOINT" ? new Bone() : new Group();
        for (let i = 0; i < objects.length; i++) {
          object.add(objects[i]);
        }
      }
      object.name = type === "JOINT" ? data2.sid : data2.name;
      object.matrix.copy(matrix3);
      object.matrix.decompose(object.position, object.quaternion, object.scale);
      return object;
    }
    const fallbackMaterial = new MeshBasicMaterial({
      name: Loader.DEFAULT_MATERIAL_NAME,
      color: 16711935
    });
    function resolveMaterialBinding(keys2, instanceMaterials) {
      const materials = [];
      for (let i = 0, l2 = keys2.length; i < l2; i++) {
        const id = instanceMaterials[keys2[i]];
        if (id === void 0) {
          console.warn("THREE.ColladaLoader: Material with key %s not found. Apply fallback material.", keys2[i]);
          materials.push(fallbackMaterial);
        } else {
          materials.push(getMaterial(id));
        }
      }
      return materials;
    }
    function buildObjects(geometries, instanceMaterials) {
      const objects = [];
      for (const type in geometries) {
        const geometry = geometries[type];
        const materials = resolveMaterialBinding(geometry.materialKeys, instanceMaterials);
        if (materials.length === 0) {
          if (type === "lines" || type === "linestrips") {
            materials.push(new LineBasicMaterial());
          } else {
            materials.push(new MeshPhongMaterial());
          }
        }
        if (type === "lines" || type === "linestrips") {
          for (let i = 0, l2 = materials.length; i < l2; i++) {
            const material2 = materials[i];
            if (material2.isMeshPhongMaterial === true || material2.isMeshLambertMaterial === true) {
              const lineMaterial = new LineBasicMaterial();
              lineMaterial.color.copy(material2.color);
              lineMaterial.opacity = material2.opacity;
              lineMaterial.transparent = material2.transparent;
              materials[i] = lineMaterial;
            }
          }
        }
        const skinning = geometry.data.attributes.skinIndex !== void 0;
        const material = materials.length === 1 ? materials[0] : materials;
        let object;
        switch (type) {
          case "lines":
            object = new LineSegments(geometry.data, material);
            break;
          case "linestrips":
            object = new Line(geometry.data, material);
            break;
          case "triangles":
          case "polylist":
            if (skinning) {
              object = new SkinnedMesh(geometry.data, material);
            } else {
              object = new Mesh(geometry.data, material);
            }
            break;
        }
        objects.push(object);
      }
      return objects;
    }
    function hasNode(id) {
      return library.nodes[id] !== void 0;
    }
    function getNode(id) {
      return getBuild(library.nodes[id], buildNode);
    }
    function parseVisualScene(xml2) {
      const data2 = {
        name: xml2.getAttribute("name"),
        children: []
      };
      prepareNodes(xml2);
      const elements = getElementsByTagName(xml2, "node");
      for (let i = 0; i < elements.length; i++) {
        data2.children.push(parseNode(elements[i]));
      }
      library.visualScenes[xml2.getAttribute("id")] = data2;
    }
    function buildVisualScene(data2) {
      const group = new Group();
      group.name = data2.name;
      const children = data2.children;
      for (let i = 0; i < children.length; i++) {
        const child = children[i];
        group.add(getNode(child.id));
      }
      return group;
    }
    function hasVisualScene(id) {
      return library.visualScenes[id] !== void 0;
    }
    function getVisualScene(id) {
      return getBuild(library.visualScenes[id], buildVisualScene);
    }
    function parseScene(xml2) {
      const instance = getElementsByTagName(xml2, "instance_visual_scene")[0];
      return getVisualScene(parseId(instance.getAttribute("url")));
    }
    function setupAnimations() {
      const clips = library.clips;
      if (isEmpty2(clips) === true) {
        if (isEmpty2(library.animations) === false) {
          const tracks = [];
          for (const id in library.animations) {
            const animationTracks = getAnimation(id);
            for (let i = 0, l2 = animationTracks.length; i < l2; i++) {
              tracks.push(animationTracks[i]);
            }
          }
          animations.push(new AnimationClip("default", -1, tracks));
        }
      } else {
        for (const id in clips) {
          animations.push(getAnimationClip(id));
        }
      }
    }
    function parserErrorToText(parserError2) {
      let result = "";
      const stack = [parserError2];
      while (stack.length) {
        const node = stack.shift();
        if (node.nodeType === Node.TEXT_NODE) {
          result += node.textContent;
        } else {
          result += "\n";
          stack.push(...node.childNodes);
        }
      }
      return result.trim();
    }
    if (text2.length === 0) {
      return { scene: new Scene() };
    }
    const xml = new DOMParser().parseFromString(text2, "application/xml");
    const collada = getElementsByTagName(xml, "COLLADA")[0];
    const parserError = xml.getElementsByTagName("parsererror")[0];
    if (parserError !== void 0) {
      const errorElement = getElementsByTagName(parserError, "div")[0];
      let errorText;
      if (errorElement) {
        errorText = errorElement.textContent;
      } else {
        errorText = parserErrorToText(parserError);
      }
      console.error("THREE.ColladaLoader: Failed to parse collada file.\n", errorText);
      return null;
    }
    const version = collada.getAttribute("version");
    console.debug("THREE.ColladaLoader: File version", version);
    const asset = parseAsset(getElementsByTagName(collada, "asset")[0]);
    const textureLoader = new TextureLoader(this.manager);
    textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
    let tgaLoader;
    if (TGALoader) {
      tgaLoader = new TGALoader(this.manager);
      tgaLoader.setPath(this.resourcePath || path);
    }
    const tempColor = new Color();
    const animations = [];
    let kinematics = {};
    let count = 0;
    const library = {
      animations: {},
      clips: {},
      controllers: {},
      images: {},
      effects: {},
      materials: {},
      cameras: {},
      lights: {},
      geometries: {},
      nodes: {},
      visualScenes: {},
      kinematicsModels: {},
      physicsModels: {},
      kinematicsScenes: {}
    };
    parseLibrary(collada, "library_animations", "animation", parseAnimation);
    parseLibrary(collada, "library_animation_clips", "animation_clip", parseAnimationClip);
    parseLibrary(collada, "library_controllers", "controller", parseController);
    parseLibrary(collada, "library_images", "image", parseImage);
    parseLibrary(collada, "library_effects", "effect", parseEffect);
    parseLibrary(collada, "library_materials", "material", parseMaterial);
    parseLibrary(collada, "library_cameras", "camera", parseCamera);
    parseLibrary(collada, "library_lights", "light", parseLight);
    parseLibrary(collada, "library_geometries", "geometry", parseGeometry);
    parseLibrary(collada, "library_nodes", "node", parseNode);
    parseLibrary(collada, "library_visual_scenes", "visual_scene", parseVisualScene);
    parseLibrary(collada, "library_kinematics_models", "kinematics_model", parseKinematicsModel);
    parseLibrary(collada, "library_physics_models", "physics_model", parsePhysicsModel);
    parseLibrary(collada, "scene", "instance_kinematics_scene", parseKinematicsScene);
    buildLibrary(library.animations, buildAnimation);
    buildLibrary(library.clips, buildAnimationClip);
    buildLibrary(library.controllers, buildController);
    buildLibrary(library.images, buildImage);
    buildLibrary(library.effects, buildEffect);
    buildLibrary(library.materials, buildMaterial2);
    buildLibrary(library.cameras, buildCamera2);
    buildLibrary(library.lights, buildLight);
    buildLibrary(library.geometries, buildGeometry);
    buildLibrary(library.visualScenes, buildVisualScene);
    setupAnimations();
    setupKinematics();
    const scene = parseScene(getElementsByTagName(collada, "scene")[0]);
    scene.animations = animations;
    if (asset.upAxis === "Z_UP") {
      console.warn("THREE.ColladaLoader: You are loading an asset with a Z-UP coordinate system. The loader just rotates the asset to transform it into Y-UP. The vertex data are not converted, see #24289.");
      scene.rotation.set(-Math.PI / 2, 0, 0);
    }
    scene.scale.multiplyScalar(asset.unit);
    return {
      get animations() {
        console.warn("THREE.ColladaLoader: Please access animations over scene.animations now.");
        return animations;
      },
      kinematics,
      library,
      scene
    };
  }
};

// node_modules/three/examples/jsm/loaders/DDSLoader.js
var DDSLoader = class extends CompressedTextureLoader {
  /**
   * Constructs a new DDS loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Parses the given S3TC texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @param {boolean} loadMipmaps - Whether to load mipmaps or not.
   * @return {CompressedTextureLoader~TexData} An object representing the parsed texture data.
   */
  parse(buffer, loadMipmaps) {
    const dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
    const DDS_MAGIC = 542327876;
    const DDSD_MIPMAPCOUNT = 131072;
    const DDSCAPS2_CUBEMAP = 512;
    const DDSCAPS2_CUBEMAP_POSITIVEX = 1024;
    const DDSCAPS2_CUBEMAP_NEGATIVEX = 2048;
    const DDSCAPS2_CUBEMAP_POSITIVEY = 4096;
    const DDSCAPS2_CUBEMAP_NEGATIVEY = 8192;
    const DDSCAPS2_CUBEMAP_POSITIVEZ = 16384;
    const DDSCAPS2_CUBEMAP_NEGATIVEZ = 32768;
    const DXGI_FORMAT_BC6H_UF16 = 95;
    const DXGI_FORMAT_BC6H_SF16 = 96;
    function fourCCToInt32(value2) {
      return value2.charCodeAt(0) + (value2.charCodeAt(1) << 8) + (value2.charCodeAt(2) << 16) + (value2.charCodeAt(3) << 24);
    }
    function int32ToFourCC(value2) {
      return String.fromCharCode(
        value2 & 255,
        value2 >> 8 & 255,
        value2 >> 16 & 255,
        value2 >> 24 & 255
      );
    }
    function loadARGBMip(buffer2, dataOffset2, width2, height2) {
      const dataLength = width2 * height2 * 4;
      const srcBuffer = new Uint8Array(buffer2, dataOffset2, dataLength);
      const byteArray = new Uint8Array(dataLength);
      let dst = 0;
      let src = 0;
      for (let y = 0; y < height2; y++) {
        for (let x2 = 0; x2 < width2; x2++) {
          const b3 = srcBuffer[src];
          src++;
          const g3 = srcBuffer[src];
          src++;
          const r = srcBuffer[src];
          src++;
          const a2 = srcBuffer[src];
          src++;
          byteArray[dst] = r;
          dst++;
          byteArray[dst] = g3;
          dst++;
          byteArray[dst] = b3;
          dst++;
          byteArray[dst] = a2;
          dst++;
        }
      }
      return byteArray;
    }
    function loadRGBMip(buffer2, dataOffset2, width2, height2) {
      const dataLength = width2 * height2 * 3;
      const srcBuffer = new Uint8Array(buffer2, dataOffset2, dataLength);
      const byteArray = new Uint8Array(width2 * height2 * 4);
      let dst = 0;
      let src = 0;
      for (let y = 0; y < height2; y++) {
        for (let x2 = 0; x2 < width2; x2++) {
          const b3 = srcBuffer[src];
          src++;
          const g3 = srcBuffer[src];
          src++;
          const r = srcBuffer[src];
          src++;
          byteArray[dst] = r;
          dst++;
          byteArray[dst] = g3;
          dst++;
          byteArray[dst] = b3;
          dst++;
          byteArray[dst] = 255;
          dst++;
        }
      }
      return byteArray;
    }
    const FOURCC_DXT1 = fourCCToInt32("DXT1");
    const FOURCC_DXT3 = fourCCToInt32("DXT3");
    const FOURCC_DXT5 = fourCCToInt32("DXT5");
    const FOURCC_ETC1 = fourCCToInt32("ETC1");
    const FOURCC_DX10 = fourCCToInt32("DX10");
    const headerLengthInt = 31;
    const extendedHeaderLengthInt = 5;
    const off_magic = 0;
    const off_size = 1;
    const off_flags = 2;
    const off_height = 3;
    const off_width = 4;
    const off_mipmapCount = 7;
    const off_pfFourCC = 21;
    const off_RGBBitCount = 22;
    const off_RBitMask = 23;
    const off_GBitMask = 24;
    const off_BBitMask = 25;
    const off_ABitMask = 26;
    const off_caps2 = 28;
    const off_dxgiFormat = 0;
    const header = new Int32Array(buffer, 0, headerLengthInt);
    if (header[off_magic] !== DDS_MAGIC) {
      console.error("THREE.DDSLoader.parse: Invalid magic number in DDS header.");
      return dds;
    }
    let blockBytes;
    const fourCC = header[off_pfFourCC];
    let isRGBAUncompressed = false;
    let isRGBUncompressed = false;
    let dataOffset = header[off_size] + 4;
    switch (fourCC) {
      case FOURCC_DXT1:
        blockBytes = 8;
        dds.format = RGB_S3TC_DXT1_Format;
        break;
      case FOURCC_DXT3:
        blockBytes = 16;
        dds.format = RGBA_S3TC_DXT3_Format;
        break;
      case FOURCC_DXT5:
        blockBytes = 16;
        dds.format = RGBA_S3TC_DXT5_Format;
        break;
      case FOURCC_ETC1:
        blockBytes = 8;
        dds.format = RGB_ETC1_Format;
        break;
      case FOURCC_DX10:
        dataOffset += extendedHeaderLengthInt * 4;
        const extendedHeader = new Int32Array(buffer, (headerLengthInt + 1) * 4, extendedHeaderLengthInt);
        const dxgiFormat = extendedHeader[off_dxgiFormat];
        switch (dxgiFormat) {
          case DXGI_FORMAT_BC6H_SF16: {
            blockBytes = 16;
            dds.format = RGB_BPTC_SIGNED_Format;
            break;
          }
          case DXGI_FORMAT_BC6H_UF16: {
            blockBytes = 16;
            dds.format = RGB_BPTC_UNSIGNED_Format;
            break;
          }
          default: {
            console.error("THREE.DDSLoader.parse: Unsupported DXGI_FORMAT code ", dxgiFormat);
            return dds;
          }
        }
        break;
      default:
        if (header[off_RGBBitCount] === 32 && header[off_RBitMask] & 16711680 && header[off_GBitMask] & 65280 && header[off_BBitMask] & 255 && header[off_ABitMask] & 4278190080) {
          isRGBAUncompressed = true;
          blockBytes = 64;
          dds.format = RGBAFormat;
        } else if (header[off_RGBBitCount] === 24 && header[off_RBitMask] & 16711680 && header[off_GBitMask] & 65280 && header[off_BBitMask] & 255) {
          isRGBUncompressed = true;
          blockBytes = 64;
          dds.format = RGBAFormat;
        } else {
          console.error("THREE.DDSLoader.parse: Unsupported FourCC code ", int32ToFourCC(fourCC));
          return dds;
        }
    }
    dds.mipmapCount = 1;
    if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
      dds.mipmapCount = Math.max(1, header[off_mipmapCount]);
    }
    const caps2 = header[off_caps2];
    dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false;
    if (dds.isCubemap && (!(caps2 & DDSCAPS2_CUBEMAP_POSITIVEX) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) || !(caps2 & DDSCAPS2_CUBEMAP_POSITIVEY) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) || !(caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ))) {
      console.error("THREE.DDSLoader.parse: Incomplete cubemap faces");
      return dds;
    }
    dds.width = header[off_width];
    dds.height = header[off_height];
    const faces = dds.isCubemap ? 6 : 1;
    for (let face = 0; face < faces; face++) {
      let width2 = dds.width;
      let height2 = dds.height;
      for (let i = 0; i < dds.mipmapCount; i++) {
        let byteArray, dataLength;
        if (isRGBAUncompressed) {
          byteArray = loadARGBMip(buffer, dataOffset, width2, height2);
          dataLength = byteArray.length;
        } else if (isRGBUncompressed) {
          byteArray = loadRGBMip(buffer, dataOffset, width2, height2);
          dataLength = width2 * height2 * 3;
        } else {
          dataLength = Math.max(4, width2) / 4 * Math.max(4, height2) / 4 * blockBytes;
          byteArray = new Uint8Array(buffer, dataOffset, dataLength);
        }
        const mipmap = { "data": byteArray, "width": width2, "height": height2 };
        dds.mipmaps.push(mipmap);
        dataOffset += dataLength;
        width2 = Math.max(width2 >> 1, 1);
        height2 = Math.max(height2 >> 1, 1);
      }
    }
    return dds;
  }
};

// node_modules/three/examples/jsm/loaders/DRACOLoader.js
var _taskCache2 = /* @__PURE__ */ new WeakMap();
var DRACOLoader = class extends Loader {
  /**
   * Constructs a new Draco loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.decoderPath = "";
    this.decoderConfig = {};
    this.decoderBinary = null;
    this.decoderPending = null;
    this.workerLimit = 4;
    this.workerPool = [];
    this.workerNextTaskID = 1;
    this.workerSourceURL = "";
    this.defaultAttributeIDs = {
      position: "POSITION",
      normal: "NORMAL",
      color: "COLOR",
      uv: "TEX_COORD"
    };
    this.defaultAttributeTypes = {
      position: "Float32Array",
      normal: "Float32Array",
      color: "Float32Array",
      uv: "Float32Array"
    };
  }
  /**
   * Provides configuration for the decoder libraries. Configuration cannot be changed after decoding begins.
   *
   * @param {string} path - The decoder path.
   * @return {DRACOLoader} A reference to this loader.
   */
  setDecoderPath(path) {
    this.decoderPath = path;
    return this;
  }
  /**
   * Provides configuration for the decoder libraries. Configuration cannot be changed after decoding begins.
   *
   * @param {{type:('js'|'wasm')}} config - The decoder config.
   * @return {DRACOLoader} A reference to this loader.
   */
  setDecoderConfig(config) {
    this.decoderConfig = config;
    return this;
  }
  /**
   * Sets the maximum number of Web Workers to be used during decoding.
   * A lower limit may be preferable if workers are also for other tasks in the application.
   *
   * @param {number} workerLimit - The worker limit.
   * @return {DRACOLoader} A reference to this loader.
   */
  setWorkerLimit(workerLimit) {
    this.workerLimit = workerLimit;
    return this;
  }
  /**
   * Starts loading from the given URL and passes the loaded Draco asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, (buffer) => {
      this.parse(buffer, onLoad, onError);
    }, onProgress, onError);
  }
  /**
   * Parses the given Draco data.
   *
   * @param {ArrayBuffer} buffer - The raw Draco data as an array buffer.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading/parsing process has been finished.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  parse(buffer, onLoad, onError = () => {
  }) {
    this.decodeDracoFile(buffer, onLoad, null, null, SRGBColorSpace, onError).catch(onError);
  }
  //
  decodeDracoFile(buffer, callback, attributeIDs, attributeTypes, vertexColorSpace = LinearSRGBColorSpace, onError = () => {
  }) {
    const taskConfig = {
      attributeIDs: attributeIDs || this.defaultAttributeIDs,
      attributeTypes: attributeTypes || this.defaultAttributeTypes,
      useUniqueIDs: !!attributeIDs,
      vertexColorSpace
    };
    return this.decodeGeometry(buffer, taskConfig).then(callback).catch(onError);
  }
  decodeGeometry(buffer, taskConfig) {
    const taskKey = JSON.stringify(taskConfig);
    if (_taskCache2.has(buffer)) {
      const cachedTask = _taskCache2.get(buffer);
      if (cachedTask.key === taskKey) {
        return cachedTask.promise;
      } else if (buffer.byteLength === 0) {
        throw new Error(
          "THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred."
        );
      }
    }
    let worker;
    const taskID = this.workerNextTaskID++;
    const taskCost = buffer.byteLength;
    const geometryPending = this._getWorker(taskID, taskCost).then((_worker) => {
      worker = _worker;
      return new Promise((resolve, reject2) => {
        worker._callbacks[taskID] = { resolve, reject: reject2 };
        worker.postMessage({ type: "decode", id: taskID, taskConfig, buffer }, [buffer]);
      });
    }).then((message) => this._createGeometry(message.geometry));
    geometryPending.catch(() => true).then(() => {
      if (worker && taskID) {
        this._releaseTask(worker, taskID);
      }
    });
    _taskCache2.set(buffer, {
      key: taskKey,
      promise: geometryPending
    });
    return geometryPending;
  }
  _createGeometry(geometryData) {
    const geometry = new BufferGeometry();
    if (geometryData.index) {
      geometry.setIndex(new BufferAttribute(geometryData.index.array, 1));
    }
    for (let i = 0; i < geometryData.attributes.length; i++) {
      const result = geometryData.attributes[i];
      const name2 = result.name;
      const array = result.array;
      const itemSize = result.itemSize;
      const attribute = new BufferAttribute(array, itemSize);
      if (name2 === "color") {
        this._assignVertexColorSpace(attribute, result.vertexColorSpace);
        attribute.normalized = array instanceof Float32Array === false;
      }
      geometry.setAttribute(name2, attribute);
    }
    return geometry;
  }
  _assignVertexColorSpace(attribute, inputColorSpace) {
    if (inputColorSpace !== SRGBColorSpace) return;
    const _color5 = new Color();
    for (let i = 0, il = attribute.count; i < il; i++) {
      _color5.fromBufferAttribute(attribute, i);
      ColorManagement.colorSpaceToWorking(_color5, SRGBColorSpace);
      attribute.setXYZ(i, _color5.r, _color5.g, _color5.b);
    }
  }
  _loadLibrary(url, responseType) {
    const loader = new FileLoader(this.manager);
    loader.setPath(this.decoderPath);
    loader.setResponseType(responseType);
    loader.setWithCredentials(this.withCredentials);
    return new Promise((resolve, reject2) => {
      loader.load(url, resolve, void 0, reject2);
    });
  }
  preload() {
    this._initDecoder();
    return this;
  }
  _initDecoder() {
    if (this.decoderPending) return this.decoderPending;
    const useJS = typeof WebAssembly !== "object" || this.decoderConfig.type === "js";
    const librariesPending = [];
    if (useJS) {
      librariesPending.push(this._loadLibrary("draco_decoder.js", "text"));
    } else {
      librariesPending.push(this._loadLibrary("draco_wasm_wrapper.js", "text"));
      librariesPending.push(this._loadLibrary("draco_decoder.wasm", "arraybuffer"));
    }
    this.decoderPending = Promise.all(librariesPending).then((libraries) => {
      const jsContent = libraries[0];
      if (!useJS) {
        this.decoderConfig.wasmBinary = libraries[1];
      }
      const fn = DRACOWorker.toString();
      const body = [
        "/* draco decoder */",
        jsContent,
        "",
        "/* worker */",
        fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}"))
      ].join("\n");
      this.workerSourceURL = URL.createObjectURL(new Blob([body]));
    });
    return this.decoderPending;
  }
  _getWorker(taskID, taskCost) {
    return this._initDecoder().then(() => {
      if (this.workerPool.length < this.workerLimit) {
        const worker2 = new Worker(this.workerSourceURL);
        worker2._callbacks = {};
        worker2._taskCosts = {};
        worker2._taskLoad = 0;
        worker2.postMessage({ type: "init", decoderConfig: this.decoderConfig });
        worker2.onmessage = function(e) {
          const message = e.data;
          switch (message.type) {
            case "decode":
              worker2._callbacks[message.id].resolve(message);
              break;
            case "error":
              worker2._callbacks[message.id].reject(message);
              break;
            default:
              console.error('THREE.DRACOLoader: Unexpected message, "' + message.type + '"');
          }
        };
        this.workerPool.push(worker2);
      } else {
        this.workerPool.sort(function(a2, b3) {
          return a2._taskLoad > b3._taskLoad ? -1 : 1;
        });
      }
      const worker = this.workerPool[this.workerPool.length - 1];
      worker._taskCosts[taskID] = taskCost;
      worker._taskLoad += taskCost;
      return worker;
    });
  }
  _releaseTask(worker, taskID) {
    worker._taskLoad -= worker._taskCosts[taskID];
    delete worker._callbacks[taskID];
    delete worker._taskCosts[taskID];
  }
  debug() {
    console.log("Task load: ", this.workerPool.map((worker) => worker._taskLoad));
  }
  dispose() {
    for (let i = 0; i < this.workerPool.length; ++i) {
      this.workerPool[i].terminate();
    }
    this.workerPool.length = 0;
    if (this.workerSourceURL !== "") {
      URL.revokeObjectURL(this.workerSourceURL);
    }
    return this;
  }
};
function DRACOWorker() {
  let decoderConfig;
  let decoderPending;
  onmessage = function(e) {
    const message = e.data;
    switch (message.type) {
      case "init":
        decoderConfig = message.decoderConfig;
        decoderPending = new Promise(function(resolve) {
          decoderConfig.onModuleLoaded = function(draco) {
            resolve({ draco });
          };
          DracoDecoderModule(decoderConfig);
        });
        break;
      case "decode":
        const buffer = message.buffer;
        const taskConfig = message.taskConfig;
        decoderPending.then((module2) => {
          const draco = module2.draco;
          const decoder = new draco.Decoder();
          try {
            const geometry = decodeGeometry(draco, decoder, new Int8Array(buffer), taskConfig);
            const buffers = geometry.attributes.map((attr) => attr.array.buffer);
            if (geometry.index) buffers.push(geometry.index.array.buffer);
            self.postMessage({ type: "decode", id: message.id, geometry }, buffers);
          } catch (error) {
            console.error(error);
            self.postMessage({ type: "error", id: message.id, error: error.message });
          } finally {
            draco.destroy(decoder);
          }
        });
        break;
    }
  };
  function decodeGeometry(draco, decoder, array, taskConfig) {
    const attributeIDs = taskConfig.attributeIDs;
    const attributeTypes = taskConfig.attributeTypes;
    let dracoGeometry;
    let decodingStatus;
    const geometryType = decoder.GetEncodedGeometryType(array);
    if (geometryType === draco.TRIANGULAR_MESH) {
      dracoGeometry = new draco.Mesh();
      decodingStatus = decoder.DecodeArrayToMesh(array, array.byteLength, dracoGeometry);
    } else if (geometryType === draco.POINT_CLOUD) {
      dracoGeometry = new draco.PointCloud();
      decodingStatus = decoder.DecodeArrayToPointCloud(array, array.byteLength, dracoGeometry);
    } else {
      throw new Error("THREE.DRACOLoader: Unexpected geometry type.");
    }
    if (!decodingStatus.ok() || dracoGeometry.ptr === 0) {
      throw new Error("THREE.DRACOLoader: Decoding failed: " + decodingStatus.error_msg());
    }
    const geometry = { index: null, attributes: [] };
    for (const attributeName in attributeIDs) {
      const attributeType = self[attributeTypes[attributeName]];
      let attribute;
      let attributeID;
      if (taskConfig.useUniqueIDs) {
        attributeID = attributeIDs[attributeName];
        attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeID);
      } else {
        attributeID = decoder.GetAttributeId(dracoGeometry, draco[attributeIDs[attributeName]]);
        if (attributeID === -1) continue;
        attribute = decoder.GetAttribute(dracoGeometry, attributeID);
      }
      const attributeResult = decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute);
      if (attributeName === "color") {
        attributeResult.vertexColorSpace = taskConfig.vertexColorSpace;
      }
      geometry.attributes.push(attributeResult);
    }
    if (geometryType === draco.TRIANGULAR_MESH) {
      geometry.index = decodeIndex(draco, decoder, dracoGeometry);
    }
    draco.destroy(dracoGeometry);
    return geometry;
  }
  function decodeIndex(draco, decoder, dracoGeometry) {
    const numFaces = dracoGeometry.num_faces();
    const numIndices = numFaces * 3;
    const byteLength = numIndices * 4;
    const ptr = draco._malloc(byteLength);
    decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
    const index2 = new Uint32Array(draco.HEAPF32.buffer, ptr, numIndices).slice();
    draco._free(ptr);
    return { array: index2, itemSize: 1 };
  }
  function decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute) {
    const numComponents = attribute.num_components();
    const numPoints = dracoGeometry.num_points();
    const numValues = numPoints * numComponents;
    const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
    const dataType = getDracoDataType(draco, attributeType);
    const ptr = draco._malloc(byteLength);
    decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, attribute, dataType, byteLength, ptr);
    const array = new attributeType(draco.HEAPF32.buffer, ptr, numValues).slice();
    draco._free(ptr);
    return {
      name: attributeName,
      array,
      itemSize: numComponents
    };
  }
  function getDracoDataType(draco, attributeType) {
    switch (attributeType) {
      case Float32Array:
        return draco.DT_FLOAT32;
      case Int8Array:
        return draco.DT_INT8;
      case Int16Array:
        return draco.DT_INT16;
      case Int32Array:
        return draco.DT_INT32;
      case Uint8Array:
        return draco.DT_UINT8;
      case Uint16Array:
        return draco.DT_UINT16;
      case Uint32Array:
        return draco.DT_UINT32;
    }
  }
}

// node_modules/three/examples/jsm/loaders/FBXLoader.js
var fbxTree;
var connections;
var sceneGraph;
var FBXLoader = class extends Loader {
  /**
   * Constructs a new FBX loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded FBX asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Group)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const path = scope.path === "" ? LoaderUtils.extractUrlBase(url) : scope.path;
    const loader = new FileLoader(this.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(buffer) {
      try {
        onLoad(scope.parse(buffer, path));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given FBX data and returns the resulting group.
   *
   * @param {ArrayBuffer} FBXBuffer - The raw FBX data as an array buffer.
   * @param {string} path - The URL base path.
   * @return {Group} An object representing the parsed asset.
   */
  parse(FBXBuffer, path) {
    if (isFbxFormatBinary(FBXBuffer)) {
      fbxTree = new BinaryParser().parse(FBXBuffer);
    } else {
      const FBXText = convertArrayBufferToString(FBXBuffer);
      if (!isFbxFormatASCII(FBXText)) {
        throw new Error("THREE.FBXLoader: Unknown format.");
      }
      if (getFbxVersion(FBXText) < 7e3) {
        throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: " + getFbxVersion(FBXText));
      }
      fbxTree = new TextParser().parse(FBXText);
    }
    const textureLoader = new TextureLoader(this.manager).setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
    return new FBXTreeParser(textureLoader, this.manager).parse(fbxTree);
  }
};
var FBXTreeParser = class {
  constructor(textureLoader, manager) {
    this.textureLoader = textureLoader;
    this.manager = manager;
  }
  parse() {
    connections = this.parseConnections();
    const images = this.parseImages();
    const textures = this.parseTextures(images);
    const materials = this.parseMaterials(textures);
    const deformers = this.parseDeformers();
    const geometryMap = new GeometryParser().parse(deformers);
    this.parseScene(deformers, geometryMap, materials);
    return sceneGraph;
  }
  // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  // and details the connection type
  parseConnections() {
    const connectionMap = /* @__PURE__ */ new Map();
    if ("Connections" in fbxTree) {
      const rawConnections = fbxTree.Connections.connections;
      rawConnections.forEach(function(rawConnection) {
        const fromID = rawConnection[0];
        const toID = rawConnection[1];
        const relationship = rawConnection[2];
        if (!connectionMap.has(fromID)) {
          connectionMap.set(fromID, {
            parents: [],
            children: []
          });
        }
        const parentRelationship = { ID: toID, relationship };
        connectionMap.get(fromID).parents.push(parentRelationship);
        if (!connectionMap.has(toID)) {
          connectionMap.set(toID, {
            parents: [],
            children: []
          });
        }
        const childRelationship = { ID: fromID, relationship };
        connectionMap.get(toID).children.push(childRelationship);
      });
    }
    return connectionMap;
  }
  // Parse FBXTree.Objects.Video for embedded image data
  // These images are connected to textures in FBXTree.Objects.Textures
  // via FBXTree.Connections.
  parseImages() {
    const images = {};
    const blobs = {};
    if ("Video" in fbxTree.Objects) {
      const videoNodes = fbxTree.Objects.Video;
      for (const nodeID in videoNodes) {
        const videoNode = videoNodes[nodeID];
        const id = parseInt(nodeID);
        images[id] = videoNode.RelativeFilename || videoNode.Filename;
        if ("Content" in videoNode) {
          const arrayBufferContent = videoNode.Content instanceof ArrayBuffer && videoNode.Content.byteLength > 0;
          const base64Content = typeof videoNode.Content === "string" && videoNode.Content !== "";
          if (arrayBufferContent || base64Content) {
            const image = this.parseImage(videoNodes[nodeID]);
            blobs[videoNode.RelativeFilename || videoNode.Filename] = image;
          }
        }
      }
    }
    for (const id in images) {
      const filename = images[id];
      if (blobs[filename] !== void 0) images[id] = blobs[filename];
      else images[id] = images[id].split("\\").pop();
    }
    return images;
  }
  // Parse embedded image data in FBXTree.Video.Content
  parseImage(videoNode) {
    const content2 = videoNode.Content;
    const fileName = videoNode.RelativeFilename || videoNode.Filename;
    const extension = fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase();
    let type;
    switch (extension) {
      case "bmp":
        type = "image/bmp";
        break;
      case "jpg":
      case "jpeg":
        type = "image/jpeg";
        break;
      case "png":
        type = "image/png";
        break;
      case "tif":
        type = "image/tiff";
        break;
      case "tga":
        if (this.manager.getHandler(".tga") === null) {
          console.warn("FBXLoader: TGA loader not found, skipping ", fileName);
        }
        type = "image/tga";
        break;
      case "webp":
        type = "image/webp";
        break;
      default:
        console.warn('FBXLoader: Image type "' + extension + '" is not supported.');
        return;
    }
    if (typeof content2 === "string") {
      return "data:" + type + ";base64," + content2;
    } else {
      const array = new Uint8Array(content2);
      return window.URL.createObjectURL(new Blob([array], { type }));
    }
  }
  // Parse nodes in FBXTree.Objects.Texture
  // These contain details such as UV scaling, cropping, rotation etc and are connected
  // to images in FBXTree.Objects.Video
  parseTextures(images) {
    const textureMap = /* @__PURE__ */ new Map();
    if ("Texture" in fbxTree.Objects) {
      const textureNodes = fbxTree.Objects.Texture;
      for (const nodeID in textureNodes) {
        const texture = this.parseTexture(textureNodes[nodeID], images);
        textureMap.set(parseInt(nodeID), texture);
      }
    }
    return textureMap;
  }
  // Parse individual node in FBXTree.Objects.Texture
  parseTexture(textureNode, images) {
    const texture = this.loadTexture(textureNode, images);
    texture.ID = textureNode.id;
    texture.name = textureNode.attrName;
    const wrapModeU = textureNode.WrapModeU;
    const wrapModeV = textureNode.WrapModeV;
    const valueU = wrapModeU !== void 0 ? wrapModeU.value : 0;
    const valueV = wrapModeV !== void 0 ? wrapModeV.value : 0;
    texture.wrapS = valueU === 0 ? RepeatWrapping : ClampToEdgeWrapping;
    texture.wrapT = valueV === 0 ? RepeatWrapping : ClampToEdgeWrapping;
    if ("Scaling" in textureNode) {
      const values2 = textureNode.Scaling.value;
      texture.repeat.x = values2[0];
      texture.repeat.y = values2[1];
    }
    if ("Translation" in textureNode) {
      const values2 = textureNode.Translation.value;
      texture.offset.x = values2[0];
      texture.offset.y = values2[1];
    }
    return texture;
  }
  // load a texture specified as a blob or data URI, or via an external URL using TextureLoader
  loadTexture(textureNode, images) {
    const extension = textureNode.FileName.split(".").pop().toLowerCase();
    let loader = this.manager.getHandler(`.${extension}`);
    if (loader === null) loader = this.textureLoader;
    const loaderPath = loader.path;
    if (!loaderPath) {
      loader.setPath(this.textureLoader.path);
    }
    const children = connections.get(textureNode.id).children;
    let fileName;
    if (children !== void 0 && children.length > 0 && images[children[0].ID] !== void 0) {
      fileName = images[children[0].ID];
      if (fileName.indexOf("blob:") === 0 || fileName.indexOf("data:") === 0) {
        loader.setPath(void 0);
      }
    }
    if (fileName === void 0) {
      console.warn("FBXLoader: Undefined filename, creating placeholder texture.");
      return new Texture();
    }
    const texture = loader.load(fileName);
    loader.setPath(loaderPath);
    return texture;
  }
  // Parse nodes in FBXTree.Objects.Material
  parseMaterials(textureMap) {
    const materialMap = /* @__PURE__ */ new Map();
    if ("Material" in fbxTree.Objects) {
      const materialNodes = fbxTree.Objects.Material;
      for (const nodeID in materialNodes) {
        const material = this.parseMaterial(materialNodes[nodeID], textureMap);
        if (material !== null) materialMap.set(parseInt(nodeID), material);
      }
    }
    return materialMap;
  }
  // Parse single node in FBXTree.Objects.Material
  // Materials are connected to texture maps in FBXTree.Objects.Textures
  // FBX format currently only supports Lambert and Phong shading models
  parseMaterial(materialNode, textureMap) {
    const ID = materialNode.id;
    const name2 = materialNode.attrName;
    let type = materialNode.ShadingModel;
    if (typeof type === "object") {
      type = type.value;
    }
    if (!connections.has(ID)) return null;
    const parameters = this.parseParameters(materialNode, textureMap, ID);
    let material;
    switch (type.toLowerCase()) {
      case "phong":
        material = new MeshPhongMaterial();
        break;
      case "lambert":
        material = new MeshLambertMaterial();
        break;
      default:
        console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type);
        material = new MeshPhongMaterial();
        break;
    }
    material.setValues(parameters);
    material.name = name2;
    return material;
  }
  // Parse FBX material and return parameters suitable for a three.js material
  // Also parse the texture map and return any textures associated with the material
  parseParameters(materialNode, textureMap, ID) {
    const parameters = {};
    if (materialNode.BumpFactor) {
      parameters.bumpScale = materialNode.BumpFactor.value;
    }
    if (materialNode.Diffuse) {
      parameters.color = ColorManagement.colorSpaceToWorking(new Color().fromArray(materialNode.Diffuse.value), SRGBColorSpace);
    } else if (materialNode.DiffuseColor && (materialNode.DiffuseColor.type === "Color" || materialNode.DiffuseColor.type === "ColorRGB")) {
      parameters.color = ColorManagement.colorSpaceToWorking(new Color().fromArray(materialNode.DiffuseColor.value), SRGBColorSpace);
    }
    if (materialNode.DisplacementFactor) {
      parameters.displacementScale = materialNode.DisplacementFactor.value;
    }
    if (materialNode.Emissive) {
      parameters.emissive = ColorManagement.colorSpaceToWorking(new Color().fromArray(materialNode.Emissive.value), SRGBColorSpace);
    } else if (materialNode.EmissiveColor && (materialNode.EmissiveColor.type === "Color" || materialNode.EmissiveColor.type === "ColorRGB")) {
      parameters.emissive = ColorManagement.colorSpaceToWorking(new Color().fromArray(materialNode.EmissiveColor.value), SRGBColorSpace);
    }
    if (materialNode.EmissiveFactor) {
      parameters.emissiveIntensity = parseFloat(materialNode.EmissiveFactor.value);
    }
    parameters.opacity = 1 - (materialNode.TransparencyFactor ? parseFloat(materialNode.TransparencyFactor.value) : 0);
    if (parameters.opacity === 1 || parameters.opacity === 0) {
      parameters.opacity = materialNode.Opacity ? parseFloat(materialNode.Opacity.value) : null;
      if (parameters.opacity === null) {
        parameters.opacity = 1 - (materialNode.TransparentColor ? parseFloat(materialNode.TransparentColor.value[0]) : 0);
      }
    }
    if (parameters.opacity < 1) {
      parameters.transparent = true;
    }
    if (materialNode.ReflectionFactor) {
      parameters.reflectivity = materialNode.ReflectionFactor.value;
    }
    if (materialNode.Shininess) {
      parameters.shininess = materialNode.Shininess.value;
    }
    if (materialNode.Specular) {
      parameters.specular = ColorManagement.colorSpaceToWorking(new Color().fromArray(materialNode.Specular.value), SRGBColorSpace);
    } else if (materialNode.SpecularColor && materialNode.SpecularColor.type === "Color") {
      parameters.specular = ColorManagement.colorSpaceToWorking(new Color().fromArray(materialNode.SpecularColor.value), SRGBColorSpace);
    }
    const scope = this;
    connections.get(ID).children.forEach(function(child) {
      const type = child.relationship;
      switch (type) {
        case "Bump":
          parameters.bumpMap = scope.getTexture(textureMap, child.ID);
          break;
        case "Maya|TEX_ao_map":
          parameters.aoMap = scope.getTexture(textureMap, child.ID);
          break;
        case "DiffuseColor":
        case "Maya|TEX_color_map":
          parameters.map = scope.getTexture(textureMap, child.ID);
          if (parameters.map !== void 0) {
            parameters.map.colorSpace = SRGBColorSpace;
          }
          break;
        case "DisplacementColor":
          parameters.displacementMap = scope.getTexture(textureMap, child.ID);
          break;
        case "EmissiveColor":
          parameters.emissiveMap = scope.getTexture(textureMap, child.ID);
          if (parameters.emissiveMap !== void 0) {
            parameters.emissiveMap.colorSpace = SRGBColorSpace;
          }
          break;
        case "NormalMap":
        case "Maya|TEX_normal_map":
          parameters.normalMap = scope.getTexture(textureMap, child.ID);
          break;
        case "ReflectionColor":
          parameters.envMap = scope.getTexture(textureMap, child.ID);
          if (parameters.envMap !== void 0) {
            parameters.envMap.mapping = EquirectangularReflectionMapping;
            parameters.envMap.colorSpace = SRGBColorSpace;
          }
          break;
        case "SpecularColor":
          parameters.specularMap = scope.getTexture(textureMap, child.ID);
          if (parameters.specularMap !== void 0) {
            parameters.specularMap.colorSpace = SRGBColorSpace;
          }
          break;
        case "TransparentColor":
        case "TransparencyFactor":
          parameters.alphaMap = scope.getTexture(textureMap, child.ID);
          parameters.transparent = true;
          break;
        case "AmbientColor":
        case "ShininessExponent":
        // AKA glossiness map
        case "SpecularFactor":
        // AKA specularLevel
        case "VectorDisplacementColor":
        // NOTE: Seems to be a copy of DisplacementColor
        default:
          console.warn("THREE.FBXLoader: %s map is not supported in three.js, skipping texture.", type);
          break;
      }
    });
    return parameters;
  }
  // get a texture from the textureMap for use by a material.
  getTexture(textureMap, id) {
    if ("LayeredTexture" in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture) {
      console.warn("THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.");
      id = connections.get(id).children[0].ID;
    }
    return textureMap.get(id);
  }
  // Parse nodes in FBXTree.Objects.Deformer
  // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  parseDeformers() {
    const skeletons = {};
    const morphTargets = {};
    if ("Deformer" in fbxTree.Objects) {
      const DeformerNodes = fbxTree.Objects.Deformer;
      for (const nodeID in DeformerNodes) {
        const deformerNode = DeformerNodes[nodeID];
        const relationships = connections.get(parseInt(nodeID));
        if (deformerNode.attrType === "Skin") {
          const skeleton = this.parseSkeleton(relationships, DeformerNodes);
          skeleton.ID = nodeID;
          if (relationships.parents.length > 1) console.warn("THREE.FBXLoader: skeleton attached to more than one geometry is not supported.");
          skeleton.geometryID = relationships.parents[0].ID;
          skeletons[nodeID] = skeleton;
        } else if (deformerNode.attrType === "BlendShape") {
          const morphTarget = {
            id: nodeID
          };
          morphTarget.rawTargets = this.parseMorphTargets(relationships, DeformerNodes);
          morphTarget.id = nodeID;
          if (relationships.parents.length > 1) console.warn("THREE.FBXLoader: morph target attached to more than one geometry is not supported.");
          morphTargets[nodeID] = morphTarget;
        }
      }
    }
    return {
      skeletons,
      morphTargets
    };
  }
  // Parse single nodes in FBXTree.Objects.Deformer
  // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  // Each skin node represents a skeleton and each cluster node represents a bone
  parseSkeleton(relationships, deformerNodes) {
    const rawBones = [];
    relationships.children.forEach(function(child) {
      const boneNode = deformerNodes[child.ID];
      if (boneNode.attrType !== "Cluster") return;
      const rawBone = {
        ID: child.ID,
        indices: [],
        weights: [],
        transformLink: new Matrix4().fromArray(boneNode.TransformLink.a)
        // transform: new Matrix4().fromArray( boneNode.Transform.a ),
        // linkMode: boneNode.Mode,
      };
      if ("Indexes" in boneNode) {
        rawBone.indices = boneNode.Indexes.a;
        rawBone.weights = boneNode.Weights.a;
      }
      rawBones.push(rawBone);
    });
    return {
      rawBones,
      bones: []
    };
  }
  // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  parseMorphTargets(relationships, deformerNodes) {
    const rawMorphTargets = [];
    for (let i = 0; i < relationships.children.length; i++) {
      const child = relationships.children[i];
      const morphTargetNode = deformerNodes[child.ID];
      const rawMorphTarget = {
        name: morphTargetNode.attrName,
        initialWeight: morphTargetNode.DeformPercent,
        id: morphTargetNode.id,
        fullWeights: morphTargetNode.FullWeights.a
      };
      if (morphTargetNode.attrType !== "BlendShapeChannel") return;
      rawMorphTarget.geoID = connections.get(parseInt(child.ID)).children.filter(function(child2) {
        return child2.relationship === void 0;
      })[0].ID;
      rawMorphTargets.push(rawMorphTarget);
    }
    return rawMorphTargets;
  }
  // create the main Group() to be returned by the loader
  parseScene(deformers, geometryMap, materialMap) {
    sceneGraph = new Group();
    const modelMap = this.parseModels(deformers.skeletons, geometryMap, materialMap);
    const modelNodes = fbxTree.Objects.Model;
    const scope = this;
    modelMap.forEach(function(model) {
      const modelNode = modelNodes[model.ID];
      scope.setLookAtProperties(model, modelNode);
      const parentConnections = connections.get(model.ID).parents;
      parentConnections.forEach(function(connection) {
        const parent2 = modelMap.get(connection.ID);
        if (parent2 !== void 0) parent2.add(model);
      });
      if (model.parent === null) {
        sceneGraph.add(model);
      }
    });
    this.bindSkeleton(deformers.skeletons, geometryMap, modelMap);
    this.addGlobalSceneSettings();
    sceneGraph.traverse(function(node) {
      if (node.userData.transformData) {
        if (node.parent) {
          node.userData.transformData.parentMatrix = node.parent.matrix;
          node.userData.transformData.parentMatrixWorld = node.parent.matrixWorld;
        }
        const transform2 = generateTransform(node.userData.transformData);
        node.applyMatrix4(transform2);
        node.updateWorldMatrix();
      }
    });
    const animations = new AnimationParser().parse();
    if (sceneGraph.children.length === 1 && sceneGraph.children[0].isGroup) {
      sceneGraph.children[0].animations = animations;
      sceneGraph = sceneGraph.children[0];
    }
    sceneGraph.animations = animations;
  }
  // parse nodes in FBXTree.Objects.Model
  parseModels(skeletons, geometryMap, materialMap) {
    const modelMap = /* @__PURE__ */ new Map();
    const modelNodes = fbxTree.Objects.Model;
    for (const nodeID in modelNodes) {
      const id = parseInt(nodeID);
      const node = modelNodes[nodeID];
      const relationships = connections.get(id);
      let model = this.buildSkeleton(relationships, skeletons, id, node.attrName);
      if (!model) {
        switch (node.attrType) {
          case "Camera":
            model = this.createCamera(relationships);
            break;
          case "Light":
            model = this.createLight(relationships);
            break;
          case "Mesh":
            model = this.createMesh(relationships, geometryMap, materialMap);
            break;
          case "NurbsCurve":
            model = this.createCurve(relationships, geometryMap);
            break;
          case "LimbNode":
          case "Root":
            model = new Bone();
            break;
          case "Null":
          default:
            model = new Group();
            break;
        }
        model.name = node.attrName ? PropertyBinding.sanitizeNodeName(node.attrName) : "";
        model.userData.originalName = node.attrName;
        model.ID = id;
      }
      this.getTransformData(model, node);
      modelMap.set(id, model);
    }
    return modelMap;
  }
  buildSkeleton(relationships, skeletons, id, name2) {
    let bone = null;
    relationships.parents.forEach(function(parent2) {
      for (const ID in skeletons) {
        const skeleton = skeletons[ID];
        skeleton.rawBones.forEach(function(rawBone, i) {
          if (rawBone.ID === parent2.ID) {
            const subBone = bone;
            bone = new Bone();
            bone.matrixWorld.copy(rawBone.transformLink);
            bone.name = name2 ? PropertyBinding.sanitizeNodeName(name2) : "";
            bone.userData.originalName = name2;
            bone.ID = id;
            skeleton.bones[i] = bone;
            if (subBone !== null) {
              bone.add(subBone);
            }
          }
        });
      }
    });
    return bone;
  }
  // create a PerspectiveCamera or OrthographicCamera
  createCamera(relationships) {
    let model;
    let cameraAttribute;
    relationships.children.forEach(function(child) {
      const attr = fbxTree.Objects.NodeAttribute[child.ID];
      if (attr !== void 0) {
        cameraAttribute = attr;
      }
    });
    if (cameraAttribute === void 0) {
      model = new Object3D();
    } else {
      let type = 0;
      if (cameraAttribute.CameraProjectionType !== void 0 && cameraAttribute.CameraProjectionType.value === 1) {
        type = 1;
      }
      let nearClippingPlane = 1;
      if (cameraAttribute.NearPlane !== void 0) {
        nearClippingPlane = cameraAttribute.NearPlane.value / 1e3;
      }
      let farClippingPlane = 1e3;
      if (cameraAttribute.FarPlane !== void 0) {
        farClippingPlane = cameraAttribute.FarPlane.value / 1e3;
      }
      let width2 = window.innerWidth;
      let height2 = window.innerHeight;
      if (cameraAttribute.AspectWidth !== void 0 && cameraAttribute.AspectHeight !== void 0) {
        width2 = cameraAttribute.AspectWidth.value;
        height2 = cameraAttribute.AspectHeight.value;
      }
      const aspect = width2 / height2;
      let fov = 45;
      if (cameraAttribute.FieldOfView !== void 0) {
        fov = cameraAttribute.FieldOfView.value;
      }
      const focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
      switch (type) {
        case 0:
          model = new PerspectiveCamera(fov, aspect, nearClippingPlane, farClippingPlane);
          if (focalLength !== null) model.setFocalLength(focalLength);
          break;
        case 1:
          console.warn("THREE.FBXLoader: Orthographic cameras not supported yet.");
          model = new Object3D();
          break;
        default:
          console.warn("THREE.FBXLoader: Unknown camera type " + type + ".");
          model = new Object3D();
          break;
      }
    }
    return model;
  }
  // Create a DirectionalLight, PointLight or SpotLight
  createLight(relationships) {
    let model;
    let lightAttribute;
    relationships.children.forEach(function(child) {
      const attr = fbxTree.Objects.NodeAttribute[child.ID];
      if (attr !== void 0) {
        lightAttribute = attr;
      }
    });
    if (lightAttribute === void 0) {
      model = new Object3D();
    } else {
      let type;
      if (lightAttribute.LightType === void 0) {
        type = 0;
      } else {
        type = lightAttribute.LightType.value;
      }
      let color = 16777215;
      if (lightAttribute.Color !== void 0) {
        color = ColorManagement.colorSpaceToWorking(new Color().fromArray(lightAttribute.Color.value), SRGBColorSpace);
      }
      let intensity = lightAttribute.Intensity === void 0 ? 1 : lightAttribute.Intensity.value / 100;
      if (lightAttribute.CastLightOnObject !== void 0 && lightAttribute.CastLightOnObject.value === 0) {
        intensity = 0;
      }
      let distance = 0;
      if (lightAttribute.FarAttenuationEnd !== void 0) {
        if (lightAttribute.EnableFarAttenuation !== void 0 && lightAttribute.EnableFarAttenuation.value === 0) {
          distance = 0;
        } else {
          distance = lightAttribute.FarAttenuationEnd.value;
        }
      }
      const decay = 1;
      switch (type) {
        case 0:
          model = new PointLight(color, intensity, distance, decay);
          break;
        case 1:
          model = new DirectionalLight(color, intensity);
          break;
        case 2:
          let angle = Math.PI / 3;
          if (lightAttribute.InnerAngle !== void 0) {
            angle = MathUtils.degToRad(lightAttribute.InnerAngle.value);
          }
          let penumbra = 0;
          if (lightAttribute.OuterAngle !== void 0) {
            penumbra = MathUtils.degToRad(lightAttribute.OuterAngle.value);
            penumbra = Math.max(penumbra, 1);
          }
          model = new SpotLight(color, intensity, distance, angle, penumbra, decay);
          break;
        default:
          console.warn("THREE.FBXLoader: Unknown light type " + lightAttribute.LightType.value + ", defaulting to a PointLight.");
          model = new PointLight(color, intensity);
          break;
      }
      if (lightAttribute.CastShadows !== void 0 && lightAttribute.CastShadows.value === 1) {
        model.castShadow = true;
      }
    }
    return model;
  }
  createMesh(relationships, geometryMap, materialMap) {
    let model;
    let geometry = null;
    let material = null;
    const materials = [];
    relationships.children.forEach(function(child) {
      if (geometryMap.has(child.ID)) {
        geometry = geometryMap.get(child.ID);
      }
      if (materialMap.has(child.ID)) {
        materials.push(materialMap.get(child.ID));
      }
    });
    if (materials.length > 1) {
      material = materials;
    } else if (materials.length > 0) {
      material = materials[0];
    } else {
      material = new MeshPhongMaterial({
        name: Loader.DEFAULT_MATERIAL_NAME,
        color: 13421772
      });
      materials.push(material);
    }
    if ("color" in geometry.attributes) {
      materials.forEach(function(material2) {
        material2.vertexColors = true;
      });
    }
    if (geometry.groups.length > 0) {
      let needsDefaultMaterial = false;
      for (let i = 0, il = geometry.groups.length; i < il; i++) {
        const group = geometry.groups[i];
        if (group.materialIndex < 0 || group.materialIndex >= materials.length) {
          group.materialIndex = materials.length;
          needsDefaultMaterial = true;
        }
      }
      if (needsDefaultMaterial) {
        const defaultMaterial = new MeshPhongMaterial();
        materials.push(defaultMaterial);
      }
    }
    if (geometry.FBX_Deformer) {
      model = new SkinnedMesh(geometry, material);
      model.normalizeSkinWeights();
    } else {
      model = new Mesh(geometry, material);
    }
    return model;
  }
  createCurve(relationships, geometryMap) {
    const geometry = relationships.children.reduce(function(geo, child) {
      if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID);
      return geo;
    }, null);
    const material = new LineBasicMaterial({
      name: Loader.DEFAULT_MATERIAL_NAME,
      color: 3342591,
      linewidth: 1
    });
    return new Line(geometry, material);
  }
  // parse the model node for transform data
  getTransformData(model, modelNode) {
    const transformData = {};
    if ("InheritType" in modelNode) transformData.inheritType = parseInt(modelNode.InheritType.value);
    if ("RotationOrder" in modelNode) transformData.eulerOrder = getEulerOrder(modelNode.RotationOrder.value);
    else transformData.eulerOrder = getEulerOrder(0);
    if ("Lcl_Translation" in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
    if ("PreRotation" in modelNode) transformData.preRotation = modelNode.PreRotation.value;
    if ("Lcl_Rotation" in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
    if ("PostRotation" in modelNode) transformData.postRotation = modelNode.PostRotation.value;
    if ("Lcl_Scaling" in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
    if ("ScalingOffset" in modelNode) transformData.scalingOffset = modelNode.ScalingOffset.value;
    if ("ScalingPivot" in modelNode) transformData.scalingPivot = modelNode.ScalingPivot.value;
    if ("RotationOffset" in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
    if ("RotationPivot" in modelNode) transformData.rotationPivot = modelNode.RotationPivot.value;
    model.userData.transformData = transformData;
  }
  setLookAtProperties(model, modelNode) {
    if ("LookAtProperty" in modelNode) {
      const children = connections.get(model.ID).children;
      children.forEach(function(child) {
        if (child.relationship === "LookAtProperty") {
          const lookAtTarget = fbxTree.Objects.Model[child.ID];
          if ("Lcl_Translation" in lookAtTarget) {
            const pos = lookAtTarget.Lcl_Translation.value;
            if (model.target !== void 0) {
              model.target.position.fromArray(pos);
              sceneGraph.add(model.target);
            } else {
              model.lookAt(new Vector3().fromArray(pos));
            }
          }
        }
      });
    }
  }
  bindSkeleton(skeletons, geometryMap, modelMap) {
    const bindMatrices = this.parsePoseNodes();
    for (const ID in skeletons) {
      const skeleton = skeletons[ID];
      const parents = connections.get(parseInt(skeleton.ID)).parents;
      parents.forEach(function(parent2) {
        if (geometryMap.has(parent2.ID)) {
          const geoID = parent2.ID;
          const geoRelationships = connections.get(geoID);
          geoRelationships.parents.forEach(function(geoConnParent) {
            if (modelMap.has(geoConnParent.ID)) {
              const model = modelMap.get(geoConnParent.ID);
              model.bind(new Skeleton(skeleton.bones), bindMatrices[geoConnParent.ID]);
            }
          });
        }
      });
    }
  }
  parsePoseNodes() {
    const bindMatrices = {};
    if ("Pose" in fbxTree.Objects) {
      const BindPoseNode = fbxTree.Objects.Pose;
      for (const nodeID in BindPoseNode) {
        if (BindPoseNode[nodeID].attrType === "BindPose" && BindPoseNode[nodeID].NbPoseNodes > 0) {
          const poseNodes = BindPoseNode[nodeID].PoseNode;
          if (Array.isArray(poseNodes)) {
            poseNodes.forEach(function(poseNode) {
              bindMatrices[poseNode.Node] = new Matrix4().fromArray(poseNode.Matrix.a);
            });
          } else {
            bindMatrices[poseNodes.Node] = new Matrix4().fromArray(poseNodes.Matrix.a);
          }
        }
      }
    }
    return bindMatrices;
  }
  addGlobalSceneSettings() {
    if ("GlobalSettings" in fbxTree) {
      if ("AmbientColor" in fbxTree.GlobalSettings) {
        const ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
        const r = ambientColor[0];
        const g3 = ambientColor[1];
        const b3 = ambientColor[2];
        if (r !== 0 || g3 !== 0 || b3 !== 0) {
          const color = new Color().setRGB(r, g3, b3, SRGBColorSpace);
          sceneGraph.add(new AmbientLight(color, 1));
        }
      }
      if ("UnitScaleFactor" in fbxTree.GlobalSettings) {
        sceneGraph.userData.unitScaleFactor = fbxTree.GlobalSettings.UnitScaleFactor.value;
      }
    }
  }
};
var GeometryParser = class {
  constructor() {
    this.negativeMaterialIndices = false;
  }
  // Parse nodes in FBXTree.Objects.Geometry
  parse(deformers) {
    const geometryMap = /* @__PURE__ */ new Map();
    if ("Geometry" in fbxTree.Objects) {
      const geoNodes = fbxTree.Objects.Geometry;
      for (const nodeID in geoNodes) {
        const relationships = connections.get(parseInt(nodeID));
        const geo = this.parseGeometry(relationships, geoNodes[nodeID], deformers);
        geometryMap.set(parseInt(nodeID), geo);
      }
    }
    if (this.negativeMaterialIndices === true) {
      console.warn("THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected.");
    }
    return geometryMap;
  }
  // Parse single node in FBXTree.Objects.Geometry
  parseGeometry(relationships, geoNode, deformers) {
    switch (geoNode.attrType) {
      case "Mesh":
        return this.parseMeshGeometry(relationships, geoNode, deformers);
        break;
      case "NurbsCurve":
        return this.parseNurbsGeometry(geoNode);
        break;
    }
  }
  // Parse single node mesh geometry in FBXTree.Objects.Geometry
  parseMeshGeometry(relationships, geoNode, deformers) {
    const skeletons = deformers.skeletons;
    const morphTargets = [];
    const modelNodes = relationships.parents.map(function(parent2) {
      return fbxTree.Objects.Model[parent2.ID];
    });
    if (modelNodes.length === 0) return;
    const skeleton = relationships.children.reduce(function(skeleton2, child) {
      if (skeletons[child.ID] !== void 0) skeleton2 = skeletons[child.ID];
      return skeleton2;
    }, null);
    relationships.children.forEach(function(child) {
      if (deformers.morphTargets[child.ID] !== void 0) {
        morphTargets.push(deformers.morphTargets[child.ID]);
      }
    });
    const modelNode = modelNodes[0];
    const transformData = {};
    if ("RotationOrder" in modelNode) transformData.eulerOrder = getEulerOrder(modelNode.RotationOrder.value);
    if ("InheritType" in modelNode) transformData.inheritType = parseInt(modelNode.InheritType.value);
    if ("GeometricTranslation" in modelNode) transformData.translation = modelNode.GeometricTranslation.value;
    if ("GeometricRotation" in modelNode) transformData.rotation = modelNode.GeometricRotation.value;
    if ("GeometricScaling" in modelNode) transformData.scale = modelNode.GeometricScaling.value;
    const transform2 = generateTransform(transformData);
    return this.genGeometry(geoNode, skeleton, morphTargets, transform2);
  }
  // Generate a BufferGeometry from a node in FBXTree.Objects.Geometry
  genGeometry(geoNode, skeleton, morphTargets, preTransform) {
    const geo = new BufferGeometry();
    if (geoNode.attrName) geo.name = geoNode.attrName;
    const geoInfo = this.parseGeoNode(geoNode, skeleton);
    const buffers = this.genBuffers(geoInfo);
    const positionAttribute = new Float32BufferAttribute(buffers.vertex, 3);
    positionAttribute.applyMatrix4(preTransform);
    geo.setAttribute("position", positionAttribute);
    if (buffers.colors.length > 0) {
      geo.setAttribute("color", new Float32BufferAttribute(buffers.colors, 3));
    }
    if (skeleton) {
      geo.setAttribute("skinIndex", new Uint16BufferAttribute(buffers.weightsIndices, 4));
      geo.setAttribute("skinWeight", new Float32BufferAttribute(buffers.vertexWeights, 4));
      geo.FBX_Deformer = skeleton;
    }
    if (buffers.normal.length > 0) {
      const normalMatrix = new Matrix3().getNormalMatrix(preTransform);
      const normalAttribute = new Float32BufferAttribute(buffers.normal, 3);
      normalAttribute.applyNormalMatrix(normalMatrix);
      geo.setAttribute("normal", normalAttribute);
    }
    buffers.uvs.forEach(function(uvBuffer, i) {
      const name2 = i === 0 ? "uv" : `uv${i}`;
      geo.setAttribute(name2, new Float32BufferAttribute(buffers.uvs[i], 2));
    });
    if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") {
      let prevMaterialIndex = buffers.materialIndex[0];
      let startIndex = 0;
      buffers.materialIndex.forEach(function(currentIndex, i) {
        if (currentIndex !== prevMaterialIndex) {
          geo.addGroup(startIndex, i - startIndex, prevMaterialIndex);
          prevMaterialIndex = currentIndex;
          startIndex = i;
        }
      });
      if (geo.groups.length > 0) {
        const lastGroup = geo.groups[geo.groups.length - 1];
        const lastIndex = lastGroup.start + lastGroup.count;
        if (lastIndex !== buffers.materialIndex.length) {
          geo.addGroup(lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex);
        }
      }
      if (geo.groups.length === 0) {
        geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]);
      }
    }
    this.addMorphTargets(geo, geoNode, morphTargets, preTransform);
    return geo;
  }
  parseGeoNode(geoNode, skeleton) {
    const geoInfo = {};
    geoInfo.vertexPositions = geoNode.Vertices !== void 0 ? geoNode.Vertices.a : [];
    geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== void 0 ? geoNode.PolygonVertexIndex.a : [];
    if (geoNode.LayerElementColor && geoNode.LayerElementColor.Color) {
      geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]);
    }
    if (geoNode.LayerElementMaterial) {
      geoInfo.material = this.parseMaterialIndices(geoNode.LayerElementMaterial[0]);
    }
    if (geoNode.LayerElementNormal) {
      geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]);
    }
    if (geoNode.LayerElementUV) {
      geoInfo.uv = [];
      let i = 0;
      while (geoNode.LayerElementUV[i]) {
        if (geoNode.LayerElementUV[i].UV) {
          geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i]));
        }
        i++;
      }
    }
    geoInfo.weightTable = {};
    if (skeleton !== null) {
      geoInfo.skeleton = skeleton;
      skeleton.rawBones.forEach(function(rawBone, i) {
        rawBone.indices.forEach(function(index2, j2) {
          if (geoInfo.weightTable[index2] === void 0) geoInfo.weightTable[index2] = [];
          geoInfo.weightTable[index2].push({
            id: i,
            weight: rawBone.weights[j2]
          });
        });
      });
    }
    return geoInfo;
  }
  genBuffers(geoInfo) {
    const buffers = {
      vertex: [],
      normal: [],
      colors: [],
      uvs: [],
      materialIndex: [],
      vertexWeights: [],
      weightsIndices: []
    };
    let polygonIndex = 0;
    let faceLength = 0;
    let displayedWeightsWarning = false;
    let facePositionIndexes = [];
    let faceNormals = [];
    let faceColors = [];
    let faceUVs = [];
    let faceWeights = [];
    let faceWeightIndices = [];
    const scope = this;
    geoInfo.vertexIndices.forEach(function(vertexIndex, polygonVertexIndex) {
      let materialIndex;
      let endOfFace = false;
      if (vertexIndex < 0) {
        vertexIndex = vertexIndex ^ -1;
        endOfFace = true;
      }
      let weightIndices = [];
      let weights = [];
      facePositionIndexes.push(vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2);
      if (geoInfo.color) {
        const data2 = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color);
        faceColors.push(data2[0], data2[1], data2[2]);
      }
      if (geoInfo.skeleton) {
        if (geoInfo.weightTable[vertexIndex] !== void 0) {
          geoInfo.weightTable[vertexIndex].forEach(function(wt2) {
            weights.push(wt2.weight);
            weightIndices.push(wt2.id);
          });
        }
        if (weights.length > 4) {
          if (!displayedWeightsWarning) {
            console.warn("THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.");
            displayedWeightsWarning = true;
          }
          const wIndex = [0, 0, 0, 0];
          const Weight = [0, 0, 0, 0];
          weights.forEach(function(weight, weightIndex) {
            let currentWeight = weight;
            let currentIndex = weightIndices[weightIndex];
            Weight.forEach(function(comparedWeight, comparedWeightIndex, comparedWeightArray) {
              if (currentWeight > comparedWeight) {
                comparedWeightArray[comparedWeightIndex] = currentWeight;
                currentWeight = comparedWeight;
                const tmp = wIndex[comparedWeightIndex];
                wIndex[comparedWeightIndex] = currentIndex;
                currentIndex = tmp;
              }
            });
          });
          weightIndices = wIndex;
          weights = Weight;
        }
        while (weights.length < 4) {
          weights.push(0);
          weightIndices.push(0);
        }
        for (let i = 0; i < 4; ++i) {
          faceWeights.push(weights[i]);
          faceWeightIndices.push(weightIndices[i]);
        }
      }
      if (geoInfo.normal) {
        const data2 = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal);
        faceNormals.push(data2[0], data2[1], data2[2]);
      }
      if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") {
        materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material)[0];
        if (materialIndex < 0) {
          scope.negativeMaterialIndices = true;
          materialIndex = 0;
        }
      }
      if (geoInfo.uv) {
        geoInfo.uv.forEach(function(uv, i) {
          const data2 = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv);
          if (faceUVs[i] === void 0) {
            faceUVs[i] = [];
          }
          faceUVs[i].push(data2[0]);
          faceUVs[i].push(data2[1]);
        });
      }
      faceLength++;
      if (endOfFace) {
        scope.genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength);
        polygonIndex++;
        faceLength = 0;
        facePositionIndexes = [];
        faceNormals = [];
        faceColors = [];
        faceUVs = [];
        faceWeights = [];
        faceWeightIndices = [];
      }
    });
    return buffers;
  }
  // See https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal
  getNormalNewell(vertices) {
    const normal = new Vector3(0, 0, 0);
    for (let i = 0; i < vertices.length; i++) {
      const current = vertices[i];
      const next = vertices[(i + 1) % vertices.length];
      normal.x += (current.y - next.y) * (current.z + next.z);
      normal.y += (current.z - next.z) * (current.x + next.x);
      normal.z += (current.x - next.x) * (current.y + next.y);
    }
    normal.normalize();
    return normal;
  }
  getNormalTangentAndBitangent(vertices) {
    const normalVector = this.getNormalNewell(vertices);
    const up = Math.abs(normalVector.z) > 0.5 ? new Vector3(0, 1, 0) : new Vector3(0, 0, 1);
    const tangent = up.cross(normalVector).normalize();
    const bitangent = normalVector.clone().cross(tangent).normalize();
    return {
      normal: normalVector,
      tangent,
      bitangent
    };
  }
  flattenVertex(vertex, normalTangent, normalBitangent) {
    return new Vector2(
      vertex.dot(normalTangent),
      vertex.dot(normalBitangent)
    );
  }
  // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength) {
    let triangles;
    if (faceLength > 3) {
      const vertices = [];
      const positions = geoInfo.baseVertexPositions || geoInfo.vertexPositions;
      for (let i = 0; i < facePositionIndexes.length; i += 3) {
        vertices.push(
          new Vector3(
            positions[facePositionIndexes[i]],
            positions[facePositionIndexes[i + 1]],
            positions[facePositionIndexes[i + 2]]
          )
        );
      }
      const { tangent, bitangent } = this.getNormalTangentAndBitangent(vertices);
      const triangulationInput = [];
      for (const vertex of vertices) {
        triangulationInput.push(this.flattenVertex(vertex, tangent, bitangent));
      }
      triangles = ShapeUtils.triangulateShape(triangulationInput, []);
    } else {
      triangles = [[0, 1, 2]];
    }
    for (const [i0, i1, i2] of triangles) {
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i0 * 3]]);
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i0 * 3 + 1]]);
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i0 * 3 + 2]]);
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i1 * 3]]);
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i1 * 3 + 1]]);
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i1 * 3 + 2]]);
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i2 * 3]]);
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i2 * 3 + 1]]);
      buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i2 * 3 + 2]]);
      if (geoInfo.skeleton) {
        buffers.vertexWeights.push(faceWeights[i0 * 4]);
        buffers.vertexWeights.push(faceWeights[i0 * 4 + 1]);
        buffers.vertexWeights.push(faceWeights[i0 * 4 + 2]);
        buffers.vertexWeights.push(faceWeights[i0 * 4 + 3]);
        buffers.vertexWeights.push(faceWeights[i1 * 4]);
        buffers.vertexWeights.push(faceWeights[i1 * 4 + 1]);
        buffers.vertexWeights.push(faceWeights[i1 * 4 + 2]);
        buffers.vertexWeights.push(faceWeights[i1 * 4 + 3]);
        buffers.vertexWeights.push(faceWeights[i2 * 4]);
        buffers.vertexWeights.push(faceWeights[i2 * 4 + 1]);
        buffers.vertexWeights.push(faceWeights[i2 * 4 + 2]);
        buffers.vertexWeights.push(faceWeights[i2 * 4 + 3]);
        buffers.weightsIndices.push(faceWeightIndices[i0 * 4]);
        buffers.weightsIndices.push(faceWeightIndices[i0 * 4 + 1]);
        buffers.weightsIndices.push(faceWeightIndices[i0 * 4 + 2]);
        buffers.weightsIndices.push(faceWeightIndices[i0 * 4 + 3]);
        buffers.weightsIndices.push(faceWeightIndices[i1 * 4]);
        buffers.weightsIndices.push(faceWeightIndices[i1 * 4 + 1]);
        buffers.weightsIndices.push(faceWeightIndices[i1 * 4 + 2]);
        buffers.weightsIndices.push(faceWeightIndices[i1 * 4 + 3]);
        buffers.weightsIndices.push(faceWeightIndices[i2 * 4]);
        buffers.weightsIndices.push(faceWeightIndices[i2 * 4 + 1]);
        buffers.weightsIndices.push(faceWeightIndices[i2 * 4 + 2]);
        buffers.weightsIndices.push(faceWeightIndices[i2 * 4 + 3]);
      }
      if (geoInfo.color) {
        buffers.colors.push(faceColors[i0 * 3]);
        buffers.colors.push(faceColors[i0 * 3 + 1]);
        buffers.colors.push(faceColors[i0 * 3 + 2]);
        buffers.colors.push(faceColors[i1 * 3]);
        buffers.colors.push(faceColors[i1 * 3 + 1]);
        buffers.colors.push(faceColors[i1 * 3 + 2]);
        buffers.colors.push(faceColors[i2 * 3]);
        buffers.colors.push(faceColors[i2 * 3 + 1]);
        buffers.colors.push(faceColors[i2 * 3 + 2]);
      }
      if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") {
        buffers.materialIndex.push(materialIndex);
        buffers.materialIndex.push(materialIndex);
        buffers.materialIndex.push(materialIndex);
      }
      if (geoInfo.normal) {
        buffers.normal.push(faceNormals[i0 * 3]);
        buffers.normal.push(faceNormals[i0 * 3 + 1]);
        buffers.normal.push(faceNormals[i0 * 3 + 2]);
        buffers.normal.push(faceNormals[i1 * 3]);
        buffers.normal.push(faceNormals[i1 * 3 + 1]);
        buffers.normal.push(faceNormals[i1 * 3 + 2]);
        buffers.normal.push(faceNormals[i2 * 3]);
        buffers.normal.push(faceNormals[i2 * 3 + 1]);
        buffers.normal.push(faceNormals[i2 * 3 + 2]);
      }
      if (geoInfo.uv) {
        geoInfo.uv.forEach(function(uv, j2) {
          if (buffers.uvs[j2] === void 0) buffers.uvs[j2] = [];
          buffers.uvs[j2].push(faceUVs[j2][i0 * 2]);
          buffers.uvs[j2].push(faceUVs[j2][i0 * 2 + 1]);
          buffers.uvs[j2].push(faceUVs[j2][i1 * 2]);
          buffers.uvs[j2].push(faceUVs[j2][i1 * 2 + 1]);
          buffers.uvs[j2].push(faceUVs[j2][i2 * 2]);
          buffers.uvs[j2].push(faceUVs[j2][i2 * 2 + 1]);
        });
      }
    }
  }
  addMorphTargets(parentGeo, parentGeoNode, morphTargets, preTransform) {
    if (morphTargets.length === 0) return;
    parentGeo.morphTargetsRelative = true;
    parentGeo.morphAttributes.position = [];
    const scope = this;
    morphTargets.forEach(function(morphTarget) {
      morphTarget.rawTargets.forEach(function(rawTarget) {
        const morphGeoNode = fbxTree.Objects.Geometry[rawTarget.geoID];
        if (morphGeoNode !== void 0) {
          scope.genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform, rawTarget.name);
        }
      });
    });
  }
  // a morph geometry node is similar to a standard  node, and the node is also contained
  // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  // and a special attribute Index defining which vertices of the original geometry are affected
  // Normal and position attributes only have data for the vertices that are affected by the morph
  genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform, name2) {
    const basePositions = parentGeoNode.Vertices !== void 0 ? parentGeoNode.Vertices.a : [];
    const baseIndices = parentGeoNode.PolygonVertexIndex !== void 0 ? parentGeoNode.PolygonVertexIndex.a : [];
    const morphPositionsSparse = morphGeoNode.Vertices !== void 0 ? morphGeoNode.Vertices.a : [];
    const morphIndices = morphGeoNode.Indexes !== void 0 ? morphGeoNode.Indexes.a : [];
    const length2 = parentGeo.attributes.position.count * 3;
    const morphPositions = new Float32Array(length2);
    for (let i = 0; i < morphIndices.length; i++) {
      const morphIndex = morphIndices[i] * 3;
      morphPositions[morphIndex] = morphPositionsSparse[i * 3];
      morphPositions[morphIndex + 1] = morphPositionsSparse[i * 3 + 1];
      morphPositions[morphIndex + 2] = morphPositionsSparse[i * 3 + 2];
    }
    const morphGeoInfo = {
      vertexIndices: baseIndices,
      vertexPositions: morphPositions,
      baseVertexPositions: basePositions
    };
    const morphBuffers = this.genBuffers(morphGeoInfo);
    const positionAttribute = new Float32BufferAttribute(morphBuffers.vertex, 3);
    positionAttribute.name = name2 || morphGeoNode.attrName;
    positionAttribute.applyMatrix4(preTransform);
    parentGeo.morphAttributes.position.push(positionAttribute);
  }
  // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  parseNormals(NormalNode) {
    const mappingType = NormalNode.MappingInformationType;
    const referenceType = NormalNode.ReferenceInformationType;
    const buffer = NormalNode.Normals.a;
    let indexBuffer = [];
    if (referenceType === "IndexToDirect") {
      if ("NormalIndex" in NormalNode) {
        indexBuffer = NormalNode.NormalIndex.a;
      } else if ("NormalsIndex" in NormalNode) {
        indexBuffer = NormalNode.NormalsIndex.a;
      }
    }
    return {
      dataSize: 3,
      buffer,
      indices: indexBuffer,
      mappingType,
      referenceType
    };
  }
  // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  parseUVs(UVNode) {
    const mappingType = UVNode.MappingInformationType;
    const referenceType = UVNode.ReferenceInformationType;
    const buffer = UVNode.UV.a;
    let indexBuffer = [];
    if (referenceType === "IndexToDirect") {
      indexBuffer = UVNode.UVIndex.a;
    }
    return {
      dataSize: 2,
      buffer,
      indices: indexBuffer,
      mappingType,
      referenceType
    };
  }
  // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  parseVertexColors(ColorNode) {
    const mappingType = ColorNode.MappingInformationType;
    const referenceType = ColorNode.ReferenceInformationType;
    const buffer = ColorNode.Colors.a;
    let indexBuffer = [];
    if (referenceType === "IndexToDirect") {
      indexBuffer = ColorNode.ColorIndex.a;
    }
    for (let i = 0, c2 = new Color(); i < buffer.length; i += 4) {
      c2.fromArray(buffer, i);
      ColorManagement.colorSpaceToWorking(c2, SRGBColorSpace);
      c2.toArray(buffer, i);
    }
    return {
      dataSize: 4,
      buffer,
      indices: indexBuffer,
      mappingType,
      referenceType
    };
  }
  // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  parseMaterialIndices(MaterialNode) {
    const mappingType = MaterialNode.MappingInformationType;
    const referenceType = MaterialNode.ReferenceInformationType;
    if (mappingType === "NoMappingInformation") {
      return {
        dataSize: 1,
        buffer: [0],
        indices: [0],
        mappingType: "AllSame",
        referenceType
      };
    }
    const materialIndexBuffer = MaterialNode.Materials.a;
    const materialIndices = [];
    for (let i = 0; i < materialIndexBuffer.length; ++i) {
      materialIndices.push(i);
    }
    return {
      dataSize: 1,
      buffer: materialIndexBuffer,
      indices: materialIndices,
      mappingType,
      referenceType
    };
  }
  // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  parseNurbsGeometry(geoNode) {
    const order = parseInt(geoNode.Order);
    if (isNaN(order)) {
      console.error("THREE.FBXLoader: Invalid Order %s given for geometry ID: %s", geoNode.Order, geoNode.id);
      return new BufferGeometry();
    }
    const degree = order - 1;
    const knots = geoNode.KnotVector.a;
    const controlPoints = [];
    const pointsValues = geoNode.Points.a;
    for (let i = 0, l2 = pointsValues.length; i < l2; i += 4) {
      controlPoints.push(new Vector4().fromArray(pointsValues, i));
    }
    let startKnot, endKnot;
    if (geoNode.Form === "Closed") {
      controlPoints.push(controlPoints[0]);
    } else if (geoNode.Form === "Periodic") {
      startKnot = degree;
      endKnot = knots.length - 1 - startKnot;
      for (let i = 0; i < degree; ++i) {
        controlPoints.push(controlPoints[i]);
      }
    }
    const curve = new NURBSCurve(degree, knots, controlPoints, startKnot, endKnot);
    const points = curve.getPoints(controlPoints.length * 12);
    return new BufferGeometry().setFromPoints(points);
  }
};
var AnimationParser = class {
  // take raw animation clips and turn them into three.js animation clips
  parse() {
    const animationClips = [];
    const rawClips = this.parseClips();
    if (rawClips !== void 0) {
      for (const key2 in rawClips) {
        const rawClip = rawClips[key2];
        const clip = this.addClip(rawClip);
        animationClips.push(clip);
      }
    }
    return animationClips;
  }
  parseClips() {
    if (fbxTree.Objects.AnimationCurve === void 0) return void 0;
    const curveNodesMap = this.parseAnimationCurveNodes();
    this.parseAnimationCurves(curveNodesMap);
    const layersMap = this.parseAnimationLayers(curveNodesMap);
    const rawClips = this.parseAnimStacks(layersMap);
    return rawClips;
  }
  // parse nodes in FBXTree.Objects.AnimationCurveNode
  // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  // and is referenced by an AnimationLayer
  parseAnimationCurveNodes() {
    const rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
    const curveNodesMap = /* @__PURE__ */ new Map();
    for (const nodeID in rawCurveNodes) {
      const rawCurveNode = rawCurveNodes[nodeID];
      if (rawCurveNode.attrName.match(/S|R|T|DeformPercent/) !== null) {
        const curveNode = {
          id: rawCurveNode.id,
          attr: rawCurveNode.attrName,
          curves: {}
        };
        curveNodesMap.set(curveNode.id, curveNode);
      }
    }
    return curveNodesMap;
  }
  // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  // axis ( e.g. times and values of x rotation)
  parseAnimationCurves(curveNodesMap) {
    const rawCurves = fbxTree.Objects.AnimationCurve;
    for (const nodeID in rawCurves) {
      const animationCurve = {
        id: rawCurves[nodeID].id,
        times: rawCurves[nodeID].KeyTime.a.map(convertFBXTimeToSeconds),
        values: rawCurves[nodeID].KeyValueFloat.a
      };
      const relationships = connections.get(animationCurve.id);
      if (relationships !== void 0) {
        const animationCurveID = relationships.parents[0].ID;
        const animationCurveRelationship = relationships.parents[0].relationship;
        if (animationCurveRelationship.match(/X/)) {
          curveNodesMap.get(animationCurveID).curves["x"] = animationCurve;
        } else if (animationCurveRelationship.match(/Y/)) {
          curveNodesMap.get(animationCurveID).curves["y"] = animationCurve;
        } else if (animationCurveRelationship.match(/Z/)) {
          curveNodesMap.get(animationCurveID).curves["z"] = animationCurve;
        } else if (animationCurveRelationship.match(/DeformPercent/) && curveNodesMap.has(animationCurveID)) {
          curveNodesMap.get(animationCurveID).curves["morph"] = animationCurve;
        }
      }
    }
  }
  // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  // to various AnimationCurveNodes and is referenced by an AnimationStack node
  // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  parseAnimationLayers(curveNodesMap) {
    const rawLayers = fbxTree.Objects.AnimationLayer;
    const layersMap = /* @__PURE__ */ new Map();
    for (const nodeID in rawLayers) {
      const layerCurveNodes = [];
      const connection = connections.get(parseInt(nodeID));
      if (connection !== void 0) {
        const children = connection.children;
        children.forEach(function(child, i) {
          if (curveNodesMap.has(child.ID)) {
            const curveNode = curveNodesMap.get(child.ID);
            if (curveNode.curves.x !== void 0 || curveNode.curves.y !== void 0 || curveNode.curves.z !== void 0) {
              if (layerCurveNodes[i] === void 0) {
                const modelID = connections.get(child.ID).parents.filter(function(parent2) {
                  return parent2.relationship !== void 0;
                })[0].ID;
                if (modelID !== void 0) {
                  const rawModel = fbxTree.Objects.Model[modelID.toString()];
                  if (rawModel === void 0) {
                    console.warn("THREE.FBXLoader: Encountered a unused curve.", child);
                    return;
                  }
                  const node = {
                    modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName(rawModel.attrName) : "",
                    ID: rawModel.id,
                    initialPosition: [0, 0, 0],
                    initialRotation: [0, 0, 0],
                    initialScale: [1, 1, 1]
                  };
                  sceneGraph.traverse(function(child2) {
                    if (child2.ID === rawModel.id) {
                      node.transform = child2.matrix;
                      if (child2.userData.transformData) node.eulerOrder = child2.userData.transformData.eulerOrder;
                    }
                  });
                  if (!node.transform) node.transform = new Matrix4();
                  if ("PreRotation" in rawModel) node.preRotation = rawModel.PreRotation.value;
                  if ("PostRotation" in rawModel) node.postRotation = rawModel.PostRotation.value;
                  layerCurveNodes[i] = node;
                }
              }
              if (layerCurveNodes[i]) layerCurveNodes[i][curveNode.attr] = curveNode;
            } else if (curveNode.curves.morph !== void 0) {
              if (layerCurveNodes[i] === void 0) {
                const deformerID = connections.get(child.ID).parents.filter(function(parent2) {
                  return parent2.relationship !== void 0;
                })[0].ID;
                const morpherID = connections.get(deformerID).parents[0].ID;
                const geoID = connections.get(morpherID).parents[0].ID;
                const modelID = connections.get(geoID).parents[0].ID;
                const rawModel = fbxTree.Objects.Model[modelID];
                const node = {
                  modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName(rawModel.attrName) : "",
                  morphName: fbxTree.Objects.Deformer[deformerID].attrName
                };
                layerCurveNodes[i] = node;
              }
              layerCurveNodes[i][curveNode.attr] = curveNode;
            }
          }
        });
        layersMap.set(parseInt(nodeID), layerCurveNodes);
      }
    }
    return layersMap;
  }
  // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  // hierarchy. Each Stack node will be used to create an AnimationClip
  parseAnimStacks(layersMap) {
    const rawStacks = fbxTree.Objects.AnimationStack;
    const rawClips = {};
    for (const nodeID in rawStacks) {
      const children = connections.get(parseInt(nodeID)).children;
      if (children.length > 1) {
        console.warn("THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.");
      }
      const layer = layersMap.get(children[0].ID);
      rawClips[nodeID] = {
        name: rawStacks[nodeID].attrName,
        layer
      };
    }
    return rawClips;
  }
  addClip(rawClip) {
    let tracks = [];
    const scope = this;
    rawClip.layer.forEach(function(rawTracks) {
      tracks = tracks.concat(scope.generateTracks(rawTracks));
    });
    return new AnimationClip(rawClip.name, -1, tracks);
  }
  generateTracks(rawTracks) {
    const tracks = [];
    let initialPosition = new Vector3();
    let initialScale = new Vector3();
    if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, new Quaternion(), initialScale);
    initialPosition = initialPosition.toArray();
    initialScale = initialScale.toArray();
    if (rawTracks.T !== void 0 && Object.keys(rawTracks.T.curves).length > 0) {
      const positionTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.T.curves, initialPosition, "position");
      if (positionTrack !== void 0) tracks.push(positionTrack);
    }
    if (rawTracks.R !== void 0 && Object.keys(rawTracks.R.curves).length > 0) {
      const rotationTrack = this.generateRotationTrack(rawTracks.modelName, rawTracks.R.curves, rawTracks.preRotation, rawTracks.postRotation, rawTracks.eulerOrder);
      if (rotationTrack !== void 0) tracks.push(rotationTrack);
    }
    if (rawTracks.S !== void 0 && Object.keys(rawTracks.S.curves).length > 0) {
      const scaleTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.S.curves, initialScale, "scale");
      if (scaleTrack !== void 0) tracks.push(scaleTrack);
    }
    if (rawTracks.DeformPercent !== void 0) {
      const morphTrack = this.generateMorphTrack(rawTracks);
      if (morphTrack !== void 0) tracks.push(morphTrack);
    }
    return tracks;
  }
  generateVectorTrack(modelName, curves, initialValue, type) {
    const times = this.getTimesForAllAxes(curves);
    const values2 = this.getKeyframeTrackValues(times, curves, initialValue);
    return new VectorKeyframeTrack(modelName + "." + type, times, values2);
  }
  generateRotationTrack(modelName, curves, preRotation, postRotation, eulerOrder) {
    let times;
    let values2;
    if (curves.x !== void 0 && curves.y !== void 0 && curves.z !== void 0) {
      const result = this.interpolateRotations(curves.x, curves.y, curves.z, eulerOrder);
      times = result[0];
      values2 = result[1];
    }
    const defaultEulerOrder = getEulerOrder(0);
    if (preRotation !== void 0) {
      preRotation = preRotation.map(MathUtils.degToRad);
      preRotation.push(defaultEulerOrder);
      preRotation = new Euler().fromArray(preRotation);
      preRotation = new Quaternion().setFromEuler(preRotation);
    }
    if (postRotation !== void 0) {
      postRotation = postRotation.map(MathUtils.degToRad);
      postRotation.push(defaultEulerOrder);
      postRotation = new Euler().fromArray(postRotation);
      postRotation = new Quaternion().setFromEuler(postRotation).invert();
    }
    const quaternion = new Quaternion();
    const euler = new Euler();
    const quaternionValues = [];
    if (!values2 || !times) return new QuaternionKeyframeTrack(modelName + ".quaternion", [0], [0]);
    for (let i = 0; i < values2.length; i += 3) {
      euler.set(values2[i], values2[i + 1], values2[i + 2], eulerOrder);
      quaternion.setFromEuler(euler);
      if (preRotation !== void 0) quaternion.premultiply(preRotation);
      if (postRotation !== void 0) quaternion.multiply(postRotation);
      if (i > 2) {
        const prevQuat = new Quaternion().fromArray(
          quaternionValues,
          (i - 3) / 3 * 4
        );
        if (prevQuat.dot(quaternion) < 0) {
          quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);
        }
      }
      quaternion.toArray(quaternionValues, i / 3 * 4);
    }
    return new QuaternionKeyframeTrack(modelName + ".quaternion", times, quaternionValues);
  }
  generateMorphTrack(rawTracks) {
    const curves = rawTracks.DeformPercent.curves.morph;
    const values2 = curves.values.map(function(val2) {
      return val2 / 100;
    });
    const morphNum = sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName];
    return new NumberKeyframeTrack(rawTracks.modelName + ".morphTargetInfluences[" + morphNum + "]", curves.times, values2);
  }
  // For all animated objects, times are defined separately for each axis
  // Here we'll combine the times into one sorted array without duplicates
  getTimesForAllAxes(curves) {
    let times = [];
    if (curves.x !== void 0) times = times.concat(curves.x.times);
    if (curves.y !== void 0) times = times.concat(curves.y.times);
    if (curves.z !== void 0) times = times.concat(curves.z.times);
    times = times.sort(function(a2, b3) {
      return a2 - b3;
    });
    if (times.length > 1) {
      let targetIndex = 1;
      let lastValue = times[0];
      for (let i = 1; i < times.length; i++) {
        const currentValue = times[i];
        if (currentValue !== lastValue) {
          times[targetIndex] = currentValue;
          lastValue = currentValue;
          targetIndex++;
        }
      }
      times = times.slice(0, targetIndex);
    }
    return times;
  }
  getKeyframeTrackValues(times, curves, initialValue) {
    const prevValue = initialValue;
    const values2 = [];
    let xIndex = -1;
    let yIndex = -1;
    let zIndex = -1;
    times.forEach(function(time2) {
      if (curves.x) xIndex = curves.x.times.indexOf(time2);
      if (curves.y) yIndex = curves.y.times.indexOf(time2);
      if (curves.z) zIndex = curves.z.times.indexOf(time2);
      if (xIndex !== -1) {
        const xValue = curves.x.values[xIndex];
        values2.push(xValue);
        prevValue[0] = xValue;
      } else {
        values2.push(prevValue[0]);
      }
      if (yIndex !== -1) {
        const yValue = curves.y.values[yIndex];
        values2.push(yValue);
        prevValue[1] = yValue;
      } else {
        values2.push(prevValue[1]);
      }
      if (zIndex !== -1) {
        const zValue = curves.z.values[zIndex];
        values2.push(zValue);
        prevValue[2] = zValue;
      } else {
        values2.push(prevValue[2]);
      }
    });
    return values2;
  }
  // Rotations are defined as Euler angles which can have values  of any size
  // These will be converted to quaternions which don't support values greater than
  // PI, so we'll interpolate large rotations
  interpolateRotations(curvex, curvey, curvez, eulerOrder) {
    const times = [];
    const values2 = [];
    times.push(curvex.times[0]);
    values2.push(MathUtils.degToRad(curvex.values[0]));
    values2.push(MathUtils.degToRad(curvey.values[0]));
    values2.push(MathUtils.degToRad(curvez.values[0]));
    for (let i = 1; i < curvex.values.length; i++) {
      const initialValue = [
        curvex.values[i - 1],
        curvey.values[i - 1],
        curvez.values[i - 1]
      ];
      if (isNaN(initialValue[0]) || isNaN(initialValue[1]) || isNaN(initialValue[2])) {
        continue;
      }
      const initialValueRad = initialValue.map(MathUtils.degToRad);
      const currentValue = [
        curvex.values[i],
        curvey.values[i],
        curvez.values[i]
      ];
      if (isNaN(currentValue[0]) || isNaN(currentValue[1]) || isNaN(currentValue[2])) {
        continue;
      }
      const currentValueRad = currentValue.map(MathUtils.degToRad);
      const valuesSpan = [
        currentValue[0] - initialValue[0],
        currentValue[1] - initialValue[1],
        currentValue[2] - initialValue[2]
      ];
      const absoluteSpan = [
        Math.abs(valuesSpan[0]),
        Math.abs(valuesSpan[1]),
        Math.abs(valuesSpan[2])
      ];
      if (absoluteSpan[0] >= 180 || absoluteSpan[1] >= 180 || absoluteSpan[2] >= 180) {
        const maxAbsSpan = Math.max(...absoluteSpan);
        const numSubIntervals = maxAbsSpan / 180;
        const E1 = new Euler(...initialValueRad, eulerOrder);
        const E2 = new Euler(...currentValueRad, eulerOrder);
        const Q1 = new Quaternion().setFromEuler(E1);
        const Q2 = new Quaternion().setFromEuler(E2);
        if (Q1.dot(Q2)) {
          Q2.set(-Q2.x, -Q2.y, -Q2.z, -Q2.w);
        }
        const initialTime = curvex.times[i - 1];
        const timeSpan = curvex.times[i] - initialTime;
        const Q3 = new Quaternion();
        const E = new Euler();
        for (let t3 = 0; t3 < 1; t3 += 1 / numSubIntervals) {
          Q3.copy(Q1.clone().slerp(Q2.clone(), t3));
          times.push(initialTime + t3 * timeSpan);
          E.setFromQuaternion(Q3, eulerOrder);
          values2.push(E.x);
          values2.push(E.y);
          values2.push(E.z);
        }
      } else {
        times.push(curvex.times[i]);
        values2.push(MathUtils.degToRad(curvex.values[i]));
        values2.push(MathUtils.degToRad(curvey.values[i]));
        values2.push(MathUtils.degToRad(curvez.values[i]));
      }
    }
    return [times, values2];
  }
};
var TextParser = class {
  getPrevNode() {
    return this.nodeStack[this.currentIndent - 2];
  }
  getCurrentNode() {
    return this.nodeStack[this.currentIndent - 1];
  }
  getCurrentProp() {
    return this.currentProp;
  }
  pushStack(node) {
    this.nodeStack.push(node);
    this.currentIndent += 1;
  }
  popStack() {
    this.nodeStack.pop();
    this.currentIndent -= 1;
  }
  setCurrentProp(val2, name2) {
    this.currentProp = val2;
    this.currentPropName = name2;
  }
  parse(text2) {
    this.currentIndent = 0;
    this.allNodes = new FBXTree();
    this.nodeStack = [];
    this.currentProp = [];
    this.currentPropName = "";
    const scope = this;
    const split = text2.split(/[\r\n]+/);
    split.forEach(function(line2, i) {
      const matchComment = line2.match(/^[\s\t]*;/);
      const matchEmpty = line2.match(/^[\s\t]*$/);
      if (matchComment || matchEmpty) return;
      const matchBeginning = line2.match("^\\t{" + scope.currentIndent + "}(\\w+):(.*){", "");
      const matchProperty = line2.match("^\\t{" + scope.currentIndent + "}(\\w+):[\\s\\t\\r\\n](.*)");
      const matchEnd = line2.match("^\\t{" + (scope.currentIndent - 1) + "}}");
      if (matchBeginning) {
        scope.parseNodeBegin(line2, matchBeginning);
      } else if (matchProperty) {
        scope.parseNodeProperty(line2, matchProperty, split[++i]);
      } else if (matchEnd) {
        scope.popStack();
      } else if (line2.match(/^[^\s\t}]/)) {
        scope.parseNodePropertyContinued(line2);
      }
    });
    return this.allNodes;
  }
  parseNodeBegin(line2, property2) {
    const nodeName = property2[1].trim().replace(/^"/, "").replace(/"$/, "");
    const nodeAttrs = property2[2].split(",").map(function(attr) {
      return attr.trim().replace(/^"/, "").replace(/"$/, "");
    });
    const node = { name: nodeName };
    const attrs = this.parseNodeAttr(nodeAttrs);
    const currentNode = this.getCurrentNode();
    if (this.currentIndent === 0) {
      this.allNodes.add(nodeName, node);
    } else {
      if (nodeName in currentNode) {
        if (nodeName === "PoseNode") {
          currentNode.PoseNode.push(node);
        } else if (currentNode[nodeName].id !== void 0) {
          currentNode[nodeName] = {};
          currentNode[nodeName][currentNode[nodeName].id] = currentNode[nodeName];
        }
        if (attrs.id !== "") currentNode[nodeName][attrs.id] = node;
      } else if (typeof attrs.id === "number") {
        currentNode[nodeName] = {};
        currentNode[nodeName][attrs.id] = node;
      } else if (nodeName !== "Properties70") {
        if (nodeName === "PoseNode") currentNode[nodeName] = [node];
        else currentNode[nodeName] = node;
      }
    }
    if (typeof attrs.id === "number") node.id = attrs.id;
    if (attrs.name !== "") node.attrName = attrs.name;
    if (attrs.type !== "") node.attrType = attrs.type;
    this.pushStack(node);
  }
  parseNodeAttr(attrs) {
    let id = attrs[0];
    if (attrs[0] !== "") {
      id = parseInt(attrs[0]);
      if (isNaN(id)) {
        id = attrs[0];
      }
    }
    let name2 = "", type = "";
    if (attrs.length > 1) {
      name2 = attrs[1].replace(/^(\w+)::/, "");
      type = attrs[2];
    }
    return { id, name: name2, type };
  }
  parseNodeProperty(line2, property2, contentLine) {
    let propName = property2[1].replace(/^"/, "").replace(/"$/, "").trim();
    let propValue = property2[2].replace(/^"/, "").replace(/"$/, "").trim();
    if (propName === "Content" && propValue === ",") {
      propValue = contentLine.replace(/"/g, "").replace(/,$/, "").trim();
    }
    const currentNode = this.getCurrentNode();
    const parentName = currentNode.name;
    if (parentName === "Properties70") {
      this.parseNodeSpecialProperty(line2, propName, propValue);
      return;
    }
    if (propName === "C") {
      const connProps = propValue.split(",").slice(1);
      const from = parseInt(connProps[0]);
      const to = parseInt(connProps[1]);
      let rest = propValue.split(",").slice(3);
      rest = rest.map(function(elem2) {
        return elem2.trim().replace(/^"/, "");
      });
      propName = "connections";
      propValue = [from, to];
      append(propValue, rest);
      if (currentNode[propName] === void 0) {
        currentNode[propName] = [];
      }
    }
    if (propName === "Node") currentNode.id = propValue;
    if (propName in currentNode && Array.isArray(currentNode[propName])) {
      currentNode[propName].push(propValue);
    } else {
      if (propName !== "a") currentNode[propName] = propValue;
      else currentNode.a = propValue;
    }
    this.setCurrentProp(currentNode, propName);
    if (propName === "a" && propValue.slice(-1) !== ",") {
      currentNode.a = parseNumberArray(propValue);
    }
  }
  parseNodePropertyContinued(line2) {
    const currentNode = this.getCurrentNode();
    currentNode.a += line2;
    if (line2.slice(-1) !== ",") {
      currentNode.a = parseNumberArray(currentNode.a);
    }
  }
  // parse "Property70"
  parseNodeSpecialProperty(line2, propName, propValue) {
    const props = propValue.split('",').map(function(prop) {
      return prop.trim().replace(/^\"/, "").replace(/\s/, "_");
    });
    const innerPropName = props[0];
    const innerPropType1 = props[1];
    const innerPropType2 = props[2];
    const innerPropFlag = props[3];
    let innerPropValue = props[4];
    switch (innerPropType1) {
      case "int":
      case "enum":
      case "bool":
      case "ULongLong":
      case "double":
      case "Number":
      case "FieldOfView":
        innerPropValue = parseFloat(innerPropValue);
        break;
      case "Color":
      case "ColorRGB":
      case "Vector3D":
      case "Lcl_Translation":
      case "Lcl_Rotation":
      case "Lcl_Scaling":
        innerPropValue = parseNumberArray(innerPropValue);
        break;
    }
    this.getPrevNode()[innerPropName] = {
      "type": innerPropType1,
      "type2": innerPropType2,
      "flag": innerPropFlag,
      "value": innerPropValue
    };
    this.setCurrentProp(this.getPrevNode(), innerPropName);
  }
};
var BinaryParser = class {
  parse(buffer) {
    const reader = new BinaryReader(buffer);
    reader.skip(23);
    const version = reader.getUint32();
    if (version < 6400) {
      throw new Error("THREE.FBXLoader: FBX version not supported, FileVersion: " + version);
    }
    const allNodes = new FBXTree();
    while (!this.endOfContent(reader)) {
      const node = this.parseNode(reader, version);
      if (node !== null) allNodes.add(node.name, node);
    }
    return allNodes;
  }
  // Check if reader has reached the end of content.
  endOfContent(reader) {
    if (reader.size() % 16 === 0) {
      return (reader.getOffset() + 160 + 16 & ~15) >= reader.size();
    } else {
      return reader.getOffset() + 160 + 16 >= reader.size();
    }
  }
  // recursively parse nodes until the end of the file is reached
  parseNode(reader, version) {
    const node = {};
    const endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32();
    const numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32();
    version >= 7500 ? reader.getUint64() : reader.getUint32();
    const nameLen = reader.getUint8();
    const name2 = reader.getString(nameLen);
    if (endOffset === 0) return null;
    const propertyList = [];
    for (let i = 0; i < numProperties; i++) {
      propertyList.push(this.parseProperty(reader));
    }
    const id = propertyList.length > 0 ? propertyList[0] : "";
    const attrName = propertyList.length > 1 ? propertyList[1] : "";
    const attrType = propertyList.length > 2 ? propertyList[2] : "";
    node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false;
    while (endOffset > reader.getOffset()) {
      const subNode = this.parseNode(reader, version);
      if (subNode !== null) this.parseSubNode(name2, node, subNode);
    }
    node.propertyList = propertyList;
    if (typeof id === "number") node.id = id;
    if (attrName !== "") node.attrName = attrName;
    if (attrType !== "") node.attrType = attrType;
    if (name2 !== "") node.name = name2;
    return node;
  }
  parseSubNode(name2, node, subNode) {
    if (subNode.singleProperty === true) {
      const value2 = subNode.propertyList[0];
      if (Array.isArray(value2)) {
        node[subNode.name] = subNode;
        subNode.a = value2;
      } else {
        node[subNode.name] = value2;
      }
    } else if (name2 === "Connections" && subNode.name === "C") {
      const array = [];
      subNode.propertyList.forEach(function(property2, i) {
        if (i !== 0) array.push(property2);
      });
      if (node.connections === void 0) {
        node.connections = [];
      }
      node.connections.push(array);
    } else if (subNode.name === "Properties70") {
      const keys2 = Object.keys(subNode);
      keys2.forEach(function(key2) {
        node[key2] = subNode[key2];
      });
    } else if (name2 === "Properties70" && subNode.name === "P") {
      let innerPropName = subNode.propertyList[0];
      let innerPropType1 = subNode.propertyList[1];
      const innerPropType2 = subNode.propertyList[2];
      const innerPropFlag = subNode.propertyList[3];
      let innerPropValue;
      if (innerPropName.indexOf("Lcl ") === 0) innerPropName = innerPropName.replace("Lcl ", "Lcl_");
      if (innerPropType1.indexOf("Lcl ") === 0) innerPropType1 = innerPropType1.replace("Lcl ", "Lcl_");
      if (innerPropType1 === "Color" || innerPropType1 === "ColorRGB" || innerPropType1 === "Vector" || innerPropType1 === "Vector3D" || innerPropType1.indexOf("Lcl_") === 0) {
        innerPropValue = [
          subNode.propertyList[4],
          subNode.propertyList[5],
          subNode.propertyList[6]
        ];
      } else {
        innerPropValue = subNode.propertyList[4];
      }
      node[innerPropName] = {
        "type": innerPropType1,
        "type2": innerPropType2,
        "flag": innerPropFlag,
        "value": innerPropValue
      };
    } else if (node[subNode.name] === void 0) {
      if (typeof subNode.id === "number") {
        node[subNode.name] = {};
        node[subNode.name][subNode.id] = subNode;
      } else {
        node[subNode.name] = subNode;
      }
    } else {
      if (subNode.name === "PoseNode") {
        if (!Array.isArray(node[subNode.name])) {
          node[subNode.name] = [node[subNode.name]];
        }
        node[subNode.name].push(subNode);
      } else if (node[subNode.name][subNode.id] === void 0) {
        node[subNode.name][subNode.id] = subNode;
      }
    }
  }
  parseProperty(reader) {
    const type = reader.getString(1);
    let length2;
    switch (type) {
      case "C":
        return reader.getBoolean();
      case "D":
        return reader.getFloat64();
      case "F":
        return reader.getFloat32();
      case "I":
        return reader.getInt32();
      case "L":
        return reader.getInt64();
      case "R":
        length2 = reader.getUint32();
        return reader.getArrayBuffer(length2);
      case "S":
        length2 = reader.getUint32();
        return reader.getString(length2);
      case "Y":
        return reader.getInt16();
      case "b":
      case "c":
      case "d":
      case "f":
      case "i":
      case "l":
        const arrayLength = reader.getUint32();
        const encoding = reader.getUint32();
        const compressedLength = reader.getUint32();
        if (encoding === 0) {
          switch (type) {
            case "b":
            case "c":
              return reader.getBooleanArray(arrayLength);
            case "d":
              return reader.getFloat64Array(arrayLength);
            case "f":
              return reader.getFloat32Array(arrayLength);
            case "i":
              return reader.getInt32Array(arrayLength);
            case "l":
              return reader.getInt64Array(arrayLength);
          }
        }
        const data2 = unzlibSync(new Uint8Array(reader.getArrayBuffer(compressedLength)));
        const reader2 = new BinaryReader(data2.buffer);
        switch (type) {
          case "b":
          case "c":
            return reader2.getBooleanArray(arrayLength);
          case "d":
            return reader2.getFloat64Array(arrayLength);
          case "f":
            return reader2.getFloat32Array(arrayLength);
          case "i":
            return reader2.getInt32Array(arrayLength);
          case "l":
            return reader2.getInt64Array(arrayLength);
        }
        break;
      // cannot happen but is required by the DeepScan
      default:
        throw new Error("THREE.FBXLoader: Unknown property type " + type);
    }
  }
};
var BinaryReader = class {
  constructor(buffer, littleEndian) {
    this.dv = new DataView(buffer);
    this.offset = 0;
    this.littleEndian = littleEndian !== void 0 ? littleEndian : true;
    this._textDecoder = new TextDecoder();
  }
  getOffset() {
    return this.offset;
  }
  size() {
    return this.dv.buffer.byteLength;
  }
  skip(length2) {
    this.offset += length2;
  }
  // seems like true/false representation depends on exporter.
  // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  // then sees LSB.
  getBoolean() {
    return (this.getUint8() & 1) === 1;
  }
  getBooleanArray(size2) {
    const a2 = [];
    for (let i = 0; i < size2; i++) {
      a2.push(this.getBoolean());
    }
    return a2;
  }
  getUint8() {
    const value2 = this.dv.getUint8(this.offset);
    this.offset += 1;
    return value2;
  }
  getInt16() {
    const value2 = this.dv.getInt16(this.offset, this.littleEndian);
    this.offset += 2;
    return value2;
  }
  getInt32() {
    const value2 = this.dv.getInt32(this.offset, this.littleEndian);
    this.offset += 4;
    return value2;
  }
  getInt32Array(size2) {
    const a2 = [];
    for (let i = 0; i < size2; i++) {
      a2.push(this.getInt32());
    }
    return a2;
  }
  getUint32() {
    const value2 = this.dv.getUint32(this.offset, this.littleEndian);
    this.offset += 4;
    return value2;
  }
  // JavaScript doesn't support 64-bit integer so calculate this here
  // 1 << 32 will return 1 so using multiply operation instead here.
  // There's a possibility that this method returns wrong value if the value
  // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  // TODO: safely handle 64-bit integer
  getInt64() {
    let low, high;
    if (this.littleEndian) {
      low = this.getUint32();
      high = this.getUint32();
    } else {
      high = this.getUint32();
      low = this.getUint32();
    }
    if (high & 2147483648) {
      high = ~high & 4294967295;
      low = ~low & 4294967295;
      if (low === 4294967295) high = high + 1 & 4294967295;
      low = low + 1 & 4294967295;
      return -(high * 4294967296 + low);
    }
    return high * 4294967296 + low;
  }
  getInt64Array(size2) {
    const a2 = [];
    for (let i = 0; i < size2; i++) {
      a2.push(this.getInt64());
    }
    return a2;
  }
  // Note: see getInt64() comment
  getUint64() {
    let low, high;
    if (this.littleEndian) {
      low = this.getUint32();
      high = this.getUint32();
    } else {
      high = this.getUint32();
      low = this.getUint32();
    }
    return high * 4294967296 + low;
  }
  getFloat32() {
    const value2 = this.dv.getFloat32(this.offset, this.littleEndian);
    this.offset += 4;
    return value2;
  }
  getFloat32Array(size2) {
    const a2 = [];
    for (let i = 0; i < size2; i++) {
      a2.push(this.getFloat32());
    }
    return a2;
  }
  getFloat64() {
    const value2 = this.dv.getFloat64(this.offset, this.littleEndian);
    this.offset += 8;
    return value2;
  }
  getFloat64Array(size2) {
    const a2 = [];
    for (let i = 0; i < size2; i++) {
      a2.push(this.getFloat64());
    }
    return a2;
  }
  getArrayBuffer(size2) {
    const value2 = this.dv.buffer.slice(this.offset, this.offset + size2);
    this.offset += size2;
    return value2;
  }
  getString(size2) {
    const start = this.offset;
    let a2 = new Uint8Array(this.dv.buffer, start, size2);
    this.skip(size2);
    const nullByte = a2.indexOf(0);
    if (nullByte >= 0) a2 = new Uint8Array(this.dv.buffer, start, nullByte);
    return this._textDecoder.decode(a2);
  }
};
var FBXTree = class {
  add(key2, val2) {
    this[key2] = val2;
  }
};
function isFbxFormatBinary(buffer) {
  const CORRECT = "Kaydara FBX Binary  \0";
  return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString(buffer, 0, CORRECT.length);
}
function isFbxFormatASCII(text2) {
  const CORRECT = ["K", "a", "y", "d", "a", "r", "a", "\\", "F", "B", "X", "\\", "B", "i", "n", "a", "r", "y", "\\", "\\"];
  let cursor = 0;
  function read(offset) {
    const result = text2[offset - 1];
    text2 = text2.slice(cursor + offset);
    cursor++;
    return result;
  }
  for (let i = 0; i < CORRECT.length; ++i) {
    const num = read(1);
    if (num === CORRECT[i]) {
      return false;
    }
  }
  return true;
}
function getFbxVersion(text2) {
  const versionRegExp = /FBXVersion: (\d+)/;
  const match = text2.match(versionRegExp);
  if (match) {
    const version = parseInt(match[1]);
    return version;
  }
  throw new Error("THREE.FBXLoader: Cannot find the version number for the file given.");
}
function convertFBXTimeToSeconds(time2) {
  return time2 / 46186158e3;
}
var dataArray = [];
function getData(polygonVertexIndex, polygonIndex, vertexIndex, infoObject) {
  let index2;
  switch (infoObject.mappingType) {
    case "ByPolygonVertex":
      index2 = polygonVertexIndex;
      break;
    case "ByPolygon":
      index2 = polygonIndex;
      break;
    case "ByVertice":
      index2 = vertexIndex;
      break;
    case "AllSame":
      index2 = infoObject.indices[0];
      break;
    default:
      console.warn("THREE.FBXLoader: unknown attribute mapping type " + infoObject.mappingType);
  }
  if (infoObject.referenceType === "IndexToDirect") index2 = infoObject.indices[index2];
  const from = index2 * infoObject.dataSize;
  const to = from + infoObject.dataSize;
  return slice(dataArray, infoObject.buffer, from, to);
}
var tempEuler = new Euler();
var tempVec = new Vector3();
function generateTransform(transformData) {
  const lTranslationM = new Matrix4();
  const lPreRotationM = new Matrix4();
  const lRotationM = new Matrix4();
  const lPostRotationM = new Matrix4();
  const lScalingM = new Matrix4();
  const lScalingPivotM = new Matrix4();
  const lScalingOffsetM = new Matrix4();
  const lRotationOffsetM = new Matrix4();
  const lRotationPivotM = new Matrix4();
  const lParentGX = new Matrix4();
  const lParentLX = new Matrix4();
  const lGlobalT = new Matrix4();
  const inheritType = transformData.inheritType ? transformData.inheritType : 0;
  if (transformData.translation) lTranslationM.setPosition(tempVec.fromArray(transformData.translation));
  const defaultEulerOrder = getEulerOrder(0);
  if (transformData.preRotation) {
    const array = transformData.preRotation.map(MathUtils.degToRad);
    array.push(defaultEulerOrder);
    lPreRotationM.makeRotationFromEuler(tempEuler.fromArray(array));
  }
  if (transformData.rotation) {
    const array = transformData.rotation.map(MathUtils.degToRad);
    array.push(transformData.eulerOrder || defaultEulerOrder);
    lRotationM.makeRotationFromEuler(tempEuler.fromArray(array));
  }
  if (transformData.postRotation) {
    const array = transformData.postRotation.map(MathUtils.degToRad);
    array.push(defaultEulerOrder);
    lPostRotationM.makeRotationFromEuler(tempEuler.fromArray(array));
    lPostRotationM.invert();
  }
  if (transformData.scale) lScalingM.scale(tempVec.fromArray(transformData.scale));
  if (transformData.scalingOffset) lScalingOffsetM.setPosition(tempVec.fromArray(transformData.scalingOffset));
  if (transformData.scalingPivot) lScalingPivotM.setPosition(tempVec.fromArray(transformData.scalingPivot));
  if (transformData.rotationOffset) lRotationOffsetM.setPosition(tempVec.fromArray(transformData.rotationOffset));
  if (transformData.rotationPivot) lRotationPivotM.setPosition(tempVec.fromArray(transformData.rotationPivot));
  if (transformData.parentMatrixWorld) {
    lParentLX.copy(transformData.parentMatrix);
    lParentGX.copy(transformData.parentMatrixWorld);
  }
  const lLRM = lPreRotationM.clone().multiply(lRotationM).multiply(lPostRotationM);
  const lParentGRM = new Matrix4();
  lParentGRM.extractRotation(lParentGX);
  const lParentTM = new Matrix4();
  lParentTM.copyPosition(lParentGX);
  const lParentGRSM = lParentTM.clone().invert().multiply(lParentGX);
  const lParentGSM = lParentGRM.clone().invert().multiply(lParentGRSM);
  const lLSM = lScalingM;
  const lGlobalRS = new Matrix4();
  if (inheritType === 0) {
    lGlobalRS.copy(lParentGRM).multiply(lLRM).multiply(lParentGSM).multiply(lLSM);
  } else if (inheritType === 1) {
    lGlobalRS.copy(lParentGRM).multiply(lParentGSM).multiply(lLRM).multiply(lLSM);
  } else {
    const lParentLSM = new Matrix4().scale(new Vector3().setFromMatrixScale(lParentLX));
    const lParentLSM_inv = lParentLSM.clone().invert();
    const lParentGSM_noLocal = lParentGSM.clone().multiply(lParentLSM_inv);
    lGlobalRS.copy(lParentGRM).multiply(lLRM).multiply(lParentGSM_noLocal).multiply(lLSM);
  }
  const lRotationPivotM_inv = lRotationPivotM.clone().invert();
  const lScalingPivotM_inv = lScalingPivotM.clone().invert();
  let lTransform = lTranslationM.clone().multiply(lRotationOffsetM).multiply(lRotationPivotM).multiply(lPreRotationM).multiply(lRotationM).multiply(lPostRotationM).multiply(lRotationPivotM_inv).multiply(lScalingOffsetM).multiply(lScalingPivotM).multiply(lScalingM).multiply(lScalingPivotM_inv);
  const lLocalTWithAllPivotAndOffsetInfo = new Matrix4().copyPosition(lTransform);
  const lGlobalTranslation = lParentGX.clone().multiply(lLocalTWithAllPivotAndOffsetInfo);
  lGlobalT.copyPosition(lGlobalTranslation);
  lTransform = lGlobalT.clone().multiply(lGlobalRS);
  lTransform.premultiply(lParentGX.invert());
  return lTransform;
}
function getEulerOrder(order) {
  order = order || 0;
  const enums = [
    "ZYX",
    // -> XYZ extrinsic
    "YZX",
    // -> XZY extrinsic
    "XZY",
    // -> YZX extrinsic
    "ZXY",
    // -> YXZ extrinsic
    "YXZ",
    // -> ZXY extrinsic
    "XYZ"
    // -> ZYX extrinsic
    //'SphericXYZ', // not possible to support
  ];
  if (order === 6) {
    console.warn("THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.");
    return enums[0];
  }
  return enums[order];
}
function parseNumberArray(value2) {
  const array = value2.split(",").map(function(val2) {
    return parseFloat(val2);
  });
  return array;
}
function convertArrayBufferToString(buffer, from, to) {
  if (from === void 0) from = 0;
  if (to === void 0) to = buffer.byteLength;
  return new TextDecoder().decode(new Uint8Array(buffer, from, to));
}
function append(a2, b3) {
  for (let i = 0, j2 = a2.length, l2 = b3.length; i < l2; i++, j2++) {
    a2[j2] = b3[i];
  }
}
function slice(a2, b3, from, to) {
  for (let i = from, j2 = 0; i < to; i++, j2++) {
    a2[j2] = b3[i];
  }
  return a2;
}

// node_modules/three/examples/jsm/loaders/FontLoader.js
var FontLoader = class extends Loader {
  /**
   * Constructs a new font loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded font
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Font)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(text2) {
      const font = scope.parse(JSON.parse(text2));
      if (onLoad) onLoad(font);
    }, onProgress, onError);
  }
  /**
   * Parses the given font data and returns the resulting font.
   *
   * @param {Object} json - The raw font data as a JSON object.
   * @return {Font} The font.
   */
  parse(json) {
    return new Font(json);
  }
};
var Font = class {
  /**
   * Constructs a new font.
   *
   * @param {Object} data - The font data as JSON.
   */
  constructor(data2) {
    this.isFont = true;
    this.type = "Font";
    this.data = data2;
  }
  /**
   * Generates geometry shapes from the given text and size. The result of this method
   * should be used with {@link ShapeGeometry} to generate the actual geometry data.
   *
   * @param {string} text - The text.
   * @param {number} [size=100] - The text size.
   * @return {Array<Shape>} An array of shapes representing the text.
   */
  generateShapes(text2, size2 = 100) {
    const shapes = [];
    const paths = createPaths(text2, size2, this.data);
    for (let p = 0, pl = paths.length; p < pl; p++) {
      shapes.push(...paths[p].toShapes());
    }
    return shapes;
  }
};
function createPaths(text2, size2, data2) {
  const chars = Array.from(text2);
  const scale2 = size2 / data2.resolution;
  const line_height = (data2.boundingBox.yMax - data2.boundingBox.yMin + data2.underlineThickness) * scale2;
  const paths = [];
  let offsetX = 0, offsetY = 0;
  for (let i = 0; i < chars.length; i++) {
    const char = chars[i];
    if (char === "\n") {
      offsetX = 0;
      offsetY -= line_height;
    } else {
      const ret = createPath2(char, scale2, offsetX, offsetY, data2);
      offsetX += ret.offsetX;
      paths.push(ret.path);
    }
  }
  return paths;
}
function createPath2(char, scale2, offsetX, offsetY, data2) {
  const glyph = data2.glyphs[char] || data2.glyphs["?"];
  if (!glyph) {
    console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data2.familyName + ".");
    return;
  }
  const path = new ShapePath2();
  let x2, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  if (glyph.o) {
    const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(" "));
    for (let i = 0, l2 = outline.length; i < l2; ) {
      const action = outline[i++];
      switch (action) {
        case "m":
          x2 = outline[i++] * scale2 + offsetX;
          y = outline[i++] * scale2 + offsetY;
          path.moveTo(x2, y);
          break;
        case "l":
          x2 = outline[i++] * scale2 + offsetX;
          y = outline[i++] * scale2 + offsetY;
          path.lineTo(x2, y);
          break;
        case "q":
          cpx = outline[i++] * scale2 + offsetX;
          cpy = outline[i++] * scale2 + offsetY;
          cpx1 = outline[i++] * scale2 + offsetX;
          cpy1 = outline[i++] * scale2 + offsetY;
          path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
          break;
        case "b":
          cpx = outline[i++] * scale2 + offsetX;
          cpy = outline[i++] * scale2 + offsetY;
          cpx1 = outline[i++] * scale2 + offsetX;
          cpy1 = outline[i++] * scale2 + offsetY;
          cpx2 = outline[i++] * scale2 + offsetX;
          cpy2 = outline[i++] * scale2 + offsetY;
          path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
          break;
      }
    }
  }
  return { offsetX: glyph.ha * scale2, path };
}

// node_modules/three/examples/jsm/loaders/GCodeLoader.js
var GCodeLoader = class extends Loader {
  /**
   * Constructs a new GCode loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.splitLayer = false;
  }
  /**
   * Starts loading from the given URL and passes the loaded GCode asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Group)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given GCode data and returns a group with lines.
   *
   * @param {string} data - The raw Gcode data as a string.
   * @return {Group} The parsed GCode asset.
   */
  parse(data2) {
    let state = { x: 0, y: 0, z: 0, e: 0, f: 0, extruding: false, relative: false };
    const layers = [];
    let currentLayer = void 0;
    const pathMaterial = new LineBasicMaterial({ color: 16711680 });
    pathMaterial.name = "path";
    const extrudingMaterial = new LineBasicMaterial({ color: 65280 });
    extrudingMaterial.name = "extruded";
    function newLayer(line2) {
      currentLayer = { vertex: [], pathVertex: [], z: line2.z };
      layers.push(currentLayer);
    }
    function addSegment2(p1, p2) {
      if (currentLayer === void 0) {
        newLayer(p1);
      }
      if (state.extruding) {
        currentLayer.vertex.push(p1.x, p1.y, p1.z);
        currentLayer.vertex.push(p2.x, p2.y, p2.z);
      } else {
        currentLayer.pathVertex.push(p1.x, p1.y, p1.z);
        currentLayer.pathVertex.push(p2.x, p2.y, p2.z);
      }
    }
    function delta(v12, v2) {
      return state.relative ? v2 : v2 - v12;
    }
    function absolute(v12, v2) {
      return state.relative ? v12 + v2 : v2;
    }
    const lines = data2.replace(/;.+/g, "").split("\n");
    for (let i = 0; i < lines.length; i++) {
      const tokens = lines[i].split(" ");
      const cmd = tokens[0].toUpperCase();
      const args = {};
      tokens.splice(1).forEach(function(token) {
        if (token[0] !== void 0) {
          const key2 = token[0].toLowerCase();
          const value2 = parseFloat(token.substring(1));
          args[key2] = value2;
        }
      });
      if (cmd === "G0" || cmd === "G1") {
        const line2 = {
          x: args.x !== void 0 ? absolute(state.x, args.x) : state.x,
          y: args.y !== void 0 ? absolute(state.y, args.y) : state.y,
          z: args.z !== void 0 ? absolute(state.z, args.z) : state.z,
          e: args.e !== void 0 ? absolute(state.e, args.e) : state.e,
          f: args.f !== void 0 ? absolute(state.f, args.f) : state.f
        };
        if (delta(state.e, line2.e) > 0) {
          state.extruding = delta(state.e, line2.e) > 0;
          if (currentLayer == void 0 || line2.z != currentLayer.z) {
            newLayer(line2);
          }
        }
        addSegment2(state, line2);
        state = line2;
      } else if (cmd === "G2" || cmd === "G3") {
      } else if (cmd === "G90") {
        state.relative = false;
      } else if (cmd === "G91") {
        state.relative = true;
      } else if (cmd === "G92") {
        const line2 = state;
        line2.x = args.x !== void 0 ? args.x : line2.x;
        line2.y = args.y !== void 0 ? args.y : line2.y;
        line2.z = args.z !== void 0 ? args.z : line2.z;
        line2.e = args.e !== void 0 ? args.e : line2.e;
      } else {
      }
    }
    function addObject(vertex, extruding, i) {
      const geometry = new BufferGeometry();
      geometry.setAttribute("position", new Float32BufferAttribute(vertex, 3));
      const segments = new LineSegments(geometry, extruding ? extrudingMaterial : pathMaterial);
      segments.name = "layer" + i;
      object.add(segments);
    }
    const object = new Group();
    object.name = "gcode";
    if (this.splitLayer) {
      for (let i = 0; i < layers.length; i++) {
        const layer = layers[i];
        addObject(layer.vertex, true, i);
        addObject(layer.pathVertex, false, i);
      }
    } else {
      const vertex = [], pathVertex = [];
      for (let i = 0; i < layers.length; i++) {
        const layer = layers[i];
        const layerVertex = layer.vertex;
        const layerPathVertex = layer.pathVertex;
        for (let j2 = 0; j2 < layerVertex.length; j2++) {
          vertex.push(layerVertex[j2]);
        }
        for (let j2 = 0; j2 < layerPathVertex.length; j2++) {
          pathVertex.push(layerPathVertex[j2]);
        }
      }
      addObject(vertex, true, layers.length);
      addObject(pathVertex, false, layers.length);
    }
    object.rotation.set(-Math.PI / 2, 0, 0);
    return object;
  }
};

// node_modules/three/examples/jsm/loaders/GLTFLoader.js
var GLTFLoader = class extends Loader {
  /**
   * Constructs a new glTF loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.dracoLoader = null;
    this.ktx2Loader = null;
    this.meshoptDecoder = null;
    this.pluginCallbacks = [];
    this.register(function(parser) {
      return new GLTFMaterialsClearcoatExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsDispersionExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFTextureBasisUExtension(parser);
    });
    this.register(function(parser) {
      return new GLTFTextureWebPExtension(parser);
    });
    this.register(function(parser) {
      return new GLTFTextureAVIFExtension(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsSheenExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsTransmissionExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsVolumeExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsIorExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsEmissiveStrengthExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsSpecularExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsIridescenceExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsAnisotropyExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFMaterialsBumpExtension2(parser);
    });
    this.register(function(parser) {
      return new GLTFLightsExtension(parser);
    });
    this.register(function(parser) {
      return new GLTFMeshoptCompression(parser);
    });
    this.register(function(parser) {
      return new GLTFMeshGpuInstancing2(parser);
    });
  }
  /**
   * Starts loading from the given URL and passes the loaded glTF asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    let resourcePath;
    if (this.resourcePath !== "") {
      resourcePath = this.resourcePath;
    } else if (this.path !== "") {
      const relativeUrl = LoaderUtils.extractUrlBase(url);
      resourcePath = LoaderUtils.resolveURL(relativeUrl, this.path);
    } else {
      resourcePath = LoaderUtils.extractUrlBase(url);
    }
    this.manager.itemStart(url);
    const _onError = function(e) {
      if (onError) {
        onError(e);
      } else {
        console.error(e);
      }
      scope.manager.itemError(url);
      scope.manager.itemEnd(url);
    };
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(data2) {
      try {
        scope.parse(data2, resourcePath, function(gltf) {
          onLoad(gltf);
          scope.manager.itemEnd(url);
        }, _onError);
      } catch (e) {
        _onError(e);
      }
    }, onProgress, _onError);
  }
  /**
   * Sets the given Draco loader to this loader. Required for decoding assets
   * compressed with the `KHR_draco_mesh_compression` extension.
   *
   * @param {DRACOLoader} dracoLoader - The Draco loader to set.
   * @return {GLTFLoader} A reference to this loader.
   */
  setDRACOLoader(dracoLoader) {
    this.dracoLoader = dracoLoader;
    return this;
  }
  /**
   * Sets the given KTX2 loader to this loader. Required for loading KTX2
   * compressed textures.
   *
   * @param {KTX2Loader} ktx2Loader - The KTX2 loader to set.
   * @return {GLTFLoader} A reference to this loader.
   */
  setKTX2Loader(ktx2Loader) {
    this.ktx2Loader = ktx2Loader;
    return this;
  }
  /**
   * Sets the given meshopt decoder. Required for decoding assets
   * compressed with the `EXT_meshopt_compression` extension.
   *
   * @param {Object} meshoptDecoder - The meshopt decoder to set.
   * @return {GLTFLoader} A reference to this loader.
   */
  setMeshoptDecoder(meshoptDecoder) {
    this.meshoptDecoder = meshoptDecoder;
    return this;
  }
  /**
   * Registers a plugin callback. This API is internally used to implement the various
   * glTF extensions but can also used by third-party code to add additional logic
   * to the loader.
   *
   * @param {function(parser:GLTFParser)} callback - The callback function to register.
   * @return {GLTFLoader} A reference to this loader.
   */
  register(callback) {
    if (this.pluginCallbacks.indexOf(callback) === -1) {
      this.pluginCallbacks.push(callback);
    }
    return this;
  }
  /**
   * Unregisters a plugin callback.
   *
   * @param {Function} callback - The callback function to unregister.
   * @return {GLTFLoader} A reference to this loader.
   */
  unregister(callback) {
    if (this.pluginCallbacks.indexOf(callback) !== -1) {
      this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1);
    }
    return this;
  }
  /**
   * Parses the given FBX data and returns the resulting group.
   *
   * @param {string|ArrayBuffer} data - The raw glTF data.
   * @param {string} path - The URL base path.
   * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  parse(data2, path, onLoad, onError) {
    let json;
    const extensions = {};
    const plugins = {};
    const textDecoder = new TextDecoder();
    if (typeof data2 === "string") {
      json = JSON.parse(data2);
    } else if (data2 instanceof ArrayBuffer) {
      const magic = textDecoder.decode(new Uint8Array(data2, 0, 4));
      if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
        try {
          extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data2);
        } catch (error) {
          if (onError) onError(error);
          return;
        }
        json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content);
      } else {
        json = JSON.parse(textDecoder.decode(data2));
      }
    } else {
      json = data2;
    }
    if (json.asset === void 0 || json.asset.version[0] < 2) {
      if (onError) onError(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));
      return;
    }
    const parser = new GLTFParser(json, {
      path: path || this.resourcePath || "",
      crossOrigin: this.crossOrigin,
      requestHeader: this.requestHeader,
      manager: this.manager,
      ktx2Loader: this.ktx2Loader,
      meshoptDecoder: this.meshoptDecoder
    });
    parser.fileLoader.setRequestHeader(this.requestHeader);
    for (let i = 0; i < this.pluginCallbacks.length; i++) {
      const plugin = this.pluginCallbacks[i](parser);
      if (!plugin.name) console.error("THREE.GLTFLoader: Invalid plugin found: missing name");
      plugins[plugin.name] = plugin;
      extensions[plugin.name] = true;
    }
    if (json.extensionsUsed) {
      for (let i = 0; i < json.extensionsUsed.length; ++i) {
        const extensionName = json.extensionsUsed[i];
        const extensionsRequired = json.extensionsRequired || [];
        switch (extensionName) {
          case EXTENSIONS.KHR_MATERIALS_UNLIT:
            extensions[extensionName] = new GLTFMaterialsUnlitExtension2();
            break;
          case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
            extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
            break;
          case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
            extensions[extensionName] = new GLTFTextureTransformExtension();
            break;
          case EXTENSIONS.KHR_MESH_QUANTIZATION:
            extensions[extensionName] = new GLTFMeshQuantizationExtension();
            break;
          default:
            if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === void 0) {
              console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
            }
        }
      }
    }
    parser.setExtensions(extensions);
    parser.setPlugins(plugins);
    parser.parse(onLoad, onError);
  }
  /**
   * Async version of {@link GLTFLoader#parse}.
   *
   * @async
   * @param {string|ArrayBuffer} data - The raw glTF data.
   * @param {string} path - The URL base path.
   * @return {Promise<GLTFLoader~LoadObject>} A Promise that resolves with the loaded glTF when the parsing has been finished.
   */
  parseAsync(data2, path) {
    const scope = this;
    return new Promise(function(resolve, reject2) {
      scope.parse(data2, path, resolve, reject2);
    });
  }
};
function GLTFRegistry() {
  let objects = {};
  return {
    get: function(key2) {
      return objects[key2];
    },
    add: function(key2, object) {
      objects[key2] = object;
    },
    remove: function(key2) {
      delete objects[key2];
    },
    removeAll: function() {
      objects = {};
    }
  };
}
var EXTENSIONS = {
  KHR_BINARY_GLTF: "KHR_binary_glTF",
  KHR_DRACO_MESH_COMPRESSION: "KHR_draco_mesh_compression",
  KHR_LIGHTS_PUNCTUAL: "KHR_lights_punctual",
  KHR_MATERIALS_CLEARCOAT: "KHR_materials_clearcoat",
  KHR_MATERIALS_DISPERSION: "KHR_materials_dispersion",
  KHR_MATERIALS_IOR: "KHR_materials_ior",
  KHR_MATERIALS_SHEEN: "KHR_materials_sheen",
  KHR_MATERIALS_SPECULAR: "KHR_materials_specular",
  KHR_MATERIALS_TRANSMISSION: "KHR_materials_transmission",
  KHR_MATERIALS_IRIDESCENCE: "KHR_materials_iridescence",
  KHR_MATERIALS_ANISOTROPY: "KHR_materials_anisotropy",
  KHR_MATERIALS_UNLIT: "KHR_materials_unlit",
  KHR_MATERIALS_VOLUME: "KHR_materials_volume",
  KHR_TEXTURE_BASISU: "KHR_texture_basisu",
  KHR_TEXTURE_TRANSFORM: "KHR_texture_transform",
  KHR_MESH_QUANTIZATION: "KHR_mesh_quantization",
  KHR_MATERIALS_EMISSIVE_STRENGTH: "KHR_materials_emissive_strength",
  EXT_MATERIALS_BUMP: "EXT_materials_bump",
  EXT_TEXTURE_WEBP: "EXT_texture_webp",
  EXT_TEXTURE_AVIF: "EXT_texture_avif",
  EXT_MESHOPT_COMPRESSION: "EXT_meshopt_compression",
  EXT_MESH_GPU_INSTANCING: "EXT_mesh_gpu_instancing"
};
var GLTFLightsExtension = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
    this.cache = { refs: {}, uses: {} };
  }
  _markDefs() {
    const parser = this.parser;
    const nodeDefs = this.parser.json.nodes || [];
    for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
      const nodeDef = nodeDefs[nodeIndex];
      if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== void 0) {
        parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light);
      }
    }
  }
  _loadLight(lightIndex) {
    const parser = this.parser;
    const cacheKey = "light:" + lightIndex;
    let dependency = parser.cache.get(cacheKey);
    if (dependency) return dependency;
    const json = parser.json;
    const extensions = json.extensions && json.extensions[this.name] || {};
    const lightDefs = extensions.lights || [];
    const lightDef = lightDefs[lightIndex];
    let lightNode;
    const color = new Color(16777215);
    if (lightDef.color !== void 0) color.setRGB(lightDef.color[0], lightDef.color[1], lightDef.color[2], LinearSRGBColorSpace);
    const range = lightDef.range !== void 0 ? lightDef.range : 0;
    switch (lightDef.type) {
      case "directional":
        lightNode = new DirectionalLight(color);
        lightNode.target.position.set(0, 0, -1);
        lightNode.add(lightNode.target);
        break;
      case "point":
        lightNode = new PointLight(color);
        lightNode.distance = range;
        break;
      case "spot":
        lightNode = new SpotLight(color);
        lightNode.distance = range;
        lightDef.spot = lightDef.spot || {};
        lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== void 0 ? lightDef.spot.innerConeAngle : 0;
        lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== void 0 ? lightDef.spot.outerConeAngle : Math.PI / 4;
        lightNode.angle = lightDef.spot.outerConeAngle;
        lightNode.penumbra = 1 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
        lightNode.target.position.set(0, 0, -1);
        lightNode.add(lightNode.target);
        break;
      default:
        throw new Error("THREE.GLTFLoader: Unexpected light type: " + lightDef.type);
    }
    lightNode.position.set(0, 0, 0);
    assignExtrasToUserData(lightNode, lightDef);
    if (lightDef.intensity !== void 0) lightNode.intensity = lightDef.intensity;
    lightNode.name = parser.createUniqueName(lightDef.name || "light_" + lightIndex);
    dependency = Promise.resolve(lightNode);
    parser.cache.add(cacheKey, dependency);
    return dependency;
  }
  getDependency(type, index2) {
    if (type !== "light") return;
    return this._loadLight(index2);
  }
  createNodeAttachment(nodeIndex) {
    const self2 = this;
    const parser = this.parser;
    const json = parser.json;
    const nodeDef = json.nodes[nodeIndex];
    const lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {};
    const lightIndex = lightDef.light;
    if (lightIndex === void 0) return null;
    return this._loadLight(lightIndex).then(function(light) {
      return parser._getNodeRef(self2.cache, lightIndex, light);
    });
  }
};
var GLTFMaterialsUnlitExtension2 = class {
  constructor() {
    this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  }
  getMaterialType() {
    return MeshBasicMaterial;
  }
  extendParams(materialParams, materialDef, parser) {
    const pending = [];
    materialParams.color = new Color(1, 1, 1);
    materialParams.opacity = 1;
    const metallicRoughness = materialDef.pbrMetallicRoughness;
    if (metallicRoughness) {
      if (Array.isArray(metallicRoughness.baseColorFactor)) {
        const array = metallicRoughness.baseColorFactor;
        materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace);
        materialParams.opacity = array[3];
      }
      if (metallicRoughness.baseColorTexture !== void 0) {
        pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace));
      }
    }
    return Promise.all(pending);
  }
};
var GLTFMaterialsEmissiveStrengthExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const emissiveStrength = materialDef.extensions[this.name].emissiveStrength;
    if (emissiveStrength !== void 0) {
      materialParams.emissiveIntensity = emissiveStrength;
    }
    return Promise.resolve();
  }
};
var GLTFMaterialsClearcoatExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const pending = [];
    const extension = materialDef.extensions[this.name];
    if (extension.clearcoatFactor !== void 0) {
      materialParams.clearcoat = extension.clearcoatFactor;
    }
    if (extension.clearcoatTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "clearcoatMap", extension.clearcoatTexture));
    }
    if (extension.clearcoatRoughnessFactor !== void 0) {
      materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
    }
    if (extension.clearcoatRoughnessTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "clearcoatRoughnessMap", extension.clearcoatRoughnessTexture));
    }
    if (extension.clearcoatNormalTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "clearcoatNormalMap", extension.clearcoatNormalTexture));
      if (extension.clearcoatNormalTexture.scale !== void 0) {
        const scale2 = extension.clearcoatNormalTexture.scale;
        materialParams.clearcoatNormalScale = new Vector2(scale2, scale2);
      }
    }
    return Promise.all(pending);
  }
};
var GLTFMaterialsDispersionExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const extension = materialDef.extensions[this.name];
    materialParams.dispersion = extension.dispersion !== void 0 ? extension.dispersion : 0;
    return Promise.resolve();
  }
};
var GLTFMaterialsIridescenceExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const pending = [];
    const extension = materialDef.extensions[this.name];
    if (extension.iridescenceFactor !== void 0) {
      materialParams.iridescence = extension.iridescenceFactor;
    }
    if (extension.iridescenceTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "iridescenceMap", extension.iridescenceTexture));
    }
    if (extension.iridescenceIor !== void 0) {
      materialParams.iridescenceIOR = extension.iridescenceIor;
    }
    if (materialParams.iridescenceThicknessRange === void 0) {
      materialParams.iridescenceThicknessRange = [100, 400];
    }
    if (extension.iridescenceThicknessMinimum !== void 0) {
      materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum;
    }
    if (extension.iridescenceThicknessMaximum !== void 0) {
      materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum;
    }
    if (extension.iridescenceThicknessTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "iridescenceThicknessMap", extension.iridescenceThicknessTexture));
    }
    return Promise.all(pending);
  }
};
var GLTFMaterialsSheenExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const pending = [];
    materialParams.sheenColor = new Color(0, 0, 0);
    materialParams.sheenRoughness = 0;
    materialParams.sheen = 1;
    const extension = materialDef.extensions[this.name];
    if (extension.sheenColorFactor !== void 0) {
      const colorFactor = extension.sheenColorFactor;
      materialParams.sheenColor.setRGB(colorFactor[0], colorFactor[1], colorFactor[2], LinearSRGBColorSpace);
    }
    if (extension.sheenRoughnessFactor !== void 0) {
      materialParams.sheenRoughness = extension.sheenRoughnessFactor;
    }
    if (extension.sheenColorTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "sheenColorMap", extension.sheenColorTexture, SRGBColorSpace));
    }
    if (extension.sheenRoughnessTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "sheenRoughnessMap", extension.sheenRoughnessTexture));
    }
    return Promise.all(pending);
  }
};
var GLTFMaterialsTransmissionExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const pending = [];
    const extension = materialDef.extensions[this.name];
    if (extension.transmissionFactor !== void 0) {
      materialParams.transmission = extension.transmissionFactor;
    }
    if (extension.transmissionTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "transmissionMap", extension.transmissionTexture));
    }
    return Promise.all(pending);
  }
};
var GLTFMaterialsVolumeExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const pending = [];
    const extension = materialDef.extensions[this.name];
    materialParams.thickness = extension.thicknessFactor !== void 0 ? extension.thicknessFactor : 0;
    if (extension.thicknessTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "thicknessMap", extension.thicknessTexture));
    }
    materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
    const colorArray = extension.attenuationColor || [1, 1, 1];
    materialParams.attenuationColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace);
    return Promise.all(pending);
  }
};
var GLTFMaterialsIorExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_IOR;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const extension = materialDef.extensions[this.name];
    materialParams.ior = extension.ior !== void 0 ? extension.ior : 1.5;
    return Promise.resolve();
  }
};
var GLTFMaterialsSpecularExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const pending = [];
    const extension = materialDef.extensions[this.name];
    materialParams.specularIntensity = extension.specularFactor !== void 0 ? extension.specularFactor : 1;
    if (extension.specularTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "specularIntensityMap", extension.specularTexture));
    }
    const colorArray = extension.specularColorFactor || [1, 1, 1];
    materialParams.specularColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace);
    if (extension.specularColorTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "specularColorMap", extension.specularColorTexture, SRGBColorSpace));
    }
    return Promise.all(pending);
  }
};
var GLTFMaterialsBumpExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.EXT_MATERIALS_BUMP;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const pending = [];
    const extension = materialDef.extensions[this.name];
    materialParams.bumpScale = extension.bumpFactor !== void 0 ? extension.bumpFactor : 1;
    if (extension.bumpTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "bumpMap", extension.bumpTexture));
    }
    return Promise.all(pending);
  }
};
var GLTFMaterialsAnisotropyExtension2 = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY;
  }
  getMaterialType(materialIndex) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
    return MeshPhysicalMaterial;
  }
  extendMaterialParams(materialIndex, materialParams) {
    const parser = this.parser;
    const materialDef = parser.json.materials[materialIndex];
    if (!materialDef.extensions || !materialDef.extensions[this.name]) {
      return Promise.resolve();
    }
    const pending = [];
    const extension = materialDef.extensions[this.name];
    if (extension.anisotropyStrength !== void 0) {
      materialParams.anisotropy = extension.anisotropyStrength;
    }
    if (extension.anisotropyRotation !== void 0) {
      materialParams.anisotropyRotation = extension.anisotropyRotation;
    }
    if (extension.anisotropyTexture !== void 0) {
      pending.push(parser.assignTexture(materialParams, "anisotropyMap", extension.anisotropyTexture));
    }
    return Promise.all(pending);
  }
};
var GLTFTextureBasisUExtension = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  }
  loadTexture(textureIndex) {
    const parser = this.parser;
    const json = parser.json;
    const textureDef = json.textures[textureIndex];
    if (!textureDef.extensions || !textureDef.extensions[this.name]) {
      return null;
    }
    const extension = textureDef.extensions[this.name];
    const loader = parser.options.ktx2Loader;
    if (!loader) {
      if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
        throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");
      } else {
        return null;
      }
    }
    return parser.loadTextureImage(textureIndex, extension.source, loader);
  }
};
var GLTFTextureWebPExtension = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  }
  loadTexture(textureIndex) {
    const name2 = this.name;
    const parser = this.parser;
    const json = parser.json;
    const textureDef = json.textures[textureIndex];
    if (!textureDef.extensions || !textureDef.extensions[name2]) {
      return null;
    }
    const extension = textureDef.extensions[name2];
    const source = json.images[extension.source];
    let loader = parser.textureLoader;
    if (source.uri) {
      const handler = parser.options.manager.getHandler(source.uri);
      if (handler !== null) loader = handler;
    }
    return parser.loadTextureImage(textureIndex, extension.source, loader);
  }
};
var GLTFTextureAVIFExtension = class {
  constructor(parser) {
    this.parser = parser;
    this.name = EXTENSIONS.EXT_TEXTURE_AVIF;
  }
  loadTexture(textureIndex) {
    const name2 = this.name;
    const parser = this.parser;
    const json = parser.json;
    const textureDef = json.textures[textureIndex];
    if (!textureDef.extensions || !textureDef.extensions[name2]) {
      return null;
    }
    const extension = textureDef.extensions[name2];
    const source = json.images[extension.source];
    let loader = parser.textureLoader;
    if (source.uri) {
      const handler = parser.options.manager.getHandler(source.uri);
      if (handler !== null) loader = handler;
    }
    return parser.loadTextureImage(textureIndex, extension.source, loader);
  }
};
var GLTFMeshoptCompression = class {
  constructor(parser) {
    this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
    this.parser = parser;
  }
  loadBufferView(index2) {
    const json = this.parser.json;
    const bufferView = json.bufferViews[index2];
    if (bufferView.extensions && bufferView.extensions[this.name]) {
      const extensionDef = bufferView.extensions[this.name];
      const buffer = this.parser.getDependency("buffer", extensionDef.buffer);
      const decoder = this.parser.options.meshoptDecoder;
      if (!decoder || !decoder.supported) {
        if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
          throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");
        } else {
          return null;
        }
      }
      return buffer.then(function(res) {
        const byteOffset = extensionDef.byteOffset || 0;
        const byteLength = extensionDef.byteLength || 0;
        const count = extensionDef.count;
        const stride = extensionDef.byteStride;
        const source = new Uint8Array(res, byteOffset, byteLength);
        if (decoder.decodeGltfBufferAsync) {
          return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function(res2) {
            return res2.buffer;
          });
        } else {
          return decoder.ready.then(function() {
            const result = new ArrayBuffer(count * stride);
            decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter);
            return result;
          });
        }
      });
    } else {
      return null;
    }
  }
};
var GLTFMeshGpuInstancing2 = class {
  constructor(parser) {
    this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
    this.parser = parser;
  }
  createNodeMesh(nodeIndex) {
    const json = this.parser.json;
    const nodeDef = json.nodes[nodeIndex];
    if (!nodeDef.extensions || !nodeDef.extensions[this.name] || nodeDef.mesh === void 0) {
      return null;
    }
    const meshDef = json.meshes[nodeDef.mesh];
    for (const primitive of meshDef.primitives) {
      if (primitive.mode !== WEBGL_CONSTANTS2.TRIANGLES && primitive.mode !== WEBGL_CONSTANTS2.TRIANGLE_STRIP && primitive.mode !== WEBGL_CONSTANTS2.TRIANGLE_FAN && primitive.mode !== void 0) {
        return null;
      }
    }
    const extensionDef = nodeDef.extensions[this.name];
    const attributesDef = extensionDef.attributes;
    const pending = [];
    const attributes = {};
    for (const key2 in attributesDef) {
      pending.push(this.parser.getDependency("accessor", attributesDef[key2]).then((accessor) => {
        attributes[key2] = accessor;
        return attributes[key2];
      }));
    }
    if (pending.length < 1) {
      return null;
    }
    pending.push(this.parser.createNodeMesh(nodeIndex));
    return Promise.all(pending).then((results) => {
      const nodeObject = results.pop();
      const meshes = nodeObject.isGroup ? nodeObject.children : [nodeObject];
      const count = results[0].count;
      const instancedMeshes = [];
      for (const mesh of meshes) {
        const m = new Matrix4();
        const p = new Vector3();
        const q2 = new Quaternion();
        const s = new Vector3(1, 1, 1);
        const instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count);
        for (let i = 0; i < count; i++) {
          if (attributes.TRANSLATION) {
            p.fromBufferAttribute(attributes.TRANSLATION, i);
          }
          if (attributes.ROTATION) {
            q2.fromBufferAttribute(attributes.ROTATION, i);
          }
          if (attributes.SCALE) {
            s.fromBufferAttribute(attributes.SCALE, i);
          }
          instancedMesh.setMatrixAt(i, m.compose(p, q2, s));
        }
        for (const attributeName in attributes) {
          if (attributeName === "_COLOR_0") {
            const attr = attributes[attributeName];
            instancedMesh.instanceColor = new InstancedBufferAttribute(attr.array, attr.itemSize, attr.normalized);
          } else if (attributeName !== "TRANSLATION" && attributeName !== "ROTATION" && attributeName !== "SCALE") {
            mesh.geometry.setAttribute(attributeName, attributes[attributeName]);
          }
        }
        Object3D.prototype.copy.call(instancedMesh, mesh);
        this.parser.assignFinalMaterial(instancedMesh);
        instancedMeshes.push(instancedMesh);
      }
      if (nodeObject.isGroup) {
        nodeObject.clear();
        nodeObject.add(...instancedMeshes);
        return nodeObject;
      }
      return instancedMeshes[0];
    });
  }
};
var BINARY_EXTENSION_HEADER_MAGIC = "glTF";
var BINARY_EXTENSION_HEADER_LENGTH = 12;
var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 1313821514, BIN: 5130562 };
var GLTFBinaryExtension = class {
  constructor(data2) {
    this.name = EXTENSIONS.KHR_BINARY_GLTF;
    this.content = null;
    this.body = null;
    const headerView = new DataView(data2, 0, BINARY_EXTENSION_HEADER_LENGTH);
    const textDecoder = new TextDecoder();
    this.header = {
      magic: textDecoder.decode(new Uint8Array(data2.slice(0, 4))),
      version: headerView.getUint32(4, true),
      length: headerView.getUint32(8, true)
    };
    if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
      throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");
    } else if (this.header.version < 2) {
      throw new Error("THREE.GLTFLoader: Legacy binary file detected.");
    }
    const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
    const chunkView = new DataView(data2, BINARY_EXTENSION_HEADER_LENGTH);
    let chunkIndex = 0;
    while (chunkIndex < chunkContentsLength) {
      const chunkLength = chunkView.getUint32(chunkIndex, true);
      chunkIndex += 4;
      const chunkType = chunkView.getUint32(chunkIndex, true);
      chunkIndex += 4;
      if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
        const contentArray = new Uint8Array(data2, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
        this.content = textDecoder.decode(contentArray);
      } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
        const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
        this.body = data2.slice(byteOffset, byteOffset + chunkLength);
      }
      chunkIndex += chunkLength;
    }
    if (this.content === null) {
      throw new Error("THREE.GLTFLoader: JSON content not found.");
    }
  }
};
var GLTFDracoMeshCompressionExtension = class {
  constructor(json, dracoLoader) {
    if (!dracoLoader) {
      throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");
    }
    this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
    this.json = json;
    this.dracoLoader = dracoLoader;
    this.dracoLoader.preload();
  }
  decodePrimitive(primitive, parser) {
    const json = this.json;
    const dracoLoader = this.dracoLoader;
    const bufferViewIndex = primitive.extensions[this.name].bufferView;
    const gltfAttributeMap = primitive.extensions[this.name].attributes;
    const threeAttributeMap = {};
    const attributeNormalizedMap = {};
    const attributeTypeMap = {};
    for (const attributeName in gltfAttributeMap) {
      const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
      threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
    }
    for (const attributeName in primitive.attributes) {
      const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
      if (gltfAttributeMap[attributeName] !== void 0) {
        const accessorDef = json.accessors[primitive.attributes[attributeName]];
        const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
        attributeTypeMap[threeAttributeName] = componentType.name;
        attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
      }
    }
    return parser.getDependency("bufferView", bufferViewIndex).then(function(bufferView) {
      return new Promise(function(resolve, reject2) {
        dracoLoader.decodeDracoFile(bufferView, function(geometry) {
          for (const attributeName in geometry.attributes) {
            const attribute = geometry.attributes[attributeName];
            const normalized = attributeNormalizedMap[attributeName];
            if (normalized !== void 0) attribute.normalized = normalized;
          }
          resolve(geometry);
        }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace, reject2);
      });
    });
  }
};
var GLTFTextureTransformExtension = class {
  constructor() {
    this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  }
  extendTexture(texture, transform2) {
    if ((transform2.texCoord === void 0 || transform2.texCoord === texture.channel) && transform2.offset === void 0 && transform2.rotation === void 0 && transform2.scale === void 0) {
      return texture;
    }
    texture = texture.clone();
    if (transform2.texCoord !== void 0) {
      texture.channel = transform2.texCoord;
    }
    if (transform2.offset !== void 0) {
      texture.offset.fromArray(transform2.offset);
    }
    if (transform2.rotation !== void 0) {
      texture.rotation = transform2.rotation;
    }
    if (transform2.scale !== void 0) {
      texture.repeat.fromArray(transform2.scale);
    }
    texture.needsUpdate = true;
    return texture;
  }
};
var GLTFMeshQuantizationExtension = class {
  constructor() {
    this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  }
};
var GLTFCubicSplineInterpolant = class extends Interpolant {
  constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
    super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  }
  copySampleValue_(index2) {
    const result = this.resultBuffer, values2 = this.sampleValues, valueSize = this.valueSize, offset = index2 * valueSize * 3 + valueSize;
    for (let i = 0; i !== valueSize; i++) {
      result[i] = values2[offset + i];
    }
    return result;
  }
  interpolate_(i1, t0, t3, t1) {
    const result = this.resultBuffer;
    const values2 = this.sampleValues;
    const stride = this.valueSize;
    const stride2 = stride * 2;
    const stride3 = stride * 3;
    const td2 = t1 - t0;
    const p = (t3 - t0) / td2;
    const pp = p * p;
    const ppp = pp * p;
    const offset1 = i1 * stride3;
    const offset0 = offset1 - stride3;
    const s2 = -2 * ppp + 3 * pp;
    const s3 = ppp - pp;
    const s0 = 1 - s2;
    const s1 = s3 - pp + p;
    for (let i = 0; i !== stride; i++) {
      const p0 = values2[offset0 + i + stride];
      const m0 = values2[offset0 + i + stride2] * td2;
      const p1 = values2[offset1 + i + stride];
      const m1 = values2[offset1 + i] * td2;
      result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
    }
    return result;
  }
};
var _quaternion4 = new Quaternion();
var GLTFCubicSplineQuaternionInterpolant = class extends GLTFCubicSplineInterpolant {
  interpolate_(i1, t0, t3, t1) {
    const result = super.interpolate_(i1, t0, t3, t1);
    _quaternion4.fromArray(result).normalize().toArray(result);
    return result;
  }
};
var WEBGL_CONSTANTS2 = {
  FLOAT: 5126,
  //FLOAT_MAT2: 35674,
  FLOAT_MAT3: 35675,
  FLOAT_MAT4: 35676,
  FLOAT_VEC2: 35664,
  FLOAT_VEC3: 35665,
  FLOAT_VEC4: 35666,
  LINEAR: 9729,
  REPEAT: 10497,
  SAMPLER_2D: 35678,
  POINTS: 0,
  LINES: 1,
  LINE_LOOP: 2,
  LINE_STRIP: 3,
  TRIANGLES: 4,
  TRIANGLE_STRIP: 5,
  TRIANGLE_FAN: 6,
  UNSIGNED_BYTE: 5121,
  UNSIGNED_SHORT: 5123
};
var WEBGL_COMPONENT_TYPES = {
  5120: Int8Array,
  5121: Uint8Array,
  5122: Int16Array,
  5123: Uint16Array,
  5125: Uint32Array,
  5126: Float32Array
};
var WEBGL_FILTERS = {
  9728: NearestFilter,
  9729: LinearFilter,
  9984: NearestMipmapNearestFilter,
  9985: LinearMipmapNearestFilter,
  9986: NearestMipmapLinearFilter,
  9987: LinearMipmapLinearFilter
};
var WEBGL_WRAPPINGS = {
  33071: ClampToEdgeWrapping,
  33648: MirroredRepeatWrapping,
  10497: RepeatWrapping
};
var WEBGL_TYPE_SIZES = {
  "SCALAR": 1,
  "VEC2": 2,
  "VEC3": 3,
  "VEC4": 4,
  "MAT2": 4,
  "MAT3": 9,
  "MAT4": 16
};
var ATTRIBUTES = {
  POSITION: "position",
  NORMAL: "normal",
  TANGENT: "tangent",
  TEXCOORD_0: "uv",
  TEXCOORD_1: "uv1",
  TEXCOORD_2: "uv2",
  TEXCOORD_3: "uv3",
  COLOR_0: "color",
  WEIGHTS_0: "skinWeight",
  JOINTS_0: "skinIndex"
};
var PATH_PROPERTIES2 = {
  scale: "scale",
  translation: "position",
  rotation: "quaternion",
  weights: "morphTargetInfluences"
};
var INTERPOLATION = {
  CUBICSPLINE: void 0,
  // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  // keyframe track will be initialized with a default interpolation type, then modified.
  LINEAR: InterpolateLinear,
  STEP: InterpolateDiscrete
};
var ALPHA_MODES = {
  OPAQUE: "OPAQUE",
  MASK: "MASK",
  BLEND: "BLEND"
};
function createDefaultMaterial(cache) {
  if (cache["DefaultMaterial"] === void 0) {
    cache["DefaultMaterial"] = new MeshStandardMaterial({
      color: 16777215,
      emissive: 0,
      metalness: 1,
      roughness: 1,
      transparent: false,
      depthTest: true,
      side: FrontSide
    });
  }
  return cache["DefaultMaterial"];
}
function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  for (const name2 in objectDef.extensions) {
    if (knownExtensions[name2] === void 0) {
      object.userData.gltfExtensions = object.userData.gltfExtensions || {};
      object.userData.gltfExtensions[name2] = objectDef.extensions[name2];
    }
  }
}
function assignExtrasToUserData(object, gltfDef) {
  if (gltfDef.extras !== void 0) {
    if (typeof gltfDef.extras === "object") {
      Object.assign(object.userData, gltfDef.extras);
    } else {
      console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, " + gltfDef.extras);
    }
  }
}
function addMorphTargets(geometry, targets, parser) {
  let hasMorphPosition = false;
  let hasMorphNormal = false;
  let hasMorphColor = false;
  for (let i = 0, il = targets.length; i < il; i++) {
    const target = targets[i];
    if (target.POSITION !== void 0) hasMorphPosition = true;
    if (target.NORMAL !== void 0) hasMorphNormal = true;
    if (target.COLOR_0 !== void 0) hasMorphColor = true;
    if (hasMorphPosition && hasMorphNormal && hasMorphColor) break;
  }
  if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) return Promise.resolve(geometry);
  const pendingPositionAccessors = [];
  const pendingNormalAccessors = [];
  const pendingColorAccessors = [];
  for (let i = 0, il = targets.length; i < il; i++) {
    const target = targets[i];
    if (hasMorphPosition) {
      const pendingAccessor = target.POSITION !== void 0 ? parser.getDependency("accessor", target.POSITION) : geometry.attributes.position;
      pendingPositionAccessors.push(pendingAccessor);
    }
    if (hasMorphNormal) {
      const pendingAccessor = target.NORMAL !== void 0 ? parser.getDependency("accessor", target.NORMAL) : geometry.attributes.normal;
      pendingNormalAccessors.push(pendingAccessor);
    }
    if (hasMorphColor) {
      const pendingAccessor = target.COLOR_0 !== void 0 ? parser.getDependency("accessor", target.COLOR_0) : geometry.attributes.color;
      pendingColorAccessors.push(pendingAccessor);
    }
  }
  return Promise.all([
    Promise.all(pendingPositionAccessors),
    Promise.all(pendingNormalAccessors),
    Promise.all(pendingColorAccessors)
  ]).then(function(accessors) {
    const morphPositions = accessors[0];
    const morphNormals = accessors[1];
    const morphColors = accessors[2];
    if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
    if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
    if (hasMorphColor) geometry.morphAttributes.color = morphColors;
    geometry.morphTargetsRelative = true;
    return geometry;
  });
}
function updateMorphTargets(mesh, meshDef) {
  mesh.updateMorphTargets();
  if (meshDef.weights !== void 0) {
    for (let i = 0, il = meshDef.weights.length; i < il; i++) {
      mesh.morphTargetInfluences[i] = meshDef.weights[i];
    }
  }
  if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
    const targetNames = meshDef.extras.targetNames;
    if (mesh.morphTargetInfluences.length === targetNames.length) {
      mesh.morphTargetDictionary = {};
      for (let i = 0, il = targetNames.length; i < il; i++) {
        mesh.morphTargetDictionary[targetNames[i]] = i;
      }
    } else {
      console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.");
    }
  }
}
function createPrimitiveKey(primitiveDef) {
  let geometryKey;
  const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  if (dracoExtension) {
    geometryKey = "draco:" + dracoExtension.bufferView + ":" + dracoExtension.indices + ":" + createAttributesKey(dracoExtension.attributes);
  } else {
    geometryKey = primitiveDef.indices + ":" + createAttributesKey(primitiveDef.attributes) + ":" + primitiveDef.mode;
  }
  if (primitiveDef.targets !== void 0) {
    for (let i = 0, il = primitiveDef.targets.length; i < il; i++) {
      geometryKey += ":" + createAttributesKey(primitiveDef.targets[i]);
    }
  }
  return geometryKey;
}
function createAttributesKey(attributes) {
  let attributesKey = "";
  const keys2 = Object.keys(attributes).sort();
  for (let i = 0, il = keys2.length; i < il; i++) {
    attributesKey += keys2[i] + ":" + attributes[keys2[i]] + ";";
  }
  return attributesKey;
}
function getNormalizedComponentScale(constructor) {
  switch (constructor) {
    case Int8Array:
      return 1 / 127;
    case Uint8Array:
      return 1 / 255;
    case Int16Array:
      return 1 / 32767;
    case Uint16Array:
      return 1 / 65535;
    default:
      throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.");
  }
}
function getImageURIMimeType(uri) {
  if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) return "image/jpeg";
  if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) return "image/webp";
  if (uri.search(/\.ktx2($|\?)/i) > 0 || uri.search(/^data\:image\/ktx2/) === 0) return "image/ktx2";
  return "image/png";
}
var _identityMatrix = new Matrix4();
var GLTFParser = class {
  constructor(json = {}, options = {}) {
    this.json = json;
    this.extensions = {};
    this.plugins = {};
    this.options = options;
    this.cache = new GLTFRegistry();
    this.associations = /* @__PURE__ */ new Map();
    this.primitiveCache = {};
    this.nodeCache = {};
    this.meshCache = { refs: {}, uses: {} };
    this.cameraCache = { refs: {}, uses: {} };
    this.lightCache = { refs: {}, uses: {} };
    this.sourceCache = {};
    this.textureCache = {};
    this.nodeNamesUsed = {};
    let isSafari2 = false;
    let safariVersion = -1;
    let isFirefox = false;
    let firefoxVersion = -1;
    if (typeof navigator !== "undefined") {
      const userAgent = navigator.userAgent;
      isSafari2 = /^((?!chrome|android).)*safari/i.test(userAgent) === true;
      const safariMatch = userAgent.match(/Version\/(\d+)/);
      safariVersion = isSafari2 && safariMatch ? parseInt(safariMatch[1], 10) : -1;
      isFirefox = userAgent.indexOf("Firefox") > -1;
      firefoxVersion = isFirefox ? userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1;
    }
    if (typeof createImageBitmap === "undefined" || isSafari2 && safariVersion < 17 || isFirefox && firefoxVersion < 98) {
      this.textureLoader = new TextureLoader(this.options.manager);
    } else {
      this.textureLoader = new ImageBitmapLoader(this.options.manager);
    }
    this.textureLoader.setCrossOrigin(this.options.crossOrigin);
    this.textureLoader.setRequestHeader(this.options.requestHeader);
    this.fileLoader = new FileLoader(this.options.manager);
    this.fileLoader.setResponseType("arraybuffer");
    if (this.options.crossOrigin === "use-credentials") {
      this.fileLoader.setWithCredentials(true);
    }
  }
  setExtensions(extensions) {
    this.extensions = extensions;
  }
  setPlugins(plugins) {
    this.plugins = plugins;
  }
  parse(onLoad, onError) {
    const parser = this;
    const json = this.json;
    const extensions = this.extensions;
    this.cache.removeAll();
    this.nodeCache = {};
    this._invokeAll(function(ext) {
      return ext._markDefs && ext._markDefs();
    });
    Promise.all(this._invokeAll(function(ext) {
      return ext.beforeRoot && ext.beforeRoot();
    })).then(function() {
      return Promise.all([
        parser.getDependencies("scene"),
        parser.getDependencies("animation"),
        parser.getDependencies("camera")
      ]);
    }).then(function(dependencies) {
      const result = {
        scene: dependencies[0][json.scene || 0],
        scenes: dependencies[0],
        animations: dependencies[1],
        cameras: dependencies[2],
        asset: json.asset,
        parser,
        userData: {}
      };
      addUnknownExtensionsToUserData(extensions, result, json);
      assignExtrasToUserData(result, json);
      return Promise.all(parser._invokeAll(function(ext) {
        return ext.afterRoot && ext.afterRoot(result);
      })).then(function() {
        for (const scene of result.scenes) {
          scene.updateMatrixWorld();
        }
        onLoad(result);
      });
    }).catch(onError);
  }
  /**
   * Marks the special nodes/meshes in json for efficient parse.
   *
   * @private
   */
  _markDefs() {
    const nodeDefs = this.json.nodes || [];
    const skinDefs = this.json.skins || [];
    const meshDefs = this.json.meshes || [];
    for (let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
      const joints = skinDefs[skinIndex].joints;
      for (let i = 0, il = joints.length; i < il; i++) {
        nodeDefs[joints[i]].isBone = true;
      }
    }
    for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
      const nodeDef = nodeDefs[nodeIndex];
      if (nodeDef.mesh !== void 0) {
        this._addNodeRef(this.meshCache, nodeDef.mesh);
        if (nodeDef.skin !== void 0) {
          meshDefs[nodeDef.mesh].isSkinnedMesh = true;
        }
      }
      if (nodeDef.camera !== void 0) {
        this._addNodeRef(this.cameraCache, nodeDef.camera);
      }
    }
  }
  /**
   * Counts references to shared node / Object3D resources. These resources
   * can be reused, or "instantiated", at multiple nodes in the scene
   * hierarchy. Mesh, Camera, and Light instances are instantiated and must
   * be marked. Non-scenegraph resources (like Materials, Geometries, and
   * Textures) can be reused directly and are not marked here.
   *
   * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
   *
   * @private
   * @param {Object} cache
   * @param {Object3D} index
   */
  _addNodeRef(cache, index2) {
    if (index2 === void 0) return;
    if (cache.refs[index2] === void 0) {
      cache.refs[index2] = cache.uses[index2] = 0;
    }
    cache.refs[index2]++;
  }
  /**
   * Returns a reference to a shared resource, cloning it if necessary.
   *
   * @private
   * @param {Object} cache
   * @param {number} index
   * @param {Object} object
   * @return {Object}
   */
  _getNodeRef(cache, index2, object) {
    if (cache.refs[index2] <= 1) return object;
    const ref = object.clone();
    const updateMappings = (original, clone2) => {
      const mappings = this.associations.get(original);
      if (mappings != null) {
        this.associations.set(clone2, mappings);
      }
      for (const [i, child] of original.children.entries()) {
        updateMappings(child, clone2.children[i]);
      }
    };
    updateMappings(object, ref);
    ref.name += "_instance_" + cache.uses[index2]++;
    return ref;
  }
  _invokeOne(func) {
    const extensions = Object.values(this.plugins);
    extensions.push(this);
    for (let i = 0; i < extensions.length; i++) {
      const result = func(extensions[i]);
      if (result) return result;
    }
    return null;
  }
  _invokeAll(func) {
    const extensions = Object.values(this.plugins);
    extensions.unshift(this);
    const pending = [];
    for (let i = 0; i < extensions.length; i++) {
      const result = func(extensions[i]);
      if (result) pending.push(result);
    }
    return pending;
  }
  /**
   * Requests the specified dependency asynchronously, with caching.
   *
   * @private
   * @param {string} type
   * @param {number} index
   * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
   */
  getDependency(type, index2) {
    const cacheKey = type + ":" + index2;
    let dependency = this.cache.get(cacheKey);
    if (!dependency) {
      switch (type) {
        case "scene":
          dependency = this.loadScene(index2);
          break;
        case "node":
          dependency = this._invokeOne(function(ext) {
            return ext.loadNode && ext.loadNode(index2);
          });
          break;
        case "mesh":
          dependency = this._invokeOne(function(ext) {
            return ext.loadMesh && ext.loadMesh(index2);
          });
          break;
        case "accessor":
          dependency = this.loadAccessor(index2);
          break;
        case "bufferView":
          dependency = this._invokeOne(function(ext) {
            return ext.loadBufferView && ext.loadBufferView(index2);
          });
          break;
        case "buffer":
          dependency = this.loadBuffer(index2);
          break;
        case "material":
          dependency = this._invokeOne(function(ext) {
            return ext.loadMaterial && ext.loadMaterial(index2);
          });
          break;
        case "texture":
          dependency = this._invokeOne(function(ext) {
            return ext.loadTexture && ext.loadTexture(index2);
          });
          break;
        case "skin":
          dependency = this.loadSkin(index2);
          break;
        case "animation":
          dependency = this._invokeOne(function(ext) {
            return ext.loadAnimation && ext.loadAnimation(index2);
          });
          break;
        case "camera":
          dependency = this.loadCamera(index2);
          break;
        default:
          dependency = this._invokeOne(function(ext) {
            return ext != this && ext.getDependency && ext.getDependency(type, index2);
          });
          if (!dependency) {
            throw new Error("Unknown type: " + type);
          }
          break;
      }
      this.cache.add(cacheKey, dependency);
    }
    return dependency;
  }
  /**
   * Requests all dependencies of the specified type asynchronously, with caching.
   *
   * @private
   * @param {string} type
   * @return {Promise<Array<Object>>}
   */
  getDependencies(type) {
    let dependencies = this.cache.get(type);
    if (!dependencies) {
      const parser = this;
      const defs = this.json[type + (type === "mesh" ? "es" : "s")] || [];
      dependencies = Promise.all(defs.map(function(def, index2) {
        return parser.getDependency(type, index2);
      }));
      this.cache.add(type, dependencies);
    }
    return dependencies;
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
   *
   * @private
   * @param {number} bufferIndex
   * @return {Promise<ArrayBuffer>}
   */
  loadBuffer(bufferIndex) {
    const bufferDef = this.json.buffers[bufferIndex];
    const loader = this.fileLoader;
    if (bufferDef.type && bufferDef.type !== "arraybuffer") {
      throw new Error("THREE.GLTFLoader: " + bufferDef.type + " buffer type is not supported.");
    }
    if (bufferDef.uri === void 0 && bufferIndex === 0) {
      return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
    }
    const options = this.options;
    return new Promise(function(resolve, reject2) {
      loader.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, void 0, function() {
        reject2(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
      });
    });
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
   *
   * @private
   * @param {number} bufferViewIndex
   * @return {Promise<ArrayBuffer>}
   */
  loadBufferView(bufferViewIndex) {
    const bufferViewDef = this.json.bufferViews[bufferViewIndex];
    return this.getDependency("buffer", bufferViewDef.buffer).then(function(buffer) {
      const byteLength = bufferViewDef.byteLength || 0;
      const byteOffset = bufferViewDef.byteOffset || 0;
      return buffer.slice(byteOffset, byteOffset + byteLength);
    });
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
   *
   * @private
   * @param {number} accessorIndex
   * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
   */
  loadAccessor(accessorIndex) {
    const parser = this;
    const json = this.json;
    const accessorDef = this.json.accessors[accessorIndex];
    if (accessorDef.bufferView === void 0 && accessorDef.sparse === void 0) {
      const itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
      const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
      const normalized = accessorDef.normalized === true;
      const array = new TypedArray(accessorDef.count * itemSize);
      return Promise.resolve(new BufferAttribute(array, itemSize, normalized));
    }
    const pendingBufferViews = [];
    if (accessorDef.bufferView !== void 0) {
      pendingBufferViews.push(this.getDependency("bufferView", accessorDef.bufferView));
    } else {
      pendingBufferViews.push(null);
    }
    if (accessorDef.sparse !== void 0) {
      pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.indices.bufferView));
      pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.values.bufferView));
    }
    return Promise.all(pendingBufferViews).then(function(bufferViews) {
      const bufferView = bufferViews[0];
      const itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
      const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
      const elementBytes = TypedArray.BYTES_PER_ELEMENT;
      const itemBytes = elementBytes * itemSize;
      const byteOffset = accessorDef.byteOffset || 0;
      const byteStride = accessorDef.bufferView !== void 0 ? json.bufferViews[accessorDef.bufferView].byteStride : void 0;
      const normalized = accessorDef.normalized === true;
      let array, bufferAttribute;
      if (byteStride && byteStride !== itemBytes) {
        const ibSlice = Math.floor(byteOffset / byteStride);
        const ibCacheKey = "InterleavedBuffer:" + accessorDef.bufferView + ":" + accessorDef.componentType + ":" + ibSlice + ":" + accessorDef.count;
        let ib = parser.cache.get(ibCacheKey);
        if (!ib) {
          array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes);
          ib = new InterleavedBuffer(array, byteStride / elementBytes);
          parser.cache.add(ibCacheKey, ib);
        }
        bufferAttribute = new InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
      } else {
        if (bufferView === null) {
          array = new TypedArray(accessorDef.count * itemSize);
        } else {
          array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
        }
        bufferAttribute = new BufferAttribute(array, itemSize, normalized);
      }
      if (accessorDef.sparse !== void 0) {
        const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
        const TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
        const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
        const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
        const sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
        const sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
        if (bufferView !== null) {
          bufferAttribute = new BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
        }
        bufferAttribute.normalized = false;
        for (let i = 0, il = sparseIndices.length; i < il; i++) {
          const index2 = sparseIndices[i];
          bufferAttribute.setX(index2, sparseValues[i * itemSize]);
          if (itemSize >= 2) bufferAttribute.setY(index2, sparseValues[i * itemSize + 1]);
          if (itemSize >= 3) bufferAttribute.setZ(index2, sparseValues[i * itemSize + 2]);
          if (itemSize >= 4) bufferAttribute.setW(index2, sparseValues[i * itemSize + 3]);
          if (itemSize >= 5) throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.");
        }
        bufferAttribute.normalized = normalized;
      }
      return bufferAttribute;
    });
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
   *
   * @private
   * @param {number} textureIndex
   * @return {Promise<THREE.Texture|null>}
   */
  loadTexture(textureIndex) {
    const json = this.json;
    const options = this.options;
    const textureDef = json.textures[textureIndex];
    const sourceIndex = textureDef.source;
    const sourceDef = json.images[sourceIndex];
    let loader = this.textureLoader;
    if (sourceDef.uri) {
      const handler = options.manager.getHandler(sourceDef.uri);
      if (handler !== null) loader = handler;
    }
    return this.loadTextureImage(textureIndex, sourceIndex, loader);
  }
  loadTextureImage(textureIndex, sourceIndex, loader) {
    const parser = this;
    const json = this.json;
    const textureDef = json.textures[textureIndex];
    const sourceDef = json.images[sourceIndex];
    const cacheKey = (sourceDef.uri || sourceDef.bufferView) + ":" + textureDef.sampler;
    if (this.textureCache[cacheKey]) {
      return this.textureCache[cacheKey];
    }
    const promise = this.loadImageSource(sourceIndex, loader).then(function(texture) {
      texture.flipY = false;
      texture.name = textureDef.name || sourceDef.name || "";
      if (texture.name === "" && typeof sourceDef.uri === "string" && sourceDef.uri.startsWith("data:image/") === false) {
        texture.name = sourceDef.uri;
      }
      const samplers = json.samplers || {};
      const sampler = samplers[textureDef.sampler] || {};
      texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || LinearFilter;
      texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || LinearMipmapLinearFilter;
      texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || RepeatWrapping;
      texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || RepeatWrapping;
      texture.generateMipmaps = !texture.isCompressedTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
      parser.associations.set(texture, { textures: textureIndex });
      return texture;
    }).catch(function() {
      return null;
    });
    this.textureCache[cacheKey] = promise;
    return promise;
  }
  loadImageSource(sourceIndex, loader) {
    const parser = this;
    const json = this.json;
    const options = this.options;
    if (this.sourceCache[sourceIndex] !== void 0) {
      return this.sourceCache[sourceIndex].then((texture) => texture.clone());
    }
    const sourceDef = json.images[sourceIndex];
    const URL2 = self.URL || self.webkitURL;
    let sourceURI = sourceDef.uri || "";
    let isObjectURL = false;
    if (sourceDef.bufferView !== void 0) {
      sourceURI = parser.getDependency("bufferView", sourceDef.bufferView).then(function(bufferView) {
        isObjectURL = true;
        const blob = new Blob([bufferView], { type: sourceDef.mimeType });
        sourceURI = URL2.createObjectURL(blob);
        return sourceURI;
      });
    } else if (sourceDef.uri === void 0) {
      throw new Error("THREE.GLTFLoader: Image " + sourceIndex + " is missing URI and bufferView");
    }
    const promise = Promise.resolve(sourceURI).then(function(sourceURI2) {
      return new Promise(function(resolve, reject2) {
        let onLoad = resolve;
        if (loader.isImageBitmapLoader === true) {
          onLoad = function(imageBitmap) {
            const texture = new Texture(imageBitmap);
            texture.needsUpdate = true;
            resolve(texture);
          };
        }
        loader.load(LoaderUtils.resolveURL(sourceURI2, options.path), onLoad, void 0, reject2);
      });
    }).then(function(texture) {
      if (isObjectURL === true) {
        URL2.revokeObjectURL(sourceURI);
      }
      assignExtrasToUserData(texture, sourceDef);
      texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri);
      return texture;
    }).catch(function(error) {
      console.error("THREE.GLTFLoader: Couldn't load texture", sourceURI);
      throw error;
    });
    this.sourceCache[sourceIndex] = promise;
    return promise;
  }
  /**
   * Asynchronously assigns a texture to the given material parameters.
   *
   * @private
   * @param {Object} materialParams
   * @param {string} mapName
   * @param {Object} mapDef
   * @param {string} [colorSpace]
   * @return {Promise<Texture>}
   */
  assignTexture(materialParams, mapName, mapDef, colorSpace) {
    const parser = this;
    return this.getDependency("texture", mapDef.index).then(function(texture) {
      if (!texture) return null;
      if (mapDef.texCoord !== void 0 && mapDef.texCoord > 0) {
        texture = texture.clone();
        texture.channel = mapDef.texCoord;
      }
      if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
        const transform2 = mapDef.extensions !== void 0 ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : void 0;
        if (transform2) {
          const gltfReference = parser.associations.get(texture);
          texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform2);
          parser.associations.set(texture, gltfReference);
        }
      }
      if (colorSpace !== void 0) {
        texture.colorSpace = colorSpace;
      }
      materialParams[mapName] = texture;
      return texture;
    });
  }
  /**
   * Assigns final material to a Mesh, Line, or Points instance. The instance
   * already has a material (generated from the glTF material options alone)
   * but reuse of the same glTF material may require multiple threejs materials
   * to accommodate different primitive types, defines, etc. New materials will
   * be created if necessary, and reused from a cache.
   *
   * @private
   * @param {Object3D} mesh Mesh, Line, or Points instance.
   */
  assignFinalMaterial(mesh) {
    const geometry = mesh.geometry;
    let material = mesh.material;
    const useDerivativeTangents = geometry.attributes.tangent === void 0;
    const useVertexColors = geometry.attributes.color !== void 0;
    const useFlatShading = geometry.attributes.normal === void 0;
    if (mesh.isPoints) {
      const cacheKey = "PointsMaterial:" + material.uuid;
      let pointsMaterial = this.cache.get(cacheKey);
      if (!pointsMaterial) {
        pointsMaterial = new PointsMaterial();
        Material.prototype.copy.call(pointsMaterial, material);
        pointsMaterial.color.copy(material.color);
        pointsMaterial.map = material.map;
        pointsMaterial.sizeAttenuation = false;
        this.cache.add(cacheKey, pointsMaterial);
      }
      material = pointsMaterial;
    } else if (mesh.isLine) {
      const cacheKey = "LineBasicMaterial:" + material.uuid;
      let lineMaterial = this.cache.get(cacheKey);
      if (!lineMaterial) {
        lineMaterial = new LineBasicMaterial();
        Material.prototype.copy.call(lineMaterial, material);
        lineMaterial.color.copy(material.color);
        lineMaterial.map = material.map;
        this.cache.add(cacheKey, lineMaterial);
      }
      material = lineMaterial;
    }
    if (useDerivativeTangents || useVertexColors || useFlatShading) {
      let cacheKey = "ClonedMaterial:" + material.uuid + ":";
      if (useDerivativeTangents) cacheKey += "derivative-tangents:";
      if (useVertexColors) cacheKey += "vertex-colors:";
      if (useFlatShading) cacheKey += "flat-shading:";
      let cachedMaterial = this.cache.get(cacheKey);
      if (!cachedMaterial) {
        cachedMaterial = material.clone();
        if (useVertexColors) cachedMaterial.vertexColors = true;
        if (useFlatShading) cachedMaterial.flatShading = true;
        if (useDerivativeTangents) {
          if (cachedMaterial.normalScale) cachedMaterial.normalScale.y *= -1;
          if (cachedMaterial.clearcoatNormalScale) cachedMaterial.clearcoatNormalScale.y *= -1;
        }
        this.cache.add(cacheKey, cachedMaterial);
        this.associations.set(cachedMaterial, this.associations.get(material));
      }
      material = cachedMaterial;
    }
    mesh.material = material;
  }
  getMaterialType() {
    return MeshStandardMaterial;
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
   *
   * @private
   * @param {number} materialIndex
   * @return {Promise<Material>}
   */
  loadMaterial(materialIndex) {
    const parser = this;
    const json = this.json;
    const extensions = this.extensions;
    const materialDef = json.materials[materialIndex];
    let materialType;
    const materialParams = {};
    const materialExtensions = materialDef.extensions || {};
    const pending = [];
    if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
      const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
      materialType = kmuExtension.getMaterialType();
      pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
    } else {
      const metallicRoughness = materialDef.pbrMetallicRoughness || {};
      materialParams.color = new Color(1, 1, 1);
      materialParams.opacity = 1;
      if (Array.isArray(metallicRoughness.baseColorFactor)) {
        const array = metallicRoughness.baseColorFactor;
        materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace);
        materialParams.opacity = array[3];
      }
      if (metallicRoughness.baseColorTexture !== void 0) {
        pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace));
      }
      materialParams.metalness = metallicRoughness.metallicFactor !== void 0 ? metallicRoughness.metallicFactor : 1;
      materialParams.roughness = metallicRoughness.roughnessFactor !== void 0 ? metallicRoughness.roughnessFactor : 1;
      if (metallicRoughness.metallicRoughnessTexture !== void 0) {
        pending.push(parser.assignTexture(materialParams, "metalnessMap", metallicRoughness.metallicRoughnessTexture));
        pending.push(parser.assignTexture(materialParams, "roughnessMap", metallicRoughness.metallicRoughnessTexture));
      }
      materialType = this._invokeOne(function(ext) {
        return ext.getMaterialType && ext.getMaterialType(materialIndex);
      });
      pending.push(Promise.all(this._invokeAll(function(ext) {
        return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams);
      })));
    }
    if (materialDef.doubleSided === true) {
      materialParams.side = DoubleSide;
    }
    const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
    if (alphaMode === ALPHA_MODES.BLEND) {
      materialParams.transparent = true;
      materialParams.depthWrite = false;
    } else {
      materialParams.transparent = false;
      if (alphaMode === ALPHA_MODES.MASK) {
        materialParams.alphaTest = materialDef.alphaCutoff !== void 0 ? materialDef.alphaCutoff : 0.5;
      }
    }
    if (materialDef.normalTexture !== void 0 && materialType !== MeshBasicMaterial) {
      pending.push(parser.assignTexture(materialParams, "normalMap", materialDef.normalTexture));
      materialParams.normalScale = new Vector2(1, 1);
      if (materialDef.normalTexture.scale !== void 0) {
        const scale2 = materialDef.normalTexture.scale;
        materialParams.normalScale.set(scale2, scale2);
      }
    }
    if (materialDef.occlusionTexture !== void 0 && materialType !== MeshBasicMaterial) {
      pending.push(parser.assignTexture(materialParams, "aoMap", materialDef.occlusionTexture));
      if (materialDef.occlusionTexture.strength !== void 0) {
        materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
      }
    }
    if (materialDef.emissiveFactor !== void 0 && materialType !== MeshBasicMaterial) {
      const emissiveFactor = materialDef.emissiveFactor;
      materialParams.emissive = new Color().setRGB(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2], LinearSRGBColorSpace);
    }
    if (materialDef.emissiveTexture !== void 0 && materialType !== MeshBasicMaterial) {
      pending.push(parser.assignTexture(materialParams, "emissiveMap", materialDef.emissiveTexture, SRGBColorSpace));
    }
    return Promise.all(pending).then(function() {
      const material = new materialType(materialParams);
      if (materialDef.name) material.name = materialDef.name;
      assignExtrasToUserData(material, materialDef);
      parser.associations.set(material, { materials: materialIndex });
      if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
      return material;
    });
  }
  /**
   * When Object3D instances are targeted by animation, they need unique names.
   *
   * @private
   * @param {string} originalName
   * @return {string}
   */
  createUniqueName(originalName) {
    const sanitizedName = PropertyBinding.sanitizeNodeName(originalName || "");
    if (sanitizedName in this.nodeNamesUsed) {
      return sanitizedName + "_" + ++this.nodeNamesUsed[sanitizedName];
    } else {
      this.nodeNamesUsed[sanitizedName] = 0;
      return sanitizedName;
    }
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
   *
   * Creates BufferGeometries from primitives.
   *
   * @private
   * @param {Array<GLTF.Primitive>} primitives
   * @return {Promise<Array<BufferGeometry>>}
   */
  loadGeometries(primitives) {
    const parser = this;
    const extensions = this.extensions;
    const cache = this.primitiveCache;
    function createDracoPrimitive(primitive) {
      return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function(geometry) {
        return addPrimitiveAttributes(geometry, primitive, parser);
      });
    }
    const pending = [];
    for (let i = 0, il = primitives.length; i < il; i++) {
      const primitive = primitives[i];
      const cacheKey = createPrimitiveKey(primitive);
      const cached = cache[cacheKey];
      if (cached) {
        pending.push(cached.promise);
      } else {
        let geometryPromise;
        if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
          geometryPromise = createDracoPrimitive(primitive);
        } else {
          geometryPromise = addPrimitiveAttributes(new BufferGeometry(), primitive, parser);
        }
        cache[cacheKey] = { primitive, promise: geometryPromise };
        pending.push(geometryPromise);
      }
    }
    return Promise.all(pending);
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
   *
   * @private
   * @param {number} meshIndex
   * @return {Promise<Group|Mesh|SkinnedMesh|Line|Points>}
   */
  loadMesh(meshIndex) {
    const parser = this;
    const json = this.json;
    const extensions = this.extensions;
    const meshDef = json.meshes[meshIndex];
    const primitives = meshDef.primitives;
    const pending = [];
    for (let i = 0, il = primitives.length; i < il; i++) {
      const material = primitives[i].material === void 0 ? createDefaultMaterial(this.cache) : this.getDependency("material", primitives[i].material);
      pending.push(material);
    }
    pending.push(parser.loadGeometries(primitives));
    return Promise.all(pending).then(function(results) {
      const materials = results.slice(0, results.length - 1);
      const geometries = results[results.length - 1];
      const meshes = [];
      for (let i = 0, il = geometries.length; i < il; i++) {
        const geometry = geometries[i];
        const primitive = primitives[i];
        let mesh;
        const material = materials[i];
        if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLES || primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_FAN || primitive.mode === void 0) {
          mesh = meshDef.isSkinnedMesh === true ? new SkinnedMesh(geometry, material) : new Mesh(geometry, material);
          if (mesh.isSkinnedMesh === true) {
            mesh.normalizeSkinWeights();
          }
          if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_STRIP) {
            mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleStripDrawMode);
          } else if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_FAN) {
            mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleFanDrawMode);
          }
        } else if (primitive.mode === WEBGL_CONSTANTS2.LINES) {
          mesh = new LineSegments(geometry, material);
        } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_STRIP) {
          mesh = new Line(geometry, material);
        } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_LOOP) {
          mesh = new LineLoop(geometry, material);
        } else if (primitive.mode === WEBGL_CONSTANTS2.POINTS) {
          mesh = new Points(geometry, material);
        } else {
          throw new Error("THREE.GLTFLoader: Primitive mode unsupported: " + primitive.mode);
        }
        if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
          updateMorphTargets(mesh, meshDef);
        }
        mesh.name = parser.createUniqueName(meshDef.name || "mesh_" + meshIndex);
        assignExtrasToUserData(mesh, meshDef);
        if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive);
        parser.assignFinalMaterial(mesh);
        meshes.push(mesh);
      }
      for (let i = 0, il = meshes.length; i < il; i++) {
        parser.associations.set(meshes[i], {
          meshes: meshIndex,
          primitives: i
        });
      }
      if (meshes.length === 1) {
        if (meshDef.extensions) addUnknownExtensionsToUserData(extensions, meshes[0], meshDef);
        return meshes[0];
      }
      const group = new Group();
      if (meshDef.extensions) addUnknownExtensionsToUserData(extensions, group, meshDef);
      parser.associations.set(group, { meshes: meshIndex });
      for (let i = 0, il = meshes.length; i < il; i++) {
        group.add(meshes[i]);
      }
      return group;
    });
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
   *
   * @private
   * @param {number} cameraIndex
   * @return {Promise<THREE.Camera>}
   */
  loadCamera(cameraIndex) {
    let camera;
    const cameraDef = this.json.cameras[cameraIndex];
    const params = cameraDef[cameraDef.type];
    if (!params) {
      console.warn("THREE.GLTFLoader: Missing camera parameters.");
      return;
    }
    if (cameraDef.type === "perspective") {
      camera = new PerspectiveCamera(MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
    } else if (cameraDef.type === "orthographic") {
      camera = new OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar);
    }
    if (cameraDef.name) camera.name = this.createUniqueName(cameraDef.name);
    assignExtrasToUserData(camera, cameraDef);
    return Promise.resolve(camera);
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
   *
   * @private
   * @param {number} skinIndex
   * @return {Promise<Skeleton>}
   */
  loadSkin(skinIndex) {
    const skinDef = this.json.skins[skinIndex];
    const pending = [];
    for (let i = 0, il = skinDef.joints.length; i < il; i++) {
      pending.push(this._loadNodeShallow(skinDef.joints[i]));
    }
    if (skinDef.inverseBindMatrices !== void 0) {
      pending.push(this.getDependency("accessor", skinDef.inverseBindMatrices));
    } else {
      pending.push(null);
    }
    return Promise.all(pending).then(function(results) {
      const inverseBindMatrices = results.pop();
      const jointNodes = results;
      const bones = [];
      const boneInverses = [];
      for (let i = 0, il = jointNodes.length; i < il; i++) {
        const jointNode = jointNodes[i];
        if (jointNode) {
          bones.push(jointNode);
          const mat = new Matrix4();
          if (inverseBindMatrices !== null) {
            mat.fromArray(inverseBindMatrices.array, i * 16);
          }
          boneInverses.push(mat);
        } else {
          console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[i]);
        }
      }
      return new Skeleton(bones, boneInverses);
    });
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
   *
   * @private
   * @param {number} animationIndex
   * @return {Promise<AnimationClip>}
   */
  loadAnimation(animationIndex) {
    const json = this.json;
    const parser = this;
    const animationDef = json.animations[animationIndex];
    const animationName = animationDef.name ? animationDef.name : "animation_" + animationIndex;
    const pendingNodes = [];
    const pendingInputAccessors = [];
    const pendingOutputAccessors = [];
    const pendingSamplers = [];
    const pendingTargets = [];
    for (let i = 0, il = animationDef.channels.length; i < il; i++) {
      const channel = animationDef.channels[i];
      const sampler = animationDef.samplers[channel.sampler];
      const target = channel.target;
      const name2 = target.node;
      const input = animationDef.parameters !== void 0 ? animationDef.parameters[sampler.input] : sampler.input;
      const output = animationDef.parameters !== void 0 ? animationDef.parameters[sampler.output] : sampler.output;
      if (target.node === void 0) continue;
      pendingNodes.push(this.getDependency("node", name2));
      pendingInputAccessors.push(this.getDependency("accessor", input));
      pendingOutputAccessors.push(this.getDependency("accessor", output));
      pendingSamplers.push(sampler);
      pendingTargets.push(target);
    }
    return Promise.all([
      Promise.all(pendingNodes),
      Promise.all(pendingInputAccessors),
      Promise.all(pendingOutputAccessors),
      Promise.all(pendingSamplers),
      Promise.all(pendingTargets)
    ]).then(function(dependencies) {
      const nodes = dependencies[0];
      const inputAccessors = dependencies[1];
      const outputAccessors = dependencies[2];
      const samplers = dependencies[3];
      const targets = dependencies[4];
      const tracks = [];
      for (let i = 0, il = nodes.length; i < il; i++) {
        const node = nodes[i];
        const inputAccessor = inputAccessors[i];
        const outputAccessor = outputAccessors[i];
        const sampler = samplers[i];
        const target = targets[i];
        if (node === void 0) continue;
        if (node.updateMatrix) {
          node.updateMatrix();
        }
        const createdTracks = parser._createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target);
        if (createdTracks) {
          for (let k2 = 0; k2 < createdTracks.length; k2++) {
            tracks.push(createdTracks[k2]);
          }
        }
      }
      return new AnimationClip(animationName, void 0, tracks);
    });
  }
  createNodeMesh(nodeIndex) {
    const json = this.json;
    const parser = this;
    const nodeDef = json.nodes[nodeIndex];
    if (nodeDef.mesh === void 0) return null;
    return parser.getDependency("mesh", nodeDef.mesh).then(function(mesh) {
      const node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh);
      if (nodeDef.weights !== void 0) {
        node.traverse(function(o) {
          if (!o.isMesh) return;
          for (let i = 0, il = nodeDef.weights.length; i < il; i++) {
            o.morphTargetInfluences[i] = nodeDef.weights[i];
          }
        });
      }
      return node;
    });
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
   *
   * @private
   * @param {number} nodeIndex
   * @return {Promise<Object3D>}
   */
  loadNode(nodeIndex) {
    const json = this.json;
    const parser = this;
    const nodeDef = json.nodes[nodeIndex];
    const nodePending = parser._loadNodeShallow(nodeIndex);
    const childPending = [];
    const childrenDef = nodeDef.children || [];
    for (let i = 0, il = childrenDef.length; i < il; i++) {
      childPending.push(parser.getDependency("node", childrenDef[i]));
    }
    const skeletonPending = nodeDef.skin === void 0 ? Promise.resolve(null) : parser.getDependency("skin", nodeDef.skin);
    return Promise.all([
      nodePending,
      Promise.all(childPending),
      skeletonPending
    ]).then(function(results) {
      const node = results[0];
      const children = results[1];
      const skeleton = results[2];
      if (skeleton !== null) {
        node.traverse(function(mesh) {
          if (!mesh.isSkinnedMesh) return;
          mesh.bind(skeleton, _identityMatrix);
        });
      }
      for (let i = 0, il = children.length; i < il; i++) {
        node.add(children[i]);
      }
      return node;
    });
  }
  // ._loadNodeShallow() parses a single node.
  // skin and child nodes are created and added in .loadNode() (no '_' prefix).
  _loadNodeShallow(nodeIndex) {
    const json = this.json;
    const extensions = this.extensions;
    const parser = this;
    if (this.nodeCache[nodeIndex] !== void 0) {
      return this.nodeCache[nodeIndex];
    }
    const nodeDef = json.nodes[nodeIndex];
    const nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : "";
    const pending = [];
    const meshPromise = parser._invokeOne(function(ext) {
      return ext.createNodeMesh && ext.createNodeMesh(nodeIndex);
    });
    if (meshPromise) {
      pending.push(meshPromise);
    }
    if (nodeDef.camera !== void 0) {
      pending.push(parser.getDependency("camera", nodeDef.camera).then(function(camera) {
        return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera);
      }));
    }
    parser._invokeAll(function(ext) {
      return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex);
    }).forEach(function(promise) {
      pending.push(promise);
    });
    this.nodeCache[nodeIndex] = Promise.all(pending).then(function(objects) {
      let node;
      if (nodeDef.isBone === true) {
        node = new Bone();
      } else if (objects.length > 1) {
        node = new Group();
      } else if (objects.length === 1) {
        node = objects[0];
      } else {
        node = new Object3D();
      }
      if (node !== objects[0]) {
        for (let i = 0, il = objects.length; i < il; i++) {
          node.add(objects[i]);
        }
      }
      if (nodeDef.name) {
        node.userData.name = nodeDef.name;
        node.name = nodeName;
      }
      assignExtrasToUserData(node, nodeDef);
      if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
      if (nodeDef.matrix !== void 0) {
        const matrix2 = new Matrix4();
        matrix2.fromArray(nodeDef.matrix);
        node.applyMatrix4(matrix2);
      } else {
        if (nodeDef.translation !== void 0) {
          node.position.fromArray(nodeDef.translation);
        }
        if (nodeDef.rotation !== void 0) {
          node.quaternion.fromArray(nodeDef.rotation);
        }
        if (nodeDef.scale !== void 0) {
          node.scale.fromArray(nodeDef.scale);
        }
      }
      if (!parser.associations.has(node)) {
        parser.associations.set(node, {});
      } else if (nodeDef.mesh !== void 0 && parser.meshCache.refs[nodeDef.mesh] > 1) {
        const mapping = parser.associations.get(node);
        parser.associations.set(node, { ...mapping });
      }
      parser.associations.get(node).nodes = nodeIndex;
      return node;
    });
    return this.nodeCache[nodeIndex];
  }
  /**
   * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
   *
   * @private
   * @param {number} sceneIndex
   * @return {Promise<Group>}
   */
  loadScene(sceneIndex) {
    const extensions = this.extensions;
    const sceneDef = this.json.scenes[sceneIndex];
    const parser = this;
    const scene = new Group();
    if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name);
    assignExtrasToUserData(scene, sceneDef);
    if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
    const nodeIds = sceneDef.nodes || [];
    const pending = [];
    for (let i = 0, il = nodeIds.length; i < il; i++) {
      pending.push(parser.getDependency("node", nodeIds[i]));
    }
    return Promise.all(pending).then(function(nodes) {
      for (let i = 0, il = nodes.length; i < il; i++) {
        scene.add(nodes[i]);
      }
      const reduceAssociations = (node) => {
        const reducedAssociations = /* @__PURE__ */ new Map();
        for (const [key2, value2] of parser.associations) {
          if (key2 instanceof Material || key2 instanceof Texture) {
            reducedAssociations.set(key2, value2);
          }
        }
        node.traverse((node2) => {
          const mappings = parser.associations.get(node2);
          if (mappings != null) {
            reducedAssociations.set(node2, mappings);
          }
        });
        return reducedAssociations;
      };
      parser.associations = reduceAssociations(scene);
      return scene;
    });
  }
  _createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target) {
    const tracks = [];
    const targetName = node.name ? node.name : node.uuid;
    const targetNames = [];
    if (PATH_PROPERTIES2[target.path] === PATH_PROPERTIES2.weights) {
      node.traverse(function(object) {
        if (object.morphTargetInfluences) {
          targetNames.push(object.name ? object.name : object.uuid);
        }
      });
    } else {
      targetNames.push(targetName);
    }
    let TypedKeyframeTrack;
    switch (PATH_PROPERTIES2[target.path]) {
      case PATH_PROPERTIES2.weights:
        TypedKeyframeTrack = NumberKeyframeTrack;
        break;
      case PATH_PROPERTIES2.rotation:
        TypedKeyframeTrack = QuaternionKeyframeTrack;
        break;
      case PATH_PROPERTIES2.translation:
      case PATH_PROPERTIES2.scale:
        TypedKeyframeTrack = VectorKeyframeTrack;
        break;
      default:
        switch (outputAccessor.itemSize) {
          case 1:
            TypedKeyframeTrack = NumberKeyframeTrack;
            break;
          case 2:
          case 3:
          default:
            TypedKeyframeTrack = VectorKeyframeTrack;
            break;
        }
        break;
    }
    const interpolation = sampler.interpolation !== void 0 ? INTERPOLATION[sampler.interpolation] : InterpolateLinear;
    const outputArray = this._getArrayFromAccessor(outputAccessor);
    for (let j2 = 0, jl = targetNames.length; j2 < jl; j2++) {
      const track = new TypedKeyframeTrack(
        targetNames[j2] + "." + PATH_PROPERTIES2[target.path],
        inputAccessor.array,
        outputArray,
        interpolation
      );
      if (sampler.interpolation === "CUBICSPLINE") {
        this._createCubicSplineTrackInterpolant(track);
      }
      tracks.push(track);
    }
    return tracks;
  }
  _getArrayFromAccessor(accessor) {
    let outputArray = accessor.array;
    if (accessor.normalized) {
      const scale2 = getNormalizedComponentScale(outputArray.constructor);
      const scaled = new Float32Array(outputArray.length);
      for (let j2 = 0, jl = outputArray.length; j2 < jl; j2++) {
        scaled[j2] = outputArray[j2] * scale2;
      }
      outputArray = scaled;
    }
    return outputArray;
  }
  _createCubicSplineTrackInterpolant(track) {
    track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
      const interpolantType = this instanceof QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
      return new interpolantType(this.times, this.values, this.getValueSize() / 3, result);
    };
    track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  }
};
function computeBounds(geometry, primitiveDef, parser) {
  const attributes = primitiveDef.attributes;
  const box = new Box3();
  if (attributes.POSITION !== void 0) {
    const accessor = parser.json.accessors[attributes.POSITION];
    const min = accessor.min;
    const max2 = accessor.max;
    if (min !== void 0 && max2 !== void 0) {
      box.set(
        new Vector3(min[0], min[1], min[2]),
        new Vector3(max2[0], max2[1], max2[2])
      );
      if (accessor.normalized) {
        const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]);
        box.min.multiplyScalar(boxScale);
        box.max.multiplyScalar(boxScale);
      }
    } else {
      console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");
      return;
    }
  } else {
    return;
  }
  const targets = primitiveDef.targets;
  if (targets !== void 0) {
    const maxDisplacement = new Vector3();
    const vector = new Vector3();
    for (let i = 0, il = targets.length; i < il; i++) {
      const target = targets[i];
      if (target.POSITION !== void 0) {
        const accessor = parser.json.accessors[target.POSITION];
        const min = accessor.min;
        const max2 = accessor.max;
        if (min !== void 0 && max2 !== void 0) {
          vector.setX(Math.max(Math.abs(min[0]), Math.abs(max2[0])));
          vector.setY(Math.max(Math.abs(min[1]), Math.abs(max2[1])));
          vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max2[2])));
          if (accessor.normalized) {
            const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]);
            vector.multiplyScalar(boxScale);
          }
          maxDisplacement.max(vector);
        } else {
          console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");
        }
      }
    }
    box.expandByVector(maxDisplacement);
  }
  geometry.boundingBox = box;
  const sphere = new Sphere();
  box.getCenter(sphere.center);
  sphere.radius = box.min.distanceTo(box.max) / 2;
  geometry.boundingSphere = sphere;
}
function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  const attributes = primitiveDef.attributes;
  const pending = [];
  function assignAttributeAccessor(accessorIndex, attributeName) {
    return parser.getDependency("accessor", accessorIndex).then(function(accessor) {
      geometry.setAttribute(attributeName, accessor);
    });
  }
  for (const gltfAttributeName in attributes) {
    const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase();
    if (threeAttributeName in geometry.attributes) continue;
    pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  }
  if (primitiveDef.indices !== void 0 && !geometry.index) {
    const accessor = parser.getDependency("accessor", primitiveDef.indices).then(function(accessor2) {
      geometry.setIndex(accessor2);
    });
    pending.push(accessor);
  }
  if (ColorManagement.workingColorSpace !== LinearSRGBColorSpace && "COLOR_0" in attributes) {
    console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ColorManagement.workingColorSpace}" not supported.`);
  }
  assignExtrasToUserData(geometry, primitiveDef);
  computeBounds(geometry, primitiveDef, parser);
  return Promise.all(pending).then(function() {
    return primitiveDef.targets !== void 0 ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  });
}

// node_modules/three/examples/jsm/loaders/RGBELoader.js
var RGBELoader = class extends DataTextureLoader {
  /**
   * Constructs a new RGBE loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.type = HalfFloatType;
  }
  /**
   * Parses the given RGBE texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @return {DataTextureLoader~TexData} An object representing the parsed texture data.
   */
  parse(buffer) {
    const rgbe_read_error = 1, rgbe_write_error = 2, rgbe_format_error = 3, rgbe_memory_error = 4, rgbe_error = function(rgbe_error_code, msg) {
      switch (rgbe_error_code) {
        case rgbe_read_error:
          throw new Error("THREE.RGBELoader: Read Error: " + (msg || ""));
        case rgbe_write_error:
          throw new Error("THREE.RGBELoader: Write Error: " + (msg || ""));
        case rgbe_format_error:
          throw new Error("THREE.RGBELoader: Bad File Format: " + (msg || ""));
        default:
        case rgbe_memory_error:
          throw new Error("THREE.RGBELoader: Memory Error: " + (msg || ""));
      }
    }, RGBE_VALID_PROGRAMTYPE = 1, RGBE_VALID_FORMAT = 2, RGBE_VALID_DIMENSIONS = 4, NEWLINE = "\n", fgets = function(buffer2, lineLimit, consume) {
      const chunkSize = 128;
      lineLimit = !lineLimit ? 1024 : lineLimit;
      let p = buffer2.pos, i = -1, len = 0, s = "", chunk = String.fromCharCode.apply(null, new Uint16Array(buffer2.subarray(p, p + chunkSize)));
      while (0 > (i = chunk.indexOf(NEWLINE)) && len < lineLimit && p < buffer2.byteLength) {
        s += chunk;
        len += chunk.length;
        p += chunkSize;
        chunk += String.fromCharCode.apply(null, new Uint16Array(buffer2.subarray(p, p + chunkSize)));
      }
      if (-1 < i) {
        if (false !== consume) buffer2.pos += len + i + 1;
        return s + chunk.slice(0, i);
      }
      return false;
    }, RGBE_ReadHeader = function(buffer2) {
      const magic_token_re = /^#\?(\S+)/, gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/, exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/, format_re = /^\s*FORMAT=(\S+)\s*$/, dimensions_re = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/, header = {
        valid: 0,
        /* indicate which fields are valid */
        string: "",
        /* the actual header string */
        comments: "",
        /* comments found in header */
        programtype: "RGBE",
        /* listed at beginning of file to identify it after "#?". defaults to "RGBE" */
        format: "",
        /* RGBE format, default 32-bit_rle_rgbe */
        gamma: 1,
        /* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */
        exposure: 1,
        /* a value of 1.0 in an image corresponds to <exposure> watts/steradian/m^2. defaults to 1.0 */
        width: 0,
        height: 0
        /* image dimensions, width/height */
      };
      let line2, match;
      if (buffer2.pos >= buffer2.byteLength || !(line2 = fgets(buffer2))) {
        rgbe_error(rgbe_read_error, "no header found");
      }
      if (!(match = line2.match(magic_token_re))) {
        rgbe_error(rgbe_format_error, "bad initial token");
      }
      header.valid |= RGBE_VALID_PROGRAMTYPE;
      header.programtype = match[1];
      header.string += line2 + "\n";
      while (true) {
        line2 = fgets(buffer2);
        if (false === line2) break;
        header.string += line2 + "\n";
        if ("#" === line2.charAt(0)) {
          header.comments += line2 + "\n";
          continue;
        }
        if (match = line2.match(gamma_re)) {
          header.gamma = parseFloat(match[1]);
        }
        if (match = line2.match(exposure_re)) {
          header.exposure = parseFloat(match[1]);
        }
        if (match = line2.match(format_re)) {
          header.valid |= RGBE_VALID_FORMAT;
          header.format = match[1];
        }
        if (match = line2.match(dimensions_re)) {
          header.valid |= RGBE_VALID_DIMENSIONS;
          header.height = parseInt(match[1], 10);
          header.width = parseInt(match[2], 10);
        }
        if (header.valid & RGBE_VALID_FORMAT && header.valid & RGBE_VALID_DIMENSIONS) break;
      }
      if (!(header.valid & RGBE_VALID_FORMAT)) {
        rgbe_error(rgbe_format_error, "missing format specifier");
      }
      if (!(header.valid & RGBE_VALID_DIMENSIONS)) {
        rgbe_error(rgbe_format_error, "missing image size specifier");
      }
      return header;
    }, RGBE_ReadPixels_RLE = function(buffer2, w2, h2) {
      const scanline_width = w2;
      if (
        // run length encoding is not allowed so read flat
        scanline_width < 8 || scanline_width > 32767 || // this file is not run length encoded
        (2 !== buffer2[0] || 2 !== buffer2[1] || buffer2[2] & 128)
      ) {
        return new Uint8Array(buffer2);
      }
      if (scanline_width !== (buffer2[2] << 8 | buffer2[3])) {
        rgbe_error(rgbe_format_error, "wrong scanline width");
      }
      const data_rgba = new Uint8Array(4 * w2 * h2);
      if (!data_rgba.length) {
        rgbe_error(rgbe_memory_error, "unable to allocate buffer space");
      }
      let offset = 0, pos = 0;
      const ptr_end = 4 * scanline_width;
      const rgbeStart = new Uint8Array(4);
      const scanline_buffer = new Uint8Array(ptr_end);
      let num_scanlines = h2;
      while (num_scanlines > 0 && pos < buffer2.byteLength) {
        if (pos + 4 > buffer2.byteLength) {
          rgbe_error(rgbe_read_error);
        }
        rgbeStart[0] = buffer2[pos++];
        rgbeStart[1] = buffer2[pos++];
        rgbeStart[2] = buffer2[pos++];
        rgbeStart[3] = buffer2[pos++];
        if (2 != rgbeStart[0] || 2 != rgbeStart[1] || (rgbeStart[2] << 8 | rgbeStart[3]) != scanline_width) {
          rgbe_error(rgbe_format_error, "bad rgbe scanline format");
        }
        let ptr = 0, count;
        while (ptr < ptr_end && pos < buffer2.byteLength) {
          count = buffer2[pos++];
          const isEncodedRun = count > 128;
          if (isEncodedRun) count -= 128;
          if (0 === count || ptr + count > ptr_end) {
            rgbe_error(rgbe_format_error, "bad scanline data");
          }
          if (isEncodedRun) {
            const byteValue = buffer2[pos++];
            for (let i = 0; i < count; i++) {
              scanline_buffer[ptr++] = byteValue;
            }
          } else {
            scanline_buffer.set(buffer2.subarray(pos, pos + count), ptr);
            ptr += count;
            pos += count;
          }
        }
        const l2 = scanline_width;
        for (let i = 0; i < l2; i++) {
          let off = 0;
          data_rgba[offset] = scanline_buffer[i + off];
          off += scanline_width;
          data_rgba[offset + 1] = scanline_buffer[i + off];
          off += scanline_width;
          data_rgba[offset + 2] = scanline_buffer[i + off];
          off += scanline_width;
          data_rgba[offset + 3] = scanline_buffer[i + off];
          offset += 4;
        }
        num_scanlines--;
      }
      return data_rgba;
    };
    const RGBEByteToRGBFloat = function(sourceArray, sourceOffset, destArray, destOffset) {
      const e = sourceArray[sourceOffset + 3];
      const scale2 = Math.pow(2, e - 128) / 255;
      destArray[destOffset + 0] = sourceArray[sourceOffset + 0] * scale2;
      destArray[destOffset + 1] = sourceArray[sourceOffset + 1] * scale2;
      destArray[destOffset + 2] = sourceArray[sourceOffset + 2] * scale2;
      destArray[destOffset + 3] = 1;
    };
    const RGBEByteToRGBHalf = function(sourceArray, sourceOffset, destArray, destOffset) {
      const e = sourceArray[sourceOffset + 3];
      const scale2 = Math.pow(2, e - 128) / 255;
      destArray[destOffset + 0] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 0] * scale2, 65504));
      destArray[destOffset + 1] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 1] * scale2, 65504));
      destArray[destOffset + 2] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 2] * scale2, 65504));
      destArray[destOffset + 3] = DataUtils.toHalfFloat(1);
    };
    const byteArray = new Uint8Array(buffer);
    byteArray.pos = 0;
    const rgbe_header_info = RGBE_ReadHeader(byteArray);
    const w = rgbe_header_info.width, h = rgbe_header_info.height, image_rgba_data = RGBE_ReadPixels_RLE(byteArray.subarray(byteArray.pos), w, h);
    let data2, type;
    let numElements;
    switch (this.type) {
      case FloatType:
        numElements = image_rgba_data.length / 4;
        const floatArray = new Float32Array(numElements * 4);
        for (let j2 = 0; j2 < numElements; j2++) {
          RGBEByteToRGBFloat(image_rgba_data, j2 * 4, floatArray, j2 * 4);
        }
        data2 = floatArray;
        type = FloatType;
        break;
      case HalfFloatType:
        numElements = image_rgba_data.length / 4;
        const halfArray = new Uint16Array(numElements * 4);
        for (let j2 = 0; j2 < numElements; j2++) {
          RGBEByteToRGBHalf(image_rgba_data, j2 * 4, halfArray, j2 * 4);
        }
        data2 = halfArray;
        type = HalfFloatType;
        break;
      default:
        throw new Error("THREE.RGBELoader: Unsupported type: " + this.type);
        break;
    }
    return {
      width: w,
      height: h,
      data: data2,
      header: rgbe_header_info.string,
      gamma: rgbe_header_info.gamma,
      exposure: rgbe_header_info.exposure,
      type
    };
  }
  /**
   * Sets the texture type.
   *
   * @param {(HalfFloatType|FloatType)} value - The texture type to set.
   * @return {RGBELoader} A reference to this loader.
   */
  setDataType(value2) {
    this.type = value2;
    return this;
  }
  load(url, onLoad, onProgress, onError) {
    function onLoadCallback(texture, texData) {
      switch (texture.type) {
        case FloatType:
        case HalfFloatType:
          texture.colorSpace = LinearSRGBColorSpace;
          texture.minFilter = LinearFilter;
          texture.magFilter = LinearFilter;
          texture.generateMipmaps = false;
          texture.flipY = true;
          break;
      }
      if (onLoad) onLoad(texture, texData);
    }
    return super.load(url, onLoadCallback, onProgress, onError);
  }
};

// node_modules/three/examples/jsm/loaders/HDRCubeTextureLoader.js
var HDRCubeTextureLoader = class extends Loader {
  /**
   * Constructs a new HDR cube texture loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.hdrLoader = new RGBELoader();
    this.type = HalfFloatType;
  }
  /**
   * Starts loading from the given URLs and passes the loaded HDR cube texture
   * to the `onLoad()` callback.
   *
   * @param {Array<string>} urls - The paths/URLs of the files to be loaded. This can also be a data URIs.
   * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {CubeTexture} The HDR cube texture.
   */
  load(urls, onLoad, onProgress, onError) {
    const texture = new CubeTexture();
    texture.type = this.type;
    switch (texture.type) {
      case FloatType:
        texture.colorSpace = LinearSRGBColorSpace;
        texture.minFilter = LinearFilter;
        texture.magFilter = LinearFilter;
        texture.generateMipmaps = false;
        break;
      case HalfFloatType:
        texture.colorSpace = LinearSRGBColorSpace;
        texture.minFilter = LinearFilter;
        texture.magFilter = LinearFilter;
        texture.generateMipmaps = false;
        break;
    }
    const scope = this;
    let loaded = 0;
    function loadHDRData(i, onLoad2, onProgress2, onError2) {
      new FileLoader(scope.manager).setPath(scope.path).setResponseType("arraybuffer").setWithCredentials(scope.withCredentials).load(urls[i], function(buffer) {
        loaded++;
        const texData = scope.hdrLoader.parse(buffer);
        if (!texData) return;
        if (texData.data !== void 0) {
          const dataTexture = new DataTexture(texData.data, texData.width, texData.height);
          dataTexture.type = texture.type;
          dataTexture.colorSpace = texture.colorSpace;
          dataTexture.format = texture.format;
          dataTexture.minFilter = texture.minFilter;
          dataTexture.magFilter = texture.magFilter;
          dataTexture.generateMipmaps = texture.generateMipmaps;
          texture.images[i] = dataTexture;
        }
        if (loaded === 6) {
          texture.needsUpdate = true;
          if (onLoad2) onLoad2(texture);
        }
      }, onProgress2, onError2);
    }
    for (let i = 0; i < urls.length; i++) {
      loadHDRData(i, onLoad, onProgress, onError);
    }
    return texture;
  }
  /**
   * Sets the texture type.
   *
   * @param {(HalfFloatType|FloatType)} value - The texture type to set.
   * @return {RGBELoader} A reference to this loader.
   */
  setDataType(value2) {
    this.type = value2;
    this.hdrLoader.setDataType(value2);
    return this;
  }
};

// node_modules/three/examples/jsm/loaders/IESLoader.js
var IESLoader = class extends Loader {
  /**
   * Constructs a new IES loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.type = HalfFloatType;
  }
  _getIESValues(iesLamp, type) {
    const width2 = 360;
    const height2 = 180;
    const size2 = width2 * height2;
    const data2 = new Array(size2);
    function interpolateCandelaValues(phi, theta) {
      let phiIndex = 0, thetaIndex = 0;
      let startTheta2 = 0, endTheta2 = 0, startPhi = 0, endPhi = 0;
      for (let i = 0; i < iesLamp.numHorAngles - 1; ++i) {
        if (theta < iesLamp.horAngles[i + 1] || i == iesLamp.numHorAngles - 2) {
          thetaIndex = i;
          startTheta2 = iesLamp.horAngles[i];
          endTheta2 = iesLamp.horAngles[i + 1];
          break;
        }
      }
      for (let i = 0; i < iesLamp.numVerAngles - 1; ++i) {
        if (phi < iesLamp.verAngles[i + 1] || i == iesLamp.numVerAngles - 2) {
          phiIndex = i;
          startPhi = iesLamp.verAngles[i];
          endPhi = iesLamp.verAngles[i + 1];
          break;
        }
      }
      const deltaTheta = endTheta2 - startTheta2;
      const deltaPhi = endPhi - startPhi;
      if (deltaPhi === 0)
        return 0;
      const t1 = deltaTheta === 0 ? 0 : (theta - startTheta2) / deltaTheta;
      const t22 = (phi - startPhi) / deltaPhi;
      const nextThetaIndex = deltaTheta === 0 ? thetaIndex : thetaIndex + 1;
      const v12 = MathUtils.lerp(iesLamp.candelaValues[thetaIndex][phiIndex], iesLamp.candelaValues[nextThetaIndex][phiIndex], t1);
      const v2 = MathUtils.lerp(iesLamp.candelaValues[thetaIndex][phiIndex + 1], iesLamp.candelaValues[nextThetaIndex][phiIndex + 1], t1);
      const v = MathUtils.lerp(v12, v2, t22);
      return v;
    }
    const startTheta = iesLamp.horAngles[0], endTheta = iesLamp.horAngles[iesLamp.numHorAngles - 1];
    for (let i = 0; i < size2; ++i) {
      let theta = i % width2;
      const phi = Math.floor(i / width2);
      if (endTheta - startTheta !== 0 && (theta < startTheta || theta >= endTheta)) {
        theta %= endTheta * 2;
        if (theta > endTheta)
          theta = endTheta * 2 - theta;
      }
      data2[phi + theta * height2] = interpolateCandelaValues(phi, theta);
    }
    let result = null;
    if (type === UnsignedByteType) result = Uint8Array.from(data2.map((v) => Math.min(v * 255, 255)));
    else if (type === HalfFloatType) result = Uint16Array.from(data2.map((v) => DataUtils.toHalfFloat(v)));
    else if (type === FloatType) result = Float32Array.from(data2);
    else console.error("IESLoader: Unsupported type:", type);
    return result;
  }
  /**
   * Starts loading from the given URL and passes the loaded IES texture
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const loader = new FileLoader(this.manager);
    loader.setResponseType("text");
    loader.setCrossOrigin(this.crossOrigin);
    loader.setWithCredentials(this.withCredentials);
    loader.setPath(this.path);
    loader.setRequestHeader(this.requestHeader);
    loader.load(url, (text2) => {
      onLoad(this.parse(text2));
    }, onProgress, onError);
  }
  /**
   * Parses the given IES data.
   *
   * @param {string} text - The raw IES data.
   * @return {DataTexture} THE IES data as a texture.
   */
  parse(text2) {
    const type = this.type;
    const iesLamp = new IESLamp(text2);
    const data2 = this._getIESValues(iesLamp, type);
    const texture = new DataTexture(data2, 180, 1, RedFormat, type);
    texture.minFilter = LinearFilter;
    texture.magFilter = LinearFilter;
    texture.needsUpdate = true;
    return texture;
  }
};
function IESLamp(text2) {
  const _self = this;
  const textArray = text2.split("\n");
  let lineNumber = 0;
  let line2;
  _self.verAngles = [];
  _self.horAngles = [];
  _self.candelaValues = [];
  _self.tiltData = {};
  _self.tiltData.angles = [];
  _self.tiltData.mulFactors = [];
  function textToArray(text3) {
    text3 = text3.replace(/^\s+|\s+$/g, "");
    text3 = text3.replace(/,/g, " ");
    text3 = text3.replace(/\s\s+/g, " ");
    const array = text3.split(" ");
    return array;
  }
  function readArray(count, array) {
    while (true) {
      const line3 = textArray[lineNumber++];
      const lineData = textToArray(line3);
      for (let i = 0; i < lineData.length; ++i) {
        array.push(Number(lineData[i]));
      }
      if (array.length === count)
        break;
    }
  }
  function readTilt() {
    let line3 = textArray[lineNumber++];
    let lineData = textToArray(line3);
    _self.tiltData.lampToLumGeometry = Number(lineData[0]);
    line3 = textArray[lineNumber++];
    lineData = textToArray(line3);
    _self.tiltData.numAngles = Number(lineData[0]);
    readArray(_self.tiltData.numAngles, _self.tiltData.angles);
    readArray(_self.tiltData.numAngles, _self.tiltData.mulFactors);
  }
  function readLampValues() {
    const values2 = [];
    readArray(10, values2);
    _self.count = Number(values2[0]);
    _self.lumens = Number(values2[1]);
    _self.multiplier = Number(values2[2]);
    _self.numVerAngles = Number(values2[3]);
    _self.numHorAngles = Number(values2[4]);
    _self.gonioType = Number(values2[5]);
    _self.units = Number(values2[6]);
    _self.width = Number(values2[7]);
    _self.length = Number(values2[8]);
    _self.height = Number(values2[9]);
  }
  function readLampFactors() {
    const values2 = [];
    readArray(3, values2);
    _self.ballFactor = Number(values2[0]);
    _self.blpFactor = Number(values2[1]);
    _self.inputWatts = Number(values2[2]);
  }
  while (true) {
    line2 = textArray[lineNumber++];
    if (line2.includes("TILT")) {
      break;
    }
  }
  if (!line2.includes("NONE")) {
    if (line2.includes("INCLUDE")) {
      readTilt();
    } else {
    }
  }
  readLampValues();
  readLampFactors();
  for (let i = 0; i < _self.numHorAngles; ++i) {
    _self.candelaValues.push([]);
  }
  readArray(_self.numVerAngles, _self.verAngles);
  readArray(_self.numHorAngles, _self.horAngles);
  for (let i = 0; i < _self.numHorAngles; ++i) {
    readArray(_self.numVerAngles, _self.candelaValues[i]);
  }
  for (let i = 0; i < _self.numHorAngles; ++i) {
    for (let j2 = 0; j2 < _self.numVerAngles; ++j2) {
      _self.candelaValues[i][j2] *= _self.candelaValues[i][j2] * _self.multiplier * _self.ballFactor * _self.blpFactor;
    }
  }
  let maxVal = -1;
  for (let i = 0; i < _self.numHorAngles; ++i) {
    for (let j2 = 0; j2 < _self.numVerAngles; ++j2) {
      const value2 = _self.candelaValues[i][j2];
      maxVal = maxVal < value2 ? value2 : maxVal;
    }
  }
  const bNormalize = true;
  if (bNormalize && maxVal > 0) {
    for (let i = 0; i < _self.numHorAngles; ++i) {
      for (let j2 = 0; j2 < _self.numVerAngles; ++j2) {
        _self.candelaValues[i][j2] /= maxVal;
      }
    }
  }
}

// node_modules/three/examples/jsm/loaders/KMZLoader.js
var KMZLoader = class extends Loader {
  /**
   * Constructs a new KMZ loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded KMZ asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function({scene:Group})} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given KMZ data and returns an object holding the scene.
   *
   * @param {ArrayBuffer} data - The raw KMZ data as an array buffer.
   * @return {{scene:Group}} The parsed KMZ asset.
   */
  parse(data2) {
    function findFile(url) {
      for (const path in zip) {
        if (path.slice(-url.length) === url) {
          return zip[path];
        }
      }
    }
    const manager = new LoadingManager();
    manager.setURLModifier(function(url) {
      const image = findFile(url);
      if (image) {
        console.log("Loading", url);
        const blob = new Blob([image.buffer], { type: "application/octet-stream" });
        return URL.createObjectURL(blob);
      }
      return url;
    });
    const zip = unzipSync(new Uint8Array(data2));
    if (zip["doc.kml"]) {
      const xml = new DOMParser().parseFromString(strFromU8(zip["doc.kml"]), "application/xml");
      const model = xml.querySelector("Placemark Model Link href");
      if (model) {
        const loader = new ColladaLoader(manager);
        return loader.parse(strFromU8(zip[model.textContent]));
      }
    } else {
      console.warn("KMZLoader: Missing doc.kml file.");
      for (const path in zip) {
        const extension = path.split(".").pop().toLowerCase();
        if (extension === "dae") {
          const loader = new ColladaLoader(manager);
          return loader.parse(strFromU8(zip[path]));
        }
      }
    }
    console.error("KMZLoader: Couldn't find .dae file.");
    return { scene: new Group() };
  }
};

// node_modules/three/examples/jsm/utils/WorkerPool.js
var WorkerPool = class {
  /**
   * Constructs a new Worker pool.
   *
   * @param {number} [pool=4] - The size of the pool.
   */
  constructor(pool = 4) {
    this.pool = pool;
    this.queue = [];
    this.workers = [];
    this.workersResolve = [];
    this.workerStatus = 0;
    this.workerCreator = null;
  }
  _initWorker(workerId) {
    if (!this.workers[workerId]) {
      const worker = this.workerCreator();
      worker.addEventListener("message", this._onMessage.bind(this, workerId));
      this.workers[workerId] = worker;
    }
  }
  _getIdleWorker() {
    for (let i = 0; i < this.pool; i++)
      if (!(this.workerStatus & 1 << i)) return i;
    return -1;
  }
  _onMessage(workerId, msg) {
    const resolve = this.workersResolve[workerId];
    resolve && resolve(msg);
    if (this.queue.length) {
      const { resolve: resolve2, msg: msg2, transfer } = this.queue.shift();
      this.workersResolve[workerId] = resolve2;
      this.workers[workerId].postMessage(msg2, transfer);
    } else {
      this.workerStatus ^= 1 << workerId;
    }
  }
  /**
   * Sets a function that is responsible for creating Workers.
   *
   * @param {Function} workerCreator - The worker creator function.
   */
  setWorkerCreator(workerCreator) {
    this.workerCreator = workerCreator;
  }
  /**
   * Sets the Worker limit
   *
   * @param {number} pool - The size of the pool.
   */
  setWorkerLimit(pool) {
    this.pool = pool;
  }
  /**
   * Post a message to an idle Worker. If no Worker is available,
   * the message is pushed into a message queue for later processing.
   *
   * @param {Object} msg - The message.
   * @param {Array<ArrayBuffer>} transfer - An array with array buffers for data transfer.
   * @return {Promise} A Promise that resolves when the message has been processed.
   */
  postMessage(msg, transfer) {
    return new Promise((resolve) => {
      const workerId = this._getIdleWorker();
      if (workerId !== -1) {
        this._initWorker(workerId);
        this.workerStatus |= 1 << workerId;
        this.workersResolve[workerId] = resolve;
        this.workers[workerId].postMessage(msg, transfer);
      } else {
        this.queue.push({ resolve, msg, transfer });
      }
    });
  }
  /**
   * Terminates all Workers of this pool. Call this  method whenever this
   * Worker pool is no longer used in your app.
   */
  dispose() {
    this.workers.forEach((worker) => worker.terminate());
    this.workersResolve.length = 0;
    this.workers.length = 0;
    this.queue.length = 0;
    this.workerStatus = 0;
  }
};

// node_modules/three/examples/jsm/libs/zstddec.module.js
var A;
var I;
var B;
var g2 = { env: { emscripten_notify_memory_growth: function(A2) {
  B = new Uint8Array(I.exports.memory.buffer);
} } };
var Q = class {
  init() {
    return A || (A = "undefined" != typeof fetch ? fetch("data:application/wasm;base64," + C2).then((A2) => A2.arrayBuffer()).then((A2) => WebAssembly.instantiate(A2, g2)).then(this._init) : WebAssembly.instantiate(Buffer.from(C2, "base64"), g2).then(this._init), A);
  }
  _init(A2) {
    I = A2.instance, g2.env.emscripten_notify_memory_growth(0);
  }
  decode(A2, g3 = 0) {
    if (!I) throw new Error("ZSTDDecoder: Await .init() before decoding.");
    const Q2 = A2.byteLength, C3 = I.exports.malloc(Q2);
    B.set(A2, C3), g3 = g3 || Number(I.exports.ZSTD_findDecompressedSize(C3, Q2));
    const E = I.exports.malloc(g3), i = I.exports.ZSTD_decompress(E, g3, C3, Q2), D = B.slice(E, E + i);
    return I.exports.free(C3), I.exports.free(E), D;
  }
};
var C2 = "[encoded data, 38976 characters]";

// node_modules/three/examples/jsm/math/ColorSpaces.js
var LINEAR_DISPLAY_P3_TO_XYZ = new Matrix3().set(
  0.4865709,
  0.2656677,
  0.1982173,
  0.2289746,
  0.6917385,
  0.0792869,
  0,
  0.0451134,
  1.0439444
);
var XYZ_TO_LINEAR_DISPLAY_P3 = new Matrix3().set(
  2.4934969,
  -0.9313836,
  -0.4027108,
  -0.829489,
  1.7626641,
  0.0236247,
  0.0358458,
  -0.0761724,
  0.9568845
);
var DisplayP3ColorSpace = "display-p3";
var LinearDisplayP3ColorSpace = "display-p3-linear";
var LINEAR_REC2020_TO_XYZ = new Matrix3().set(
  0.636958,
  0.1446169,
  0.168881,
  0.2627002,
  0.6779981,
  0.0593017,
  0,
  0.0280727,
  1.0609851
);
var XYZ_TO_LINEAR_REC2020 = new Matrix3().set(
  1.7166512,
  -0.3556708,
  -0.2533663,
  -0.6666844,
  1.6164812,
  0.0157685,
  0.0176399,
  -0.0427706,
  0.9421031
);

// node_modules/three/examples/jsm/loaders/KTX2Loader.js
var _taskCache3 = /* @__PURE__ */ new WeakMap();
var _activeLoaders = 0;
var _zstd;
var KTX2Loader = class _KTX2Loader extends Loader {
  /**
   * Constructs a new KTX2 loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.transcoderPath = "";
    this.transcoderBinary = null;
    this.transcoderPending = null;
    this.workerPool = new WorkerPool();
    this.workerSourceURL = "";
    this.workerConfig = null;
    if (typeof MSC_TRANSCODER !== "undefined") {
      console.warn(
        'THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.'
      );
    }
  }
  /**
   * Sets the transcoder path.
   *
   * The WASM transcoder and JS wrapper are available from the `examples/jsm/libs/basis` directory.
   *
   * @param {string} path - The transcoder path to set.
   * @return {KTX2Loader} A reference to this loader.
   */
  setTranscoderPath(path) {
    this.transcoderPath = path;
    return this;
  }
  /**
   * Sets the maximum number of Web Workers to be allocated by this instance.
   *
   * @param {number} workerLimit - The worker limit.
   * @return {KTX2Loader} A reference to this loader.
   */
  setWorkerLimit(workerLimit) {
    this.workerPool.setWorkerLimit(workerLimit);
    return this;
  }
  /**
   * Async version of {@link KTX2Loader#detectSupport}.
   *
   * @async
   * @param {WebGPURenderer|WebGLRenderer} renderer - The renderer.
   * @return {Promise} A Promise that resolves when the support has been detected.
   */
  async detectSupportAsync(renderer2) {
    this.workerConfig = {
      astcSupported: await renderer2.hasFeatureAsync("texture-compression-astc"),
      astcHDRSupported: false,
      // https://github.com/gpuweb/gpuweb/issues/3856
      etc1Supported: await renderer2.hasFeatureAsync("texture-compression-etc1"),
      etc2Supported: await renderer2.hasFeatureAsync("texture-compression-etc2"),
      dxtSupported: await renderer2.hasFeatureAsync("texture-compression-bc"),
      bptcSupported: await renderer2.hasFeatureAsync("texture-compression-bptc"),
      pvrtcSupported: await renderer2.hasFeatureAsync("texture-compression-pvrtc")
    };
    return this;
  }
  /**
   * Detects hardware support for available compressed texture formats, to determine
   * the output format for the transcoder. Must be called before loading a texture.
   *
   * @param {WebGPURenderer|WebGLRenderer} renderer - The renderer.
   * @return {KTX2Loader} A reference to this loader.
   */
  detectSupport(renderer2) {
    if (renderer2.isWebGPURenderer === true) {
      this.workerConfig = {
        astcSupported: renderer2.hasFeature("texture-compression-astc"),
        astcHDRSupported: false,
        // https://github.com/gpuweb/gpuweb/issues/3856
        etc1Supported: renderer2.hasFeature("texture-compression-etc1"),
        etc2Supported: renderer2.hasFeature("texture-compression-etc2"),
        dxtSupported: renderer2.hasFeature("texture-compression-bc"),
        bptcSupported: renderer2.hasFeature("texture-compression-bptc"),
        pvrtcSupported: renderer2.hasFeature("texture-compression-pvrtc")
      };
    } else {
      this.workerConfig = {
        astcSupported: renderer2.extensions.has("WEBGL_compressed_texture_astc"),
        astcHDRSupported: renderer2.extensions.has("WEBGL_compressed_texture_astc") && renderer2.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),
        etc1Supported: renderer2.extensions.has("WEBGL_compressed_texture_etc1"),
        etc2Supported: renderer2.extensions.has("WEBGL_compressed_texture_etc"),
        dxtSupported: renderer2.extensions.has("WEBGL_compressed_texture_s3tc"),
        bptcSupported: renderer2.extensions.has("EXT_texture_compression_bptc"),
        pvrtcSupported: renderer2.extensions.has("WEBGL_compressed_texture_pvrtc") || renderer2.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")
      };
    }
    return this;
  }
  // TODO: Make this method private
  init() {
    if (!this.transcoderPending) {
      const jsLoader = new FileLoader(this.manager);
      jsLoader.setPath(this.transcoderPath);
      jsLoader.setWithCredentials(this.withCredentials);
      const jsContent = jsLoader.loadAsync("basis_transcoder.js");
      const binaryLoader = new FileLoader(this.manager);
      binaryLoader.setPath(this.transcoderPath);
      binaryLoader.setResponseType("arraybuffer");
      binaryLoader.setWithCredentials(this.withCredentials);
      const binaryContent = binaryLoader.loadAsync("basis_transcoder.wasm");
      this.transcoderPending = Promise.all([jsContent, binaryContent]).then(([jsContent2, binaryContent2]) => {
        const fn = _KTX2Loader.BasisWorker.toString();
        const body = [
          "/* constants */",
          "let _EngineFormat = " + JSON.stringify(_KTX2Loader.EngineFormat),
          "let _EngineType = " + JSON.stringify(_KTX2Loader.EngineType),
          "let _TranscoderFormat = " + JSON.stringify(_KTX2Loader.TranscoderFormat),
          "let _BasisFormat = " + JSON.stringify(_KTX2Loader.BasisFormat),
          "/* basis_transcoder.js */",
          jsContent2,
          "/* worker */",
          fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}"))
        ].join("\n");
        this.workerSourceURL = URL.createObjectURL(new Blob([body]));
        this.transcoderBinary = binaryContent2;
        this.workerPool.setWorkerCreator(() => {
          const worker = new Worker(this.workerSourceURL);
          const transcoderBinary = this.transcoderBinary.slice(0);
          worker.postMessage({ type: "init", config: this.workerConfig, transcoderBinary }, [transcoderBinary]);
          return worker;
        });
      });
      if (_activeLoaders > 0) {
        console.warn(
          "THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."
        );
      }
      _activeLoaders++;
    }
    return this.transcoderPending;
  }
  /**
   * Starts loading from the given URL and passes the loaded KTX2 texture
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    if (this.workerConfig === null) {
      throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");
    }
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setCrossOrigin(this.crossOrigin);
    loader.setWithCredentials(this.withCredentials);
    loader.setResponseType("arraybuffer");
    loader.load(url, (buffer) => {
      this.parse(buffer, onLoad, onError);
    }, onProgress, onError);
  }
  /**
   * Parses the given KTX2 data.
   *
   * @param {ArrayBuffer} buffer - The raw KTX2 data as an array buffer.
   * @param {function(CompressedTexture)} onLoad - Executed when the loading/parsing process has been finished.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @returns {Promise} A Promise that resolves when the parsing has been finished.
   */
  parse(buffer, onLoad, onError) {
    if (this.workerConfig === null) {
      throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");
    }
    if (_taskCache3.has(buffer)) {
      const cachedTask = _taskCache3.get(buffer);
      return cachedTask.promise.then(onLoad).catch(onError);
    }
    this._createTexture(buffer).then((texture) => onLoad ? onLoad(texture) : null).catch(onError);
  }
  _createTextureFrom(transcodeResult, container) {
    const { type: messageType, error, data: { faces, width: width2, height: height2, format, type, dfdFlags } } = transcodeResult;
    if (messageType === "error") return Promise.reject(error);
    let texture;
    if (container.faceCount === 6) {
      texture = new CompressedCubeTexture(faces, format, type);
    } else {
      const mipmaps = faces[0].mipmaps;
      texture = container.layerCount > 1 ? new CompressedArrayTexture(mipmaps, width2, height2, container.layerCount, format, type) : new CompressedTexture(mipmaps, width2, height2, format, type);
    }
    texture.minFilter = faces[0].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
    texture.magFilter = LinearFilter;
    texture.generateMipmaps = false;
    texture.needsUpdate = true;
    texture.colorSpace = parseColorSpace(container);
    texture.premultiplyAlpha = !!(dfdFlags & g);
    return texture;
  }
  /**
   * @private
   * @param {ArrayBuffer} buffer
   * @param {?Object} config
   * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
   */
  async _createTexture(buffer, config = {}) {
    const container = Pi(new Uint8Array(buffer));
    const isBasisHDR = container.vkFormat === pi && container.dataFormatDescriptor[0].colorModel === 167;
    const needsTranscoder = container.vkFormat === it || isBasisHDR && !this.workerConfig.astcHDRSupported;
    if (!needsTranscoder) {
      return createRawTexture(container);
    }
    const taskConfig = config;
    const texturePending = this.init().then(() => {
      return this.workerPool.postMessage({ type: "transcode", buffer, taskConfig }, [buffer]);
    }).then((e) => this._createTextureFrom(e.data, container));
    _taskCache3.set(buffer, { promise: texturePending });
    return texturePending;
  }
  /**
   * Frees internal resources. This method should be called
   * when the loader is no longer required.
   */
  dispose() {
    this.workerPool.dispose();
    if (this.workerSourceURL) URL.revokeObjectURL(this.workerSourceURL);
    _activeLoaders--;
  }
};
KTX2Loader.BasisFormat = {
  ETC1S: 0,
  UASTC: 1,
  UASTC_HDR: 2
};
KTX2Loader.TranscoderFormat = {
  ETC1: 0,
  ETC2: 1,
  BC1: 2,
  BC3: 3,
  BC4: 4,
  BC5: 5,
  BC7_M6_OPAQUE_ONLY: 6,
  BC7_M5: 7,
  PVRTC1_4_RGB: 8,
  PVRTC1_4_RGBA: 9,
  ASTC_4x4: 10,
  ATC_RGB: 11,
  ATC_RGBA_INTERPOLATED_ALPHA: 12,
  RGBA32: 13,
  RGB565: 14,
  BGR565: 15,
  RGBA4444: 16,
  BC6H: 22,
  RGB_HALF: 24,
  RGBA_HALF: 25
};
KTX2Loader.EngineFormat = {
  RGBAFormat,
  RGBA_ASTC_4x4_Format,
  RGB_BPTC_UNSIGNED_Format,
  RGBA_BPTC_Format,
  RGBA_ETC2_EAC_Format,
  RGBA_PVRTC_4BPPV1_Format,
  RGBA_S3TC_DXT5_Format,
  RGB_ETC1_Format,
  RGB_ETC2_Format,
  RGB_PVRTC_4BPPV1_Format,
  RGBA_S3TC_DXT1_Format
};
KTX2Loader.EngineType = {
  UnsignedByteType,
  HalfFloatType,
  FloatType
};
KTX2Loader.BasisWorker = function() {
  let config;
  let transcoderPending;
  let BasisModule;
  const EngineFormat = _EngineFormat;
  const EngineType = _EngineType;
  const TranscoderFormat = _TranscoderFormat;
  const BasisFormat = _BasisFormat;
  self.addEventListener("message", function(e) {
    const message = e.data;
    switch (message.type) {
      case "init":
        config = message.config;
        init(message.transcoderBinary);
        break;
      case "transcode":
        transcoderPending.then(() => {
          try {
            const { faces, buffers, width: width2, height: height2, hasAlpha, format, type, dfdFlags } = transcode(message.buffer);
            self.postMessage({ type: "transcode", id: message.id, data: { faces, width: width2, height: height2, hasAlpha, format, type, dfdFlags } }, buffers);
          } catch (error) {
            console.error(error);
            self.postMessage({ type: "error", id: message.id, error: error.message });
          }
        });
        break;
    }
  });
  function init(wasmBinary) {
    transcoderPending = new Promise((resolve) => {
      BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
      BASIS(BasisModule);
    }).then(() => {
      BasisModule.initializeBasis();
      if (BasisModule.KTX2File === void 0) {
        console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.");
      }
    });
  }
  function transcode(buffer) {
    const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer));
    function cleanup() {
      ktx2File.close();
      ktx2File.delete();
    }
    if (!ktx2File.isValid()) {
      cleanup();
      throw new Error("THREE.KTX2Loader:	Invalid or unsupported .ktx2 file");
    }
    let basisFormat;
    if (ktx2File.isUASTC()) {
      basisFormat = BasisFormat.UASTC;
    } else if (ktx2File.isETC1S()) {
      basisFormat = BasisFormat.ETC1S;
    } else if (ktx2File.isHDR()) {
      basisFormat = BasisFormat.UASTC_HDR;
    } else {
      throw new Error("THREE.KTX2Loader: Unknown Basis encoding");
    }
    const width2 = ktx2File.getWidth();
    const height2 = ktx2File.getHeight();
    const layerCount = ktx2File.getLayers() || 1;
    const levelCount = ktx2File.getLevels();
    const faceCount = ktx2File.getFaces();
    const hasAlpha = ktx2File.getHasAlpha();
    const dfdFlags = ktx2File.getDFDFlags();
    const { transcoderFormat, engineFormat, engineType } = getTranscoderFormat(basisFormat, width2, height2, hasAlpha);
    if (!width2 || !height2 || !levelCount) {
      cleanup();
      throw new Error("THREE.KTX2Loader:	Invalid texture");
    }
    if (!ktx2File.startTranscoding()) {
      cleanup();
      throw new Error("THREE.KTX2Loader: .startTranscoding failed");
    }
    const faces = [];
    const buffers = [];
    for (let face = 0; face < faceCount; face++) {
      const mipmaps = [];
      for (let mip = 0; mip < levelCount; mip++) {
        const layerMips = [];
        let mipWidth, mipHeight;
        for (let layer = 0; layer < layerCount; layer++) {
          const levelInfo = ktx2File.getImageLevelInfo(mip, layer, face);
          if (face === 0 && mip === 0 && layer === 0 && (levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0)) {
            console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.");
          }
          if (levelCount > 1) {
            mipWidth = levelInfo.origWidth;
            mipHeight = levelInfo.origHeight;
          } else {
            mipWidth = levelInfo.width;
            mipHeight = levelInfo.height;
          }
          let dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat));
          const status = ktx2File.transcodeImage(dst, mip, layer, face, transcoderFormat, 0, -1, -1);
          if (engineType === EngineType.HalfFloatType) {
            dst = new Uint16Array(dst.buffer, dst.byteOffset, dst.byteLength / Uint16Array.BYTES_PER_ELEMENT);
          }
          if (!status) {
            cleanup();
            throw new Error("THREE.KTX2Loader: .transcodeImage failed.");
          }
          layerMips.push(dst);
        }
        const mipData = concat(layerMips);
        mipmaps.push({ data: mipData, width: mipWidth, height: mipHeight });
        buffers.push(mipData.buffer);
      }
      faces.push({ mipmaps, width: width2, height: height2, format: engineFormat, type: engineType });
    }
    cleanup();
    return { faces, buffers, width: width2, height: height2, hasAlpha, dfdFlags, format: engineFormat, type: engineType };
  }
  const FORMAT_OPTIONS = [
    {
      if: "astcSupported",
      basisFormat: [BasisFormat.UASTC],
      transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4],
      engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format],
      engineType: [EngineType.UnsignedByteType],
      priorityETC1S: Infinity,
      priorityUASTC: 1,
      needsPowerOfTwo: false
    },
    {
      if: "bptcSupported",
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC],
      transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5],
      engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format],
      engineType: [EngineType.UnsignedByteType],
      priorityETC1S: 3,
      priorityUASTC: 2,
      needsPowerOfTwo: false
    },
    {
      if: "dxtSupported",
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC],
      transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3],
      engineFormat: [EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format],
      engineType: [EngineType.UnsignedByteType],
      priorityETC1S: 4,
      priorityUASTC: 5,
      needsPowerOfTwo: false
    },
    {
      if: "etc2Supported",
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC],
      transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2],
      engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format],
      engineType: [EngineType.UnsignedByteType],
      priorityETC1S: 1,
      priorityUASTC: 3,
      needsPowerOfTwo: false
    },
    {
      if: "etc1Supported",
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC],
      transcoderFormat: [TranscoderFormat.ETC1],
      engineFormat: [EngineFormat.RGB_ETC1_Format],
      engineType: [EngineType.UnsignedByteType],
      priorityETC1S: 2,
      priorityUASTC: 4,
      needsPowerOfTwo: false
    },
    {
      if: "pvrtcSupported",
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC],
      transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA],
      engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format],
      engineType: [EngineType.UnsignedByteType],
      priorityETC1S: 5,
      priorityUASTC: 6,
      needsPowerOfTwo: true
    },
    {
      if: "bptcSupported",
      basisFormat: [BasisFormat.UASTC_HDR],
      transcoderFormat: [TranscoderFormat.BC6H],
      engineFormat: [EngineFormat.RGB_BPTC_UNSIGNED_Format],
      engineType: [EngineType.HalfFloatType],
      priorityHDR: 1,
      needsPowerOfTwo: false
    },
    // Uncompressed fallbacks.
    {
      basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC],
      transcoderFormat: [TranscoderFormat.RGBA32, TranscoderFormat.RGBA32],
      engineFormat: [EngineFormat.RGBAFormat, EngineFormat.RGBAFormat],
      engineType: [EngineType.UnsignedByteType, EngineType.UnsignedByteType],
      priorityETC1S: 100,
      priorityUASTC: 100,
      needsPowerOfTwo: false
    },
    {
      basisFormat: [BasisFormat.UASTC_HDR],
      transcoderFormat: [TranscoderFormat.RGBA_HALF],
      engineFormat: [EngineFormat.RGBAFormat],
      engineType: [EngineType.HalfFloatType],
      priorityHDR: 100,
      needsPowerOfTwo: false
    }
  ];
  const OPTIONS = {
    // TODO: For ETC1S we intentionally sort by _UASTC_ priority, preserving
    // a historical accident shown to avoid performance pitfalls for Linux with
    // Firefox & AMD GPU (RadeonSI). Further work needed.
    // See https://github.com/mrdoob/three.js/pull/29730.
    [BasisFormat.ETC1S]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.ETC1S)).sort((a2, b3) => a2.priorityUASTC - b3.priorityUASTC),
    [BasisFormat.UASTC]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.UASTC)).sort((a2, b3) => a2.priorityUASTC - b3.priorityUASTC),
    [BasisFormat.UASTC_HDR]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.UASTC_HDR)).sort((a2, b3) => a2.priorityHDR - b3.priorityHDR)
  };
  function getTranscoderFormat(basisFormat, width2, height2, hasAlpha) {
    const options = OPTIONS[basisFormat];
    for (let i = 0; i < options.length; i++) {
      const opt = options[i];
      if (opt.if && !config[opt.if]) continue;
      if (!opt.basisFormat.includes(basisFormat)) continue;
      if (hasAlpha && opt.transcoderFormat.length < 2) continue;
      if (opt.needsPowerOfTwo && !(isPowerOfTwo(width2) && isPowerOfTwo(height2))) continue;
      const transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0];
      const engineFormat = opt.engineFormat[hasAlpha ? 1 : 0];
      const engineType = opt.engineType[0];
      return { transcoderFormat, engineFormat, engineType };
    }
    throw new Error("THREE.KTX2Loader: Failed to identify transcoding target.");
  }
  function isPowerOfTwo(value2) {
    if (value2 <= 2) return true;
    return (value2 & value2 - 1) === 0 && value2 !== 0;
  }
  function concat(arrays) {
    if (arrays.length === 1) return arrays[0];
    let totalByteLength = 0;
    for (let i = 0; i < arrays.length; i++) {
      const array = arrays[i];
      totalByteLength += array.byteLength;
    }
    const result = new Uint8Array(totalByteLength);
    let byteOffset = 0;
    for (let i = 0; i < arrays.length; i++) {
      const array = arrays[i];
      result.set(array, byteOffset);
      byteOffset += array.byteLength;
    }
    return result;
  }
};
var UNCOMPRESSED_FORMATS = /* @__PURE__ */ new Set([RGBAFormat, RGFormat, RedFormat]);
var FORMAT_MAP = {
  [Ae]: RGBAFormat,
  [ge]: RGBAFormat,
  [Ft]: RGBAFormat,
  [Ct]: RGBAFormat,
  [we]: RGFormat,
  [ae]: RGFormat,
  [xt]: RGFormat,
  [wt]: RGFormat,
  [ue]: RedFormat,
  [te2]: RedFormat,
  [yt]: RedFormat,
  [ct]: RedFormat,
  [_n]: RGB_ETC2_Format,
  [xn]: RGBA_ETC2_EAC_Format,
  [pi]: RGBA_ASTC_4x4_Format,
  [Dn]: RGBA_ASTC_4x4_Format,
  [mn]: RGBA_ASTC_4x4_Format,
  [Sn]: RGBA_ASTC_6x6_Format,
  [In]: RGBA_ASTC_6x6_Format,
  [Qe]: RGBA_S3TC_DXT1_Format,
  [Ze]: RGBA_S3TC_DXT1_Format,
  [Ge]: RGB_S3TC_DXT1_Format,
  [Je]: RGB_S3TC_DXT1_Format,
  [nn]: RGBA_S3TC_DXT3_Format,
  [en]: RGBA_S3TC_DXT3_Format,
  [on]: RGBA_S3TC_DXT5_Format,
  [rn]: RGBA_S3TC_DXT5_Format,
  [Un]: RGBA_BPTC_Format,
  [hn]: RGBA_BPTC_Format
};
var TYPE_MAP = {
  [Ae]: FloatType,
  [ge]: HalfFloatType,
  [Ft]: UnsignedByteType,
  [Ct]: UnsignedByteType,
  [we]: FloatType,
  [ae]: HalfFloatType,
  [xt]: UnsignedByteType,
  [wt]: UnsignedByteType,
  [ue]: FloatType,
  [te2]: HalfFloatType,
  [yt]: UnsignedByteType,
  [ct]: UnsignedByteType,
  [_n]: UnsignedByteType,
  [xn]: UnsignedByteType,
  [pi]: HalfFloatType,
  [Sn]: UnsignedByteType,
  [In]: UnsignedByteType
};
async function createRawTexture(container) {
  const { vkFormat } = container;
  if (FORMAT_MAP[vkFormat] === void 0) {
    throw new Error("THREE.KTX2Loader: Unsupported vkFormat.");
  }
  let zstd;
  if (container.supercompressionScheme === n) {
    if (!_zstd) {
      _zstd = new Promise(async (resolve) => {
        const zstd2 = new Q();
        await zstd2.init();
        resolve(zstd2);
      });
    }
    zstd = await _zstd;
  }
  const mipmaps = [];
  for (let levelIndex = 0; levelIndex < container.levels.length; levelIndex++) {
    const levelWidth = Math.max(1, container.pixelWidth >> levelIndex);
    const levelHeight = Math.max(1, container.pixelHeight >> levelIndex);
    const levelDepth = container.pixelDepth ? Math.max(1, container.pixelDepth >> levelIndex) : 0;
    const level = container.levels[levelIndex];
    let levelData;
    if (container.supercompressionScheme === t) {
      levelData = level.levelData;
    } else if (container.supercompressionScheme === n) {
      levelData = zstd.decode(level.levelData, level.uncompressedByteLength);
    } else {
      throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");
    }
    let data2;
    if (TYPE_MAP[vkFormat] === FloatType) {
      data2 = new Float32Array(
        levelData.buffer,
        levelData.byteOffset,
        levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
      );
    } else if (TYPE_MAP[vkFormat] === HalfFloatType) {
      data2 = new Uint16Array(
        levelData.buffer,
        levelData.byteOffset,
        levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
      );
    } else {
      data2 = levelData;
    }
    mipmaps.push({
      data: data2,
      width: levelWidth,
      height: levelHeight,
      depth: levelDepth
    });
  }
  let texture;
  if (UNCOMPRESSED_FORMATS.has(FORMAT_MAP[vkFormat])) {
    texture = container.pixelDepth === 0 ? new DataTexture(mipmaps[0].data, container.pixelWidth, container.pixelHeight) : new Data3DTexture(mipmaps[0].data, container.pixelWidth, container.pixelHeight, container.pixelDepth);
  } else {
    if (container.pixelDepth > 0) throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");
    texture = new CompressedTexture(mipmaps, container.pixelWidth, container.pixelHeight);
    texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
    texture.magFilter = LinearFilter;
  }
  texture.mipmaps = mipmaps;
  texture.type = TYPE_MAP[vkFormat];
  texture.format = FORMAT_MAP[vkFormat];
  texture.colorSpace = parseColorSpace(container);
  texture.needsUpdate = true;
  return Promise.resolve(texture);
}
function parseColorSpace(container) {
  const dfd = container.dataFormatDescriptor[0];
  if (dfd.colorPrimaries === C) {
    return dfd.transferFunction === u ? SRGBColorSpace : LinearSRGBColorSpace;
  } else if (dfd.colorPrimaries === R) {
    return dfd.transferFunction === u ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace;
  } else if (dfd.colorPrimaries === T) {
    return NoColorSpace;
  } else {
    console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${dfd.colorPrimaries}"`);
    return NoColorSpace;
  }
}

// node_modules/three/examples/jsm/loaders/KTXLoader.js
var KTXLoader = class extends CompressedTextureLoader {
  /**
   * Constructs a new KTX loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Parses the given KTX texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @param {boolean} loadMipmaps - Whether to load mipmaps or not.
   * @return {CompressedTextureLoader~TexData} An object representing the parsed texture data.
   */
  parse(buffer, loadMipmaps) {
    const ktx = new KhronosTextureContainer(buffer, 1);
    return {
      mipmaps: ktx.mipmaps(loadMipmaps),
      width: ktx.pixelWidth,
      height: ktx.pixelHeight,
      format: ktx.glInternalFormat,
      isCubemap: ktx.numberOfFaces === 6,
      mipmapCount: ktx.numberOfMipmapLevels
    };
  }
};
var HEADER_LEN = 12 + 13 * 4;
var COMPRESSED_2D = 0;
var KhronosTextureContainer = class {
  /**
   * @private
   * @param {ArrayBuffer} arrayBuffer - contents of the KTX container file
   * @param {number} facesExpected - should be either 1 or 6, based whether a cube texture or or
   * @param {boolean} threeDExpected - provision for indicating that data should be a 3D texture, not implemented
   * @param {boolean} textureArrayExpected - provision for indicating that data should be a texture array, not implemented
   */
  constructor(arrayBuffer, facesExpected) {
    this.arrayBuffer = arrayBuffer;
    const identifier = new Uint8Array(this.arrayBuffer, 0, 12);
    if (identifier[0] !== 171 || identifier[1] !== 75 || identifier[2] !== 84 || identifier[3] !== 88 || identifier[4] !== 32 || identifier[5] !== 49 || identifier[6] !== 49 || identifier[7] !== 187 || identifier[8] !== 13 || identifier[9] !== 10 || identifier[10] !== 26 || identifier[11] !== 10) {
      console.error("texture missing KTX identifier");
      return;
    }
    const dataSize = Uint32Array.BYTES_PER_ELEMENT;
    const headerDataView = new DataView(this.arrayBuffer, 12, 13 * dataSize);
    const endianness = headerDataView.getUint32(0, true);
    const littleEndian = endianness === 67305985;
    this.glType = headerDataView.getUint32(1 * dataSize, littleEndian);
    this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian);
    this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian);
    this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian);
    this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian);
    this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian);
    this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian);
    this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian);
    this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian);
    this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian);
    this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian);
    this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian);
    if (this.glType !== 0) {
      console.warn("only compressed formats currently supported");
      return;
    } else {
      this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
    }
    if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
      console.warn("only 2D textures currently supported");
      return;
    }
    if (this.numberOfArrayElements !== 0) {
      console.warn("texture arrays not currently supported");
      return;
    }
    if (this.numberOfFaces !== facesExpected) {
      console.warn("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
      return;
    }
    this.loadType = COMPRESSED_2D;
  }
  mipmaps(loadMipmaps) {
    const mipmaps = [];
    let dataOffset = HEADER_LEN + this.bytesOfKeyValueData;
    let width2 = this.pixelWidth;
    let height2 = this.pixelHeight;
    const mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
    for (let level = 0; level < mipmapCount; level++) {
      const imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0];
      dataOffset += 4;
      for (let face = 0; face < this.numberOfFaces; face++) {
        const byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
        mipmaps.push({ "data": byteArray, "width": width2, "height": height2 });
        dataOffset += imageSize;
        dataOffset += 3 - (imageSize + 3) % 4;
      }
      width2 = Math.max(1, width2 * 0.5);
      height2 = Math.max(1, height2 * 0.5);
    }
    return mipmaps;
  }
};

// node_modules/three/examples/jsm/loaders/LDrawLoader.js
var FINISH_TYPE_DEFAULT = 0;
var FINISH_TYPE_CHROME = 1;
var FINISH_TYPE_PEARLESCENT = 2;
var FINISH_TYPE_RUBBER = 3;
var FINISH_TYPE_MATTE_METALLIC = 4;
var FINISH_TYPE_METAL = 5;
var FILE_LOCATION_TRY_PARTS = 0;
var FILE_LOCATION_TRY_P = 1;
var FILE_LOCATION_TRY_MODELS = 2;
var FILE_LOCATION_AS_IS = 3;
var FILE_LOCATION_TRY_RELATIVE = 4;
var FILE_LOCATION_TRY_ABSOLUTE = 5;
var FILE_LOCATION_NOT_FOUND = 6;
var MAIN_COLOUR_CODE = "16";
var MAIN_EDGE_COLOUR_CODE = "24";
var COLOR_SPACE_LDRAW = SRGBColorSpace;
var _tempVec0 = new Vector3();
var _tempVec1 = new Vector3();
var ConditionalLineSegments = class extends LineSegments {
  constructor(geometry, material) {
    super(geometry, material);
    this.isConditionalLine = true;
  }
};
function generateFaceNormals(faces) {
  for (let i = 0, l2 = faces.length; i < l2; i++) {
    const face = faces[i];
    const vertices = face.vertices;
    const v0 = vertices[0];
    const v12 = vertices[1];
    const v2 = vertices[2];
    _tempVec0.subVectors(v12, v0);
    _tempVec1.subVectors(v2, v12);
    face.faceNormal = new Vector3().crossVectors(_tempVec0, _tempVec1).normalize();
  }
}
var _ray3 = new Ray();
function smoothNormals(faces, lineSegments, checkSubSegments = false) {
  const hashMultiplier = (1 + 1e-10) * 100;
  function hashVertex(v) {
    const x2 = ~~(v.x * hashMultiplier);
    const y = ~~(v.y * hashMultiplier);
    const z = ~~(v.z * hashMultiplier);
    return `${x2},${y},${z}`;
  }
  function hashEdge(v0, v12) {
    return `${hashVertex(v0)}_${hashVertex(v12)}`;
  }
  function toNormalizedRay(v0, v12, targetRay) {
    targetRay.direction.subVectors(v12, v0).normalize();
    const scalar = v0.dot(targetRay.direction);
    targetRay.origin.copy(v0).addScaledVector(targetRay.direction, -scalar);
    return targetRay;
  }
  function hashRay(ray) {
    return hashEdge(ray.origin, ray.direction);
  }
  const hardEdges = /* @__PURE__ */ new Set();
  const hardEdgeRays = /* @__PURE__ */ new Map();
  const halfEdgeList = {};
  const normals = [];
  for (let i = 0, l2 = lineSegments.length; i < l2; i++) {
    const ls = lineSegments[i];
    const vertices = ls.vertices;
    const v0 = vertices[0];
    const v12 = vertices[1];
    hardEdges.add(hashEdge(v0, v12));
    hardEdges.add(hashEdge(v12, v0));
    if (checkSubSegments) {
      const ray = toNormalizedRay(v0, v12, new Ray());
      const rh1 = hashRay(ray);
      if (!hardEdgeRays.has(rh1)) {
        toNormalizedRay(v12, v0, ray);
        const rh2 = hashRay(ray);
        const info2 = {
          ray,
          distances: []
        };
        hardEdgeRays.set(rh1, info2);
        hardEdgeRays.set(rh2, info2);
      }
      const info = hardEdgeRays.get(rh1);
      let d0 = info.ray.direction.dot(v0);
      let d1 = info.ray.direction.dot(v12);
      if (d0 > d1) {
        [d0, d1] = [d1, d0];
      }
      info.distances.push(d0, d1);
    }
  }
  for (let i = 0, l2 = faces.length; i < l2; i++) {
    const tri = faces[i];
    const vertices = tri.vertices;
    const vertCount = vertices.length;
    for (let i2 = 0; i2 < vertCount; i2++) {
      const index2 = i2;
      const next = (i2 + 1) % vertCount;
      const v0 = vertices[index2];
      const v12 = vertices[next];
      const hash = hashEdge(v0, v12);
      if (hardEdges.has(hash)) {
        continue;
      }
      if (checkSubSegments) {
        toNormalizedRay(v0, v12, _ray3);
        const rayHash = hashRay(_ray3);
        if (hardEdgeRays.has(rayHash)) {
          const info2 = hardEdgeRays.get(rayHash);
          const { ray, distances } = info2;
          let d0 = ray.direction.dot(v0);
          let d1 = ray.direction.dot(v12);
          if (d0 > d1) {
            [d0, d1] = [d1, d0];
          }
          let found = false;
          for (let i3 = 0, l3 = distances.length; i3 < l3; i3 += 2) {
            if (d0 >= distances[i3] && d1 <= distances[i3 + 1]) {
              found = true;
              break;
            }
          }
          if (found) {
            continue;
          }
        }
      }
      const info = {
        index: index2,
        tri
      };
      halfEdgeList[hash] = info;
    }
  }
  while (true) {
    let halfEdge = null;
    for (const key2 in halfEdgeList) {
      halfEdge = halfEdgeList[key2];
      break;
    }
    if (halfEdge === null) {
      break;
    }
    const queue = [halfEdge];
    while (queue.length > 0) {
      const tri = queue.pop().tri;
      const vertices = tri.vertices;
      const vertNormals = tri.normals;
      const faceNormal = tri.faceNormal;
      const vertCount = vertices.length;
      for (let i2 = 0; i2 < vertCount; i2++) {
        const index2 = i2;
        const next = (i2 + 1) % vertCount;
        const v0 = vertices[index2];
        const v12 = vertices[next];
        const hash = hashEdge(v0, v12);
        delete halfEdgeList[hash];
        const reverseHash = hashEdge(v12, v0);
        const otherInfo = halfEdgeList[reverseHash];
        if (otherInfo) {
          const otherTri = otherInfo.tri;
          const otherIndex = otherInfo.index;
          const otherNormals = otherTri.normals;
          const otherVertCount = otherNormals.length;
          const otherFaceNormal = otherTri.faceNormal;
          if (Math.abs(otherTri.faceNormal.dot(tri.faceNormal)) < 0.25) {
            continue;
          }
          if (reverseHash in halfEdgeList) {
            queue.push(otherInfo);
            delete halfEdgeList[reverseHash];
          }
          const otherNext = (otherIndex + 1) % otherVertCount;
          if (vertNormals[index2] && otherNormals[otherNext] && vertNormals[index2] !== otherNormals[otherNext]) {
            otherNormals[otherNext].norm.add(vertNormals[index2].norm);
            vertNormals[index2].norm = otherNormals[otherNext].norm;
          }
          let sharedNormal1 = vertNormals[index2] || otherNormals[otherNext];
          if (sharedNormal1 === null) {
            sharedNormal1 = { norm: new Vector3() };
            normals.push(sharedNormal1.norm);
          }
          if (vertNormals[index2] === null) {
            vertNormals[index2] = sharedNormal1;
            sharedNormal1.norm.add(faceNormal);
          }
          if (otherNormals[otherNext] === null) {
            otherNormals[otherNext] = sharedNormal1;
            sharedNormal1.norm.add(otherFaceNormal);
          }
          if (vertNormals[next] && otherNormals[otherIndex] && vertNormals[next] !== otherNormals[otherIndex]) {
            otherNormals[otherIndex].norm.add(vertNormals[next].norm);
            vertNormals[next].norm = otherNormals[otherIndex].norm;
          }
          let sharedNormal2 = vertNormals[next] || otherNormals[otherIndex];
          if (sharedNormal2 === null) {
            sharedNormal2 = { norm: new Vector3() };
            normals.push(sharedNormal2.norm);
          }
          if (vertNormals[next] === null) {
            vertNormals[next] = sharedNormal2;
            sharedNormal2.norm.add(faceNormal);
          }
          if (otherNormals[otherIndex] === null) {
            otherNormals[otherIndex] = sharedNormal2;
            sharedNormal2.norm.add(otherFaceNormal);
          }
        }
      }
    }
  }
  for (let i = 0, l2 = normals.length; i < l2; i++) {
    normals[i].normalize();
  }
}
function isPartType(type) {
  return type === "Part" || type === "Unofficial_Part";
}
function isPrimitiveType(type) {
  return /primitive/i.test(type) || type === "Subpart";
}
var LineParser = class {
  constructor(line2, lineNumber) {
    this.line = line2;
    this.lineLength = line2.length;
    this.currentCharIndex = 0;
    this.currentChar = " ";
    this.lineNumber = lineNumber;
  }
  seekNonSpace() {
    while (this.currentCharIndex < this.lineLength) {
      this.currentChar = this.line.charAt(this.currentCharIndex);
      if (this.currentChar !== " " && this.currentChar !== "	") {
        return;
      }
      this.currentCharIndex++;
    }
  }
  getToken() {
    const pos0 = this.currentCharIndex++;
    while (this.currentCharIndex < this.lineLength) {
      this.currentChar = this.line.charAt(this.currentCharIndex);
      if (this.currentChar === " " || this.currentChar === "	") {
        break;
      }
      this.currentCharIndex++;
    }
    const pos1 = this.currentCharIndex;
    this.seekNonSpace();
    return this.line.substring(pos0, pos1);
  }
  getVector() {
    return new Vector3(parseFloat(this.getToken()), parseFloat(this.getToken()), parseFloat(this.getToken()));
  }
  getRemainingString() {
    return this.line.substring(this.currentCharIndex, this.lineLength);
  }
  isAtTheEnd() {
    return this.currentCharIndex >= this.lineLength;
  }
  setToEnd() {
    this.currentCharIndex = this.lineLength;
  }
  getLineNumberString() {
    return this.lineNumber >= 0 ? " at line " + this.lineNumber : "";
  }
};
var LDrawParsedCache = class {
  constructor(loader) {
    this.loader = loader;
    this._cache = {};
  }
  cloneResult(original) {
    const result = {};
    result.faces = original.faces.map((face) => {
      return {
        colorCode: face.colorCode,
        material: face.material,
        vertices: face.vertices.map((v) => v.clone()),
        normals: face.normals.map(() => null),
        faceNormal: null
      };
    });
    result.conditionalSegments = original.conditionalSegments.map((face) => {
      return {
        colorCode: face.colorCode,
        material: face.material,
        vertices: face.vertices.map((v) => v.clone()),
        controlPoints: face.controlPoints.map((v) => v.clone())
      };
    });
    result.lineSegments = original.lineSegments.map((face) => {
      return {
        colorCode: face.colorCode,
        material: face.material,
        vertices: face.vertices.map((v) => v.clone())
      };
    });
    result.type = original.type;
    result.category = original.category;
    result.keywords = original.keywords;
    result.author = original.author;
    result.subobjects = original.subobjects;
    result.fileName = original.fileName;
    result.totalFaces = original.totalFaces;
    result.startingBuildingStep = original.startingBuildingStep;
    result.materials = original.materials;
    result.group = null;
    return result;
  }
  async fetchData(fileName) {
    let triedLowerCase = false;
    let locationState = FILE_LOCATION_TRY_PARTS;
    while (locationState !== FILE_LOCATION_NOT_FOUND) {
      let subobjectURL = fileName;
      switch (locationState) {
        case FILE_LOCATION_AS_IS:
          locationState = locationState + 1;
          break;
        case FILE_LOCATION_TRY_PARTS:
          subobjectURL = "parts/" + subobjectURL;
          locationState = locationState + 1;
          break;
        case FILE_LOCATION_TRY_P:
          subobjectURL = "p/" + subobjectURL;
          locationState = locationState + 1;
          break;
        case FILE_LOCATION_TRY_MODELS:
          subobjectURL = "models/" + subobjectURL;
          locationState = locationState + 1;
          break;
        case FILE_LOCATION_TRY_RELATIVE:
          subobjectURL = fileName.substring(0, fileName.lastIndexOf("/") + 1) + subobjectURL;
          locationState = locationState + 1;
          break;
        case FILE_LOCATION_TRY_ABSOLUTE:
          if (triedLowerCase) {
            locationState = FILE_LOCATION_NOT_FOUND;
          } else {
            fileName = fileName.toLowerCase();
            subobjectURL = fileName;
            triedLowerCase = true;
            locationState = FILE_LOCATION_TRY_PARTS;
          }
          break;
      }
      const loader = this.loader;
      const fileLoader = new FileLoader(loader.manager);
      fileLoader.setPath(loader.partsLibraryPath);
      fileLoader.setRequestHeader(loader.requestHeader);
      fileLoader.setWithCredentials(loader.withCredentials);
      try {
        const text2 = await fileLoader.loadAsync(subobjectURL);
        return text2;
      } catch (_) {
        continue;
      }
    }
    throw new Error('LDrawLoader: Subobject "' + fileName + '" could not be loaded.');
  }
  parse(text2, fileName = null) {
    const loader = this.loader;
    const faces = [];
    const lineSegments = [];
    const conditionalSegments = [];
    const subobjects = [];
    const materials = {};
    const getLocalMaterial = (colorCode) => {
      return materials[colorCode] || null;
    };
    let type = "Model";
    let category = null;
    let keywords = null;
    let author = null;
    let totalFaces = 0;
    if (text2.indexOf("\r\n") !== -1) {
      text2 = text2.replace(/\r\n/g, "\n");
    }
    const lines = text2.split("\n");
    const numLines = lines.length;
    let parsingEmbeddedFiles = false;
    let currentEmbeddedFileName = null;
    let currentEmbeddedText = null;
    let bfcCertified = false;
    let bfcCCW = true;
    let bfcInverted = false;
    let bfcCull = true;
    let startingBuildingStep = false;
    for (let lineIndex = 0; lineIndex < numLines; lineIndex++) {
      const line2 = lines[lineIndex];
      if (line2.length === 0) continue;
      if (parsingEmbeddedFiles) {
        if (line2.startsWith("0 FILE ")) {
          this.setData(currentEmbeddedFileName, currentEmbeddedText);
          currentEmbeddedFileName = line2.substring(7);
          currentEmbeddedText = "";
        } else {
          currentEmbeddedText += line2 + "\n";
        }
        continue;
      }
      const lp = new LineParser(line2, lineIndex + 1);
      lp.seekNonSpace();
      if (lp.isAtTheEnd()) {
        continue;
      }
      const lineType = lp.getToken();
      let material;
      let colorCode;
      let segment;
      let ccw;
      let doubleSided;
      let v0, v12, v2, v3, c0, c1;
      switch (lineType) {
        // Line type 0: Comment or META
        case "0":
          const meta2 = lp.getToken();
          if (meta2) {
            switch (meta2) {
              case "!LDRAW_ORG":
                type = lp.getToken();
                break;
              case "!COLOUR":
                material = loader.parseColorMetaDirective(lp);
                if (material) {
                  materials[material.userData.code] = material;
                } else {
                  console.warn("LDrawLoader: Error parsing material" + lp.getLineNumberString());
                }
                break;
              case "!CATEGORY":
                category = lp.getToken();
                break;
              case "!KEYWORDS":
                const newKeywords = lp.getRemainingString().split(",");
                if (newKeywords.length > 0) {
                  if (!keywords) {
                    keywords = [];
                  }
                  newKeywords.forEach(function(keyword) {
                    keywords.push(keyword.trim());
                  });
                }
                break;
              case "FILE":
                if (lineIndex > 0) {
                  parsingEmbeddedFiles = true;
                  currentEmbeddedFileName = lp.getRemainingString();
                  currentEmbeddedText = "";
                  bfcCertified = false;
                  bfcCCW = true;
                }
                break;
              case "BFC":
                while (!lp.isAtTheEnd()) {
                  const token = lp.getToken();
                  switch (token) {
                    case "CERTIFY":
                    case "NOCERTIFY":
                      bfcCertified = token === "CERTIFY";
                      bfcCCW = true;
                      break;
                    case "CW":
                    case "CCW":
                      bfcCCW = token === "CCW";
                      break;
                    case "INVERTNEXT":
                      bfcInverted = true;
                      break;
                    case "CLIP":
                    case "NOCLIP":
                      bfcCull = token === "CLIP";
                      break;
                    default:
                      console.warn('THREE.LDrawLoader: BFC directive "' + token + '" is unknown.');
                      break;
                  }
                }
                break;
              case "STEP":
                startingBuildingStep = true;
                break;
              case "Author:":
                author = lp.getToken();
                break;
              default:
                break;
            }
          }
          break;
        // Line type 1: Sub-object file
        case "1":
          colorCode = lp.getToken();
          material = getLocalMaterial(colorCode);
          const posX = parseFloat(lp.getToken());
          const posY = parseFloat(lp.getToken());
          const posZ = parseFloat(lp.getToken());
          const m0 = parseFloat(lp.getToken());
          const m1 = parseFloat(lp.getToken());
          const m2 = parseFloat(lp.getToken());
          const m3 = parseFloat(lp.getToken());
          const m4 = parseFloat(lp.getToken());
          const m5 = parseFloat(lp.getToken());
          const m6 = parseFloat(lp.getToken());
          const m7 = parseFloat(lp.getToken());
          const m8 = parseFloat(lp.getToken());
          const matrix2 = new Matrix4().set(
            m0,
            m1,
            m2,
            posX,
            m3,
            m4,
            m5,
            posY,
            m6,
            m7,
            m8,
            posZ,
            0,
            0,
            0,
            1
          );
          let fileName2 = lp.getRemainingString().trim().replace(/\\/g, "/");
          if (loader.fileMap[fileName2]) {
            fileName2 = loader.fileMap[fileName2];
          } else {
            if (fileName2.startsWith("s/")) {
              fileName2 = "parts/" + fileName2;
            } else if (fileName2.startsWith("48/")) {
              fileName2 = "p/" + fileName2;
            }
          }
          subobjects.push({
            material,
            colorCode,
            matrix: matrix2,
            fileName: fileName2,
            inverted: bfcInverted,
            startingBuildingStep
          });
          startingBuildingStep = false;
          bfcInverted = false;
          break;
        // Line type 2: Line segment
        case "2":
          colorCode = lp.getToken();
          material = getLocalMaterial(colorCode);
          v0 = lp.getVector();
          v12 = lp.getVector();
          segment = {
            material,
            colorCode,
            vertices: [v0, v12]
          };
          lineSegments.push(segment);
          break;
        // Line type 5: Conditional Line segment
        case "5":
          colorCode = lp.getToken();
          material = getLocalMaterial(colorCode);
          v0 = lp.getVector();
          v12 = lp.getVector();
          c0 = lp.getVector();
          c1 = lp.getVector();
          segment = {
            material,
            colorCode,
            vertices: [v0, v12],
            controlPoints: [c0, c1]
          };
          conditionalSegments.push(segment);
          break;
        // Line type 3: Triangle
        case "3":
          colorCode = lp.getToken();
          material = getLocalMaterial(colorCode);
          ccw = bfcCCW;
          doubleSided = !bfcCertified || !bfcCull;
          if (ccw === true) {
            v0 = lp.getVector();
            v12 = lp.getVector();
            v2 = lp.getVector();
          } else {
            v2 = lp.getVector();
            v12 = lp.getVector();
            v0 = lp.getVector();
          }
          faces.push({
            material,
            colorCode,
            faceNormal: null,
            vertices: [v0, v12, v2],
            normals: [null, null, null]
          });
          totalFaces++;
          if (doubleSided === true) {
            faces.push({
              material,
              colorCode,
              faceNormal: null,
              vertices: [v2, v12, v0],
              normals: [null, null, null]
            });
            totalFaces++;
          }
          break;
        // Line type 4: Quadrilateral
        case "4":
          colorCode = lp.getToken();
          material = getLocalMaterial(colorCode);
          ccw = bfcCCW;
          doubleSided = !bfcCertified || !bfcCull;
          if (ccw === true) {
            v0 = lp.getVector();
            v12 = lp.getVector();
            v2 = lp.getVector();
            v3 = lp.getVector();
          } else {
            v3 = lp.getVector();
            v2 = lp.getVector();
            v12 = lp.getVector();
            v0 = lp.getVector();
          }
          faces.push({
            material,
            colorCode,
            faceNormal: null,
            vertices: [v0, v12, v2, v3],
            normals: [null, null, null, null]
          });
          totalFaces += 2;
          if (doubleSided === true) {
            faces.push({
              material,
              colorCode,
              faceNormal: null,
              vertices: [v3, v2, v12, v0],
              normals: [null, null, null, null]
            });
            totalFaces += 2;
          }
          break;
        default:
          throw new Error('LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + ".");
      }
    }
    if (parsingEmbeddedFiles) {
      this.setData(currentEmbeddedFileName, currentEmbeddedText);
    }
    return {
      faces,
      conditionalSegments,
      lineSegments,
      type,
      category,
      keywords,
      author,
      subobjects,
      totalFaces,
      startingBuildingStep,
      materials,
      fileName,
      group: null
    };
  }
  // returns an (optionally cloned) instance of the data
  getData(fileName, clone2 = true) {
    const key2 = fileName.toLowerCase();
    const result = this._cache[key2];
    if (result === null || result instanceof Promise) {
      return null;
    }
    if (clone2) {
      return this.cloneResult(result);
    } else {
      return result;
    }
  }
  // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
  // the data is ready to use and can be retrieved synchronously with "getData".
  async ensureDataLoaded(fileName) {
    const key2 = fileName.toLowerCase();
    if (!(key2 in this._cache)) {
      this._cache[key2] = this.fetchData(fileName).then((text2) => {
        const info = this.parse(text2, fileName);
        this._cache[key2] = info;
        return info;
      });
    }
    await this._cache[key2];
  }
  // sets the data in the cache from parsed data
  setData(fileName, text2) {
    const key2 = fileName.toLowerCase();
    this._cache[key2] = this.parse(text2, fileName);
  }
};
function getMaterialFromCode(colorCode, parentColorCode, materialHierarchy, forEdge) {
  const isPassthrough = !forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  if (isPassthrough) {
    colorCode = parentColorCode;
  }
  return materialHierarchy[colorCode] || null;
}
var LDrawPartsGeometryCache = class {
  constructor(loader) {
    this.loader = loader;
    this.parseCache = new LDrawParsedCache(loader);
    this._cache = {};
  }
  // Convert the given file information into a mesh by processing subobjects.
  async processIntoMesh(info) {
    const loader = this.loader;
    const parseCache = this.parseCache;
    const faceMaterials = /* @__PURE__ */ new Set();
    const processInfoSubobjects = async (info2, subobject = null) => {
      const subobjects = info2.subobjects;
      const promises = [];
      for (let i = 0, l2 = subobjects.length; i < l2; i++) {
        const subobject2 = subobjects[i];
        const promise = parseCache.ensureDataLoaded(subobject2.fileName).then(() => {
          const subobjectInfo = parseCache.getData(subobject2.fileName, false);
          if (!isPrimitiveType(subobjectInfo.type)) {
            return this.loadModel(subobject2.fileName).catch((error) => {
              console.warn(error);
              return null;
            });
          }
          return processInfoSubobjects(parseCache.getData(subobject2.fileName), subobject2);
        });
        promises.push(promise);
      }
      const group2 = new Group();
      group2.userData.category = info2.category;
      group2.userData.keywords = info2.keywords;
      group2.userData.author = info2.author;
      group2.userData.type = info2.type;
      group2.userData.fileName = info2.fileName;
      info2.group = group2;
      const subobjectInfos = await Promise.all(promises);
      for (let i = 0, l2 = subobjectInfos.length; i < l2; i++) {
        const subobject2 = info2.subobjects[i];
        const subobjectInfo = subobjectInfos[i];
        if (subobjectInfo === null) {
          continue;
        }
        if (subobjectInfo.isGroup) {
          const subobjectGroup = subobjectInfo;
          subobject2.matrix.decompose(subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale);
          subobjectGroup.userData.startingBuildingStep = subobject2.startingBuildingStep;
          subobjectGroup.name = subobject2.fileName;
          loader.applyMaterialsToMesh(subobjectGroup, subobject2.colorCode, info2.materials);
          subobjectGroup.userData.colorCode = subobject2.colorCode;
          group2.add(subobjectGroup);
          continue;
        }
        if (subobjectInfo.group.children.length) {
          group2.add(subobjectInfo.group);
        }
        const parentLineSegments = info2.lineSegments;
        const parentConditionalSegments = info2.conditionalSegments;
        const parentFaces = info2.faces;
        const lineSegments = subobjectInfo.lineSegments;
        const conditionalSegments = subobjectInfo.conditionalSegments;
        const faces = subobjectInfo.faces;
        const matrix2 = subobject2.matrix;
        const inverted = subobject2.inverted;
        const matrixScaleInverted = matrix2.determinant() < 0;
        const colorCode = subobject2.colorCode;
        const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
        for (let i2 = 0, l3 = lineSegments.length; i2 < l3; i2++) {
          const ls = lineSegments[i2];
          const vertices = ls.vertices;
          vertices[0].applyMatrix4(matrix2);
          vertices[1].applyMatrix4(matrix2);
          ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
          ls.material = ls.material || getMaterialFromCode(ls.colorCode, ls.colorCode, info2.materials, true);
          parentLineSegments.push(ls);
        }
        for (let i2 = 0, l3 = conditionalSegments.length; i2 < l3; i2++) {
          const os = conditionalSegments[i2];
          const vertices = os.vertices;
          const controlPoints = os.controlPoints;
          vertices[0].applyMatrix4(matrix2);
          vertices[1].applyMatrix4(matrix2);
          controlPoints[0].applyMatrix4(matrix2);
          controlPoints[1].applyMatrix4(matrix2);
          os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
          os.material = os.material || getMaterialFromCode(os.colorCode, os.colorCode, info2.materials, true);
          parentConditionalSegments.push(os);
        }
        for (let i2 = 0, l3 = faces.length; i2 < l3; i2++) {
          const tri = faces[i2];
          const vertices = tri.vertices;
          for (let i3 = 0, l4 = vertices.length; i3 < l4; i3++) {
            vertices[i3].applyMatrix4(matrix2);
          }
          tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
          tri.material = tri.material || getMaterialFromCode(tri.colorCode, colorCode, info2.materials, false);
          faceMaterials.add(tri.colorCode);
          if (matrixScaleInverted !== inverted) {
            vertices.reverse();
          }
          parentFaces.push(tri);
        }
        info2.totalFaces += subobjectInfo.totalFaces;
      }
      if (subobject) {
        loader.applyMaterialsToMesh(group2, subobject.colorCode, info2.materials);
        group2.userData.colorCode = subobject.colorCode;
      }
      return info2;
    };
    for (let i = 0, l2 = info.faces; i < l2; i++) {
      faceMaterials.add(info.faces[i].colorCode);
    }
    await processInfoSubobjects(info);
    if (loader.smoothNormals) {
      const checkSubSegments = faceMaterials.size > 1;
      generateFaceNormals(info.faces);
      smoothNormals(info.faces, info.lineSegments, checkSubSegments);
    }
    const group = info.group;
    if (info.faces.length > 0) {
      group.add(createObject(this.loader, info.faces, 3, false, info.totalFaces));
    }
    if (info.lineSegments.length > 0) {
      group.add(createObject(this.loader, info.lineSegments, 2));
    }
    if (info.conditionalSegments.length > 0) {
      group.add(createObject(this.loader, info.conditionalSegments, 2, true));
    }
    return group;
  }
  hasCachedModel(fileName) {
    return fileName !== null && fileName.toLowerCase() in this._cache;
  }
  async getCachedModel(fileName) {
    if (fileName !== null && this.hasCachedModel(fileName)) {
      const key2 = fileName.toLowerCase();
      const group = await this._cache[key2];
      return group.clone();
    } else {
      return null;
    }
  }
  // Loads and parses the model with the given file name. Returns a cached copy if available.
  async loadModel(fileName) {
    const parseCache = this.parseCache;
    const key2 = fileName.toLowerCase();
    if (this.hasCachedModel(fileName)) {
      return this.getCachedModel(fileName);
    } else {
      await parseCache.ensureDataLoaded(fileName);
      const info = parseCache.getData(fileName);
      const promise = this.processIntoMesh(info);
      if (this.hasCachedModel(fileName)) {
        return this.getCachedModel(fileName);
      }
      if (isPartType(info.type)) {
        this._cache[key2] = promise;
      }
      const group = await promise;
      return group.clone();
    }
  }
  // parses the given model text into a renderable object. Returns cached copy if available.
  async parseModel(text2) {
    const parseCache = this.parseCache;
    const info = parseCache.parse(text2);
    if (isPartType(info.type) && this.hasCachedModel(info.fileName)) {
      return this.getCachedModel(info.fileName);
    }
    return this.processIntoMesh(info);
  }
};
function sortByMaterial(a2, b3) {
  if (a2.colorCode === b3.colorCode) {
    return 0;
  }
  if (a2.colorCode < b3.colorCode) {
    return -1;
  }
  return 1;
}
function createObject(loader, elements, elementSize, isConditionalSegments = false, totalElements = null) {
  elements.sort(sortByMaterial);
  if (totalElements === null) {
    totalElements = elements.length;
  }
  const positions = new Float32Array(elementSize * totalElements * 3);
  const normals = elementSize === 3 ? new Float32Array(elementSize * totalElements * 3) : null;
  const materials = [];
  const quadArray = new Array(6);
  const bufferGeometry = new BufferGeometry();
  let prevMaterial = null;
  let index0 = 0;
  let numGroupVerts = 0;
  let offset = 0;
  for (let iElem = 0, nElem = elements.length; iElem < nElem; iElem++) {
    const elem2 = elements[iElem];
    let vertices = elem2.vertices;
    if (vertices.length === 4) {
      quadArray[0] = vertices[0];
      quadArray[1] = vertices[1];
      quadArray[2] = vertices[2];
      quadArray[3] = vertices[0];
      quadArray[4] = vertices[2];
      quadArray[5] = vertices[3];
      vertices = quadArray;
    }
    for (let j2 = 0, l2 = vertices.length; j2 < l2; j2++) {
      const v = vertices[j2];
      const index2 = offset + j2 * 3;
      positions[index2 + 0] = v.x;
      positions[index2 + 1] = v.y;
      positions[index2 + 2] = v.z;
    }
    if (elementSize === 3) {
      if (!elem2.faceNormal) {
        const v0 = vertices[0];
        const v12 = vertices[1];
        const v2 = vertices[2];
        _tempVec0.subVectors(v12, v0);
        _tempVec1.subVectors(v2, v12);
        elem2.faceNormal = new Vector3().crossVectors(_tempVec0, _tempVec1).normalize();
      }
      let elemNormals = elem2.normals;
      if (elemNormals.length === 4) {
        quadArray[0] = elemNormals[0];
        quadArray[1] = elemNormals[1];
        quadArray[2] = elemNormals[2];
        quadArray[3] = elemNormals[0];
        quadArray[4] = elemNormals[2];
        quadArray[5] = elemNormals[3];
        elemNormals = quadArray;
      }
      for (let j2 = 0, l2 = elemNormals.length; j2 < l2; j2++) {
        let n2 = elem2.faceNormal;
        if (elemNormals[j2]) {
          n2 = elemNormals[j2].norm;
        }
        const index2 = offset + j2 * 3;
        normals[index2 + 0] = n2.x;
        normals[index2 + 1] = n2.y;
        normals[index2 + 2] = n2.z;
      }
    }
    if (prevMaterial !== elem2.colorCode) {
      if (prevMaterial !== null) {
        bufferGeometry.addGroup(index0, numGroupVerts, materials.length - 1);
      }
      const material = elem2.material;
      if (material !== null) {
        if (elementSize === 3) {
          materials.push(material);
        } else if (elementSize === 2) {
          if (isConditionalSegments) {
            const edgeMaterial = loader.edgeMaterialCache.get(material);
            materials.push(loader.conditionalEdgeMaterialCache.get(edgeMaterial));
          } else {
            materials.push(loader.edgeMaterialCache.get(material));
          }
        }
      } else {
        materials.push(elem2.colorCode);
      }
      prevMaterial = elem2.colorCode;
      index0 = offset / 3;
      numGroupVerts = vertices.length;
    } else {
      numGroupVerts += vertices.length;
    }
    offset += 3 * vertices.length;
  }
  if (numGroupVerts > 0) {
    bufferGeometry.addGroup(index0, Infinity, materials.length - 1);
  }
  bufferGeometry.setAttribute("position", new BufferAttribute(positions, 3));
  if (normals !== null) {
    bufferGeometry.setAttribute("normal", new BufferAttribute(normals, 3));
  }
  let object3d = null;
  if (elementSize === 2) {
    if (isConditionalSegments) {
      object3d = new ConditionalLineSegments(bufferGeometry, materials.length === 1 ? materials[0] : materials);
    } else {
      object3d = new LineSegments(bufferGeometry, materials.length === 1 ? materials[0] : materials);
    }
  } else if (elementSize === 3) {
    object3d = new Mesh(bufferGeometry, materials.length === 1 ? materials[0] : materials);
  }
  if (isConditionalSegments) {
    object3d.isConditionalLine = true;
    const controlArray0 = new Float32Array(elements.length * 3 * 2);
    const controlArray1 = new Float32Array(elements.length * 3 * 2);
    const directionArray = new Float32Array(elements.length * 3 * 2);
    for (let i = 0, l2 = elements.length; i < l2; i++) {
      const os = elements[i];
      const vertices = os.vertices;
      const controlPoints = os.controlPoints;
      const c0 = controlPoints[0];
      const c1 = controlPoints[1];
      const v0 = vertices[0];
      const v12 = vertices[1];
      const index2 = i * 3 * 2;
      controlArray0[index2 + 0] = c0.x;
      controlArray0[index2 + 1] = c0.y;
      controlArray0[index2 + 2] = c0.z;
      controlArray0[index2 + 3] = c0.x;
      controlArray0[index2 + 4] = c0.y;
      controlArray0[index2 + 5] = c0.z;
      controlArray1[index2 + 0] = c1.x;
      controlArray1[index2 + 1] = c1.y;
      controlArray1[index2 + 2] = c1.z;
      controlArray1[index2 + 3] = c1.x;
      controlArray1[index2 + 4] = c1.y;
      controlArray1[index2 + 5] = c1.z;
      directionArray[index2 + 0] = v12.x - v0.x;
      directionArray[index2 + 1] = v12.y - v0.y;
      directionArray[index2 + 2] = v12.z - v0.z;
      directionArray[index2 + 3] = v12.x - v0.x;
      directionArray[index2 + 4] = v12.y - v0.y;
      directionArray[index2 + 5] = v12.z - v0.z;
    }
    bufferGeometry.setAttribute("control0", new BufferAttribute(controlArray0, 3, false));
    bufferGeometry.setAttribute("control1", new BufferAttribute(controlArray1, 3, false));
    bufferGeometry.setAttribute("direction", new BufferAttribute(directionArray, 3, false));
  }
  return object3d;
}
var LDrawLoader = class extends Loader {
  /**
   * Constructs a new LDraw loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.materials = [];
    this.materialLibrary = {};
    this.edgeMaterialCache = /* @__PURE__ */ new WeakMap();
    this.conditionalEdgeMaterialCache = /* @__PURE__ */ new WeakMap();
    this.partsCache = new LDrawPartsGeometryCache(this);
    this.fileMap = {};
    this.smoothNormals = true;
    this.partsLibraryPath = "";
    this.ConditionalLineMaterial = null;
    this.missingColorMaterial = new MeshStandardMaterial({ name: Loader.DEFAULT_MATERIAL_NAME, color: 16711935, roughness: 0.3, metalness: 0 });
    this.missingEdgeColorMaterial = new LineBasicMaterial({ name: Loader.DEFAULT_MATERIAL_NAME, color: 16711935 });
    this.missingConditionalEdgeColorMaterial = null;
    this.edgeMaterialCache.set(this.missingColorMaterial, this.missingEdgeColorMaterial);
    this.conditionalEdgeMaterialCache.set(this.missingEdgeColorMaterial, this.missingConditionalEdgeColorMaterial);
  }
  /**
   * This method must be called prior to `load()` unless the model to load does not reference
   * library parts (usually it will be a model with all its parts packed in a single file).
   *
   * @param {string} path - Path to library parts files to load referenced parts from.
   * This is different from Loader.setPath, which indicates the path to load the main asset from.
   * @return {LDrawLoader} A reference to this loader.
   */
  setPartsLibraryPath(path) {
    this.partsLibraryPath = path;
    return this;
  }
  /**
   * Sets the conditional line material type which depends on the used renderer.
   * Use {@link LDrawConditionalLineMaterial} when using `WebGLRenderer` and
   * {@link LDrawConditionalLineNodeMaterial} when using `WebGPURenderer`.
   *
   * @param {(LDrawConditionalLineMaterial.constructor|LDrawConditionalLineNodeMaterial.constructor)} type - The conditional line material type.
   * @return {LDrawLoader} A reference to this loader.
   */
  setConditionalLineMaterial(type) {
    this.ConditionalLineMaterial = type;
    this.missingConditionalEdgeColorMaterial = new this.ConditionalLineMaterial({ name: Loader.DEFAULT_MATERIAL_NAME, fog: true, color: 16711935 });
    return this;
  }
  /**
   * This async method preloads materials from a single LDraw file. In the official
   * parts library there is a special file which is loaded always the first (LDConfig.ldr)
   * and contains all the standard color codes. This method is intended to be used with
   * not packed files, for example in an editor where materials are preloaded and parts
   * are loaded on demand.
   *
   * @async
   * @param {string} url - Path of the LDraw materials asset.
   * @return {Promise} A Promise that resolves when the preload has finished.
   */
  async preloadMaterials(url) {
    const fileLoader = new FileLoader(this.manager);
    fileLoader.setPath(this.path);
    fileLoader.setRequestHeader(this.requestHeader);
    fileLoader.setWithCredentials(this.withCredentials);
    const text2 = await fileLoader.loadAsync(url);
    const colorLineRegex = /^0 !COLOUR/;
    const lines = text2.split(/[\n\r]/g);
    const materials = [];
    for (let i = 0, l2 = lines.length; i < l2; i++) {
      const line2 = lines[i];
      if (colorLineRegex.test(line2)) {
        const directive = line2.replace(colorLineRegex, "");
        const material = this.parseColorMetaDirective(new LineParser(directive));
        materials.push(material);
      }
    }
    this.addMaterials(materials);
  }
  /**
   * Starts loading from the given URL and passes the loaded LDraw asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Group)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const fileLoader = new FileLoader(this.manager);
    fileLoader.setPath(this.path);
    fileLoader.setRequestHeader(this.requestHeader);
    fileLoader.setWithCredentials(this.withCredentials);
    fileLoader.load(url, (text2) => {
      this.addDefaultMaterials();
      this.partsCache.parseModel(text2).then((group) => {
        this.applyMaterialsToMesh(group, MAIN_COLOUR_CODE, this.materialLibrary, true);
        this.computeBuildingSteps(group);
        group.userData.fileName = url;
        onLoad(group);
      }).catch(onError);
    }, onProgress, onError);
  }
  /**
   * Parses the given LDraw data and returns the resulting group.
   *
   * @param {string} text - The raw VRML data as a string.
   * @param {function(Group)} onLoad - Executed when the loading/parsing process has been finished.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  parse(text2, onLoad, onError) {
    this.partsCache.parseModel(text2).then((group) => {
      this.applyMaterialsToMesh(group, MAIN_COLOUR_CODE, this.materialLibrary, true);
      this.computeBuildingSteps(group);
      group.userData.fileName = "";
      onLoad(group);
    }).catch(onError);
  }
  /**
   * Sets the loader's material library. This method clears existing
   * material definitions.
   *
   * @param {Array<Material>} materials - The materials to set.
   * @return {LDrawLoader} A reference to this loader.
   */
  setMaterials(materials) {
    this.clearMaterials();
    this.addMaterials(materials);
    return this;
  }
  /**
   * Clears the loader's material library.
   *
   * @return {LDrawLoader} A reference to this loader.
   */
  clearMaterials() {
    this.materialLibrary = {};
    this.materials = [];
    return this;
  }
  /**
   * Adds a list of materials to the loader's material library.
   *
   * @param {Array<Material>} materials - The materials to add.
   * @return {LDrawLoader} A reference to this loader.
   */
  addMaterials(materials) {
    for (let i = 0, l2 = materials.length; i < l2; i++) {
      this.addMaterial(materials[i]);
    }
    return this;
  }
  /**
   * Initializes the loader with default materials.
   *
   * @return {LDrawLoader} A reference to this loader.
   */
  addDefaultMaterials() {
    this.addMaterial(this.parseColorMetaDirective(new LineParser("Main_Colour CODE 16 VALUE #FF8080 EDGE #333333")));
    this.addMaterial(this.parseColorMetaDirective(new LineParser("Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333")));
    return this;
  }
  /**
   * Sets a map which maps referenced library filenames to new filenames.
   * If a fileMap is not specified (the default), library parts will be accessed by trial and
   * error in subfolders 'parts', 'p' and 'models'.
   *
   * @param {Object<string,string>} fileMap - The file map to set.
   * @return {LDrawLoader} A reference to this loader.
   */
  setFileMap(fileMap) {
    this.fileMap = fileMap;
    return this;
  }
  /**
   * Adds a single material to the loader's material library.
   *
   * @param {Material} material - The material to add.
   * @return {LDrawLoader} A reference to this loader.
   */
  addMaterial(material) {
    const matLib = this.materialLibrary;
    if (!matLib[material.userData.code]) {
      this.materials.push(material);
      matLib[material.userData.code] = material;
    }
    return this;
  }
  /**
   * Returns a material for the given color code.
   *
   * @param {string} colorCode - The color code.
   * @return {?Material} The material. Returns `null` if no material has been found.
   */
  getMaterial(colorCode) {
    if (colorCode.startsWith("0x2")) {
      const color = colorCode.substring(3);
      return this.parseColorMetaDirective(new LineParser("Direct_Color_" + color + " CODE -1 VALUE #" + color + " EDGE #" + color));
    }
    return this.materialLibrary[colorCode] || null;
  }
  // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
  // in the material array if they need to be filled in.
  applyMaterialsToMesh(group, parentColorCode, materialHierarchy, finalMaterialPass = false) {
    const loader = this;
    const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
    group.traverse((c2) => {
      if (c2.isMesh || c2.isLineSegments) {
        if (Array.isArray(c2.material)) {
          for (let i = 0, l2 = c2.material.length; i < l2; i++) {
            if (!c2.material[i].isMaterial) {
              c2.material[i] = getMaterial(c2, c2.material[i]);
            }
          }
        } else if (!c2.material.isMaterial) {
          c2.material = getMaterial(c2, c2.material);
        }
      }
    });
    function getMaterial(c2, colorCode) {
      if (parentIsPassthrough && !(colorCode in materialHierarchy) && !finalMaterialPass) {
        return colorCode;
      }
      const forEdge = c2.isLineSegments || c2.isConditionalLine;
      const isPassthrough = !forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
      if (isPassthrough) {
        colorCode = parentColorCode;
      }
      let material = null;
      if (colorCode in materialHierarchy) {
        material = materialHierarchy[colorCode];
      } else if (finalMaterialPass) {
        material = loader.getMaterial(colorCode);
        if (material === null) {
          console.warn(`LDrawLoader: Material properties for code ${colorCode} not available.`);
          material = loader.missingColorMaterial;
        }
      } else {
        return colorCode;
      }
      if (c2.isLineSegments) {
        material = loader.edgeMaterialCache.get(material);
        if (c2.isConditionalLine) {
          material = loader.conditionalEdgeMaterialCache.get(material);
        }
      }
      return material;
    }
  }
  /**
   * Returns the Material for the main LDraw color.
   *
   * For an already loaded LDraw asset, returns the Material associated with the main color code.
   * This method can be useful to modify the main material of a model or part that exposes it.
   *
   * The main color code is the standard way to color an LDraw part. It is '16' for triangles and
   * '24' for edges. Usually a complete model will not expose the main color (that is, no part
   * uses the code '16' at the top level, because they are assigned other specific colors) An LDraw
   *  part file on the other hand will expose the code '16' to be colored, and can have additional
   * fixed colors.
   *
   * @return {?Material} The material. Returns `null` if no material has been found.
   */
  getMainMaterial() {
    return this.getMaterial(MAIN_COLOUR_CODE);
  }
  /**
   * Returns the material for the edges main LDraw color.
   *
   * @return {?Material} The material. Returns `null` if no material has been found.
   */
  getMainEdgeMaterial() {
    const mat = this.getMaterial(MAIN_EDGE_COLOUR_CODE);
    return mat ? this.edgeMaterialCache.get(mat) : null;
  }
  parseColorMetaDirective(lineParser) {
    let code = null;
    let fillColor = "#FF00FF";
    let edgeColor = "#FF00FF";
    let alpha = 1;
    let isTransparent = false;
    let luminance = 0;
    let finishType = FINISH_TYPE_DEFAULT;
    let edgeMaterial = null;
    const name2 = lineParser.getToken();
    if (!name2) {
      throw new Error('LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + ".");
    }
    let token = null;
    while (true) {
      token = lineParser.getToken();
      if (!token) {
        break;
      }
      if (!parseLuminance(token)) {
        switch (token.toUpperCase()) {
          case "CODE":
            code = lineParser.getToken();
            break;
          case "VALUE":
            fillColor = lineParser.getToken();
            if (fillColor.startsWith("0x")) {
              fillColor = "#" + fillColor.substring(2);
            } else if (!fillColor.startsWith("#")) {
              throw new Error("LDrawLoader: Invalid color while parsing material" + lineParser.getLineNumberString() + ".");
            }
            break;
          case "EDGE":
            edgeColor = lineParser.getToken();
            if (edgeColor.startsWith("0x")) {
              edgeColor = "#" + edgeColor.substring(2);
            } else if (!edgeColor.startsWith("#")) {
              edgeMaterial = this.getMaterial(edgeColor);
              if (!edgeMaterial) {
                throw new Error("LDrawLoader: Invalid edge color while parsing material" + lineParser.getLineNumberString() + ".");
              }
              edgeMaterial = this.edgeMaterialCache.get(edgeMaterial);
            }
            break;
          case "ALPHA":
            alpha = parseInt(lineParser.getToken());
            if (isNaN(alpha)) {
              throw new Error("LDrawLoader: Invalid alpha value in material definition" + lineParser.getLineNumberString() + ".");
            }
            alpha = Math.max(0, Math.min(1, alpha / 255));
            if (alpha < 1) {
              isTransparent = true;
            }
            break;
          case "LUMINANCE":
            if (!parseLuminance(lineParser.getToken())) {
              throw new Error("LDrawLoader: Invalid luminance value in material definition" + lineParser.getLineNumberString() + ".");
            }
            break;
          case "CHROME":
            finishType = FINISH_TYPE_CHROME;
            break;
          case "PEARLESCENT":
            finishType = FINISH_TYPE_PEARLESCENT;
            break;
          case "RUBBER":
            finishType = FINISH_TYPE_RUBBER;
            break;
          case "MATTE_METALLIC":
            finishType = FINISH_TYPE_MATTE_METALLIC;
            break;
          case "METAL":
            finishType = FINISH_TYPE_METAL;
            break;
          case "MATERIAL":
            lineParser.setToEnd();
            break;
          default:
            throw new Error('LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + ".");
        }
      }
    }
    let material = null;
    switch (finishType) {
      case FINISH_TYPE_DEFAULT:
        material = new MeshStandardMaterial({ roughness: 0.3, metalness: 0 });
        break;
      case FINISH_TYPE_PEARLESCENT:
        material = new MeshStandardMaterial({ roughness: 0.3, metalness: 0.25 });
        break;
      case FINISH_TYPE_CHROME:
        material = new MeshStandardMaterial({ roughness: 0, metalness: 1 });
        break;
      case FINISH_TYPE_RUBBER:
        material = new MeshStandardMaterial({ roughness: 0.9, metalness: 0 });
        break;
      case FINISH_TYPE_MATTE_METALLIC:
        material = new MeshStandardMaterial({ roughness: 0.8, metalness: 0.4 });
        break;
      case FINISH_TYPE_METAL:
        material = new MeshStandardMaterial({ roughness: 0.2, metalness: 0.85 });
        break;
      default:
        break;
    }
    material.color.setStyle(fillColor, COLOR_SPACE_LDRAW);
    material.transparent = isTransparent;
    material.premultipliedAlpha = true;
    material.opacity = alpha;
    material.depthWrite = !isTransparent;
    material.polygonOffset = true;
    material.polygonOffsetFactor = 1;
    if (luminance !== 0) {
      material.emissive.setStyle(fillColor, COLOR_SPACE_LDRAW).multiplyScalar(luminance);
    }
    if (!edgeMaterial) {
      edgeMaterial = new LineBasicMaterial({
        color: new Color().setStyle(edgeColor, COLOR_SPACE_LDRAW),
        transparent: isTransparent,
        opacity: alpha,
        depthWrite: !isTransparent
      });
      edgeMaterial.color;
      edgeMaterial.userData.code = code;
      edgeMaterial.name = name2 + " - Edge";
      if (this.ConditionalLineMaterial === null) {
        throw new Error("THREE.LDrawLoader: ConditionalLineMaterial type must be specified via .setConditionalLineMaterial().");
      }
      const conditionalEdgeMaterial = new this.ConditionalLineMaterial({
        fog: true,
        transparent: isTransparent,
        depthWrite: !isTransparent,
        color: new Color().setStyle(edgeColor, COLOR_SPACE_LDRAW),
        opacity: alpha
      });
      conditionalEdgeMaterial.userData.code = code;
      conditionalEdgeMaterial.name = name2 + " - Conditional Edge";
      this.conditionalEdgeMaterialCache.set(edgeMaterial, conditionalEdgeMaterial);
    }
    material.userData.code = code;
    material.name = name2;
    this.edgeMaterialCache.set(material, edgeMaterial);
    this.addMaterial(material);
    return material;
    function parseLuminance(token2) {
      let lum;
      if (token2.startsWith("LUMINANCE")) {
        lum = parseInt(token2.substring(9));
      } else {
        lum = parseInt(token2);
      }
      if (isNaN(lum)) {
        return false;
      }
      luminance = Math.max(0, Math.min(1, lum / 255));
      return true;
    }
  }
  computeBuildingSteps(model) {
    let stepNumber = 0;
    model.traverse((c2) => {
      if (c2.isGroup) {
        if (c2.userData.startingBuildingStep) {
          stepNumber++;
        }
        c2.userData.buildingStep = stepNumber;
      }
    });
    model.userData.numBuildingSteps = stepNumber + 1;
  }
};

// node_modules/three/examples/jsm/loaders/LUT3dlLoader.js
var LUT3dlLoader = class extends Loader {
  /**
   * Constructs a new 3DL LUT loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.type = UnsignedByteType;
  }
  /**
   * Sets the texture type.
   *
   * @param {(UnsignedByteType|FloatType)} type - The texture type to set.
   * @return {LUT3dlLoader} A reference to this loader.
   */
  setType(type) {
    this.type = type;
    return this;
  }
  /**
   * Starts loading from the given URL and passes the loaded 3DL LUT asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function({size:number,texture3D:Data3DTexture})} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("text");
    loader.load(url, (text2) => {
      try {
        onLoad(this.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        this.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given 3DL LUT data and returns the resulting 3D data texture.
   *
   * @param {string} input - The raw 3DL LUT data as a string.
   * @return {{size:number,texture3D:Data3DTexture}} The parsed 3DL LUT.
   */
  parse(input) {
    const regExpGridInfo = /^[\d ]+$/m;
    const regExpDataPoints = /^([\d.e+-]+) +([\d.e+-]+) +([\d.e+-]+) *$/gm;
    let result = regExpGridInfo.exec(input);
    if (result === null) {
      throw new Error("LUT3dlLoader: Missing grid information");
    }
    const gridLines = result[0].trim().split(/\s+/g).map(Number);
    const gridStep = gridLines[1] - gridLines[0];
    const size2 = gridLines.length;
    const sizeSq = size2 ** 2;
    for (let i = 1, l2 = gridLines.length; i < l2; ++i) {
      if (gridStep !== gridLines[i] - gridLines[i - 1]) {
        throw new Error("LUT3dlLoader: Inconsistent grid size");
      }
    }
    const dataFloat = new Float32Array(size2 ** 3 * 4);
    let maxValue = 0;
    let index2 = 0;
    while ((result = regExpDataPoints.exec(input)) !== null) {
      const r = Number(result[1]);
      const g3 = Number(result[2]);
      const b3 = Number(result[3]);
      maxValue = Math.max(maxValue, r, g3, b3);
      const bLayer = index2 % size2;
      const gLayer = Math.floor(index2 / size2) % size2;
      const rLayer = Math.floor(index2 / sizeSq) % size2;
      const d4 = (bLayer * sizeSq + gLayer * size2 + rLayer) * 4;
      dataFloat[d4 + 0] = r;
      dataFloat[d4 + 1] = g3;
      dataFloat[d4 + 2] = b3;
      ++index2;
    }
    const bits2 = Math.ceil(Math.log2(maxValue));
    const maxBitValue = Math.pow(2, bits2);
    const data2 = this.type === UnsignedByteType ? new Uint8Array(dataFloat.length) : dataFloat;
    const scale2 = this.type === UnsignedByteType ? 255 : 1;
    for (let i = 0, l2 = data2.length; i < l2; i += 4) {
      const i1 = i + 1;
      const i2 = i + 2;
      const i3 = i + 3;
      data2[i] = dataFloat[i] / maxBitValue * scale2;
      data2[i1] = dataFloat[i1] / maxBitValue * scale2;
      data2[i2] = dataFloat[i2] / maxBitValue * scale2;
      data2[i3] = scale2;
    }
    const texture3D = new Data3DTexture();
    texture3D.image.data = data2;
    texture3D.image.width = size2;
    texture3D.image.height = size2;
    texture3D.image.depth = size2;
    texture3D.format = RGBAFormat;
    texture3D.type = this.type;
    texture3D.magFilter = LinearFilter;
    texture3D.minFilter = LinearFilter;
    texture3D.wrapS = ClampToEdgeWrapping;
    texture3D.wrapT = ClampToEdgeWrapping;
    texture3D.wrapR = ClampToEdgeWrapping;
    texture3D.generateMipmaps = false;
    texture3D.needsUpdate = true;
    return {
      size: size2,
      texture3D
    };
  }
};

// node_modules/three/examples/jsm/loaders/LUTCubeLoader.js
var LUTCubeLoader = class extends Loader {
  /**
   * Constructs a new Cube LUT loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.type = UnsignedByteType;
  }
  /**
   * Sets the texture type.
   *
   * @param {(UnsignedByteType|FloatType)} type - The texture type to set.
   * @return {LUTCubeLoader} A reference to this loader.
   */
  setType(type) {
    this.type = type;
    return this;
  }
  /**
   * Starts loading from the given URL and passes the loaded Cube LUT asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function({title:string,size:number,domainMin:Vector3,domainMax:Vector3,texture3D:Data3DTexture})} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("text");
    loader.load(url, (text2) => {
      try {
        onLoad(this.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        this.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given Cube LUT data and returns the resulting 3D data texture.
   *
   * @param {string} input - The raw Cube LUT data as a string.
   * @return {{title:string,size:number,domainMin:Vector3,domainMax:Vector3,texture3D:Data3DTexture}} The parsed Cube LUT.
   */
  parse(input) {
    const regExpTitle = /TITLE +"([^"]*)"/;
    const regExpSize = /LUT_3D_SIZE +(\d+)/;
    const regExpDomainMin = /DOMAIN_MIN +([\d.]+) +([\d.]+) +([\d.]+)/;
    const regExpDomainMax = /DOMAIN_MAX +([\d.]+) +([\d.]+) +([\d.]+)/;
    const regExpDataPoints = /^([\d.e+-]+) +([\d.e+-]+) +([\d.e+-]+) *$/gm;
    let result = regExpTitle.exec(input);
    const title = result !== null ? result[1] : null;
    result = regExpSize.exec(input);
    if (result === null) {
      throw new Error("LUTCubeLoader: Missing LUT_3D_SIZE information");
    }
    const size2 = Number(result[1]);
    const length2 = size2 ** 3 * 4;
    const data2 = this.type === UnsignedByteType ? new Uint8Array(length2) : new Float32Array(length2);
    const domainMin = new Vector3(0, 0, 0);
    const domainMax = new Vector3(1, 1, 1);
    result = regExpDomainMin.exec(input);
    if (result !== null) {
      domainMin.set(Number(result[1]), Number(result[2]), Number(result[3]));
    }
    result = regExpDomainMax.exec(input);
    if (result !== null) {
      domainMax.set(Number(result[1]), Number(result[2]), Number(result[3]));
    }
    if (domainMin.x > domainMax.x || domainMin.y > domainMax.y || domainMin.z > domainMax.z) {
      throw new Error("LUTCubeLoader: Invalid input domain");
    }
    const scale2 = this.type === UnsignedByteType ? 255 : 1;
    let i = 0;
    while ((result = regExpDataPoints.exec(input)) !== null) {
      data2[i++] = Number(result[1]) * scale2;
      data2[i++] = Number(result[2]) * scale2;
      data2[i++] = Number(result[3]) * scale2;
      data2[i++] = scale2;
    }
    const texture3D = new Data3DTexture();
    texture3D.image.data = data2;
    texture3D.image.width = size2;
    texture3D.image.height = size2;
    texture3D.image.depth = size2;
    texture3D.type = this.type;
    texture3D.magFilter = LinearFilter;
    texture3D.minFilter = LinearFilter;
    texture3D.wrapS = ClampToEdgeWrapping;
    texture3D.wrapT = ClampToEdgeWrapping;
    texture3D.wrapR = ClampToEdgeWrapping;
    texture3D.generateMipmaps = false;
    texture3D.needsUpdate = true;
    return {
      title,
      size: size2,
      domainMin,
      domainMax,
      texture3D
    };
  }
};

// node_modules/three/examples/jsm/loaders/lwo/LWO2Parser.js
var LWO2Parser = class {
  constructor(IFFParser2) {
    this.IFF = IFFParser2;
  }
  parseBlock() {
    this.IFF.debugger.offset = this.IFF.reader.offset;
    this.IFF.debugger.closeForms();
    const blockID = this.IFF.reader.getIDTag();
    let length2 = this.IFF.reader.getUint32();
    if (length2 > this.IFF.reader.dv.byteLength - this.IFF.reader.offset) {
      this.IFF.reader.offset -= 4;
      length2 = this.IFF.reader.getUint16();
    }
    this.IFF.debugger.dataOffset = this.IFF.reader.offset;
    this.IFF.debugger.length = length2;
    switch (blockID) {
      case "FORM":
        this.IFF.parseForm(length2);
        break;
      // SKIPPED CHUNKS
      // if break; is called directly, the position in the lwoTree is not created
      // any sub chunks and forms are added to the parent form instead
      // MISC skipped
      case "ICON":
      // Thumbnail Icon Image
      case "VMPA":
      // Vertex Map Parameter
      case "BBOX":
      // bounding box
      // case 'VMMD':
      // case 'VTYP':
      // normal maps can be specified, normally on models imported from other applications. Currently ignored
      case "NORM":
      // ENVL FORM skipped
      case "PRE ":
      case "POST":
      case "KEY ":
      case "SPAN":
      // CLIP FORM skipped
      case "TIME":
      case "CLRS":
      case "CLRA":
      case "FILT":
      case "DITH":
      case "CONT":
      case "BRIT":
      case "SATR":
      case "HUE ":
      case "GAMM":
      case "NEGA":
      case "IFLT":
      case "PFLT":
      // Image Map Layer skipped
      case "PROJ":
      case "AXIS":
      case "AAST":
      case "PIXB":
      case "AUVO":
      case "STCK":
      // Procedural Textures skipped
      case "PROC":
      case "VALU":
      case "FUNC":
      // Gradient Textures skipped
      case "PNAM":
      case "INAM":
      case "GRST":
      case "GREN":
      case "GRPT":
      case "FKEY":
      case "IKEY":
      // Texture Mapping Form skipped
      case "CSYS":
      // Surface CHUNKs skipped
      case "OPAQ":
      // top level 'opacity' checkbox
      case "CMAP":
      // clip map
      // Surface node CHUNKS skipped
      // These mainly specify the node editor setup in LW
      case "NLOC":
      case "NZOM":
      case "NVER":
      case "NSRV":
      case "NVSK":
      // unknown
      case "NCRD":
      case "WRPW":
      // image wrap w ( for cylindrical and spherical projections)
      case "WRPH":
      // image wrap h
      case "NMOD":
      case "NSEL":
      case "NPRW":
      case "NPLA":
      case "NODS":
      case "VERS":
      case "ENUM":
      case "TAG ":
      case "OPAC":
      // Car Material CHUNKS
      case "CGMD":
      case "CGTY":
      case "CGST":
      case "CGEN":
      case "CGTS":
      case "CGTE":
      case "OSMP":
      case "OMDE":
      case "OUTR":
      case "FLAG":
      case "TRNL":
      case "GLOW":
      case "GVAL":
      // glow intensity
      case "SHRP":
      case "RFOP":
      case "RSAN":
      case "TROP":
      case "RBLR":
      case "TBLR":
      case "CLRH":
      case "CLRF":
      case "ADTR":
      case "LINE":
      case "ALPH":
      case "VCOL":
      case "ENAB":
        this.IFF.debugger.skipped = true;
        this.IFF.reader.skip(length2);
        break;
      case "SURF":
        this.IFF.parseSurfaceLwo2(length2);
        break;
      case "CLIP":
        this.IFF.parseClipLwo2(length2);
        break;
      // Texture node chunks (not in spec)
      case "IPIX":
      // usePixelBlending
      case "IMIP":
      // useMipMaps
      case "IMOD":
      // imageBlendingMode
      case "AMOD":
      // unknown
      case "IINV":
      // imageInvertAlpha
      case "INCR":
      // imageInvertColor
      case "IAXS":
      // imageAxis ( for non-UV maps)
      case "IFOT":
      // imageFallofType
      case "ITIM":
      // timing for animated textures
      case "IWRL":
      case "IUTI":
      case "IINX":
      case "IINY":
      case "IINZ":
      case "IREF":
        if (length2 === 4) this.IFF.currentNode[blockID] = this.IFF.reader.getInt32();
        else this.IFF.reader.skip(length2);
        break;
      case "OTAG":
        this.IFF.parseObjectTag();
        break;
      case "LAYR":
        this.IFF.parseLayer(length2);
        break;
      case "PNTS":
        this.IFF.parsePoints(length2);
        break;
      case "VMAP":
        this.IFF.parseVertexMapping(length2);
        break;
      case "AUVU":
      case "AUVN":
        this.IFF.reader.skip(length2 - 1);
        this.IFF.reader.getVariableLengthIndex();
        break;
      case "POLS":
        this.IFF.parsePolygonList(length2);
        break;
      case "TAGS":
        this.IFF.parseTagStrings(length2);
        break;
      case "PTAG":
        this.IFF.parsePolygonTagMapping(length2);
        break;
      case "VMAD":
        this.IFF.parseVertexMapping(length2, true);
        break;
      // Misc CHUNKS
      case "DESC":
        this.IFF.currentForm.description = this.IFF.reader.getString();
        break;
      case "TEXT":
      case "CMNT":
      case "NCOM":
        this.IFF.currentForm.comment = this.IFF.reader.getString();
        break;
      // Envelope Form
      case "NAME":
        this.IFF.currentForm.channelName = this.IFF.reader.getString();
        break;
      // Image Map Layer
      case "WRAP":
        this.IFF.currentForm.wrap = { w: this.IFF.reader.getUint16(), h: this.IFF.reader.getUint16() };
        break;
      case "IMAG":
        const index2 = this.IFF.reader.getVariableLengthIndex();
        this.IFF.currentForm.imageIndex = index2;
        break;
      // Texture Mapping Form
      case "OREF":
        this.IFF.currentForm.referenceObject = this.IFF.reader.getString();
        break;
      case "ROID":
        this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32();
        break;
      // Surface Blocks
      case "SSHN":
        this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString();
        break;
      case "AOVN":
        this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString();
        break;
      // Nodal Blocks
      case "NSTA":
        this.IFF.currentForm.disabled = this.IFF.reader.getUint16();
        break;
      case "NRNM":
        this.IFF.currentForm.realName = this.IFF.reader.getString();
        break;
      case "NNME":
        this.IFF.currentForm.refName = this.IFF.reader.getString();
        this.IFF.currentSurface.nodes[this.IFF.currentForm.refName] = this.IFF.currentForm;
        break;
      // Nodal Blocks : connections
      case "INME":
        if (!this.IFF.currentForm.nodeName) this.IFF.currentForm.nodeName = [];
        this.IFF.currentForm.nodeName.push(this.IFF.reader.getString());
        break;
      case "IINN":
        if (!this.IFF.currentForm.inputNodeName) this.IFF.currentForm.inputNodeName = [];
        this.IFF.currentForm.inputNodeName.push(this.IFF.reader.getString());
        break;
      case "IINM":
        if (!this.IFF.currentForm.inputName) this.IFF.currentForm.inputName = [];
        this.IFF.currentForm.inputName.push(this.IFF.reader.getString());
        break;
      case "IONM":
        if (!this.IFF.currentForm.inputOutputName) this.IFF.currentForm.inputOutputName = [];
        this.IFF.currentForm.inputOutputName.push(this.IFF.reader.getString());
        break;
      case "FNAM":
        this.IFF.currentForm.fileName = this.IFF.reader.getString();
        break;
      case "CHAN":
        if (length2 === 4) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();
        else this.IFF.reader.skip(length2);
        break;
      // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
      case "SMAN":
        const maxSmoothingAngle = this.IFF.reader.getFloat32();
        this.IFF.currentSurface.attributes.smooth = maxSmoothingAngle < 0 ? false : true;
        break;
      // LWO2: Basic Surface Parameters
      case "COLR":
        this.IFF.currentSurface.attributes.Color = { value: this.IFF.reader.getFloat32Array(3) };
        this.IFF.reader.skip(2);
        break;
      case "LUMI":
        this.IFF.currentSurface.attributes.Luminosity = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "SPEC":
        this.IFF.currentSurface.attributes.Specular = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "DIFF":
        this.IFF.currentSurface.attributes.Diffuse = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "REFL":
        this.IFF.currentSurface.attributes.Reflection = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "GLOS":
        this.IFF.currentSurface.attributes.Glossiness = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "TRAN":
        this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32();
        this.IFF.reader.skip(2);
        break;
      case "BUMP":
        this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32();
        this.IFF.reader.skip(2);
        break;
      case "SIDE":
        this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16();
        break;
      case "RIMG":
        this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex();
        break;
      case "RIND":
        this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32();
        this.IFF.reader.skip(2);
        break;
      case "TIMG":
        this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex();
        break;
      case "IMAP":
        this.IFF.reader.skip(2);
        break;
      case "TMAP":
        this.IFF.debugger.skipped = true;
        this.IFF.reader.skip(length2);
        break;
      case "IUVI":
        this.IFF.currentNode.UVChannel = this.IFF.reader.getString(length2);
        break;
      case "IUTL":
        this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32();
        break;
      case "IVTL":
        this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32();
        break;
      // LWO2 USE
      case "BLOK":
        break;
      default:
        this.IFF.parseUnknownCHUNK(blockID, length2);
    }
    if (blockID != "FORM") {
      this.IFF.debugger.node = 1;
      this.IFF.debugger.nodeID = blockID;
      this.IFF.debugger.log();
    }
    if (this.IFF.reader.offset >= this.IFF.currentFormEnd) {
      this.IFF.currentForm = this.IFF.parentForm;
    }
  }
};

// node_modules/three/examples/jsm/loaders/lwo/LWO3Parser.js
var LWO3Parser = class {
  constructor(IFFParser2) {
    this.IFF = IFFParser2;
  }
  parseBlock() {
    this.IFF.debugger.offset = this.IFF.reader.offset;
    this.IFF.debugger.closeForms();
    const blockID = this.IFF.reader.getIDTag();
    const length2 = this.IFF.reader.getUint32();
    this.IFF.debugger.dataOffset = this.IFF.reader.offset;
    this.IFF.debugger.length = length2;
    switch (blockID) {
      case "FORM":
        this.IFF.parseForm(length2);
        break;
      // SKIPPED CHUNKS
      // MISC skipped
      case "ICON":
      // Thumbnail Icon Image
      case "VMPA":
      // Vertex Map Parameter
      case "BBOX":
      // bounding box
      // case 'VMMD':
      // case 'VTYP':
      // normal maps can be specified, normally on models imported from other applications. Currently ignored
      case "NORM":
      // ENVL FORM skipped
      case "PRE ":
      // Pre-loop behavior for the keyframe
      case "POST":
      // Post-loop behavior for the keyframe
      case "KEY ":
      case "SPAN":
      // CLIP FORM skipped
      case "TIME":
      case "CLRS":
      case "CLRA":
      case "FILT":
      case "DITH":
      case "CONT":
      case "BRIT":
      case "SATR":
      case "HUE ":
      case "GAMM":
      case "NEGA":
      case "IFLT":
      case "PFLT":
      // Image Map Layer skipped
      case "PROJ":
      case "AXIS":
      case "AAST":
      case "PIXB":
      case "STCK":
      // Procedural Textures skipped
      case "VALU":
      // Gradient Textures skipped
      case "PNAM":
      case "INAM":
      case "GRST":
      case "GREN":
      case "GRPT":
      case "FKEY":
      case "IKEY":
      // Texture Mapping Form skipped
      case "CSYS":
      // Surface CHUNKs skipped
      case "OPAQ":
      // top level 'opacity' checkbox
      case "CMAP":
      // clip map
      // Surface node CHUNKS skipped
      // These mainly specify the node editor setup in LW
      case "NLOC":
      case "NZOM":
      case "NVER":
      case "NSRV":
      case "NCRD":
      case "NMOD":
      case "NSEL":
      case "NPRW":
      case "NPLA":
      case "VERS":
      case "ENUM":
      case "TAG ":
      // Car Material CHUNKS
      case "CGMD":
      case "CGTY":
      case "CGST":
      case "CGEN":
      case "CGTS":
      case "CGTE":
      case "OSMP":
      case "OMDE":
      case "OUTR":
      case "FLAG":
      case "TRNL":
      case "SHRP":
      case "RFOP":
      case "RSAN":
      case "TROP":
      case "RBLR":
      case "TBLR":
      case "CLRH":
      case "CLRF":
      case "ADTR":
      case "GLOW":
      case "LINE":
      case "ALPH":
      case "VCOL":
      case "ENAB":
        this.IFF.debugger.skipped = true;
        this.IFF.reader.skip(length2);
        break;
      // Texture node chunks (not in spec)
      case "IPIX":
      // usePixelBlending
      case "IMIP":
      // useMipMaps
      case "IMOD":
      // imageBlendingMode
      case "AMOD":
      // unknown
      case "IINV":
      // imageInvertAlpha
      case "INCR":
      // imageInvertColor
      case "IAXS":
      // imageAxis ( for non-UV maps)
      case "IFOT":
      // imageFallofType
      case "ITIM":
      // timing for animated textures
      case "IWRL":
      case "IUTI":
      case "IINX":
      case "IINY":
      case "IINZ":
      case "IREF":
        if (length2 === 4) this.IFF.currentNode[blockID] = this.IFF.reader.getInt32();
        else this.IFF.reader.skip(length2);
        break;
      case "OTAG":
        this.IFF.parseObjectTag();
        break;
      case "LAYR":
        this.IFF.parseLayer(length2);
        break;
      case "PNTS":
        this.IFF.parsePoints(length2);
        break;
      case "VMAP":
        this.IFF.parseVertexMapping(length2);
        break;
      case "POLS":
        this.IFF.parsePolygonList(length2);
        break;
      case "TAGS":
        this.IFF.parseTagStrings(length2);
        break;
      case "PTAG":
        this.IFF.parsePolygonTagMapping(length2);
        break;
      case "VMAD":
        this.IFF.parseVertexMapping(length2, true);
        break;
      // Misc CHUNKS
      case "DESC":
        this.IFF.currentForm.description = this.IFF.reader.getString();
        break;
      case "TEXT":
      case "CMNT":
      case "NCOM":
        this.IFF.currentForm.comment = this.IFF.reader.getString();
        break;
      // Envelope Form
      case "NAME":
        this.IFF.currentForm.channelName = this.IFF.reader.getString();
        break;
      // Image Map Layer
      case "WRAP":
        this.IFF.currentForm.wrap = { w: this.IFF.reader.getUint16(), h: this.IFF.reader.getUint16() };
        break;
      case "IMAG":
        const index2 = this.IFF.reader.getVariableLengthIndex();
        this.IFF.currentForm.imageIndex = index2;
        break;
      // Texture Mapping Form
      case "OREF":
        this.IFF.currentForm.referenceObject = this.IFF.reader.getString();
        break;
      case "ROID":
        this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32();
        break;
      // Surface Blocks
      case "SSHN":
        this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString();
        break;
      case "AOVN":
        this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString();
        break;
      // Nodal Blocks
      case "NSTA":
        this.IFF.currentForm.disabled = this.IFF.reader.getUint16();
        break;
      case "NRNM":
        this.IFF.currentForm.realName = this.IFF.reader.getString();
        break;
      case "NNME":
        this.IFF.currentForm.refName = this.IFF.reader.getString();
        this.IFF.currentSurface.nodes[this.IFF.currentForm.refName] = this.IFF.currentForm;
        break;
      // Nodal Blocks : connections
      case "INME":
        if (!this.IFF.currentForm.nodeName) this.IFF.currentForm.nodeName = [];
        this.IFF.currentForm.nodeName.push(this.IFF.reader.getString());
        break;
      case "IINN":
        if (!this.IFF.currentForm.inputNodeName) this.IFF.currentForm.inputNodeName = [];
        this.IFF.currentForm.inputNodeName.push(this.IFF.reader.getString());
        break;
      case "IINM":
        if (!this.IFF.currentForm.inputName) this.IFF.currentForm.inputName = [];
        this.IFF.currentForm.inputName.push(this.IFF.reader.getString());
        break;
      case "IONM":
        if (!this.IFF.currentForm.inputOutputName) this.IFF.currentForm.inputOutputName = [];
        this.IFF.currentForm.inputOutputName.push(this.IFF.reader.getString());
        break;
      case "FNAM":
        this.IFF.currentForm.fileName = this.IFF.reader.getString();
        break;
      case "CHAN":
        if (length2 === 4) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();
        else this.IFF.reader.skip(length2);
        break;
      // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
      case "SMAN":
        const maxSmoothingAngle = this.IFF.reader.getFloat32();
        this.IFF.currentSurface.attributes.smooth = maxSmoothingAngle < 0 ? false : true;
        break;
      // LWO2: Basic Surface Parameters
      case "COLR":
        this.IFF.currentSurface.attributes.Color = { value: this.IFF.reader.getFloat32Array(3) };
        this.IFF.reader.skip(2);
        break;
      case "LUMI":
        this.IFF.currentSurface.attributes.Luminosity = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "SPEC":
        this.IFF.currentSurface.attributes.Specular = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "DIFF":
        this.IFF.currentSurface.attributes.Diffuse = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "REFL":
        this.IFF.currentSurface.attributes.Reflection = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "GLOS":
        this.IFF.currentSurface.attributes.Glossiness = { value: this.IFF.reader.getFloat32() };
        this.IFF.reader.skip(2);
        break;
      case "TRAN":
        this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32();
        this.IFF.reader.skip(2);
        break;
      case "BUMP":
        this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32();
        this.IFF.reader.skip(2);
        break;
      case "SIDE":
        this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16();
        break;
      case "RIMG":
        this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex();
        break;
      case "RIND":
        this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32();
        this.IFF.reader.skip(2);
        break;
      case "TIMG":
        this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex();
        break;
      case "IMAP":
        this.IFF.currentSurface.attributes.imageMapIndex = this.IFF.reader.getUint32();
        break;
      case "IUVI":
        this.IFF.currentNode.UVChannel = this.IFF.reader.getString(length2);
        break;
      case "IUTL":
        this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32();
        break;
      case "IVTL":
        this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32();
        break;
      default:
        this.IFF.parseUnknownCHUNK(blockID, length2);
    }
    if (blockID != "FORM") {
      this.IFF.debugger.node = 1;
      this.IFF.debugger.nodeID = blockID;
      this.IFF.debugger.log();
    }
    if (this.IFF.reader.offset >= this.IFF.currentFormEnd) {
      this.IFF.currentForm = this.IFF.parentForm;
    }
  }
};

// node_modules/three/examples/jsm/loaders/lwo/IFFParser.js
var IFFParser = class {
  constructor() {
    this.debugger = new Debugger();
  }
  parse(buffer) {
    this.reader = new DataViewReader(buffer);
    this.tree = {
      materials: {},
      layers: [],
      tags: [],
      textures: []
    };
    this.currentLayer = this.tree;
    this.currentForm = this.tree;
    this.parseTopForm();
    if (this.tree.format === void 0) return;
    if (this.tree.format === "LWO2") {
      this.parser = new LWO2Parser(this);
      while (!this.reader.endOfFile()) this.parser.parseBlock();
    } else if (this.tree.format === "LWO3") {
      this.parser = new LWO3Parser(this);
      while (!this.reader.endOfFile()) this.parser.parseBlock();
    }
    this.debugger.offset = this.reader.offset;
    this.debugger.closeForms();
    return this.tree;
  }
  parseTopForm() {
    this.debugger.offset = this.reader.offset;
    const topForm = this.reader.getIDTag();
    if (topForm !== "FORM") {
      console.warn("LWOLoader: Top-level FORM missing.");
      return;
    }
    const length2 = this.reader.getUint32();
    this.debugger.dataOffset = this.reader.offset;
    this.debugger.length = length2;
    const type = this.reader.getIDTag();
    if (type === "LWO2") {
      this.tree.format = type;
    } else if (type === "LWO3") {
      this.tree.format = type;
    }
    this.debugger.node = 0;
    this.debugger.nodeID = type;
    this.debugger.log();
    return;
  }
  ///
  // FORM PARSING METHODS
  ///
  // Forms are organisational and can contain any number of sub chunks and sub forms
  // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * }
  parseForm(length2) {
    const type = this.reader.getIDTag();
    switch (type) {
      // SKIPPED FORMS
      // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped
      case "ISEQ":
      // Image sequence
      case "ANIM":
      // plug in animation
      case "STCC":
      // Color-cycling Still
      case "VPVL":
      case "VPRM":
      case "NROT":
      case "WRPW":
      // image wrap w ( for cylindrical and spherical projections)
      case "WRPH":
      // image wrap h
      case "FUNC":
      case "FALL":
      case "OPAC":
      case "GRAD":
      // gradient texture
      case "ENVS":
      case "VMOP":
      case "VMBG":
      // Car Material FORMS
      case "OMAX":
      case "STEX":
      case "CKBG":
      case "CKEY":
      case "VMLA":
      case "VMLB":
        this.debugger.skipped = true;
        this.skipForm(length2);
        break;
      // if break; is called directly, the position in the lwoTree is not created
      // any sub chunks and forms are added to the parent form instead
      case "META":
      case "NNDS":
      case "NODS":
      case "NDTA":
      case "ADAT":
      case "AOVS":
      case "BLOK":
      // used by texture nodes
      case "IBGC":
      // imageBackgroundColor
      case "IOPC":
      // imageOpacity
      case "IIMG":
      // hold reference to image path
      case "TXTR":
        this.debugger.length = 4;
        this.debugger.skipped = true;
        break;
      case "IFAL":
      // imageFallof
      case "ISCL":
      // imageScale
      case "IPOS":
      // imagePosition
      case "IROT":
      // imageRotation
      case "IBMP":
      case "IUTD":
      case "IVTD":
        this.parseTextureNodeAttribute(type);
        break;
      case "ENVL":
        this.parseEnvelope(length2);
        break;
      // CLIP FORM AND SUB FORMS
      case "CLIP":
        if (this.tree.format === "LWO2") {
          this.parseForm(length2);
        } else {
          this.parseClip(length2);
        }
        break;
      case "STIL":
        this.parseImage();
        break;
      case "XREF":
        this.reader.skip(8);
        this.currentForm.referenceTexture = {
          index: this.reader.getUint32(),
          refName: this.reader.getString()
          // internal unique ref
        };
        break;
      // Not in spec, used by texture nodes
      case "IMST":
        this.parseImageStateForm(length2);
        break;
      // SURF FORM AND SUB FORMS
      case "SURF":
        this.parseSurfaceForm(length2);
        break;
      case "VALU":
        this.parseValueForm(length2);
        break;
      case "NTAG":
        this.parseSubNode(length2);
        break;
      case "ATTR":
      // BSDF Node Attributes
      case "SATR":
        this.setupForm("attributes", length2);
        break;
      case "NCON":
        this.parseConnections(length2);
        break;
      case "SSHA":
        this.parentForm = this.currentForm;
        this.currentForm = this.currentSurface;
        this.setupForm("surfaceShader", length2);
        break;
      case "SSHD":
        this.setupForm("surfaceShaderData", length2);
        break;
      case "ENTR":
        this.parseEntryForm(length2);
        break;
      // Image Map Layer
      case "IMAP":
        this.parseImageMap(length2);
        break;
      case "TAMP":
        this.parseXVAL("amplitude", length2);
        break;
      //Texture Mapping Form
      case "TMAP":
        this.setupForm("textureMap", length2);
        break;
      case "CNTR":
        this.parseXVAL3("center", length2);
        break;
      case "SIZE":
        this.parseXVAL3("scale", length2);
        break;
      case "ROTA":
        this.parseXVAL3("rotation", length2);
        break;
      default:
        this.parseUnknownForm(type, length2);
    }
    this.debugger.node = 0;
    this.debugger.nodeID = type;
    this.debugger.log();
  }
  setupForm(type, length2) {
    if (!this.currentForm) this.currentForm = this.currentNode;
    this.currentFormEnd = this.reader.offset + length2;
    this.parentForm = this.currentForm;
    if (!this.currentForm[type]) {
      this.currentForm[type] = {};
      this.currentForm = this.currentForm[type];
    } else {
      console.warn("LWOLoader: form already exists on parent: ", type, this.currentForm);
      this.currentForm = this.currentForm[type];
    }
  }
  skipForm(length2) {
    this.reader.skip(length2 - 4);
  }
  parseUnknownForm(type, length2) {
    console.warn("LWOLoader: unknown FORM encountered: " + type, length2);
    printBuffer(this.reader.dv.buffer, this.reader.offset, length2 - 4);
    this.reader.skip(length2 - 4);
  }
  parseSurfaceForm(length2) {
    this.reader.skip(8);
    const name2 = this.reader.getString();
    const surface = {
      attributes: {},
      // LWO2 style non-node attributes will go here
      connections: {},
      name: name2,
      inputName: name2,
      nodes: {},
      source: this.reader.getString()
    };
    this.tree.materials[name2] = surface;
    this.currentSurface = surface;
    this.parentForm = this.tree.materials;
    this.currentForm = surface;
    this.currentFormEnd = this.reader.offset + length2;
  }
  parseSurfaceLwo2(length2) {
    const name2 = this.reader.getString();
    const surface = {
      attributes: {},
      // LWO2 style non-node attributes will go here
      connections: {},
      name: name2,
      nodes: {},
      source: this.reader.getString()
    };
    this.tree.materials[name2] = surface;
    this.currentSurface = surface;
    this.parentForm = this.tree.materials;
    this.currentForm = surface;
    this.currentFormEnd = this.reader.offset + length2;
  }
  parseSubNode(length2) {
    this.reader.skip(8);
    const name2 = this.reader.getString();
    const node = {
      name: name2
    };
    this.currentForm = node;
    this.currentNode = node;
    this.currentFormEnd = this.reader.offset + length2;
  }
  // collect attributes from all nodes at the top level of a surface
  parseConnections(length2) {
    this.currentFormEnd = this.reader.offset + length2;
    this.parentForm = this.currentForm;
    this.currentForm = this.currentSurface.connections;
  }
  // surface node attribute data, e.g. specular, roughness etc
  parseEntryForm(length2) {
    this.reader.skip(8);
    const name2 = this.reader.getString();
    this.currentForm = this.currentNode.attributes;
    this.setupForm(name2, length2);
  }
  // parse values from material - doesn't match up to other LWO3 data types
  // sub form of entry form
  parseValueForm() {
    this.reader.skip(8);
    const valueType = this.reader.getString();
    if (valueType === "double") {
      this.currentForm.value = this.reader.getUint64();
    } else if (valueType === "int") {
      this.currentForm.value = this.reader.getUint32();
    } else if (valueType === "vparam") {
      this.reader.skip(24);
      this.currentForm.value = this.reader.getFloat64();
    } else if (valueType === "vparam3") {
      this.reader.skip(24);
      this.currentForm.value = this.reader.getFloat64Array(3);
    }
  }
  // holds various data about texture node image state
  // Data other than mipMapLevel unknown
  parseImageStateForm() {
    this.reader.skip(8);
    this.currentForm.mipMapLevel = this.reader.getFloat32();
  }
  // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node)
  parseImageMap(length2) {
    this.currentFormEnd = this.reader.offset + length2;
    this.parentForm = this.currentForm;
    if (!this.currentForm.maps) this.currentForm.maps = [];
    const map2 = {};
    this.currentForm.maps.push(map2);
    this.currentForm = map2;
    this.reader.skip(10);
  }
  parseTextureNodeAttribute(type) {
    this.reader.skip(28);
    this.reader.skip(20);
    switch (type) {
      case "ISCL":
        this.currentNode.scale = this.reader.getFloat32Array(3);
        break;
      case "IPOS":
        this.currentNode.position = this.reader.getFloat32Array(3);
        break;
      case "IROT":
        this.currentNode.rotation = this.reader.getFloat32Array(3);
        break;
      case "IFAL":
        this.currentNode.falloff = this.reader.getFloat32Array(3);
        break;
      case "IBMP":
        this.currentNode.amplitude = this.reader.getFloat32();
        break;
      case "IUTD":
        this.currentNode.uTiles = this.reader.getFloat32();
        break;
      case "IVTD":
        this.currentNode.vTiles = this.reader.getFloat32();
        break;
    }
    this.reader.skip(2);
  }
  // ENVL forms are currently ignored
  parseEnvelope(length2) {
    this.reader.skip(length2 - 4);
  }
  ///
  // CHUNK PARSING METHODS
  ///
  // clips can either be defined inside a surface node, or at the top
  // level and they have a different format in each case
  parseClip(length2) {
    const tag = this.reader.getIDTag();
    if (tag === "FORM") {
      this.reader.skip(16);
      this.currentNode.fileName = this.reader.getString();
      return;
    }
    this.reader.setOffset(this.reader.offset - 4);
    this.currentFormEnd = this.reader.offset + length2;
    this.parentForm = this.currentForm;
    this.reader.skip(8);
    const texture = {
      index: this.reader.getUint32()
    };
    this.tree.textures.push(texture);
    this.currentForm = texture;
  }
  parseClipLwo2(length2) {
    const texture = {
      index: this.reader.getUint32(),
      fileName: ""
    };
    while (true) {
      const tag = this.reader.getIDTag();
      const n_length = this.reader.getUint16();
      if (tag === "STIL") {
        texture.fileName = this.reader.getString();
        break;
      }
      if (n_length >= length2) {
        break;
      }
    }
    this.tree.textures.push(texture);
    this.currentForm = texture;
  }
  parseImage() {
    this.reader.skip(8);
    this.currentForm.fileName = this.reader.getString();
  }
  parseXVAL(type, length2) {
    const endOffset = this.reader.offset + length2 - 4;
    this.reader.skip(8);
    this.currentForm[type] = this.reader.getFloat32();
    this.reader.setOffset(endOffset);
  }
  parseXVAL3(type, length2) {
    const endOffset = this.reader.offset + length2 - 4;
    this.reader.skip(8);
    this.currentForm[type] = {
      x: this.reader.getFloat32(),
      y: this.reader.getFloat32(),
      z: this.reader.getFloat32()
    };
    this.reader.setOffset(endOffset);
  }
  // Tags associated with an object
  // OTAG { type[ID4], tag-string[S0] }
  parseObjectTag() {
    if (!this.tree.objectTags) this.tree.objectTags = {};
    this.tree.objectTags[this.reader.getIDTag()] = {
      tagString: this.reader.getString()
    };
  }
  // Signals the start of a new layer. All the data chunks which follow will be included in this layer until another layer chunk is encountered.
  // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2]
  parseLayer(length2) {
    const number = this.reader.getUint16();
    const flags = this.reader.getUint16();
    const pivot = this.reader.getFloat32Array(3);
    const layer = {
      number,
      flags,
      // If the least significant bit of flags is set, the layer is hidden.
      pivot: [-pivot[0], pivot[1], pivot[2]],
      // Note: this seems to be superfluous, as the geometry is translated when pivot is present
      name: this.reader.getString()
    };
    this.tree.layers.push(layer);
    this.currentLayer = layer;
    const parsedLength = 16 + stringOffset(this.currentLayer.name);
    this.currentLayer.parent = parsedLength < length2 ? this.reader.getUint16() : -1;
  }
  // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors
  // Converting from left to right handed coordinate system:
  // x -> -x and switch material FrontSide -> BackSide
  parsePoints(length2) {
    this.currentPoints = [];
    for (let i = 0; i < length2 / 4; i += 3) {
      this.currentPoints.push(-this.reader.getFloat32(), this.reader.getFloat32(), this.reader.getFloat32());
    }
  }
  // parse VMAP or VMAD
  // Associates a set of floating-point vectors with a set of points.
  // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * }
  // VMAD Associates a set of floating-point vectors with the vertices of specific polygons.
  // Similar to VMAP UVs, but associates with polygon vertices rather than points
  // to solve to problem of UV seams:  VMAD chunks are paired with VMAPs of the same name,
  // if they exist. The vector values in the VMAD will then replace those in the
  // corresponding VMAP, but only for calculations involving the specified polygons.
  // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * }
  parseVertexMapping(length2, discontinuous) {
    const finalOffset = this.reader.offset + length2;
    const channelName = this.reader.getString();
    if (this.reader.offset === finalOffset) {
      this.currentForm.UVChannel = channelName;
      return;
    }
    this.reader.setOffset(this.reader.offset - stringOffset(channelName));
    const type = this.reader.getIDTag();
    this.reader.getUint16();
    const name2 = this.reader.getString();
    const remainingLength = length2 - 6 - stringOffset(name2);
    switch (type) {
      case "TXUV":
        this.parseUVMapping(name2, finalOffset, discontinuous);
        break;
      case "MORF":
      case "SPOT":
        this.parseMorphTargets(name2, finalOffset, type);
        break;
      // unsupported VMAPs
      case "APSL":
      case "NORM":
      case "WGHT":
      case "MNVW":
      case "PICK":
      case "RGB ":
      case "RGBA":
        this.reader.skip(remainingLength);
        break;
      default:
        console.warn("LWOLoader: unknown vertex map type: " + type);
        this.reader.skip(remainingLength);
    }
  }
  parseUVMapping(name2, finalOffset, discontinuous) {
    const uvIndices = [];
    const polyIndices = [];
    const uvs = [];
    while (this.reader.offset < finalOffset) {
      uvIndices.push(this.reader.getVariableLengthIndex());
      if (discontinuous) polyIndices.push(this.reader.getVariableLengthIndex());
      uvs.push(this.reader.getFloat32(), this.reader.getFloat32());
    }
    if (discontinuous) {
      if (!this.currentLayer.discontinuousUVs) this.currentLayer.discontinuousUVs = {};
      this.currentLayer.discontinuousUVs[name2] = {
        uvIndices,
        polyIndices,
        uvs
      };
    } else {
      if (!this.currentLayer.uvs) this.currentLayer.uvs = {};
      this.currentLayer.uvs[name2] = {
        uvIndices,
        uvs
      };
    }
  }
  parseMorphTargets(name2, finalOffset, type) {
    const indices = [];
    const points = [];
    type = type === "MORF" ? "relative" : "absolute";
    while (this.reader.offset < finalOffset) {
      indices.push(this.reader.getVariableLengthIndex());
      points.push(this.reader.getFloat32(), this.reader.getFloat32(), -this.reader.getFloat32());
    }
    if (!this.currentLayer.morphTargets) this.currentLayer.morphTargets = {};
    this.currentLayer.morphTargets[name2] = {
      indices,
      points,
      type
    };
  }
  // A list of polygons for the current layer.
  // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * }
  parsePolygonList(length2) {
    const finalOffset = this.reader.offset + length2;
    const type = this.reader.getIDTag();
    const indices = [];
    const polygonDimensions = [];
    while (this.reader.offset < finalOffset) {
      let numverts = this.reader.getUint16();
      numverts = numverts & 1023;
      polygonDimensions.push(numverts);
      for (let j2 = 0; j2 < numverts; j2++) indices.push(this.reader.getVariableLengthIndex());
    }
    const geometryData = {
      type,
      vertexIndices: indices,
      polygonDimensions,
      points: this.currentPoints
    };
    if (polygonDimensions[0] === 1) geometryData.type = "points";
    else if (polygonDimensions[0] === 2) geometryData.type = "lines";
    this.currentLayer.geometry = geometryData;
  }
  // Lists the tag strings that can be associated with polygons by the PTAG chunk.
  // TAGS { tag-string[S0] * }
  parseTagStrings(length2) {
    this.tree.tags = this.reader.getStringArray(length2);
  }
  // Associates tags of a given type with polygons in the most recent POLS chunk.
  // PTAG { type[ID4], ( poly[VX], tag[U2] ) * }
  parsePolygonTagMapping(length2) {
    const finalOffset = this.reader.offset + length2;
    const type = this.reader.getIDTag();
    if (type === "SURF") this.parseMaterialIndices(finalOffset);
    else {
      this.reader.skip(length2 - 4);
    }
  }
  parseMaterialIndices(finalOffset) {
    this.currentLayer.geometry.materialIndices = [];
    while (this.reader.offset < finalOffset) {
      const polygonIndex = this.reader.getVariableLengthIndex();
      const materialIndex = this.reader.getUint16();
      this.currentLayer.geometry.materialIndices.push(polygonIndex, materialIndex);
    }
  }
  parseUnknownCHUNK(blockID, length2) {
    console.warn("LWOLoader: unknown chunk type: " + blockID + " length: " + length2);
    const data2 = this.reader.getString(length2);
    this.currentForm[blockID] = data2;
  }
};
var DataViewReader = class {
  constructor(buffer) {
    this.dv = new DataView(buffer);
    this.offset = 0;
    this._textDecoder = new TextDecoder();
    this._bytes = new Uint8Array(buffer);
  }
  size() {
    return this.dv.buffer.byteLength;
  }
  setOffset(offset) {
    if (offset > 0 && offset < this.dv.buffer.byteLength) {
      this.offset = offset;
    } else {
      console.error("LWOLoader: invalid buffer offset");
    }
  }
  endOfFile() {
    if (this.offset >= this.size()) return true;
    return false;
  }
  skip(length2) {
    this.offset += length2;
  }
  getUint8() {
    const value2 = this.dv.getUint8(this.offset);
    this.offset += 1;
    return value2;
  }
  getUint16() {
    const value2 = this.dv.getUint16(this.offset);
    this.offset += 2;
    return value2;
  }
  getInt32() {
    const value2 = this.dv.getInt32(this.offset, false);
    this.offset += 4;
    return value2;
  }
  getUint32() {
    const value2 = this.dv.getUint32(this.offset, false);
    this.offset += 4;
    return value2;
  }
  getUint64() {
    const low = this.getUint32();
    const high = this.getUint32();
    return high * 4294967296 + low;
  }
  getFloat32() {
    const value2 = this.dv.getFloat32(this.offset, false);
    this.offset += 4;
    return value2;
  }
  getFloat32Array(size2) {
    const a2 = [];
    for (let i = 0; i < size2; i++) {
      a2.push(this.getFloat32());
    }
    return a2;
  }
  getFloat64() {
    const value2 = this.dv.getFloat64(this.offset, this.littleEndian);
    this.offset += 8;
    return value2;
  }
  getFloat64Array(size2) {
    const a2 = [];
    for (let i = 0; i < size2; i++) {
      a2.push(this.getFloat64());
    }
    return a2;
  }
  // get variable-length index data type
  // VX ::= index[U2] | (index + 0xFF000000)[U4]
  // If the index value is less than 65,280 (0xFF00),then VX === U2
  // otherwise VX === U4 with bits 24-31 set
  // When reading an index, if the first byte encountered is 255 (0xFF), then
  // the four-byte form is being used and the first byte should be discarded or masked out.
  getVariableLengthIndex() {
    const firstByte = this.getUint8();
    if (firstByte === 255) {
      return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8();
    }
    return firstByte * 256 + this.getUint8();
  }
  // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values
  getIDTag() {
    return this.getString(4);
  }
  getString(size2) {
    if (size2 === 0) return;
    const start = this.offset;
    let result;
    let length2;
    if (size2) {
      length2 = size2;
      result = this._textDecoder.decode(new Uint8Array(this.dv.buffer, start, size2));
    } else {
      length2 = this._bytes.indexOf(0, start) - start;
      result = this._textDecoder.decode(new Uint8Array(this.dv.buffer, start, length2));
      length2++;
      length2 += length2 % 2;
    }
    this.skip(length2);
    return result;
  }
  getStringArray(size2) {
    let a2 = this.getString(size2);
    a2 = a2.split("\0");
    return a2.filter(Boolean);
  }
};
var Debugger = class {
  constructor() {
    this.active = false;
    this.depth = 0;
    this.formList = [];
    this.offset = 0;
    this.node = 0;
    this.nodeID = "FORM";
    this.dataOffset = 0;
    this.length = 0;
    this.skipped = false;
  }
  enable() {
    this.active = true;
  }
  log() {
    if (!this.active) return;
    let nodeType;
    switch (this.node) {
      case 0:
        nodeType = "FORM";
        break;
      case 1:
        nodeType = "CHK";
        break;
      case 2:
        nodeType = "S-CHK";
        break;
    }
    console.log(
      "| ".repeat(this.depth) + nodeType,
      this.nodeID,
      `( ${this.offset} ) -> ( ${this.dataOffset + this.length} )`,
      this.node == 0 ? " {" : "",
      this.skipped ? "SKIPPED" : "",
      this.node == 0 && this.skipped ? "}" : ""
    );
    if (this.node == 0 && !this.skipped) {
      this.depth += 1;
      this.formList.push(this.dataOffset + this.length);
    }
    this.skipped = false;
  }
  closeForms() {
    if (!this.active) return;
    for (let i = this.formList.length - 1; i >= 0; i--) {
      if (this.offset >= this.formList[i]) {
        this.depth -= 1;
        console.log("| ".repeat(this.depth) + "}");
        this.formList.splice(-1, 1);
      }
    }
  }
};
function stringOffset(string) {
  return string.length + 1 + (string.length + 1) % 2;
}
function printBuffer(buffer, from, to) {
  console.log(new TextDecoder().decode(new Uint8Array(buffer, from, to)));
}

// node_modules/three/examples/jsm/loaders/LWOLoader.js
var _lwoTree;
var LWOLoader = class extends Loader {
  /**
   * Constructs a new LWO loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded LWO asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function({meshes:Array<Mesh>,materials:Array<Material>})} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const path = scope.path === "" ? extractParentUrl(url, "Objects") : scope.path;
    const modelName = url.split(path).pop().split(".")[0];
    const loader = new FileLoader(this.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.load(url, function(buffer) {
      try {
        onLoad(scope.parse(buffer, path, modelName));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given LWO data and returns the resulting meshes and materials.
   *
   * @param {ArrayBuffer} iffBuffer - The raw LWO data as an array buffer.
   * @param {string} path - The URL base path.
   * @param {string} modelName - The model name.
   * @return {{meshes:Array<Mesh>,materials:Array<Material>}} An object holding the parse meshes and materials.
   */
  parse(iffBuffer, path, modelName) {
    _lwoTree = new IFFParser().parse(iffBuffer);
    const textureLoader = new TextureLoader(this.manager).setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
    return new LWOTreeParser(textureLoader).parse(modelName);
  }
};
var LWOTreeParser = class {
  constructor(textureLoader) {
    this.textureLoader = textureLoader;
  }
  parse(modelName) {
    this.materials = new MaterialParser(this.textureLoader).parse();
    this.defaultLayerName = modelName;
    this.meshes = this.parseLayers();
    return {
      materials: this.materials,
      meshes: this.meshes
    };
  }
  parseLayers() {
    const meshes = [];
    const finalMeshes = [];
    const geometryParser = new GeometryParser2();
    const scope = this;
    _lwoTree.layers.forEach(function(layer) {
      const geometry = geometryParser.parse(layer.geometry, layer);
      const mesh = scope.parseMesh(geometry, layer);
      meshes[layer.number] = mesh;
      if (layer.parent === -1) finalMeshes.push(mesh);
      else meshes[layer.parent].add(mesh);
    });
    this.applyPivots(finalMeshes);
    return finalMeshes;
  }
  parseMesh(geometry, layer) {
    let mesh;
    const materials = this.getMaterials(geometry.userData.matNames, layer.geometry.type);
    if (layer.geometry.type === "points") mesh = new Points(geometry, materials);
    else if (layer.geometry.type === "lines") mesh = new LineSegments(geometry, materials);
    else mesh = new Mesh(geometry, materials);
    if (layer.name) mesh.name = layer.name;
    else mesh.name = this.defaultLayerName + "_layer_" + layer.number;
    mesh.userData.pivot = layer.pivot;
    return mesh;
  }
  // TODO: may need to be reversed in z to convert LWO to three.js coordinates
  applyPivots(meshes) {
    meshes.forEach(function(mesh) {
      mesh.traverse(function(child) {
        const pivot = child.userData.pivot;
        child.position.x += pivot[0];
        child.position.y += pivot[1];
        child.position.z += pivot[2];
        if (child.parent) {
          const parentPivot = child.parent.userData.pivot;
          child.position.x -= parentPivot[0];
          child.position.y -= parentPivot[1];
          child.position.z -= parentPivot[2];
        }
      });
    });
  }
  getMaterials(namesArray, type) {
    const materials = [];
    const scope = this;
    namesArray.forEach(function(name2, i) {
      materials[i] = scope.getMaterialByName(name2);
    });
    if (type === "points" || type === "lines") {
      materials.forEach(function(mat, i) {
        const spec = {
          color: mat.color
        };
        if (type === "points") {
          spec.size = 0.1;
          spec.map = mat.map;
          materials[i] = new PointsMaterial(spec);
        } else if (type === "lines") {
          materials[i] = new LineBasicMaterial(spec);
        }
      });
    }
    const filtered = materials.filter(Boolean);
    if (filtered.length === 1) return filtered[0];
    return materials;
  }
  getMaterialByName(name2) {
    return this.materials.filter(function(m) {
      return m.name === name2;
    })[0];
  }
};
var MaterialParser = class {
  constructor(textureLoader) {
    this.textureLoader = textureLoader;
  }
  parse() {
    const materials = [];
    this.textures = {};
    for (const name2 in _lwoTree.materials) {
      if (_lwoTree.format === "LWO3") {
        materials.push(this.parseMaterial(_lwoTree.materials[name2], name2, _lwoTree.textures));
      } else if (_lwoTree.format === "LWO2") {
        materials.push(this.parseMaterialLwo2(_lwoTree.materials[name2], name2, _lwoTree.textures));
      }
    }
    return materials;
  }
  parseMaterial(materialData, name2, textures) {
    let params = {
      name: name2,
      side: this.getSide(materialData.attributes),
      flatShading: this.getSmooth(materialData.attributes)
    };
    const connections2 = this.parseConnections(materialData.connections, materialData.nodes);
    const maps = this.parseTextureNodes(connections2.maps);
    this.parseAttributeImageMaps(connections2.attributes, textures, maps);
    const attributes = this.parseAttributes(connections2.attributes, maps);
    this.parseEnvMap(connections2, maps, attributes);
    params = Object.assign(maps, params);
    params = Object.assign(params, attributes);
    const materialType = this.getMaterialType(connections2.attributes);
    if (materialType !== MeshPhongMaterial) delete params.refractionRatio;
    return new materialType(params);
  }
  parseMaterialLwo2(materialData, name2) {
    let params = {
      name: name2,
      side: this.getSide(materialData.attributes),
      flatShading: this.getSmooth(materialData.attributes)
    };
    const attributes = this.parseAttributes(materialData.attributes, {});
    params = Object.assign(params, attributes);
    return new MeshPhongMaterial(params);
  }
  // Note: converting from left to right handed coords by switching x -> -x in vertices, and
  // then switching mat FrontSide -> BackSide
  // NB: this means that FrontSide and BackSide have been switched!
  getSide(attributes) {
    if (!attributes.side) return BackSide;
    switch (attributes.side) {
      case 0:
      case 1:
        return BackSide;
      case 2:
        return FrontSide;
      case 3:
        return DoubleSide;
    }
  }
  getSmooth(attributes) {
    if (!attributes.smooth) return true;
    return !attributes.smooth;
  }
  parseConnections(connections2, nodes) {
    const materialConnections = {
      maps: {}
    };
    const inputName = connections2.inputName;
    const inputNodeName = connections2.inputNodeName;
    const nodeName = connections2.nodeName;
    const scope = this;
    inputName.forEach(function(name2, index2) {
      if (name2 === "Material") {
        const matNode = scope.getNodeByRefName(inputNodeName[index2], nodes);
        materialConnections.attributes = matNode.attributes;
        materialConnections.envMap = matNode.fileName;
        materialConnections.name = inputNodeName[index2];
      }
    });
    nodeName.forEach(function(name2, index2) {
      if (name2 === materialConnections.name) {
        materialConnections.maps[inputName[index2]] = scope.getNodeByRefName(inputNodeName[index2], nodes);
      }
    });
    return materialConnections;
  }
  getNodeByRefName(refName, nodes) {
    for (const name2 in nodes) {
      if (nodes[name2].refName === refName) return nodes[name2];
    }
  }
  parseTextureNodes(textureNodes) {
    const maps = {};
    for (const name2 in textureNodes) {
      const node = textureNodes[name2];
      const path = node.fileName;
      if (!path) return;
      const texture = this.loadTexture(path);
      if (node.widthWrappingMode !== void 0) texture.wrapS = this.getWrappingType(node.widthWrappingMode);
      if (node.heightWrappingMode !== void 0) texture.wrapT = this.getWrappingType(node.heightWrappingMode);
      switch (name2) {
        case "Color":
          maps.map = texture;
          maps.map.colorSpace = SRGBColorSpace;
          break;
        case "Roughness":
          maps.roughnessMap = texture;
          maps.roughness = 1;
          break;
        case "Specular":
          maps.specularMap = texture;
          maps.specularMap.colorSpace = SRGBColorSpace;
          maps.specular = 16777215;
          break;
        case "Luminous":
          maps.emissiveMap = texture;
          maps.emissiveMap.colorSpace = SRGBColorSpace;
          maps.emissive = 8421504;
          break;
        case "Luminous Color":
          maps.emissive = 8421504;
          break;
        case "Metallic":
          maps.metalnessMap = texture;
          maps.metalness = 1;
          break;
        case "Transparency":
        case "Alpha":
          maps.alphaMap = texture;
          maps.transparent = true;
          break;
        case "Normal":
          maps.normalMap = texture;
          if (node.amplitude !== void 0) maps.normalScale = new Vector2(node.amplitude, node.amplitude);
          break;
        case "Bump":
          maps.bumpMap = texture;
          break;
      }
    }
    if (maps.roughnessMap && maps.specularMap) delete maps.specularMap;
    return maps;
  }
  // maps can also be defined on individual material attributes, parse those here
  // This occurs on Standard (Phong) surfaces
  parseAttributeImageMaps(attributes, textures, maps) {
    for (const name2 in attributes) {
      const attribute = attributes[name2];
      if (attribute.maps) {
        const mapData = attribute.maps[0];
        const path = this.getTexturePathByIndex(mapData.imageIndex);
        if (!path) return;
        const texture = this.loadTexture(path);
        if (mapData.wrap !== void 0) texture.wrapS = this.getWrappingType(mapData.wrap.w);
        if (mapData.wrap !== void 0) texture.wrapT = this.getWrappingType(mapData.wrap.h);
        switch (name2) {
          case "Color":
            maps.map = texture;
            maps.map.colorSpace = SRGBColorSpace;
            break;
          case "Diffuse":
            maps.aoMap = texture;
            break;
          case "Roughness":
            maps.roughnessMap = texture;
            maps.roughness = 1;
            break;
          case "Specular":
            maps.specularMap = texture;
            maps.specularMap.colorSpace = SRGBColorSpace;
            maps.specular = 16777215;
            break;
          case "Luminosity":
            maps.emissiveMap = texture;
            maps.emissiveMap.colorSpace = SRGBColorSpace;
            maps.emissive = 8421504;
            break;
          case "Metallic":
            maps.metalnessMap = texture;
            maps.metalness = 1;
            break;
          case "Transparency":
          case "Alpha":
            maps.alphaMap = texture;
            maps.transparent = true;
            break;
          case "Normal":
            maps.normalMap = texture;
            break;
          case "Bump":
            maps.bumpMap = texture;
            break;
        }
      }
    }
  }
  parseAttributes(attributes, maps) {
    const params = {};
    if (attributes.Color && !maps.map) {
      params.color = new Color().fromArray(attributes.Color.value);
    } else {
      params.color = new Color();
    }
    if (attributes.Transparency && attributes.Transparency.value !== 0) {
      params.opacity = 1 - attributes.Transparency.value;
      params.transparent = true;
    }
    if (attributes["Bump Height"]) params.bumpScale = attributes["Bump Height"].value * 0.1;
    this.parsePhysicalAttributes(params, attributes, maps);
    this.parseStandardAttributes(params, attributes, maps);
    this.parsePhongAttributes(params, attributes, maps);
    return params;
  }
  parsePhysicalAttributes(params, attributes) {
    if (attributes.Clearcoat && attributes.Clearcoat.value > 0) {
      params.clearcoat = attributes.Clearcoat.value;
      if (attributes["Clearcoat Gloss"]) {
        params.clearcoatRoughness = 0.5 * (1 - attributes["Clearcoat Gloss"].value);
      }
    }
  }
  parseStandardAttributes(params, attributes, maps) {
    if (attributes.Luminous) {
      params.emissiveIntensity = attributes.Luminous.value;
      if (attributes["Luminous Color"] && !maps.emissive) {
        params.emissive = new Color().fromArray(attributes["Luminous Color"].value);
      } else {
        params.emissive = new Color(8421504);
      }
    }
    if (attributes.Roughness && !maps.roughnessMap) params.roughness = attributes.Roughness.value;
    if (attributes.Metallic && !maps.metalnessMap) params.metalness = attributes.Metallic.value;
  }
  parsePhongAttributes(params, attributes, maps) {
    if (attributes["Refraction Index"]) params.refractionRatio = 0.98 / attributes["Refraction Index"].value;
    if (attributes.Diffuse) params.color.multiplyScalar(attributes.Diffuse.value);
    if (attributes.Reflection) {
      params.reflectivity = attributes.Reflection.value;
      params.combine = AddOperation;
    }
    if (attributes.Luminosity) {
      params.emissiveIntensity = attributes.Luminosity.value;
      if (!maps.emissiveMap && !maps.map) {
        params.emissive = params.color;
      } else {
        params.emissive = new Color(8421504);
      }
    }
    if (!attributes.Roughness && attributes.Specular && !maps.specularMap) {
      if (attributes["Color Highlight"]) {
        params.specular = new Color().setScalar(attributes.Specular.value).lerp(params.color.clone().multiplyScalar(attributes.Specular.value), attributes["Color Highlight"].value);
      } else {
        params.specular = new Color().setScalar(attributes.Specular.value);
      }
    }
    if (params.specular && attributes.Glossiness) params.shininess = 7 + Math.pow(2, attributes.Glossiness.value * 12 + 2);
  }
  parseEnvMap(connections2, maps, attributes) {
    if (connections2.envMap) {
      const envMap = this.loadTexture(connections2.envMap);
      if (attributes.transparent && attributes.opacity < 0.999) {
        envMap.mapping = EquirectangularRefractionMapping;
        if (attributes.reflectivity !== void 0) {
          delete attributes.reflectivity;
          delete attributes.combine;
        }
        if (attributes.metalness !== void 0) {
          attributes.metalness = 1;
        }
        attributes.opacity = 1;
      } else envMap.mapping = EquirectangularReflectionMapping;
      maps.envMap = envMap;
    }
  }
  // get texture defined at top level by its index
  getTexturePathByIndex(index2) {
    let fileName = "";
    if (!_lwoTree.textures) return fileName;
    _lwoTree.textures.forEach(function(texture) {
      if (texture.index === index2) fileName = texture.fileName;
    });
    return fileName;
  }
  loadTexture(path) {
    if (!path) return null;
    const texture = this.textureLoader.load(
      path,
      void 0,
      void 0,
      function() {
        console.warn("LWOLoader: non-standard resource hierarchy. Use `resourcePath` parameter to specify root content directory.");
      }
    );
    return texture;
  }
  // 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  getWrappingType(num) {
    switch (num) {
      case 0:
        console.warn('LWOLoader: "Reset" texture wrapping type is not supported in three.js');
        return ClampToEdgeWrapping;
      case 1:
        return RepeatWrapping;
      case 2:
        return MirroredRepeatWrapping;
      case 3:
        return ClampToEdgeWrapping;
    }
  }
  getMaterialType(nodeData) {
    if (nodeData.Clearcoat && nodeData.Clearcoat.value > 0) return MeshPhysicalMaterial;
    if (nodeData.Roughness) return MeshStandardMaterial;
    return MeshPhongMaterial;
  }
};
var GeometryParser2 = class {
  parse(geoData, layer) {
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(geoData.points, 3));
    const indices = this.splitIndices(geoData.vertexIndices, geoData.polygonDimensions);
    geometry.setIndex(indices);
    this.parseGroups(geometry, geoData);
    geometry.computeVertexNormals();
    this.parseUVs(geometry, layer);
    this.parseMorphTargets(geometry, layer);
    geometry.translate(-layer.pivot[0], -layer.pivot[1], -layer.pivot[2]);
    return geometry;
  }
  // split quads into tris
  splitIndices(indices, polygonDimensions) {
    const remappedIndices = [];
    let i = 0;
    polygonDimensions.forEach(function(dim) {
      if (dim < 4) {
        for (let k2 = 0; k2 < dim; k2++) remappedIndices.push(indices[i + k2]);
      } else if (dim === 4) {
        remappedIndices.push(
          indices[i],
          indices[i + 1],
          indices[i + 2],
          indices[i],
          indices[i + 2],
          indices[i + 3]
        );
      } else if (dim > 4) {
        for (let k2 = 1; k2 < dim - 1; k2++) {
          remappedIndices.push(indices[i], indices[i + k2], indices[i + k2 + 1]);
        }
        console.warn("LWOLoader: polygons with greater than 4 sides are not supported");
      }
      i += dim;
    });
    return remappedIndices;
  }
  // NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
  parseGroups(geometry, geoData) {
    const tags = _lwoTree.tags;
    const matNames = [];
    let elemSize = 3;
    if (geoData.type === "lines") elemSize = 2;
    if (geoData.type === "points") elemSize = 1;
    const remappedIndices = this.splitMaterialIndices(geoData.polygonDimensions, geoData.materialIndices);
    let indexNum = 0;
    const indexPairs = {};
    let prevMaterialIndex;
    let materialIndex;
    let prevStart = 0;
    let currentCount = 0;
    for (let i = 0; i < remappedIndices.length; i += 2) {
      materialIndex = remappedIndices[i + 1];
      if (i === 0) matNames[indexNum] = tags[materialIndex];
      if (prevMaterialIndex === void 0) prevMaterialIndex = materialIndex;
      if (materialIndex !== prevMaterialIndex) {
        let currentIndex;
        if (indexPairs[tags[prevMaterialIndex]]) {
          currentIndex = indexPairs[tags[prevMaterialIndex]];
        } else {
          currentIndex = indexNum;
          indexPairs[tags[prevMaterialIndex]] = indexNum;
          matNames[indexNum] = tags[prevMaterialIndex];
          indexNum++;
        }
        geometry.addGroup(prevStart, currentCount, currentIndex);
        prevStart += currentCount;
        prevMaterialIndex = materialIndex;
        currentCount = 0;
      }
      currentCount += elemSize;
    }
    if (geometry.groups.length > 0) {
      let currentIndex;
      if (indexPairs[tags[materialIndex]]) {
        currentIndex = indexPairs[tags[materialIndex]];
      } else {
        currentIndex = indexNum;
        indexPairs[tags[materialIndex]] = indexNum;
        matNames[indexNum] = tags[materialIndex];
      }
      geometry.addGroup(prevStart, currentCount, currentIndex);
    }
    geometry.userData.matNames = matNames;
  }
  splitMaterialIndices(polygonDimensions, indices) {
    const remappedIndices = [];
    polygonDimensions.forEach(function(dim, i) {
      if (dim <= 3) {
        remappedIndices.push(indices[i * 2], indices[i * 2 + 1]);
      } else if (dim === 4) {
        remappedIndices.push(indices[i * 2], indices[i * 2 + 1], indices[i * 2], indices[i * 2 + 1]);
      } else {
        for (let k2 = 0; k2 < dim - 2; k2++) {
          remappedIndices.push(indices[i * 2], indices[i * 2 + 1]);
        }
      }
    });
    return remappedIndices;
  }
  // UV maps:
  // 1: are defined via index into an array of points, not into a geometry
  // - the geometry is also defined by an index into this array, but the indexes may not match
  // 2: there can be any number of UV maps for a single geometry. Here these are combined,
  // 	with preference given to the first map encountered
  // 3: UV maps can be partial - that is, defined for only a part of the geometry
  // 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
  // UV maps are defined as partially VMAP and partially VMAD
  // VMADs are currently not supported
  parseUVs(geometry, layer) {
    const remappedUVs = Array.from(Array(geometry.attributes.position.count * 2), function() {
      return 0;
    });
    for (const name2 in layer.uvs) {
      const uvs = layer.uvs[name2].uvs;
      const uvIndices = layer.uvs[name2].uvIndices;
      uvIndices.forEach(function(i, j2) {
        remappedUVs[i * 2] = uvs[j2 * 2];
        remappedUVs[i * 2 + 1] = uvs[j2 * 2 + 1];
      });
    }
    geometry.setAttribute("uv", new Float32BufferAttribute(remappedUVs, 2));
  }
  parseMorphTargets(geometry, layer) {
    let num = 0;
    for (const name2 in layer.morphTargets) {
      const remappedPoints = geometry.attributes.position.array.slice();
      if (!geometry.morphAttributes.position) geometry.morphAttributes.position = [];
      const morphPoints = layer.morphTargets[name2].points;
      const morphIndices = layer.morphTargets[name2].indices;
      const type = layer.morphTargets[name2].type;
      morphIndices.forEach(function(i, j2) {
        if (type === "relative") {
          remappedPoints[i * 3] += morphPoints[j2 * 3];
          remappedPoints[i * 3 + 1] += morphPoints[j2 * 3 + 1];
          remappedPoints[i * 3 + 2] += morphPoints[j2 * 3 + 2];
        } else {
          remappedPoints[i * 3] = morphPoints[j2 * 3];
          remappedPoints[i * 3 + 1] = morphPoints[j2 * 3 + 1];
          remappedPoints[i * 3 + 2] = morphPoints[j2 * 3 + 2];
        }
      });
      geometry.morphAttributes.position[num] = new Float32BufferAttribute(remappedPoints, 3);
      geometry.morphAttributes.position[num].name = name2;
      num++;
    }
    geometry.morphTargetsRelative = false;
  }
};
function extractParentUrl(url, dir) {
  const index2 = url.indexOf(dir);
  if (index2 === -1) return "./";
  return url.slice(0, index2);
}

// node_modules/three/examples/jsm/libs/lottie_canvas.module.js
var lottie = {};
if (typeof document !== "undefined") {
  function createTag(type) {
    return document.createElement(type);
  }
  function extendPrototype(sources, destination) {
    var i;
    var len = sources.length;
    var sourcePrototype;
    for (i = 0; i < len; i += 1) {
      sourcePrototype = sources[i].prototype;
      for (var attr in sourcePrototype) {
        if (Object.prototype.hasOwnProperty.call(sourcePrototype, attr)) destination.prototype[attr] = sourcePrototype[attr];
      }
    }
  }
  function getDescriptor(object, prop) {
    return Object.getOwnPropertyDescriptor(object, prop);
  }
  function createProxyFunction(prototype) {
    function ProxyFunction() {
    }
    ProxyFunction.prototype = prototype;
    return ProxyFunction;
  }
  function createSizedArray(len) {
    return Array.apply(null, { length: len });
  }
  function ProjectInterface$1() {
    return {};
  }
  function roundValues(flag) {
    _shouldRoundValues = !!flag;
  }
  function bmRnd(value2) {
    if (_shouldRoundValues) {
      return Math.round(value2);
    }
    return value2;
  }
  function styleDiv(element) {
    element.style.position = "absolute";
    element.style.top = 0;
    element.style.left = 0;
    element.style.display = "block";
    element.style.transformOrigin = "0 0";
    element.style.webkitTransformOrigin = "0 0";
    element.style.backfaceVisibility = "visible";
    element.style.webkitBackfaceVisibility = "visible";
    element.style.transformStyle = "preserve-3d";
    element.style.webkitTransformStyle = "preserve-3d";
    element.style.mozTransformStyle = "preserve-3d";
  }
  function BMEnterFrameEvent(type, currentTime, totalTime, frameMultiplier) {
    this.type = type;
    this.currentTime = currentTime;
    this.totalTime = totalTime;
    this.direction = frameMultiplier < 0 ? -1 : 1;
  }
  function BMCompleteEvent(type, frameMultiplier) {
    this.type = type;
    this.direction = frameMultiplier < 0 ? -1 : 1;
  }
  function BMCompleteLoopEvent(type, totalLoops, currentLoop, frameMultiplier) {
    this.type = type;
    this.currentLoop = currentLoop;
    this.totalLoops = totalLoops;
    this.direction = frameMultiplier < 0 ? -1 : 1;
  }
  function BMSegmentStartEvent(type, firstFrame, totalFrames) {
    this.type = type;
    this.firstFrame = firstFrame;
    this.totalFrames = totalFrames;
  }
  function BMDestroyEvent(type, target) {
    this.type = type;
    this.target = target;
  }
  function BMRenderFrameErrorEvent(nativeError, currentTime) {
    this.type = "renderFrameError";
    this.nativeError = nativeError;
    this.currentTime = currentTime;
  }
  function BMConfigErrorEvent(nativeError) {
    this.type = "configError";
    this.nativeError = nativeError;
  }
  function BMAnimationConfigErrorEvent(type, nativeError) {
    this.type = type;
    this.nativeError = nativeError;
  }
  function HSVtoRGB(h, s, v) {
    var r;
    var g3;
    var b3;
    var i;
    var f;
    var p;
    var q2;
    var t3;
    i = Math.floor(h * 6);
    f = h * 6 - i;
    p = v * (1 - s);
    q2 = v * (1 - f * s);
    t3 = v * (1 - (1 - f) * s);
    switch (i % 6) {
      case 0:
        r = v;
        g3 = t3;
        b3 = p;
        break;
      case 1:
        r = q2;
        g3 = v;
        b3 = p;
        break;
      case 2:
        r = p;
        g3 = v;
        b3 = t3;
        break;
      case 3:
        r = p;
        g3 = q2;
        b3 = v;
        break;
      case 4:
        r = t3;
        g3 = p;
        b3 = v;
        break;
      case 5:
        r = v;
        g3 = p;
        b3 = q2;
        break;
      default:
        break;
    }
    return [
      r,
      g3,
      b3
    ];
  }
  function RGBtoHSV(r, g3, b3) {
    var max2 = Math.max(r, g3, b3);
    var min = Math.min(r, g3, b3);
    var d = max2 - min;
    var h;
    var s = max2 === 0 ? 0 : d / max2;
    var v = max2 / 255;
    switch (max2) {
      case min:
        h = 0;
        break;
      case r:
        h = g3 - b3 + d * (g3 < b3 ? 6 : 0);
        h /= 6 * d;
        break;
      case g3:
        h = b3 - r + d * 2;
        h /= 6 * d;
        break;
      case b3:
        h = r - g3 + d * 4;
        h /= 6 * d;
        break;
      default:
        break;
    }
    return [
      h,
      s,
      v
    ];
  }
  function addSaturationToRGB(color, offset) {
    var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255);
    hsv[1] += offset;
    if (hsv[1] > 1) {
      hsv[1] = 1;
    } else if (hsv[1] <= 0) {
      hsv[1] = 0;
    }
    return HSVtoRGB(hsv[0], hsv[1], hsv[2]);
  }
  function addBrightnessToRGB(color, offset) {
    var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255);
    hsv[2] += offset;
    if (hsv[2] > 1) {
      hsv[2] = 1;
    } else if (hsv[2] < 0) {
      hsv[2] = 0;
    }
    return HSVtoRGB(hsv[0], hsv[1], hsv[2]);
  }
  function addHueToRGB(color, offset) {
    var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255);
    hsv[0] += offset / 360;
    if (hsv[0] > 1) {
      hsv[0] -= 1;
    } else if (hsv[0] < 0) {
      hsv[0] += 1;
    }
    return HSVtoRGB(hsv[0], hsv[1], hsv[2]);
  }
  function createNS(type) {
    return document.createElementNS(svgNS, type);
  }
  function BaseEvent() {
  }
  function getRenderer(key2) {
    return renderers[key2];
  }
  function bezFunction() {
    var math = Math;
    function pointOnLine2D(x1, y1, x2, y2, x3, y3) {
      var det1 = x1 * y2 + y1 * x3 + x2 * y3 - x3 * y2 - y3 * x1 - x2 * y1;
      return det1 > -1e-3 && det1 < 1e-3;
    }
    function pointOnLine3D(x1, y1, z1, x2, y2, z2, x3, y3, z3) {
      if (z1 === 0 && z2 === 0 && z3 === 0) {
        return pointOnLine2D(x1, y1, x2, y2, x3, y3);
      }
      var dist1 = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2) + math.pow(z2 - z1, 2));
      var dist2 = math.sqrt(math.pow(x3 - x1, 2) + math.pow(y3 - y1, 2) + math.pow(z3 - z1, 2));
      var dist3 = math.sqrt(math.pow(x3 - x2, 2) + math.pow(y3 - y2, 2) + math.pow(z3 - z2, 2));
      var diffDist;
      if (dist1 > dist2) {
        if (dist1 > dist3) {
          diffDist = dist1 - dist2 - dist3;
        } else {
          diffDist = dist3 - dist2 - dist1;
        }
      } else if (dist3 > dist2) {
        diffDist = dist3 - dist2 - dist1;
      } else {
        diffDist = dist2 - dist1 - dist3;
      }
      return diffDist > -1e-4 && diffDist < 1e-4;
    }
    var getBezierLength = /* @__PURE__ */ function() {
      return function(pt1, pt2, pt3, pt4) {
        var curveSegments = getDefaultCurveSegments();
        var k2;
        var i;
        var len;
        var ptCoord;
        var perc;
        var addedLength = 0;
        var ptDistance;
        var point = [];
        var lastPoint = [];
        var lengthData = bezierLengthPool.newElement();
        len = pt3.length;
        for (k2 = 0; k2 < curveSegments; k2 += 1) {
          perc = k2 / (curveSegments - 1);
          ptDistance = 0;
          for (i = 0; i < len; i += 1) {
            ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * pt3[i] + 3 * (1 - perc) * bmPow(perc, 2) * pt4[i] + bmPow(perc, 3) * pt2[i];
            point[i] = ptCoord;
            if (lastPoint[i] !== null) {
              ptDistance += bmPow(point[i] - lastPoint[i], 2);
            }
            lastPoint[i] = point[i];
          }
          if (ptDistance) {
            ptDistance = bmSqrt(ptDistance);
            addedLength += ptDistance;
          }
          lengthData.percents[k2] = perc;
          lengthData.lengths[k2] = addedLength;
        }
        lengthData.addedLength = addedLength;
        return lengthData;
      };
    }();
    function getSegmentsLength(shapeData) {
      var segmentsLength = segmentsLengthPool.newElement();
      var closed = shapeData.c;
      var pathV = shapeData.v;
      var pathO = shapeData.o;
      var pathI = shapeData.i;
      var i;
      var len = shapeData._length;
      var lengths2 = segmentsLength.lengths;
      var totalLength = 0;
      for (i = 0; i < len - 1; i += 1) {
        lengths2[i] = getBezierLength(pathV[i], pathV[i + 1], pathO[i], pathI[i + 1]);
        totalLength += lengths2[i].addedLength;
      }
      if (closed && len) {
        lengths2[i] = getBezierLength(pathV[i], pathV[0], pathO[i], pathI[0]);
        totalLength += lengths2[i].addedLength;
      }
      segmentsLength.totalLength = totalLength;
      return segmentsLength;
    }
    function BezierData(length2) {
      this.segmentLength = 0;
      this.points = new Array(length2);
    }
    function PointData(partial2, point) {
      this.partialLength = partial2;
      this.point = point;
    }
    var buildBezierData = /* @__PURE__ */ function() {
      var storedData = {};
      return function(pt1, pt2, pt3, pt4) {
        var bezierName = (pt1[0] + "_" + pt1[1] + "_" + pt2[0] + "_" + pt2[1] + "_" + pt3[0] + "_" + pt3[1] + "_" + pt4[0] + "_" + pt4[1]).replace(/\./g, "p");
        if (!storedData[bezierName]) {
          var curveSegments = getDefaultCurveSegments();
          var k2;
          var i;
          var len;
          var ptCoord;
          var perc;
          var addedLength = 0;
          var ptDistance;
          var point;
          var lastPoint = null;
          if (pt1.length === 2 && (pt1[0] !== pt2[0] || pt1[1] !== pt2[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt1[0] + pt3[0], pt1[1] + pt3[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt2[0] + pt4[0], pt2[1] + pt4[1])) {
            curveSegments = 2;
          }
          var bezierData = new BezierData(curveSegments);
          len = pt3.length;
          for (k2 = 0; k2 < curveSegments; k2 += 1) {
            point = createSizedArray(len);
            perc = k2 / (curveSegments - 1);
            ptDistance = 0;
            for (i = 0; i < len; i += 1) {
              ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * (pt1[i] + pt3[i]) + 3 * (1 - perc) * bmPow(perc, 2) * (pt2[i] + pt4[i]) + bmPow(perc, 3) * pt2[i];
              point[i] = ptCoord;
              if (lastPoint !== null) {
                ptDistance += bmPow(point[i] - lastPoint[i], 2);
              }
            }
            ptDistance = bmSqrt(ptDistance);
            addedLength += ptDistance;
            bezierData.points[k2] = new PointData(ptDistance, point);
            lastPoint = point;
          }
          bezierData.segmentLength = addedLength;
          storedData[bezierName] = bezierData;
        }
        return storedData[bezierName];
      };
    }();
    function getDistancePerc(perc, bezierData) {
      var percents = bezierData.percents;
      var lengths2 = bezierData.lengths;
      var len = percents.length;
      var initPos = bmFloor((len - 1) * perc);
      var lengthPos = perc * bezierData.addedLength;
      var lPerc = 0;
      if (initPos === len - 1 || initPos === 0 || lengthPos === lengths2[initPos]) {
        return percents[initPos];
      }
      var dir = lengths2[initPos] > lengthPos ? -1 : 1;
      var flag = true;
      while (flag) {
        if (lengths2[initPos] <= lengthPos && lengths2[initPos + 1] > lengthPos) {
          lPerc = (lengthPos - lengths2[initPos]) / (lengths2[initPos + 1] - lengths2[initPos]);
          flag = false;
        } else {
          initPos += dir;
        }
        if (initPos < 0 || initPos >= len - 1) {
          if (initPos === len - 1) {
            return percents[initPos];
          }
          flag = false;
        }
      }
      return percents[initPos] + (percents[initPos + 1] - percents[initPos]) * lPerc;
    }
    function getPointInSegment(pt1, pt2, pt3, pt4, percent, bezierData) {
      var t1 = getDistancePerc(percent, bezierData);
      var u1 = 1 - t1;
      var ptX = math.round((u1 * u1 * u1 * pt1[0] + (t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1) * pt3[0] + (t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1) * pt4[0] + t1 * t1 * t1 * pt2[0]) * 1e3) / 1e3;
      var ptY = math.round((u1 * u1 * u1 * pt1[1] + (t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1) * pt3[1] + (t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1) * pt4[1] + t1 * t1 * t1 * pt2[1]) * 1e3) / 1e3;
      return [ptX, ptY];
    }
    var bezierSegmentPoints = createTypedArray("float32", 8);
    function getNewSegment(pt1, pt2, pt3, pt4, startPerc, endPerc, bezierData) {
      if (startPerc < 0) {
        startPerc = 0;
      } else if (startPerc > 1) {
        startPerc = 1;
      }
      var t0 = getDistancePerc(startPerc, bezierData);
      endPerc = endPerc > 1 ? 1 : endPerc;
      var t1 = getDistancePerc(endPerc, bezierData);
      var i;
      var len = pt1.length;
      var u0 = 1 - t0;
      var u1 = 1 - t1;
      var u0u0u0 = u0 * u0 * u0;
      var t0u0u0_3 = t0 * u0 * u0 * 3;
      var t0t0u0_3 = t0 * t0 * u0 * 3;
      var t0t0t0 = t0 * t0 * t0;
      var u0u0u1 = u0 * u0 * u1;
      var t0u0u1_3 = t0 * u0 * u1 + u0 * t0 * u1 + u0 * u0 * t1;
      var t0t0u1_3 = t0 * t0 * u1 + u0 * t0 * t1 + t0 * u0 * t1;
      var t0t0t1 = t0 * t0 * t1;
      var u0u1u1 = u0 * u1 * u1;
      var t0u1u1_3 = t0 * u1 * u1 + u0 * t1 * u1 + u0 * u1 * t1;
      var t0t1u1_3 = t0 * t1 * u1 + u0 * t1 * t1 + t0 * u1 * t1;
      var t0t1t1 = t0 * t1 * t1;
      var u1u1u1 = u1 * u1 * u1;
      var t1u1u1_3 = t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1;
      var t1t1u1_3 = t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1;
      var t1t1t1 = t1 * t1 * t1;
      for (i = 0; i < len; i += 1) {
        bezierSegmentPoints[i * 4] = math.round((u0u0u0 * pt1[i] + t0u0u0_3 * pt3[i] + t0t0u0_3 * pt4[i] + t0t0t0 * pt2[i]) * 1e3) / 1e3;
        bezierSegmentPoints[i * 4 + 1] = math.round((u0u0u1 * pt1[i] + t0u0u1_3 * pt3[i] + t0t0u1_3 * pt4[i] + t0t0t1 * pt2[i]) * 1e3) / 1e3;
        bezierSegmentPoints[i * 4 + 2] = math.round((u0u1u1 * pt1[i] + t0u1u1_3 * pt3[i] + t0t1u1_3 * pt4[i] + t0t1t1 * pt2[i]) * 1e3) / 1e3;
        bezierSegmentPoints[i * 4 + 3] = math.round((u1u1u1 * pt1[i] + t1u1u1_3 * pt3[i] + t1t1u1_3 * pt4[i] + t1t1t1 * pt2[i]) * 1e3) / 1e3;
      }
      return bezierSegmentPoints;
    }
    return {
      getSegmentsLength,
      getNewSegment,
      getPointInSegment,
      buildBezierData,
      pointOnLine2D,
      pointOnLine3D
    };
  }
  function DynamicPropertyContainer() {
  }
  function ShapePath() {
    this.c = false;
    this._length = 0;
    this._maxLength = 8;
    this.v = createSizedArray(this._maxLength);
    this.o = createSizedArray(this._maxLength);
    this.i = createSizedArray(this._maxLength);
  }
  function ShapeCollection() {
    this._length = 0;
    this._maxLength = 4;
    this.shapes = createSizedArray(this._maxLength);
  }
  function setLocation(href) {
    setLocationHref(href);
  }
  function searchAnimations() {
    if (standalone === true) {
      animationManager.searchAnimations(animationData, standalone, renderer);
    } else {
      animationManager.searchAnimations();
    }
  }
  function setSubframeRendering(flag) {
    setSubframeEnabled(flag);
  }
  function setPrefix(prefix) {
    setIdPrefix(prefix);
  }
  function loadAnimation(params) {
    if (standalone === true) {
      params.animationData = JSON.parse(animationData);
    }
    return animationManager.loadAnimation(params);
  }
  function setQuality(value2) {
    if (typeof value2 === "string") {
      switch (value2) {
        case "high":
          setDefaultCurveSegments(200);
          break;
        default:
        case "medium":
          setDefaultCurveSegments(50);
          break;
        case "low":
          setDefaultCurveSegments(10);
          break;
      }
    } else if (!isNaN(value2) && value2 > 1) {
      setDefaultCurveSegments(value2);
    }
    if (getDefaultCurveSegments() >= 50) {
      roundValues(false);
    } else {
      roundValues(true);
    }
  }
  function inBrowser() {
    return typeof navigator !== "undefined";
  }
  function installPlugin(type, plugin) {
    if (type === "expressions") {
      setExpressionsPlugin(plugin);
    }
  }
  function getFactory(name2) {
    switch (name2) {
      case "propertyFactory":
        return PropertyFactory;
      case "shapePropertyFactory":
        return ShapePropertyFactory;
      case "matrix":
        return Matrix;
      default:
        return null;
    }
  }
  function checkReady() {
    if (document.readyState === "complete") {
      clearInterval(readyStateCheckInterval);
      searchAnimations();
    }
  }
  function getQueryVariable(variable) {
    var vars = queryString.split("&");
    for (var i = 0; i < vars.length; i += 1) {
      var pair = vars[i].split("=");
      if (decodeURIComponent(pair[0]) == variable) {
        return decodeURIComponent(pair[1]);
      }
    }
    return null;
  }
  function ShapeModifier() {
  }
  function TrimModifier() {
  }
  function PuckerAndBloatModifier() {
  }
  function RepeaterModifier() {
  }
  function RoundCornersModifier() {
  }
  function getFontProperties(fontData) {
    var styles = fontData.fStyle ? fontData.fStyle.split(" ") : [];
    var fWeight = "normal";
    var fStyle = "normal";
    var len = styles.length;
    var styleName;
    for (var i = 0; i < len; i += 1) {
      styleName = styles[i].toLowerCase();
      switch (styleName) {
        case "italic":
          fStyle = "italic";
          break;
        case "bold":
          fWeight = "700";
          break;
        case "black":
          fWeight = "900";
          break;
        case "medium":
          fWeight = "500";
          break;
        case "regular":
        case "normal":
          fWeight = "400";
          break;
        case "light":
        case "thin":
          fWeight = "200";
          break;
        default:
          break;
      }
    }
    return {
      style: fStyle,
      weight: fontData.fWeight || fWeight
    };
  }
  function RenderableElement() {
  }
  function SliderEffect(data2, elem2, container) {
    this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container);
  }
  function AngleEffect(data2, elem2, container) {
    this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container);
  }
  function ColorEffect(data2, elem2, container) {
    this.p = PropertyFactory.getProp(elem2, data2.v, 1, 0, container);
  }
  function PointEffect(data2, elem2, container) {
    this.p = PropertyFactory.getProp(elem2, data2.v, 1, 0, container);
  }
  function LayerIndexEffect(data2, elem2, container) {
    this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container);
  }
  function MaskIndexEffect(data2, elem2, container) {
    this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container);
  }
  function CheckboxEffect(data2, elem2, container) {
    this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container);
  }
  function NoValueEffect() {
    this.p = {};
  }
  function EffectsManager(data2, element) {
    var effects = data2.ef || [];
    this.effectElements = [];
    var i;
    var len = effects.length;
    var effectItem;
    for (i = 0; i < len; i += 1) {
      effectItem = new GroupEffect(effects[i], element);
      this.effectElements.push(effectItem);
    }
  }
  function GroupEffect(data2, element) {
    this.init(data2, element);
  }
  function BaseElement() {
  }
  function FrameElement() {
  }
  function FootageElement(data2, globalData2, comp2) {
    this.initFrame();
    this.initRenderable();
    this.assetData = globalData2.getAssetData(data2.refId);
    this.footageData = globalData2.imageLoader.getAsset(this.assetData);
    this.initBaseData(data2, globalData2, comp2);
  }
  function AudioElement(data2, globalData2, comp2) {
    this.initFrame();
    this.initRenderable();
    this.assetData = globalData2.getAssetData(data2.refId);
    this.initBaseData(data2, globalData2, comp2);
    this._isPlaying = false;
    this._canPlay = false;
    var assetPath = this.globalData.getAssetsPath(this.assetData);
    this.audio = this.globalData.audioController.createAudio(assetPath);
    this._currentTime = 0;
    this.globalData.audioController.addAudio(this);
    this._volumeMultiplier = 1;
    this._volume = 1;
    this._previousVolume = null;
    this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true };
    this.lv = PropertyFactory.getProp(this, data2.au && data2.au.lv ? data2.au.lv : { k: [100] }, 1, 0.01, this);
  }
  function BaseRenderer() {
  }
  function TransformElement() {
  }
  function MaskElement(data2, element, globalData2) {
    this.data = data2;
    this.element = element;
    this.globalData = globalData2;
    this.storedData = [];
    this.masksProperties = this.data.masksProperties || [];
    this.maskElement = null;
    var defs = this.globalData.defs;
    var i;
    var len = this.masksProperties ? this.masksProperties.length : 0;
    this.viewData = createSizedArray(len);
    this.solidPath = "";
    var path;
    var properties = this.masksProperties;
    var count = 0;
    var currentMasks = [];
    var j2;
    var jLen;
    var layerId = createElementID();
    var rect;
    var expansor;
    var feMorph;
    var x2;
    var maskType = "clipPath";
    var maskRef = "clip-path";
    for (i = 0; i < len; i += 1) {
      if (properties[i].mode !== "a" && properties[i].mode !== "n" || properties[i].inv || properties[i].o.k !== 100 || properties[i].o.x) {
        maskType = "mask";
        maskRef = "mask";
      }
      if ((properties[i].mode === "s" || properties[i].mode === "i") && count === 0) {
        rect = createNS("rect");
        rect.setAttribute("fill", "#ffffff");
        rect.setAttribute("width", this.element.comp.data.w || 0);
        rect.setAttribute("height", this.element.comp.data.h || 0);
        currentMasks.push(rect);
      } else {
        rect = null;
      }
      path = createNS("path");
      if (properties[i].mode === "n") {
        this.viewData[i] = {
          op: PropertyFactory.getProp(this.element, properties[i].o, 0, 0.01, this.element),
          prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3),
          elem: path,
          lastPath: ""
        };
        defs.appendChild(path);
      } else {
        count += 1;
        path.setAttribute("fill", properties[i].mode === "s" ? "#000000" : "#ffffff");
        path.setAttribute("clip-rule", "nonzero");
        var filterID;
        if (properties[i].x.k !== 0) {
          maskType = "mask";
          maskRef = "mask";
          x2 = PropertyFactory.getProp(this.element, properties[i].x, 0, null, this.element);
          filterID = createElementID();
          expansor = createNS("filter");
          expansor.setAttribute("id", filterID);
          feMorph = createNS("feMorphology");
          feMorph.setAttribute("operator", "erode");
          feMorph.setAttribute("in", "SourceGraphic");
          feMorph.setAttribute("radius", "0");
          expansor.appendChild(feMorph);
          defs.appendChild(expansor);
          path.setAttribute("stroke", properties[i].mode === "s" ? "#000000" : "#ffffff");
        } else {
          feMorph = null;
          x2 = null;
        }
        this.storedData[i] = {
          elem: path,
          x: x2,
          expan: feMorph,
          lastPath: "",
          lastOperator: "",
          filterId: filterID,
          lastRadius: 0
        };
        if (properties[i].mode === "i") {
          jLen = currentMasks.length;
          var g3 = createNS("g");
          for (j2 = 0; j2 < jLen; j2 += 1) {
            g3.appendChild(currentMasks[j2]);
          }
          var mask2 = createNS("mask");
          mask2.setAttribute("mask-type", "alpha");
          mask2.setAttribute("id", layerId + "_" + count);
          mask2.appendChild(path);
          defs.appendChild(mask2);
          g3.setAttribute("mask", "url(" + getLocationHref() + "#" + layerId + "_" + count + ")");
          currentMasks.length = 0;
          currentMasks.push(g3);
        } else {
          currentMasks.push(path);
        }
        if (properties[i].inv && !this.solidPath) {
          this.solidPath = this.createLayerSolidPath();
        }
        this.viewData[i] = {
          elem: path,
          lastPath: "",
          op: PropertyFactory.getProp(this.element, properties[i].o, 0, 0.01, this.element),
          prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3),
          invRect: rect
        };
        if (!this.viewData[i].prop.k) {
          this.drawPath(properties[i], this.viewData[i].prop.v, this.viewData[i]);
        }
      }
    }
    this.maskElement = createNS(maskType);
    len = currentMasks.length;
    for (i = 0; i < len; i += 1) {
      this.maskElement.appendChild(currentMasks[i]);
    }
    if (count > 0) {
      this.maskElement.setAttribute("id", layerId);
      this.element.maskedElement.setAttribute(maskRef, "url(" + getLocationHref() + "#" + layerId + ")");
      defs.appendChild(this.maskElement);
    }
    if (this.viewData.length) {
      this.element.addRenderableComponent(this);
    }
  }
  function SVGEffects(elem2) {
    var i;
    var source = "SourceGraphic";
    var len = elem2.data.ef ? elem2.data.ef.length : 0;
    var filId = createElementID();
    var fil = filtersFactory.createFilter(filId, true);
    var count = 0;
    this.filters = [];
    var filterManager;
    for (i = 0; i < len; i += 1) {
      filterManager = null;
      var type = elem2.data.ef[i].ty;
      if (registeredEffects[type]) {
        var Effect = registeredEffects[type].effect;
        filterManager = new Effect(fil, elem2.effectsManager.effectElements[i], elem2, idPrefix + count, source);
        source = idPrefix + count;
        if (registeredEffects[type].countsAsEffect) {
          count += 1;
        }
      }
      if (filterManager) {
        this.filters.push(filterManager);
      }
    }
    if (count) {
      elem2.globalData.defs.appendChild(fil);
      elem2.layerElement.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")");
    }
    if (this.filters.length) {
      elem2.addRenderableComponent(this);
    }
  }
  function registerEffect(id, effect2, countsAsEffect) {
    registeredEffects[id] = {
      effect: effect2,
      countsAsEffect
    };
  }
  function SVGBaseElement() {
  }
  function HierarchyElement() {
  }
  function RenderableDOMElement() {
  }
  function IImageElement(data2, globalData2, comp2) {
    this.assetData = globalData2.getAssetData(data2.refId);
    this.initElement(data2, globalData2, comp2);
    this.sourceRect = {
      top: 0,
      left: 0,
      width: this.assetData.w,
      height: this.assetData.h
    };
  }
  function ProcessedElement(element, position2) {
    this.elem = element;
    this.pos = position2;
  }
  function IShapeElement() {
  }
  function SVGShapeData(transformers, level, shape) {
    this.caches = [];
    this.styles = [];
    this.transformers = transformers;
    this.lStr = "";
    this.sh = shape;
    this.lvl = level;
    this._isAnimated = !!shape.k;
    var i = 0;
    var len = transformers.length;
    while (i < len) {
      if (transformers[i].mProps.dynamicProperties.length) {
        this._isAnimated = true;
        break;
      }
      i += 1;
    }
  }
  function SVGStyleData(data2, level) {
    this.data = data2;
    this.type = data2.ty;
    this.d = "";
    this.lvl = level;
    this._mdf = false;
    this.closed = data2.hd === true;
    this.pElem = createNS("path");
    this.msElem = null;
  }
  function DashProperty(elem2, data2, renderer2, container) {
    this.elem = elem2;
    this.frameId = -1;
    this.dataProps = createSizedArray(data2.length);
    this.renderer = renderer2;
    this.k = false;
    this.dashStr = "";
    this.dashArray = createTypedArray("float32", data2.length ? data2.length - 1 : 0);
    this.dashoffset = createTypedArray("float32", 1);
    this.initDynamicPropertyContainer(container);
    var i;
    var len = data2.length || 0;
    var prop;
    for (i = 0; i < len; i += 1) {
      prop = PropertyFactory.getProp(elem2, data2[i].v, 0, 0, this);
      this.k = prop.k || this.k;
      this.dataProps[i] = { n: data2[i].n, p: prop };
    }
    if (!this.k) {
      this.getValue(true);
    }
    this._isAnimated = this.k;
  }
  function SVGStrokeStyleData(elem2, data2, styleOb) {
    this.initDynamicPropertyContainer(elem2);
    this.getValue = this.iterateDynamicProperties;
    this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this);
    this.w = PropertyFactory.getProp(elem2, data2.w, 0, null, this);
    this.d = new DashProperty(elem2, data2.d || {}, "svg", this);
    this.c = PropertyFactory.getProp(elem2, data2.c, 1, 255, this);
    this.style = styleOb;
    this._isAnimated = !!this._isAnimated;
  }
  function SVGFillStyleData(elem2, data2, styleOb) {
    this.initDynamicPropertyContainer(elem2);
    this.getValue = this.iterateDynamicProperties;
    this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this);
    this.c = PropertyFactory.getProp(elem2, data2.c, 1, 255, this);
    this.style = styleOb;
  }
  function SVGNoStyleData(elem2, data2, styleOb) {
    this.initDynamicPropertyContainer(elem2);
    this.getValue = this.iterateDynamicProperties;
    this.style = styleOb;
  }
  function GradientProperty(elem2, data2, container) {
    this.data = data2;
    this.c = createTypedArray("uint8c", data2.p * 4);
    var cLength = data2.k.k[0].s ? data2.k.k[0].s.length - data2.p * 4 : data2.k.k.length - data2.p * 4;
    this.o = createTypedArray("float32", cLength);
    this._cmdf = false;
    this._omdf = false;
    this._collapsable = this.checkCollapsable();
    this._hasOpacity = cLength;
    this.initDynamicPropertyContainer(container);
    this.prop = PropertyFactory.getProp(elem2, data2.k, 1, null, this);
    this.k = this.prop.k;
    this.getValue(true);
  }
  function SVGGradientFillStyleData(elem2, data2, styleOb) {
    this.initDynamicPropertyContainer(elem2);
    this.getValue = this.iterateDynamicProperties;
    this.initGradientData(elem2, data2, styleOb);
  }
  function SVGGradientStrokeStyleData(elem2, data2, styleOb) {
    this.initDynamicPropertyContainer(elem2);
    this.getValue = this.iterateDynamicProperties;
    this.w = PropertyFactory.getProp(elem2, data2.w, 0, null, this);
    this.d = new DashProperty(elem2, data2.d || {}, "svg", this);
    this.initGradientData(elem2, data2, styleOb);
    this._isAnimated = !!this._isAnimated;
  }
  function ShapeGroupData() {
    this.it = [];
    this.prevViewData = [];
    this.gr = createNS("g");
  }
  function SVGTransformData(mProps, op, container) {
    this.transform = {
      mProps,
      op,
      container
    };
    this.elements = [];
    this._isAnimated = this.transform.mProps.dynamicProperties.length || this.transform.op.effectsSequence.length;
  }
  function SVGShapeElement(data2, globalData2, comp2) {
    this.shapes = [];
    this.shapesData = data2.shapes;
    this.stylesList = [];
    this.shapeModifiers = [];
    this.itemsData = [];
    this.processedElements = [];
    this.animatedContents = [];
    this.initElement(data2, globalData2, comp2);
    this.prevViewData = [];
  }
  function LetterProps(o, sw, sc, fc, m, p) {
    this.o = o;
    this.sw = sw;
    this.sc = sc;
    this.fc = fc;
    this.m = m;
    this.p = p;
    this._mdf = {
      o: true,
      sw: !!sw,
      sc: !!sc,
      fc: !!fc,
      m: true,
      p: true
    };
  }
  function TextProperty(elem2, data2) {
    this._frameId = initialDefaultFrame;
    this.pv = "";
    this.v = "";
    this.kf = false;
    this._isFirstFrame = true;
    this._mdf = false;
    this.data = data2;
    this.elem = elem2;
    this.comp = this.elem.comp;
    this.keysIndex = 0;
    this.canResize = false;
    this.minimumFontSize = 1;
    this.effectsSequence = [];
    this.currentData = {
      ascent: 0,
      boxWidth: this.defaultBoxWidth,
      f: "",
      fStyle: "",
      fWeight: "",
      fc: "",
      j: "",
      justifyOffset: "",
      l: [],
      lh: 0,
      lineWidths: [],
      ls: "",
      of: "",
      s: "",
      sc: "",
      sw: 0,
      t: 0,
      tr: 0,
      sz: 0,
      ps: null,
      fillColorAnim: false,
      strokeColorAnim: false,
      strokeWidthAnim: false,
      yOffset: 0,
      finalSize: 0,
      finalText: [],
      finalLineHeight: 0,
      __complete: false
    };
    this.copyData(this.currentData, this.data.d.k[0].s);
    if (!this.searchProperty()) {
      this.completeTextData(this.currentData);
    }
  }
  function TextAnimatorDataProperty(elem2, animatorProps, container) {
    var defaultData = { propType: false };
    var getProp = PropertyFactory.getProp;
    var textAnimatorAnimatables = animatorProps.a;
    this.a = {
      r: textAnimatorAnimatables.r ? getProp(elem2, textAnimatorAnimatables.r, 0, degToRads, container) : defaultData,
      rx: textAnimatorAnimatables.rx ? getProp(elem2, textAnimatorAnimatables.rx, 0, degToRads, container) : defaultData,
      ry: textAnimatorAnimatables.ry ? getProp(elem2, textAnimatorAnimatables.ry, 0, degToRads, container) : defaultData,
      sk: textAnimatorAnimatables.sk ? getProp(elem2, textAnimatorAnimatables.sk, 0, degToRads, container) : defaultData,
      sa: textAnimatorAnimatables.sa ? getProp(elem2, textAnimatorAnimatables.sa, 0, degToRads, container) : defaultData,
      s: textAnimatorAnimatables.s ? getProp(elem2, textAnimatorAnimatables.s, 1, 0.01, container) : defaultData,
      a: textAnimatorAnimatables.a ? getProp(elem2, textAnimatorAnimatables.a, 1, 0, container) : defaultData,
      o: textAnimatorAnimatables.o ? getProp(elem2, textAnimatorAnimatables.o, 0, 0.01, container) : defaultData,
      p: textAnimatorAnimatables.p ? getProp(elem2, textAnimatorAnimatables.p, 1, 0, container) : defaultData,
      sw: textAnimatorAnimatables.sw ? getProp(elem2, textAnimatorAnimatables.sw, 0, 0, container) : defaultData,
      sc: textAnimatorAnimatables.sc ? getProp(elem2, textAnimatorAnimatables.sc, 1, 0, container) : defaultData,
      fc: textAnimatorAnimatables.fc ? getProp(elem2, textAnimatorAnimatables.fc, 1, 0, container) : defaultData,
      fh: textAnimatorAnimatables.fh ? getProp(elem2, textAnimatorAnimatables.fh, 0, 0, container) : defaultData,
      fs: textAnimatorAnimatables.fs ? getProp(elem2, textAnimatorAnimatables.fs, 0, 0.01, container) : defaultData,
      fb: textAnimatorAnimatables.fb ? getProp(elem2, textAnimatorAnimatables.fb, 0, 0.01, container) : defaultData,
      t: textAnimatorAnimatables.t ? getProp(elem2, textAnimatorAnimatables.t, 0, 0, container) : defaultData
    };
    this.s = TextSelectorProp.getTextSelectorProp(elem2, animatorProps.s, container);
    this.s.t = animatorProps.s.t;
  }
  function TextAnimatorProperty(textData, renderType, elem2) {
    this._isFirstFrame = true;
    this._hasMaskedPath = false;
    this._frameId = -1;
    this._textData = textData;
    this._renderType = renderType;
    this._elem = elem2;
    this._animatorsData = createSizedArray(this._textData.a.length);
    this._pathData = {};
    this._moreOptions = {
      alignment: {}
    };
    this.renderedLetters = [];
    this.lettersChangedFlag = false;
    this.initDynamicPropertyContainer(elem2);
  }
  function ITextElement() {
  }
  function SVGTextLottieElement(data2, globalData2, comp2) {
    this.textSpans = [];
    this.renderType = "svg";
    this.initElement(data2, globalData2, comp2);
  }
  function ISolidElement(data2, globalData2, comp2) {
    this.initElement(data2, globalData2, comp2);
  }
  function NullElement(data2, globalData2, comp2) {
    this.initFrame();
    this.initBaseData(data2, globalData2, comp2);
    this.initFrame();
    this.initTransform(data2, globalData2, comp2);
    this.initHierarchy();
  }
  function SVGRendererBase() {
  }
  function ICompElement() {
  }
  function SVGCompElement(data2, globalData2, comp2) {
    this.layers = data2.layers;
    this.supports3d = true;
    this.completeLayers = false;
    this.pendingElements = [];
    this.elements = this.layers ? createSizedArray(this.layers.length) : [];
    this.initElement(data2, globalData2, comp2);
    this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true };
  }
  function SVGRenderer(animationItem, config) {
    this.animationItem = animationItem;
    this.layers = null;
    this.renderedFrame = -1;
    this.svgElement = createNS("svg");
    var ariaLabel = "";
    if (config && config.title) {
      var titleElement = createNS("title");
      var titleId = createElementID();
      titleElement.setAttribute("id", titleId);
      titleElement.textContent = config.title;
      this.svgElement.appendChild(titleElement);
      ariaLabel += titleId;
    }
    if (config && config.description) {
      var descElement = createNS("desc");
      var descId = createElementID();
      descElement.setAttribute("id", descId);
      descElement.textContent = config.description;
      this.svgElement.appendChild(descElement);
      ariaLabel += " " + descId;
    }
    if (ariaLabel) {
      this.svgElement.setAttribute("aria-labelledby", ariaLabel);
    }
    var defs = createNS("defs");
    this.svgElement.appendChild(defs);
    var maskElement = createNS("g");
    this.svgElement.appendChild(maskElement);
    this.layerElement = maskElement;
    this.renderConfig = {
      preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet",
      imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice",
      contentVisibility: config && config.contentVisibility || "visible",
      progressiveLoad: config && config.progressiveLoad || false,
      hideOnTransparent: !(config && config.hideOnTransparent === false),
      viewBoxOnly: config && config.viewBoxOnly || false,
      viewBoxSize: config && config.viewBoxSize || false,
      className: config && config.className || "",
      id: config && config.id || "",
      focusable: config && config.focusable,
      filterSize: {
        width: config && config.filterSize && config.filterSize.width || "100%",
        height: config && config.filterSize && config.filterSize.height || "100%",
        x: config && config.filterSize && config.filterSize.x || "0%",
        y: config && config.filterSize && config.filterSize.y || "0%"
      },
      width: config && config.width,
      height: config && config.height
    };
    this.globalData = {
      _mdf: false,
      frameNum: -1,
      defs,
      renderConfig: this.renderConfig
    };
    this.elements = [];
    this.pendingElements = [];
    this.destroyed = false;
    this.rendererType = "svg";
  }
  function CVContextData() {
    this.saved = [];
    this.cArrPos = 0;
    this.cTr = new Matrix();
    this.cO = 1;
    var i;
    var len = 15;
    this.savedOp = createTypedArray("float32", len);
    for (i = 0; i < len; i += 1) {
      this.saved[i] = createTypedArray("float32", 16);
    }
    this._length = len;
  }
  function ShapeTransformManager() {
    this.sequences = {};
    this.sequenceList = [];
    this.transform_key_count = 0;
  }
  function CVEffects() {
  }
  function CVMaskElement(data2, element) {
    this.data = data2;
    this.element = element;
    this.masksProperties = this.data.masksProperties || [];
    this.viewData = createSizedArray(this.masksProperties.length);
    var i;
    var len = this.masksProperties.length;
    var hasMasks = false;
    for (i = 0; i < len; i += 1) {
      if (this.masksProperties[i].mode !== "n") {
        hasMasks = true;
      }
      this.viewData[i] = ShapePropertyFactory.getShapeProp(this.element, this.masksProperties[i], 3);
    }
    this.hasMasks = hasMasks;
    if (hasMasks) {
      this.element.addRenderableComponent(this);
    }
  }
  function CVBaseElement() {
  }
  function CVShapeData(element, data2, styles, transformsManager) {
    this.styledShapes = [];
    this.tr = [0, 0, 0, 0, 0, 0];
    var ty = 4;
    if (data2.ty === "rc") {
      ty = 5;
    } else if (data2.ty === "el") {
      ty = 6;
    } else if (data2.ty === "sr") {
      ty = 7;
    }
    this.sh = ShapePropertyFactory.getShapeProp(element, data2, ty, element);
    var i;
    var len = styles.length;
    var styledShape;
    for (i = 0; i < len; i += 1) {
      if (!styles[i].closed) {
        styledShape = {
          transforms: transformsManager.addTransformSequence(styles[i].transforms),
          trNodes: []
        };
        this.styledShapes.push(styledShape);
        styles[i].elements.push(styledShape);
      }
    }
  }
  function CVShapeElement(data2, globalData2, comp2) {
    this.shapes = [];
    this.shapesData = data2.shapes;
    this.stylesList = [];
    this.itemsData = [];
    this.prevViewData = [];
    this.shapeModifiers = [];
    this.processedElements = [];
    this.transformsManager = new ShapeTransformManager();
    this.initElement(data2, globalData2, comp2);
  }
  function CVTextElement(data2, globalData2, comp2) {
    this.textSpans = [];
    this.yOffset = 0;
    this.fillColorAnim = false;
    this.strokeColorAnim = false;
    this.strokeWidthAnim = false;
    this.stroke = false;
    this.fill = false;
    this.justifyOffset = 0;
    this.currentRender = null;
    this.renderType = "canvas";
    this.values = {
      fill: "rgba(0,0,0,0)",
      stroke: "rgba(0,0,0,0)",
      sWidth: 0,
      fValue: ""
    };
    this.initElement(data2, globalData2, comp2);
  }
  function CVImageElement(data2, globalData2, comp2) {
    this.assetData = globalData2.getAssetData(data2.refId);
    this.img = globalData2.imageLoader.getAsset(this.assetData);
    this.initElement(data2, globalData2, comp2);
  }
  function CVSolidElement(data2, globalData2, comp2) {
    this.initElement(data2, globalData2, comp2);
  }
  function CanvasRendererBase(animationItem, config) {
    this.animationItem = animationItem;
    this.renderConfig = {
      clearCanvas: config && config.clearCanvas !== void 0 ? config.clearCanvas : true,
      context: config && config.context || null,
      progressiveLoad: config && config.progressiveLoad || false,
      preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet",
      imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice",
      contentVisibility: config && config.contentVisibility || "visible",
      className: config && config.className || "",
      id: config && config.id || ""
    };
    this.renderConfig.dpr = config && config.dpr || 1;
    if (this.animationItem.wrapper) {
      this.renderConfig.dpr = config && config.dpr || window.devicePixelRatio || 1;
    }
    this.renderedFrame = -1;
    this.globalData = {
      frameNum: -1,
      _mdf: false,
      renderConfig: this.renderConfig,
      currentGlobalAlpha: -1
    };
    this.contextData = new CVContextData();
    this.elements = [];
    this.pendingElements = [];
    this.transformMat = new Matrix();
    this.completeLayers = false;
    this.rendererType = "canvas";
  }
  function CVCompElement(data2, globalData2, comp2) {
    this.completeLayers = false;
    this.layers = data2.layers;
    this.pendingElements = [];
    this.elements = createSizedArray(this.layers.length);
    this.initElement(data2, globalData2, comp2);
    this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true };
  }
  function CanvasRenderer(animationItem, config) {
    this.animationItem = animationItem;
    this.renderConfig = {
      clearCanvas: config && config.clearCanvas !== void 0 ? config.clearCanvas : true,
      context: config && config.context || null,
      progressiveLoad: config && config.progressiveLoad || false,
      preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet",
      imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice",
      contentVisibility: config && config.contentVisibility || "visible",
      className: config && config.className || "",
      id: config && config.id || ""
    };
    this.renderConfig.dpr = config && config.dpr || 1;
    if (this.animationItem.wrapper) {
      this.renderConfig.dpr = config && config.dpr || window.devicePixelRatio || 1;
    }
    this.renderedFrame = -1;
    this.globalData = {
      frameNum: -1,
      _mdf: false,
      renderConfig: this.renderConfig,
      currentGlobalAlpha: -1
    };
    this.contextData = new CVContextData();
    this.elements = [];
    this.pendingElements = [];
    this.transformMat = new Matrix();
    this.completeLayers = false;
    this.rendererType = "canvas";
  }
  function seedRandom(pool, math) {
    var global = this, width2 = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width2, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask2 = width2 - 1, nodecrypto;
    function seedrandom(seed, options, callback) {
      var key2 = [];
      options = options === true ? { entropy: true } : options || {};
      var shortseed = mixkey(flatten2(
        options.entropy ? [seed, tostring(pool)] : seed === null ? autoseed() : seed,
        3
      ), key2);
      var arc4 = new ARC4(key2);
      var prng = function() {
        var n2 = arc4.g(chunks), d = startdenom, x2 = 0;
        while (n2 < significance) {
          n2 = (n2 + x2) * width2;
          d *= width2;
          x2 = arc4.g(1);
        }
        while (n2 >= overflow) {
          n2 /= 2;
          d /= 2;
          x2 >>>= 1;
        }
        return (n2 + x2) / d;
      };
      prng.int32 = function() {
        return arc4.g(4) | 0;
      };
      prng.quick = function() {
        return arc4.g(4) / 4294967296;
      };
      prng.double = prng;
      mixkey(tostring(arc4.S), pool);
      return (options.pass || callback || function(prng2, seed2, is_math_call, state) {
        if (state) {
          if (state.S) {
            copy(state, arc4);
          }
          prng2.state = function() {
            return copy(arc4, {});
          };
        }
        if (is_math_call) {
          math[rngname] = prng2;
          return seed2;
        } else return prng2;
      })(
        prng,
        shortseed,
        "global" in options ? options.global : this == math,
        options.state
      );
    }
    math["seed" + rngname] = seedrandom;
    function ARC4(key2) {
      var t3, keylen = key2.length, me = this, i = 0, j2 = me.i = me.j = 0, s = me.S = [];
      if (!keylen) {
        key2 = [keylen++];
      }
      while (i < width2) {
        s[i] = i++;
      }
      for (i = 0; i < width2; i++) {
        s[i] = s[j2 = mask2 & j2 + key2[i % keylen] + (t3 = s[i])];
        s[j2] = t3;
      }
      me.g = function(count) {
        var t4, r = 0, i2 = me.i, j3 = me.j, s2 = me.S;
        while (count--) {
          t4 = s2[i2 = mask2 & i2 + 1];
          r = r * width2 + s2[mask2 & (s2[i2] = s2[j3 = mask2 & j3 + t4]) + (s2[j3] = t4)];
        }
        me.i = i2;
        me.j = j3;
        return r;
      };
    }
    function copy(f, t3) {
      t3.i = f.i;
      t3.j = f.j;
      t3.S = f.S.slice();
      return t3;
    }
    function flatten2(obj, depth) {
      var result = [], typ = typeof obj, prop;
      if (depth && typ == "object") {
        for (prop in obj) {
          try {
            result.push(flatten2(obj[prop], depth - 1));
          } catch (e) {
          }
        }
      }
      return result.length ? result : typ == "string" ? obj : obj + "\0";
    }
    function mixkey(seed, key2) {
      var stringseed = seed + "", smear, j2 = 0;
      while (j2 < stringseed.length) {
        key2[mask2 & j2] = mask2 & (smear ^= key2[mask2 & j2] * 19) + stringseed.charCodeAt(j2++);
      }
      return tostring(key2);
    }
    function autoseed() {
      try {
        if (nodecrypto) {
          return tostring(nodecrypto.randomBytes(width2));
        }
        var out = new Uint8Array(width2);
        (global.crypto || global.msCrypto).getRandomValues(out);
        return tostring(out);
      } catch (e) {
        var browser = global.navigator, plugins = browser && browser.plugins;
        return [+/* @__PURE__ */ new Date(), global, plugins, global.screen, tostring(pool)];
      }
    }
    function tostring(a2) {
      return String.fromCharCode.apply(0, a2);
    }
    mixkey(math.random(), pool);
  }
  function initialize$2(BMMath2) {
    seedRandom([], BMMath2);
  }
  function addPropertyDecorator() {
    function loopOut2(type, duration, durationFlag) {
      if (!this.k || !this.keyframes) {
        return this.pv;
      }
      type = type ? type.toLowerCase() : "";
      var currentFrame = this.comp.renderedFrame;
      var keyframes = this.keyframes;
      var lastKeyFrame = keyframes[keyframes.length - 1].t;
      if (currentFrame <= lastKeyFrame) {
        return this.pv;
      }
      var cycleDuration;
      var firstKeyFrame;
      if (!durationFlag) {
        if (!duration || duration > keyframes.length - 1) {
          duration = keyframes.length - 1;
        }
        firstKeyFrame = keyframes[keyframes.length - 1 - duration].t;
        cycleDuration = lastKeyFrame - firstKeyFrame;
      } else {
        if (!duration) {
          cycleDuration = Math.max(0, lastKeyFrame - this.elem.data.ip);
        } else {
          cycleDuration = Math.abs(lastKeyFrame - this.elem.comp.globalData.frameRate * duration);
        }
        firstKeyFrame = lastKeyFrame - cycleDuration;
      }
      var i;
      var len;
      var ret;
      if (type === "pingpong") {
        var iterations = Math.floor((currentFrame - firstKeyFrame) / cycleDuration);
        if (iterations % 2 !== 0) {
          return this.getValueAtTime((cycleDuration - (currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0);
        }
      } else if (type === "offset") {
        var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0);
        var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0);
        var current = this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0);
        var repeats = Math.floor((currentFrame - firstKeyFrame) / cycleDuration);
        if (this.pv.length) {
          ret = new Array(initV.length);
          len = ret.length;
          for (i = 0; i < len; i += 1) {
            ret[i] = (endV[i] - initV[i]) * repeats + current[i];
          }
          return ret;
        }
        return (endV - initV) * repeats + current;
      } else if (type === "continue") {
        var lastValue = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0);
        var nextLastValue = this.getValueAtTime((lastKeyFrame - 1e-3) / this.comp.globalData.frameRate, 0);
        if (this.pv.length) {
          ret = new Array(lastValue.length);
          len = ret.length;
          for (i = 0; i < len; i += 1) {
            ret[i] = lastValue[i] + (lastValue[i] - nextLastValue[i]) * ((currentFrame - lastKeyFrame) / this.comp.globalData.frameRate) / 5e-4;
          }
          return ret;
        }
        return lastValue + (lastValue - nextLastValue) * ((currentFrame - lastKeyFrame) / 1e-3);
      }
      return this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0);
    }
    function loopIn2(type, duration, durationFlag) {
      if (!this.k) {
        return this.pv;
      }
      type = type ? type.toLowerCase() : "";
      var currentFrame = this.comp.renderedFrame;
      var keyframes = this.keyframes;
      var firstKeyFrame = keyframes[0].t;
      if (currentFrame >= firstKeyFrame) {
        return this.pv;
      }
      var cycleDuration;
      var lastKeyFrame;
      if (!durationFlag) {
        if (!duration || duration > keyframes.length - 1) {
          duration = keyframes.length - 1;
        }
        lastKeyFrame = keyframes[duration].t;
        cycleDuration = lastKeyFrame - firstKeyFrame;
      } else {
        if (!duration) {
          cycleDuration = Math.max(0, this.elem.data.op - firstKeyFrame);
        } else {
          cycleDuration = Math.abs(this.elem.comp.globalData.frameRate * duration);
        }
        lastKeyFrame = firstKeyFrame + cycleDuration;
      }
      var i;
      var len;
      var ret;
      if (type === "pingpong") {
        var iterations = Math.floor((firstKeyFrame - currentFrame) / cycleDuration);
        if (iterations % 2 === 0) {
          return this.getValueAtTime(((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0);
        }
      } else if (type === "offset") {
        var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0);
        var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0);
        var current = this.getValueAtTime((cycleDuration - (firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0);
        var repeats = Math.floor((firstKeyFrame - currentFrame) / cycleDuration) + 1;
        if (this.pv.length) {
          ret = new Array(initV.length);
          len = ret.length;
          for (i = 0; i < len; i += 1) {
            ret[i] = current[i] - (endV[i] - initV[i]) * repeats;
          }
          return ret;
        }
        return current - (endV - initV) * repeats;
      } else if (type === "continue") {
        var firstValue = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0);
        var nextFirstValue = this.getValueAtTime((firstKeyFrame + 1e-3) / this.comp.globalData.frameRate, 0);
        if (this.pv.length) {
          ret = new Array(firstValue.length);
          len = ret.length;
          for (i = 0; i < len; i += 1) {
            ret[i] = firstValue[i] + (firstValue[i] - nextFirstValue[i]) * (firstKeyFrame - currentFrame) / 1e-3;
          }
          return ret;
        }
        return firstValue + (firstValue - nextFirstValue) * (firstKeyFrame - currentFrame) / 1e-3;
      }
      return this.getValueAtTime((cycleDuration - ((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame)) / this.comp.globalData.frameRate, 0);
    }
    function smooth2(width2, samples) {
      if (!this.k) {
        return this.pv;
      }
      width2 = (width2 || 0.4) * 0.5;
      samples = Math.floor(samples || 5);
      if (samples <= 1) {
        return this.pv;
      }
      var currentTime = this.comp.renderedFrame / this.comp.globalData.frameRate;
      var initFrame = currentTime - width2;
      var endFrame = currentTime + width2;
      var sampleFrequency = samples > 1 ? (endFrame - initFrame) / (samples - 1) : 1;
      var i = 0;
      var j2 = 0;
      var value2;
      if (this.pv.length) {
        value2 = createTypedArray("float32", this.pv.length);
      } else {
        value2 = 0;
      }
      var sampleValue;
      while (i < samples) {
        sampleValue = this.getValueAtTime(initFrame + i * sampleFrequency);
        if (this.pv.length) {
          for (j2 = 0; j2 < this.pv.length; j2 += 1) {
            value2[j2] += sampleValue[j2];
          }
        } else {
          value2 += sampleValue;
        }
        i += 1;
      }
      if (this.pv.length) {
        for (j2 = 0; j2 < this.pv.length; j2 += 1) {
          value2[j2] /= samples;
        }
      } else {
        value2 /= samples;
      }
      return value2;
    }
    function getTransformValueAtTime(time2) {
      if (!this._transformCachingAtTime) {
        this._transformCachingAtTime = {
          v: new Matrix()
        };
      }
      var matrix2 = this._transformCachingAtTime.v;
      matrix2.cloneFromProps(this.pre.props);
      if (this.appliedTransformations < 1) {
        var anchor = this.a.getValueAtTime(time2);
        matrix2.translate(
          -anchor[0] * this.a.mult,
          -anchor[1] * this.a.mult,
          anchor[2] * this.a.mult
        );
      }
      if (this.appliedTransformations < 2) {
        var scale2 = this.s.getValueAtTime(time2);
        matrix2.scale(
          scale2[0] * this.s.mult,
          scale2[1] * this.s.mult,
          scale2[2] * this.s.mult
        );
      }
      if (this.sk && this.appliedTransformations < 3) {
        var skew = this.sk.getValueAtTime(time2);
        var skewAxis = this.sa.getValueAtTime(time2);
        matrix2.skewFromAxis(-skew * this.sk.mult, skewAxis * this.sa.mult);
      }
      if (this.r && this.appliedTransformations < 4) {
        var rotation2 = this.r.getValueAtTime(time2);
        matrix2.rotate(-rotation2 * this.r.mult);
      } else if (!this.r && this.appliedTransformations < 4) {
        var rotationZ = this.rz.getValueAtTime(time2);
        var rotationY = this.ry.getValueAtTime(time2);
        var rotationX = this.rx.getValueAtTime(time2);
        var orientation = this.or.getValueAtTime(time2);
        matrix2.rotateZ(-rotationZ * this.rz.mult).rotateY(rotationY * this.ry.mult).rotateX(rotationX * this.rx.mult).rotateZ(-orientation[2] * this.or.mult).rotateY(orientation[1] * this.or.mult).rotateX(orientation[0] * this.or.mult);
      }
      if (this.data.p && this.data.p.s) {
        var positionX = this.px.getValueAtTime(time2);
        var positionY = this.py.getValueAtTime(time2);
        if (this.data.p.z) {
          var positionZ = this.pz.getValueAtTime(time2);
          matrix2.translate(
            positionX * this.px.mult,
            positionY * this.py.mult,
            -positionZ * this.pz.mult
          );
        } else {
          matrix2.translate(positionX * this.px.mult, positionY * this.py.mult, 0);
        }
      } else {
        var position2 = this.p.getValueAtTime(time2);
        matrix2.translate(
          position2[0] * this.p.mult,
          position2[1] * this.p.mult,
          -position2[2] * this.p.mult
        );
      }
      return matrix2;
    }
    function getTransformStaticValueAtTime() {
      return this.v.clone(new Matrix());
    }
    var getTransformProperty = TransformPropertyFactory.getTransformProperty;
    TransformPropertyFactory.getTransformProperty = function(elem2, data2, container) {
      var prop = getTransformProperty(elem2, data2, container);
      if (prop.dynamicProperties.length) {
        prop.getValueAtTime = getTransformValueAtTime.bind(prop);
      } else {
        prop.getValueAtTime = getTransformStaticValueAtTime.bind(prop);
      }
      prop.setGroupProperty = expressionHelpers.setGroupProperty;
      return prop;
    };
    var propertyGetProp = PropertyFactory.getProp;
    PropertyFactory.getProp = function(elem2, data2, type, mult, container) {
      var prop = propertyGetProp(elem2, data2, type, mult, container);
      if (prop.kf) {
        prop.getValueAtTime = expressionHelpers.getValueAtTime.bind(prop);
      } else {
        prop.getValueAtTime = expressionHelpers.getStaticValueAtTime.bind(prop);
      }
      prop.setGroupProperty = expressionHelpers.setGroupProperty;
      prop.loopOut = loopOut2;
      prop.loopIn = loopIn2;
      prop.smooth = smooth2;
      prop.getVelocityAtTime = expressionHelpers.getVelocityAtTime.bind(prop);
      prop.getSpeedAtTime = expressionHelpers.getSpeedAtTime.bind(prop);
      prop.numKeys = data2.a === 1 ? data2.k.length : 0;
      prop.propertyIndex = data2.ix;
      var value2 = 0;
      if (type !== 0) {
        value2 = createTypedArray("float32", data2.a === 1 ? data2.k[0].s.length : data2.k.length);
      }
      prop._cachingAtTime = {
        lastFrame: initialDefaultFrame,
        lastIndex: 0,
        value: value2
      };
      expressionHelpers.searchExpressions(elem2, data2, prop);
      if (prop.k) {
        container.addDynamicProperty(prop);
      }
      return prop;
    };
    function getShapeValueAtTime(frameNum) {
      if (!this._cachingAtTime) {
        this._cachingAtTime = {
          shapeValue: shapePool.clone(this.pv),
          lastIndex: 0,
          lastTime: initialDefaultFrame
        };
      }
      frameNum *= this.elem.globalData.frameRate;
      frameNum -= this.offsetTime;
      if (frameNum !== this._cachingAtTime.lastTime) {
        this._cachingAtTime.lastIndex = this._cachingAtTime.lastTime < frameNum ? this._caching.lastIndex : 0;
        this._cachingAtTime.lastTime = frameNum;
        this.interpolateShape(frameNum, this._cachingAtTime.shapeValue, this._cachingAtTime);
      }
      return this._cachingAtTime.shapeValue;
    }
    var ShapePropertyConstructorFunction = ShapePropertyFactory.getConstructorFunction();
    var KeyframedShapePropertyConstructorFunction = ShapePropertyFactory.getKeyframedConstructorFunction();
    function ShapeExpressions() {
    }
    ShapeExpressions.prototype = {
      vertices: function(prop, time2) {
        if (this.k) {
          this.getValue();
        }
        var shapePath = this.v;
        if (time2 !== void 0) {
          shapePath = this.getValueAtTime(time2, 0);
        }
        var i;
        var len = shapePath._length;
        var vertices = shapePath[prop];
        var points = shapePath.v;
        var arr = createSizedArray(len);
        for (i = 0; i < len; i += 1) {
          if (prop === "i" || prop === "o") {
            arr[i] = [vertices[i][0] - points[i][0], vertices[i][1] - points[i][1]];
          } else {
            arr[i] = [vertices[i][0], vertices[i][1]];
          }
        }
        return arr;
      },
      points: function(time2) {
        return this.vertices("v", time2);
      },
      inTangents: function(time2) {
        return this.vertices("i", time2);
      },
      outTangents: function(time2) {
        return this.vertices("o", time2);
      },
      isClosed: function() {
        return this.v.c;
      },
      pointOnPath: function(perc, time2) {
        var shapePath = this.v;
        if (time2 !== void 0) {
          shapePath = this.getValueAtTime(time2, 0);
        }
        if (!this._segmentsLength) {
          this._segmentsLength = bez.getSegmentsLength(shapePath);
        }
        var segmentsLength = this._segmentsLength;
        var lengths2 = segmentsLength.lengths;
        var lengthPos = segmentsLength.totalLength * perc;
        var i = 0;
        var len = lengths2.length;
        var accumulatedLength = 0;
        var pt;
        while (i < len) {
          if (accumulatedLength + lengths2[i].addedLength > lengthPos) {
            var initIndex = i;
            var endIndex = shapePath.c && i === len - 1 ? 0 : i + 1;
            var segmentPerc = (lengthPos - accumulatedLength) / lengths2[i].addedLength;
            pt = bez.getPointInSegment(shapePath.v[initIndex], shapePath.v[endIndex], shapePath.o[initIndex], shapePath.i[endIndex], segmentPerc, lengths2[i]);
            break;
          } else {
            accumulatedLength += lengths2[i].addedLength;
          }
          i += 1;
        }
        if (!pt) {
          pt = shapePath.c ? [shapePath.v[0][0], shapePath.v[0][1]] : [shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1]];
        }
        return pt;
      },
      vectorOnPath: function(perc, time2, vectorType) {
        if (perc == 1) {
          perc = this.v.c;
        } else if (perc == 0) {
          perc = 0.999;
        }
        var pt1 = this.pointOnPath(perc, time2);
        var pt2 = this.pointOnPath(perc + 1e-3, time2);
        var xLength = pt2[0] - pt1[0];
        var yLength = pt2[1] - pt1[1];
        var magnitude = Math.sqrt(Math.pow(xLength, 2) + Math.pow(yLength, 2));
        if (magnitude === 0) {
          return [0, 0];
        }
        var unitVector = vectorType === "tangent" ? [xLength / magnitude, yLength / magnitude] : [-yLength / magnitude, xLength / magnitude];
        return unitVector;
      },
      tangentOnPath: function(perc, time2) {
        return this.vectorOnPath(perc, time2, "tangent");
      },
      normalOnPath: function(perc, time2) {
        return this.vectorOnPath(perc, time2, "normal");
      },
      setGroupProperty: expressionHelpers.setGroupProperty,
      getValueAtTime: expressionHelpers.getStaticValueAtTime
    };
    extendPrototype([ShapeExpressions], ShapePropertyConstructorFunction);
    extendPrototype([ShapeExpressions], KeyframedShapePropertyConstructorFunction);
    KeyframedShapePropertyConstructorFunction.prototype.getValueAtTime = getShapeValueAtTime;
    KeyframedShapePropertyConstructorFunction.prototype.initiateExpression = ExpressionManager.initiateExpression;
    var propertyGetShapeProp = ShapePropertyFactory.getShapeProp;
    ShapePropertyFactory.getShapeProp = function(elem2, data2, type, arr, trims) {
      var prop = propertyGetShapeProp(elem2, data2, type, arr, trims);
      prop.propertyIndex = data2.ix;
      prop.lock = false;
      if (type === 3) {
        expressionHelpers.searchExpressions(elem2, data2.pt, prop);
      } else if (type === 4) {
        expressionHelpers.searchExpressions(elem2, data2.ks, prop);
      }
      if (prop.k) {
        elem2.addDynamicProperty(prop);
      }
      return prop;
    };
  }
  function initialize$1() {
    addPropertyDecorator();
  }
  function addDecorator() {
    function searchExpressions() {
      if (this.data.d.x) {
        this.calculateExpression = ExpressionManager.initiateExpression.bind(this)(this.elem, this.data.d, this);
        this.addEffect(this.getExpressionValue.bind(this));
        return true;
      }
      return null;
    }
    TextProperty.prototype.getExpressionValue = function(currentValue, text2) {
      var newValue = this.calculateExpression(text2);
      if (currentValue.t !== newValue) {
        var newData = {};
        this.copyData(newData, currentValue);
        newData.t = newValue.toString();
        newData.__complete = false;
        return newData;
      }
      return currentValue;
    };
    TextProperty.prototype.searchProperty = function() {
      var isKeyframed = this.searchKeyframes();
      var hasExpressions = this.searchExpressions();
      this.kf = isKeyframed || hasExpressions;
      return this.kf;
    };
    TextProperty.prototype.searchExpressions = searchExpressions;
  }
  function initialize() {
    addDecorator();
  }
  const svgNS = "http://www.w3.org/2000/svg";
  let locationHref = "";
  let _useWebWorker = false;
  const initialDefaultFrame = -999999;
  const setWebWorker = (flag) => {
    _useWebWorker = !!flag;
  };
  const getWebWorker = () => _useWebWorker;
  const setLocationHref = (value2) => {
    locationHref = value2;
  };
  const getLocationHref = () => locationHref;
  const audioControllerFactory = function() {
    function AudioController(audioFactory) {
      this.audios = [];
      this.audioFactory = audioFactory;
      this._volume = 1;
      this._isMuted = false;
    }
    AudioController.prototype = {
      addAudio: function(audio) {
        this.audios.push(audio);
      },
      pause: function() {
        var i;
        var len = this.audios.length;
        for (i = 0; i < len; i += 1) {
          this.audios[i].pause();
        }
      },
      resume: function() {
        var i;
        var len = this.audios.length;
        for (i = 0; i < len; i += 1) {
          this.audios[i].resume();
        }
      },
      setRate: function(rateValue) {
        var i;
        var len = this.audios.length;
        for (i = 0; i < len; i += 1) {
          this.audios[i].setRate(rateValue);
        }
      },
      createAudio: function(assetPath) {
        if (this.audioFactory) {
          return this.audioFactory(assetPath);
        }
        if (window.Howl) {
          return new window.Howl({
            src: [assetPath]
          });
        }
        return {
          isPlaying: false,
          play: function() {
            this.isPlaying = true;
          },
          seek: function() {
            this.isPlaying = false;
          },
          playing: function() {
          },
          rate: function() {
          },
          setVolume: function() {
          }
        };
      },
      setAudioFactory: function(audioFactory) {
        this.audioFactory = audioFactory;
      },
      setVolume: function(value2) {
        this._volume = value2;
        this._updateVolume();
      },
      mute: function() {
        this._isMuted = true;
        this._updateVolume();
      },
      unmute: function() {
        this._isMuted = false;
        this._updateVolume();
      },
      getVolume: function() {
        return this._volume;
      },
      _updateVolume: function() {
        var i;
        var len = this.audios.length;
        for (i = 0; i < len; i += 1) {
          this.audios[i].volume(this._volume * (this._isMuted ? 0 : 1));
        }
      }
    };
    return function() {
      return new AudioController();
    };
  }();
  const createTypedArray = function() {
    function createRegularArray(type, len) {
      var i = 0;
      var arr = [];
      var value2;
      switch (type) {
        case "int16":
        case "uint8c":
          value2 = 1;
          break;
        default:
          value2 = 1.1;
          break;
      }
      for (i = 0; i < len; i += 1) {
        arr.push(value2);
      }
      return arr;
    }
    function createTypedArrayFactory(type, len) {
      if (type === "float32") {
        return new Float32Array(len);
      }
      if (type === "int16") {
        return new Int16Array(len);
      }
      if (type === "uint8c") {
        return new Uint8ClampedArray(len);
      }
      return createRegularArray(type, len);
    }
    if (typeof Uint8ClampedArray === "function" && typeof Float32Array === "function") {
      return createTypedArrayFactory;
    }
    return createRegularArray;
  }();
  let subframeEnabled = true;
  let expressionsPlugin = null;
  let idPrefix$1 = "";
  const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  let _shouldRoundValues = false;
  const bmPow = Math.pow;
  const bmSqrt = Math.sqrt;
  const bmFloor = Math.floor;
  const bmMax = Math.max;
  const bmMin = Math.min;
  const BMMath = {};
  (function() {
    var propertyNames = ["abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2", "ceil", "cbrt", "expm1", "clz32", "cos", "cosh", "exp", "floor", "fround", "hypot", "imul", "log", "log1p", "log2", "log10", "max", "min", "pow", "random", "round", "sign", "sin", "sinh", "sqrt", "tan", "tanh", "trunc", "E", "LN10", "LN2", "LOG10E", "LOG2E", "PI", "SQRT1_2", "SQRT2"];
    var i;
    var len = propertyNames.length;
    for (i = 0; i < len; i += 1) {
      BMMath[propertyNames[i]] = Math[propertyNames[i]];
    }
  })();
  BMMath.random = Math.random;
  BMMath.abs = function(val2) {
    var tOfVal = typeof val2;
    if (tOfVal === "object" && val2.length) {
      var absArr = createSizedArray(val2.length);
      var i;
      var len = val2.length;
      for (i = 0; i < len; i += 1) {
        absArr[i] = Math.abs(val2[i]);
      }
      return absArr;
    }
    return Math.abs(val2);
  };
  let defaultCurveSegments = 150;
  const degToRads = Math.PI / 180;
  const roundCorner = 0.5519;
  const createElementID = /* @__PURE__ */ function() {
    var _count = 0;
    return function createID() {
      _count += 1;
      return idPrefix$1 + "__lottie_element_" + _count;
    };
  }();
  const rgbToHex = function() {
    var colorMap = [];
    var i;
    var hex;
    for (i = 0; i < 256; i += 1) {
      hex = i.toString(16);
      colorMap[i] = hex.length === 1 ? "0" + hex : hex;
    }
    return function(r, g3, b3) {
      if (r < 0) {
        r = 0;
      }
      if (g3 < 0) {
        g3 = 0;
      }
      if (b3 < 0) {
        b3 = 0;
      }
      return "#" + colorMap[r] + colorMap[g3] + colorMap[b3];
    };
  }();
  const setSubframeEnabled = (flag) => {
    subframeEnabled = !!flag;
  };
  const getSubframeEnabled = () => subframeEnabled;
  const setExpressionsPlugin = (value2) => {
    expressionsPlugin = value2;
  };
  const getExpressionsPlugin = () => expressionsPlugin;
  const setDefaultCurveSegments = (value2) => {
    defaultCurveSegments = value2;
  };
  const getDefaultCurveSegments = () => defaultCurveSegments;
  const setIdPrefix = (value2) => {
    idPrefix$1 = value2;
  };
  const getIdPrefix = () => idPrefix$1;
  const dataManager = /* @__PURE__ */ function() {
    var _counterId = 1;
    var processes = [];
    var workerFn;
    var workerInstance;
    var workerProxy = {
      onmessage: function() {
      },
      postMessage: function(path) {
        workerFn({
          data: path
        });
      }
    };
    var _workerSelf = {
      postMessage: function(data2) {
        workerProxy.onmessage({
          data: data2
        });
      }
    };
    function createWorker(fn) {
      if (window.Worker && window.Blob && getWebWorker()) {
        var blob = new Blob(["var _workerSelf = self; self.onmessage = ", fn.toString()], { type: "text/javascript" });
        var url = URL.createObjectURL(blob);
        return new Worker(url);
      }
      workerFn = fn;
      return workerProxy;
    }
    function setupWorker() {
      if (!workerInstance) {
        workerInstance = createWorker(function workerStart(e) {
          function dataFunctionManager() {
            function completeLayers(layers, comps) {
              var layerData;
              var i;
              var len = layers.length;
              var j2;
              var jLen;
              var k2;
              var kLen;
              for (i = 0; i < len; i += 1) {
                layerData = layers[i];
                if ("ks" in layerData && !layerData.completed) {
                  layerData.completed = true;
                  if (layerData.tt) {
                    layers[i - 1].td = layerData.tt;
                  }
                  if (layerData.hasMask) {
                    var maskProps = layerData.masksProperties;
                    jLen = maskProps.length;
                    for (j2 = 0; j2 < jLen; j2 += 1) {
                      if (maskProps[j2].pt.k.i) {
                        convertPathsToAbsoluteValues(maskProps[j2].pt.k);
                      } else {
                        kLen = maskProps[j2].pt.k.length;
                        for (k2 = 0; k2 < kLen; k2 += 1) {
                          if (maskProps[j2].pt.k[k2].s) {
                            convertPathsToAbsoluteValues(maskProps[j2].pt.k[k2].s[0]);
                          }
                          if (maskProps[j2].pt.k[k2].e) {
                            convertPathsToAbsoluteValues(maskProps[j2].pt.k[k2].e[0]);
                          }
                        }
                      }
                    }
                  }
                  if (layerData.ty === 0) {
                    layerData.layers = findCompLayers(layerData.refId, comps);
                    completeLayers(layerData.layers, comps);
                  } else if (layerData.ty === 4) {
                    completeShapes(layerData.shapes);
                  } else if (layerData.ty === 5) {
                    completeText(layerData);
                  }
                }
              }
            }
            function completeChars(chars, assets) {
              if (chars) {
                var i = 0;
                var len = chars.length;
                for (i = 0; i < len; i += 1) {
                  if (chars[i].t === 1) {
                    chars[i].data.layers = findCompLayers(chars[i].data.refId, assets);
                    completeLayers(chars[i].data.layers, assets);
                  }
                }
              }
            }
            function findComp(id, comps) {
              var i = 0;
              var len = comps.length;
              while (i < len) {
                if (comps[i].id === id) {
                  return comps[i];
                }
                i += 1;
              }
              return null;
            }
            function findCompLayers(id, comps) {
              var comp2 = findComp(id, comps);
              if (comp2) {
                if (!comp2.layers.__used) {
                  comp2.layers.__used = true;
                  return comp2.layers;
                }
                return JSON.parse(JSON.stringify(comp2.layers));
              }
              return null;
            }
            function completeShapes(arr) {
              var i;
              var len = arr.length;
              var j2;
              var jLen;
              for (i = len - 1; i >= 0; i -= 1) {
                if (arr[i].ty === "sh") {
                  if (arr[i].ks.k.i) {
                    convertPathsToAbsoluteValues(arr[i].ks.k);
                  } else {
                    jLen = arr[i].ks.k.length;
                    for (j2 = 0; j2 < jLen; j2 += 1) {
                      if (arr[i].ks.k[j2].s) {
                        convertPathsToAbsoluteValues(arr[i].ks.k[j2].s[0]);
                      }
                      if (arr[i].ks.k[j2].e) {
                        convertPathsToAbsoluteValues(arr[i].ks.k[j2].e[0]);
                      }
                    }
                  }
                } else if (arr[i].ty === "gr") {
                  completeShapes(arr[i].it);
                }
              }
            }
            function convertPathsToAbsoluteValues(path) {
              var i;
              var len = path.i.length;
              for (i = 0; i < len; i += 1) {
                path.i[i][0] += path.v[i][0];
                path.i[i][1] += path.v[i][1];
                path.o[i][0] += path.v[i][0];
                path.o[i][1] += path.v[i][1];
              }
            }
            function checkVersion(minimum, animVersionString) {
              var animVersion = animVersionString ? animVersionString.split(".") : [100, 100, 100];
              if (minimum[0] > animVersion[0]) {
                return true;
              }
              if (animVersion[0] > minimum[0]) {
                return false;
              }
              if (minimum[1] > animVersion[1]) {
                return true;
              }
              if (animVersion[1] > minimum[1]) {
                return false;
              }
              if (minimum[2] > animVersion[2]) {
                return true;
              }
              if (animVersion[2] > minimum[2]) {
                return false;
              }
              return null;
            }
            var checkText = /* @__PURE__ */ function() {
              var minimumVersion = [4, 4, 14];
              function updateTextLayer(textLayer) {
                var documentData = textLayer.t.d;
                textLayer.t.d = {
                  k: [
                    {
                      s: documentData,
                      t: 0
                    }
                  ]
                };
              }
              function iterateLayers(layers) {
                var i;
                var len = layers.length;
                for (i = 0; i < len; i += 1) {
                  if (layers[i].ty === 5) {
                    updateTextLayer(layers[i]);
                  }
                }
              }
              return function(animationData2) {
                if (checkVersion(minimumVersion, animationData2.v)) {
                  iterateLayers(animationData2.layers);
                  if (animationData2.assets) {
                    var i;
                    var len = animationData2.assets.length;
                    for (i = 0; i < len; i += 1) {
                      if (animationData2.assets[i].layers) {
                        iterateLayers(animationData2.assets[i].layers);
                      }
                    }
                  }
                }
              };
            }();
            var checkChars = /* @__PURE__ */ function() {
              var minimumVersion = [4, 7, 99];
              return function(animationData2) {
                if (animationData2.chars && !checkVersion(minimumVersion, animationData2.v)) {
                  var i;
                  var len = animationData2.chars.length;
                  for (i = 0; i < len; i += 1) {
                    var charData = animationData2.chars[i];
                    if (charData.data && charData.data.shapes) {
                      completeShapes(charData.data.shapes);
                      charData.data.ip = 0;
                      charData.data.op = 99999;
                      charData.data.st = 0;
                      charData.data.sr = 1;
                      charData.data.ks = {
                        p: { k: [0, 0], a: 0 },
                        s: { k: [100, 100], a: 0 },
                        a: { k: [0, 0], a: 0 },
                        r: { k: 0, a: 0 },
                        o: { k: 100, a: 0 }
                      };
                      if (!animationData2.chars[i].t) {
                        charData.data.shapes.push(
                          {
                            ty: "no"
                          }
                        );
                        charData.data.shapes[0].it.push(
                          {
                            p: { k: [0, 0], a: 0 },
                            s: { k: [100, 100], a: 0 },
                            a: { k: [0, 0], a: 0 },
                            r: { k: 0, a: 0 },
                            o: { k: 100, a: 0 },
                            sk: { k: 0, a: 0 },
                            sa: { k: 0, a: 0 },
                            ty: "tr"
                          }
                        );
                      }
                    }
                  }
                }
              };
            }();
            var checkPathProperties = /* @__PURE__ */ function() {
              var minimumVersion = [5, 7, 15];
              function updateTextLayer(textLayer) {
                var pathData = textLayer.t.p;
                if (typeof pathData.a === "number") {
                  pathData.a = {
                    a: 0,
                    k: pathData.a
                  };
                }
                if (typeof pathData.p === "number") {
                  pathData.p = {
                    a: 0,
                    k: pathData.p
                  };
                }
                if (typeof pathData.r === "number") {
                  pathData.r = {
                    a: 0,
                    k: pathData.r
                  };
                }
              }
              function iterateLayers(layers) {
                var i;
                var len = layers.length;
                for (i = 0; i < len; i += 1) {
                  if (layers[i].ty === 5) {
                    updateTextLayer(layers[i]);
                  }
                }
              }
              return function(animationData2) {
                if (checkVersion(minimumVersion, animationData2.v)) {
                  iterateLayers(animationData2.layers);
                  if (animationData2.assets) {
                    var i;
                    var len = animationData2.assets.length;
                    for (i = 0; i < len; i += 1) {
                      if (animationData2.assets[i].layers) {
                        iterateLayers(animationData2.assets[i].layers);
                      }
                    }
                  }
                }
              };
            }();
            var checkColors = /* @__PURE__ */ function() {
              var minimumVersion = [4, 1, 9];
              function iterateShapes(shapes) {
                var i;
                var len = shapes.length;
                var j2;
                var jLen;
                for (i = 0; i < len; i += 1) {
                  if (shapes[i].ty === "gr") {
                    iterateShapes(shapes[i].it);
                  } else if (shapes[i].ty === "fl" || shapes[i].ty === "st") {
                    if (shapes[i].c.k && shapes[i].c.k[0].i) {
                      jLen = shapes[i].c.k.length;
                      for (j2 = 0; j2 < jLen; j2 += 1) {
                        if (shapes[i].c.k[j2].s) {
                          shapes[i].c.k[j2].s[0] /= 255;
                          shapes[i].c.k[j2].s[1] /= 255;
                          shapes[i].c.k[j2].s[2] /= 255;
                          shapes[i].c.k[j2].s[3] /= 255;
                        }
                        if (shapes[i].c.k[j2].e) {
                          shapes[i].c.k[j2].e[0] /= 255;
                          shapes[i].c.k[j2].e[1] /= 255;
                          shapes[i].c.k[j2].e[2] /= 255;
                          shapes[i].c.k[j2].e[3] /= 255;
                        }
                      }
                    } else {
                      shapes[i].c.k[0] /= 255;
                      shapes[i].c.k[1] /= 255;
                      shapes[i].c.k[2] /= 255;
                      shapes[i].c.k[3] /= 255;
                    }
                  }
                }
              }
              function iterateLayers(layers) {
                var i;
                var len = layers.length;
                for (i = 0; i < len; i += 1) {
                  if (layers[i].ty === 4) {
                    iterateShapes(layers[i].shapes);
                  }
                }
              }
              return function(animationData2) {
                if (checkVersion(minimumVersion, animationData2.v)) {
                  iterateLayers(animationData2.layers);
                  if (animationData2.assets) {
                    var i;
                    var len = animationData2.assets.length;
                    for (i = 0; i < len; i += 1) {
                      if (animationData2.assets[i].layers) {
                        iterateLayers(animationData2.assets[i].layers);
                      }
                    }
                  }
                }
              };
            }();
            var checkShapes = /* @__PURE__ */ function() {
              var minimumVersion = [4, 4, 18];
              function completeClosingShapes(arr) {
                var i;
                var len = arr.length;
                var j2;
                var jLen;
                for (i = len - 1; i >= 0; i -= 1) {
                  if (arr[i].ty === "sh") {
                    if (arr[i].ks.k.i) {
                      arr[i].ks.k.c = arr[i].closed;
                    } else {
                      jLen = arr[i].ks.k.length;
                      for (j2 = 0; j2 < jLen; j2 += 1) {
                        if (arr[i].ks.k[j2].s) {
                          arr[i].ks.k[j2].s[0].c = arr[i].closed;
                        }
                        if (arr[i].ks.k[j2].e) {
                          arr[i].ks.k[j2].e[0].c = arr[i].closed;
                        }
                      }
                    }
                  } else if (arr[i].ty === "gr") {
                    completeClosingShapes(arr[i].it);
                  }
                }
              }
              function iterateLayers(layers) {
                var layerData;
                var i;
                var len = layers.length;
                var j2;
                var jLen;
                var k2;
                var kLen;
                for (i = 0; i < len; i += 1) {
                  layerData = layers[i];
                  if (layerData.hasMask) {
                    var maskProps = layerData.masksProperties;
                    jLen = maskProps.length;
                    for (j2 = 0; j2 < jLen; j2 += 1) {
                      if (maskProps[j2].pt.k.i) {
                        maskProps[j2].pt.k.c = maskProps[j2].cl;
                      } else {
                        kLen = maskProps[j2].pt.k.length;
                        for (k2 = 0; k2 < kLen; k2 += 1) {
                          if (maskProps[j2].pt.k[k2].s) {
                            maskProps[j2].pt.k[k2].s[0].c = maskProps[j2].cl;
                          }
                          if (maskProps[j2].pt.k[k2].e) {
                            maskProps[j2].pt.k[k2].e[0].c = maskProps[j2].cl;
                          }
                        }
                      }
                    }
                  }
                  if (layerData.ty === 4) {
                    completeClosingShapes(layerData.shapes);
                  }
                }
              }
              return function(animationData2) {
                if (checkVersion(minimumVersion, animationData2.v)) {
                  iterateLayers(animationData2.layers);
                  if (animationData2.assets) {
                    var i;
                    var len = animationData2.assets.length;
                    for (i = 0; i < len; i += 1) {
                      if (animationData2.assets[i].layers) {
                        iterateLayers(animationData2.assets[i].layers);
                      }
                    }
                  }
                }
              };
            }();
            function completeData(animationData2) {
              if (animationData2.__complete) {
                return;
              }
              checkColors(animationData2);
              checkText(animationData2);
              checkChars(animationData2);
              checkPathProperties(animationData2);
              checkShapes(animationData2);
              completeLayers(animationData2.layers, animationData2.assets);
              completeChars(animationData2.chars, animationData2.assets);
              animationData2.__complete = true;
            }
            function completeText(data2) {
              if (data2.t.a.length === 0 && !("m" in data2.t.p)) {
              }
            }
            var moduleOb = {};
            moduleOb.completeData = completeData;
            moduleOb.checkColors = checkColors;
            moduleOb.checkChars = checkChars;
            moduleOb.checkPathProperties = checkPathProperties;
            moduleOb.checkShapes = checkShapes;
            moduleOb.completeLayers = completeLayers;
            return moduleOb;
          }
          if (!_workerSelf.dataManager) {
            _workerSelf.dataManager = dataFunctionManager();
          }
          if (!_workerSelf.assetLoader) {
            _workerSelf.assetLoader = /* @__PURE__ */ function() {
              function formatResponse(xhr) {
                var contentTypeHeader = xhr.getResponseHeader("content-type");
                if (contentTypeHeader && xhr.responseType === "json" && contentTypeHeader.indexOf("json") !== -1) {
                  return xhr.response;
                }
                if (xhr.response && typeof xhr.response === "object") {
                  return xhr.response;
                }
                if (xhr.response && typeof xhr.response === "string") {
                  return JSON.parse(xhr.response);
                }
                if (xhr.responseText) {
                  return JSON.parse(xhr.responseText);
                }
                return null;
              }
              function loadAsset(path, fullPath, callback, errorCallback) {
                var response;
                var xhr = new XMLHttpRequest();
                try {
                  xhr.responseType = "json";
                } catch (err2) {
                }
                xhr.onreadystatechange = function() {
                  if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                      response = formatResponse(xhr);
                      callback(response);
                    } else {
                      try {
                        response = formatResponse(xhr);
                        callback(response);
                      } catch (err2) {
                        if (errorCallback) {
                          errorCallback(err2);
                        }
                      }
                    }
                  }
                };
                try {
                  xhr.open("GET", path, true);
                } catch (error) {
                  xhr.open("GET", fullPath + "/" + path, true);
                }
                xhr.send();
              }
              return {
                load: loadAsset
              };
            }();
          }
          if (e.data.type === "loadAnimation") {
            _workerSelf.assetLoader.load(
              e.data.path,
              e.data.fullPath,
              function(data2) {
                _workerSelf.dataManager.completeData(data2);
                _workerSelf.postMessage({
                  id: e.data.id,
                  payload: data2,
                  status: "success"
                });
              },
              function() {
                _workerSelf.postMessage({
                  id: e.data.id,
                  status: "error"
                });
              }
            );
          } else if (e.data.type === "complete") {
            var animation = e.data.animation;
            _workerSelf.dataManager.completeData(animation);
            _workerSelf.postMessage({
              id: e.data.id,
              payload: animation,
              status: "success"
            });
          } else if (e.data.type === "loadData") {
            _workerSelf.assetLoader.load(
              e.data.path,
              e.data.fullPath,
              function(data2) {
                _workerSelf.postMessage({
                  id: e.data.id,
                  payload: data2,
                  status: "success"
                });
              },
              function() {
                _workerSelf.postMessage({
                  id: e.data.id,
                  status: "error"
                });
              }
            );
          }
        });
        workerInstance.onmessage = function(event) {
          var data2 = event.data;
          var id = data2.id;
          var process = processes[id];
          processes[id] = null;
          if (data2.status === "success") {
            process.onComplete(data2.payload);
          } else if (process.onError) {
            process.onError();
          }
        };
      }
    }
    function createProcess(onComplete, onError) {
      _counterId += 1;
      var id = "processId_" + _counterId;
      processes[id] = {
        onComplete,
        onError
      };
      return id;
    }
    function loadAnimation2(path, onComplete, onError) {
      setupWorker();
      var processId = createProcess(onComplete, onError);
      workerInstance.postMessage({
        type: "loadAnimation",
        path,
        fullPath: window.location.origin + window.location.pathname,
        id: processId
      });
    }
    function loadData(path, onComplete, onError) {
      setupWorker();
      var processId = createProcess(onComplete, onError);
      workerInstance.postMessage({
        type: "loadData",
        path,
        fullPath: window.location.origin + window.location.pathname,
        id: processId
      });
    }
    function completeAnimation(anim, onComplete, onError) {
      setupWorker();
      var processId = createProcess(onComplete, onError);
      workerInstance.postMessage({
        type: "complete",
        animation: anim,
        id: processId
      });
    }
    return {
      loadAnimation: loadAnimation2,
      loadData,
      completeAnimation
    };
  }();
  const ImagePreloader = function() {
    var proxyImage = function() {
      var canvas = createTag("canvas");
      canvas.width = 1;
      canvas.height = 1;
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "rgba(0,0,0,0)";
      ctx.fillRect(0, 0, 1, 1);
      return canvas;
    }();
    function imageLoaded() {
      this.loadedAssets += 1;
      if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) {
        if (this.imagesLoadedCb) {
          this.imagesLoadedCb(null);
        }
      }
    }
    function footageLoaded() {
      this.loadedFootagesCount += 1;
      if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) {
        if (this.imagesLoadedCb) {
          this.imagesLoadedCb(null);
        }
      }
    }
    function getAssetsPath(assetData, assetsPath, originalPath) {
      var path = "";
      if (assetData.e) {
        path = assetData.p;
      } else if (assetsPath) {
        var imagePath = assetData.p;
        if (imagePath.indexOf("images/") !== -1) {
          imagePath = imagePath.split("/")[1];
        }
        path = assetsPath + imagePath;
      } else {
        path = originalPath;
        path += assetData.u ? assetData.u : "";
        path += assetData.p;
      }
      return path;
    }
    function testImageLoaded(img) {
      var _count = 0;
      var intervalId = setInterval((function() {
        var box = img.getBBox();
        if (box.width || _count > 500) {
          this._imageLoaded();
          clearInterval(intervalId);
        }
        _count += 1;
      }).bind(this), 50);
    }
    function createImageData(assetData) {
      var path = getAssetsPath(assetData, this.assetsPath, this.path);
      var img = createNS("image");
      if (isSafari) {
        this.testImageLoaded(img);
      } else {
        img.addEventListener("load", this._imageLoaded, false);
      }
      img.addEventListener("error", (function() {
        ob2.img = proxyImage;
        this._imageLoaded();
      }).bind(this), false);
      img.setAttributeNS("http://www.w3.org/1999/xlink", "href", path);
      if (this._elementHelper.append) {
        this._elementHelper.append(img);
      } else {
        this._elementHelper.appendChild(img);
      }
      var ob2 = {
        img,
        assetData
      };
      return ob2;
    }
    function createImgData(assetData) {
      var path = getAssetsPath(assetData, this.assetsPath, this.path);
      var img = createTag("img");
      img.crossOrigin = "anonymous";
      img.addEventListener("load", this._imageLoaded, false);
      img.addEventListener("error", (function() {
        ob2.img = proxyImage;
        this._imageLoaded();
      }).bind(this), false);
      img.src = path;
      var ob2 = {
        img,
        assetData
      };
      return ob2;
    }
    function createFootageData(data2) {
      var ob2 = {
        assetData: data2
      };
      var path = getAssetsPath(data2, this.assetsPath, this.path);
      dataManager.loadData(path, (function(footageData) {
        ob2.img = footageData;
        this._footageLoaded();
      }).bind(this), (function() {
        ob2.img = {};
        this._footageLoaded();
      }).bind(this));
      return ob2;
    }
    function loadAssets(assets, cb) {
      this.imagesLoadedCb = cb;
      var i;
      var len = assets.length;
      for (i = 0; i < len; i += 1) {
        if (!assets[i].layers) {
          if (!assets[i].t || assets[i].t === "seq") {
            this.totalImages += 1;
            this.images.push(this._createImageData(assets[i]));
          } else if (assets[i].t === 3) {
            this.totalFootages += 1;
            this.images.push(this.createFootageData(assets[i]));
          }
        }
      }
    }
    function setPath(path) {
      this.path = path || "";
    }
    function setAssetsPath(path) {
      this.assetsPath = path || "";
    }
    function getAsset(assetData) {
      var i = 0;
      var len = this.images.length;
      while (i < len) {
        if (this.images[i].assetData === assetData) {
          return this.images[i].img;
        }
        i += 1;
      }
      return null;
    }
    function destroy() {
      this.imagesLoadedCb = null;
      this.images.length = 0;
    }
    function loadedImages() {
      return this.totalImages === this.loadedAssets;
    }
    function loadedFootages() {
      return this.totalFootages === this.loadedFootagesCount;
    }
    function setCacheType(type, elementHelper) {
      if (type === "svg") {
        this._elementHelper = elementHelper;
        this._createImageData = this.createImageData.bind(this);
      } else {
        this._createImageData = this.createImgData.bind(this);
      }
    }
    function ImagePreloaderFactory() {
      this._imageLoaded = imageLoaded.bind(this);
      this._footageLoaded = footageLoaded.bind(this);
      this.testImageLoaded = testImageLoaded.bind(this);
      this.createFootageData = createFootageData.bind(this);
      this.assetsPath = "";
      this.path = "";
      this.totalImages = 0;
      this.totalFootages = 0;
      this.loadedAssets = 0;
      this.loadedFootagesCount = 0;
      this.imagesLoadedCb = null;
      this.images = [];
    }
    ImagePreloaderFactory.prototype = {
      loadAssets,
      setAssetsPath,
      setPath,
      loadedImages,
      loadedFootages,
      destroy,
      getAsset,
      createImgData,
      createImageData,
      imageLoaded,
      footageLoaded,
      setCacheType
    };
    return ImagePreloaderFactory;
  }();
  BaseEvent.prototype = {
    triggerEvent: function(eventName, args) {
      if (this._cbs[eventName]) {
        var callbacks = this._cbs[eventName];
        for (var i = 0; i < callbacks.length; i += 1) {
          callbacks[i](args);
        }
      }
    },
    addEventListener: function(eventName, callback) {
      if (!this._cbs[eventName]) {
        this._cbs[eventName] = [];
      }
      this._cbs[eventName].push(callback);
      return (function() {
        this.removeEventListener(eventName, callback);
      }).bind(this);
    },
    removeEventListener: function(eventName, callback) {
      if (!callback) {
        this._cbs[eventName] = null;
      } else if (this._cbs[eventName]) {
        var i = 0;
        var len = this._cbs[eventName].length;
        while (i < len) {
          if (this._cbs[eventName][i] === callback) {
            this._cbs[eventName].splice(i, 1);
            i -= 1;
            len -= 1;
          }
          i += 1;
        }
        if (!this._cbs[eventName].length) {
          this._cbs[eventName] = null;
        }
      }
    }
  };
  const markerParser = /* @__PURE__ */ function() {
    function parsePayloadLines(payload) {
      var lines = payload.split("\r\n");
      var keys2 = {};
      var line2;
      var keysCount = 0;
      for (var i = 0; i < lines.length; i += 1) {
        line2 = lines[i].split(":");
        if (line2.length === 2) {
          keys2[line2[0]] = line2[1].trim();
          keysCount += 1;
        }
      }
      if (keysCount === 0) {
        throw new Error();
      }
      return keys2;
    }
    return function(_markers) {
      var markers = [];
      for (var i = 0; i < _markers.length; i += 1) {
        var _marker = _markers[i];
        var markerData = {
          time: _marker.tm,
          duration: _marker.dr
        };
        try {
          markerData.payload = JSON.parse(_markers[i].cm);
        } catch (_) {
          try {
            markerData.payload = parsePayloadLines(_markers[i].cm);
          } catch (__) {
            markerData.payload = {
              name: _markers[i].cm
            };
          }
        }
        markers.push(markerData);
      }
      return markers;
    };
  }();
  const ProjectInterface = /* @__PURE__ */ function() {
    function registerComposition(comp2) {
      this.compositions.push(comp2);
    }
    return function() {
      function _thisProjectFunction(name2) {
        var i = 0;
        var len = this.compositions.length;
        while (i < len) {
          if (this.compositions[i].data && this.compositions[i].data.nm === name2) {
            if (this.compositions[i].prepareFrame && this.compositions[i].data.xt) {
              this.compositions[i].prepareFrame(this.currentFrame);
            }
            return this.compositions[i].compInterface;
          }
          i += 1;
        }
        return null;
      }
      _thisProjectFunction.compositions = [];
      _thisProjectFunction.currentFrame = 0;
      _thisProjectFunction.registerComposition = registerComposition;
      return _thisProjectFunction;
    };
  }();
  const renderers = {};
  const registerRenderer = (key2, value2) => {
    renderers[key2] = value2;
  };
  const AnimationItem = function() {
    this._cbs = [];
    this.name = "";
    this.path = "";
    this.isLoaded = false;
    this.currentFrame = 0;
    this.currentRawFrame = 0;
    this.firstFrame = 0;
    this.totalFrames = 0;
    this.frameRate = 0;
    this.frameMult = 0;
    this.playSpeed = 1;
    this.playDirection = 1;
    this.playCount = 0;
    this.animationData = {};
    this.assets = [];
    this.isPaused = true;
    this.autoplay = false;
    this.loop = true;
    this.renderer = null;
    this.animationID = createElementID();
    this.assetsPath = "";
    this.timeCompleted = 0;
    this.segmentPos = 0;
    this.isSubframeEnabled = getSubframeEnabled();
    this.segments = [];
    this._idle = true;
    this._completedLoop = false;
    this.projectInterface = ProjectInterface();
    this.imagePreloader = new ImagePreloader();
    this.audioController = audioControllerFactory();
    this.markers = [];
    this.configAnimation = this.configAnimation.bind(this);
    this.onSetupError = this.onSetupError.bind(this);
    this.onSegmentComplete = this.onSegmentComplete.bind(this);
    this.drawnFrameEvent = new BMEnterFrameEvent("drawnFrame", 0, 0, 0);
  };
  extendPrototype([BaseEvent], AnimationItem);
  AnimationItem.prototype.setParams = function(params) {
    if (params.wrapper || params.container) {
      this.wrapper = params.wrapper || params.container;
    }
    var animType = "svg";
    if (params.animType) {
      animType = params.animType;
    } else if (params.renderer) {
      animType = params.renderer;
    }
    const RendererClass = getRenderer(animType);
    this.renderer = new RendererClass(this, params.rendererSettings);
    this.imagePreloader.setCacheType(animType, this.renderer.globalData.defs);
    this.renderer.setProjectInterface(this.projectInterface);
    this.animType = animType;
    if (params.loop === "" || params.loop === null || params.loop === void 0 || params.loop === true) {
      this.loop = true;
    } else if (params.loop === false) {
      this.loop = false;
    } else {
      this.loop = parseInt(params.loop, 10);
    }
    this.autoplay = "autoplay" in params ? params.autoplay : true;
    this.name = params.name ? params.name : "";
    this.autoloadSegments = Object.prototype.hasOwnProperty.call(params, "autoloadSegments") ? params.autoloadSegments : true;
    this.assetsPath = params.assetsPath;
    this.initialSegment = params.initialSegment;
    if (params.audioFactory) {
      this.audioController.setAudioFactory(params.audioFactory);
    }
    if (params.animationData) {
      this.setupAnimation(params.animationData);
    } else if (params.path) {
      if (params.path.lastIndexOf("\\") !== -1) {
        this.path = params.path.substr(0, params.path.lastIndexOf("\\") + 1);
      } else {
        this.path = params.path.substr(0, params.path.lastIndexOf("/") + 1);
      }
      this.fileName = params.path.substr(params.path.lastIndexOf("/") + 1);
      this.fileName = this.fileName.substr(0, this.fileName.lastIndexOf(".json"));
      dataManager.loadAnimation(
        params.path,
        this.configAnimation,
        this.onSetupError
      );
    }
  };
  AnimationItem.prototype.onSetupError = function() {
    this.trigger("data_failed");
  };
  AnimationItem.prototype.setupAnimation = function(data2) {
    dataManager.completeAnimation(
      data2,
      this.configAnimation
    );
  };
  AnimationItem.prototype.setData = function(wrapper, animationData2) {
    if (animationData2) {
      if (typeof animationData2 !== "object") {
        animationData2 = JSON.parse(animationData2);
      }
    }
    var params = {
      wrapper,
      animationData: animationData2
    };
    var wrapperAttributes = wrapper.attributes;
    params.path = wrapperAttributes.getNamedItem("data-animation-path") ? wrapperAttributes.getNamedItem("data-animation-path").value : wrapperAttributes.getNamedItem("data-bm-path") ? wrapperAttributes.getNamedItem("data-bm-path").value : wrapperAttributes.getNamedItem("bm-path") ? wrapperAttributes.getNamedItem("bm-path").value : "";
    params.animType = wrapperAttributes.getNamedItem("data-anim-type") ? wrapperAttributes.getNamedItem("data-anim-type").value : wrapperAttributes.getNamedItem("data-bm-type") ? wrapperAttributes.getNamedItem("data-bm-type").value : wrapperAttributes.getNamedItem("bm-type") ? wrapperAttributes.getNamedItem("bm-type").value : wrapperAttributes.getNamedItem("data-bm-renderer") ? wrapperAttributes.getNamedItem("data-bm-renderer").value : wrapperAttributes.getNamedItem("bm-renderer") ? wrapperAttributes.getNamedItem("bm-renderer").value : "canvas";
    var loop = wrapperAttributes.getNamedItem("data-anim-loop") ? wrapperAttributes.getNamedItem("data-anim-loop").value : wrapperAttributes.getNamedItem("data-bm-loop") ? wrapperAttributes.getNamedItem("data-bm-loop").value : wrapperAttributes.getNamedItem("bm-loop") ? wrapperAttributes.getNamedItem("bm-loop").value : "";
    if (loop === "false") {
      params.loop = false;
    } else if (loop === "true") {
      params.loop = true;
    } else if (loop !== "") {
      params.loop = parseInt(loop, 10);
    }
    var autoplay = wrapperAttributes.getNamedItem("data-anim-autoplay") ? wrapperAttributes.getNamedItem("data-anim-autoplay").value : wrapperAttributes.getNamedItem("data-bm-autoplay") ? wrapperAttributes.getNamedItem("data-bm-autoplay").value : wrapperAttributes.getNamedItem("bm-autoplay") ? wrapperAttributes.getNamedItem("bm-autoplay").value : true;
    params.autoplay = autoplay !== "false";
    params.name = wrapperAttributes.getNamedItem("data-name") ? wrapperAttributes.getNamedItem("data-name").value : wrapperAttributes.getNamedItem("data-bm-name") ? wrapperAttributes.getNamedItem("data-bm-name").value : wrapperAttributes.getNamedItem("bm-name") ? wrapperAttributes.getNamedItem("bm-name").value : "";
    var prerender = wrapperAttributes.getNamedItem("data-anim-prerender") ? wrapperAttributes.getNamedItem("data-anim-prerender").value : wrapperAttributes.getNamedItem("data-bm-prerender") ? wrapperAttributes.getNamedItem("data-bm-prerender").value : wrapperAttributes.getNamedItem("bm-prerender") ? wrapperAttributes.getNamedItem("bm-prerender").value : "";
    if (prerender === "false") {
      params.prerender = false;
    }
    this.setParams(params);
  };
  AnimationItem.prototype.includeLayers = function(data2) {
    if (data2.op > this.animationData.op) {
      this.animationData.op = data2.op;
      this.totalFrames = Math.floor(data2.op - this.animationData.ip);
    }
    var layers = this.animationData.layers;
    var i;
    var len = layers.length;
    var newLayers = data2.layers;
    var j2;
    var jLen = newLayers.length;
    for (j2 = 0; j2 < jLen; j2 += 1) {
      i = 0;
      while (i < len) {
        if (layers[i].id === newLayers[j2].id) {
          layers[i] = newLayers[j2];
          break;
        }
        i += 1;
      }
    }
    if (data2.chars || data2.fonts) {
      this.renderer.globalData.fontManager.addChars(data2.chars);
      this.renderer.globalData.fontManager.addFonts(data2.fonts, this.renderer.globalData.defs);
    }
    if (data2.assets) {
      len = data2.assets.length;
      for (i = 0; i < len; i += 1) {
        this.animationData.assets.push(data2.assets[i]);
      }
    }
    this.animationData.__complete = false;
    dataManager.completeAnimation(
      this.animationData,
      this.onSegmentComplete
    );
  };
  AnimationItem.prototype.onSegmentComplete = function(data2) {
    this.animationData = data2;
    var expressionsPlugin2 = getExpressionsPlugin();
    if (expressionsPlugin2) {
      expressionsPlugin2.initExpressions(this);
    }
    this.loadNextSegment();
  };
  AnimationItem.prototype.loadNextSegment = function() {
    var segments = this.animationData.segments;
    if (!segments || segments.length === 0 || !this.autoloadSegments) {
      this.trigger("data_ready");
      this.timeCompleted = this.totalFrames;
      return;
    }
    var segment = segments.shift();
    this.timeCompleted = segment.time * this.frameRate;
    var segmentPath = this.path + this.fileName + "_" + this.segmentPos + ".json";
    this.segmentPos += 1;
    dataManager.loadData(segmentPath, this.includeLayers.bind(this), (function() {
      this.trigger("data_failed");
    }).bind(this));
  };
  AnimationItem.prototype.loadSegments = function() {
    var segments = this.animationData.segments;
    if (!segments) {
      this.timeCompleted = this.totalFrames;
    }
    this.loadNextSegment();
  };
  AnimationItem.prototype.imagesLoaded = function() {
    this.trigger("loaded_images");
    this.checkLoaded();
  };
  AnimationItem.prototype.preloadImages = function() {
    this.imagePreloader.setAssetsPath(this.assetsPath);
    this.imagePreloader.setPath(this.path);
    this.imagePreloader.loadAssets(this.animationData.assets, this.imagesLoaded.bind(this));
  };
  AnimationItem.prototype.configAnimation = function(animData) {
    if (!this.renderer) {
      return;
    }
    try {
      this.animationData = animData;
      if (this.initialSegment) {
        this.totalFrames = Math.floor(this.initialSegment[1] - this.initialSegment[0]);
        this.firstFrame = Math.round(this.initialSegment[0]);
      } else {
        this.totalFrames = Math.floor(this.animationData.op - this.animationData.ip);
        this.firstFrame = Math.round(this.animationData.ip);
      }
      this.renderer.configAnimation(animData);
      if (!animData.assets) {
        animData.assets = [];
      }
      this.assets = this.animationData.assets;
      this.frameRate = this.animationData.fr;
      this.frameMult = this.animationData.fr / 1e3;
      this.renderer.searchExtraCompositions(animData.assets);
      this.markers = markerParser(animData.markers || []);
      this.trigger("config_ready");
      this.preloadImages();
      this.loadSegments();
      this.updaFrameModifier();
      this.waitForFontsLoaded();
      if (this.isPaused) {
        this.audioController.pause();
      }
    } catch (error) {
      this.triggerConfigError(error);
    }
  };
  AnimationItem.prototype.waitForFontsLoaded = function() {
    if (!this.renderer) {
      return;
    }
    if (this.renderer.globalData.fontManager.isLoaded) {
      this.checkLoaded();
    } else {
      setTimeout(this.waitForFontsLoaded.bind(this), 20);
    }
  };
  AnimationItem.prototype.checkLoaded = function() {
    if (!this.isLoaded && this.renderer.globalData.fontManager.isLoaded && (this.imagePreloader.loadedImages() || this.renderer.rendererType !== "canvas") && this.imagePreloader.loadedFootages()) {
      this.isLoaded = true;
      var expressionsPlugin2 = getExpressionsPlugin();
      if (expressionsPlugin2) {
        expressionsPlugin2.initExpressions(this);
      }
      this.renderer.initItems();
      setTimeout((function() {
        this.trigger("DOMLoaded");
      }).bind(this), 0);
      this.gotoFrame();
      if (this.autoplay) {
        this.play();
      }
    }
  };
  AnimationItem.prototype.resize = function() {
    this.renderer.updateContainerSize();
  };
  AnimationItem.prototype.setSubframe = function(flag) {
    this.isSubframeEnabled = !!flag;
  };
  AnimationItem.prototype.gotoFrame = function() {
    this.currentFrame = this.isSubframeEnabled ? this.currentRawFrame : ~~this.currentRawFrame;
    if (this.timeCompleted !== this.totalFrames && this.currentFrame > this.timeCompleted) {
      this.currentFrame = this.timeCompleted;
    }
    this.trigger("enterFrame");
    this.renderFrame();
    this.trigger("drawnFrame");
  };
  AnimationItem.prototype.renderFrame = function() {
    if (this.isLoaded === false || !this.renderer) {
      return;
    }
    try {
      this.renderer.renderFrame(this.currentFrame + this.firstFrame);
    } catch (error) {
      this.triggerRenderFrameError(error);
    }
  };
  AnimationItem.prototype.play = function(name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    if (this.isPaused === true) {
      this.isPaused = false;
      this.trigger("_pause");
      this.audioController.resume();
      if (this._idle) {
        this._idle = false;
        this.trigger("_active");
      }
    }
  };
  AnimationItem.prototype.pause = function(name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    if (this.isPaused === false) {
      this.isPaused = true;
      this.trigger("_play");
      this._idle = true;
      this.trigger("_idle");
      this.audioController.pause();
    }
  };
  AnimationItem.prototype.togglePause = function(name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    if (this.isPaused === true) {
      this.play();
    } else {
      this.pause();
    }
  };
  AnimationItem.prototype.stop = function(name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    this.pause();
    this.playCount = 0;
    this._completedLoop = false;
    this.setCurrentRawFrameValue(0);
  };
  AnimationItem.prototype.getMarkerData = function(markerName) {
    var marker;
    for (var i = 0; i < this.markers.length; i += 1) {
      marker = this.markers[i];
      if (marker.payload && marker.payload.name === markerName) {
        return marker;
      }
    }
    return null;
  };
  AnimationItem.prototype.goToAndStop = function(value2, isFrame, name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    var numValue = Number(value2);
    if (isNaN(numValue)) {
      var marker = this.getMarkerData(value2);
      if (marker) {
        this.goToAndStop(marker.time, true);
      }
    } else if (isFrame) {
      this.setCurrentRawFrameValue(value2);
    } else {
      this.setCurrentRawFrameValue(value2 * this.frameModifier);
    }
    this.pause();
  };
  AnimationItem.prototype.goToAndPlay = function(value2, isFrame, name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    var numValue = Number(value2);
    if (isNaN(numValue)) {
      var marker = this.getMarkerData(value2);
      if (marker) {
        if (!marker.duration) {
          this.goToAndStop(marker.time, true);
        } else {
          this.playSegments([marker.time, marker.time + marker.duration], true);
        }
      }
    } else {
      this.goToAndStop(numValue, isFrame, name2);
    }
    this.play();
  };
  AnimationItem.prototype.advanceTime = function(value2) {
    if (this.isPaused === true || this.isLoaded === false) {
      return;
    }
    var nextValue = this.currentRawFrame + value2 * this.frameModifier;
    var _isComplete = false;
    if (nextValue >= this.totalFrames - 1 && this.frameModifier > 0) {
      if (!this.loop || this.playCount === this.loop) {
        if (!this.checkSegments(nextValue > this.totalFrames ? nextValue % this.totalFrames : 0)) {
          _isComplete = true;
          nextValue = this.totalFrames - 1;
        }
      } else if (nextValue >= this.totalFrames) {
        this.playCount += 1;
        if (!this.checkSegments(nextValue % this.totalFrames)) {
          this.setCurrentRawFrameValue(nextValue % this.totalFrames);
          this._completedLoop = true;
          this.trigger("loopComplete");
        }
      } else {
        this.setCurrentRawFrameValue(nextValue);
      }
    } else if (nextValue < 0) {
      if (!this.checkSegments(nextValue % this.totalFrames)) {
        if (this.loop && !(this.playCount-- <= 0 && this.loop !== true)) {
          this.setCurrentRawFrameValue(this.totalFrames + nextValue % this.totalFrames);
          if (!this._completedLoop) {
            this._completedLoop = true;
          } else {
            this.trigger("loopComplete");
          }
        } else {
          _isComplete = true;
          nextValue = 0;
        }
      }
    } else {
      this.setCurrentRawFrameValue(nextValue);
    }
    if (_isComplete) {
      this.setCurrentRawFrameValue(nextValue);
      this.pause();
      this.trigger("complete");
    }
  };
  AnimationItem.prototype.adjustSegment = function(arr, offset) {
    this.playCount = 0;
    if (arr[1] < arr[0]) {
      if (this.frameModifier > 0) {
        if (this.playSpeed < 0) {
          this.setSpeed(-this.playSpeed);
        } else {
          this.setDirection(-1);
        }
      }
      this.totalFrames = arr[0] - arr[1];
      this.timeCompleted = this.totalFrames;
      this.firstFrame = arr[1];
      this.setCurrentRawFrameValue(this.totalFrames - 1e-3 - offset);
    } else if (arr[1] > arr[0]) {
      if (this.frameModifier < 0) {
        if (this.playSpeed < 0) {
          this.setSpeed(-this.playSpeed);
        } else {
          this.setDirection(1);
        }
      }
      this.totalFrames = arr[1] - arr[0];
      this.timeCompleted = this.totalFrames;
      this.firstFrame = arr[0];
      this.setCurrentRawFrameValue(1e-3 + offset);
    }
    this.trigger("segmentStart");
  };
  AnimationItem.prototype.setSegment = function(init, end) {
    var pendingFrame = -1;
    if (this.isPaused) {
      if (this.currentRawFrame + this.firstFrame < init) {
        pendingFrame = init;
      } else if (this.currentRawFrame + this.firstFrame > end) {
        pendingFrame = end - init;
      }
    }
    this.firstFrame = init;
    this.totalFrames = end - init;
    this.timeCompleted = this.totalFrames;
    if (pendingFrame !== -1) {
      this.goToAndStop(pendingFrame, true);
    }
  };
  AnimationItem.prototype.playSegments = function(arr, forceFlag) {
    if (forceFlag) {
      this.segments.length = 0;
    }
    if (typeof arr[0] === "object") {
      var i;
      var len = arr.length;
      for (i = 0; i < len; i += 1) {
        this.segments.push(arr[i]);
      }
    } else {
      this.segments.push(arr);
    }
    if (this.segments.length && forceFlag) {
      this.adjustSegment(this.segments.shift(), 0);
    }
    if (this.isPaused) {
      this.play();
    }
  };
  AnimationItem.prototype.resetSegments = function(forceFlag) {
    this.segments.length = 0;
    this.segments.push([this.animationData.ip, this.animationData.op]);
    if (forceFlag) {
      this.checkSegments(0);
    }
  };
  AnimationItem.prototype.checkSegments = function(offset) {
    if (this.segments.length) {
      this.adjustSegment(this.segments.shift(), offset);
      return true;
    }
    return false;
  };
  AnimationItem.prototype.destroy = function(name2) {
    if (name2 && this.name !== name2 || !this.renderer) {
      return;
    }
    this.renderer.destroy();
    this.imagePreloader.destroy();
    this.trigger("destroy");
    this._cbs = null;
    this.onEnterFrame = null;
    this.onLoopComplete = null;
    this.onComplete = null;
    this.onSegmentStart = null;
    this.onDestroy = null;
    this.renderer = null;
    this.renderer = null;
    this.imagePreloader = null;
    this.projectInterface = null;
  };
  AnimationItem.prototype.setCurrentRawFrameValue = function(value2) {
    this.currentRawFrame = value2;
    this.gotoFrame();
  };
  AnimationItem.prototype.setSpeed = function(val2) {
    this.playSpeed = val2;
    this.updaFrameModifier();
  };
  AnimationItem.prototype.setDirection = function(val2) {
    this.playDirection = val2 < 0 ? -1 : 1;
    this.updaFrameModifier();
  };
  AnimationItem.prototype.setVolume = function(val2, name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    this.audioController.setVolume(val2);
  };
  AnimationItem.prototype.getVolume = function() {
    return this.audioController.getVolume();
  };
  AnimationItem.prototype.mute = function(name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    this.audioController.mute();
  };
  AnimationItem.prototype.unmute = function(name2) {
    if (name2 && this.name !== name2) {
      return;
    }
    this.audioController.unmute();
  };
  AnimationItem.prototype.updaFrameModifier = function() {
    this.frameModifier = this.frameMult * this.playSpeed * this.playDirection;
    this.audioController.setRate(this.playSpeed * this.playDirection);
  };
  AnimationItem.prototype.getPath = function() {
    return this.path;
  };
  AnimationItem.prototype.getAssetsPath = function(assetData) {
    var path = "";
    if (assetData.e) {
      path = assetData.p;
    } else if (this.assetsPath) {
      var imagePath = assetData.p;
      if (imagePath.indexOf("images/") !== -1) {
        imagePath = imagePath.split("/")[1];
      }
      path = this.assetsPath + imagePath;
    } else {
      path = this.path;
      path += assetData.u ? assetData.u : "";
      path += assetData.p;
    }
    return path;
  };
  AnimationItem.prototype.getAssetData = function(id) {
    var i = 0;
    var len = this.assets.length;
    while (i < len) {
      if (id === this.assets[i].id) {
        return this.assets[i];
      }
      i += 1;
    }
    return null;
  };
  AnimationItem.prototype.hide = function() {
    this.renderer.hide();
  };
  AnimationItem.prototype.show = function() {
    this.renderer.show();
  };
  AnimationItem.prototype.getDuration = function(isFrame) {
    return isFrame ? this.totalFrames : this.totalFrames / this.frameRate;
  };
  AnimationItem.prototype.updateDocumentData = function(path, documentData, index2) {
    try {
      var element = this.renderer.getElementByPath(path);
      element.updateDocumentData(documentData, index2);
    } catch (error) {
    }
  };
  AnimationItem.prototype.trigger = function(name2) {
    if (this._cbs && this._cbs[name2]) {
      switch (name2) {
        case "enterFrame":
          this.triggerEvent(name2, new BMEnterFrameEvent(name2, this.currentFrame, this.totalFrames, this.frameModifier));
          break;
        case "drawnFrame":
          this.drawnFrameEvent.currentTime = this.currentFrame;
          this.drawnFrameEvent.totalTime = this.totalFrames;
          this.drawnFrameEvent.direction = this.frameModifier;
          this.triggerEvent(name2, this.drawnFrameEvent);
          break;
        case "loopComplete":
          this.triggerEvent(name2, new BMCompleteLoopEvent(name2, this.loop, this.playCount, this.frameMult));
          break;
        case "complete":
          this.triggerEvent(name2, new BMCompleteEvent(name2, this.frameMult));
          break;
        case "segmentStart":
          this.triggerEvent(name2, new BMSegmentStartEvent(name2, this.firstFrame, this.totalFrames));
          break;
        case "destroy":
          this.triggerEvent(name2, new BMDestroyEvent(name2, this));
          break;
        default:
          this.triggerEvent(name2);
      }
    }
    if (name2 === "enterFrame" && this.onEnterFrame) {
      this.onEnterFrame.call(this, new BMEnterFrameEvent(name2, this.currentFrame, this.totalFrames, this.frameMult));
    }
    if (name2 === "loopComplete" && this.onLoopComplete) {
      this.onLoopComplete.call(this, new BMCompleteLoopEvent(name2, this.loop, this.playCount, this.frameMult));
    }
    if (name2 === "complete" && this.onComplete) {
      this.onComplete.call(this, new BMCompleteEvent(name2, this.frameMult));
    }
    if (name2 === "segmentStart" && this.onSegmentStart) {
      this.onSegmentStart.call(this, new BMSegmentStartEvent(name2, this.firstFrame, this.totalFrames));
    }
    if (name2 === "destroy" && this.onDestroy) {
      this.onDestroy.call(this, new BMDestroyEvent(name2, this));
    }
  };
  AnimationItem.prototype.triggerRenderFrameError = function(nativeError) {
    var error = new BMRenderFrameErrorEvent(nativeError, this.currentFrame);
    this.triggerEvent("error", error);
    if (this.onError) {
      this.onError.call(this, error);
    }
  };
  AnimationItem.prototype.triggerConfigError = function(nativeError) {
    var error = new BMConfigErrorEvent(nativeError, this.currentFrame);
    this.triggerEvent("error", error);
    if (this.onError) {
      this.onError.call(this, error);
    }
  };
  const animationManager = function() {
    var moduleOb = {};
    var registeredAnimations = [];
    var initTime = 0;
    var len = 0;
    var playingAnimationsNum = 0;
    var _stopped = true;
    var _isFrozen = false;
    function removeElement(ev) {
      var i = 0;
      var animItem = ev.target;
      while (i < len) {
        if (registeredAnimations[i].animation === animItem) {
          registeredAnimations.splice(i, 1);
          i -= 1;
          len -= 1;
          if (!animItem.isPaused) {
            subtractPlayingCount();
          }
        }
        i += 1;
      }
    }
    function registerAnimation(element, animationData2) {
      if (!element) {
        return null;
      }
      var i = 0;
      while (i < len) {
        if (registeredAnimations[i].elem === element && registeredAnimations[i].elem !== null) {
          return registeredAnimations[i].animation;
        }
        i += 1;
      }
      var animItem = new AnimationItem();
      setupAnimation(animItem, element);
      animItem.setData(element, animationData2);
      return animItem;
    }
    function getRegisteredAnimations() {
      var i;
      var lenAnims = registeredAnimations.length;
      var animations = [];
      for (i = 0; i < lenAnims; i += 1) {
        animations.push(registeredAnimations[i].animation);
      }
      return animations;
    }
    function addPlayingCount() {
      playingAnimationsNum += 1;
      activate();
    }
    function subtractPlayingCount() {
      playingAnimationsNum -= 1;
    }
    function setupAnimation(animItem, element) {
      animItem.addEventListener("destroy", removeElement);
      animItem.addEventListener("_active", addPlayingCount);
      animItem.addEventListener("_idle", subtractPlayingCount);
      registeredAnimations.push({ elem: element, animation: animItem });
      len += 1;
    }
    function loadAnimation2(params) {
      var animItem = new AnimationItem();
      setupAnimation(animItem, null);
      animItem.setParams(params);
      return animItem;
    }
    function setSpeed(val2, animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.setSpeed(val2, animation);
      }
    }
    function setDirection(val2, animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.setDirection(val2, animation);
      }
    }
    function play(animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.play(animation);
      }
    }
    function resume(nowTime) {
      var elapsedTime = nowTime - initTime;
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.advanceTime(elapsedTime);
      }
      initTime = nowTime;
      if (playingAnimationsNum && !_isFrozen) {
        window.requestAnimationFrame(resume);
      } else {
        _stopped = true;
      }
    }
    function first2(nowTime) {
      initTime = nowTime;
      window.requestAnimationFrame(resume);
    }
    function pause(animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.pause(animation);
      }
    }
    function goToAndStop(value2, isFrame, animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.goToAndStop(value2, isFrame, animation);
      }
    }
    function stop(animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.stop(animation);
      }
    }
    function togglePause(animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.togglePause(animation);
      }
    }
    function destroy(animation) {
      var i;
      for (i = len - 1; i >= 0; i -= 1) {
        registeredAnimations[i].animation.destroy(animation);
      }
    }
    function searchAnimations2(animationData2, standalone2, renderer2) {
      var animElements = [].concat(
        [].slice.call(document.getElementsByClassName("lottie")),
        [].slice.call(document.getElementsByClassName("bodymovin"))
      );
      var i;
      var lenAnims = animElements.length;
      for (i = 0; i < lenAnims; i += 1) {
        if (renderer2) {
          animElements[i].setAttribute("data-bm-type", renderer2);
        }
        registerAnimation(animElements[i], animationData2);
      }
      if (standalone2 && lenAnims === 0) {
        if (!renderer2) {
          renderer2 = "svg";
        }
        var body = document.getElementsByTagName("body")[0];
        body.innerText = "";
        var div2 = createTag("div");
        div2.style.width = "100%";
        div2.style.height = "100%";
        div2.setAttribute("data-bm-type", renderer2);
        body.appendChild(div2);
        registerAnimation(div2, animationData2);
      }
    }
    function resize() {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.resize();
      }
    }
    function activate() {
      if (!_isFrozen && playingAnimationsNum) {
        if (_stopped) {
          window.requestAnimationFrame(first2);
          _stopped = false;
        }
      }
    }
    function freeze() {
      _isFrozen = true;
    }
    function unfreeze() {
      _isFrozen = false;
      activate();
    }
    function setVolume(val2, animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.setVolume(val2, animation);
      }
    }
    function mute(animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.mute(animation);
      }
    }
    function unmute(animation) {
      var i;
      for (i = 0; i < len; i += 1) {
        registeredAnimations[i].animation.unmute(animation);
      }
    }
    moduleOb.registerAnimation = registerAnimation;
    moduleOb.loadAnimation = loadAnimation2;
    moduleOb.setSpeed = setSpeed;
    moduleOb.setDirection = setDirection;
    moduleOb.play = play;
    moduleOb.pause = pause;
    moduleOb.stop = stop;
    moduleOb.togglePause = togglePause;
    moduleOb.searchAnimations = searchAnimations2;
    moduleOb.resize = resize;
    moduleOb.goToAndStop = goToAndStop;
    moduleOb.destroy = destroy;
    moduleOb.freeze = freeze;
    moduleOb.unfreeze = unfreeze;
    moduleOb.setVolume = setVolume;
    moduleOb.mute = mute;
    moduleOb.unmute = unmute;
    moduleOb.getRegisteredAnimations = getRegisteredAnimations;
    return moduleOb;
  }();
  const BezierFactory = function() {
    var ob2 = {};
    ob2.getBezierEasing = getBezierEasing;
    var beziers = {};
    function getBezierEasing(a2, b3, c2, d, nm) {
      var str = nm || ("bez_" + a2 + "_" + b3 + "_" + c2 + "_" + d).replace(/\./g, "p");
      if (beziers[str]) {
        return beziers[str];
      }
      var bezEasing = new BezierEasing([a2, b3, c2, d]);
      beziers[str] = bezEasing;
      return bezEasing;
    }
    var NEWTON_ITERATIONS = 4;
    var NEWTON_MIN_SLOPE = 1e-3;
    var SUBDIVISION_PRECISION = 1e-7;
    var SUBDIVISION_MAX_ITERATIONS = 10;
    var kSplineTableSize = 11;
    var kSampleStepSize = 1 / (kSplineTableSize - 1);
    var float32ArraySupported = typeof Float32Array === "function";
    function A2(aA1, aA2) {
      return 1 - 3 * aA2 + 3 * aA1;
    }
    function B2(aA1, aA2) {
      return 3 * aA2 - 6 * aA1;
    }
    function C3(aA1) {
      return 3 * aA1;
    }
    function calcBezier(aT, aA1, aA2) {
      return ((A2(aA1, aA2) * aT + B2(aA1, aA2)) * aT + C3(aA1)) * aT;
    }
    function getSlope(aT, aA1, aA2) {
      return 3 * A2(aA1, aA2) * aT * aT + 2 * B2(aA1, aA2) * aT + C3(aA1);
    }
    function binarySubdivide(aX, aA, aB, mX1, mX2) {
      var currentX, currentT, i = 0;
      do {
        currentT = aA + (aB - aA) / 2;
        currentX = calcBezier(currentT, mX1, mX2) - aX;
        if (currentX > 0) {
          aB = currentT;
        } else {
          aA = currentT;
        }
      } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
      return currentT;
    }
    function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
      for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
        var currentSlope = getSlope(aGuessT, mX1, mX2);
        if (currentSlope === 0) return aGuessT;
        var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
        aGuessT -= currentX / currentSlope;
      }
      return aGuessT;
    }
    function BezierEasing(points) {
      this._p = points;
      this._mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
      this._precomputed = false;
      this.get = this.get.bind(this);
    }
    BezierEasing.prototype = {
      get: function(x2) {
        var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3];
        if (!this._precomputed) this._precompute();
        if (mX1 === mY1 && mX2 === mY2) return x2;
        if (x2 === 0) return 0;
        if (x2 === 1) return 1;
        return calcBezier(this._getTForX(x2), mY1, mY2);
      },
      // Private part
      _precompute: function() {
        var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3];
        this._precomputed = true;
        if (mX1 !== mY1 || mX2 !== mY2) {
          this._calcSampleValues();
        }
      },
      _calcSampleValues: function() {
        var mX1 = this._p[0], mX2 = this._p[2];
        for (var i = 0; i < kSplineTableSize; ++i) {
          this._mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
        }
      },
      /**
           * getTForX chose the fastest heuristic to determine the percentage value precisely from a given X projection.
           */
      _getTForX: function(aX) {
        var mX1 = this._p[0], mX2 = this._p[2], mSampleValues = this._mSampleValues;
        var intervalStart = 0;
        var currentSample = 1;
        var lastSample = kSplineTableSize - 1;
        for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
          intervalStart += kSampleStepSize;
        }
        --currentSample;
        var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]);
        var guessForT = intervalStart + dist * kSampleStepSize;
        var initialSlope = getSlope(guessForT, mX1, mX2);
        if (initialSlope >= NEWTON_MIN_SLOPE) {
          return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
        }
        if (initialSlope === 0) {
          return guessForT;
        }
        return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
      }
    };
    return ob2;
  }();
  const pooling = /* @__PURE__ */ function() {
    function double(arr) {
      return arr.concat(createSizedArray(arr.length));
    }
    return {
      double
    };
  }();
  const poolFactory = /* @__PURE__ */ function() {
    return function(initialLength, _create, _release) {
      var _length = 0;
      var _maxLength = initialLength;
      var pool = createSizedArray(_maxLength);
      var ob2 = {
        newElement,
        release
      };
      function newElement() {
        var element;
        if (_length) {
          _length -= 1;
          element = pool[_length];
        } else {
          element = _create();
        }
        return element;
      }
      function release(element) {
        if (_length === _maxLength) {
          pool = pooling.double(pool);
          _maxLength *= 2;
        }
        if (_release) {
          _release(element);
        }
        pool[_length] = element;
        _length += 1;
      }
      return ob2;
    };
  }();
  const bezierLengthPool = function() {
    function create() {
      return {
        addedLength: 0,
        percents: createTypedArray("float32", getDefaultCurveSegments()),
        lengths: createTypedArray("float32", getDefaultCurveSegments())
      };
    }
    return poolFactory(8, create);
  }();
  const segmentsLengthPool = function() {
    function create() {
      return {
        lengths: [],
        totalLength: 0
      };
    }
    function release(element) {
      var i;
      var len = element.lengths.length;
      for (i = 0; i < len; i += 1) {
        bezierLengthPool.release(element.lengths[i]);
      }
      element.lengths.length = 0;
    }
    return poolFactory(8, create, release);
  }();
  const bez = bezFunction();
  const PropertyFactory = /* @__PURE__ */ function() {
    var initFrame = initialDefaultFrame;
    var mathAbs = Math.abs;
    function interpolateValue(frameNum, caching) {
      var offsetTime = this.offsetTime;
      var newValue;
      if (this.propType === "multidimensional") {
        newValue = createTypedArray("float32", this.pv.length);
      }
      var iterationIndex = caching.lastIndex;
      var i = iterationIndex;
      var len = this.keyframes.length - 1;
      var flag = true;
      var keyData;
      var nextKeyData;
      var keyframeMetadata;
      while (flag) {
        keyData = this.keyframes[i];
        nextKeyData = this.keyframes[i + 1];
        if (i === len - 1 && frameNum >= nextKeyData.t - offsetTime) {
          if (keyData.h) {
            keyData = nextKeyData;
          }
          iterationIndex = 0;
          break;
        }
        if (nextKeyData.t - offsetTime > frameNum) {
          iterationIndex = i;
          break;
        }
        if (i < len - 1) {
          i += 1;
        } else {
          iterationIndex = 0;
          flag = false;
        }
      }
      keyframeMetadata = this.keyframesMetadata[i] || {};
      var k2;
      var kLen;
      var perc;
      var jLen;
      var j2;
      var fnc;
      var nextKeyTime = nextKeyData.t - offsetTime;
      var keyTime = keyData.t - offsetTime;
      var endValue;
      if (keyData.to) {
        if (!keyframeMetadata.bezierData) {
          keyframeMetadata.bezierData = bez.buildBezierData(keyData.s, nextKeyData.s || keyData.e, keyData.to, keyData.ti);
        }
        var bezierData = keyframeMetadata.bezierData;
        if (frameNum >= nextKeyTime || frameNum < keyTime) {
          var ind = frameNum >= nextKeyTime ? bezierData.points.length - 1 : 0;
          kLen = bezierData.points[ind].point.length;
          for (k2 = 0; k2 < kLen; k2 += 1) {
            newValue[k2] = bezierData.points[ind].point[k2];
          }
        } else {
          if (keyframeMetadata.__fnct) {
            fnc = keyframeMetadata.__fnct;
          } else {
            fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y, keyData.n).get;
            keyframeMetadata.__fnct = fnc;
          }
          perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime));
          var distanceInLine = bezierData.segmentLength * perc;
          var segmentPerc;
          var addedLength = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? caching._lastAddedLength : 0;
          j2 = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? caching._lastPoint : 0;
          flag = true;
          jLen = bezierData.points.length;
          while (flag) {
            addedLength += bezierData.points[j2].partialLength;
            if (distanceInLine === 0 || perc === 0 || j2 === bezierData.points.length - 1) {
              kLen = bezierData.points[j2].point.length;
              for (k2 = 0; k2 < kLen; k2 += 1) {
                newValue[k2] = bezierData.points[j2].point[k2];
              }
              break;
            } else if (distanceInLine >= addedLength && distanceInLine < addedLength + bezierData.points[j2 + 1].partialLength) {
              segmentPerc = (distanceInLine - addedLength) / bezierData.points[j2 + 1].partialLength;
              kLen = bezierData.points[j2].point.length;
              for (k2 = 0; k2 < kLen; k2 += 1) {
                newValue[k2] = bezierData.points[j2].point[k2] + (bezierData.points[j2 + 1].point[k2] - bezierData.points[j2].point[k2]) * segmentPerc;
              }
              break;
            }
            if (j2 < jLen - 1) {
              j2 += 1;
            } else {
              flag = false;
            }
          }
          caching._lastPoint = j2;
          caching._lastAddedLength = addedLength - bezierData.points[j2].partialLength;
          caching._lastKeyframeIndex = i;
        }
      } else {
        var outX;
        var outY;
        var inX;
        var inY;
        var keyValue;
        len = keyData.s.length;
        endValue = nextKeyData.s || keyData.e;
        if (this.sh && keyData.h !== 1) {
          if (frameNum >= nextKeyTime) {
            newValue[0] = endValue[0];
            newValue[1] = endValue[1];
            newValue[2] = endValue[2];
          } else if (frameNum <= keyTime) {
            newValue[0] = keyData.s[0];
            newValue[1] = keyData.s[1];
            newValue[2] = keyData.s[2];
          } else {
            var quatStart = createQuaternion(keyData.s);
            var quatEnd = createQuaternion(endValue);
            var time2 = (frameNum - keyTime) / (nextKeyTime - keyTime);
            quaternionToEuler(newValue, slerp(quatStart, quatEnd, time2));
          }
        } else {
          for (i = 0; i < len; i += 1) {
            if (keyData.h !== 1) {
              if (frameNum >= nextKeyTime) {
                perc = 1;
              } else if (frameNum < keyTime) {
                perc = 0;
              } else {
                if (keyData.o.x.constructor === Array) {
                  if (!keyframeMetadata.__fnct) {
                    keyframeMetadata.__fnct = [];
                  }
                  if (!keyframeMetadata.__fnct[i]) {
                    outX = keyData.o.x[i] === void 0 ? keyData.o.x[0] : keyData.o.x[i];
                    outY = keyData.o.y[i] === void 0 ? keyData.o.y[0] : keyData.o.y[i];
                    inX = keyData.i.x[i] === void 0 ? keyData.i.x[0] : keyData.i.x[i];
                    inY = keyData.i.y[i] === void 0 ? keyData.i.y[0] : keyData.i.y[i];
                    fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get;
                    keyframeMetadata.__fnct[i] = fnc;
                  } else {
                    fnc = keyframeMetadata.__fnct[i];
                  }
                } else if (!keyframeMetadata.__fnct) {
                  outX = keyData.o.x;
                  outY = keyData.o.y;
                  inX = keyData.i.x;
                  inY = keyData.i.y;
                  fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get;
                  keyData.keyframeMetadata = fnc;
                } else {
                  fnc = keyframeMetadata.__fnct;
                }
                perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime));
              }
            }
            endValue = nextKeyData.s || keyData.e;
            keyValue = keyData.h === 1 ? keyData.s[i] : keyData.s[i] + (endValue[i] - keyData.s[i]) * perc;
            if (this.propType === "multidimensional") {
              newValue[i] = keyValue;
            } else {
              newValue = keyValue;
            }
          }
        }
      }
      caching.lastIndex = iterationIndex;
      return newValue;
    }
    function slerp(a2, b3, t3) {
      var out = [];
      var ax = a2[0];
      var ay = a2[1];
      var az = a2[2];
      var aw = a2[3];
      var bx = b3[0];
      var by = b3[1];
      var bz = b3[2];
      var bw = b3[3];
      var omega;
      var cosom;
      var sinom;
      var scale0;
      var scale1;
      cosom = ax * bx + ay * by + az * bz + aw * bw;
      if (cosom < 0) {
        cosom = -cosom;
        bx = -bx;
        by = -by;
        bz = -bz;
        bw = -bw;
      }
      if (1 - cosom > 1e-6) {
        omega = Math.acos(cosom);
        sinom = Math.sin(omega);
        scale0 = Math.sin((1 - t3) * omega) / sinom;
        scale1 = Math.sin(t3 * omega) / sinom;
      } else {
        scale0 = 1 - t3;
        scale1 = t3;
      }
      out[0] = scale0 * ax + scale1 * bx;
      out[1] = scale0 * ay + scale1 * by;
      out[2] = scale0 * az + scale1 * bz;
      out[3] = scale0 * aw + scale1 * bw;
      return out;
    }
    function quaternionToEuler(out, quat) {
      var qx = quat[0];
      var qy = quat[1];
      var qz = quat[2];
      var qw = quat[3];
      var heading = Math.atan2(2 * qy * qw - 2 * qx * qz, 1 - 2 * qy * qy - 2 * qz * qz);
      var attitude = Math.asin(2 * qx * qy + 2 * qz * qw);
      var bank = Math.atan2(2 * qx * qw - 2 * qy * qz, 1 - 2 * qx * qx - 2 * qz * qz);
      out[0] = heading / degToRads;
      out[1] = attitude / degToRads;
      out[2] = bank / degToRads;
    }
    function createQuaternion(values2) {
      var heading = values2[0] * degToRads;
      var attitude = values2[1] * degToRads;
      var bank = values2[2] * degToRads;
      var c1 = Math.cos(heading / 2);
      var c2 = Math.cos(attitude / 2);
      var c3 = Math.cos(bank / 2);
      var s1 = Math.sin(heading / 2);
      var s2 = Math.sin(attitude / 2);
      var s3 = Math.sin(bank / 2);
      var w = c1 * c2 * c3 - s1 * s2 * s3;
      var x2 = s1 * s2 * c3 + c1 * c2 * s3;
      var y = s1 * c2 * c3 + c1 * s2 * s3;
      var z = c1 * s2 * c3 - s1 * c2 * s3;
      return [x2, y, z, w];
    }
    function getValueAtCurrentTime() {
      var frameNum = this.comp.renderedFrame - this.offsetTime;
      var initTime = this.keyframes[0].t - this.offsetTime;
      var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime;
      if (!(frameNum === this._caching.lastFrame || this._caching.lastFrame !== initFrame && (this._caching.lastFrame >= endTime && frameNum >= endTime || this._caching.lastFrame < initTime && frameNum < initTime))) {
        if (this._caching.lastFrame >= frameNum) {
          this._caching._lastKeyframeIndex = -1;
          this._caching.lastIndex = 0;
        }
        var renderResult = this.interpolateValue(frameNum, this._caching);
        this.pv = renderResult;
      }
      this._caching.lastFrame = frameNum;
      return this.pv;
    }
    function setVValue(val2) {
      var multipliedValue;
      if (this.propType === "unidimensional") {
        multipliedValue = val2 * this.mult;
        if (mathAbs(this.v - multipliedValue) > 1e-5) {
          this.v = multipliedValue;
          this._mdf = true;
        }
      } else {
        var i = 0;
        var len = this.v.length;
        while (i < len) {
          multipliedValue = val2[i] * this.mult;
          if (mathAbs(this.v[i] - multipliedValue) > 1e-5) {
            this.v[i] = multipliedValue;
            this._mdf = true;
          }
          i += 1;
        }
      }
    }
    function processEffectsSequence() {
      if (this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) {
        return;
      }
      if (this.lock) {
        this.setVValue(this.pv);
        return;
      }
      this.lock = true;
      this._mdf = this._isFirstFrame;
      var i;
      var len = this.effectsSequence.length;
      var finalValue = this.kf ? this.pv : this.data.k;
      for (i = 0; i < len; i += 1) {
        finalValue = this.effectsSequence[i](finalValue);
      }
      this.setVValue(finalValue);
      this._isFirstFrame = false;
      this.lock = false;
      this.frameId = this.elem.globalData.frameId;
    }
    function addEffect(effectFunction) {
      this.effectsSequence.push(effectFunction);
      this.container.addDynamicProperty(this);
    }
    function ValueProperty(elem2, data2, mult, container) {
      this.propType = "unidimensional";
      this.mult = mult || 1;
      this.data = data2;
      this.v = mult ? data2.k * mult : data2.k;
      this.pv = data2.k;
      this._mdf = false;
      this.elem = elem2;
      this.container = container;
      this.comp = elem2.comp;
      this.k = false;
      this.kf = false;
      this.vel = 0;
      this.effectsSequence = [];
      this._isFirstFrame = true;
      this.getValue = processEffectsSequence;
      this.setVValue = setVValue;
      this.addEffect = addEffect;
    }
    function MultiDimensionalProperty(elem2, data2, mult, container) {
      this.propType = "multidimensional";
      this.mult = mult || 1;
      this.data = data2;
      this._mdf = false;
      this.elem = elem2;
      this.container = container;
      this.comp = elem2.comp;
      this.k = false;
      this.kf = false;
      this.frameId = -1;
      var i;
      var len = data2.k.length;
      this.v = createTypedArray("float32", len);
      this.pv = createTypedArray("float32", len);
      this.vel = createTypedArray("float32", len);
      for (i = 0; i < len; i += 1) {
        this.v[i] = data2.k[i] * this.mult;
        this.pv[i] = data2.k[i];
      }
      this._isFirstFrame = true;
      this.effectsSequence = [];
      this.getValue = processEffectsSequence;
      this.setVValue = setVValue;
      this.addEffect = addEffect;
    }
    function KeyframedValueProperty(elem2, data2, mult, container) {
      this.propType = "unidimensional";
      this.keyframes = data2.k;
      this.keyframesMetadata = [];
      this.offsetTime = elem2.data.st;
      this.frameId = -1;
      this._caching = {
        lastFrame: initFrame,
        lastIndex: 0,
        value: 0,
        _lastKeyframeIndex: -1
      };
      this.k = true;
      this.kf = true;
      this.data = data2;
      this.mult = mult || 1;
      this.elem = elem2;
      this.container = container;
      this.comp = elem2.comp;
      this.v = initFrame;
      this.pv = initFrame;
      this._isFirstFrame = true;
      this.getValue = processEffectsSequence;
      this.setVValue = setVValue;
      this.interpolateValue = interpolateValue;
      this.effectsSequence = [getValueAtCurrentTime.bind(this)];
      this.addEffect = addEffect;
    }
    function KeyframedMultidimensionalProperty(elem2, data2, mult, container) {
      this.propType = "multidimensional";
      var i;
      var len = data2.k.length;
      var s;
      var e;
      var to;
      var ti;
      for (i = 0; i < len - 1; i += 1) {
        if (data2.k[i].to && data2.k[i].s && data2.k[i + 1] && data2.k[i + 1].s) {
          s = data2.k[i].s;
          e = data2.k[i + 1].s;
          to = data2.k[i].to;
          ti = data2.k[i].ti;
          if (s.length === 2 && !(s[0] === e[0] && s[1] === e[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], s[0] + to[0], s[1] + to[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], e[0] + ti[0], e[1] + ti[1]) || s.length === 3 && !(s[0] === e[0] && s[1] === e[1] && s[2] === e[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], s[0] + to[0], s[1] + to[1], s[2] + to[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], e[0] + ti[0], e[1] + ti[1], e[2] + ti[2])) {
            data2.k[i].to = null;
            data2.k[i].ti = null;
          }
          if (s[0] === e[0] && s[1] === e[1] && to[0] === 0 && to[1] === 0 && ti[0] === 0 && ti[1] === 0) {
            if (s.length === 2 || s[2] === e[2] && to[2] === 0 && ti[2] === 0) {
              data2.k[i].to = null;
              data2.k[i].ti = null;
            }
          }
        }
      }
      this.effectsSequence = [getValueAtCurrentTime.bind(this)];
      this.data = data2;
      this.keyframes = data2.k;
      this.keyframesMetadata = [];
      this.offsetTime = elem2.data.st;
      this.k = true;
      this.kf = true;
      this._isFirstFrame = true;
      this.mult = mult || 1;
      this.elem = elem2;
      this.container = container;
      this.comp = elem2.comp;
      this.getValue = processEffectsSequence;
      this.setVValue = setVValue;
      this.interpolateValue = interpolateValue;
      this.frameId = -1;
      var arrLen = data2.k[0].s.length;
      this.v = createTypedArray("float32", arrLen);
      this.pv = createTypedArray("float32", arrLen);
      for (i = 0; i < arrLen; i += 1) {
        this.v[i] = initFrame;
        this.pv[i] = initFrame;
      }
      this._caching = { lastFrame: initFrame, lastIndex: 0, value: createTypedArray("float32", arrLen) };
      this.addEffect = addEffect;
    }
    function getProp(elem2, data2, type, mult, container) {
      var p;
      if (!data2.k.length) {
        p = new ValueProperty(elem2, data2, mult, container);
      } else if (typeof data2.k[0] === "number") {
        p = new MultiDimensionalProperty(elem2, data2, mult, container);
      } else {
        switch (type) {
          case 0:
            p = new KeyframedValueProperty(elem2, data2, mult, container);
            break;
          case 1:
            p = new KeyframedMultidimensionalProperty(elem2, data2, mult, container);
            break;
          default:
            break;
        }
      }
      if (p.effectsSequence.length) {
        container.addDynamicProperty(p);
      }
      return p;
    }
    var ob2 = {
      getProp
    };
    return ob2;
  }();
  DynamicPropertyContainer.prototype = {
    addDynamicProperty: function(prop) {
      if (this.dynamicProperties.indexOf(prop) === -1) {
        this.dynamicProperties.push(prop);
        this.container.addDynamicProperty(this);
        this._isAnimated = true;
      }
    },
    iterateDynamicProperties: function() {
      this._mdf = false;
      var i;
      var len = this.dynamicProperties.length;
      for (i = 0; i < len; i += 1) {
        this.dynamicProperties[i].getValue();
        if (this.dynamicProperties[i]._mdf) {
          this._mdf = true;
        }
      }
    },
    initDynamicPropertyContainer: function(container) {
      this.container = container;
      this.dynamicProperties = [];
      this._mdf = false;
      this._isAnimated = false;
    }
  };
  const pointPool = function() {
    function create() {
      return createTypedArray("float32", 2);
    }
    return poolFactory(8, create);
  }();
  ShapePath.prototype.setPathData = function(closed, len) {
    this.c = closed;
    this.setLength(len);
    var i = 0;
    while (i < len) {
      this.v[i] = pointPool.newElement();
      this.o[i] = pointPool.newElement();
      this.i[i] = pointPool.newElement();
      i += 1;
    }
  };
  ShapePath.prototype.setLength = function(len) {
    while (this._maxLength < len) {
      this.doubleArrayLength();
    }
    this._length = len;
  };
  ShapePath.prototype.doubleArrayLength = function() {
    this.v = this.v.concat(createSizedArray(this._maxLength));
    this.i = this.i.concat(createSizedArray(this._maxLength));
    this.o = this.o.concat(createSizedArray(this._maxLength));
    this._maxLength *= 2;
  };
  ShapePath.prototype.setXYAt = function(x2, y, type, pos, replace) {
    var arr;
    this._length = Math.max(this._length, pos + 1);
    if (this._length >= this._maxLength) {
      this.doubleArrayLength();
    }
    switch (type) {
      case "v":
        arr = this.v;
        break;
      case "i":
        arr = this.i;
        break;
      case "o":
        arr = this.o;
        break;
      default:
        arr = [];
        break;
    }
    if (!arr[pos] || arr[pos] && !replace) {
      arr[pos] = pointPool.newElement();
    }
    arr[pos][0] = x2;
    arr[pos][1] = y;
  };
  ShapePath.prototype.setTripleAt = function(vX, vY, oX, oY, iX, iY, pos, replace) {
    this.setXYAt(vX, vY, "v", pos, replace);
    this.setXYAt(oX, oY, "o", pos, replace);
    this.setXYAt(iX, iY, "i", pos, replace);
  };
  ShapePath.prototype.reverse = function() {
    var newPath = new ShapePath();
    newPath.setPathData(this.c, this._length);
    var vertices = this.v;
    var outPoints = this.o;
    var inPoints = this.i;
    var init = 0;
    if (this.c) {
      newPath.setTripleAt(vertices[0][0], vertices[0][1], inPoints[0][0], inPoints[0][1], outPoints[0][0], outPoints[0][1], 0, false);
      init = 1;
    }
    var cnt = this._length - 1;
    var len = this._length;
    var i;
    for (i = init; i < len; i += 1) {
      newPath.setTripleAt(vertices[cnt][0], vertices[cnt][1], inPoints[cnt][0], inPoints[cnt][1], outPoints[cnt][0], outPoints[cnt][1], i, false);
      cnt -= 1;
    }
    return newPath;
  };
  const shapePool = function() {
    function create() {
      return new ShapePath();
    }
    function release(shapePath) {
      var len = shapePath._length;
      var i;
      for (i = 0; i < len; i += 1) {
        pointPool.release(shapePath.v[i]);
        pointPool.release(shapePath.i[i]);
        pointPool.release(shapePath.o[i]);
        shapePath.v[i] = null;
        shapePath.i[i] = null;
        shapePath.o[i] = null;
      }
      shapePath._length = 0;
      shapePath.c = false;
    }
    function clone2(shape) {
      var cloned = factory.newElement();
      var i;
      var len = shape._length === void 0 ? shape.v.length : shape._length;
      cloned.setLength(len);
      cloned.c = shape.c;
      for (i = 0; i < len; i += 1) {
        cloned.setTripleAt(shape.v[i][0], shape.v[i][1], shape.o[i][0], shape.o[i][1], shape.i[i][0], shape.i[i][1], i);
      }
      return cloned;
    }
    var factory = poolFactory(4, create, release);
    factory.clone = clone2;
    return factory;
  }();
  ShapeCollection.prototype.addShape = function(shapeData) {
    if (this._length === this._maxLength) {
      this.shapes = this.shapes.concat(createSizedArray(this._maxLength));
      this._maxLength *= 2;
    }
    this.shapes[this._length] = shapeData;
    this._length += 1;
  };
  ShapeCollection.prototype.releaseShapes = function() {
    var i;
    for (i = 0; i < this._length; i += 1) {
      shapePool.release(this.shapes[i]);
    }
    this._length = 0;
  };
  const shapeCollectionPool = function() {
    var ob2 = {
      newShapeCollection,
      release
    };
    var _length = 0;
    var _maxLength = 4;
    var pool = createSizedArray(_maxLength);
    function newShapeCollection() {
      var shapeCollection;
      if (_length) {
        _length -= 1;
        shapeCollection = pool[_length];
      } else {
        shapeCollection = new ShapeCollection();
      }
      return shapeCollection;
    }
    function release(shapeCollection) {
      var i;
      var len = shapeCollection._length;
      for (i = 0; i < len; i += 1) {
        shapePool.release(shapeCollection.shapes[i]);
      }
      shapeCollection._length = 0;
      if (_length === _maxLength) {
        pool = pooling.double(pool);
        _maxLength *= 2;
      }
      pool[_length] = shapeCollection;
      _length += 1;
    }
    return ob2;
  }();
  const ShapePropertyFactory = function() {
    var initFrame = -999999;
    function interpolateShape(frameNum, previousValue, caching) {
      var iterationIndex = caching.lastIndex;
      var keyPropS;
      var keyPropE;
      var isHold;
      var j2;
      var k2;
      var jLen;
      var kLen;
      var perc;
      var vertexValue;
      var kf = this.keyframes;
      if (frameNum < kf[0].t - this.offsetTime) {
        keyPropS = kf[0].s[0];
        isHold = true;
        iterationIndex = 0;
      } else if (frameNum >= kf[kf.length - 1].t - this.offsetTime) {
        keyPropS = kf[kf.length - 1].s ? kf[kf.length - 1].s[0] : kf[kf.length - 2].e[0];
        isHold = true;
      } else {
        var i = iterationIndex;
        var len = kf.length - 1;
        var flag = true;
        var keyData;
        var nextKeyData;
        var keyframeMetadata;
        while (flag) {
          keyData = kf[i];
          nextKeyData = kf[i + 1];
          if (nextKeyData.t - this.offsetTime > frameNum) {
            break;
          }
          if (i < len - 1) {
            i += 1;
          } else {
            flag = false;
          }
        }
        keyframeMetadata = this.keyframesMetadata[i] || {};
        isHold = keyData.h === 1;
        iterationIndex = i;
        if (!isHold) {
          if (frameNum >= nextKeyData.t - this.offsetTime) {
            perc = 1;
          } else if (frameNum < keyData.t - this.offsetTime) {
            perc = 0;
          } else {
            var fnc;
            if (keyframeMetadata.__fnct) {
              fnc = keyframeMetadata.__fnct;
            } else {
              fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y).get;
              keyframeMetadata.__fnct = fnc;
            }
            perc = fnc((frameNum - (keyData.t - this.offsetTime)) / (nextKeyData.t - this.offsetTime - (keyData.t - this.offsetTime)));
          }
          keyPropE = nextKeyData.s ? nextKeyData.s[0] : keyData.e[0];
        }
        keyPropS = keyData.s[0];
      }
      jLen = previousValue._length;
      kLen = keyPropS.i[0].length;
      caching.lastIndex = iterationIndex;
      for (j2 = 0; j2 < jLen; j2 += 1) {
        for (k2 = 0; k2 < kLen; k2 += 1) {
          vertexValue = isHold ? keyPropS.i[j2][k2] : keyPropS.i[j2][k2] + (keyPropE.i[j2][k2] - keyPropS.i[j2][k2]) * perc;
          previousValue.i[j2][k2] = vertexValue;
          vertexValue = isHold ? keyPropS.o[j2][k2] : keyPropS.o[j2][k2] + (keyPropE.o[j2][k2] - keyPropS.o[j2][k2]) * perc;
          previousValue.o[j2][k2] = vertexValue;
          vertexValue = isHold ? keyPropS.v[j2][k2] : keyPropS.v[j2][k2] + (keyPropE.v[j2][k2] - keyPropS.v[j2][k2]) * perc;
          previousValue.v[j2][k2] = vertexValue;
        }
      }
    }
    function interpolateShapeCurrentTime() {
      var frameNum = this.comp.renderedFrame - this.offsetTime;
      var initTime = this.keyframes[0].t - this.offsetTime;
      var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime;
      var lastFrame = this._caching.lastFrame;
      if (!(lastFrame !== initFrame && (lastFrame < initTime && frameNum < initTime || lastFrame > endTime && frameNum > endTime))) {
        this._caching.lastIndex = lastFrame < frameNum ? this._caching.lastIndex : 0;
        this.interpolateShape(frameNum, this.pv, this._caching);
      }
      this._caching.lastFrame = frameNum;
      return this.pv;
    }
    function resetShape() {
      this.paths = this.localShapeCollection;
    }
    function shapesEqual(shape1, shape2) {
      if (shape1._length !== shape2._length || shape1.c !== shape2.c) {
        return false;
      }
      var i;
      var len = shape1._length;
      for (i = 0; i < len; i += 1) {
        if (shape1.v[i][0] !== shape2.v[i][0] || shape1.v[i][1] !== shape2.v[i][1] || shape1.o[i][0] !== shape2.o[i][0] || shape1.o[i][1] !== shape2.o[i][1] || shape1.i[i][0] !== shape2.i[i][0] || shape1.i[i][1] !== shape2.i[i][1]) {
          return false;
        }
      }
      return true;
    }
    function setVValue(newPath) {
      if (!shapesEqual(this.v, newPath)) {
        this.v = shapePool.clone(newPath);
        this.localShapeCollection.releaseShapes();
        this.localShapeCollection.addShape(this.v);
        this._mdf = true;
        this.paths = this.localShapeCollection;
      }
    }
    function processEffectsSequence() {
      if (this.elem.globalData.frameId === this.frameId) {
        return;
      }
      if (!this.effectsSequence.length) {
        this._mdf = false;
        return;
      }
      if (this.lock) {
        this.setVValue(this.pv);
        return;
      }
      this.lock = true;
      this._mdf = false;
      var finalValue;
      if (this.kf) {
        finalValue = this.pv;
      } else if (this.data.ks) {
        finalValue = this.data.ks.k;
      } else {
        finalValue = this.data.pt.k;
      }
      var i;
      var len = this.effectsSequence.length;
      for (i = 0; i < len; i += 1) {
        finalValue = this.effectsSequence[i](finalValue);
      }
      this.setVValue(finalValue);
      this.lock = false;
      this.frameId = this.elem.globalData.frameId;
    }
    function ShapeProperty(elem2, data2, type) {
      this.propType = "shape";
      this.comp = elem2.comp;
      this.container = elem2;
      this.elem = elem2;
      this.data = data2;
      this.k = false;
      this.kf = false;
      this._mdf = false;
      var pathData = type === 3 ? data2.pt.k : data2.ks.k;
      this.v = shapePool.clone(pathData);
      this.pv = shapePool.clone(this.v);
      this.localShapeCollection = shapeCollectionPool.newShapeCollection();
      this.paths = this.localShapeCollection;
      this.paths.addShape(this.v);
      this.reset = resetShape;
      this.effectsSequence = [];
    }
    function addEffect(effectFunction) {
      this.effectsSequence.push(effectFunction);
      this.container.addDynamicProperty(this);
    }
    ShapeProperty.prototype.interpolateShape = interpolateShape;
    ShapeProperty.prototype.getValue = processEffectsSequence;
    ShapeProperty.prototype.setVValue = setVValue;
    ShapeProperty.prototype.addEffect = addEffect;
    function KeyframedShapeProperty(elem2, data2, type) {
      this.propType = "shape";
      this.comp = elem2.comp;
      this.elem = elem2;
      this.container = elem2;
      this.offsetTime = elem2.data.st;
      this.keyframes = type === 3 ? data2.pt.k : data2.ks.k;
      this.keyframesMetadata = [];
      this.k = true;
      this.kf = true;
      var len = this.keyframes[0].s[0].i.length;
      this.v = shapePool.newElement();
      this.v.setPathData(this.keyframes[0].s[0].c, len);
      this.pv = shapePool.clone(this.v);
      this.localShapeCollection = shapeCollectionPool.newShapeCollection();
      this.paths = this.localShapeCollection;
      this.paths.addShape(this.v);
      this.lastFrame = initFrame;
      this.reset = resetShape;
      this._caching = { lastFrame: initFrame, lastIndex: 0 };
      this.effectsSequence = [interpolateShapeCurrentTime.bind(this)];
    }
    KeyframedShapeProperty.prototype.getValue = processEffectsSequence;
    KeyframedShapeProperty.prototype.interpolateShape = interpolateShape;
    KeyframedShapeProperty.prototype.setVValue = setVValue;
    KeyframedShapeProperty.prototype.addEffect = addEffect;
    var EllShapeProperty = function() {
      var cPoint = roundCorner;
      function EllShapePropertyFactory(elem2, data2) {
        this.v = shapePool.newElement();
        this.v.setPathData(true, 4);
        this.localShapeCollection = shapeCollectionPool.newShapeCollection();
        this.paths = this.localShapeCollection;
        this.localShapeCollection.addShape(this.v);
        this.d = data2.d;
        this.elem = elem2;
        this.comp = elem2.comp;
        this.frameId = -1;
        this.initDynamicPropertyContainer(elem2);
        this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this);
        this.s = PropertyFactory.getProp(elem2, data2.s, 1, 0, this);
        if (this.dynamicProperties.length) {
          this.k = true;
        } else {
          this.k = false;
          this.convertEllToPath();
        }
      }
      EllShapePropertyFactory.prototype = {
        reset: resetShape,
        getValue: function() {
          if (this.elem.globalData.frameId === this.frameId) {
            return;
          }
          this.frameId = this.elem.globalData.frameId;
          this.iterateDynamicProperties();
          if (this._mdf) {
            this.convertEllToPath();
          }
        },
        convertEllToPath: function() {
          var p0 = this.p.v[0];
          var p1 = this.p.v[1];
          var s0 = this.s.v[0] / 2;
          var s1 = this.s.v[1] / 2;
          var _cw = this.d !== 3;
          var _v4 = this.v;
          _v4.v[0][0] = p0;
          _v4.v[0][1] = p1 - s1;
          _v4.v[1][0] = _cw ? p0 + s0 : p0 - s0;
          _v4.v[1][1] = p1;
          _v4.v[2][0] = p0;
          _v4.v[2][1] = p1 + s1;
          _v4.v[3][0] = _cw ? p0 - s0 : p0 + s0;
          _v4.v[3][1] = p1;
          _v4.i[0][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint;
          _v4.i[0][1] = p1 - s1;
          _v4.i[1][0] = _cw ? p0 + s0 : p0 - s0;
          _v4.i[1][1] = p1 - s1 * cPoint;
          _v4.i[2][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint;
          _v4.i[2][1] = p1 + s1;
          _v4.i[3][0] = _cw ? p0 - s0 : p0 + s0;
          _v4.i[3][1] = p1 + s1 * cPoint;
          _v4.o[0][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint;
          _v4.o[0][1] = p1 - s1;
          _v4.o[1][0] = _cw ? p0 + s0 : p0 - s0;
          _v4.o[1][1] = p1 + s1 * cPoint;
          _v4.o[2][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint;
          _v4.o[2][1] = p1 + s1;
          _v4.o[3][0] = _cw ? p0 - s0 : p0 + s0;
          _v4.o[3][1] = p1 - s1 * cPoint;
        }
      };
      extendPrototype([DynamicPropertyContainer], EllShapePropertyFactory);
      return EllShapePropertyFactory;
    }();
    var StarShapeProperty = function() {
      function StarShapePropertyFactory(elem2, data2) {
        this.v = shapePool.newElement();
        this.v.setPathData(true, 0);
        this.elem = elem2;
        this.comp = elem2.comp;
        this.data = data2;
        this.frameId = -1;
        this.d = data2.d;
        this.initDynamicPropertyContainer(elem2);
        if (data2.sy === 1) {
          this.ir = PropertyFactory.getProp(elem2, data2.ir, 0, 0, this);
          this.is = PropertyFactory.getProp(elem2, data2.is, 0, 0.01, this);
          this.convertToPath = this.convertStarToPath;
        } else {
          this.convertToPath = this.convertPolygonToPath;
        }
        this.pt = PropertyFactory.getProp(elem2, data2.pt, 0, 0, this);
        this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this);
        this.r = PropertyFactory.getProp(elem2, data2.r, 0, degToRads, this);
        this.or = PropertyFactory.getProp(elem2, data2.or, 0, 0, this);
        this.os = PropertyFactory.getProp(elem2, data2.os, 0, 0.01, this);
        this.localShapeCollection = shapeCollectionPool.newShapeCollection();
        this.localShapeCollection.addShape(this.v);
        this.paths = this.localShapeCollection;
        if (this.dynamicProperties.length) {
          this.k = true;
        } else {
          this.k = false;
          this.convertToPath();
        }
      }
      StarShapePropertyFactory.prototype = {
        reset: resetShape,
        getValue: function() {
          if (this.elem.globalData.frameId === this.frameId) {
            return;
          }
          this.frameId = this.elem.globalData.frameId;
          this.iterateDynamicProperties();
          if (this._mdf) {
            this.convertToPath();
          }
        },
        convertStarToPath: function() {
          var numPts = Math.floor(this.pt.v) * 2;
          var angle = Math.PI * 2 / numPts;
          var longFlag = true;
          var longRad = this.or.v;
          var shortRad = this.ir.v;
          var longRound = this.os.v;
          var shortRound = this.is.v;
          var longPerimSegment = 2 * Math.PI * longRad / (numPts * 2);
          var shortPerimSegment = 2 * Math.PI * shortRad / (numPts * 2);
          var i;
          var rad;
          var roundness;
          var perimSegment;
          var currentAng = -Math.PI / 2;
          currentAng += this.r.v;
          var dir = this.data.d === 3 ? -1 : 1;
          this.v._length = 0;
          for (i = 0; i < numPts; i += 1) {
            rad = longFlag ? longRad : shortRad;
            roundness = longFlag ? longRound : shortRound;
            perimSegment = longFlag ? longPerimSegment : shortPerimSegment;
            var x2 = rad * Math.cos(currentAng);
            var y = rad * Math.sin(currentAng);
            var ox = x2 === 0 && y === 0 ? 0 : y / Math.sqrt(x2 * x2 + y * y);
            var oy = x2 === 0 && y === 0 ? 0 : -x2 / Math.sqrt(x2 * x2 + y * y);
            x2 += +this.p.v[0];
            y += +this.p.v[1];
            this.v.setTripleAt(x2, y, x2 - ox * perimSegment * roundness * dir, y - oy * perimSegment * roundness * dir, x2 + ox * perimSegment * roundness * dir, y + oy * perimSegment * roundness * dir, i, true);
            longFlag = !longFlag;
            currentAng += angle * dir;
          }
        },
        convertPolygonToPath: function() {
          var numPts = Math.floor(this.pt.v);
          var angle = Math.PI * 2 / numPts;
          var rad = this.or.v;
          var roundness = this.os.v;
          var perimSegment = 2 * Math.PI * rad / (numPts * 4);
          var i;
          var currentAng = -Math.PI * 0.5;
          var dir = this.data.d === 3 ? -1 : 1;
          currentAng += this.r.v;
          this.v._length = 0;
          for (i = 0; i < numPts; i += 1) {
            var x2 = rad * Math.cos(currentAng);
            var y = rad * Math.sin(currentAng);
            var ox = x2 === 0 && y === 0 ? 0 : y / Math.sqrt(x2 * x2 + y * y);
            var oy = x2 === 0 && y === 0 ? 0 : -x2 / Math.sqrt(x2 * x2 + y * y);
            x2 += +this.p.v[0];
            y += +this.p.v[1];
            this.v.setTripleAt(x2, y, x2 - ox * perimSegment * roundness * dir, y - oy * perimSegment * roundness * dir, x2 + ox * perimSegment * roundness * dir, y + oy * perimSegment * roundness * dir, i, true);
            currentAng += angle * dir;
          }
          this.paths.length = 0;
          this.paths[0] = this.v;
        }
      };
      extendPrototype([DynamicPropertyContainer], StarShapePropertyFactory);
      return StarShapePropertyFactory;
    }();
    var RectShapeProperty = function() {
      function RectShapePropertyFactory(elem2, data2) {
        this.v = shapePool.newElement();
        this.v.c = true;
        this.localShapeCollection = shapeCollectionPool.newShapeCollection();
        this.localShapeCollection.addShape(this.v);
        this.paths = this.localShapeCollection;
        this.elem = elem2;
        this.comp = elem2.comp;
        this.frameId = -1;
        this.d = data2.d;
        this.initDynamicPropertyContainer(elem2);
        this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this);
        this.s = PropertyFactory.getProp(elem2, data2.s, 1, 0, this);
        this.r = PropertyFactory.getProp(elem2, data2.r, 0, 0, this);
        if (this.dynamicProperties.length) {
          this.k = true;
        } else {
          this.k = false;
          this.convertRectToPath();
        }
      }
      RectShapePropertyFactory.prototype = {
        convertRectToPath: function() {
          var p0 = this.p.v[0];
          var p1 = this.p.v[1];
          var v0 = this.s.v[0] / 2;
          var v12 = this.s.v[1] / 2;
          var round = bmMin(v0, v12, this.r.v);
          var cPoint = round * (1 - roundCorner);
          this.v._length = 0;
          if (this.d === 2 || this.d === 1) {
            this.v.setTripleAt(p0 + v0, p1 - v12 + round, p0 + v0, p1 - v12 + round, p0 + v0, p1 - v12 + cPoint, 0, true);
            this.v.setTripleAt(p0 + v0, p1 + v12 - round, p0 + v0, p1 + v12 - cPoint, p0 + v0, p1 + v12 - round, 1, true);
            if (round !== 0) {
              this.v.setTripleAt(p0 + v0 - round, p1 + v12, p0 + v0 - round, p1 + v12, p0 + v0 - cPoint, p1 + v12, 2, true);
              this.v.setTripleAt(p0 - v0 + round, p1 + v12, p0 - v0 + cPoint, p1 + v12, p0 - v0 + round, p1 + v12, 3, true);
              this.v.setTripleAt(p0 - v0, p1 + v12 - round, p0 - v0, p1 + v12 - round, p0 - v0, p1 + v12 - cPoint, 4, true);
              this.v.setTripleAt(p0 - v0, p1 - v12 + round, p0 - v0, p1 - v12 + cPoint, p0 - v0, p1 - v12 + round, 5, true);
              this.v.setTripleAt(p0 - v0 + round, p1 - v12, p0 - v0 + round, p1 - v12, p0 - v0 + cPoint, p1 - v12, 6, true);
              this.v.setTripleAt(p0 + v0 - round, p1 - v12, p0 + v0 - cPoint, p1 - v12, p0 + v0 - round, p1 - v12, 7, true);
            } else {
              this.v.setTripleAt(p0 - v0, p1 + v12, p0 - v0 + cPoint, p1 + v12, p0 - v0, p1 + v12, 2);
              this.v.setTripleAt(p0 - v0, p1 - v12, p0 - v0, p1 - v12 + cPoint, p0 - v0, p1 - v12, 3);
            }
          } else {
            this.v.setTripleAt(p0 + v0, p1 - v12 + round, p0 + v0, p1 - v12 + cPoint, p0 + v0, p1 - v12 + round, 0, true);
            if (round !== 0) {
              this.v.setTripleAt(p0 + v0 - round, p1 - v12, p0 + v0 - round, p1 - v12, p0 + v0 - cPoint, p1 - v12, 1, true);
              this.v.setTripleAt(p0 - v0 + round, p1 - v12, p0 - v0 + cPoint, p1 - v12, p0 - v0 + round, p1 - v12, 2, true);
              this.v.setTripleAt(p0 - v0, p1 - v12 + round, p0 - v0, p1 - v12 + round, p0 - v0, p1 - v12 + cPoint, 3, true);
              this.v.setTripleAt(p0 - v0, p1 + v12 - round, p0 - v0, p1 + v12 - cPoint, p0 - v0, p1 + v12 - round, 4, true);
              this.v.setTripleAt(p0 - v0 + round, p1 + v12, p0 - v0 + round, p1 + v12, p0 - v0 + cPoint, p1 + v12, 5, true);
              this.v.setTripleAt(p0 + v0 - round, p1 + v12, p0 + v0 - cPoint, p1 + v12, p0 + v0 - round, p1 + v12, 6, true);
              this.v.setTripleAt(p0 + v0, p1 + v12 - round, p0 + v0, p1 + v12 - round, p0 + v0, p1 + v12 - cPoint, 7, true);
            } else {
              this.v.setTripleAt(p0 - v0, p1 - v12, p0 - v0 + cPoint, p1 - v12, p0 - v0, p1 - v12, 1, true);
              this.v.setTripleAt(p0 - v0, p1 + v12, p0 - v0, p1 + v12 - cPoint, p0 - v0, p1 + v12, 2, true);
              this.v.setTripleAt(p0 + v0, p1 + v12, p0 + v0 - cPoint, p1 + v12, p0 + v0, p1 + v12, 3, true);
            }
          }
        },
        getValue: function() {
          if (this.elem.globalData.frameId === this.frameId) {
            return;
          }
          this.frameId = this.elem.globalData.frameId;
          this.iterateDynamicProperties();
          if (this._mdf) {
            this.convertRectToPath();
          }
        },
        reset: resetShape
      };
      extendPrototype([DynamicPropertyContainer], RectShapePropertyFactory);
      return RectShapePropertyFactory;
    }();
    function getShapeProp(elem2, data2, type) {
      var prop;
      if (type === 3 || type === 4) {
        var dataProp = type === 3 ? data2.pt : data2.ks;
        var keys2 = dataProp.k;
        if (keys2.length) {
          prop = new KeyframedShapeProperty(elem2, data2, type);
        } else {
          prop = new ShapeProperty(elem2, data2, type);
        }
      } else if (type === 5) {
        prop = new RectShapeProperty(elem2, data2);
      } else if (type === 6) {
        prop = new EllShapeProperty(elem2, data2);
      } else if (type === 7) {
        prop = new StarShapeProperty(elem2, data2);
      }
      if (prop.k) {
        elem2.addDynamicProperty(prop);
      }
      return prop;
    }
    function getConstructorFunction() {
      return ShapeProperty;
    }
    function getKeyframedConstructorFunction() {
      return KeyframedShapeProperty;
    }
    var ob2 = {};
    ob2.getShapeProp = getShapeProp;
    ob2.getConstructorFunction = getConstructorFunction;
    ob2.getKeyframedConstructorFunction = getKeyframedConstructorFunction;
    return ob2;
  }();
  const Matrix = /* @__PURE__ */ function() {
    var _cos = Math.cos;
    var _sin = Math.sin;
    var _tan = Math.tan;
    var _rnd = Math.round;
    function reset() {
      this.props[0] = 1;
      this.props[1] = 0;
      this.props[2] = 0;
      this.props[3] = 0;
      this.props[4] = 0;
      this.props[5] = 1;
      this.props[6] = 0;
      this.props[7] = 0;
      this.props[8] = 0;
      this.props[9] = 0;
      this.props[10] = 1;
      this.props[11] = 0;
      this.props[12] = 0;
      this.props[13] = 0;
      this.props[14] = 0;
      this.props[15] = 1;
      return this;
    }
    function rotate(angle) {
      if (angle === 0) {
        return this;
      }
      var mCos = _cos(angle);
      var mSin = _sin(angle);
      return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    }
    function rotateX(angle) {
      if (angle === 0) {
        return this;
      }
      var mCos = _cos(angle);
      var mSin = _sin(angle);
      return this._t(1, 0, 0, 0, 0, mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1);
    }
    function rotateY(angle) {
      if (angle === 0) {
        return this;
      }
      var mCos = _cos(angle);
      var mSin = _sin(angle);
      return this._t(mCos, 0, mSin, 0, 0, 1, 0, 0, -mSin, 0, mCos, 0, 0, 0, 0, 1);
    }
    function rotateZ(angle) {
      if (angle === 0) {
        return this;
      }
      var mCos = _cos(angle);
      var mSin = _sin(angle);
      return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    }
    function shear(sx, sy) {
      return this._t(1, sy, sx, 1, 0, 0);
    }
    function skew(ax, ay) {
      return this.shear(_tan(ax), _tan(ay));
    }
    function skewFromAxis(ax, angle) {
      var mCos = _cos(angle);
      var mSin = _sin(angle);
      return this._t(mCos, mSin, 0, 0, -mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(1, 0, 0, 0, _tan(ax), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
    }
    function scale2(sx, sy, sz) {
      if (!sz && sz !== 0) {
        sz = 1;
      }
      if (sx === 1 && sy === 1 && sz === 1) {
        return this;
      }
      return this._t(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1);
    }
    function setTransform(a2, b3, c2, d, e, f, g3, h, i, j2, k2, l2, m, n2, o, p) {
      this.props[0] = a2;
      this.props[1] = b3;
      this.props[2] = c2;
      this.props[3] = d;
      this.props[4] = e;
      this.props[5] = f;
      this.props[6] = g3;
      this.props[7] = h;
      this.props[8] = i;
      this.props[9] = j2;
      this.props[10] = k2;
      this.props[11] = l2;
      this.props[12] = m;
      this.props[13] = n2;
      this.props[14] = o;
      this.props[15] = p;
      return this;
    }
    function translate(tx, ty, tz) {
      tz = tz || 0;
      if (tx !== 0 || ty !== 0 || tz !== 0) {
        return this._t(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty, tz, 1);
      }
      return this;
    }
    function transform2(a2, b22, c2, d2, e2, f2, g22, h2, i2, j2, k2, l2, m2, n2, o2, p2) {
      var _p2 = this.props;
      if (a2 === 1 && b22 === 0 && c2 === 0 && d2 === 0 && e2 === 0 && f2 === 1 && g22 === 0 && h2 === 0 && i2 === 0 && j2 === 0 && k2 === 1 && l2 === 0) {
        _p2[12] = _p2[12] * a2 + _p2[15] * m2;
        _p2[13] = _p2[13] * f2 + _p2[15] * n2;
        _p2[14] = _p2[14] * k2 + _p2[15] * o2;
        _p2[15] *= p2;
        this._identityCalculated = false;
        return this;
      }
      var a1 = _p2[0];
      var b1 = _p2[1];
      var c1 = _p2[2];
      var d1 = _p2[3];
      var e1 = _p2[4];
      var f1 = _p2[5];
      var g1 = _p2[6];
      var h1 = _p2[7];
      var i1 = _p2[8];
      var j1 = _p2[9];
      var k1 = _p2[10];
      var l1 = _p2[11];
      var m1 = _p2[12];
      var n1 = _p2[13];
      var o1 = _p2[14];
      var p1 = _p2[15];
      _p2[0] = a1 * a2 + b1 * e2 + c1 * i2 + d1 * m2;
      _p2[1] = a1 * b22 + b1 * f2 + c1 * j2 + d1 * n2;
      _p2[2] = a1 * c2 + b1 * g22 + c1 * k2 + d1 * o2;
      _p2[3] = a1 * d2 + b1 * h2 + c1 * l2 + d1 * p2;
      _p2[4] = e1 * a2 + f1 * e2 + g1 * i2 + h1 * m2;
      _p2[5] = e1 * b22 + f1 * f2 + g1 * j2 + h1 * n2;
      _p2[6] = e1 * c2 + f1 * g22 + g1 * k2 + h1 * o2;
      _p2[7] = e1 * d2 + f1 * h2 + g1 * l2 + h1 * p2;
      _p2[8] = i1 * a2 + j1 * e2 + k1 * i2 + l1 * m2;
      _p2[9] = i1 * b22 + j1 * f2 + k1 * j2 + l1 * n2;
      _p2[10] = i1 * c2 + j1 * g22 + k1 * k2 + l1 * o2;
      _p2[11] = i1 * d2 + j1 * h2 + k1 * l2 + l1 * p2;
      _p2[12] = m1 * a2 + n1 * e2 + o1 * i2 + p1 * m2;
      _p2[13] = m1 * b22 + n1 * f2 + o1 * j2 + p1 * n2;
      _p2[14] = m1 * c2 + n1 * g22 + o1 * k2 + p1 * o2;
      _p2[15] = m1 * d2 + n1 * h2 + o1 * l2 + p1 * p2;
      this._identityCalculated = false;
      return this;
    }
    function isIdentity() {
      if (!this._identityCalculated) {
        this._identity = !(this.props[0] !== 1 || this.props[1] !== 0 || this.props[2] !== 0 || this.props[3] !== 0 || this.props[4] !== 0 || this.props[5] !== 1 || this.props[6] !== 0 || this.props[7] !== 0 || this.props[8] !== 0 || this.props[9] !== 0 || this.props[10] !== 1 || this.props[11] !== 0 || this.props[12] !== 0 || this.props[13] !== 0 || this.props[14] !== 0 || this.props[15] !== 1);
        this._identityCalculated = true;
      }
      return this._identity;
    }
    function equals2(matr) {
      var i = 0;
      while (i < 16) {
        if (matr.props[i] !== this.props[i]) {
          return false;
        }
        i += 1;
      }
      return true;
    }
    function clone2(matr) {
      var i;
      for (i = 0; i < 16; i += 1) {
        matr.props[i] = this.props[i];
      }
      return matr;
    }
    function cloneFromProps(props) {
      var i;
      for (i = 0; i < 16; i += 1) {
        this.props[i] = props[i];
      }
    }
    function applyToPoint(x2, y, z) {
      return {
        x: x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12],
        y: x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13],
        z: x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14]
      };
    }
    function applyToX(x2, y, z) {
      return x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12];
    }
    function applyToY(x2, y, z) {
      return x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13];
    }
    function applyToZ(x2, y, z) {
      return x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14];
    }
    function getInverseMatrix() {
      var determinant = this.props[0] * this.props[5] - this.props[1] * this.props[4];
      var a2 = this.props[5] / determinant;
      var b3 = -this.props[1] / determinant;
      var c2 = -this.props[4] / determinant;
      var d = this.props[0] / determinant;
      var e = (this.props[4] * this.props[13] - this.props[5] * this.props[12]) / determinant;
      var f = -(this.props[0] * this.props[13] - this.props[1] * this.props[12]) / determinant;
      var inverseMatrix = new Matrix();
      inverseMatrix.props[0] = a2;
      inverseMatrix.props[1] = b3;
      inverseMatrix.props[4] = c2;
      inverseMatrix.props[5] = d;
      inverseMatrix.props[12] = e;
      inverseMatrix.props[13] = f;
      return inverseMatrix;
    }
    function inversePoint(pt) {
      var inverseMatrix = this.getInverseMatrix();
      return inverseMatrix.applyToPointArray(pt[0], pt[1], pt[2] || 0);
    }
    function inversePoints(pts) {
      var i;
      var len = pts.length;
      var retPts = [];
      for (i = 0; i < len; i += 1) {
        retPts[i] = inversePoint(pts[i]);
      }
      return retPts;
    }
    function applyToTriplePoints(pt1, pt2, pt3) {
      var arr = createTypedArray("float32", 6);
      if (this.isIdentity()) {
        arr[0] = pt1[0];
        arr[1] = pt1[1];
        arr[2] = pt2[0];
        arr[3] = pt2[1];
        arr[4] = pt3[0];
        arr[5] = pt3[1];
      } else {
        var p0 = this.props[0];
        var p1 = this.props[1];
        var p4 = this.props[4];
        var p5 = this.props[5];
        var p12 = this.props[12];
        var p13 = this.props[13];
        arr[0] = pt1[0] * p0 + pt1[1] * p4 + p12;
        arr[1] = pt1[0] * p1 + pt1[1] * p5 + p13;
        arr[2] = pt2[0] * p0 + pt2[1] * p4 + p12;
        arr[3] = pt2[0] * p1 + pt2[1] * p5 + p13;
        arr[4] = pt3[0] * p0 + pt3[1] * p4 + p12;
        arr[5] = pt3[0] * p1 + pt3[1] * p5 + p13;
      }
      return arr;
    }
    function applyToPointArray(x2, y, z) {
      var arr;
      if (this.isIdentity()) {
        arr = [x2, y, z];
      } else {
        arr = [
          x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12],
          x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13],
          x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14]
        ];
      }
      return arr;
    }
    function applyToPointStringified(x2, y) {
      if (this.isIdentity()) {
        return x2 + "," + y;
      }
      var _p2 = this.props;
      return Math.round((x2 * _p2[0] + y * _p2[4] + _p2[12]) * 100) / 100 + "," + Math.round((x2 * _p2[1] + y * _p2[5] + _p2[13]) * 100) / 100;
    }
    function toCSS() {
      var i = 0;
      var props = this.props;
      var cssValue = "matrix3d(";
      var v = 1e4;
      while (i < 16) {
        cssValue += _rnd(props[i] * v) / v;
        cssValue += i === 15 ? ")" : ",";
        i += 1;
      }
      return cssValue;
    }
    function roundMatrixProperty(val2) {
      var v = 1e4;
      if (val2 < 1e-6 && val2 > 0 || val2 > -1e-6 && val2 < 0) {
        return _rnd(val2 * v) / v;
      }
      return val2;
    }
    function to2dCSS() {
      var props = this.props;
      var _a3 = roundMatrixProperty(props[0]);
      var _b3 = roundMatrixProperty(props[1]);
      var _c = roundMatrixProperty(props[4]);
      var _d = roundMatrixProperty(props[5]);
      var _e = roundMatrixProperty(props[12]);
      var _f = roundMatrixProperty(props[13]);
      return "matrix(" + _a3 + "," + _b3 + "," + _c + "," + _d + "," + _e + "," + _f + ")";
    }
    return function() {
      this.reset = reset;
      this.rotate = rotate;
      this.rotateX = rotateX;
      this.rotateY = rotateY;
      this.rotateZ = rotateZ;
      this.skew = skew;
      this.skewFromAxis = skewFromAxis;
      this.shear = shear;
      this.scale = scale2;
      this.setTransform = setTransform;
      this.translate = translate;
      this.transform = transform2;
      this.applyToPoint = applyToPoint;
      this.applyToX = applyToX;
      this.applyToY = applyToY;
      this.applyToZ = applyToZ;
      this.applyToPointArray = applyToPointArray;
      this.applyToTriplePoints = applyToTriplePoints;
      this.applyToPointStringified = applyToPointStringified;
      this.toCSS = toCSS;
      this.to2dCSS = to2dCSS;
      this.clone = clone2;
      this.cloneFromProps = cloneFromProps;
      this.equals = equals2;
      this.inversePoints = inversePoints;
      this.inversePoint = inversePoint;
      this.getInverseMatrix = getInverseMatrix;
      this._t = this.transform;
      this.isIdentity = isIdentity;
      this._identity = true;
      this._identityCalculated = false;
      this.props = createTypedArray("float32", 16);
      this.reset();
    };
  }();
  standalone = "__[STANDALONE]__";
  animationData = "__[ANIMATIONDATA]__";
  renderer = "";
  lottie.play = animationManager.play;
  lottie.pause = animationManager.pause;
  lottie.setLocationHref = setLocation;
  lottie.togglePause = animationManager.togglePause;
  lottie.setSpeed = animationManager.setSpeed;
  lottie.setDirection = animationManager.setDirection;
  lottie.stop = animationManager.stop;
  lottie.searchAnimations = searchAnimations;
  lottie.registerAnimation = animationManager.registerAnimation;
  lottie.loadAnimation = loadAnimation;
  lottie.setSubframeRendering = setSubframeRendering;
  lottie.resize = animationManager.resize;
  lottie.goToAndStop = animationManager.goToAndStop;
  lottie.destroy = animationManager.destroy;
  lottie.setQuality = setQuality;
  lottie.inBrowser = inBrowser;
  lottie.installPlugin = installPlugin;
  lottie.freeze = animationManager.freeze;
  lottie.unfreeze = animationManager.unfreeze;
  lottie.setVolume = animationManager.setVolume;
  lottie.mute = animationManager.mute;
  lottie.unmute = animationManager.unmute;
  lottie.getRegisteredAnimations = animationManager.getRegisteredAnimations;
  lottie.useWebWorker = setWebWorker;
  lottie.setIDPrefix = setPrefix;
  lottie.__getFactory = getFactory;
  lottie.version = "[[BM_VERSION]]";
  queryString = "";
  if (standalone) {
    scripts = document.getElementsByTagName("script");
    index2 = scripts.length - 1;
    myScript = scripts[index2] || {
      src: ""
    };
    queryString = myScript.src ? myScript.src.replace(/^[^\?]+\??/, "") : "";
    renderer = getQueryVariable("renderer");
  }
  readyStateCheckInterval = setInterval(checkReady, 100);
  try {
    if (!(typeof exports === "object" && typeof module !== "undefined") && !(typeof define === "function" && define.amd)) {
      window.bodymovin = lottie;
    }
  } catch (err2) {
  }
  const ShapeModifiers = function() {
    var ob2 = {};
    var modifiers = {};
    ob2.registerModifier = registerModifier;
    ob2.getModifier = getModifier;
    function registerModifier(nm, factory) {
      if (!modifiers[nm]) {
        modifiers[nm] = factory;
      }
    }
    function getModifier(nm, elem2, data2) {
      return new modifiers[nm](elem2, data2);
    }
    return ob2;
  }();
  ShapeModifier.prototype.initModifierProperties = function() {
  };
  ShapeModifier.prototype.addShapeToModifier = function() {
  };
  ShapeModifier.prototype.addShape = function(data2) {
    if (!this.closed) {
      data2.sh.container.addDynamicProperty(data2.sh);
      var shapeData = { shape: data2.sh, data: data2, localShapeCollection: shapeCollectionPool.newShapeCollection() };
      this.shapes.push(shapeData);
      this.addShapeToModifier(shapeData);
      if (this._isAnimated) {
        data2.setAsAnimated();
      }
    }
  };
  ShapeModifier.prototype.init = function(elem2, data2) {
    this.shapes = [];
    this.elem = elem2;
    this.initDynamicPropertyContainer(elem2);
    this.initModifierProperties(elem2, data2);
    this.frameId = initialDefaultFrame;
    this.closed = false;
    this.k = false;
    if (this.dynamicProperties.length) {
      this.k = true;
    } else {
      this.getValue(true);
    }
  };
  ShapeModifier.prototype.processKeys = function() {
    if (this.elem.globalData.frameId === this.frameId) {
      return;
    }
    this.frameId = this.elem.globalData.frameId;
    this.iterateDynamicProperties();
  };
  extendPrototype([DynamicPropertyContainer], ShapeModifier);
  extendPrototype([ShapeModifier], TrimModifier);
  TrimModifier.prototype.initModifierProperties = function(elem2, data2) {
    this.s = PropertyFactory.getProp(elem2, data2.s, 0, 0.01, this);
    this.e = PropertyFactory.getProp(elem2, data2.e, 0, 0.01, this);
    this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0, this);
    this.sValue = 0;
    this.eValue = 0;
    this.getValue = this.processKeys;
    this.m = data2.m;
    this._isAnimated = !!this.s.effectsSequence.length || !!this.e.effectsSequence.length || !!this.o.effectsSequence.length;
  };
  TrimModifier.prototype.addShapeToModifier = function(shapeData) {
    shapeData.pathsData = [];
  };
  TrimModifier.prototype.calculateShapeEdges = function(s, e, shapeLength, addedLength, totalModifierLength) {
    var segments = [];
    if (e <= 1) {
      segments.push({
        s,
        e
      });
    } else if (s >= 1) {
      segments.push({
        s: s - 1,
        e: e - 1
      });
    } else {
      segments.push({
        s,
        e: 1
      });
      segments.push({
        s: 0,
        e: e - 1
      });
    }
    var shapeSegments = [];
    var i;
    var len = segments.length;
    var segmentOb;
    for (i = 0; i < len; i += 1) {
      segmentOb = segments[i];
      if (!(segmentOb.e * totalModifierLength < addedLength || segmentOb.s * totalModifierLength > addedLength + shapeLength)) {
        var shapeS;
        var shapeE;
        if (segmentOb.s * totalModifierLength <= addedLength) {
          shapeS = 0;
        } else {
          shapeS = (segmentOb.s * totalModifierLength - addedLength) / shapeLength;
        }
        if (segmentOb.e * totalModifierLength >= addedLength + shapeLength) {
          shapeE = 1;
        } else {
          shapeE = (segmentOb.e * totalModifierLength - addedLength) / shapeLength;
        }
        shapeSegments.push([shapeS, shapeE]);
      }
    }
    if (!shapeSegments.length) {
      shapeSegments.push([0, 0]);
    }
    return shapeSegments;
  };
  TrimModifier.prototype.releasePathsData = function(pathsData) {
    var i;
    var len = pathsData.length;
    for (i = 0; i < len; i += 1) {
      segmentsLengthPool.release(pathsData[i]);
    }
    pathsData.length = 0;
    return pathsData;
  };
  TrimModifier.prototype.processShapes = function(_isFirstFrame) {
    var s;
    var e;
    if (this._mdf || _isFirstFrame) {
      var o = this.o.v % 360 / 360;
      if (o < 0) {
        o += 1;
      }
      if (this.s.v > 1) {
        s = 1 + o;
      } else if (this.s.v < 0) {
        s = 0 + o;
      } else {
        s = this.s.v + o;
      }
      if (this.e.v > 1) {
        e = 1 + o;
      } else if (this.e.v < 0) {
        e = 0 + o;
      } else {
        e = this.e.v + o;
      }
      if (s > e) {
        var _s = s;
        s = e;
        e = _s;
      }
      s = Math.round(s * 1e4) * 1e-4;
      e = Math.round(e * 1e4) * 1e-4;
      this.sValue = s;
      this.eValue = e;
    } else {
      s = this.sValue;
      e = this.eValue;
    }
    var shapePaths;
    var i;
    var len = this.shapes.length;
    var j2;
    var jLen;
    var pathsData;
    var pathData;
    var totalShapeLength;
    var totalModifierLength = 0;
    if (e === s) {
      for (i = 0; i < len; i += 1) {
        this.shapes[i].localShapeCollection.releaseShapes();
        this.shapes[i].shape._mdf = true;
        this.shapes[i].shape.paths = this.shapes[i].localShapeCollection;
        if (this._mdf) {
          this.shapes[i].pathsData.length = 0;
        }
      }
    } else if (!(e === 1 && s === 0 || e === 0 && s === 1)) {
      var segments = [];
      var shapeData;
      var localShapeCollection;
      for (i = 0; i < len; i += 1) {
        shapeData = this.shapes[i];
        if (!shapeData.shape._mdf && !this._mdf && !_isFirstFrame && this.m !== 2) {
          shapeData.shape.paths = shapeData.localShapeCollection;
        } else {
          shapePaths = shapeData.shape.paths;
          jLen = shapePaths._length;
          totalShapeLength = 0;
          if (!shapeData.shape._mdf && shapeData.pathsData.length) {
            totalShapeLength = shapeData.totalShapeLength;
          } else {
            pathsData = this.releasePathsData(shapeData.pathsData);
            for (j2 = 0; j2 < jLen; j2 += 1) {
              pathData = bez.getSegmentsLength(shapePaths.shapes[j2]);
              pathsData.push(pathData);
              totalShapeLength += pathData.totalLength;
            }
            shapeData.totalShapeLength = totalShapeLength;
            shapeData.pathsData = pathsData;
          }
          totalModifierLength += totalShapeLength;
          shapeData.shape._mdf = true;
        }
      }
      var shapeS = s;
      var shapeE = e;
      var addedLength = 0;
      var edges;
      for (i = len - 1; i >= 0; i -= 1) {
        shapeData = this.shapes[i];
        if (shapeData.shape._mdf) {
          localShapeCollection = shapeData.localShapeCollection;
          localShapeCollection.releaseShapes();
          if (this.m === 2 && len > 1) {
            edges = this.calculateShapeEdges(s, e, shapeData.totalShapeLength, addedLength, totalModifierLength);
            addedLength += shapeData.totalShapeLength;
          } else {
            edges = [[shapeS, shapeE]];
          }
          jLen = edges.length;
          for (j2 = 0; j2 < jLen; j2 += 1) {
            shapeS = edges[j2][0];
            shapeE = edges[j2][1];
            segments.length = 0;
            if (shapeE <= 1) {
              segments.push({
                s: shapeData.totalShapeLength * shapeS,
                e: shapeData.totalShapeLength * shapeE
              });
            } else if (shapeS >= 1) {
              segments.push({
                s: shapeData.totalShapeLength * (shapeS - 1),
                e: shapeData.totalShapeLength * (shapeE - 1)
              });
            } else {
              segments.push({
                s: shapeData.totalShapeLength * shapeS,
                e: shapeData.totalShapeLength
              });
              segments.push({
                s: 0,
                e: shapeData.totalShapeLength * (shapeE - 1)
              });
            }
            var newShapesData = this.addShapes(shapeData, segments[0]);
            if (segments[0].s !== segments[0].e) {
              if (segments.length > 1) {
                var lastShapeInCollection = shapeData.shape.paths.shapes[shapeData.shape.paths._length - 1];
                if (lastShapeInCollection.c) {
                  var lastShape = newShapesData.pop();
                  this.addPaths(newShapesData, localShapeCollection);
                  newShapesData = this.addShapes(shapeData, segments[1], lastShape);
                } else {
                  this.addPaths(newShapesData, localShapeCollection);
                  newShapesData = this.addShapes(shapeData, segments[1]);
                }
              }
              this.addPaths(newShapesData, localShapeCollection);
            }
          }
          shapeData.shape.paths = localShapeCollection;
        }
      }
    } else if (this._mdf) {
      for (i = 0; i < len; i += 1) {
        this.shapes[i].pathsData.length = 0;
        this.shapes[i].shape._mdf = true;
      }
    }
  };
  TrimModifier.prototype.addPaths = function(newPaths, localShapeCollection) {
    var i;
    var len = newPaths.length;
    for (i = 0; i < len; i += 1) {
      localShapeCollection.addShape(newPaths[i]);
    }
  };
  TrimModifier.prototype.addSegment = function(pt1, pt2, pt3, pt4, shapePath, pos, newShape) {
    shapePath.setXYAt(pt2[0], pt2[1], "o", pos);
    shapePath.setXYAt(pt3[0], pt3[1], "i", pos + 1);
    if (newShape) {
      shapePath.setXYAt(pt1[0], pt1[1], "v", pos);
    }
    shapePath.setXYAt(pt4[0], pt4[1], "v", pos + 1);
  };
  TrimModifier.prototype.addSegmentFromArray = function(points, shapePath, pos, newShape) {
    shapePath.setXYAt(points[1], points[5], "o", pos);
    shapePath.setXYAt(points[2], points[6], "i", pos + 1);
    if (newShape) {
      shapePath.setXYAt(points[0], points[4], "v", pos);
    }
    shapePath.setXYAt(points[3], points[7], "v", pos + 1);
  };
  TrimModifier.prototype.addShapes = function(shapeData, shapeSegment, shapePath) {
    var pathsData = shapeData.pathsData;
    var shapePaths = shapeData.shape.paths.shapes;
    var i;
    var len = shapeData.shape.paths._length;
    var j2;
    var jLen;
    var addedLength = 0;
    var currentLengthData;
    var segmentCount;
    var lengths2;
    var segment;
    var shapes = [];
    var initPos;
    var newShape = true;
    if (!shapePath) {
      shapePath = shapePool.newElement();
      segmentCount = 0;
      initPos = 0;
    } else {
      segmentCount = shapePath._length;
      initPos = shapePath._length;
    }
    shapes.push(shapePath);
    for (i = 0; i < len; i += 1) {
      lengths2 = pathsData[i].lengths;
      shapePath.c = shapePaths[i].c;
      jLen = shapePaths[i].c ? lengths2.length : lengths2.length + 1;
      for (j2 = 1; j2 < jLen; j2 += 1) {
        currentLengthData = lengths2[j2 - 1];
        if (addedLength + currentLengthData.addedLength < shapeSegment.s) {
          addedLength += currentLengthData.addedLength;
          shapePath.c = false;
        } else if (addedLength > shapeSegment.e) {
          shapePath.c = false;
          break;
        } else {
          if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + currentLengthData.addedLength) {
            this.addSegment(shapePaths[i].v[j2 - 1], shapePaths[i].o[j2 - 1], shapePaths[i].i[j2], shapePaths[i].v[j2], shapePath, segmentCount, newShape);
            newShape = false;
          } else {
            segment = bez.getNewSegment(shapePaths[i].v[j2 - 1], shapePaths[i].v[j2], shapePaths[i].o[j2 - 1], shapePaths[i].i[j2], (shapeSegment.s - addedLength) / currentLengthData.addedLength, (shapeSegment.e - addedLength) / currentLengthData.addedLength, lengths2[j2 - 1]);
            this.addSegmentFromArray(segment, shapePath, segmentCount, newShape);
            newShape = false;
            shapePath.c = false;
          }
          addedLength += currentLengthData.addedLength;
          segmentCount += 1;
        }
      }
      if (shapePaths[i].c && lengths2.length) {
        currentLengthData = lengths2[j2 - 1];
        if (addedLength <= shapeSegment.e) {
          var segmentLength = lengths2[j2 - 1].addedLength;
          if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + segmentLength) {
            this.addSegment(shapePaths[i].v[j2 - 1], shapePaths[i].o[j2 - 1], shapePaths[i].i[0], shapePaths[i].v[0], shapePath, segmentCount, newShape);
            newShape = false;
          } else {
            segment = bez.getNewSegment(shapePaths[i].v[j2 - 1], shapePaths[i].v[0], shapePaths[i].o[j2 - 1], shapePaths[i].i[0], (shapeSegment.s - addedLength) / segmentLength, (shapeSegment.e - addedLength) / segmentLength, lengths2[j2 - 1]);
            this.addSegmentFromArray(segment, shapePath, segmentCount, newShape);
            newShape = false;
            shapePath.c = false;
          }
        } else {
          shapePath.c = false;
        }
        addedLength += currentLengthData.addedLength;
        segmentCount += 1;
      }
      if (shapePath._length) {
        shapePath.setXYAt(shapePath.v[initPos][0], shapePath.v[initPos][1], "i", initPos);
        shapePath.setXYAt(shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1], "o", shapePath._length - 1);
      }
      if (addedLength > shapeSegment.e) {
        break;
      }
      if (i < len - 1) {
        shapePath = shapePool.newElement();
        newShape = true;
        shapes.push(shapePath);
        segmentCount = 0;
      }
    }
    return shapes;
  };
  extendPrototype([ShapeModifier], PuckerAndBloatModifier);
  PuckerAndBloatModifier.prototype.initModifierProperties = function(elem2, data2) {
    this.getValue = this.processKeys;
    this.amount = PropertyFactory.getProp(elem2, data2.a, 0, null, this);
    this._isAnimated = !!this.amount.effectsSequence.length;
  };
  PuckerAndBloatModifier.prototype.processPath = function(path, amount) {
    var percent = amount / 100;
    var centerPoint = [0, 0];
    var pathLength = path._length;
    var i = 0;
    for (i = 0; i < pathLength; i += 1) {
      centerPoint[0] += path.v[i][0];
      centerPoint[1] += path.v[i][1];
    }
    centerPoint[0] /= pathLength;
    centerPoint[1] /= pathLength;
    var clonedPath = shapePool.newElement();
    clonedPath.c = path.c;
    var vX;
    var vY;
    var oX;
    var oY;
    var iX;
    var iY;
    for (i = 0; i < pathLength; i += 1) {
      vX = path.v[i][0] + (centerPoint[0] - path.v[i][0]) * percent;
      vY = path.v[i][1] + (centerPoint[1] - path.v[i][1]) * percent;
      oX = path.o[i][0] + (centerPoint[0] - path.o[i][0]) * -percent;
      oY = path.o[i][1] + (centerPoint[1] - path.o[i][1]) * -percent;
      iX = path.i[i][0] + (centerPoint[0] - path.i[i][0]) * -percent;
      iY = path.i[i][1] + (centerPoint[1] - path.i[i][1]) * -percent;
      clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, i);
    }
    return clonedPath;
  };
  PuckerAndBloatModifier.prototype.processShapes = function(_isFirstFrame) {
    var shapePaths;
    var i;
    var len = this.shapes.length;
    var j2;
    var jLen;
    var amount = this.amount.v;
    if (amount !== 0) {
      var shapeData;
      var localShapeCollection;
      for (i = 0; i < len; i += 1) {
        shapeData = this.shapes[i];
        localShapeCollection = shapeData.localShapeCollection;
        if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) {
          localShapeCollection.releaseShapes();
          shapeData.shape._mdf = true;
          shapePaths = shapeData.shape.paths.shapes;
          jLen = shapeData.shape.paths._length;
          for (j2 = 0; j2 < jLen; j2 += 1) {
            localShapeCollection.addShape(this.processPath(shapePaths[j2], amount));
          }
        }
        shapeData.shape.paths = shapeData.localShapeCollection;
      }
    }
    if (!this.dynamicProperties.length) {
      this._mdf = false;
    }
  };
  const TransformPropertyFactory = function() {
    var defaultVector = [0, 0];
    function applyToMatrix(mat) {
      var _mdf = this._mdf;
      this.iterateDynamicProperties();
      this._mdf = this._mdf || _mdf;
      if (this.a) {
        mat.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]);
      }
      if (this.s) {
        mat.scale(this.s.v[0], this.s.v[1], this.s.v[2]);
      }
      if (this.sk) {
        mat.skewFromAxis(-this.sk.v, this.sa.v);
      }
      if (this.r) {
        mat.rotate(-this.r.v);
      } else {
        mat.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]);
      }
      if (this.data.p.s) {
        if (this.data.p.z) {
          mat.translate(this.px.v, this.py.v, -this.pz.v);
        } else {
          mat.translate(this.px.v, this.py.v, 0);
        }
      } else {
        mat.translate(this.p.v[0], this.p.v[1], -this.p.v[2]);
      }
    }
    function processKeys(forceRender) {
      if (this.elem.globalData.frameId === this.frameId) {
        return;
      }
      if (this._isDirty) {
        this.precalculateMatrix();
        this._isDirty = false;
      }
      this.iterateDynamicProperties();
      if (this._mdf || forceRender) {
        var frameRate2;
        this.v.cloneFromProps(this.pre.props);
        if (this.appliedTransformations < 1) {
          this.v.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]);
        }
        if (this.appliedTransformations < 2) {
          this.v.scale(this.s.v[0], this.s.v[1], this.s.v[2]);
        }
        if (this.sk && this.appliedTransformations < 3) {
          this.v.skewFromAxis(-this.sk.v, this.sa.v);
        }
        if (this.r && this.appliedTransformations < 4) {
          this.v.rotate(-this.r.v);
        } else if (!this.r && this.appliedTransformations < 4) {
          this.v.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]);
        }
        if (this.autoOriented) {
          var v12;
          var v2;
          frameRate2 = this.elem.globalData.frameRate;
          if (this.p && this.p.keyframes && this.p.getValueAtTime) {
            if (this.p._caching.lastFrame + this.p.offsetTime <= this.p.keyframes[0].t) {
              v12 = this.p.getValueAtTime((this.p.keyframes[0].t + 0.01) / frameRate2, 0);
              v2 = this.p.getValueAtTime(this.p.keyframes[0].t / frameRate2, 0);
            } else if (this.p._caching.lastFrame + this.p.offsetTime >= this.p.keyframes[this.p.keyframes.length - 1].t) {
              v12 = this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length - 1].t / frameRate2, 0);
              v2 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t - 0.05) / frameRate2, 0);
            } else {
              v12 = this.p.pv;
              v2 = this.p.getValueAtTime((this.p._caching.lastFrame + this.p.offsetTime - 0.01) / frameRate2, this.p.offsetTime);
            }
          } else if (this.px && this.px.keyframes && this.py.keyframes && this.px.getValueAtTime && this.py.getValueAtTime) {
            v12 = [];
            v2 = [];
            var px = this.px;
            var py = this.py;
            if (px._caching.lastFrame + px.offsetTime <= px.keyframes[0].t) {
              v12[0] = px.getValueAtTime((px.keyframes[0].t + 0.01) / frameRate2, 0);
              v12[1] = py.getValueAtTime((py.keyframes[0].t + 0.01) / frameRate2, 0);
              v2[0] = px.getValueAtTime(px.keyframes[0].t / frameRate2, 0);
              v2[1] = py.getValueAtTime(py.keyframes[0].t / frameRate2, 0);
            } else if (px._caching.lastFrame + px.offsetTime >= px.keyframes[px.keyframes.length - 1].t) {
              v12[0] = px.getValueAtTime(px.keyframes[px.keyframes.length - 1].t / frameRate2, 0);
              v12[1] = py.getValueAtTime(py.keyframes[py.keyframes.length - 1].t / frameRate2, 0);
              v2[0] = px.getValueAtTime((px.keyframes[px.keyframes.length - 1].t - 0.01) / frameRate2, 0);
              v2[1] = py.getValueAtTime((py.keyframes[py.keyframes.length - 1].t - 0.01) / frameRate2, 0);
            } else {
              v12 = [px.pv, py.pv];
              v2[0] = px.getValueAtTime((px._caching.lastFrame + px.offsetTime - 0.01) / frameRate2, px.offsetTime);
              v2[1] = py.getValueAtTime((py._caching.lastFrame + py.offsetTime - 0.01) / frameRate2, py.offsetTime);
            }
          } else {
            v2 = defaultVector;
            v12 = v2;
          }
          this.v.rotate(-Math.atan2(v12[1] - v2[1], v12[0] - v2[0]));
        }
        if (this.data.p && this.data.p.s) {
          if (this.data.p.z) {
            this.v.translate(this.px.v, this.py.v, -this.pz.v);
          } else {
            this.v.translate(this.px.v, this.py.v, 0);
          }
        } else {
          this.v.translate(this.p.v[0], this.p.v[1], -this.p.v[2]);
        }
      }
      this.frameId = this.elem.globalData.frameId;
    }
    function precalculateMatrix() {
      if (!this.a.k) {
        this.pre.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]);
        this.appliedTransformations = 1;
      } else {
        return;
      }
      if (!this.s.effectsSequence.length) {
        this.pre.scale(this.s.v[0], this.s.v[1], this.s.v[2]);
        this.appliedTransformations = 2;
      } else {
        return;
      }
      if (this.sk) {
        if (!this.sk.effectsSequence.length && !this.sa.effectsSequence.length) {
          this.pre.skewFromAxis(-this.sk.v, this.sa.v);
          this.appliedTransformations = 3;
        } else {
          return;
        }
      }
      if (this.r) {
        if (!this.r.effectsSequence.length) {
          this.pre.rotate(-this.r.v);
          this.appliedTransformations = 4;
        }
      } else if (!this.rz.effectsSequence.length && !this.ry.effectsSequence.length && !this.rx.effectsSequence.length && !this.or.effectsSequence.length) {
        this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]);
        this.appliedTransformations = 4;
      }
    }
    function autoOrient() {
    }
    function addDynamicProperty(prop) {
      this._addDynamicProperty(prop);
      this.elem.addDynamicProperty(prop);
      this._isDirty = true;
    }
    function TransformProperty(elem2, data2, container) {
      this.elem = elem2;
      this.frameId = -1;
      this.propType = "transform";
      this.data = data2;
      this.v = new Matrix();
      this.pre = new Matrix();
      this.appliedTransformations = 0;
      this.initDynamicPropertyContainer(container || elem2);
      if (data2.p && data2.p.s) {
        this.px = PropertyFactory.getProp(elem2, data2.p.x, 0, 0, this);
        this.py = PropertyFactory.getProp(elem2, data2.p.y, 0, 0, this);
        if (data2.p.z) {
          this.pz = PropertyFactory.getProp(elem2, data2.p.z, 0, 0, this);
        }
      } else {
        this.p = PropertyFactory.getProp(elem2, data2.p || { k: [0, 0, 0] }, 1, 0, this);
      }
      if (data2.rx) {
        this.rx = PropertyFactory.getProp(elem2, data2.rx, 0, degToRads, this);
        this.ry = PropertyFactory.getProp(elem2, data2.ry, 0, degToRads, this);
        this.rz = PropertyFactory.getProp(elem2, data2.rz, 0, degToRads, this);
        if (data2.or.k[0].ti) {
          var i;
          var len = data2.or.k.length;
          for (i = 0; i < len; i += 1) {
            data2.or.k[i].to = null;
            data2.or.k[i].ti = null;
          }
        }
        this.or = PropertyFactory.getProp(elem2, data2.or, 1, degToRads, this);
        this.or.sh = true;
      } else {
        this.r = PropertyFactory.getProp(elem2, data2.r || { k: 0 }, 0, degToRads, this);
      }
      if (data2.sk) {
        this.sk = PropertyFactory.getProp(elem2, data2.sk, 0, degToRads, this);
        this.sa = PropertyFactory.getProp(elem2, data2.sa, 0, degToRads, this);
      }
      this.a = PropertyFactory.getProp(elem2, data2.a || { k: [0, 0, 0] }, 1, 0, this);
      this.s = PropertyFactory.getProp(elem2, data2.s || { k: [100, 100, 100] }, 1, 0.01, this);
      if (data2.o) {
        this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, elem2);
      } else {
        this.o = { _mdf: false, v: 1 };
      }
      this._isDirty = true;
      if (!this.dynamicProperties.length) {
        this.getValue(true);
      }
    }
    TransformProperty.prototype = {
      applyToMatrix,
      getValue: processKeys,
      precalculateMatrix,
      autoOrient
    };
    extendPrototype([DynamicPropertyContainer], TransformProperty);
    TransformProperty.prototype.addDynamicProperty = addDynamicProperty;
    TransformProperty.prototype._addDynamicProperty = DynamicPropertyContainer.prototype.addDynamicProperty;
    function getTransformProperty(elem2, data2, container) {
      return new TransformProperty(elem2, data2, container);
    }
    return {
      getTransformProperty
    };
  }();
  extendPrototype([ShapeModifier], RepeaterModifier);
  RepeaterModifier.prototype.initModifierProperties = function(elem2, data2) {
    this.getValue = this.processKeys;
    this.c = PropertyFactory.getProp(elem2, data2.c, 0, null, this);
    this.o = PropertyFactory.getProp(elem2, data2.o, 0, null, this);
    this.tr = TransformPropertyFactory.getTransformProperty(elem2, data2.tr, this);
    this.so = PropertyFactory.getProp(elem2, data2.tr.so, 0, 0.01, this);
    this.eo = PropertyFactory.getProp(elem2, data2.tr.eo, 0, 0.01, this);
    this.data = data2;
    if (!this.dynamicProperties.length) {
      this.getValue(true);
    }
    this._isAnimated = !!this.dynamicProperties.length;
    this.pMatrix = new Matrix();
    this.rMatrix = new Matrix();
    this.sMatrix = new Matrix();
    this.tMatrix = new Matrix();
    this.matrix = new Matrix();
  };
  RepeaterModifier.prototype.applyTransforms = function(pMatrix, rMatrix, sMatrix, transform2, perc, inv) {
    var dir = inv ? -1 : 1;
    var scaleX = transform2.s.v[0] + (1 - transform2.s.v[0]) * (1 - perc);
    var scaleY = transform2.s.v[1] + (1 - transform2.s.v[1]) * (1 - perc);
    pMatrix.translate(transform2.p.v[0] * dir * perc, transform2.p.v[1] * dir * perc, transform2.p.v[2]);
    rMatrix.translate(-transform2.a.v[0], -transform2.a.v[1], transform2.a.v[2]);
    rMatrix.rotate(-transform2.r.v * dir * perc);
    rMatrix.translate(transform2.a.v[0], transform2.a.v[1], transform2.a.v[2]);
    sMatrix.translate(-transform2.a.v[0], -transform2.a.v[1], transform2.a.v[2]);
    sMatrix.scale(inv ? 1 / scaleX : scaleX, inv ? 1 / scaleY : scaleY);
    sMatrix.translate(transform2.a.v[0], transform2.a.v[1], transform2.a.v[2]);
  };
  RepeaterModifier.prototype.init = function(elem2, arr, pos, elemsData) {
    this.elem = elem2;
    this.arr = arr;
    this.pos = pos;
    this.elemsData = elemsData;
    this._currentCopies = 0;
    this._elements = [];
    this._groups = [];
    this.frameId = -1;
    this.initDynamicPropertyContainer(elem2);
    this.initModifierProperties(elem2, arr[pos]);
    while (pos > 0) {
      pos -= 1;
      this._elements.unshift(arr[pos]);
    }
    if (this.dynamicProperties.length) {
      this.k = true;
    } else {
      this.getValue(true);
    }
  };
  RepeaterModifier.prototype.resetElements = function(elements) {
    var i;
    var len = elements.length;
    for (i = 0; i < len; i += 1) {
      elements[i]._processed = false;
      if (elements[i].ty === "gr") {
        this.resetElements(elements[i].it);
      }
    }
  };
  RepeaterModifier.prototype.cloneElements = function(elements) {
    var newElements = JSON.parse(JSON.stringify(elements));
    this.resetElements(newElements);
    return newElements;
  };
  RepeaterModifier.prototype.changeGroupRender = function(elements, renderFlag) {
    var i;
    var len = elements.length;
    for (i = 0; i < len; i += 1) {
      elements[i]._render = renderFlag;
      if (elements[i].ty === "gr") {
        this.changeGroupRender(elements[i].it, renderFlag);
      }
    }
  };
  RepeaterModifier.prototype.processShapes = function(_isFirstFrame) {
    var items;
    var itemsTransform;
    var i;
    var dir;
    var cont;
    var hasReloaded = false;
    if (this._mdf || _isFirstFrame) {
      var copies = Math.ceil(this.c.v);
      if (this._groups.length < copies) {
        while (this._groups.length < copies) {
          var group = {
            it: this.cloneElements(this._elements),
            ty: "gr"
          };
          group.it.push({
            a: { a: 0, ix: 1, k: [0, 0] },
            nm: "Transform",
            o: { a: 0, ix: 7, k: 100 },
            p: { a: 0, ix: 2, k: [0, 0] },
            r: { a: 1, ix: 6, k: [{ s: 0, e: 0, t: 0 }, { s: 0, e: 0, t: 1 }] },
            s: { a: 0, ix: 3, k: [100, 100] },
            sa: { a: 0, ix: 5, k: 0 },
            sk: { a: 0, ix: 4, k: 0 },
            ty: "tr"
          });
          this.arr.splice(0, 0, group);
          this._groups.splice(0, 0, group);
          this._currentCopies += 1;
        }
        this.elem.reloadShapes();
        hasReloaded = true;
      }
      cont = 0;
      var renderFlag;
      for (i = 0; i <= this._groups.length - 1; i += 1) {
        renderFlag = cont < copies;
        this._groups[i]._render = renderFlag;
        this.changeGroupRender(this._groups[i].it, renderFlag);
        if (!renderFlag) {
          var elems = this.elemsData[i].it;
          var transformData = elems[elems.length - 1];
          if (transformData.transform.op.v !== 0) {
            transformData.transform.op._mdf = true;
            transformData.transform.op.v = 0;
          } else {
            transformData.transform.op._mdf = false;
          }
        }
        cont += 1;
      }
      this._currentCopies = copies;
      var offset = this.o.v;
      var offsetModulo = offset % 1;
      var roundOffset = offset > 0 ? Math.floor(offset) : Math.ceil(offset);
      var pProps = this.pMatrix.props;
      var rProps = this.rMatrix.props;
      var sProps = this.sMatrix.props;
      this.pMatrix.reset();
      this.rMatrix.reset();
      this.sMatrix.reset();
      this.tMatrix.reset();
      this.matrix.reset();
      var iteration = 0;
      if (offset > 0) {
        while (iteration < roundOffset) {
          this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false);
          iteration += 1;
        }
        if (offsetModulo) {
          this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, offsetModulo, false);
          iteration += offsetModulo;
        }
      } else if (offset < 0) {
        while (iteration > roundOffset) {
          this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, true);
          iteration -= 1;
        }
        if (offsetModulo) {
          this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, -offsetModulo, true);
          iteration -= offsetModulo;
        }
      }
      i = this.data.m === 1 ? 0 : this._currentCopies - 1;
      dir = this.data.m === 1 ? 1 : -1;
      cont = this._currentCopies;
      var j2;
      var jLen;
      while (cont) {
        items = this.elemsData[i].it;
        itemsTransform = items[items.length - 1].transform.mProps.v.props;
        jLen = itemsTransform.length;
        items[items.length - 1].transform.mProps._mdf = true;
        items[items.length - 1].transform.op._mdf = true;
        items[items.length - 1].transform.op.v = this._currentCopies === 1 ? this.so.v : this.so.v + (this.eo.v - this.so.v) * (i / (this._currentCopies - 1));
        if (iteration !== 0) {
          if (i !== 0 && dir === 1 || i !== this._currentCopies - 1 && dir === -1) {
            this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false);
          }
          this.matrix.transform(rProps[0], rProps[1], rProps[2], rProps[3], rProps[4], rProps[5], rProps[6], rProps[7], rProps[8], rProps[9], rProps[10], rProps[11], rProps[12], rProps[13], rProps[14], rProps[15]);
          this.matrix.transform(sProps[0], sProps[1], sProps[2], sProps[3], sProps[4], sProps[5], sProps[6], sProps[7], sProps[8], sProps[9], sProps[10], sProps[11], sProps[12], sProps[13], sProps[14], sProps[15]);
          this.matrix.transform(pProps[0], pProps[1], pProps[2], pProps[3], pProps[4], pProps[5], pProps[6], pProps[7], pProps[8], pProps[9], pProps[10], pProps[11], pProps[12], pProps[13], pProps[14], pProps[15]);
          for (j2 = 0; j2 < jLen; j2 += 1) {
            itemsTransform[j2] = this.matrix.props[j2];
          }
          this.matrix.reset();
        } else {
          this.matrix.reset();
          for (j2 = 0; j2 < jLen; j2 += 1) {
            itemsTransform[j2] = this.matrix.props[j2];
          }
        }
        iteration += 1;
        cont -= 1;
        i += dir;
      }
    } else {
      cont = this._currentCopies;
      i = 0;
      dir = 1;
      while (cont) {
        items = this.elemsData[i].it;
        itemsTransform = items[items.length - 1].transform.mProps.v.props;
        items[items.length - 1].transform.mProps._mdf = false;
        items[items.length - 1].transform.op._mdf = false;
        cont -= 1;
        i += dir;
      }
    }
    return hasReloaded;
  };
  RepeaterModifier.prototype.addShape = function() {
  };
  extendPrototype([ShapeModifier], RoundCornersModifier);
  RoundCornersModifier.prototype.initModifierProperties = function(elem2, data2) {
    this.getValue = this.processKeys;
    this.rd = PropertyFactory.getProp(elem2, data2.r, 0, null, this);
    this._isAnimated = !!this.rd.effectsSequence.length;
  };
  RoundCornersModifier.prototype.processPath = function(path, round) {
    var clonedPath = shapePool.newElement();
    clonedPath.c = path.c;
    var i;
    var len = path._length;
    var currentV;
    var currentI;
    var currentO;
    var closerV;
    var distance;
    var newPosPerc;
    var index2 = 0;
    var vX;
    var vY;
    var oX;
    var oY;
    var iX;
    var iY;
    for (i = 0; i < len; i += 1) {
      currentV = path.v[i];
      currentO = path.o[i];
      currentI = path.i[i];
      if (currentV[0] === currentO[0] && currentV[1] === currentO[1] && currentV[0] === currentI[0] && currentV[1] === currentI[1]) {
        if ((i === 0 || i === len - 1) && !path.c) {
          clonedPath.setTripleAt(currentV[0], currentV[1], currentO[0], currentO[1], currentI[0], currentI[1], index2);
          index2 += 1;
        } else {
          if (i === 0) {
            closerV = path.v[len - 1];
          } else {
            closerV = path.v[i - 1];
          }
          distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2));
          newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0;
          iX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc;
          vX = iX;
          iY = currentV[1] - (currentV[1] - closerV[1]) * newPosPerc;
          vY = iY;
          oX = vX - (vX - currentV[0]) * roundCorner;
          oY = vY - (vY - currentV[1]) * roundCorner;
          clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2);
          index2 += 1;
          if (i === len - 1) {
            closerV = path.v[0];
          } else {
            closerV = path.v[i + 1];
          }
          distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2));
          newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0;
          oX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc;
          vX = oX;
          oY = currentV[1] + (closerV[1] - currentV[1]) * newPosPerc;
          vY = oY;
          iX = vX - (vX - currentV[0]) * roundCorner;
          iY = vY - (vY - currentV[1]) * roundCorner;
          clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2);
          index2 += 1;
        }
      } else {
        clonedPath.setTripleAt(path.v[i][0], path.v[i][1], path.o[i][0], path.o[i][1], path.i[i][0], path.i[i][1], index2);
        index2 += 1;
      }
    }
    return clonedPath;
  };
  RoundCornersModifier.prototype.processShapes = function(_isFirstFrame) {
    var shapePaths;
    var i;
    var len = this.shapes.length;
    var j2;
    var jLen;
    var rd = this.rd.v;
    if (rd !== 0) {
      var shapeData;
      var localShapeCollection;
      for (i = 0; i < len; i += 1) {
        shapeData = this.shapes[i];
        localShapeCollection = shapeData.localShapeCollection;
        if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) {
          localShapeCollection.releaseShapes();
          shapeData.shape._mdf = true;
          shapePaths = shapeData.shape.paths.shapes;
          jLen = shapeData.shape.paths._length;
          for (j2 = 0; j2 < jLen; j2 += 1) {
            localShapeCollection.addShape(this.processPath(shapePaths[j2], rd));
          }
        }
        shapeData.shape.paths = shapeData.localShapeCollection;
      }
    }
    if (!this.dynamicProperties.length) {
      this._mdf = false;
    }
  };
  const FontManager = function() {
    var maxWaitingTime = 5e3;
    var emptyChar = {
      w: 0,
      size: 0,
      shapes: [],
      data: {
        shapes: []
      }
    };
    var combinedCharacters = [];
    combinedCharacters = combinedCharacters.concat([
      2304,
      2305,
      2306,
      2307,
      2362,
      2363,
      2364,
      2364,
      2366,
      2367,
      2368,
      2369,
      2370,
      2371,
      2372,
      2373,
      2374,
      2375,
      2376,
      2377,
      2378,
      2379,
      2380,
      2381,
      2382,
      2383,
      2387,
      2388,
      2389,
      2390,
      2391,
      2402,
      2403
    ]);
    var surrogateModifiers = [
      "d83cdffb",
      "d83cdffc",
      "d83cdffd",
      "d83cdffe",
      "d83cdfff"
    ];
    var zeroWidthJoiner = [65039, 8205];
    function trimFontOptions(font) {
      var familyArray = font.split(",");
      var i;
      var len = familyArray.length;
      var enabledFamilies = [];
      for (i = 0; i < len; i += 1) {
        if (familyArray[i] !== "sans-serif" && familyArray[i] !== "monospace") {
          enabledFamilies.push(familyArray[i]);
        }
      }
      return enabledFamilies.join(",");
    }
    function setUpNode(font, family) {
      var parentNode = createTag("span");
      parentNode.setAttribute("aria-hidden", true);
      parentNode.style.fontFamily = family;
      var node = createTag("span");
      node.innerText = "giItT1WQy@!-/#";
      parentNode.style.position = "absolute";
      parentNode.style.left = "-10000px";
      parentNode.style.top = "-10000px";
      parentNode.style.fontSize = "300px";
      parentNode.style.fontVariant = "normal";
      parentNode.style.fontStyle = "normal";
      parentNode.style.fontWeight = "normal";
      parentNode.style.letterSpacing = "0";
      parentNode.appendChild(node);
      document.body.appendChild(parentNode);
      var width2 = node.offsetWidth;
      node.style.fontFamily = trimFontOptions(font) + ", " + family;
      return { node, w: width2, parent: parentNode };
    }
    function checkLoadedFonts() {
      var i;
      var len = this.fonts.length;
      var node;
      var w;
      var loadedCount = len;
      for (i = 0; i < len; i += 1) {
        if (this.fonts[i].loaded) {
          loadedCount -= 1;
        } else if (this.fonts[i].fOrigin === "n" || this.fonts[i].origin === 0) {
          this.fonts[i].loaded = true;
        } else {
          node = this.fonts[i].monoCase.node;
          w = this.fonts[i].monoCase.w;
          if (node.offsetWidth !== w) {
            loadedCount -= 1;
            this.fonts[i].loaded = true;
          } else {
            node = this.fonts[i].sansCase.node;
            w = this.fonts[i].sansCase.w;
            if (node.offsetWidth !== w) {
              loadedCount -= 1;
              this.fonts[i].loaded = true;
            }
          }
          if (this.fonts[i].loaded) {
            this.fonts[i].sansCase.parent.parentNode.removeChild(this.fonts[i].sansCase.parent);
            this.fonts[i].monoCase.parent.parentNode.removeChild(this.fonts[i].monoCase.parent);
          }
        }
      }
      if (loadedCount !== 0 && Date.now() - this.initTime < maxWaitingTime) {
        setTimeout(this.checkLoadedFontsBinded, 20);
      } else {
        setTimeout(this.setIsLoadedBinded, 10);
      }
    }
    function createHelper(fontData, def) {
      var engine = document.body && def ? "svg" : "canvas";
      var helper;
      var fontProps = getFontProperties(fontData);
      if (engine === "svg") {
        var tHelper = createNS("text");
        tHelper.style.fontSize = "100px";
        tHelper.setAttribute("font-family", fontData.fFamily);
        tHelper.setAttribute("font-style", fontProps.style);
        tHelper.setAttribute("font-weight", fontProps.weight);
        tHelper.textContent = "1";
        if (fontData.fClass) {
          tHelper.style.fontFamily = "inherit";
          tHelper.setAttribute("class", fontData.fClass);
        } else {
          tHelper.style.fontFamily = fontData.fFamily;
        }
        def.appendChild(tHelper);
        helper = tHelper;
      } else {
        var tCanvasHelper = new OffscreenCanvas(500, 500).getContext("2d");
        tCanvasHelper.font = fontProps.style + " " + fontProps.weight + " 100px " + fontData.fFamily;
        helper = tCanvasHelper;
      }
      function measure(text2) {
        if (engine === "svg") {
          helper.textContent = text2;
          return helper.getComputedTextLength();
        }
        return helper.measureText(text2).width;
      }
      return {
        measureText: measure
      };
    }
    function addFonts(fontData, defs) {
      if (!fontData) {
        this.isLoaded = true;
        return;
      }
      if (this.chars) {
        this.isLoaded = true;
        this.fonts = fontData.list;
        return;
      }
      if (!document.body) {
        this.isLoaded = true;
        fontData.list.forEach((data2) => {
          data2.helper = createHelper(data2);
          data2.cache = {};
        });
        this.fonts = fontData.list;
        return;
      }
      var fontArr = fontData.list;
      var i;
      var len = fontArr.length;
      var _pendingFonts = len;
      for (i = 0; i < len; i += 1) {
        var shouldLoadFont = true;
        var loadedSelector;
        var j2;
        fontArr[i].loaded = false;
        fontArr[i].monoCase = setUpNode(fontArr[i].fFamily, "monospace");
        fontArr[i].sansCase = setUpNode(fontArr[i].fFamily, "sans-serif");
        if (!fontArr[i].fPath) {
          fontArr[i].loaded = true;
          _pendingFonts -= 1;
        } else if (fontArr[i].fOrigin === "p" || fontArr[i].origin === 3) {
          loadedSelector = document.querySelectorAll('style[f-forigin="p"][f-family="' + fontArr[i].fFamily + '"], style[f-origin="3"][f-family="' + fontArr[i].fFamily + '"]');
          if (loadedSelector.length > 0) {
            shouldLoadFont = false;
          }
          if (shouldLoadFont) {
            var s = createTag("style");
            s.setAttribute("f-forigin", fontArr[i].fOrigin);
            s.setAttribute("f-origin", fontArr[i].origin);
            s.setAttribute("f-family", fontArr[i].fFamily);
            s.type = "text/css";
            s.innerText = "@font-face {font-family: " + fontArr[i].fFamily + "; font-style: normal; src: url('" + fontArr[i].fPath + "');}";
            defs.appendChild(s);
          }
        } else if (fontArr[i].fOrigin === "g" || fontArr[i].origin === 1) {
          loadedSelector = document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]');
          for (j2 = 0; j2 < loadedSelector.length; j2 += 1) {
            if (loadedSelector[j2].href.indexOf(fontArr[i].fPath) !== -1) {
              shouldLoadFont = false;
            }
          }
          if (shouldLoadFont) {
            var l2 = createTag("link");
            l2.setAttribute("f-forigin", fontArr[i].fOrigin);
            l2.setAttribute("f-origin", fontArr[i].origin);
            l2.type = "text/css";
            l2.rel = "stylesheet";
            l2.href = fontArr[i].fPath;
            document.body.appendChild(l2);
          }
        } else if (fontArr[i].fOrigin === "t" || fontArr[i].origin === 2) {
          loadedSelector = document.querySelectorAll('script[f-forigin="t"], script[f-origin="2"]');
          for (j2 = 0; j2 < loadedSelector.length; j2 += 1) {
            if (fontArr[i].fPath === loadedSelector[j2].src) {
              shouldLoadFont = false;
            }
          }
          if (shouldLoadFont) {
            var sc = createTag("link");
            sc.setAttribute("f-forigin", fontArr[i].fOrigin);
            sc.setAttribute("f-origin", fontArr[i].origin);
            sc.setAttribute("rel", "stylesheet");
            sc.setAttribute("href", fontArr[i].fPath);
            defs.appendChild(sc);
          }
        }
        fontArr[i].helper = createHelper(fontArr[i], defs);
        fontArr[i].cache = {};
        this.fonts.push(fontArr[i]);
      }
      if (_pendingFonts === 0) {
        this.isLoaded = true;
      } else {
        setTimeout(this.checkLoadedFonts.bind(this), 100);
      }
    }
    function addChars(chars) {
      if (!chars) {
        return;
      }
      if (!this.chars) {
        this.chars = [];
      }
      var i;
      var len = chars.length;
      var j2;
      var jLen = this.chars.length;
      var found;
      for (i = 0; i < len; i += 1) {
        j2 = 0;
        found = false;
        while (j2 < jLen) {
          if (this.chars[j2].style === chars[i].style && this.chars[j2].fFamily === chars[i].fFamily && this.chars[j2].ch === chars[i].ch) {
            found = true;
          }
          j2 += 1;
        }
        if (!found) {
          this.chars.push(chars[i]);
          jLen += 1;
        }
      }
    }
    function getCharData(char, style, font) {
      var i = 0;
      var len = this.chars.length;
      while (i < len) {
        if (this.chars[i].ch === char && this.chars[i].style === style && this.chars[i].fFamily === font) {
          return this.chars[i];
        }
        i += 1;
      }
      if ((typeof char === "string" && char.charCodeAt(0) !== 13 || !char) && console && console.warn && !this._warned) {
        this._warned = true;
        console.warn("Missing character from exported characters list: ", char, style, font);
      }
      return emptyChar;
    }
    function measureText(char, fontName, size2) {
      var fontData = this.getFontByName(fontName);
      var index2 = char.charCodeAt(0);
      if (!fontData.cache[index2 + 1]) {
        var tHelper = fontData.helper;
        if (char === " ") {
          var doubleSize = tHelper.measureText("|" + char + "|");
          var singleSize = tHelper.measureText("||");
          fontData.cache[index2 + 1] = (doubleSize - singleSize) / 100;
        } else {
          fontData.cache[index2 + 1] = tHelper.measureText(char) / 100;
        }
      }
      return fontData.cache[index2 + 1] * size2;
    }
    function getFontByName(name2) {
      var i = 0;
      var len = this.fonts.length;
      while (i < len) {
        if (this.fonts[i].fName === name2) {
          return this.fonts[i];
        }
        i += 1;
      }
      return this.fonts[0];
    }
    function isModifier(firstCharCode, secondCharCode) {
      var sum2 = firstCharCode.toString(16) + secondCharCode.toString(16);
      return surrogateModifiers.indexOf(sum2) !== -1;
    }
    function isZeroWidthJoiner(firstCharCode, secondCharCode) {
      if (!secondCharCode) {
        return firstCharCode === zeroWidthJoiner[1];
      }
      return firstCharCode === zeroWidthJoiner[0] && secondCharCode === zeroWidthJoiner[1];
    }
    function isCombinedCharacter(char) {
      return combinedCharacters.indexOf(char) !== -1;
    }
    function setIsLoaded() {
      this.isLoaded = true;
    }
    var Font3 = function() {
      this.fonts = [];
      this.chars = null;
      this.typekitLoaded = 0;
      this.isLoaded = false;
      this._warned = false;
      this.initTime = Date.now();
      this.setIsLoadedBinded = this.setIsLoaded.bind(this);
      this.checkLoadedFontsBinded = this.checkLoadedFonts.bind(this);
    };
    Font3.isModifier = isModifier;
    Font3.isZeroWidthJoiner = isZeroWidthJoiner;
    Font3.isCombinedCharacter = isCombinedCharacter;
    var fontPrototype = {
      addChars,
      addFonts,
      getCharData,
      getFontByName,
      measureText,
      checkLoadedFonts,
      setIsLoaded
    };
    Font3.prototype = fontPrototype;
    return Font3;
  }();
  RenderableElement.prototype = {
    initRenderable: function() {
      this.isInRange = false;
      this.hidden = false;
      this.isTransparent = false;
      this.renderableComponents = [];
    },
    addRenderableComponent: function(component) {
      if (this.renderableComponents.indexOf(component) === -1) {
        this.renderableComponents.push(component);
      }
    },
    removeRenderableComponent: function(component) {
      if (this.renderableComponents.indexOf(component) !== -1) {
        this.renderableComponents.splice(this.renderableComponents.indexOf(component), 1);
      }
    },
    prepareRenderableFrame: function(num) {
      this.checkLayerLimits(num);
    },
    checkTransparency: function() {
      if (this.finalTransform.mProp.o.v <= 0) {
        if (!this.isTransparent && this.globalData.renderConfig.hideOnTransparent) {
          this.isTransparent = true;
          this.hide();
        }
      } else if (this.isTransparent) {
        this.isTransparent = false;
        this.show();
      }
    },
    /**
       * @function
       * Initializes frame related properties.
       *
       * @param {number} num
       * current frame number in Layer's time
       *
       */
    checkLayerLimits: function(num) {
      if (this.data.ip - this.data.st <= num && this.data.op - this.data.st > num) {
        if (this.isInRange !== true) {
          this.globalData._mdf = true;
          this._mdf = true;
          this.isInRange = true;
          this.show();
        }
      } else if (this.isInRange !== false) {
        this.globalData._mdf = true;
        this.isInRange = false;
        this.hide();
      }
    },
    renderRenderable: function() {
      var i;
      var len = this.renderableComponents.length;
      for (i = 0; i < len; i += 1) {
        this.renderableComponents[i].renderFrame(this._isFirstFrame);
      }
    },
    sourceRectAtTime: function() {
      return {
        top: 0,
        left: 0,
        width: 100,
        height: 100
      };
    },
    getLayerSize: function() {
      if (this.data.ty === 5) {
        return { w: this.data.textData.width, h: this.data.textData.height };
      }
      return { w: this.data.width, h: this.data.height };
    }
  };
  const MaskManagerInterface = function() {
    function MaskInterface(mask2, data2) {
      this._mask = mask2;
      this._data = data2;
    }
    Object.defineProperty(MaskInterface.prototype, "maskPath", {
      get: function() {
        if (this._mask.prop.k) {
          this._mask.prop.getValue();
        }
        return this._mask.prop;
      }
    });
    Object.defineProperty(MaskInterface.prototype, "maskOpacity", {
      get: function() {
        if (this._mask.op.k) {
          this._mask.op.getValue();
        }
        return this._mask.op.v * 100;
      }
    });
    var MaskManager = function(maskManager) {
      var _masksInterfaces = createSizedArray(maskManager.viewData.length);
      var i;
      var len = maskManager.viewData.length;
      for (i = 0; i < len; i += 1) {
        _masksInterfaces[i] = new MaskInterface(maskManager.viewData[i], maskManager.masksProperties[i]);
      }
      var maskFunction = function(name2) {
        i = 0;
        while (i < len) {
          if (maskManager.masksProperties[i].nm === name2) {
            return _masksInterfaces[i];
          }
          i += 1;
        }
        return null;
      };
      return maskFunction;
    };
    return MaskManager;
  }();
  const ExpressionPropertyInterface = /* @__PURE__ */ function() {
    var defaultUnidimensionalValue = { pv: 0, v: 0, mult: 1 };
    var defaultMultidimensionalValue = { pv: [0, 0, 0], v: [0, 0, 0], mult: 1 };
    function completeProperty(expressionValue, property2, type) {
      Object.defineProperty(expressionValue, "velocity", {
        get: function() {
          return property2.getVelocityAtTime(property2.comp.currentFrame);
        }
      });
      expressionValue.numKeys = property2.keyframes ? property2.keyframes.length : 0;
      expressionValue.key = function(pos) {
        if (!expressionValue.numKeys) {
          return 0;
        }
        var value2 = "";
        if ("s" in property2.keyframes[pos - 1]) {
          value2 = property2.keyframes[pos - 1].s;
        } else if ("e" in property2.keyframes[pos - 2]) {
          value2 = property2.keyframes[pos - 2].e;
        } else {
          value2 = property2.keyframes[pos - 2].s;
        }
        var valueProp = type === "unidimensional" ? new Number(value2) : Object.assign({}, value2);
        valueProp.time = property2.keyframes[pos - 1].t / property2.elem.comp.globalData.frameRate;
        valueProp.value = type === "unidimensional" ? value2[0] : value2;
        return valueProp;
      };
      expressionValue.valueAtTime = property2.getValueAtTime;
      expressionValue.speedAtTime = property2.getSpeedAtTime;
      expressionValue.velocityAtTime = property2.getVelocityAtTime;
      expressionValue.propertyGroup = property2.propertyGroup;
    }
    function UnidimensionalPropertyInterface(property2) {
      if (!property2 || !("pv" in property2)) {
        property2 = defaultUnidimensionalValue;
      }
      var mult = 1 / property2.mult;
      var val2 = property2.pv * mult;
      var expressionValue = new Number(val2);
      expressionValue.value = val2;
      completeProperty(expressionValue, property2, "unidimensional");
      return function() {
        if (property2.k) {
          property2.getValue();
        }
        val2 = property2.v * mult;
        if (expressionValue.value !== val2) {
          expressionValue = new Number(val2);
          expressionValue.value = val2;
          completeProperty(expressionValue, property2, "unidimensional");
        }
        return expressionValue;
      };
    }
    function MultidimensionalPropertyInterface(property2) {
      if (!property2 || !("pv" in property2)) {
        property2 = defaultMultidimensionalValue;
      }
      var mult = 1 / property2.mult;
      var len = property2.data && property2.data.l || property2.pv.length;
      var expressionValue = createTypedArray("float32", len);
      var arrValue = createTypedArray("float32", len);
      expressionValue.value = arrValue;
      completeProperty(expressionValue, property2, "multidimensional");
      return function() {
        if (property2.k) {
          property2.getValue();
        }
        for (var i = 0; i < len; i += 1) {
          arrValue[i] = property2.v[i] * mult;
          expressionValue[i] = arrValue[i];
        }
        return expressionValue;
      };
    }
    function defaultGetter() {
      return defaultUnidimensionalValue;
    }
    return function(property2) {
      if (!property2) {
        return defaultGetter;
      }
      if (property2.propType === "unidimensional") {
        return UnidimensionalPropertyInterface(property2);
      }
      return MultidimensionalPropertyInterface(property2);
    };
  }();
  const TransformExpressionInterface = /* @__PURE__ */ function() {
    return function(transform2) {
      function _thisFunction(name2) {
        switch (name2) {
          case "scale":
          case "Scale":
          case "ADBE Scale":
          case 6:
            return _thisFunction.scale;
          case "rotation":
          case "Rotation":
          case "ADBE Rotation":
          case "ADBE Rotate Z":
          case 10:
            return _thisFunction.rotation;
          case "ADBE Rotate X":
            return _thisFunction.xRotation;
          case "ADBE Rotate Y":
            return _thisFunction.yRotation;
          case "position":
          case "Position":
          case "ADBE Position":
          case 2:
            return _thisFunction.position;
          case "ADBE Position_0":
            return _thisFunction.xPosition;
          case "ADBE Position_1":
            return _thisFunction.yPosition;
          case "ADBE Position_2":
            return _thisFunction.zPosition;
          case "anchorPoint":
          case "AnchorPoint":
          case "Anchor Point":
          case "ADBE AnchorPoint":
          case 1:
            return _thisFunction.anchorPoint;
          case "opacity":
          case "Opacity":
          case 11:
            return _thisFunction.opacity;
          default:
            return null;
        }
      }
      Object.defineProperty(_thisFunction, "rotation", {
        get: ExpressionPropertyInterface(transform2.r || transform2.rz)
      });
      Object.defineProperty(_thisFunction, "zRotation", {
        get: ExpressionPropertyInterface(transform2.rz || transform2.r)
      });
      Object.defineProperty(_thisFunction, "xRotation", {
        get: ExpressionPropertyInterface(transform2.rx)
      });
      Object.defineProperty(_thisFunction, "yRotation", {
        get: ExpressionPropertyInterface(transform2.ry)
      });
      Object.defineProperty(_thisFunction, "scale", {
        get: ExpressionPropertyInterface(transform2.s)
      });
      var _px;
      var _py;
      var _pz;
      var _transformFactory;
      if (transform2.p) {
        _transformFactory = ExpressionPropertyInterface(transform2.p);
      } else {
        _px = ExpressionPropertyInterface(transform2.px);
        _py = ExpressionPropertyInterface(transform2.py);
        if (transform2.pz) {
          _pz = ExpressionPropertyInterface(transform2.pz);
        }
      }
      Object.defineProperty(_thisFunction, "position", {
        get: function() {
          if (transform2.p) {
            return _transformFactory();
          }
          return [
            _px(),
            _py(),
            _pz ? _pz() : 0
          ];
        }
      });
      Object.defineProperty(_thisFunction, "xPosition", {
        get: ExpressionPropertyInterface(transform2.px)
      });
      Object.defineProperty(_thisFunction, "yPosition", {
        get: ExpressionPropertyInterface(transform2.py)
      });
      Object.defineProperty(_thisFunction, "zPosition", {
        get: ExpressionPropertyInterface(transform2.pz)
      });
      Object.defineProperty(_thisFunction, "anchorPoint", {
        get: ExpressionPropertyInterface(transform2.a)
      });
      Object.defineProperty(_thisFunction, "opacity", {
        get: ExpressionPropertyInterface(transform2.o)
      });
      Object.defineProperty(_thisFunction, "skew", {
        get: ExpressionPropertyInterface(transform2.sk)
      });
      Object.defineProperty(_thisFunction, "skewAxis", {
        get: ExpressionPropertyInterface(transform2.sa)
      });
      Object.defineProperty(_thisFunction, "orientation", {
        get: ExpressionPropertyInterface(transform2.or)
      });
      return _thisFunction;
    };
  }();
  const LayerExpressionInterface = /* @__PURE__ */ function() {
    function getMatrix(time2) {
      var toWorldMat = new Matrix();
      if (time2 !== void 0) {
        var propMatrix = this._elem.finalTransform.mProp.getValueAtTime(time2);
        propMatrix.clone(toWorldMat);
      } else {
        var transformMat = this._elem.finalTransform.mProp;
        transformMat.applyToMatrix(toWorldMat);
      }
      return toWorldMat;
    }
    function toWorldVec(arr, time2) {
      var toWorldMat = this.getMatrix(time2);
      toWorldMat.props[12] = 0;
      toWorldMat.props[13] = 0;
      toWorldMat.props[14] = 0;
      return this.applyPoint(toWorldMat, arr);
    }
    function toWorld2(arr, time2) {
      var toWorldMat = this.getMatrix(time2);
      return this.applyPoint(toWorldMat, arr);
    }
    function fromWorldVec(arr, time2) {
      var toWorldMat = this.getMatrix(time2);
      toWorldMat.props[12] = 0;
      toWorldMat.props[13] = 0;
      toWorldMat.props[14] = 0;
      return this.invertPoint(toWorldMat, arr);
    }
    function fromWorld2(arr, time2) {
      var toWorldMat = this.getMatrix(time2);
      return this.invertPoint(toWorldMat, arr);
    }
    function applyPoint(matrix2, arr) {
      if (this._elem.hierarchy && this._elem.hierarchy.length) {
        var i;
        var len = this._elem.hierarchy.length;
        for (i = 0; i < len; i += 1) {
          this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix2);
        }
      }
      return matrix2.applyToPointArray(arr[0], arr[1], arr[2] || 0);
    }
    function invertPoint(matrix2, arr) {
      if (this._elem.hierarchy && this._elem.hierarchy.length) {
        var i;
        var len = this._elem.hierarchy.length;
        for (i = 0; i < len; i += 1) {
          this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix2);
        }
      }
      return matrix2.inversePoint(arr);
    }
    function fromComp2(arr) {
      var toWorldMat = new Matrix();
      toWorldMat.reset();
      this._elem.finalTransform.mProp.applyToMatrix(toWorldMat);
      if (this._elem.hierarchy && this._elem.hierarchy.length) {
        var i;
        var len = this._elem.hierarchy.length;
        for (i = 0; i < len; i += 1) {
          this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(toWorldMat);
        }
        return toWorldMat.inversePoint(arr);
      }
      return toWorldMat.inversePoint(arr);
    }
    function sampleImage() {
      return [1, 1, 1, 1];
    }
    return function(elem2) {
      var transformInterface;
      function _registerMaskInterface(maskManager) {
        _thisLayerFunction.mask = new MaskManagerInterface(maskManager, elem2);
      }
      function _registerEffectsInterface(effects) {
        _thisLayerFunction.effect = effects;
      }
      function _thisLayerFunction(name2) {
        switch (name2) {
          case "ADBE Root Vectors Group":
          case "Contents":
          case 2:
            return _thisLayerFunction.shapeInterface;
          case 1:
          case 6:
          case "Transform":
          case "transform":
          case "ADBE Transform Group":
            return transformInterface;
          case 4:
          case "ADBE Effect Parade":
          case "effects":
          case "Effects":
            return _thisLayerFunction.effect;
          case "ADBE Text Properties":
            return _thisLayerFunction.textInterface;
          default:
            return null;
        }
      }
      _thisLayerFunction.getMatrix = getMatrix;
      _thisLayerFunction.invertPoint = invertPoint;
      _thisLayerFunction.applyPoint = applyPoint;
      _thisLayerFunction.toWorld = toWorld2;
      _thisLayerFunction.toWorldVec = toWorldVec;
      _thisLayerFunction.fromWorld = fromWorld2;
      _thisLayerFunction.fromWorldVec = fromWorldVec;
      _thisLayerFunction.toComp = toWorld2;
      _thisLayerFunction.fromComp = fromComp2;
      _thisLayerFunction.sampleImage = sampleImage;
      _thisLayerFunction.sourceRectAtTime = elem2.sourceRectAtTime.bind(elem2);
      _thisLayerFunction._elem = elem2;
      transformInterface = TransformExpressionInterface(elem2.finalTransform.mProp);
      var anchorPointDescriptor = getDescriptor(transformInterface, "anchorPoint");
      Object.defineProperties(_thisLayerFunction, {
        hasParent: {
          get: function() {
            return elem2.hierarchy.length;
          }
        },
        parent: {
          get: function() {
            return elem2.hierarchy[0].layerInterface;
          }
        },
        rotation: getDescriptor(transformInterface, "rotation"),
        scale: getDescriptor(transformInterface, "scale"),
        position: getDescriptor(transformInterface, "position"),
        opacity: getDescriptor(transformInterface, "opacity"),
        anchorPoint: anchorPointDescriptor,
        anchor_point: anchorPointDescriptor,
        transform: {
          get: function() {
            return transformInterface;
          }
        },
        active: {
          get: function() {
            return elem2.isInRange;
          }
        }
      });
      _thisLayerFunction.startTime = elem2.data.st;
      _thisLayerFunction.index = elem2.data.ind;
      _thisLayerFunction.source = elem2.data.refId;
      _thisLayerFunction.height = elem2.data.ty === 0 ? elem2.data.h : 100;
      _thisLayerFunction.width = elem2.data.ty === 0 ? elem2.data.w : 100;
      _thisLayerFunction.inPoint = elem2.data.ip / elem2.comp.globalData.frameRate;
      _thisLayerFunction.outPoint = elem2.data.op / elem2.comp.globalData.frameRate;
      _thisLayerFunction._name = elem2.data.nm;
      _thisLayerFunction.registerMaskInterface = _registerMaskInterface;
      _thisLayerFunction.registerEffectsInterface = _registerEffectsInterface;
      return _thisLayerFunction;
    };
  }();
  const propertyGroupFactory = /* @__PURE__ */ function() {
    return function(interfaceFunction, parentPropertyGroup) {
      return function(val2) {
        val2 = val2 === void 0 ? 1 : val2;
        if (val2 <= 0) {
          return interfaceFunction;
        }
        return parentPropertyGroup(val2 - 1);
      };
    };
  }();
  const PropertyInterface = /* @__PURE__ */ function() {
    return function(propertyName, propertyGroup) {
      var interfaceFunction = {
        _name: propertyName
      };
      function _propertyGroup(val2) {
        val2 = val2 === void 0 ? 1 : val2;
        if (val2 <= 0) {
          return interfaceFunction;
        }
        return propertyGroup(val2 - 1);
      }
      return _propertyGroup;
    };
  }();
  const EffectsExpressionInterface = /* @__PURE__ */ function() {
    var ob2 = {
      createEffectsInterface
    };
    function createEffectsInterface(elem2, propertyGroup) {
      if (elem2.effectsManager) {
        var effectElements = [];
        var effectsData = elem2.data.ef;
        var i;
        var len = elem2.effectsManager.effectElements.length;
        for (i = 0; i < len; i += 1) {
          effectElements.push(createGroupInterface(effectsData[i], elem2.effectsManager.effectElements[i], propertyGroup, elem2));
        }
        var effects = elem2.data.ef || [];
        var groupInterface = function(name2) {
          i = 0;
          len = effects.length;
          while (i < len) {
            if (name2 === effects[i].nm || name2 === effects[i].mn || name2 === effects[i].ix) {
              return effectElements[i];
            }
            i += 1;
          }
          return null;
        };
        Object.defineProperty(groupInterface, "numProperties", {
          get: function() {
            return effects.length;
          }
        });
        return groupInterface;
      }
      return null;
    }
    function createGroupInterface(data2, elements, propertyGroup, elem2) {
      function groupInterface(name2) {
        var effects = data2.ef;
        var i2 = 0;
        var len2 = effects.length;
        while (i2 < len2) {
          if (name2 === effects[i2].nm || name2 === effects[i2].mn || name2 === effects[i2].ix) {
            if (effects[i2].ty === 5) {
              return effectElements[i2];
            }
            return effectElements[i2]();
          }
          i2 += 1;
        }
        throw new Error();
      }
      var _propertyGroup = propertyGroupFactory(groupInterface, propertyGroup);
      var effectElements = [];
      var i;
      var len = data2.ef.length;
      for (i = 0; i < len; i += 1) {
        if (data2.ef[i].ty === 5) {
          effectElements.push(createGroupInterface(data2.ef[i], elements.effectElements[i], elements.effectElements[i].propertyGroup, elem2));
        } else {
          effectElements.push(createValueInterface(elements.effectElements[i], data2.ef[i].ty, elem2, _propertyGroup));
        }
      }
      if (data2.mn === "ADBE Color Control") {
        Object.defineProperty(groupInterface, "color", {
          get: function() {
            return effectElements[0]();
          }
        });
      }
      Object.defineProperties(groupInterface, {
        numProperties: {
          get: function() {
            return data2.np;
          }
        },
        _name: { value: data2.nm },
        propertyGroup: { value: _propertyGroup }
      });
      groupInterface.enabled = data2.en !== 0;
      groupInterface.active = groupInterface.enabled;
      return groupInterface;
    }
    function createValueInterface(element, type, elem2, propertyGroup) {
      var expressionProperty = ExpressionPropertyInterface(element.p);
      function interfaceFunction() {
        if (type === 10) {
          return elem2.comp.compInterface(element.p.v);
        }
        return expressionProperty();
      }
      if (element.p.setGroupProperty) {
        element.p.setGroupProperty(PropertyInterface("", propertyGroup));
      }
      return interfaceFunction;
    }
    return ob2;
  }();
  const CompExpressionInterface = /* @__PURE__ */ function() {
    return function(comp2) {
      function _thisLayerFunction(name2) {
        var i = 0;
        var len = comp2.layers.length;
        while (i < len) {
          if (comp2.layers[i].nm === name2 || comp2.layers[i].ind === name2) {
            return comp2.elements[i].layerInterface;
          }
          i += 1;
        }
        return null;
      }
      Object.defineProperty(_thisLayerFunction, "_name", { value: comp2.data.nm });
      _thisLayerFunction.layer = _thisLayerFunction;
      _thisLayerFunction.pixelAspect = 1;
      _thisLayerFunction.height = comp2.data.h || comp2.globalData.compSize.h;
      _thisLayerFunction.width = comp2.data.w || comp2.globalData.compSize.w;
      _thisLayerFunction.pixelAspect = 1;
      _thisLayerFunction.frameDuration = 1 / comp2.globalData.frameRate;
      _thisLayerFunction.displayStartTime = 0;
      _thisLayerFunction.numLayers = comp2.layers.length;
      return _thisLayerFunction;
    };
  }();
  const ShapePathInterface = /* @__PURE__ */ function() {
    return function pathInterfaceFactory(shape, view, propertyGroup) {
      var prop = view.sh;
      function interfaceFunction(val2) {
        if (val2 === "Shape" || val2 === "shape" || val2 === "Path" || val2 === "path" || val2 === "ADBE Vector Shape" || val2 === 2) {
          return interfaceFunction.path;
        }
        return null;
      }
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      prop.setGroupProperty(PropertyInterface("Path", _propertyGroup));
      Object.defineProperties(interfaceFunction, {
        path: {
          get: function() {
            if (prop.k) {
              prop.getValue();
            }
            return prop;
          }
        },
        shape: {
          get: function() {
            if (prop.k) {
              prop.getValue();
            }
            return prop;
          }
        },
        _name: { value: shape.nm },
        ix: { value: shape.ix },
        propertyIndex: { value: shape.ix },
        mn: { value: shape.mn },
        propertyGroup: { value: propertyGroup }
      });
      return interfaceFunction;
    };
  }();
  const ShapeExpressionInterface = /* @__PURE__ */ function() {
    function iterateElements(shapes, view, propertyGroup) {
      var arr = [];
      var i;
      var len = shapes ? shapes.length : 0;
      for (i = 0; i < len; i += 1) {
        if (shapes[i].ty === "gr") {
          arr.push(groupInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "fl") {
          arr.push(fillInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "st") {
          arr.push(strokeInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "tm") {
          arr.push(trimInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "tr") {
        } else if (shapes[i].ty === "el") {
          arr.push(ellipseInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "sr") {
          arr.push(starInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "sh") {
          arr.push(ShapePathInterface(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "rc") {
          arr.push(rectInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "rd") {
          arr.push(roundedInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "rp") {
          arr.push(repeaterInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else if (shapes[i].ty === "gf") {
          arr.push(gradientFillInterfaceFactory(shapes[i], view[i], propertyGroup));
        } else {
          arr.push(defaultInterfaceFactory(shapes[i], view[i], propertyGroup));
        }
      }
      return arr;
    }
    function contentsInterfaceFactory(shape, view, propertyGroup) {
      var interfaces;
      var interfaceFunction = function _interfaceFunction(value2) {
        var i = 0;
        var len = interfaces.length;
        while (i < len) {
          if (interfaces[i]._name === value2 || interfaces[i].mn === value2 || interfaces[i].propertyIndex === value2 || interfaces[i].ix === value2 || interfaces[i].ind === value2) {
            return interfaces[i];
          }
          i += 1;
        }
        if (typeof value2 === "number") {
          return interfaces[value2 - 1];
        }
        return null;
      };
      interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      interfaces = iterateElements(shape.it, view.it, interfaceFunction.propertyGroup);
      interfaceFunction.numProperties = interfaces.length;
      var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup);
      interfaceFunction.transform = transformInterface;
      interfaceFunction.propertyIndex = shape.cix;
      interfaceFunction._name = shape.nm;
      return interfaceFunction;
    }
    function groupInterfaceFactory(shape, view, propertyGroup) {
      var interfaceFunction = function _interfaceFunction(value2) {
        switch (value2) {
          case "ADBE Vectors Group":
          case "Contents":
          case 2:
            return interfaceFunction.content;
          // Not necessary for now. Keeping them here in case a new case appears
          // case 'ADBE Vector Transform Group':
          // case 3:
          default:
            return interfaceFunction.transform;
        }
      };
      interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      var content2 = contentsInterfaceFactory(shape, view, interfaceFunction.propertyGroup);
      var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup);
      interfaceFunction.content = content2;
      interfaceFunction.transform = transformInterface;
      Object.defineProperty(interfaceFunction, "_name", {
        get: function() {
          return shape.nm;
        }
      });
      interfaceFunction.numProperties = shape.np;
      interfaceFunction.propertyIndex = shape.ix;
      interfaceFunction.nm = shape.nm;
      interfaceFunction.mn = shape.mn;
      return interfaceFunction;
    }
    function fillInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(val2) {
        if (val2 === "Color" || val2 === "color") {
          return interfaceFunction.color;
        }
        if (val2 === "Opacity" || val2 === "opacity") {
          return interfaceFunction.opacity;
        }
        return null;
      }
      Object.defineProperties(interfaceFunction, {
        color: {
          get: ExpressionPropertyInterface(view.c)
        },
        opacity: {
          get: ExpressionPropertyInterface(view.o)
        },
        _name: { value: shape.nm },
        mn: { value: shape.mn }
      });
      view.c.setGroupProperty(PropertyInterface("Color", propertyGroup));
      view.o.setGroupProperty(PropertyInterface("Opacity", propertyGroup));
      return interfaceFunction;
    }
    function gradientFillInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(val2) {
        if (val2 === "Start Point" || val2 === "start point") {
          return interfaceFunction.startPoint;
        }
        if (val2 === "End Point" || val2 === "end point") {
          return interfaceFunction.endPoint;
        }
        if (val2 === "Opacity" || val2 === "opacity") {
          return interfaceFunction.opacity;
        }
        return null;
      }
      Object.defineProperties(interfaceFunction, {
        startPoint: {
          get: ExpressionPropertyInterface(view.s)
        },
        endPoint: {
          get: ExpressionPropertyInterface(view.e)
        },
        opacity: {
          get: ExpressionPropertyInterface(view.o)
        },
        type: {
          get: function() {
            return "a";
          }
        },
        _name: { value: shape.nm },
        mn: { value: shape.mn }
      });
      view.s.setGroupProperty(PropertyInterface("Start Point", propertyGroup));
      view.e.setGroupProperty(PropertyInterface("End Point", propertyGroup));
      view.o.setGroupProperty(PropertyInterface("Opacity", propertyGroup));
      return interfaceFunction;
    }
    function defaultInterfaceFactory() {
      function interfaceFunction() {
        return null;
      }
      return interfaceFunction;
    }
    function strokeInterfaceFactory(shape, view, propertyGroup) {
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      var _dashPropertyGroup = propertyGroupFactory(dashOb, _propertyGroup);
      function addPropertyToDashOb(i2) {
        Object.defineProperty(dashOb, shape.d[i2].nm, {
          get: ExpressionPropertyInterface(view.d.dataProps[i2].p)
        });
      }
      var i;
      var len = shape.d ? shape.d.length : 0;
      var dashOb = {};
      for (i = 0; i < len; i += 1) {
        addPropertyToDashOb(i);
        view.d.dataProps[i].p.setGroupProperty(_dashPropertyGroup);
      }
      function interfaceFunction(val2) {
        if (val2 === "Color" || val2 === "color") {
          return interfaceFunction.color;
        }
        if (val2 === "Opacity" || val2 === "opacity") {
          return interfaceFunction.opacity;
        }
        if (val2 === "Stroke Width" || val2 === "stroke width") {
          return interfaceFunction.strokeWidth;
        }
        return null;
      }
      Object.defineProperties(interfaceFunction, {
        color: {
          get: ExpressionPropertyInterface(view.c)
        },
        opacity: {
          get: ExpressionPropertyInterface(view.o)
        },
        strokeWidth: {
          get: ExpressionPropertyInterface(view.w)
        },
        dash: {
          get: function() {
            return dashOb;
          }
        },
        _name: { value: shape.nm },
        mn: { value: shape.mn }
      });
      view.c.setGroupProperty(PropertyInterface("Color", _propertyGroup));
      view.o.setGroupProperty(PropertyInterface("Opacity", _propertyGroup));
      view.w.setGroupProperty(PropertyInterface("Stroke Width", _propertyGroup));
      return interfaceFunction;
    }
    function trimInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(val2) {
        if (val2 === shape.e.ix || val2 === "End" || val2 === "end") {
          return interfaceFunction.end;
        }
        if (val2 === shape.s.ix) {
          return interfaceFunction.start;
        }
        if (val2 === shape.o.ix) {
          return interfaceFunction.offset;
        }
        return null;
      }
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      interfaceFunction.propertyIndex = shape.ix;
      view.s.setGroupProperty(PropertyInterface("Start", _propertyGroup));
      view.e.setGroupProperty(PropertyInterface("End", _propertyGroup));
      view.o.setGroupProperty(PropertyInterface("Offset", _propertyGroup));
      interfaceFunction.propertyIndex = shape.ix;
      interfaceFunction.propertyGroup = propertyGroup;
      Object.defineProperties(interfaceFunction, {
        start: {
          get: ExpressionPropertyInterface(view.s)
        },
        end: {
          get: ExpressionPropertyInterface(view.e)
        },
        offset: {
          get: ExpressionPropertyInterface(view.o)
        },
        _name: { value: shape.nm }
      });
      interfaceFunction.mn = shape.mn;
      return interfaceFunction;
    }
    function transformInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(value2) {
        if (shape.a.ix === value2 || value2 === "Anchor Point") {
          return interfaceFunction.anchorPoint;
        }
        if (shape.o.ix === value2 || value2 === "Opacity") {
          return interfaceFunction.opacity;
        }
        if (shape.p.ix === value2 || value2 === "Position") {
          return interfaceFunction.position;
        }
        if (shape.r.ix === value2 || value2 === "Rotation" || value2 === "ADBE Vector Rotation") {
          return interfaceFunction.rotation;
        }
        if (shape.s.ix === value2 || value2 === "Scale") {
          return interfaceFunction.scale;
        }
        if (shape.sk && shape.sk.ix === value2 || value2 === "Skew") {
          return interfaceFunction.skew;
        }
        if (shape.sa && shape.sa.ix === value2 || value2 === "Skew Axis") {
          return interfaceFunction.skewAxis;
        }
        return null;
      }
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      view.transform.mProps.o.setGroupProperty(PropertyInterface("Opacity", _propertyGroup));
      view.transform.mProps.p.setGroupProperty(PropertyInterface("Position", _propertyGroup));
      view.transform.mProps.a.setGroupProperty(PropertyInterface("Anchor Point", _propertyGroup));
      view.transform.mProps.s.setGroupProperty(PropertyInterface("Scale", _propertyGroup));
      view.transform.mProps.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup));
      if (view.transform.mProps.sk) {
        view.transform.mProps.sk.setGroupProperty(PropertyInterface("Skew", _propertyGroup));
        view.transform.mProps.sa.setGroupProperty(PropertyInterface("Skew Angle", _propertyGroup));
      }
      view.transform.op.setGroupProperty(PropertyInterface("Opacity", _propertyGroup));
      Object.defineProperties(interfaceFunction, {
        opacity: {
          get: ExpressionPropertyInterface(view.transform.mProps.o)
        },
        position: {
          get: ExpressionPropertyInterface(view.transform.mProps.p)
        },
        anchorPoint: {
          get: ExpressionPropertyInterface(view.transform.mProps.a)
        },
        scale: {
          get: ExpressionPropertyInterface(view.transform.mProps.s)
        },
        rotation: {
          get: ExpressionPropertyInterface(view.transform.mProps.r)
        },
        skew: {
          get: ExpressionPropertyInterface(view.transform.mProps.sk)
        },
        skewAxis: {
          get: ExpressionPropertyInterface(view.transform.mProps.sa)
        },
        _name: { value: shape.nm }
      });
      interfaceFunction.ty = "tr";
      interfaceFunction.mn = shape.mn;
      interfaceFunction.propertyGroup = propertyGroup;
      return interfaceFunction;
    }
    function ellipseInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(value2) {
        if (shape.p.ix === value2) {
          return interfaceFunction.position;
        }
        if (shape.s.ix === value2) {
          return interfaceFunction.size;
        }
        return null;
      }
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      interfaceFunction.propertyIndex = shape.ix;
      var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh;
      prop.s.setGroupProperty(PropertyInterface("Size", _propertyGroup));
      prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup));
      Object.defineProperties(interfaceFunction, {
        size: {
          get: ExpressionPropertyInterface(prop.s)
        },
        position: {
          get: ExpressionPropertyInterface(prop.p)
        },
        _name: { value: shape.nm }
      });
      interfaceFunction.mn = shape.mn;
      return interfaceFunction;
    }
    function starInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(value2) {
        if (shape.p.ix === value2) {
          return interfaceFunction.position;
        }
        if (shape.r.ix === value2) {
          return interfaceFunction.rotation;
        }
        if (shape.pt.ix === value2) {
          return interfaceFunction.points;
        }
        if (shape.or.ix === value2 || value2 === "ADBE Vector Star Outer Radius") {
          return interfaceFunction.outerRadius;
        }
        if (shape.os.ix === value2) {
          return interfaceFunction.outerRoundness;
        }
        if (shape.ir && (shape.ir.ix === value2 || value2 === "ADBE Vector Star Inner Radius")) {
          return interfaceFunction.innerRadius;
        }
        if (shape.is && shape.is.ix === value2) {
          return interfaceFunction.innerRoundness;
        }
        return null;
      }
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh;
      interfaceFunction.propertyIndex = shape.ix;
      prop.or.setGroupProperty(PropertyInterface("Outer Radius", _propertyGroup));
      prop.os.setGroupProperty(PropertyInterface("Outer Roundness", _propertyGroup));
      prop.pt.setGroupProperty(PropertyInterface("Points", _propertyGroup));
      prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup));
      prop.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup));
      if (shape.ir) {
        prop.ir.setGroupProperty(PropertyInterface("Inner Radius", _propertyGroup));
        prop.is.setGroupProperty(PropertyInterface("Inner Roundness", _propertyGroup));
      }
      Object.defineProperties(interfaceFunction, {
        position: {
          get: ExpressionPropertyInterface(prop.p)
        },
        rotation: {
          get: ExpressionPropertyInterface(prop.r)
        },
        points: {
          get: ExpressionPropertyInterface(prop.pt)
        },
        outerRadius: {
          get: ExpressionPropertyInterface(prop.or)
        },
        outerRoundness: {
          get: ExpressionPropertyInterface(prop.os)
        },
        innerRadius: {
          get: ExpressionPropertyInterface(prop.ir)
        },
        innerRoundness: {
          get: ExpressionPropertyInterface(prop.is)
        },
        _name: { value: shape.nm }
      });
      interfaceFunction.mn = shape.mn;
      return interfaceFunction;
    }
    function rectInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(value2) {
        if (shape.p.ix === value2) {
          return interfaceFunction.position;
        }
        if (shape.r.ix === value2) {
          return interfaceFunction.roundness;
        }
        if (shape.s.ix === value2 || value2 === "Size" || value2 === "ADBE Vector Rect Size") {
          return interfaceFunction.size;
        }
        return null;
      }
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh;
      interfaceFunction.propertyIndex = shape.ix;
      prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup));
      prop.s.setGroupProperty(PropertyInterface("Size", _propertyGroup));
      prop.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup));
      Object.defineProperties(interfaceFunction, {
        position: {
          get: ExpressionPropertyInterface(prop.p)
        },
        roundness: {
          get: ExpressionPropertyInterface(prop.r)
        },
        size: {
          get: ExpressionPropertyInterface(prop.s)
        },
        _name: { value: shape.nm }
      });
      interfaceFunction.mn = shape.mn;
      return interfaceFunction;
    }
    function roundedInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(value2) {
        if (shape.r.ix === value2 || value2 === "Round Corners 1") {
          return interfaceFunction.radius;
        }
        return null;
      }
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      var prop = view;
      interfaceFunction.propertyIndex = shape.ix;
      prop.rd.setGroupProperty(PropertyInterface("Radius", _propertyGroup));
      Object.defineProperties(interfaceFunction, {
        radius: {
          get: ExpressionPropertyInterface(prop.rd)
        },
        _name: { value: shape.nm }
      });
      interfaceFunction.mn = shape.mn;
      return interfaceFunction;
    }
    function repeaterInterfaceFactory(shape, view, propertyGroup) {
      function interfaceFunction(value2) {
        if (shape.c.ix === value2 || value2 === "Copies") {
          return interfaceFunction.copies;
        }
        if (shape.o.ix === value2 || value2 === "Offset") {
          return interfaceFunction.offset;
        }
        return null;
      }
      var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup);
      var prop = view;
      interfaceFunction.propertyIndex = shape.ix;
      prop.c.setGroupProperty(PropertyInterface("Copies", _propertyGroup));
      prop.o.setGroupProperty(PropertyInterface("Offset", _propertyGroup));
      Object.defineProperties(interfaceFunction, {
        copies: {
          get: ExpressionPropertyInterface(prop.c)
        },
        offset: {
          get: ExpressionPropertyInterface(prop.o)
        },
        _name: { value: shape.nm }
      });
      interfaceFunction.mn = shape.mn;
      return interfaceFunction;
    }
    return function(shapes, view, propertyGroup) {
      var interfaces;
      function _interfaceFunction(value2) {
        if (typeof value2 === "number") {
          value2 = value2 === void 0 ? 1 : value2;
          if (value2 === 0) {
            return propertyGroup;
          }
          return interfaces[value2 - 1];
        }
        var i = 0;
        var len = interfaces.length;
        while (i < len) {
          if (interfaces[i]._name === value2) {
            return interfaces[i];
          }
          i += 1;
        }
        return null;
      }
      function parentGroupWrapper() {
        return propertyGroup;
      }
      _interfaceFunction.propertyGroup = propertyGroupFactory(_interfaceFunction, parentGroupWrapper);
      interfaces = iterateElements(shapes, view, _interfaceFunction.propertyGroup);
      _interfaceFunction.numProperties = interfaces.length;
      _interfaceFunction._name = "Contents";
      return _interfaceFunction;
    };
  }();
  const TextExpressionInterface = /* @__PURE__ */ function() {
    return function(elem2) {
      var _prevValue;
      var _sourceText;
      function _thisLayerFunction(name2) {
        switch (name2) {
          case "ADBE Text Document":
            return _thisLayerFunction.sourceText;
          default:
            return null;
        }
      }
      Object.defineProperty(_thisLayerFunction, "sourceText", {
        get: function() {
          elem2.textProperty.getValue();
          var stringValue = elem2.textProperty.currentData.t;
          if (stringValue !== _prevValue) {
            elem2.textProperty.currentData.t = _prevValue;
            _sourceText = new String(stringValue);
            _sourceText.value = stringValue || new String(stringValue);
          }
          return _sourceText;
        }
      });
      return _thisLayerFunction;
    };
  }();
  const getBlendMode = /* @__PURE__ */ function() {
    var blendModeEnums = {
      0: "source-over",
      1: "multiply",
      2: "screen",
      3: "overlay",
      4: "darken",
      5: "lighten",
      6: "color-dodge",
      7: "color-burn",
      8: "hard-light",
      9: "soft-light",
      10: "difference",
      11: "exclusion",
      12: "hue",
      13: "saturation",
      14: "color",
      15: "luminosity"
    };
    return function(mode) {
      return blendModeEnums[mode] || "";
    };
  }();
  extendPrototype([DynamicPropertyContainer], GroupEffect);
  GroupEffect.prototype.getValue = GroupEffect.prototype.iterateDynamicProperties;
  GroupEffect.prototype.init = function(data2, element) {
    this.data = data2;
    this.effectElements = [];
    this.initDynamicPropertyContainer(element);
    var i;
    var len = this.data.ef.length;
    var eff;
    var effects = this.data.ef;
    for (i = 0; i < len; i += 1) {
      eff = null;
      switch (effects[i].ty) {
        case 0:
          eff = new SliderEffect(effects[i], element, this);
          break;
        case 1:
          eff = new AngleEffect(effects[i], element, this);
          break;
        case 2:
          eff = new ColorEffect(effects[i], element, this);
          break;
        case 3:
          eff = new PointEffect(effects[i], element, this);
          break;
        case 4:
        case 7:
          eff = new CheckboxEffect(effects[i], element, this);
          break;
        case 10:
          eff = new LayerIndexEffect(effects[i], element, this);
          break;
        case 11:
          eff = new MaskIndexEffect(effects[i], element, this);
          break;
        case 5:
          eff = new EffectsManager(effects[i], element, this);
          break;
        // case 6:
        default:
          eff = new NoValueEffect(effects[i], element, this);
          break;
      }
      if (eff) {
        this.effectElements.push(eff);
      }
    }
  };
  BaseElement.prototype = {
    checkMasks: function() {
      if (!this.data.hasMask) {
        return false;
      }
      var i = 0;
      var len = this.data.masksProperties.length;
      while (i < len) {
        if (this.data.masksProperties[i].mode !== "n" && this.data.masksProperties[i].cl !== false) {
          return true;
        }
        i += 1;
      }
      return false;
    },
    initExpressions: function() {
      this.layerInterface = LayerExpressionInterface(this);
      if (this.data.hasMask && this.maskManager) {
        this.layerInterface.registerMaskInterface(this.maskManager);
      }
      var effectsInterface = EffectsExpressionInterface.createEffectsInterface(this, this.layerInterface);
      this.layerInterface.registerEffectsInterface(effectsInterface);
      if (this.data.ty === 0 || this.data.xt) {
        this.compInterface = CompExpressionInterface(this);
      } else if (this.data.ty === 4) {
        this.layerInterface.shapeInterface = ShapeExpressionInterface(this.shapesData, this.itemsData, this.layerInterface);
        this.layerInterface.content = this.layerInterface.shapeInterface;
      } else if (this.data.ty === 5) {
        this.layerInterface.textInterface = TextExpressionInterface(this);
        this.layerInterface.text = this.layerInterface.textInterface;
      }
    },
    setBlendMode: function() {
      var blendModeValue = getBlendMode(this.data.bm);
      var elem2 = this.baseElement || this.layerElement;
      elem2.style["mix-blend-mode"] = blendModeValue;
    },
    initBaseData: function(data2, globalData2, comp2) {
      this.globalData = globalData2;
      this.comp = comp2;
      this.data = data2;
      this.layerId = createElementID();
      if (!this.data.sr) {
        this.data.sr = 1;
      }
      this.effectsManager = new EffectsManager(this.data, this, this.dynamicProperties);
    },
    getType: function() {
      return this.type;
    },
    sourceRectAtTime: function() {
    }
  };
  FrameElement.prototype = {
    /**
       * @function
       * Initializes frame related properties.
       *
       */
    initFrame: function() {
      this._isFirstFrame = false;
      this.dynamicProperties = [];
      this._mdf = false;
    },
    /**
       * @function
       * Calculates all dynamic values
       *
       * @param {number} num
       * current frame number in Layer's time
       * @param {boolean} isVisible
       * if layers is currently in range
       *
       */
    prepareProperties: function(num, isVisible) {
      var i;
      var len = this.dynamicProperties.length;
      for (i = 0; i < len; i += 1) {
        if (isVisible || this._isParent && this.dynamicProperties[i].propType === "transform") {
          this.dynamicProperties[i].getValue();
          if (this.dynamicProperties[i]._mdf) {
            this.globalData._mdf = true;
            this._mdf = true;
          }
        }
      }
    },
    addDynamicProperty: function(prop) {
      if (this.dynamicProperties.indexOf(prop) === -1) {
        this.dynamicProperties.push(prop);
      }
    }
  };
  const FootageInterface = /* @__PURE__ */ function() {
    var outlineInterfaceFactory = function(elem2) {
      var currentPropertyName = "";
      var currentProperty = elem2.getFootageData();
      function init() {
        currentPropertyName = "";
        currentProperty = elem2.getFootageData();
        return searchProperty;
      }
      function searchProperty(value2) {
        if (currentProperty[value2]) {
          currentPropertyName = value2;
          currentProperty = currentProperty[value2];
          if (typeof currentProperty === "object") {
            return searchProperty;
          }
          return currentProperty;
        }
        var propertyNameIndex = value2.indexOf(currentPropertyName);
        if (propertyNameIndex !== -1) {
          var index2 = parseInt(value2.substr(propertyNameIndex + currentPropertyName.length), 10);
          currentProperty = currentProperty[index2];
          if (typeof currentProperty === "object") {
            return searchProperty;
          }
          return currentProperty;
        }
        return "";
      }
      return init;
    };
    var dataInterfaceFactory = function(elem2) {
      function interfaceFunction(value2) {
        if (value2 === "Outline") {
          return interfaceFunction.outlineInterface();
        }
        return null;
      }
      interfaceFunction._name = "Outline";
      interfaceFunction.outlineInterface = outlineInterfaceFactory(elem2);
      return interfaceFunction;
    };
    return function(elem2) {
      function _interfaceFunction(value2) {
        if (value2 === "Data") {
          return _interfaceFunction.dataInterface;
        }
        return null;
      }
      _interfaceFunction._name = "Data";
      _interfaceFunction.dataInterface = dataInterfaceFactory(elem2);
      return _interfaceFunction;
    };
  }();
  FootageElement.prototype.prepareFrame = function() {
  };
  extendPrototype([RenderableElement, BaseElement, FrameElement], FootageElement);
  FootageElement.prototype.getBaseElement = function() {
    return null;
  };
  FootageElement.prototype.renderFrame = function() {
  };
  FootageElement.prototype.destroy = function() {
  };
  FootageElement.prototype.initExpressions = function() {
    this.layerInterface = FootageInterface(this);
  };
  FootageElement.prototype.getFootageData = function() {
    return this.footageData;
  };
  AudioElement.prototype.prepareFrame = function(num) {
    this.prepareRenderableFrame(num, true);
    this.prepareProperties(num, true);
    if (!this.tm._placeholder) {
      var timeRemapped = this.tm.v;
      this._currentTime = timeRemapped;
    } else {
      this._currentTime = num / this.data.sr;
    }
    this._volume = this.lv.v[0];
    var totalVolume = this._volume * this._volumeMultiplier;
    if (this._previousVolume !== totalVolume) {
      this._previousVolume = totalVolume;
      this.audio.volume(totalVolume);
    }
  };
  extendPrototype([RenderableElement, BaseElement, FrameElement], AudioElement);
  AudioElement.prototype.renderFrame = function() {
    if (this.isInRange && this._canPlay) {
      if (!this._isPlaying) {
        this.audio.play();
        this.audio.seek(this._currentTime / this.globalData.frameRate);
        this._isPlaying = true;
      } else if (!this.audio.playing() || Math.abs(this._currentTime / this.globalData.frameRate - this.audio.seek()) > 0.1) {
        this.audio.seek(this._currentTime / this.globalData.frameRate);
      }
    }
  };
  AudioElement.prototype.show = function() {
  };
  AudioElement.prototype.hide = function() {
    this.audio.pause();
    this._isPlaying = false;
  };
  AudioElement.prototype.pause = function() {
    this.audio.pause();
    this._isPlaying = false;
    this._canPlay = false;
  };
  AudioElement.prototype.resume = function() {
    this._canPlay = true;
  };
  AudioElement.prototype.setRate = function(rateValue) {
    this.audio.rate(rateValue);
  };
  AudioElement.prototype.volume = function(volumeValue) {
    this._volumeMultiplier = volumeValue;
    this._previousVolume = volumeValue * this._volume;
    this.audio.volume(this._previousVolume);
  };
  AudioElement.prototype.getBaseElement = function() {
    return null;
  };
  AudioElement.prototype.destroy = function() {
  };
  AudioElement.prototype.sourceRectAtTime = function() {
  };
  AudioElement.prototype.initExpressions = function() {
  };
  BaseRenderer.prototype.checkLayers = function(num) {
    var i;
    var len = this.layers.length;
    var data2;
    this.completeLayers = true;
    for (i = len - 1; i >= 0; i -= 1) {
      if (!this.elements[i]) {
        data2 = this.layers[i];
        if (data2.ip - data2.st <= num - this.layers[i].st && data2.op - data2.st > num - this.layers[i].st) {
          this.buildItem(i);
        }
      }
      this.completeLayers = this.elements[i] ? this.completeLayers : false;
    }
    this.checkPendingElements();
  };
  BaseRenderer.prototype.createItem = function(layer) {
    switch (layer.ty) {
      case 2:
        return this.createImage(layer);
      case 0:
        return this.createComp(layer);
      case 1:
        return this.createSolid(layer);
      case 3:
        return this.createNull(layer);
      case 4:
        return this.createShape(layer);
      case 5:
        return this.createText(layer);
      case 6:
        return this.createAudio(layer);
      case 13:
        return this.createCamera(layer);
      case 15:
        return this.createFootage(layer);
      default:
        return this.createNull(layer);
    }
  };
  BaseRenderer.prototype.createCamera = function() {
    throw new Error("You're using a 3d camera. Try the html renderer.");
  };
  BaseRenderer.prototype.createAudio = function(data2) {
    return new AudioElement(data2, this.globalData, this);
  };
  BaseRenderer.prototype.createFootage = function(data2) {
    return new FootageElement(data2, this.globalData, this);
  };
  BaseRenderer.prototype.buildAllItems = function() {
    var i;
    var len = this.layers.length;
    for (i = 0; i < len; i += 1) {
      this.buildItem(i);
    }
    this.checkPendingElements();
  };
  BaseRenderer.prototype.includeLayers = function(newLayers) {
    this.completeLayers = false;
    var i;
    var len = newLayers.length;
    var j2;
    var jLen = this.layers.length;
    for (i = 0; i < len; i += 1) {
      j2 = 0;
      while (j2 < jLen) {
        if (this.layers[j2].id === newLayers[i].id) {
          this.layers[j2] = newLayers[i];
          break;
        }
        j2 += 1;
      }
    }
  };
  BaseRenderer.prototype.setProjectInterface = function(pInterface) {
    this.globalData.projectInterface = pInterface;
  };
  BaseRenderer.prototype.initItems = function() {
    if (!this.globalData.progressiveLoad) {
      this.buildAllItems();
    }
  };
  BaseRenderer.prototype.buildElementParenting = function(element, parentName, hierarchy) {
    var elements = this.elements;
    var layers = this.layers;
    var i = 0;
    var len = layers.length;
    while (i < len) {
      if (layers[i].ind == parentName) {
        if (!elements[i] || elements[i] === true) {
          this.buildItem(i);
          this.addPendingElement(element);
        } else {
          hierarchy.push(elements[i]);
          elements[i].setAsParent();
          if (layers[i].parent !== void 0) {
            this.buildElementParenting(element, layers[i].parent, hierarchy);
          } else {
            element.setHierarchy(hierarchy);
          }
        }
      }
      i += 1;
    }
  };
  BaseRenderer.prototype.addPendingElement = function(element) {
    this.pendingElements.push(element);
  };
  BaseRenderer.prototype.searchExtraCompositions = function(assets) {
    var i;
    var len = assets.length;
    for (i = 0; i < len; i += 1) {
      if (assets[i].xt) {
        var comp2 = this.createComp(assets[i]);
        comp2.initExpressions();
        this.globalData.projectInterface.registerComposition(comp2);
      }
    }
  };
  BaseRenderer.prototype.getElementByPath = function(path) {
    var pathValue = path.shift();
    var element;
    if (typeof pathValue === "number") {
      element = this.elements[pathValue];
    } else {
      var i;
      var len = this.elements.length;
      for (i = 0; i < len; i += 1) {
        if (this.elements[i].data.nm === pathValue) {
          element = this.elements[i];
          break;
        }
      }
    }
    if (path.length === 0) {
      return element;
    }
    return element.getElementByPath(path);
  };
  BaseRenderer.prototype.setupGlobalData = function(animData, fontsContainer) {
    this.globalData.fontManager = new FontManager();
    this.globalData.fontManager.addChars(animData.chars);
    this.globalData.fontManager.addFonts(animData.fonts, fontsContainer);
    this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem);
    this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem);
    this.globalData.imageLoader = this.animationItem.imagePreloader;
    this.globalData.audioController = this.animationItem.audioController;
    this.globalData.frameId = 0;
    this.globalData.frameRate = animData.fr;
    this.globalData.nm = animData.nm;
    this.globalData.compSize = {
      w: animData.w,
      h: animData.h
    };
  };
  TransformElement.prototype = {
    initTransform: function() {
      this.finalTransform = {
        mProp: this.data.ks ? TransformPropertyFactory.getTransformProperty(this, this.data.ks, this) : { o: 0 },
        _matMdf: false,
        _opMdf: false,
        mat: new Matrix()
      };
      if (this.data.ao) {
        this.finalTransform.mProp.autoOriented = true;
      }
      if (this.data.ty !== 11) {
      }
    },
    renderTransform: function() {
      this.finalTransform._opMdf = this.finalTransform.mProp.o._mdf || this._isFirstFrame;
      this.finalTransform._matMdf = this.finalTransform.mProp._mdf || this._isFirstFrame;
      if (this.hierarchy) {
        var mat;
        var finalMat = this.finalTransform.mat;
        var i = 0;
        var len = this.hierarchy.length;
        if (!this.finalTransform._matMdf) {
          while (i < len) {
            if (this.hierarchy[i].finalTransform.mProp._mdf) {
              this.finalTransform._matMdf = true;
              break;
            }
            i += 1;
          }
        }
        if (this.finalTransform._matMdf) {
          mat = this.finalTransform.mProp.v.props;
          finalMat.cloneFromProps(mat);
          for (i = 0; i < len; i += 1) {
            mat = this.hierarchy[i].finalTransform.mProp.v.props;
            finalMat.transform(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15]);
          }
        }
      }
    },
    globalToLocal: function(pt) {
      var transforms = [];
      transforms.push(this.finalTransform);
      var flag = true;
      var comp2 = this.comp;
      while (flag) {
        if (comp2.finalTransform) {
          if (comp2.data.hasMask) {
            transforms.splice(0, 0, comp2.finalTransform);
          }
          comp2 = comp2.comp;
        } else {
          flag = false;
        }
      }
      var i;
      var len = transforms.length;
      var ptNew;
      for (i = 0; i < len; i += 1) {
        ptNew = transforms[i].mat.applyToPointArray(0, 0, 0);
        pt = [pt[0] - ptNew[0], pt[1] - ptNew[1], 0];
      }
      return pt;
    },
    mHelper: new Matrix()
  };
  MaskElement.prototype.getMaskProperty = function(pos) {
    return this.viewData[pos].prop;
  };
  MaskElement.prototype.renderFrame = function(isFirstFrame) {
    var finalMat = this.element.finalTransform.mat;
    var i;
    var len = this.masksProperties.length;
    for (i = 0; i < len; i += 1) {
      if (this.viewData[i].prop._mdf || isFirstFrame) {
        this.drawPath(this.masksProperties[i], this.viewData[i].prop.v, this.viewData[i]);
      }
      if (this.viewData[i].op._mdf || isFirstFrame) {
        this.viewData[i].elem.setAttribute("fill-opacity", this.viewData[i].op.v);
      }
      if (this.masksProperties[i].mode !== "n") {
        if (this.viewData[i].invRect && (this.element.finalTransform.mProp._mdf || isFirstFrame)) {
          this.viewData[i].invRect.setAttribute("transform", finalMat.getInverseMatrix().to2dCSS());
        }
        if (this.storedData[i].x && (this.storedData[i].x._mdf || isFirstFrame)) {
          var feMorph = this.storedData[i].expan;
          if (this.storedData[i].x.v < 0) {
            if (this.storedData[i].lastOperator !== "erode") {
              this.storedData[i].lastOperator = "erode";
              this.storedData[i].elem.setAttribute("filter", "url(" + getLocationHref() + "#" + this.storedData[i].filterId + ")");
            }
            feMorph.setAttribute("radius", -this.storedData[i].x.v);
          } else {
            if (this.storedData[i].lastOperator !== "dilate") {
              this.storedData[i].lastOperator = "dilate";
              this.storedData[i].elem.setAttribute("filter", null);
            }
            this.storedData[i].elem.setAttribute("stroke-width", this.storedData[i].x.v * 2);
          }
        }
      }
    }
  };
  MaskElement.prototype.getMaskelement = function() {
    return this.maskElement;
  };
  MaskElement.prototype.createLayerSolidPath = function() {
    var path = "M0,0 ";
    path += " h" + this.globalData.compSize.w;
    path += " v" + this.globalData.compSize.h;
    path += " h-" + this.globalData.compSize.w;
    path += " v-" + this.globalData.compSize.h + " ";
    return path;
  };
  MaskElement.prototype.drawPath = function(pathData, pathNodes, viewData) {
    var pathString = " M" + pathNodes.v[0][0] + "," + pathNodes.v[0][1];
    var i;
    var len;
    len = pathNodes._length;
    for (i = 1; i < len; i += 1) {
      pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[i][0] + "," + pathNodes.i[i][1] + " " + pathNodes.v[i][0] + "," + pathNodes.v[i][1];
    }
    if (pathNodes.c && len > 1) {
      pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[0][0] + "," + pathNodes.i[0][1] + " " + pathNodes.v[0][0] + "," + pathNodes.v[0][1];
    }
    if (viewData.lastPath !== pathString) {
      var pathShapeValue = "";
      if (viewData.elem) {
        if (pathNodes.c) {
          pathShapeValue = pathData.inv ? this.solidPath + pathString : pathString;
        }
        viewData.elem.setAttribute("d", pathShapeValue);
      }
      viewData.lastPath = pathString;
    }
  };
  MaskElement.prototype.destroy = function() {
    this.element = null;
    this.globalData = null;
    this.maskElement = null;
    this.data = null;
    this.masksProperties = null;
  };
  const filtersFactory = function() {
    var ob2 = {};
    ob2.createFilter = createFilter;
    ob2.createAlphaToLuminanceFilter = createAlphaToLuminanceFilter;
    function createFilter(filId, skipCoordinates) {
      var fil = createNS("filter");
      fil.setAttribute("id", filId);
      if (skipCoordinates !== true) {
        fil.setAttribute("filterUnits", "objectBoundingBox");
        fil.setAttribute("x", "0%");
        fil.setAttribute("y", "0%");
        fil.setAttribute("width", "100%");
        fil.setAttribute("height", "100%");
      }
      return fil;
    }
    function createAlphaToLuminanceFilter() {
      var feColorMatrix = createNS("feColorMatrix");
      feColorMatrix.setAttribute("type", "matrix");
      feColorMatrix.setAttribute("color-interpolation-filters", "sRGB");
      feColorMatrix.setAttribute("values", "0 0 0 1 0  0 0 0 1 0  0 0 0 1 0  0 0 0 1 1");
      return feColorMatrix;
    }
    return ob2;
  }();
  const featureSupport = function() {
    var ob2 = {
      maskType: true
    };
    if (/MSIE 10/i.test(navigator.userAgent) || /MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent) || /Edge\/\d./i.test(navigator.userAgent)) {
      ob2.maskType = false;
    }
    return ob2;
  }();
  registeredEffects = {};
  idPrefix = "filter_result_";
  SVGEffects.prototype.renderFrame = function(_isFirstFrame) {
    var i;
    var len = this.filters.length;
    for (i = 0; i < len; i += 1) {
      this.filters[i].renderFrame(_isFirstFrame);
    }
  };
  SVGBaseElement.prototype = {
    initRendererElement: function() {
      this.layerElement = createNS("g");
    },
    createContainerElements: function() {
      this.matteElement = createNS("g");
      this.transformedElement = this.layerElement;
      this.maskedElement = this.layerElement;
      this._sizeChanged = false;
      var layerElementParent = null;
      var filId;
      var fil;
      var gg;
      if (this.data.td) {
        if (this.data.td == 3 || this.data.td == 1) {
          var masker = createNS("mask");
          masker.setAttribute("id", this.layerId);
          masker.setAttribute("mask-type", this.data.td == 3 ? "luminance" : "alpha");
          masker.appendChild(this.layerElement);
          layerElementParent = masker;
          this.globalData.defs.appendChild(masker);
          if (!featureSupport.maskType && this.data.td == 1) {
            masker.setAttribute("mask-type", "luminance");
            filId = createElementID();
            fil = filtersFactory.createFilter(filId);
            this.globalData.defs.appendChild(fil);
            fil.appendChild(filtersFactory.createAlphaToLuminanceFilter());
            gg = createNS("g");
            gg.appendChild(this.layerElement);
            layerElementParent = gg;
            masker.appendChild(gg);
            gg.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")");
          }
        } else if (this.data.td == 2) {
          var maskGroup = createNS("mask");
          maskGroup.setAttribute("id", this.layerId);
          maskGroup.setAttribute("mask-type", "alpha");
          var maskGrouper = createNS("g");
          maskGroup.appendChild(maskGrouper);
          filId = createElementID();
          fil = filtersFactory.createFilter(filId);
          var feCTr = createNS("feComponentTransfer");
          feCTr.setAttribute("in", "SourceGraphic");
          fil.appendChild(feCTr);
          var feFunc = createNS("feFuncA");
          feFunc.setAttribute("type", "table");
          feFunc.setAttribute("tableValues", "1.0 0.0");
          feCTr.appendChild(feFunc);
          this.globalData.defs.appendChild(fil);
          var alphaRect = createNS("rect");
          alphaRect.setAttribute("width", this.comp.data.w);
          alphaRect.setAttribute("height", this.comp.data.h);
          alphaRect.setAttribute("x", "0");
          alphaRect.setAttribute("y", "0");
          alphaRect.setAttribute("fill", "#ffffff");
          alphaRect.setAttribute("opacity", "0");
          maskGrouper.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")");
          maskGrouper.appendChild(alphaRect);
          maskGrouper.appendChild(this.layerElement);
          layerElementParent = maskGrouper;
          if (!featureSupport.maskType) {
            maskGroup.setAttribute("mask-type", "luminance");
            fil.appendChild(filtersFactory.createAlphaToLuminanceFilter());
            gg = createNS("g");
            maskGrouper.appendChild(alphaRect);
            gg.appendChild(this.layerElement);
            layerElementParent = gg;
            maskGrouper.appendChild(gg);
          }
          this.globalData.defs.appendChild(maskGroup);
        }
      } else if (this.data.tt) {
        this.matteElement.appendChild(this.layerElement);
        layerElementParent = this.matteElement;
        this.baseElement = this.matteElement;
      } else {
        this.baseElement = this.layerElement;
      }
      if (this.data.ln) {
        this.layerElement.setAttribute("id", this.data.ln);
      }
      if (this.data.cl) {
        this.layerElement.setAttribute("class", this.data.cl);
      }
      if (this.data.ty === 0 && !this.data.hd) {
        var cp = createNS("clipPath");
        var pt = createNS("path");
        pt.setAttribute("d", "M0,0 L" + this.data.w + ",0 L" + this.data.w + "," + this.data.h + " L0," + this.data.h + "z");
        var clipId = createElementID();
        cp.setAttribute("id", clipId);
        cp.appendChild(pt);
        this.globalData.defs.appendChild(cp);
        if (this.checkMasks()) {
          var cpGroup = createNS("g");
          cpGroup.setAttribute("clip-path", "url(" + getLocationHref() + "#" + clipId + ")");
          cpGroup.appendChild(this.layerElement);
          this.transformedElement = cpGroup;
          if (layerElementParent) {
            layerElementParent.appendChild(this.transformedElement);
          } else {
            this.baseElement = this.transformedElement;
          }
        } else {
          this.layerElement.setAttribute("clip-path", "url(" + getLocationHref() + "#" + clipId + ")");
        }
      }
      if (this.data.bm !== 0) {
        this.setBlendMode();
      }
    },
    renderElement: function() {
      if (this.finalTransform._matMdf) {
        this.transformedElement.setAttribute("transform", this.finalTransform.mat.to2dCSS());
      }
      if (this.finalTransform._opMdf) {
        this.transformedElement.setAttribute("opacity", this.finalTransform.mProp.o.v);
      }
    },
    destroyBaseElement: function() {
      this.layerElement = null;
      this.matteElement = null;
      this.maskManager.destroy();
    },
    getBaseElement: function() {
      if (this.data.hd) {
        return null;
      }
      return this.baseElement;
    },
    createRenderableComponents: function() {
      this.maskManager = new MaskElement(this.data, this, this.globalData);
      this.renderableEffectsManager = new SVGEffects(this);
    },
    setMatte: function(id) {
      if (!this.matteElement) {
        return;
      }
      this.matteElement.setAttribute("mask", "url(" + getLocationHref() + "#" + id + ")");
    }
  };
  HierarchyElement.prototype = {
    /**
       * @function
       * Initializes hierarchy properties
       *
       */
    initHierarchy: function() {
      this.hierarchy = [];
      this._isParent = false;
      this.checkParenting();
    },
    /**
       * @function
       * Sets layer's hierarchy.
       * @param {array} hierarch
       * layer's parent list
       *
       */
    setHierarchy: function(hierarchy) {
      this.hierarchy = hierarchy;
    },
    /**
       * @function
       * Sets layer as parent.
       *
       */
    setAsParent: function() {
      this._isParent = true;
    },
    /**
       * @function
       * Searches layer's parenting chain
       *
       */
    checkParenting: function() {
      if (this.data.parent !== void 0) {
        this.comp.buildElementParenting(this, this.data.parent, []);
      }
    }
  };
  (function() {
    var _prototype = {
      initElement: function(data2, globalData2, comp2) {
        this.initFrame();
        this.initBaseData(data2, globalData2, comp2);
        this.initTransform(data2, globalData2, comp2);
        this.initHierarchy();
        this.initRenderable();
        this.initRendererElement();
        this.createContainerElements();
        this.createRenderableComponents();
        this.createContent();
        this.hide();
      },
      hide: function() {
        if (!this.hidden && (!this.isInRange || this.isTransparent)) {
          var elem2 = this.baseElement || this.layerElement;
          elem2.style.display = "none";
          this.hidden = true;
        }
      },
      show: function() {
        if (this.isInRange && !this.isTransparent) {
          if (!this.data.hd) {
            var elem2 = this.baseElement || this.layerElement;
            elem2.style.display = "block";
          }
          this.hidden = false;
          this._isFirstFrame = true;
        }
      },
      renderFrame: function() {
        if (this.data.hd || this.hidden) {
          return;
        }
        this.renderTransform();
        this.renderRenderable();
        this.renderElement();
        this.renderInnerContent();
        if (this._isFirstFrame) {
          this._isFirstFrame = false;
        }
      },
      renderInnerContent: function() {
      },
      prepareFrame: function(num) {
        this._mdf = false;
        this.prepareRenderableFrame(num);
        this.prepareProperties(num, this.isInRange);
        this.checkTransparency();
      },
      destroy: function() {
        this.innerElem = null;
        this.destroyBaseElement();
      }
    };
    extendPrototype([RenderableElement, createProxyFunction(_prototype)], RenderableDOMElement);
  })();
  extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement], IImageElement);
  IImageElement.prototype.createContent = function() {
    var assetPath = this.globalData.getAssetsPath(this.assetData);
    this.innerElem = createNS("image");
    this.innerElem.setAttribute("width", this.assetData.w + "px");
    this.innerElem.setAttribute("height", this.assetData.h + "px");
    this.innerElem.setAttribute("preserveAspectRatio", this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio);
    this.innerElem.setAttributeNS("http://www.w3.org/1999/xlink", "href", assetPath);
    this.layerElement.appendChild(this.innerElem);
  };
  IImageElement.prototype.sourceRectAtTime = function() {
    return this.sourceRect;
  };
  IShapeElement.prototype = {
    addShapeToModifiers: function(data2) {
      var i;
      var len = this.shapeModifiers.length;
      for (i = 0; i < len; i += 1) {
        this.shapeModifiers[i].addShape(data2);
      }
    },
    isShapeInAnimatedModifiers: function(data2) {
      var i = 0;
      var len = this.shapeModifiers.length;
      while (i < len) {
        if (this.shapeModifiers[i].isAnimatedWithShape(data2)) {
          return true;
        }
      }
      return false;
    },
    renderModifiers: function() {
      if (!this.shapeModifiers.length) {
        return;
      }
      var i;
      var len = this.shapes.length;
      for (i = 0; i < len; i += 1) {
        this.shapes[i].sh.reset();
      }
      len = this.shapeModifiers.length;
      var shouldBreakProcess;
      for (i = len - 1; i >= 0; i -= 1) {
        shouldBreakProcess = this.shapeModifiers[i].processShapes(this._isFirstFrame);
        if (shouldBreakProcess) {
          break;
        }
      }
    },
    searchProcessedElement: function(elem2) {
      var elements = this.processedElements;
      var i = 0;
      var len = elements.length;
      while (i < len) {
        if (elements[i].elem === elem2) {
          return elements[i].pos;
        }
        i += 1;
      }
      return 0;
    },
    addProcessedElement: function(elem2, pos) {
      var elements = this.processedElements;
      var i = elements.length;
      while (i) {
        i -= 1;
        if (elements[i].elem === elem2) {
          elements[i].pos = pos;
          return;
        }
      }
      elements.push(new ProcessedElement(elem2, pos));
    },
    prepareFrame: function(num) {
      this.prepareRenderableFrame(num);
      this.prepareProperties(num, this.isInRange);
    }
  };
  const lineCapEnum = {
    1: "butt",
    2: "round",
    3: "square"
  };
  const lineJoinEnum = {
    1: "miter",
    2: "round",
    3: "bevel"
  };
  SVGShapeData.prototype.setAsAnimated = function() {
    this._isAnimated = true;
  };
  SVGStyleData.prototype.reset = function() {
    this.d = "";
    this._mdf = false;
  };
  DashProperty.prototype.getValue = function(forceRender) {
    if (this.elem.globalData.frameId === this.frameId && !forceRender) {
      return;
    }
    this.frameId = this.elem.globalData.frameId;
    this.iterateDynamicProperties();
    this._mdf = this._mdf || forceRender;
    if (this._mdf) {
      var i = 0;
      var len = this.dataProps.length;
      if (this.renderer === "svg") {
        this.dashStr = "";
      }
      for (i = 0; i < len; i += 1) {
        if (this.dataProps[i].n !== "o") {
          if (this.renderer === "svg") {
            this.dashStr += " " + this.dataProps[i].p.v;
          } else {
            this.dashArray[i] = this.dataProps[i].p.v;
          }
        } else {
          this.dashoffset[0] = this.dataProps[i].p.v;
        }
      }
    }
  };
  extendPrototype([DynamicPropertyContainer], DashProperty);
  extendPrototype([DynamicPropertyContainer], SVGStrokeStyleData);
  extendPrototype([DynamicPropertyContainer], SVGFillStyleData);
  extendPrototype([DynamicPropertyContainer], SVGNoStyleData);
  GradientProperty.prototype.comparePoints = function(values2, points) {
    var i = 0;
    var len = this.o.length / 2;
    var diff;
    while (i < len) {
      diff = Math.abs(values2[i * 4] - values2[points * 4 + i * 2]);
      if (diff > 0.01) {
        return false;
      }
      i += 1;
    }
    return true;
  };
  GradientProperty.prototype.checkCollapsable = function() {
    if (this.o.length / 2 !== this.c.length / 4) {
      return false;
    }
    if (this.data.k.k[0].s) {
      var i = 0;
      var len = this.data.k.k.length;
      while (i < len) {
        if (!this.comparePoints(this.data.k.k[i].s, this.data.p)) {
          return false;
        }
        i += 1;
      }
    } else if (!this.comparePoints(this.data.k.k, this.data.p)) {
      return false;
    }
    return true;
  };
  GradientProperty.prototype.getValue = function(forceRender) {
    this.prop.getValue();
    this._mdf = false;
    this._cmdf = false;
    this._omdf = false;
    if (this.prop._mdf || forceRender) {
      var i;
      var len = this.data.p * 4;
      var mult;
      var val2;
      for (i = 0; i < len; i += 1) {
        mult = i % 4 === 0 ? 100 : 255;
        val2 = Math.round(this.prop.v[i] * mult);
        if (this.c[i] !== val2) {
          this.c[i] = val2;
          this._cmdf = !forceRender;
        }
      }
      if (this.o.length) {
        len = this.prop.v.length;
        for (i = this.data.p * 4; i < len; i += 1) {
          mult = i % 2 === 0 ? 100 : 1;
          val2 = i % 2 === 0 ? Math.round(this.prop.v[i] * 100) : this.prop.v[i];
          if (this.o[i - this.data.p * 4] !== val2) {
            this.o[i - this.data.p * 4] = val2;
            this._omdf = !forceRender;
          }
        }
      }
      this._mdf = !forceRender;
    }
  };
  extendPrototype([DynamicPropertyContainer], GradientProperty);
  SVGGradientFillStyleData.prototype.initGradientData = function(elem2, data2, styleOb) {
    this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this);
    this.s = PropertyFactory.getProp(elem2, data2.s, 1, null, this);
    this.e = PropertyFactory.getProp(elem2, data2.e, 1, null, this);
    this.h = PropertyFactory.getProp(elem2, data2.h || { k: 0 }, 0, 0.01, this);
    this.a = PropertyFactory.getProp(elem2, data2.a || { k: 0 }, 0, degToRads, this);
    this.g = new GradientProperty(elem2, data2.g, this);
    this.style = styleOb;
    this.stops = [];
    this.setGradientData(styleOb.pElem, data2);
    this.setGradientOpacity(data2, styleOb);
    this._isAnimated = !!this._isAnimated;
  };
  SVGGradientFillStyleData.prototype.setGradientData = function(pathElement, data2) {
    var gradientId = createElementID();
    var gfill = createNS(data2.t === 1 ? "linearGradient" : "radialGradient");
    gfill.setAttribute("id", gradientId);
    gfill.setAttribute("spreadMethod", "pad");
    gfill.setAttribute("gradientUnits", "userSpaceOnUse");
    var stops = [];
    var stop;
    var j2;
    var jLen;
    jLen = data2.g.p * 4;
    for (j2 = 0; j2 < jLen; j2 += 4) {
      stop = createNS("stop");
      gfill.appendChild(stop);
      stops.push(stop);
    }
    pathElement.setAttribute(data2.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + gradientId + ")");
    this.gf = gfill;
    this.cst = stops;
  };
  SVGGradientFillStyleData.prototype.setGradientOpacity = function(data2, styleOb) {
    if (this.g._hasOpacity && !this.g._collapsable) {
      var stop;
      var j2;
      var jLen;
      var mask2 = createNS("mask");
      var maskElement = createNS("path");
      mask2.appendChild(maskElement);
      var opacityId = createElementID();
      var maskId = createElementID();
      mask2.setAttribute("id", maskId);
      var opFill = createNS(data2.t === 1 ? "linearGradient" : "radialGradient");
      opFill.setAttribute("id", opacityId);
      opFill.setAttribute("spreadMethod", "pad");
      opFill.setAttribute("gradientUnits", "userSpaceOnUse");
      jLen = data2.g.k.k[0].s ? data2.g.k.k[0].s.length : data2.g.k.k.length;
      var stops = this.stops;
      for (j2 = data2.g.p * 4; j2 < jLen; j2 += 2) {
        stop = createNS("stop");
        stop.setAttribute("stop-color", "rgb(255,255,255)");
        opFill.appendChild(stop);
        stops.push(stop);
      }
      maskElement.setAttribute(data2.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + opacityId + ")");
      if (data2.ty === "gs") {
        maskElement.setAttribute("stroke-linecap", lineCapEnum[data2.lc || 2]);
        maskElement.setAttribute("stroke-linejoin", lineJoinEnum[data2.lj || 2]);
        if (data2.lj === 1) {
          maskElement.setAttribute("stroke-miterlimit", data2.ml);
        }
      }
      this.of = opFill;
      this.ms = mask2;
      this.ost = stops;
      this.maskId = maskId;
      styleOb.msElem = maskElement;
    }
  };
  extendPrototype([DynamicPropertyContainer], SVGGradientFillStyleData);
  extendPrototype([SVGGradientFillStyleData, DynamicPropertyContainer], SVGGradientStrokeStyleData);
  const buildShapeString = function(pathNodes, length2, closed, mat) {
    if (length2 === 0) {
      return "";
    }
    var _o = pathNodes.o;
    var _i = pathNodes.i;
    var _v4 = pathNodes.v;
    var i;
    var shapeString = " M" + mat.applyToPointStringified(_v4[0][0], _v4[0][1]);
    for (i = 1; i < length2; i += 1) {
      shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[i][0], _i[i][1]) + " " + mat.applyToPointStringified(_v4[i][0], _v4[i][1]);
    }
    if (closed && length2) {
      shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[0][0], _i[0][1]) + " " + mat.applyToPointStringified(_v4[0][0], _v4[0][1]);
      shapeString += "z";
    }
    return shapeString;
  };
  const SVGElementsRenderer = function() {
    var _identityMatrix2 = new Matrix();
    var _matrixHelper = new Matrix();
    var ob2 = {
      createRenderFunction
    };
    function createRenderFunction(data2) {
      switch (data2.ty) {
        case "fl":
          return renderFill;
        case "gf":
          return renderGradient;
        case "gs":
          return renderGradientStroke;
        case "st":
          return renderStroke;
        case "sh":
        case "el":
        case "rc":
        case "sr":
          return renderPath;
        case "tr":
          return renderContentTransform;
        case "no":
          return renderNoop;
        default:
          return null;
      }
    }
    function renderContentTransform(styleData, itemData, isFirstFrame) {
      if (isFirstFrame || itemData.transform.op._mdf) {
        itemData.transform.container.setAttribute("opacity", itemData.transform.op.v);
      }
      if (isFirstFrame || itemData.transform.mProps._mdf) {
        itemData.transform.container.setAttribute("transform", itemData.transform.mProps.v.to2dCSS());
      }
    }
    function renderNoop() {
    }
    function renderPath(styleData, itemData, isFirstFrame) {
      var j2;
      var jLen;
      var pathStringTransformed;
      var redraw;
      var pathNodes;
      var l2;
      var lLen = itemData.styles.length;
      var lvl = itemData.lvl;
      var paths;
      var mat;
      var props;
      var iterations;
      var k2;
      for (l2 = 0; l2 < lLen; l2 += 1) {
        redraw = itemData.sh._mdf || isFirstFrame;
        if (itemData.styles[l2].lvl < lvl) {
          mat = _matrixHelper.reset();
          iterations = lvl - itemData.styles[l2].lvl;
          k2 = itemData.transformers.length - 1;
          while (!redraw && iterations > 0) {
            redraw = itemData.transformers[k2].mProps._mdf || redraw;
            iterations -= 1;
            k2 -= 1;
          }
          if (redraw) {
            iterations = lvl - itemData.styles[l2].lvl;
            k2 = itemData.transformers.length - 1;
            while (iterations > 0) {
              props = itemData.transformers[k2].mProps.v.props;
              mat.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]);
              iterations -= 1;
              k2 -= 1;
            }
          }
        } else {
          mat = _identityMatrix2;
        }
        paths = itemData.sh.paths;
        jLen = paths._length;
        if (redraw) {
          pathStringTransformed = "";
          for (j2 = 0; j2 < jLen; j2 += 1) {
            pathNodes = paths.shapes[j2];
            if (pathNodes && pathNodes._length) {
              pathStringTransformed += buildShapeString(pathNodes, pathNodes._length, pathNodes.c, mat);
            }
          }
          itemData.caches[l2] = pathStringTransformed;
        } else {
          pathStringTransformed = itemData.caches[l2];
        }
        itemData.styles[l2].d += styleData.hd === true ? "" : pathStringTransformed;
        itemData.styles[l2]._mdf = redraw || itemData.styles[l2]._mdf;
      }
    }
    function renderFill(styleData, itemData, isFirstFrame) {
      var styleElem = itemData.style;
      if (itemData.c._mdf || isFirstFrame) {
        styleElem.pElem.setAttribute("fill", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")");
      }
      if (itemData.o._mdf || isFirstFrame) {
        styleElem.pElem.setAttribute("fill-opacity", itemData.o.v);
      }
    }
    function renderGradientStroke(styleData, itemData, isFirstFrame) {
      renderGradient(styleData, itemData, isFirstFrame);
      renderStroke(styleData, itemData, isFirstFrame);
    }
    function renderGradient(styleData, itemData, isFirstFrame) {
      var gfill = itemData.gf;
      var hasOpacity = itemData.g._hasOpacity;
      var pt1 = itemData.s.v;
      var pt2 = itemData.e.v;
      if (itemData.o._mdf || isFirstFrame) {
        var attr = styleData.ty === "gf" ? "fill-opacity" : "stroke-opacity";
        itemData.style.pElem.setAttribute(attr, itemData.o.v);
      }
      if (itemData.s._mdf || isFirstFrame) {
        var attr1 = styleData.t === 1 ? "x1" : "cx";
        var attr2 = attr1 === "x1" ? "y1" : "cy";
        gfill.setAttribute(attr1, pt1[0]);
        gfill.setAttribute(attr2, pt1[1]);
        if (hasOpacity && !itemData.g._collapsable) {
          itemData.of.setAttribute(attr1, pt1[0]);
          itemData.of.setAttribute(attr2, pt1[1]);
        }
      }
      var stops;
      var i;
      var len;
      var stop;
      if (itemData.g._cmdf || isFirstFrame) {
        stops = itemData.cst;
        var cValues = itemData.g.c;
        len = stops.length;
        for (i = 0; i < len; i += 1) {
          stop = stops[i];
          stop.setAttribute("offset", cValues[i * 4] + "%");
          stop.setAttribute("stop-color", "rgb(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + ")");
        }
      }
      if (hasOpacity && (itemData.g._omdf || isFirstFrame)) {
        var oValues = itemData.g.o;
        if (itemData.g._collapsable) {
          stops = itemData.cst;
        } else {
          stops = itemData.ost;
        }
        len = stops.length;
        for (i = 0; i < len; i += 1) {
          stop = stops[i];
          if (!itemData.g._collapsable) {
            stop.setAttribute("offset", oValues[i * 2] + "%");
          }
          stop.setAttribute("stop-opacity", oValues[i * 2 + 1]);
        }
      }
      if (styleData.t === 1) {
        if (itemData.e._mdf || isFirstFrame) {
          gfill.setAttribute("x2", pt2[0]);
          gfill.setAttribute("y2", pt2[1]);
          if (hasOpacity && !itemData.g._collapsable) {
            itemData.of.setAttribute("x2", pt2[0]);
            itemData.of.setAttribute("y2", pt2[1]);
          }
        }
      } else {
        var rad;
        if (itemData.s._mdf || itemData.e._mdf || isFirstFrame) {
          rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2));
          gfill.setAttribute("r", rad);
          if (hasOpacity && !itemData.g._collapsable) {
            itemData.of.setAttribute("r", rad);
          }
        }
        if (itemData.e._mdf || itemData.h._mdf || itemData.a._mdf || isFirstFrame) {
          if (!rad) {
            rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2));
          }
          var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]);
          var percent = itemData.h.v;
          if (percent >= 1) {
            percent = 0.99;
          } else if (percent <= -1) {
            percent = -0.99;
          }
          var dist = rad * percent;
          var x2 = Math.cos(ang + itemData.a.v) * dist + pt1[0];
          var y = Math.sin(ang + itemData.a.v) * dist + pt1[1];
          gfill.setAttribute("fx", x2);
          gfill.setAttribute("fy", y);
          if (hasOpacity && !itemData.g._collapsable) {
            itemData.of.setAttribute("fx", x2);
            itemData.of.setAttribute("fy", y);
          }
        }
      }
    }
    function renderStroke(styleData, itemData, isFirstFrame) {
      var styleElem = itemData.style;
      var d = itemData.d;
      if (d && (d._mdf || isFirstFrame) && d.dashStr) {
        styleElem.pElem.setAttribute("stroke-dasharray", d.dashStr);
        styleElem.pElem.setAttribute("stroke-dashoffset", d.dashoffset[0]);
      }
      if (itemData.c && (itemData.c._mdf || isFirstFrame)) {
        styleElem.pElem.setAttribute("stroke", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")");
      }
      if (itemData.o._mdf || isFirstFrame) {
        styleElem.pElem.setAttribute("stroke-opacity", itemData.o.v);
      }
      if (itemData.w._mdf || isFirstFrame) {
        styleElem.pElem.setAttribute("stroke-width", itemData.w.v);
        if (styleElem.msElem) {
          styleElem.msElem.setAttribute("stroke-width", itemData.w.v);
        }
      }
    }
    return ob2;
  }();
  extendPrototype([BaseElement, TransformElement, SVGBaseElement, IShapeElement, HierarchyElement, FrameElement, RenderableDOMElement], SVGShapeElement);
  SVGShapeElement.prototype.initSecondaryElement = function() {
  };
  SVGShapeElement.prototype.identityMatrix = new Matrix();
  SVGShapeElement.prototype.buildExpressionInterface = function() {
  };
  SVGShapeElement.prototype.createContent = function() {
    this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true);
    this.filterUniqueShapes();
  };
  SVGShapeElement.prototype.filterUniqueShapes = function() {
    var i;
    var len = this.shapes.length;
    var shape;
    var j2;
    var jLen = this.stylesList.length;
    var style;
    var tempShapes = [];
    var areAnimated = false;
    for (j2 = 0; j2 < jLen; j2 += 1) {
      style = this.stylesList[j2];
      areAnimated = false;
      tempShapes.length = 0;
      for (i = 0; i < len; i += 1) {
        shape = this.shapes[i];
        if (shape.styles.indexOf(style) !== -1) {
          tempShapes.push(shape);
          areAnimated = shape._isAnimated || areAnimated;
        }
      }
      if (tempShapes.length > 1 && areAnimated) {
        this.setShapesAsAnimated(tempShapes);
      }
    }
  };
  SVGShapeElement.prototype.setShapesAsAnimated = function(shapes) {
    var i;
    var len = shapes.length;
    for (i = 0; i < len; i += 1) {
      shapes[i].setAsAnimated();
    }
  };
  SVGShapeElement.prototype.createStyleElement = function(data2, level) {
    var elementData;
    var styleOb = new SVGStyleData(data2, level);
    var pathElement = styleOb.pElem;
    if (data2.ty === "st") {
      elementData = new SVGStrokeStyleData(this, data2, styleOb);
    } else if (data2.ty === "fl") {
      elementData = new SVGFillStyleData(this, data2, styleOb);
    } else if (data2.ty === "gf" || data2.ty === "gs") {
      var GradientConstructor = data2.ty === "gf" ? SVGGradientFillStyleData : SVGGradientStrokeStyleData;
      elementData = new GradientConstructor(this, data2, styleOb);
      this.globalData.defs.appendChild(elementData.gf);
      if (elementData.maskId) {
        this.globalData.defs.appendChild(elementData.ms);
        this.globalData.defs.appendChild(elementData.of);
        pathElement.setAttribute("mask", "url(" + getLocationHref() + "#" + elementData.maskId + ")");
      }
    } else if (data2.ty === "no") {
      elementData = new SVGNoStyleData(this, data2, styleOb);
    }
    if (data2.ty === "st" || data2.ty === "gs") {
      pathElement.setAttribute("stroke-linecap", lineCapEnum[data2.lc || 2]);
      pathElement.setAttribute("stroke-linejoin", lineJoinEnum[data2.lj || 2]);
      pathElement.setAttribute("fill-opacity", "0");
      if (data2.lj === 1) {
        pathElement.setAttribute("stroke-miterlimit", data2.ml);
      }
    }
    if (data2.r === 2) {
      pathElement.setAttribute("fill-rule", "evenodd");
    }
    if (data2.ln) {
      pathElement.setAttribute("id", data2.ln);
    }
    if (data2.cl) {
      pathElement.setAttribute("class", data2.cl);
    }
    if (data2.bm) {
      pathElement.style["mix-blend-mode"] = getBlendMode(data2.bm);
    }
    this.stylesList.push(styleOb);
    this.addToAnimatedContents(data2, elementData);
    return elementData;
  };
  SVGShapeElement.prototype.createGroupElement = function(data2) {
    var elementData = new ShapeGroupData();
    if (data2.ln) {
      elementData.gr.setAttribute("id", data2.ln);
    }
    if (data2.cl) {
      elementData.gr.setAttribute("class", data2.cl);
    }
    if (data2.bm) {
      elementData.gr.style["mix-blend-mode"] = getBlendMode(data2.bm);
    }
    return elementData;
  };
  SVGShapeElement.prototype.createTransformElement = function(data2, container) {
    var transformProperty = TransformPropertyFactory.getTransformProperty(this, data2, this);
    var elementData = new SVGTransformData(transformProperty, transformProperty.o, container);
    this.addToAnimatedContents(data2, elementData);
    return elementData;
  };
  SVGShapeElement.prototype.createShapeElement = function(data2, ownTransformers, level) {
    var ty = 4;
    if (data2.ty === "rc") {
      ty = 5;
    } else if (data2.ty === "el") {
      ty = 6;
    } else if (data2.ty === "sr") {
      ty = 7;
    }
    var shapeProperty = ShapePropertyFactory.getShapeProp(this, data2, ty, this);
    var elementData = new SVGShapeData(ownTransformers, level, shapeProperty);
    this.shapes.push(elementData);
    this.addShapeToModifiers(elementData);
    this.addToAnimatedContents(data2, elementData);
    return elementData;
  };
  SVGShapeElement.prototype.addToAnimatedContents = function(data2, element) {
    var i = 0;
    var len = this.animatedContents.length;
    while (i < len) {
      if (this.animatedContents[i].element === element) {
        return;
      }
      i += 1;
    }
    this.animatedContents.push({
      fn: SVGElementsRenderer.createRenderFunction(data2),
      element,
      data: data2
    });
  };
  SVGShapeElement.prototype.setElementStyles = function(elementData) {
    var arr = elementData.styles;
    var j2;
    var jLen = this.stylesList.length;
    for (j2 = 0; j2 < jLen; j2 += 1) {
      if (!this.stylesList[j2].closed) {
        arr.push(this.stylesList[j2]);
      }
    }
  };
  SVGShapeElement.prototype.reloadShapes = function() {
    this._isFirstFrame = true;
    var i;
    var len = this.itemsData.length;
    for (i = 0; i < len; i += 1) {
      this.prevViewData[i] = this.itemsData[i];
    }
    this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true);
    this.filterUniqueShapes();
    len = this.dynamicProperties.length;
    for (i = 0; i < len; i += 1) {
      this.dynamicProperties[i].getValue();
    }
    this.renderModifiers();
  };
  SVGShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, container, level, transformers, render) {
    var ownTransformers = [].concat(transformers);
    var i;
    var len = arr.length - 1;
    var j2;
    var jLen;
    var ownStyles = [];
    var ownModifiers = [];
    var currentTransform;
    var modifier;
    var processedPos;
    for (i = len; i >= 0; i -= 1) {
      processedPos = this.searchProcessedElement(arr[i]);
      if (!processedPos) {
        arr[i]._render = render;
      } else {
        itemsData[i] = prevViewData[processedPos - 1];
      }
      if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs" || arr[i].ty === "no") {
        if (!processedPos) {
          itemsData[i] = this.createStyleElement(arr[i], level);
        } else {
          itemsData[i].style.closed = false;
        }
        if (arr[i]._render) {
          if (itemsData[i].style.pElem.parentNode !== container) {
            container.appendChild(itemsData[i].style.pElem);
          }
        }
        ownStyles.push(itemsData[i].style);
      } else if (arr[i].ty === "gr") {
        if (!processedPos) {
          itemsData[i] = this.createGroupElement(arr[i]);
        } else {
          jLen = itemsData[i].it.length;
          for (j2 = 0; j2 < jLen; j2 += 1) {
            itemsData[i].prevViewData[j2] = itemsData[i].it[j2];
          }
        }
        this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, itemsData[i].gr, level + 1, ownTransformers, render);
        if (arr[i]._render) {
          if (itemsData[i].gr.parentNode !== container) {
            container.appendChild(itemsData[i].gr);
          }
        }
      } else if (arr[i].ty === "tr") {
        if (!processedPos) {
          itemsData[i] = this.createTransformElement(arr[i], container);
        }
        currentTransform = itemsData[i].transform;
        ownTransformers.push(currentTransform);
      } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") {
        if (!processedPos) {
          itemsData[i] = this.createShapeElement(arr[i], ownTransformers, level);
        }
        this.setElementStyles(itemsData[i]);
      } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "ms" || arr[i].ty === "pb") {
        if (!processedPos) {
          modifier = ShapeModifiers.getModifier(arr[i].ty);
          modifier.init(this, arr[i]);
          itemsData[i] = modifier;
          this.shapeModifiers.push(modifier);
        } else {
          modifier = itemsData[i];
          modifier.closed = false;
        }
        ownModifiers.push(modifier);
      } else if (arr[i].ty === "rp") {
        if (!processedPos) {
          modifier = ShapeModifiers.getModifier(arr[i].ty);
          itemsData[i] = modifier;
          modifier.init(this, arr, i, itemsData);
          this.shapeModifiers.push(modifier);
          render = false;
        } else {
          modifier = itemsData[i];
          modifier.closed = true;
        }
        ownModifiers.push(modifier);
      }
      this.addProcessedElement(arr[i], i + 1);
    }
    len = ownStyles.length;
    for (i = 0; i < len; i += 1) {
      ownStyles[i].closed = true;
    }
    len = ownModifiers.length;
    for (i = 0; i < len; i += 1) {
      ownModifiers[i].closed = true;
    }
  };
  SVGShapeElement.prototype.renderInnerContent = function() {
    this.renderModifiers();
    var i;
    var len = this.stylesList.length;
    for (i = 0; i < len; i += 1) {
      this.stylesList[i].reset();
    }
    this.renderShape();
    for (i = 0; i < len; i += 1) {
      if (this.stylesList[i]._mdf || this._isFirstFrame) {
        if (this.stylesList[i].msElem) {
          this.stylesList[i].msElem.setAttribute("d", this.stylesList[i].d);
          this.stylesList[i].d = "M0 0" + this.stylesList[i].d;
        }
        this.stylesList[i].pElem.setAttribute("d", this.stylesList[i].d || "M0 0");
      }
    }
  };
  SVGShapeElement.prototype.renderShape = function() {
    var i;
    var len = this.animatedContents.length;
    var animatedContent;
    for (i = 0; i < len; i += 1) {
      animatedContent = this.animatedContents[i];
      if ((this._isFirstFrame || animatedContent.element._isAnimated) && animatedContent.data !== true) {
        animatedContent.fn(animatedContent.data, animatedContent.element, this._isFirstFrame);
      }
    }
  };
  SVGShapeElement.prototype.destroy = function() {
    this.destroyBaseElement();
    this.shapesData = null;
    this.itemsData = null;
  };
  LetterProps.prototype.update = function(o, sw, sc, fc, m, p) {
    this._mdf.o = false;
    this._mdf.sw = false;
    this._mdf.sc = false;
    this._mdf.fc = false;
    this._mdf.m = false;
    this._mdf.p = false;
    var updated = false;
    if (this.o !== o) {
      this.o = o;
      this._mdf.o = true;
      updated = true;
    }
    if (this.sw !== sw) {
      this.sw = sw;
      this._mdf.sw = true;
      updated = true;
    }
    if (this.sc !== sc) {
      this.sc = sc;
      this._mdf.sc = true;
      updated = true;
    }
    if (this.fc !== fc) {
      this.fc = fc;
      this._mdf.fc = true;
      updated = true;
    }
    if (this.m !== m) {
      this.m = m;
      this._mdf.m = true;
      updated = true;
    }
    if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) {
      this.p = p;
      this._mdf.p = true;
      updated = true;
    }
    return updated;
  };
  TextProperty.prototype.defaultBoxWidth = [0, 0];
  TextProperty.prototype.copyData = function(obj, data2) {
    for (var s in data2) {
      if (Object.prototype.hasOwnProperty.call(data2, s)) {
        obj[s] = data2[s];
      }
    }
    return obj;
  };
  TextProperty.prototype.setCurrentData = function(data2) {
    if (!data2.__complete) {
      this.completeTextData(data2);
    }
    this.currentData = data2;
    this.currentData.boxWidth = this.currentData.boxWidth || this.defaultBoxWidth;
    this._mdf = true;
  };
  TextProperty.prototype.searchProperty = function() {
    return this.searchKeyframes();
  };
  TextProperty.prototype.searchKeyframes = function() {
    this.kf = this.data.d.k.length > 1;
    if (this.kf) {
      this.addEffect(this.getKeyframeValue.bind(this));
    }
    return this.kf;
  };
  TextProperty.prototype.addEffect = function(effectFunction) {
    this.effectsSequence.push(effectFunction);
    this.elem.addDynamicProperty(this);
  };
  TextProperty.prototype.getValue = function(_finalValue) {
    if ((this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) && !_finalValue) {
      return;
    }
    this.currentData.t = this.data.d.k[this.keysIndex].s.t;
    var currentValue = this.currentData;
    var currentIndex = this.keysIndex;
    if (this.lock) {
      this.setCurrentData(this.currentData);
      return;
    }
    this.lock = true;
    this._mdf = false;
    var i;
    var len = this.effectsSequence.length;
    var finalValue = _finalValue || this.data.d.k[this.keysIndex].s;
    for (i = 0; i < len; i += 1) {
      if (currentIndex !== this.keysIndex) {
        finalValue = this.effectsSequence[i](finalValue, finalValue.t);
      } else {
        finalValue = this.effectsSequence[i](this.currentData, finalValue.t);
      }
    }
    if (currentValue !== finalValue) {
      this.setCurrentData(finalValue);
    }
    this.v = this.currentData;
    this.pv = this.v;
    this.lock = false;
    this.frameId = this.elem.globalData.frameId;
  };
  TextProperty.prototype.getKeyframeValue = function() {
    var textKeys = this.data.d.k;
    var frameNum = this.elem.comp.renderedFrame;
    var i = 0;
    var len = textKeys.length;
    while (i <= len - 1) {
      if (i === len - 1 || textKeys[i + 1].t > frameNum) {
        break;
      }
      i += 1;
    }
    if (this.keysIndex !== i) {
      this.keysIndex = i;
    }
    return this.data.d.k[this.keysIndex].s;
  };
  TextProperty.prototype.buildFinalText = function(text2) {
    var charactersArray = [];
    var i = 0;
    var len = text2.length;
    var charCode;
    var secondCharCode;
    var shouldCombine = false;
    while (i < len) {
      charCode = text2.charCodeAt(i);
      if (FontManager.isCombinedCharacter(charCode)) {
        charactersArray[charactersArray.length - 1] += text2.charAt(i);
      } else if (charCode >= 55296 && charCode <= 56319) {
        secondCharCode = text2.charCodeAt(i + 1);
        if (secondCharCode >= 56320 && secondCharCode <= 57343) {
          if (shouldCombine || FontManager.isModifier(charCode, secondCharCode)) {
            charactersArray[charactersArray.length - 1] += text2.substr(i, 2);
            shouldCombine = false;
          } else {
            charactersArray.push(text2.substr(i, 2));
          }
          i += 1;
        } else {
          charactersArray.push(text2.charAt(i));
        }
      } else if (charCode > 56319) {
        secondCharCode = text2.charCodeAt(i + 1);
        if (FontManager.isZeroWidthJoiner(charCode, secondCharCode)) {
          shouldCombine = true;
          charactersArray[charactersArray.length - 1] += text2.substr(i, 2);
          i += 1;
        } else {
          charactersArray.push(text2.charAt(i));
        }
      } else if (FontManager.isZeroWidthJoiner(charCode)) {
        charactersArray[charactersArray.length - 1] += text2.charAt(i);
        shouldCombine = true;
      } else {
        charactersArray.push(text2.charAt(i));
      }
      i += 1;
    }
    return charactersArray;
  };
  TextProperty.prototype.completeTextData = function(documentData) {
    documentData.__complete = true;
    var fontManager = this.elem.globalData.fontManager;
    var data2 = this.data;
    var letters = [];
    var i;
    var len;
    var newLineFlag;
    var index2 = 0;
    var val2;
    var anchorGrouping = data2.m.g;
    var currentSize = 0;
    var currentPos = 0;
    var currentLine = 0;
    var lineWidths = [];
    var lineWidth = 0;
    var maxLineWidth = 0;
    var j2;
    var jLen;
    var fontData = fontManager.getFontByName(documentData.f);
    var charData;
    var cLength = 0;
    var fontProps = getFontProperties(fontData);
    documentData.fWeight = fontProps.weight;
    documentData.fStyle = fontProps.style;
    documentData.finalSize = documentData.s;
    documentData.finalText = this.buildFinalText(documentData.t);
    len = documentData.finalText.length;
    documentData.finalLineHeight = documentData.lh;
    var trackingOffset = documentData.tr / 1e3 * documentData.finalSize;
    var charCode;
    if (documentData.sz) {
      var flag = true;
      var boxWidth = documentData.sz[0];
      var boxHeight = documentData.sz[1];
      var currentHeight;
      var finalText;
      while (flag) {
        finalText = this.buildFinalText(documentData.t);
        currentHeight = 0;
        lineWidth = 0;
        len = finalText.length;
        trackingOffset = documentData.tr / 1e3 * documentData.finalSize;
        var lastSpaceIndex = -1;
        for (i = 0; i < len; i += 1) {
          charCode = finalText[i].charCodeAt(0);
          newLineFlag = false;
          if (finalText[i] === " ") {
            lastSpaceIndex = i;
          } else if (charCode === 13 || charCode === 3) {
            lineWidth = 0;
            newLineFlag = true;
            currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2;
          }
          if (fontManager.chars) {
            charData = fontManager.getCharData(finalText[i], fontData.fStyle, fontData.fFamily);
            cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100;
          } else {
            cLength = fontManager.measureText(finalText[i], documentData.f, documentData.finalSize);
          }
          if (lineWidth + cLength > boxWidth && finalText[i] !== " ") {
            if (lastSpaceIndex === -1) {
              len += 1;
            } else {
              i = lastSpaceIndex;
            }
            currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2;
            finalText.splice(i, lastSpaceIndex === i ? 1 : 0, "\r");
            lastSpaceIndex = -1;
            lineWidth = 0;
          } else {
            lineWidth += cLength;
            lineWidth += trackingOffset;
          }
        }
        currentHeight += fontData.ascent * documentData.finalSize / 100;
        if (this.canResize && documentData.finalSize > this.minimumFontSize && boxHeight < currentHeight) {
          documentData.finalSize -= 1;
          documentData.finalLineHeight = documentData.finalSize * documentData.lh / documentData.s;
        } else {
          documentData.finalText = finalText;
          len = documentData.finalText.length;
          flag = false;
        }
      }
    }
    lineWidth = -trackingOffset;
    cLength = 0;
    var uncollapsedSpaces = 0;
    var currentChar;
    for (i = 0; i < len; i += 1) {
      newLineFlag = false;
      currentChar = documentData.finalText[i];
      charCode = currentChar.charCodeAt(0);
      if (charCode === 13 || charCode === 3) {
        uncollapsedSpaces = 0;
        lineWidths.push(lineWidth);
        maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth;
        lineWidth = -2 * trackingOffset;
        val2 = "";
        newLineFlag = true;
        currentLine += 1;
      } else {
        val2 = currentChar;
      }
      if (fontManager.chars) {
        charData = fontManager.getCharData(currentChar, fontData.fStyle, fontManager.getFontByName(documentData.f).fFamily);
        cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100;
      } else {
        cLength = fontManager.measureText(val2, documentData.f, documentData.finalSize);
      }
      if (currentChar === " ") {
        uncollapsedSpaces += cLength + trackingOffset;
      } else {
        lineWidth += cLength + trackingOffset + uncollapsedSpaces;
        uncollapsedSpaces = 0;
      }
      letters.push({
        l: cLength,
        an: cLength,
        add: currentSize,
        n: newLineFlag,
        anIndexes: [],
        val: val2,
        line: currentLine,
        animatorJustifyOffset: 0
      });
      if (anchorGrouping == 2) {
        currentSize += cLength;
        if (val2 === "" || val2 === " " || i === len - 1) {
          if (val2 === "" || val2 === " ") {
            currentSize -= cLength;
          }
          while (currentPos <= i) {
            letters[currentPos].an = currentSize;
            letters[currentPos].ind = index2;
            letters[currentPos].extra = cLength;
            currentPos += 1;
          }
          index2 += 1;
          currentSize = 0;
        }
      } else if (anchorGrouping == 3) {
        currentSize += cLength;
        if (val2 === "" || i === len - 1) {
          if (val2 === "") {
            currentSize -= cLength;
          }
          while (currentPos <= i) {
            letters[currentPos].an = currentSize;
            letters[currentPos].ind = index2;
            letters[currentPos].extra = cLength;
            currentPos += 1;
          }
          currentSize = 0;
          index2 += 1;
        }
      } else {
        letters[index2].ind = index2;
        letters[index2].extra = 0;
        index2 += 1;
      }
    }
    documentData.l = letters;
    maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth;
    lineWidths.push(lineWidth);
    if (documentData.sz) {
      documentData.boxWidth = documentData.sz[0];
      documentData.justifyOffset = 0;
    } else {
      documentData.boxWidth = maxLineWidth;
      switch (documentData.j) {
        case 1:
          documentData.justifyOffset = -documentData.boxWidth;
          break;
        case 2:
          documentData.justifyOffset = -documentData.boxWidth / 2;
          break;
        default:
          documentData.justifyOffset = 0;
      }
    }
    documentData.lineWidths = lineWidths;
    var animators = data2.a;
    var animatorData;
    var letterData;
    jLen = animators.length;
    var based;
    var ind;
    var indexes = [];
    for (j2 = 0; j2 < jLen; j2 += 1) {
      animatorData = animators[j2];
      if (animatorData.a.sc) {
        documentData.strokeColorAnim = true;
      }
      if (animatorData.a.sw) {
        documentData.strokeWidthAnim = true;
      }
      if (animatorData.a.fc || animatorData.a.fh || animatorData.a.fs || animatorData.a.fb) {
        documentData.fillColorAnim = true;
      }
      ind = 0;
      based = animatorData.s.b;
      for (i = 0; i < len; i += 1) {
        letterData = letters[i];
        letterData.anIndexes[j2] = ind;
        if (based == 1 && letterData.val !== "" || based == 2 && letterData.val !== "" && letterData.val !== " " || based == 3 && (letterData.n || letterData.val == " " || i == len - 1) || based == 4 && (letterData.n || i == len - 1)) {
          if (animatorData.s.rn === 1) {
            indexes.push(ind);
          }
          ind += 1;
        }
      }
      data2.a[j2].s.totalChars = ind;
      var currentInd = -1;
      var newInd;
      if (animatorData.s.rn === 1) {
        for (i = 0; i < len; i += 1) {
          letterData = letters[i];
          if (currentInd != letterData.anIndexes[j2]) {
            currentInd = letterData.anIndexes[j2];
            newInd = indexes.splice(Math.floor(Math.random() * indexes.length), 1)[0];
          }
          letterData.anIndexes[j2] = newInd;
        }
      }
    }
    documentData.yOffset = documentData.finalLineHeight || documentData.finalSize * 1.2;
    documentData.ls = documentData.ls || 0;
    documentData.ascent = fontData.ascent * documentData.finalSize / 100;
  };
  TextProperty.prototype.updateDocumentData = function(newData, index2) {
    index2 = index2 === void 0 ? this.keysIndex : index2;
    var dData = this.copyData({}, this.data.d.k[index2].s);
    dData = this.copyData(dData, newData);
    this.data.d.k[index2].s = dData;
    this.recalculate(index2);
    this.elem.addDynamicProperty(this);
  };
  TextProperty.prototype.recalculate = function(index2) {
    var dData = this.data.d.k[index2].s;
    dData.__complete = false;
    this.keysIndex = 0;
    this._isFirstFrame = true;
    this.getValue(dData);
  };
  TextProperty.prototype.canResizeFont = function(_canResize) {
    this.canResize = _canResize;
    this.recalculate(this.keysIndex);
    this.elem.addDynamicProperty(this);
  };
  TextProperty.prototype.setMinimumFontSize = function(_fontValue) {
    this.minimumFontSize = Math.floor(_fontValue) || 1;
    this.recalculate(this.keysIndex);
    this.elem.addDynamicProperty(this);
  };
  const TextSelectorProp = function() {
    var max2 = Math.max;
    var min = Math.min;
    var floor = Math.floor;
    function TextSelectorPropFactory(elem2, data2) {
      this._currentTextLength = -1;
      this.k = false;
      this.data = data2;
      this.elem = elem2;
      this.comp = elem2.comp;
      this.finalS = 0;
      this.finalE = 0;
      this.initDynamicPropertyContainer(elem2);
      this.s = PropertyFactory.getProp(elem2, data2.s || { k: 0 }, 0, 0, this);
      if ("e" in data2) {
        this.e = PropertyFactory.getProp(elem2, data2.e, 0, 0, this);
      } else {
        this.e = { v: 100 };
      }
      this.o = PropertyFactory.getProp(elem2, data2.o || { k: 0 }, 0, 0, this);
      this.xe = PropertyFactory.getProp(elem2, data2.xe || { k: 0 }, 0, 0, this);
      this.ne = PropertyFactory.getProp(elem2, data2.ne || { k: 0 }, 0, 0, this);
      this.sm = PropertyFactory.getProp(elem2, data2.sm || { k: 100 }, 0, 0, this);
      this.a = PropertyFactory.getProp(elem2, data2.a, 0, 0.01, this);
      if (!this.dynamicProperties.length) {
        this.getValue();
      }
    }
    TextSelectorPropFactory.prototype = {
      getMult: function(ind) {
        if (this._currentTextLength !== this.elem.textProperty.currentData.l.length) {
          this.getValue();
        }
        var x1 = 0;
        var y1 = 0;
        var x2 = 1;
        var y2 = 1;
        if (this.ne.v > 0) {
          x1 = this.ne.v / 100;
        } else {
          y1 = -this.ne.v / 100;
        }
        if (this.xe.v > 0) {
          x2 = 1 - this.xe.v / 100;
        } else {
          y2 = 1 + this.xe.v / 100;
        }
        var easer = BezierFactory.getBezierEasing(x1, y1, x2, y2).get;
        var mult = 0;
        var s = this.finalS;
        var e = this.finalE;
        var type = this.data.sh;
        if (type === 2) {
          if (e === s) {
            mult = ind >= e ? 1 : 0;
          } else {
            mult = max2(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1));
          }
          mult = easer(mult);
        } else if (type === 3) {
          if (e === s) {
            mult = ind >= e ? 0 : 1;
          } else {
            mult = 1 - max2(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1));
          }
          mult = easer(mult);
        } else if (type === 4) {
          if (e === s) {
            mult = 0;
          } else {
            mult = max2(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1));
            if (mult < 0.5) {
              mult *= 2;
            } else {
              mult = 1 - 2 * (mult - 0.5);
            }
          }
          mult = easer(mult);
        } else if (type === 5) {
          if (e === s) {
            mult = 0;
          } else {
            var tot = e - s;
            ind = min(max2(0, ind + 0.5 - s), e - s);
            var x3 = -tot / 2 + ind;
            var a2 = tot / 2;
            mult = Math.sqrt(1 - x3 * x3 / (a2 * a2));
          }
          mult = easer(mult);
        } else if (type === 6) {
          if (e === s) {
            mult = 0;
          } else {
            ind = min(max2(0, ind + 0.5 - s), e - s);
            mult = (1 + Math.cos(Math.PI + Math.PI * 2 * ind / (e - s))) / 2;
          }
          mult = easer(mult);
        } else {
          if (ind >= floor(s)) {
            if (ind - s < 0) {
              mult = max2(0, min(min(e, 1) - (s - ind), 1));
            } else {
              mult = max2(0, min(e - ind, 1));
            }
          }
          mult = easer(mult);
        }
        if (this.sm.v !== 100) {
          var smoothness = this.sm.v * 0.01;
          if (smoothness === 0) {
            smoothness = 1e-8;
          }
          var threshold = 0.5 - smoothness * 0.5;
          if (mult < threshold) {
            mult = 0;
          } else {
            mult = (mult - threshold) / smoothness;
            if (mult > 1) {
              mult = 1;
            }
          }
        }
        return mult * this.a.v;
      },
      getValue: function(newCharsFlag) {
        this.iterateDynamicProperties();
        this._mdf = newCharsFlag || this._mdf;
        this._currentTextLength = this.elem.textProperty.currentData.l.length || 0;
        if (newCharsFlag && this.data.r === 2) {
          this.e.v = this._currentTextLength;
        }
        var divisor = this.data.r === 2 ? 1 : 100 / this.data.totalChars;
        var o = this.o.v / divisor;
        var s = this.s.v / divisor + o;
        var e = this.e.v / divisor + o;
        if (s > e) {
          var _s = s;
          s = e;
          e = _s;
        }
        this.finalS = s;
        this.finalE = e;
      }
    };
    extendPrototype([DynamicPropertyContainer], TextSelectorPropFactory);
    function getTextSelectorProp(elem2, data2, arr) {
      return new TextSelectorPropFactory(elem2, data2, arr);
    }
    return {
      getTextSelectorProp
    };
  }();
  TextAnimatorProperty.prototype.searchProperties = function() {
    var i;
    var len = this._textData.a.length;
    var animatorProps;
    var getProp = PropertyFactory.getProp;
    for (i = 0; i < len; i += 1) {
      animatorProps = this._textData.a[i];
      this._animatorsData[i] = new TextAnimatorDataProperty(this._elem, animatorProps, this);
    }
    if (this._textData.p && "m" in this._textData.p) {
      this._pathData = {
        a: getProp(this._elem, this._textData.p.a, 0, 0, this),
        f: getProp(this._elem, this._textData.p.f, 0, 0, this),
        l: getProp(this._elem, this._textData.p.l, 0, 0, this),
        r: getProp(this._elem, this._textData.p.r, 0, 0, this),
        p: getProp(this._elem, this._textData.p.p, 0, 0, this),
        m: this._elem.maskManager.getMaskProperty(this._textData.p.m)
      };
      this._hasMaskedPath = true;
    } else {
      this._hasMaskedPath = false;
    }
    this._moreOptions.alignment = getProp(this._elem, this._textData.m.a, 1, 0, this);
  };
  TextAnimatorProperty.prototype.getMeasures = function(documentData, lettersChangedFlag) {
    this.lettersChangedFlag = lettersChangedFlag;
    if (!this._mdf && !this._isFirstFrame && !lettersChangedFlag && (!this._hasMaskedPath || !this._pathData.m._mdf)) {
      return;
    }
    this._isFirstFrame = false;
    var alignment = this._moreOptions.alignment.v;
    var animators = this._animatorsData;
    var textData = this._textData;
    var matrixHelper = this.mHelper;
    var renderType = this._renderType;
    var renderedLettersCount = this.renderedLetters.length;
    var xPos;
    var yPos;
    var i;
    var len;
    var letters = documentData.l;
    var pathInfo;
    var currentLength;
    var currentPoint;
    var segmentLength;
    var flag;
    var pointInd;
    var segmentInd;
    var prevPoint;
    var points;
    var segments;
    var partialLength;
    var totalLength;
    var perc;
    var tanAngle;
    var mask2;
    if (this._hasMaskedPath) {
      mask2 = this._pathData.m;
      if (!this._pathData.n || this._pathData._mdf) {
        var paths = mask2.v;
        if (this._pathData.r.v) {
          paths = paths.reverse();
        }
        pathInfo = {
          tLength: 0,
          segments: []
        };
        len = paths._length - 1;
        var bezierData;
        totalLength = 0;
        for (i = 0; i < len; i += 1) {
          bezierData = bez.buildBezierData(
            paths.v[i],
            paths.v[i + 1],
            [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]],
            [paths.i[i + 1][0] - paths.v[i + 1][0], paths.i[i + 1][1] - paths.v[i + 1][1]]
          );
          pathInfo.tLength += bezierData.segmentLength;
          pathInfo.segments.push(bezierData);
          totalLength += bezierData.segmentLength;
        }
        i = len;
        if (mask2.v.c) {
          bezierData = bez.buildBezierData(
            paths.v[i],
            paths.v[0],
            [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]],
            [paths.i[0][0] - paths.v[0][0], paths.i[0][1] - paths.v[0][1]]
          );
          pathInfo.tLength += bezierData.segmentLength;
          pathInfo.segments.push(bezierData);
          totalLength += bezierData.segmentLength;
        }
        this._pathData.pi = pathInfo;
      }
      pathInfo = this._pathData.pi;
      currentLength = this._pathData.f.v;
      segmentInd = 0;
      pointInd = 1;
      segmentLength = 0;
      flag = true;
      segments = pathInfo.segments;
      if (currentLength < 0 && mask2.v.c) {
        if (pathInfo.tLength < Math.abs(currentLength)) {
          currentLength = -Math.abs(currentLength) % pathInfo.tLength;
        }
        segmentInd = segments.length - 1;
        points = segments[segmentInd].points;
        pointInd = points.length - 1;
        while (currentLength < 0) {
          currentLength += points[pointInd].partialLength;
          pointInd -= 1;
          if (pointInd < 0) {
            segmentInd -= 1;
            points = segments[segmentInd].points;
            pointInd = points.length - 1;
          }
        }
      }
      points = segments[segmentInd].points;
      prevPoint = points[pointInd - 1];
      currentPoint = points[pointInd];
      partialLength = currentPoint.partialLength;
    }
    len = letters.length;
    xPos = 0;
    yPos = 0;
    var yOff = documentData.finalSize * 1.2 * 0.714;
    var firstLine = true;
    var animatorProps;
    var animatorSelector;
    var j2;
    var jLen;
    var letterValue;
    jLen = animators.length;
    var mult;
    var ind = -1;
    var offf;
    var xPathPos;
    var yPathPos;
    var initPathPos = currentLength;
    var initSegmentInd = segmentInd;
    var initPointInd = pointInd;
    var currentLine = -1;
    var elemOpacity;
    var sc;
    var sw;
    var fc;
    var k2;
    var letterSw;
    var letterSc;
    var letterFc;
    var letterM = "";
    var letterP = this.defaultPropsArray;
    var letterO;
    if (documentData.j === 2 || documentData.j === 1) {
      var animatorJustifyOffset = 0;
      var animatorFirstCharOffset = 0;
      var justifyOffsetMult = documentData.j === 2 ? -0.5 : -1;
      var lastIndex = 0;
      var isNewLine = true;
      for (i = 0; i < len; i += 1) {
        if (letters[i].n) {
          if (animatorJustifyOffset) {
            animatorJustifyOffset += animatorFirstCharOffset;
          }
          while (lastIndex < i) {
            letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset;
            lastIndex += 1;
          }
          animatorJustifyOffset = 0;
          isNewLine = true;
        } else {
          for (j2 = 0; j2 < jLen; j2 += 1) {
            animatorProps = animators[j2].a;
            if (animatorProps.t.propType) {
              if (isNewLine && documentData.j === 2) {
                animatorFirstCharOffset += animatorProps.t.v * justifyOffsetMult;
              }
              animatorSelector = animators[j2].s;
              mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars);
              if (mult.length) {
                animatorJustifyOffset += animatorProps.t.v * mult[0] * justifyOffsetMult;
              } else {
                animatorJustifyOffset += animatorProps.t.v * mult * justifyOffsetMult;
              }
            }
          }
          isNewLine = false;
        }
      }
      if (animatorJustifyOffset) {
        animatorJustifyOffset += animatorFirstCharOffset;
      }
      while (lastIndex < i) {
        letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset;
        lastIndex += 1;
      }
    }
    for (i = 0; i < len; i += 1) {
      matrixHelper.reset();
      elemOpacity = 1;
      if (letters[i].n) {
        xPos = 0;
        yPos += documentData.yOffset;
        yPos += firstLine ? 1 : 0;
        currentLength = initPathPos;
        firstLine = false;
        if (this._hasMaskedPath) {
          segmentInd = initSegmentInd;
          pointInd = initPointInd;
          points = segments[segmentInd].points;
          prevPoint = points[pointInd - 1];
          currentPoint = points[pointInd];
          partialLength = currentPoint.partialLength;
          segmentLength = 0;
        }
        letterM = "";
        letterFc = "";
        letterSw = "";
        letterO = "";
        letterP = this.defaultPropsArray;
      } else {
        if (this._hasMaskedPath) {
          if (currentLine !== letters[i].line) {
            switch (documentData.j) {
              case 1:
                currentLength += totalLength - documentData.lineWidths[letters[i].line];
                break;
              case 2:
                currentLength += (totalLength - documentData.lineWidths[letters[i].line]) / 2;
                break;
              default:
                break;
            }
            currentLine = letters[i].line;
          }
          if (ind !== letters[i].ind) {
            if (letters[ind]) {
              currentLength += letters[ind].extra;
            }
            currentLength += letters[i].an / 2;
            ind = letters[i].ind;
          }
          currentLength += alignment[0] * letters[i].an * 5e-3;
          var animatorOffset = 0;
          for (j2 = 0; j2 < jLen; j2 += 1) {
            animatorProps = animators[j2].a;
            if (animatorProps.p.propType) {
              animatorSelector = animators[j2].s;
              mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars);
              if (mult.length) {
                animatorOffset += animatorProps.p.v[0] * mult[0];
              } else {
                animatorOffset += animatorProps.p.v[0] * mult;
              }
            }
            if (animatorProps.a.propType) {
              animatorSelector = animators[j2].s;
              mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars);
              if (mult.length) {
                animatorOffset += animatorProps.a.v[0] * mult[0];
              } else {
                animatorOffset += animatorProps.a.v[0] * mult;
              }
            }
          }
          flag = true;
          if (this._pathData.a.v) {
            currentLength = letters[0].an * 0.5 + (totalLength - this._pathData.f.v - letters[0].an * 0.5 - letters[letters.length - 1].an * 0.5) * ind / (len - 1);
            currentLength += this._pathData.f.v;
          }
          while (flag) {
            if (segmentLength + partialLength >= currentLength + animatorOffset || !points) {
              perc = (currentLength + animatorOffset - segmentLength) / currentPoint.partialLength;
              xPathPos = prevPoint.point[0] + (currentPoint.point[0] - prevPoint.point[0]) * perc;
              yPathPos = prevPoint.point[1] + (currentPoint.point[1] - prevPoint.point[1]) * perc;
              matrixHelper.translate(-alignment[0] * letters[i].an * 5e-3, -(alignment[1] * yOff) * 0.01);
              flag = false;
            } else if (points) {
              segmentLength += currentPoint.partialLength;
              pointInd += 1;
              if (pointInd >= points.length) {
                pointInd = 0;
                segmentInd += 1;
                if (!segments[segmentInd]) {
                  if (mask2.v.c) {
                    pointInd = 0;
                    segmentInd = 0;
                    points = segments[segmentInd].points;
                  } else {
                    segmentLength -= currentPoint.partialLength;
                    points = null;
                  }
                } else {
                  points = segments[segmentInd].points;
                }
              }
              if (points) {
                prevPoint = currentPoint;
                currentPoint = points[pointInd];
                partialLength = currentPoint.partialLength;
              }
            }
          }
          offf = letters[i].an / 2 - letters[i].add;
          matrixHelper.translate(-offf, 0, 0);
        } else {
          offf = letters[i].an / 2 - letters[i].add;
          matrixHelper.translate(-offf, 0, 0);
          matrixHelper.translate(-alignment[0] * letters[i].an * 5e-3, -alignment[1] * yOff * 0.01, 0);
        }
        for (j2 = 0; j2 < jLen; j2 += 1) {
          animatorProps = animators[j2].a;
          if (animatorProps.t.propType) {
            animatorSelector = animators[j2].s;
            mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars);
            if (xPos !== 0 || documentData.j !== 0) {
              if (this._hasMaskedPath) {
                if (mult.length) {
                  currentLength += animatorProps.t.v * mult[0];
                } else {
                  currentLength += animatorProps.t.v * mult;
                }
              } else if (mult.length) {
                xPos += animatorProps.t.v * mult[0];
              } else {
                xPos += animatorProps.t.v * mult;
              }
            }
          }
        }
        if (documentData.strokeWidthAnim) {
          sw = documentData.sw || 0;
        }
        if (documentData.strokeColorAnim) {
          if (documentData.sc) {
            sc = [documentData.sc[0], documentData.sc[1], documentData.sc[2]];
          } else {
            sc = [0, 0, 0];
          }
        }
        if (documentData.fillColorAnim && documentData.fc) {
          fc = [documentData.fc[0], documentData.fc[1], documentData.fc[2]];
        }
        for (j2 = 0; j2 < jLen; j2 += 1) {
          animatorProps = animators[j2].a;
          if (animatorProps.a.propType) {
            animatorSelector = animators[j2].s;
            mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars);
            if (mult.length) {
              matrixHelper.translate(-animatorProps.a.v[0] * mult[0], -animatorProps.a.v[1] * mult[1], animatorProps.a.v[2] * mult[2]);
            } else {
              matrixHelper.translate(-animatorProps.a.v[0] * mult, -animatorProps.a.v[1] * mult, animatorProps.a.v[2] * mult);
            }
          }
        }
        for (j2 = 0; j2 < jLen; j2 += 1) {
          animatorProps = animators[j2].a;
          if (animatorProps.s.propType) {
            animatorSelector = animators[j2].s;
            mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars);
            if (mult.length) {
              matrixHelper.scale(1 + (animatorProps.s.v[0] - 1) * mult[0], 1 + (animatorProps.s.v[1] - 1) * mult[1], 1);
            } else {
              matrixHelper.scale(1 + (animatorProps.s.v[0] - 1) * mult, 1 + (animatorProps.s.v[1] - 1) * mult, 1);
            }
          }
        }
        for (j2 = 0; j2 < jLen; j2 += 1) {
          animatorProps = animators[j2].a;
          animatorSelector = animators[j2].s;
          mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars);
          if (animatorProps.sk.propType) {
            if (mult.length) {
              matrixHelper.skewFromAxis(-animatorProps.sk.v * mult[0], animatorProps.sa.v * mult[1]);
            } else {
              matrixHelper.skewFromAxis(-animatorProps.sk.v * mult, animatorProps.sa.v * mult);
            }
          }
          if (animatorProps.r.propType) {
            if (mult.length) {
              matrixHelper.rotateZ(-animatorProps.r.v * mult[2]);
            } else {
              matrixHelper.rotateZ(-animatorProps.r.v * mult);
            }
          }
          if (animatorProps.ry.propType) {
            if (mult.length) {
              matrixHelper.rotateY(animatorProps.ry.v * mult[1]);
            } else {
              matrixHelper.rotateY(animatorProps.ry.v * mult);
            }
          }
          if (animatorProps.rx.propType) {
            if (mult.length) {
              matrixHelper.rotateX(animatorProps.rx.v * mult[0]);
            } else {
              matrixHelper.rotateX(animatorProps.rx.v * mult);
            }
          }
          if (animatorProps.o.propType) {
            if (mult.length) {
              elemOpacity += (animatorProps.o.v * mult[0] - elemOpacity) * mult[0];
            } else {
              elemOpacity += (animatorProps.o.v * mult - elemOpacity) * mult;
            }
          }
          if (documentData.strokeWidthAnim && animatorProps.sw.propType) {
            if (mult.length) {
              sw += animatorProps.sw.v * mult[0];
            } else {
              sw += animatorProps.sw.v * mult;
            }
          }
          if (documentData.strokeColorAnim && animatorProps.sc.propType) {
            for (k2 = 0; k2 < 3; k2 += 1) {
              if (mult.length) {
                sc[k2] += (animatorProps.sc.v[k2] - sc[k2]) * mult[0];
              } else {
                sc[k2] += (animatorProps.sc.v[k2] - sc[k2]) * mult;
              }
            }
          }
          if (documentData.fillColorAnim && documentData.fc) {
            if (animatorProps.fc.propType) {
              for (k2 = 0; k2 < 3; k2 += 1) {
                if (mult.length) {
                  fc[k2] += (animatorProps.fc.v[k2] - fc[k2]) * mult[0];
                } else {
                  fc[k2] += (animatorProps.fc.v[k2] - fc[k2]) * mult;
                }
              }
            }
            if (animatorProps.fh.propType) {
              if (mult.length) {
                fc = addHueToRGB(fc, animatorProps.fh.v * mult[0]);
              } else {
                fc = addHueToRGB(fc, animatorProps.fh.v * mult);
              }
            }
            if (animatorProps.fs.propType) {
              if (mult.length) {
                fc = addSaturationToRGB(fc, animatorProps.fs.v * mult[0]);
              } else {
                fc = addSaturationToRGB(fc, animatorProps.fs.v * mult);
              }
            }
            if (animatorProps.fb.propType) {
              if (mult.length) {
                fc = addBrightnessToRGB(fc, animatorProps.fb.v * mult[0]);
              } else {
                fc = addBrightnessToRGB(fc, animatorProps.fb.v * mult);
              }
            }
          }
        }
        for (j2 = 0; j2 < jLen; j2 += 1) {
          animatorProps = animators[j2].a;
          if (animatorProps.p.propType) {
            animatorSelector = animators[j2].s;
            mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars);
            if (this._hasMaskedPath) {
              if (mult.length) {
                matrixHelper.translate(0, animatorProps.p.v[1] * mult[0], -animatorProps.p.v[2] * mult[1]);
              } else {
                matrixHelper.translate(0, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult);
              }
            } else if (mult.length) {
              matrixHelper.translate(animatorProps.p.v[0] * mult[0], animatorProps.p.v[1] * mult[1], -animatorProps.p.v[2] * mult[2]);
            } else {
              matrixHelper.translate(animatorProps.p.v[0] * mult, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult);
            }
          }
        }
        if (documentData.strokeWidthAnim) {
          letterSw = sw < 0 ? 0 : sw;
        }
        if (documentData.strokeColorAnim) {
          letterSc = "rgb(" + Math.round(sc[0] * 255) + "," + Math.round(sc[1] * 255) + "," + Math.round(sc[2] * 255) + ")";
        }
        if (documentData.fillColorAnim && documentData.fc) {
          letterFc = "rgb(" + Math.round(fc[0] * 255) + "," + Math.round(fc[1] * 255) + "," + Math.round(fc[2] * 255) + ")";
        }
        if (this._hasMaskedPath) {
          matrixHelper.translate(0, -documentData.ls);
          matrixHelper.translate(0, alignment[1] * yOff * 0.01 + yPos, 0);
          if (this._pathData.p.v) {
            tanAngle = (currentPoint.point[1] - prevPoint.point[1]) / (currentPoint.point[0] - prevPoint.point[0]);
            var rot = Math.atan(tanAngle) * 180 / Math.PI;
            if (currentPoint.point[0] < prevPoint.point[0]) {
              rot += 180;
            }
            matrixHelper.rotate(-rot * Math.PI / 180);
          }
          matrixHelper.translate(xPathPos, yPathPos, 0);
          currentLength -= alignment[0] * letters[i].an * 5e-3;
          if (letters[i + 1] && ind !== letters[i + 1].ind) {
            currentLength += letters[i].an / 2;
            currentLength += documentData.tr * 1e-3 * documentData.finalSize;
          }
        } else {
          matrixHelper.translate(xPos, yPos, 0);
          if (documentData.ps) {
            matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0);
          }
          switch (documentData.j) {
            case 1:
              matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]), 0, 0);
              break;
            case 2:
              matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]) / 2, 0, 0);
              break;
            default:
              break;
          }
          matrixHelper.translate(0, -documentData.ls);
          matrixHelper.translate(offf, 0, 0);
          matrixHelper.translate(alignment[0] * letters[i].an * 5e-3, alignment[1] * yOff * 0.01, 0);
          xPos += letters[i].l + documentData.tr * 1e-3 * documentData.finalSize;
        }
        if (renderType === "html") {
          letterM = matrixHelper.toCSS();
        } else if (renderType === "svg") {
          letterM = matrixHelper.to2dCSS();
        } else {
          letterP = [matrixHelper.props[0], matrixHelper.props[1], matrixHelper.props[2], matrixHelper.props[3], matrixHelper.props[4], matrixHelper.props[5], matrixHelper.props[6], matrixHelper.props[7], matrixHelper.props[8], matrixHelper.props[9], matrixHelper.props[10], matrixHelper.props[11], matrixHelper.props[12], matrixHelper.props[13], matrixHelper.props[14], matrixHelper.props[15]];
        }
        letterO = elemOpacity;
      }
      if (renderedLettersCount <= i) {
        letterValue = new LetterProps(letterO, letterSw, letterSc, letterFc, letterM, letterP);
        this.renderedLetters.push(letterValue);
        renderedLettersCount += 1;
        this.lettersChangedFlag = true;
      } else {
        letterValue = this.renderedLetters[i];
        this.lettersChangedFlag = letterValue.update(letterO, letterSw, letterSc, letterFc, letterM, letterP) || this.lettersChangedFlag;
      }
    }
  };
  TextAnimatorProperty.prototype.getValue = function() {
    if (this._elem.globalData.frameId === this._frameId) {
      return;
    }
    this._frameId = this._elem.globalData.frameId;
    this.iterateDynamicProperties();
  };
  TextAnimatorProperty.prototype.mHelper = new Matrix();
  TextAnimatorProperty.prototype.defaultPropsArray = [];
  extendPrototype([DynamicPropertyContainer], TextAnimatorProperty);
  ITextElement.prototype.initElement = function(data2, globalData2, comp2) {
    this.lettersChangedFlag = true;
    this.initFrame();
    this.initBaseData(data2, globalData2, comp2);
    this.textProperty = new TextProperty(this, data2.t, this.dynamicProperties);
    this.textAnimator = new TextAnimatorProperty(data2.t, this.renderType, this);
    this.initTransform(data2, globalData2, comp2);
    this.initHierarchy();
    this.initRenderable();
    this.initRendererElement();
    this.createContainerElements();
    this.createRenderableComponents();
    this.createContent();
    this.hide();
    this.textAnimator.searchProperties(this.dynamicProperties);
  };
  ITextElement.prototype.prepareFrame = function(num) {
    this._mdf = false;
    this.prepareRenderableFrame(num);
    this.prepareProperties(num, this.isInRange);
    if (this.textProperty._mdf || this.textProperty._isFirstFrame) {
      this.buildNewText();
      this.textProperty._isFirstFrame = false;
      this.textProperty._mdf = false;
    }
  };
  ITextElement.prototype.createPathShape = function(matrixHelper, shapes) {
    var j2;
    var jLen = shapes.length;
    var pathNodes;
    var shapeStr = "";
    for (j2 = 0; j2 < jLen; j2 += 1) {
      if (shapes[j2].ty === "sh") {
        pathNodes = shapes[j2].ks.k;
        shapeStr += buildShapeString(pathNodes, pathNodes.i.length, true, matrixHelper);
      }
    }
    return shapeStr;
  };
  ITextElement.prototype.updateDocumentData = function(newData, index2) {
    this.textProperty.updateDocumentData(newData, index2);
  };
  ITextElement.prototype.canResizeFont = function(_canResize) {
    this.textProperty.canResizeFont(_canResize);
  };
  ITextElement.prototype.setMinimumFontSize = function(_fontSize) {
    this.textProperty.setMinimumFontSize(_fontSize);
  };
  ITextElement.prototype.applyTextPropertiesToMatrix = function(documentData, matrixHelper, lineNumber, xPos, yPos) {
    if (documentData.ps) {
      matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0);
    }
    matrixHelper.translate(0, -documentData.ls, 0);
    switch (documentData.j) {
      case 1:
        matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]), 0, 0);
        break;
      case 2:
        matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]) / 2, 0, 0);
        break;
      default:
        break;
    }
    matrixHelper.translate(xPos, yPos, 0);
  };
  ITextElement.prototype.buildColor = function(colorData) {
    return "rgb(" + Math.round(colorData[0] * 255) + "," + Math.round(colorData[1] * 255) + "," + Math.round(colorData[2] * 255) + ")";
  };
  ITextElement.prototype.emptyProp = new LetterProps();
  ITextElement.prototype.destroy = function() {
  };
  emptyShapeData = {
    shapes: []
  };
  extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement, ITextElement], SVGTextLottieElement);
  SVGTextLottieElement.prototype.createContent = function() {
    if (this.data.singleShape && !this.globalData.fontManager.chars) {
      this.textContainer = createNS("text");
    }
  };
  SVGTextLottieElement.prototype.buildTextContents = function(textArray) {
    var i = 0;
    var len = textArray.length;
    var textContents = [];
    var currentTextContent = "";
    while (i < len) {
      if (textArray[i] === String.fromCharCode(13) || textArray[i] === String.fromCharCode(3)) {
        textContents.push(currentTextContent);
        currentTextContent = "";
      } else {
        currentTextContent += textArray[i];
      }
      i += 1;
    }
    textContents.push(currentTextContent);
    return textContents;
  };
  SVGTextLottieElement.prototype.buildShapeData = function(data2, scale2) {
    if (data2.shapes && data2.shapes.length) {
      var shape = data2.shapes[0];
      if (shape.it) {
        var shapeItem = shape.it[shape.it.length - 1];
        if (shapeItem.s) {
          shapeItem.s.k[0] = scale2;
          shapeItem.s.k[1] = scale2;
        }
      }
    }
    return data2;
  };
  SVGTextLottieElement.prototype.buildNewText = function() {
    this.addDynamicProperty(this);
    var i;
    var len;
    var documentData = this.textProperty.currentData;
    this.renderedLetters = createSizedArray(documentData ? documentData.l.length : 0);
    if (documentData.fc) {
      this.layerElement.setAttribute("fill", this.buildColor(documentData.fc));
    } else {
      this.layerElement.setAttribute("fill", "rgba(0,0,0,0)");
    }
    if (documentData.sc) {
      this.layerElement.setAttribute("stroke", this.buildColor(documentData.sc));
      this.layerElement.setAttribute("stroke-width", documentData.sw);
    }
    this.layerElement.setAttribute("font-size", documentData.finalSize);
    var fontData = this.globalData.fontManager.getFontByName(documentData.f);
    if (fontData.fClass) {
      this.layerElement.setAttribute("class", fontData.fClass);
    } else {
      this.layerElement.setAttribute("font-family", fontData.fFamily);
      var fWeight = documentData.fWeight;
      var fStyle = documentData.fStyle;
      this.layerElement.setAttribute("font-style", fStyle);
      this.layerElement.setAttribute("font-weight", fWeight);
    }
    this.layerElement.setAttribute("aria-label", documentData.t);
    var letters = documentData.l || [];
    var usesGlyphs = !!this.globalData.fontManager.chars;
    len = letters.length;
    var tSpan;
    var matrixHelper = this.mHelper;
    var shapeStr = "";
    var singleShape = this.data.singleShape;
    var xPos = 0;
    var yPos = 0;
    var firstLine = true;
    var trackingOffset = documentData.tr * 1e-3 * documentData.finalSize;
    if (singleShape && !usesGlyphs && !documentData.sz) {
      var tElement = this.textContainer;
      var justify = "start";
      switch (documentData.j) {
        case 1:
          justify = "end";
          break;
        case 2:
          justify = "middle";
          break;
        default:
          justify = "start";
          break;
      }
      tElement.setAttribute("text-anchor", justify);
      tElement.setAttribute("letter-spacing", trackingOffset);
      var textContent = this.buildTextContents(documentData.finalText);
      len = textContent.length;
      yPos = documentData.ps ? documentData.ps[1] + documentData.ascent : 0;
      for (i = 0; i < len; i += 1) {
        tSpan = this.textSpans[i].span || createNS("tspan");
        tSpan.textContent = textContent[i];
        tSpan.setAttribute("x", 0);
        tSpan.setAttribute("y", yPos);
        tSpan.style.display = "inherit";
        tElement.appendChild(tSpan);
        if (!this.textSpans[i]) {
          this.textSpans[i] = {
            span: null,
            glyph: null
          };
        }
        this.textSpans[i].span = tSpan;
        yPos += documentData.finalLineHeight;
      }
      this.layerElement.appendChild(tElement);
    } else {
      var cachedSpansLength = this.textSpans.length;
      var charData;
      for (i = 0; i < len; i += 1) {
        if (!this.textSpans[i]) {
          this.textSpans[i] = {
            span: null,
            childSpan: null,
            glyph: null
          };
        }
        if (!usesGlyphs || !singleShape || i === 0) {
          tSpan = cachedSpansLength > i ? this.textSpans[i].span : createNS(usesGlyphs ? "g" : "text");
          if (cachedSpansLength <= i) {
            tSpan.setAttribute("stroke-linecap", "butt");
            tSpan.setAttribute("stroke-linejoin", "round");
            tSpan.setAttribute("stroke-miterlimit", "4");
            this.textSpans[i].span = tSpan;
            if (usesGlyphs) {
              var childSpan = createNS("g");
              tSpan.appendChild(childSpan);
              this.textSpans[i].childSpan = childSpan;
            }
            this.textSpans[i].span = tSpan;
            this.layerElement.appendChild(tSpan);
          }
          tSpan.style.display = "inherit";
        }
        matrixHelper.reset();
        if (singleShape) {
          if (letters[i].n) {
            xPos = -trackingOffset;
            yPos += documentData.yOffset;
            yPos += firstLine ? 1 : 0;
            firstLine = false;
          }
          this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos);
          xPos += letters[i].l || 0;
          xPos += trackingOffset;
        }
        if (usesGlyphs) {
          charData = this.globalData.fontManager.getCharData(
            documentData.finalText[i],
            fontData.fStyle,
            this.globalData.fontManager.getFontByName(documentData.f).fFamily
          );
          var glyphElement;
          if (charData.t === 1) {
            glyphElement = new SVGCompElement(charData.data, this.globalData, this);
          } else {
            var data2 = emptyShapeData;
            if (charData.data && charData.data.shapes) {
              data2 = this.buildShapeData(charData.data, documentData.finalSize);
            }
            glyphElement = new SVGShapeElement(data2, this.globalData, this);
          }
          if (this.textSpans[i].glyph) {
            var glyph = this.textSpans[i].glyph;
            this.textSpans[i].childSpan.removeChild(glyph.layerElement);
            glyph.destroy();
          }
          this.textSpans[i].glyph = glyphElement;
          glyphElement._debug = true;
          glyphElement.prepareFrame(0);
          glyphElement.renderFrame();
          this.textSpans[i].childSpan.appendChild(glyphElement.layerElement);
          if (charData.t === 1) {
            this.textSpans[i].childSpan.setAttribute("transform", "scale(" + documentData.finalSize / 100 + "," + documentData.finalSize / 100 + ")");
          }
        } else {
          if (singleShape) {
            tSpan.setAttribute("transform", "translate(" + matrixHelper.props[12] + "," + matrixHelper.props[13] + ")");
          }
          tSpan.textContent = letters[i].val;
          tSpan.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve");
        }
      }
      if (singleShape && tSpan) {
        tSpan.setAttribute("d", shapeStr);
      }
    }
    while (i < this.textSpans.length) {
      this.textSpans[i].span.style.display = "none";
      i += 1;
    }
    this._sizeChanged = true;
  };
  SVGTextLottieElement.prototype.sourceRectAtTime = function() {
    this.prepareFrame(this.comp.renderedFrame - this.data.st);
    this.renderInnerContent();
    if (this._sizeChanged) {
      this._sizeChanged = false;
      var textBox = this.layerElement.getBBox();
      this.bbox = {
        top: textBox.y,
        left: textBox.x,
        width: textBox.width,
        height: textBox.height
      };
    }
    return this.bbox;
  };
  SVGTextLottieElement.prototype.getValue = function() {
    var i;
    var len = this.textSpans.length;
    var glyphElement;
    this.renderedFrame = this.comp.renderedFrame;
    for (i = 0; i < len; i += 1) {
      glyphElement = this.textSpans[i].glyph;
      if (glyphElement) {
        glyphElement.prepareFrame(this.comp.renderedFrame - this.data.st);
        if (glyphElement._mdf) {
          this._mdf = true;
        }
      }
    }
  };
  SVGTextLottieElement.prototype.renderInnerContent = function() {
    if (!this.data.singleShape || this._mdf) {
      this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag);
      if (this.lettersChangedFlag || this.textAnimator.lettersChangedFlag) {
        this._sizeChanged = true;
        var i;
        var len;
        var renderedLetters = this.textAnimator.renderedLetters;
        var letters = this.textProperty.currentData.l;
        len = letters.length;
        var renderedLetter;
        var textSpan;
        var glyphElement;
        for (i = 0; i < len; i += 1) {
          if (!letters[i].n) {
            renderedLetter = renderedLetters[i];
            textSpan = this.textSpans[i].span;
            glyphElement = this.textSpans[i].glyph;
            if (glyphElement) {
              glyphElement.renderFrame();
            }
            if (renderedLetter._mdf.m) {
              textSpan.setAttribute("transform", renderedLetter.m);
            }
            if (renderedLetter._mdf.o) {
              textSpan.setAttribute("opacity", renderedLetter.o);
            }
            if (renderedLetter._mdf.sw) {
              textSpan.setAttribute("stroke-width", renderedLetter.sw);
            }
            if (renderedLetter._mdf.sc) {
              textSpan.setAttribute("stroke", renderedLetter.sc);
            }
            if (renderedLetter._mdf.fc) {
              textSpan.setAttribute("fill", renderedLetter.fc);
            }
          }
        }
      }
    }
  };
  extendPrototype([IImageElement], ISolidElement);
  ISolidElement.prototype.createContent = function() {
    var rect = createNS("rect");
    rect.setAttribute("width", this.data.sw);
    rect.setAttribute("height", this.data.sh);
    rect.setAttribute("fill", this.data.sc);
    this.layerElement.appendChild(rect);
  };
  NullElement.prototype.prepareFrame = function(num) {
    this.prepareProperties(num, true);
  };
  NullElement.prototype.renderFrame = function() {
  };
  NullElement.prototype.getBaseElement = function() {
    return null;
  };
  NullElement.prototype.destroy = function() {
  };
  NullElement.prototype.sourceRectAtTime = function() {
  };
  NullElement.prototype.hide = function() {
  };
  extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement], NullElement);
  extendPrototype([BaseRenderer], SVGRendererBase);
  SVGRendererBase.prototype.createNull = function(data2) {
    return new NullElement(data2, this.globalData, this);
  };
  SVGRendererBase.prototype.createShape = function(data2) {
    return new SVGShapeElement(data2, this.globalData, this);
  };
  SVGRendererBase.prototype.createText = function(data2) {
    return new SVGTextLottieElement(data2, this.globalData, this);
  };
  SVGRendererBase.prototype.createImage = function(data2) {
    return new IImageElement(data2, this.globalData, this);
  };
  SVGRendererBase.prototype.createSolid = function(data2) {
    return new ISolidElement(data2, this.globalData, this);
  };
  SVGRendererBase.prototype.configAnimation = function(animData) {
    this.svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg");
    if (this.renderConfig.viewBoxSize) {
      this.svgElement.setAttribute("viewBox", this.renderConfig.viewBoxSize);
    } else {
      this.svgElement.setAttribute("viewBox", "0 0 " + animData.w + " " + animData.h);
    }
    if (!this.renderConfig.viewBoxOnly) {
      this.svgElement.setAttribute("width", animData.w);
      this.svgElement.setAttribute("height", animData.h);
      this.svgElement.style.width = "100%";
      this.svgElement.style.height = "100%";
      this.svgElement.style.transform = "translate3d(0,0,0)";
      this.svgElement.style.contentVisibility = this.renderConfig.contentVisibility;
    }
    if (this.renderConfig.width) {
      this.svgElement.setAttribute("width", this.renderConfig.width);
    }
    if (this.renderConfig.height) {
      this.svgElement.setAttribute("height", this.renderConfig.height);
    }
    if (this.renderConfig.className) {
      this.svgElement.setAttribute("class", this.renderConfig.className);
    }
    if (this.renderConfig.id) {
      this.svgElement.setAttribute("id", this.renderConfig.id);
    }
    if (this.renderConfig.focusable !== void 0) {
      this.svgElement.setAttribute("focusable", this.renderConfig.focusable);
    }
    this.svgElement.setAttribute("preserveAspectRatio", this.renderConfig.preserveAspectRatio);
    this.animationItem.wrapper.appendChild(this.svgElement);
    var defs = this.globalData.defs;
    this.setupGlobalData(animData, defs);
    this.globalData.progressiveLoad = this.renderConfig.progressiveLoad;
    this.data = animData;
    var maskElement = createNS("clipPath");
    var rect = createNS("rect");
    rect.setAttribute("width", animData.w);
    rect.setAttribute("height", animData.h);
    rect.setAttribute("x", 0);
    rect.setAttribute("y", 0);
    var maskId = createElementID();
    maskElement.setAttribute("id", maskId);
    maskElement.appendChild(rect);
    this.layerElement.setAttribute("clip-path", "url(" + getLocationHref() + "#" + maskId + ")");
    defs.appendChild(maskElement);
    this.layers = animData.layers;
    this.elements = createSizedArray(animData.layers.length);
  };
  SVGRendererBase.prototype.destroy = function() {
    if (this.animationItem.wrapper) {
      this.animationItem.wrapper.innerText = "";
    }
    this.layerElement = null;
    this.globalData.defs = null;
    var i;
    var len = this.layers ? this.layers.length : 0;
    for (i = 0; i < len; i += 1) {
      if (this.elements[i]) {
        this.elements[i].destroy();
      }
    }
    this.elements.length = 0;
    this.destroyed = true;
    this.animationItem = null;
  };
  SVGRendererBase.prototype.updateContainerSize = function() {
  };
  SVGRendererBase.prototype.buildItem = function(pos) {
    var elements = this.elements;
    if (elements[pos] || this.layers[pos].ty === 99) {
      return;
    }
    elements[pos] = true;
    var element = this.createItem(this.layers[pos]);
    elements[pos] = element;
    if (getExpressionsPlugin()) {
      if (this.layers[pos].ty === 0) {
        this.globalData.projectInterface.registerComposition(element);
      }
      element.initExpressions();
    }
    this.appendElementInPos(element, pos);
    if (this.layers[pos].tt) {
      if (!this.elements[pos - 1] || this.elements[pos - 1] === true) {
        this.buildItem(pos - 1);
        this.addPendingElement(element);
      } else {
        element.setMatte(elements[pos - 1].layerId);
      }
    }
  };
  SVGRendererBase.prototype.checkPendingElements = function() {
    while (this.pendingElements.length) {
      var element = this.pendingElements.pop();
      element.checkParenting();
      if (element.data.tt) {
        var i = 0;
        var len = this.elements.length;
        while (i < len) {
          if (this.elements[i] === element) {
            element.setMatte(this.elements[i - 1].layerId);
            break;
          }
          i += 1;
        }
      }
    }
  };
  SVGRendererBase.prototype.renderFrame = function(num) {
    if (this.renderedFrame === num || this.destroyed) {
      return;
    }
    if (num === null) {
      num = this.renderedFrame;
    } else {
      this.renderedFrame = num;
    }
    this.globalData.frameNum = num;
    this.globalData.frameId += 1;
    this.globalData.projectInterface.currentFrame = num;
    this.globalData._mdf = false;
    var i;
    var len = this.layers.length;
    if (!this.completeLayers) {
      this.checkLayers(num);
    }
    for (i = len - 1; i >= 0; i -= 1) {
      if (this.completeLayers || this.elements[i]) {
        this.elements[i].prepareFrame(num - this.layers[i].st);
      }
    }
    if (this.globalData._mdf) {
      for (i = 0; i < len; i += 1) {
        if (this.completeLayers || this.elements[i]) {
          this.elements[i].renderFrame();
        }
      }
    }
  };
  SVGRendererBase.prototype.appendElementInPos = function(element, pos) {
    var newElement = element.getBaseElement();
    if (!newElement) {
      return;
    }
    var i = 0;
    var nextElement;
    while (i < pos) {
      if (this.elements[i] && this.elements[i] !== true && this.elements[i].getBaseElement()) {
        nextElement = this.elements[i].getBaseElement();
      }
      i += 1;
    }
    if (nextElement) {
      this.layerElement.insertBefore(newElement, nextElement);
    } else {
      this.layerElement.appendChild(newElement);
    }
  };
  SVGRendererBase.prototype.hide = function() {
    this.layerElement.style.display = "none";
  };
  SVGRendererBase.prototype.show = function() {
    this.layerElement.style.display = "block";
  };
  extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement, RenderableDOMElement], ICompElement);
  ICompElement.prototype.initElement = function(data2, globalData2, comp2) {
    this.initFrame();
    this.initBaseData(data2, globalData2, comp2);
    this.initTransform(data2, globalData2, comp2);
    this.initRenderable();
    this.initHierarchy();
    this.initRendererElement();
    this.createContainerElements();
    this.createRenderableComponents();
    if (this.data.xt || !globalData2.progressiveLoad) {
      this.buildAllItems();
    }
    this.hide();
  };
  ICompElement.prototype.prepareFrame = function(num) {
    this._mdf = false;
    this.prepareRenderableFrame(num);
    this.prepareProperties(num, this.isInRange);
    if (!this.isInRange && !this.data.xt) {
      return;
    }
    if (!this.tm._placeholder) {
      var timeRemapped = this.tm.v;
      if (timeRemapped === this.data.op) {
        timeRemapped = this.data.op - 1;
      }
      this.renderedFrame = timeRemapped;
    } else {
      this.renderedFrame = num / this.data.sr;
    }
    var i;
    var len = this.elements.length;
    if (!this.completeLayers) {
      this.checkLayers(this.renderedFrame);
    }
    for (i = len - 1; i >= 0; i -= 1) {
      if (this.completeLayers || this.elements[i]) {
        this.elements[i].prepareFrame(this.renderedFrame - this.layers[i].st);
        if (this.elements[i]._mdf) {
          this._mdf = true;
        }
      }
    }
  };
  ICompElement.prototype.renderInnerContent = function() {
    var i;
    var len = this.layers.length;
    for (i = 0; i < len; i += 1) {
      if (this.completeLayers || this.elements[i]) {
        this.elements[i].renderFrame();
      }
    }
  };
  ICompElement.prototype.setElements = function(elems) {
    this.elements = elems;
  };
  ICompElement.prototype.getElements = function() {
    return this.elements;
  };
  ICompElement.prototype.destroyElements = function() {
    var i;
    var len = this.layers.length;
    for (i = 0; i < len; i += 1) {
      if (this.elements[i]) {
        this.elements[i].destroy();
      }
    }
  };
  ICompElement.prototype.destroy = function() {
    this.destroyElements();
    this.destroyBaseElement();
  };
  extendPrototype([SVGRendererBase, ICompElement, SVGBaseElement], SVGCompElement);
  SVGCompElement.prototype.createComp = function(data2) {
    return new SVGCompElement(data2, this.globalData, this);
  };
  extendPrototype([SVGRendererBase], SVGRenderer);
  SVGRenderer.prototype.createComp = function(data2) {
    return new SVGCompElement(data2, this.globalData, this);
  };
  CVContextData.prototype.duplicate = function() {
    var newLength = this._length * 2;
    var currentSavedOp = this.savedOp;
    this.savedOp = createTypedArray("float32", newLength);
    this.savedOp.set(currentSavedOp);
    var i = 0;
    for (i = this._length; i < newLength; i += 1) {
      this.saved[i] = createTypedArray("float32", 16);
    }
    this._length = newLength;
  };
  CVContextData.prototype.reset = function() {
    this.cArrPos = 0;
    this.cTr.reset();
    this.cO = 1;
  };
  ShapeTransformManager.prototype = {
    addTransformSequence: function(transforms) {
      var i;
      var len = transforms.length;
      var key2 = "_";
      for (i = 0; i < len; i += 1) {
        key2 += transforms[i].transform.key + "_";
      }
      var sequence = this.sequences[key2];
      if (!sequence) {
        sequence = {
          transforms: [].concat(transforms),
          finalTransform: new Matrix(),
          _mdf: false
        };
        this.sequences[key2] = sequence;
        this.sequenceList.push(sequence);
      }
      return sequence;
    },
    processSequence: function(sequence, isFirstFrame) {
      var i = 0;
      var len = sequence.transforms.length;
      var _mdf = isFirstFrame;
      while (i < len && !isFirstFrame) {
        if (sequence.transforms[i].transform.mProps._mdf) {
          _mdf = true;
          break;
        }
        i += 1;
      }
      if (_mdf) {
        var props;
        sequence.finalTransform.reset();
        for (i = len - 1; i >= 0; i -= 1) {
          props = sequence.transforms[i].transform.mProps.v.props;
          sequence.finalTransform.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]);
        }
      }
      sequence._mdf = _mdf;
    },
    processSequences: function(isFirstFrame) {
      var i;
      var len = this.sequenceList.length;
      for (i = 0; i < len; i += 1) {
        this.processSequence(this.sequenceList[i], isFirstFrame);
      }
    },
    getNewKey: function() {
      this.transform_key_count += 1;
      return "_" + this.transform_key_count;
    }
  };
  CVEffects.prototype.renderFrame = function() {
  };
  CVMaskElement.prototype.renderFrame = function() {
    if (!this.hasMasks) {
      return;
    }
    var transform2 = this.element.finalTransform.mat;
    var ctx = this.element.canvasContext;
    var i;
    var len = this.masksProperties.length;
    var pt;
    var pts;
    var data2;
    ctx.beginPath();
    for (i = 0; i < len; i += 1) {
      if (this.masksProperties[i].mode !== "n") {
        if (this.masksProperties[i].inv) {
          ctx.moveTo(0, 0);
          ctx.lineTo(this.element.globalData.compSize.w, 0);
          ctx.lineTo(this.element.globalData.compSize.w, this.element.globalData.compSize.h);
          ctx.lineTo(0, this.element.globalData.compSize.h);
          ctx.lineTo(0, 0);
        }
        data2 = this.viewData[i].v;
        pt = transform2.applyToPointArray(data2.v[0][0], data2.v[0][1], 0);
        ctx.moveTo(pt[0], pt[1]);
        var j2;
        var jLen = data2._length;
        for (j2 = 1; j2 < jLen; j2 += 1) {
          pts = transform2.applyToTriplePoints(data2.o[j2 - 1], data2.i[j2], data2.v[j2]);
          ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]);
        }
        pts = transform2.applyToTriplePoints(data2.o[j2 - 1], data2.i[0], data2.v[0]);
        ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]);
      }
    }
    this.element.globalData.renderer.save(true);
    ctx.clip();
  };
  CVMaskElement.prototype.getMaskProperty = MaskElement.prototype.getMaskProperty;
  CVMaskElement.prototype.destroy = function() {
    this.element = null;
  };
  CVBaseElement.prototype = {
    createElements: function() {
    },
    initRendererElement: function() {
    },
    createContainerElements: function() {
      this.canvasContext = this.globalData.canvasContext;
      this.renderableEffectsManager = new CVEffects(this);
    },
    createContent: function() {
    },
    setBlendMode: function() {
      var globalData2 = this.globalData;
      if (globalData2.blendMode !== this.data.bm) {
        globalData2.blendMode = this.data.bm;
        var blendModeValue = getBlendMode(this.data.bm);
        globalData2.canvasContext.globalCompositeOperation = blendModeValue;
      }
    },
    createRenderableComponents: function() {
      this.maskManager = new CVMaskElement(this.data, this);
    },
    hideElement: function() {
      if (!this.hidden && (!this.isInRange || this.isTransparent)) {
        this.hidden = true;
      }
    },
    showElement: function() {
      if (this.isInRange && !this.isTransparent) {
        this.hidden = false;
        this._isFirstFrame = true;
        this.maskManager._isFirstFrame = true;
      }
    },
    renderFrame: function() {
      if (this.hidden || this.data.hd) {
        return;
      }
      this.renderTransform();
      this.renderRenderable();
      this.setBlendMode();
      var forceRealStack = this.data.ty === 0;
      this.globalData.renderer.save(forceRealStack);
      this.globalData.renderer.ctxTransform(this.finalTransform.mat.props);
      this.globalData.renderer.ctxOpacity(this.finalTransform.mProp.o.v);
      this.renderInnerContent();
      this.globalData.renderer.restore(forceRealStack);
      if (this.maskManager.hasMasks) {
        this.globalData.renderer.restore(true);
      }
      if (this._isFirstFrame) {
        this._isFirstFrame = false;
      }
    },
    destroy: function() {
      this.canvasContext = null;
      this.data = null;
      this.globalData = null;
      this.maskManager.destroy();
    },
    mHelper: new Matrix()
  };
  CVBaseElement.prototype.hide = CVBaseElement.prototype.hideElement;
  CVBaseElement.prototype.show = CVBaseElement.prototype.showElement;
  CVShapeData.prototype.setAsAnimated = SVGShapeData.prototype.setAsAnimated;
  extendPrototype([BaseElement, TransformElement, CVBaseElement, IShapeElement, HierarchyElement, FrameElement, RenderableElement], CVShapeElement);
  CVShapeElement.prototype.initElement = RenderableDOMElement.prototype.initElement;
  CVShapeElement.prototype.transformHelper = { opacity: 1, _opMdf: false };
  CVShapeElement.prototype.dashResetter = [];
  CVShapeElement.prototype.createContent = function() {
    this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []);
  };
  CVShapeElement.prototype.createStyleElement = function(data2, transforms) {
    var styleElem = {
      data: data2,
      type: data2.ty,
      preTransforms: this.transformsManager.addTransformSequence(transforms),
      transforms: [],
      elements: [],
      closed: data2.hd === true
    };
    var elementData = {};
    if (data2.ty === "fl" || data2.ty === "st") {
      elementData.c = PropertyFactory.getProp(this, data2.c, 1, 255, this);
      if (!elementData.c.k) {
        styleElem.co = "rgb(" + bmFloor(elementData.c.v[0]) + "," + bmFloor(elementData.c.v[1]) + "," + bmFloor(elementData.c.v[2]) + ")";
      }
    } else if (data2.ty === "gf" || data2.ty === "gs") {
      elementData.s = PropertyFactory.getProp(this, data2.s, 1, null, this);
      elementData.e = PropertyFactory.getProp(this, data2.e, 1, null, this);
      elementData.h = PropertyFactory.getProp(this, data2.h || { k: 0 }, 0, 0.01, this);
      elementData.a = PropertyFactory.getProp(this, data2.a || { k: 0 }, 0, degToRads, this);
      elementData.g = new GradientProperty(this, data2.g, this);
    }
    elementData.o = PropertyFactory.getProp(this, data2.o, 0, 0.01, this);
    if (data2.ty === "st" || data2.ty === "gs") {
      styleElem.lc = lineCapEnum[data2.lc || 2];
      styleElem.lj = lineJoinEnum[data2.lj || 2];
      if (data2.lj == 1) {
        styleElem.ml = data2.ml;
      }
      elementData.w = PropertyFactory.getProp(this, data2.w, 0, null, this);
      if (!elementData.w.k) {
        styleElem.wi = elementData.w.v;
      }
      if (data2.d) {
        var d = new DashProperty(this, data2.d, "canvas", this);
        elementData.d = d;
        if (!elementData.d.k) {
          styleElem.da = elementData.d.dashArray;
          styleElem.do = elementData.d.dashoffset[0];
        }
      }
    } else {
      styleElem.r = data2.r === 2 ? "evenodd" : "nonzero";
    }
    this.stylesList.push(styleElem);
    elementData.style = styleElem;
    return elementData;
  };
  CVShapeElement.prototype.createGroupElement = function() {
    var elementData = {
      it: [],
      prevViewData: []
    };
    return elementData;
  };
  CVShapeElement.prototype.createTransformElement = function(data2) {
    var elementData = {
      transform: {
        opacity: 1,
        _opMdf: false,
        key: this.transformsManager.getNewKey(),
        op: PropertyFactory.getProp(this, data2.o, 0, 0.01, this),
        mProps: TransformPropertyFactory.getTransformProperty(this, data2, this)
      }
    };
    return elementData;
  };
  CVShapeElement.prototype.createShapeElement = function(data2) {
    var elementData = new CVShapeData(this, data2, this.stylesList, this.transformsManager);
    this.shapes.push(elementData);
    this.addShapeToModifiers(elementData);
    return elementData;
  };
  CVShapeElement.prototype.reloadShapes = function() {
    this._isFirstFrame = true;
    var i;
    var len = this.itemsData.length;
    for (i = 0; i < len; i += 1) {
      this.prevViewData[i] = this.itemsData[i];
    }
    this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []);
    len = this.dynamicProperties.length;
    for (i = 0; i < len; i += 1) {
      this.dynamicProperties[i].getValue();
    }
    this.renderModifiers();
    this.transformsManager.processSequences(this._isFirstFrame);
  };
  CVShapeElement.prototype.addTransformToStyleList = function(transform2) {
    var i;
    var len = this.stylesList.length;
    for (i = 0; i < len; i += 1) {
      if (!this.stylesList[i].closed) {
        this.stylesList[i].transforms.push(transform2);
      }
    }
  };
  CVShapeElement.prototype.removeTransformFromStyleList = function() {
    var i;
    var len = this.stylesList.length;
    for (i = 0; i < len; i += 1) {
      if (!this.stylesList[i].closed) {
        this.stylesList[i].transforms.pop();
      }
    }
  };
  CVShapeElement.prototype.closeStyles = function(styles) {
    var i;
    var len = styles.length;
    for (i = 0; i < len; i += 1) {
      styles[i].closed = true;
    }
  };
  CVShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, shouldRender, transforms) {
    var i;
    var len = arr.length - 1;
    var j2;
    var jLen;
    var ownStyles = [];
    var ownModifiers = [];
    var processedPos;
    var modifier;
    var currentTransform;
    var ownTransforms = [].concat(transforms);
    for (i = len; i >= 0; i -= 1) {
      processedPos = this.searchProcessedElement(arr[i]);
      if (!processedPos) {
        arr[i]._shouldRender = shouldRender;
      } else {
        itemsData[i] = prevViewData[processedPos - 1];
      }
      if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs") {
        if (!processedPos) {
          itemsData[i] = this.createStyleElement(arr[i], ownTransforms);
        } else {
          itemsData[i].style.closed = false;
        }
        ownStyles.push(itemsData[i].style);
      } else if (arr[i].ty === "gr") {
        if (!processedPos) {
          itemsData[i] = this.createGroupElement(arr[i]);
        } else {
          jLen = itemsData[i].it.length;
          for (j2 = 0; j2 < jLen; j2 += 1) {
            itemsData[i].prevViewData[j2] = itemsData[i].it[j2];
          }
        }
        this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, shouldRender, ownTransforms);
      } else if (arr[i].ty === "tr") {
        if (!processedPos) {
          currentTransform = this.createTransformElement(arr[i]);
          itemsData[i] = currentTransform;
        }
        ownTransforms.push(itemsData[i]);
        this.addTransformToStyleList(itemsData[i]);
      } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") {
        if (!processedPos) {
          itemsData[i] = this.createShapeElement(arr[i]);
        }
      } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "pb") {
        if (!processedPos) {
          modifier = ShapeModifiers.getModifier(arr[i].ty);
          modifier.init(this, arr[i]);
          itemsData[i] = modifier;
          this.shapeModifiers.push(modifier);
        } else {
          modifier = itemsData[i];
          modifier.closed = false;
        }
        ownModifiers.push(modifier);
      } else if (arr[i].ty === "rp") {
        if (!processedPos) {
          modifier = ShapeModifiers.getModifier(arr[i].ty);
          itemsData[i] = modifier;
          modifier.init(this, arr, i, itemsData);
          this.shapeModifiers.push(modifier);
          shouldRender = false;
        } else {
          modifier = itemsData[i];
          modifier.closed = true;
        }
        ownModifiers.push(modifier);
      }
      this.addProcessedElement(arr[i], i + 1);
    }
    this.removeTransformFromStyleList();
    this.closeStyles(ownStyles);
    len = ownModifiers.length;
    for (i = 0; i < len; i += 1) {
      ownModifiers[i].closed = true;
    }
  };
  CVShapeElement.prototype.renderInnerContent = function() {
    this.transformHelper.opacity = 1;
    this.transformHelper._opMdf = false;
    this.renderModifiers();
    this.transformsManager.processSequences(this._isFirstFrame);
    this.renderShape(this.transformHelper, this.shapesData, this.itemsData, true);
  };
  CVShapeElement.prototype.renderShapeTransform = function(parentTransform, groupTransform) {
    if (parentTransform._opMdf || groupTransform.op._mdf || this._isFirstFrame) {
      groupTransform.opacity = parentTransform.opacity;
      groupTransform.opacity *= groupTransform.op.v;
      groupTransform._opMdf = true;
    }
  };
  CVShapeElement.prototype.drawLayer = function() {
    var i;
    var len = this.stylesList.length;
    var j2;
    var jLen;
    var k2;
    var kLen;
    var elems;
    var nodes;
    var renderer2 = this.globalData.renderer;
    var ctx = this.globalData.canvasContext;
    var type;
    var currentStyle;
    for (i = 0; i < len; i += 1) {
      currentStyle = this.stylesList[i];
      type = currentStyle.type;
      if (!((type === "st" || type === "gs") && currentStyle.wi === 0 || !currentStyle.data._shouldRender || currentStyle.coOp === 0 || this.globalData.currentGlobalAlpha === 0)) {
        renderer2.save();
        elems = currentStyle.elements;
        if (type === "st" || type === "gs") {
          ctx.strokeStyle = type === "st" ? currentStyle.co : currentStyle.grd;
          ctx.lineWidth = currentStyle.wi;
          ctx.lineCap = currentStyle.lc;
          ctx.lineJoin = currentStyle.lj;
          ctx.miterLimit = currentStyle.ml || 0;
        } else {
          ctx.fillStyle = type === "fl" ? currentStyle.co : currentStyle.grd;
        }
        renderer2.ctxOpacity(currentStyle.coOp);
        if (type !== "st" && type !== "gs") {
          ctx.beginPath();
        }
        renderer2.ctxTransform(currentStyle.preTransforms.finalTransform.props);
        jLen = elems.length;
        for (j2 = 0; j2 < jLen; j2 += 1) {
          if (type === "st" || type === "gs") {
            ctx.beginPath();
            if (currentStyle.da) {
              ctx.setLineDash(currentStyle.da);
              ctx.lineDashOffset = currentStyle.do;
            }
          }
          nodes = elems[j2].trNodes;
          kLen = nodes.length;
          for (k2 = 0; k2 < kLen; k2 += 1) {
            if (nodes[k2].t === "m") {
              ctx.moveTo(nodes[k2].p[0], nodes[k2].p[1]);
            } else if (nodes[k2].t === "c") {
              ctx.bezierCurveTo(nodes[k2].pts[0], nodes[k2].pts[1], nodes[k2].pts[2], nodes[k2].pts[3], nodes[k2].pts[4], nodes[k2].pts[5]);
            } else {
              ctx.closePath();
            }
          }
          if (type === "st" || type === "gs") {
            ctx.stroke();
            if (currentStyle.da) {
              ctx.setLineDash(this.dashResetter);
            }
          }
        }
        if (type !== "st" && type !== "gs") {
          ctx.fill(currentStyle.r);
        }
        renderer2.restore();
      }
    }
  };
  CVShapeElement.prototype.renderShape = function(parentTransform, items, data2, isMain) {
    var i;
    var len = items.length - 1;
    var groupTransform;
    groupTransform = parentTransform;
    for (i = len; i >= 0; i -= 1) {
      if (items[i].ty === "tr") {
        groupTransform = data2[i].transform;
        this.renderShapeTransform(parentTransform, groupTransform);
      } else if (items[i].ty === "sh" || items[i].ty === "el" || items[i].ty === "rc" || items[i].ty === "sr") {
        this.renderPath(items[i], data2[i]);
      } else if (items[i].ty === "fl") {
        this.renderFill(items[i], data2[i], groupTransform);
      } else if (items[i].ty === "st") {
        this.renderStroke(items[i], data2[i], groupTransform);
      } else if (items[i].ty === "gf" || items[i].ty === "gs") {
        this.renderGradientFill(items[i], data2[i], groupTransform);
      } else if (items[i].ty === "gr") {
        this.renderShape(groupTransform, items[i].it, data2[i].it);
      } else if (items[i].ty === "tm") {
      }
    }
    if (isMain) {
      this.drawLayer();
    }
  };
  CVShapeElement.prototype.renderStyledShape = function(styledShape, shape) {
    if (this._isFirstFrame || shape._mdf || styledShape.transforms._mdf) {
      var shapeNodes = styledShape.trNodes;
      var paths = shape.paths;
      var i;
      var len;
      var j2;
      var jLen = paths._length;
      shapeNodes.length = 0;
      var groupTransformMat = styledShape.transforms.finalTransform;
      for (j2 = 0; j2 < jLen; j2 += 1) {
        var pathNodes = paths.shapes[j2];
        if (pathNodes && pathNodes.v) {
          len = pathNodes._length;
          for (i = 1; i < len; i += 1) {
            if (i === 1) {
              shapeNodes.push({
                t: "m",
                p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0)
              });
            }
            shapeNodes.push({
              t: "c",
              pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[i], pathNodes.v[i])
            });
          }
          if (len === 1) {
            shapeNodes.push({
              t: "m",
              p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0)
            });
          }
          if (pathNodes.c && len) {
            shapeNodes.push({
              t: "c",
              pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[0], pathNodes.v[0])
            });
            shapeNodes.push({
              t: "z"
            });
          }
        }
      }
      styledShape.trNodes = shapeNodes;
    }
  };
  CVShapeElement.prototype.renderPath = function(pathData, itemData) {
    if (pathData.hd !== true && pathData._shouldRender) {
      var i;
      var len = itemData.styledShapes.length;
      for (i = 0; i < len; i += 1) {
        this.renderStyledShape(itemData.styledShapes[i], itemData.sh);
      }
    }
  };
  CVShapeElement.prototype.renderFill = function(styleData, itemData, groupTransform) {
    var styleElem = itemData.style;
    if (itemData.c._mdf || this._isFirstFrame) {
      styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")";
    }
    if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) {
      styleElem.coOp = itemData.o.v * groupTransform.opacity;
    }
  };
  CVShapeElement.prototype.renderGradientFill = function(styleData, itemData, groupTransform) {
    var styleElem = itemData.style;
    var grd;
    if (!styleElem.grd || itemData.g._mdf || itemData.s._mdf || itemData.e._mdf || styleData.t !== 1 && (itemData.h._mdf || itemData.a._mdf)) {
      var ctx = this.globalData.canvasContext;
      var pt1 = itemData.s.v;
      var pt2 = itemData.e.v;
      if (styleData.t === 1) {
        grd = ctx.createLinearGradient(pt1[0], pt1[1], pt2[0], pt2[1]);
      } else {
        var rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2));
        var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]);
        var percent = itemData.h.v;
        if (percent >= 1) {
          percent = 0.99;
        } else if (percent <= -1) {
          percent = -0.99;
        }
        var dist = rad * percent;
        var x2 = Math.cos(ang + itemData.a.v) * dist + pt1[0];
        var y = Math.sin(ang + itemData.a.v) * dist + pt1[1];
        grd = ctx.createRadialGradient(x2, y, 0, pt1[0], pt1[1], rad);
      }
      var i;
      var len = styleData.g.p;
      var cValues = itemData.g.c;
      var opacity = 1;
      for (i = 0; i < len; i += 1) {
        if (itemData.g._hasOpacity && itemData.g._collapsable) {
          opacity = itemData.g.o[i * 2 + 1];
        }
        grd.addColorStop(cValues[i * 4] / 100, "rgba(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + "," + opacity + ")");
      }
      styleElem.grd = grd;
    }
    styleElem.coOp = itemData.o.v * groupTransform.opacity;
  };
  CVShapeElement.prototype.renderStroke = function(styleData, itemData, groupTransform) {
    var styleElem = itemData.style;
    var d = itemData.d;
    if (d && (d._mdf || this._isFirstFrame)) {
      styleElem.da = d.dashArray;
      styleElem.do = d.dashoffset[0];
    }
    if (itemData.c._mdf || this._isFirstFrame) {
      styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")";
    }
    if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) {
      styleElem.coOp = itemData.o.v * groupTransform.opacity;
    }
    if (itemData.w._mdf || this._isFirstFrame) {
      styleElem.wi = itemData.w.v;
    }
  };
  CVShapeElement.prototype.destroy = function() {
    this.shapesData = null;
    this.globalData = null;
    this.canvasContext = null;
    this.stylesList.length = 0;
    this.itemsData.length = 0;
  };
  extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement, ITextElement], CVTextElement);
  CVTextElement.prototype.tHelper = createTag("canvas").getContext("2d");
  CVTextElement.prototype.buildNewText = function() {
    var documentData = this.textProperty.currentData;
    this.renderedLetters = createSizedArray(documentData.l ? documentData.l.length : 0);
    var hasFill = false;
    if (documentData.fc) {
      hasFill = true;
      this.values.fill = this.buildColor(documentData.fc);
    } else {
      this.values.fill = "rgba(0,0,0,0)";
    }
    this.fill = hasFill;
    var hasStroke = false;
    if (documentData.sc) {
      hasStroke = true;
      this.values.stroke = this.buildColor(documentData.sc);
      this.values.sWidth = documentData.sw;
    }
    var fontData = this.globalData.fontManager.getFontByName(documentData.f);
    var i;
    var len;
    var letters = documentData.l;
    var matrixHelper = this.mHelper;
    this.stroke = hasStroke;
    this.values.fValue = documentData.finalSize + "px " + this.globalData.fontManager.getFontByName(documentData.f).fFamily;
    len = documentData.finalText.length;
    var charData;
    var shapeData;
    var k2;
    var kLen;
    var shapes;
    var j2;
    var jLen;
    var pathNodes;
    var commands;
    var pathArr;
    var singleShape = this.data.singleShape;
    var trackingOffset = documentData.tr * 1e-3 * documentData.finalSize;
    var xPos = 0;
    var yPos = 0;
    var firstLine = true;
    var cnt = 0;
    for (i = 0; i < len; i += 1) {
      charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily);
      shapeData = charData && charData.data || {};
      matrixHelper.reset();
      if (singleShape && letters[i].n) {
        xPos = -trackingOffset;
        yPos += documentData.yOffset;
        yPos += firstLine ? 1 : 0;
        firstLine = false;
      }
      shapes = shapeData.shapes ? shapeData.shapes[0].it : [];
      jLen = shapes.length;
      matrixHelper.scale(documentData.finalSize / 100, documentData.finalSize / 100);
      if (singleShape) {
        this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos);
      }
      commands = createSizedArray(jLen - 1);
      var commandsCounter = 0;
      for (j2 = 0; j2 < jLen; j2 += 1) {
        if (shapes[j2].ty === "sh") {
          kLen = shapes[j2].ks.k.i.length;
          pathNodes = shapes[j2].ks.k;
          pathArr = [];
          for (k2 = 1; k2 < kLen; k2 += 1) {
            if (k2 === 1) {
              pathArr.push(matrixHelper.applyToX(pathNodes.v[0][0], pathNodes.v[0][1], 0), matrixHelper.applyToY(pathNodes.v[0][0], pathNodes.v[0][1], 0));
            }
            pathArr.push(matrixHelper.applyToX(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToX(pathNodes.i[k2][0], pathNodes.i[k2][1], 0), matrixHelper.applyToY(pathNodes.i[k2][0], pathNodes.i[k2][1], 0), matrixHelper.applyToX(pathNodes.v[k2][0], pathNodes.v[k2][1], 0), matrixHelper.applyToY(pathNodes.v[k2][0], pathNodes.v[k2][1], 0));
          }
          pathArr.push(matrixHelper.applyToX(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToX(pathNodes.i[0][0], pathNodes.i[0][1], 0), matrixHelper.applyToY(pathNodes.i[0][0], pathNodes.i[0][1], 0), matrixHelper.applyToX(pathNodes.v[0][0], pathNodes.v[0][1], 0), matrixHelper.applyToY(pathNodes.v[0][0], pathNodes.v[0][1], 0));
          commands[commandsCounter] = pathArr;
          commandsCounter += 1;
        }
      }
      if (singleShape) {
        xPos += letters[i].l;
        xPos += trackingOffset;
      }
      if (this.textSpans[cnt]) {
        this.textSpans[cnt].elem = commands;
      } else {
        this.textSpans[cnt] = { elem: commands };
      }
      cnt += 1;
    }
  };
  CVTextElement.prototype.renderInnerContent = function() {
    var ctx = this.canvasContext;
    ctx.font = this.values.fValue;
    ctx.lineCap = "butt";
    ctx.lineJoin = "miter";
    ctx.miterLimit = 4;
    if (!this.data.singleShape) {
      this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag);
    }
    var i;
    var len;
    var j2;
    var jLen;
    var k2;
    var kLen;
    var renderedLetters = this.textAnimator.renderedLetters;
    var letters = this.textProperty.currentData.l;
    len = letters.length;
    var renderedLetter;
    var lastFill = null;
    var lastStroke = null;
    var lastStrokeW = null;
    var commands;
    var pathArr;
    for (i = 0; i < len; i += 1) {
      if (!letters[i].n) {
        renderedLetter = renderedLetters[i];
        if (renderedLetter) {
          this.globalData.renderer.save();
          this.globalData.renderer.ctxTransform(renderedLetter.p);
          this.globalData.renderer.ctxOpacity(renderedLetter.o);
        }
        if (this.fill) {
          if (renderedLetter && renderedLetter.fc) {
            if (lastFill !== renderedLetter.fc) {
              lastFill = renderedLetter.fc;
              ctx.fillStyle = renderedLetter.fc;
            }
          } else if (lastFill !== this.values.fill) {
            lastFill = this.values.fill;
            ctx.fillStyle = this.values.fill;
          }
          commands = this.textSpans[i].elem;
          jLen = commands.length;
          this.globalData.canvasContext.beginPath();
          for (j2 = 0; j2 < jLen; j2 += 1) {
            pathArr = commands[j2];
            kLen = pathArr.length;
            this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]);
            for (k2 = 2; k2 < kLen; k2 += 6) {
              this.globalData.canvasContext.bezierCurveTo(pathArr[k2], pathArr[k2 + 1], pathArr[k2 + 2], pathArr[k2 + 3], pathArr[k2 + 4], pathArr[k2 + 5]);
            }
          }
          this.globalData.canvasContext.closePath();
          this.globalData.canvasContext.fill();
        }
        if (this.stroke) {
          if (renderedLetter && renderedLetter.sw) {
            if (lastStrokeW !== renderedLetter.sw) {
              lastStrokeW = renderedLetter.sw;
              ctx.lineWidth = renderedLetter.sw;
            }
          } else if (lastStrokeW !== this.values.sWidth) {
            lastStrokeW = this.values.sWidth;
            ctx.lineWidth = this.values.sWidth;
          }
          if (renderedLetter && renderedLetter.sc) {
            if (lastStroke !== renderedLetter.sc) {
              lastStroke = renderedLetter.sc;
              ctx.strokeStyle = renderedLetter.sc;
            }
          } else if (lastStroke !== this.values.stroke) {
            lastStroke = this.values.stroke;
            ctx.strokeStyle = this.values.stroke;
          }
          commands = this.textSpans[i].elem;
          jLen = commands.length;
          this.globalData.canvasContext.beginPath();
          for (j2 = 0; j2 < jLen; j2 += 1) {
            pathArr = commands[j2];
            kLen = pathArr.length;
            this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]);
            for (k2 = 2; k2 < kLen; k2 += 6) {
              this.globalData.canvasContext.bezierCurveTo(pathArr[k2], pathArr[k2 + 1], pathArr[k2 + 2], pathArr[k2 + 3], pathArr[k2 + 4], pathArr[k2 + 5]);
            }
          }
          this.globalData.canvasContext.closePath();
          this.globalData.canvasContext.stroke();
        }
        if (renderedLetter) {
          this.globalData.renderer.restore();
        }
      }
    }
  };
  extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVImageElement);
  CVImageElement.prototype.initElement = SVGShapeElement.prototype.initElement;
  CVImageElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame;
  CVImageElement.prototype.createContent = function() {
    if (this.img.width && (this.assetData.w !== this.img.width || this.assetData.h !== this.img.height)) {
      var canvas = createTag("canvas");
      canvas.width = this.assetData.w;
      canvas.height = this.assetData.h;
      var ctx = canvas.getContext("2d");
      var imgW = this.img.width;
      var imgH = this.img.height;
      var imgRel = imgW / imgH;
      var canvasRel = this.assetData.w / this.assetData.h;
      var widthCrop;
      var heightCrop;
      var par = this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio;
      if (imgRel > canvasRel && par === "xMidYMid slice" || imgRel < canvasRel && par !== "xMidYMid slice") {
        heightCrop = imgH;
        widthCrop = heightCrop * canvasRel;
      } else {
        widthCrop = imgW;
        heightCrop = widthCrop / canvasRel;
      }
      ctx.drawImage(this.img, (imgW - widthCrop) / 2, (imgH - heightCrop) / 2, widthCrop, heightCrop, 0, 0, this.assetData.w, this.assetData.h);
      this.img = canvas;
    }
  };
  CVImageElement.prototype.renderInnerContent = function() {
    this.canvasContext.drawImage(this.img, 0, 0);
  };
  CVImageElement.prototype.destroy = function() {
    this.img = null;
  };
  extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVSolidElement);
  CVSolidElement.prototype.initElement = SVGShapeElement.prototype.initElement;
  CVSolidElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame;
  CVSolidElement.prototype.renderInnerContent = function() {
    var ctx = this.canvasContext;
    ctx.fillStyle = this.data.sc;
    ctx.fillRect(0, 0, this.data.sw, this.data.sh);
  };
  extendPrototype([BaseRenderer], CanvasRendererBase);
  CanvasRendererBase.prototype.createShape = function(data2) {
    return new CVShapeElement(data2, this.globalData, this);
  };
  CanvasRendererBase.prototype.createText = function(data2) {
    return new CVTextElement(data2, this.globalData, this);
  };
  CanvasRendererBase.prototype.createImage = function(data2) {
    return new CVImageElement(data2, this.globalData, this);
  };
  CanvasRendererBase.prototype.createSolid = function(data2) {
    return new CVSolidElement(data2, this.globalData, this);
  };
  CanvasRendererBase.prototype.createNull = SVGRenderer.prototype.createNull;
  CanvasRendererBase.prototype.ctxTransform = function(props) {
    if (props[0] === 1 && props[1] === 0 && props[4] === 0 && props[5] === 1 && props[12] === 0 && props[13] === 0) {
      return;
    }
    if (!this.renderConfig.clearCanvas) {
      this.canvasContext.transform(props[0], props[1], props[4], props[5], props[12], props[13]);
      return;
    }
    this.transformMat.cloneFromProps(props);
    var cProps = this.contextData.cTr.props;
    this.transformMat.transform(cProps[0], cProps[1], cProps[2], cProps[3], cProps[4], cProps[5], cProps[6], cProps[7], cProps[8], cProps[9], cProps[10], cProps[11], cProps[12], cProps[13], cProps[14], cProps[15]);
    this.contextData.cTr.cloneFromProps(this.transformMat.props);
    var trProps = this.contextData.cTr.props;
    this.canvasContext.setTransform(trProps[0], trProps[1], trProps[4], trProps[5], trProps[12], trProps[13]);
  };
  CanvasRendererBase.prototype.ctxOpacity = function(op) {
    if (!this.renderConfig.clearCanvas) {
      this.canvasContext.globalAlpha *= op < 0 ? 0 : op;
      this.globalData.currentGlobalAlpha = this.contextData.cO;
      return;
    }
    this.contextData.cO *= op < 0 ? 0 : op;
    if (this.globalData.currentGlobalAlpha !== this.contextData.cO) {
      this.canvasContext.globalAlpha = this.contextData.cO;
      this.globalData.currentGlobalAlpha = this.contextData.cO;
    }
  };
  CanvasRendererBase.prototype.reset = function() {
    if (!this.renderConfig.clearCanvas) {
      this.canvasContext.restore();
      return;
    }
    this.contextData.reset();
  };
  CanvasRendererBase.prototype.save = function(actionFlag) {
    if (!this.renderConfig.clearCanvas) {
      this.canvasContext.save();
      return;
    }
    if (actionFlag) {
      this.canvasContext.save();
    }
    var props = this.contextData.cTr.props;
    if (this.contextData._length <= this.contextData.cArrPos) {
      this.contextData.duplicate();
    }
    var i;
    var arr = this.contextData.saved[this.contextData.cArrPos];
    for (i = 0; i < 16; i += 1) {
      arr[i] = props[i];
    }
    this.contextData.savedOp[this.contextData.cArrPos] = this.contextData.cO;
    this.contextData.cArrPos += 1;
  };
  CanvasRendererBase.prototype.restore = function(actionFlag) {
    if (!this.renderConfig.clearCanvas) {
      this.canvasContext.restore();
      return;
    }
    if (actionFlag) {
      this.canvasContext.restore();
      this.globalData.blendMode = "source-over";
    }
    this.contextData.cArrPos -= 1;
    var popped = this.contextData.saved[this.contextData.cArrPos];
    var i;
    var arr = this.contextData.cTr.props;
    for (i = 0; i < 16; i += 1) {
      arr[i] = popped[i];
    }
    this.canvasContext.setTransform(popped[0], popped[1], popped[4], popped[5], popped[12], popped[13]);
    popped = this.contextData.savedOp[this.contextData.cArrPos];
    this.contextData.cO = popped;
    if (this.globalData.currentGlobalAlpha !== popped) {
      this.canvasContext.globalAlpha = popped;
      this.globalData.currentGlobalAlpha = popped;
    }
  };
  CanvasRendererBase.prototype.configAnimation = function(animData) {
    if (this.animationItem.wrapper) {
      this.animationItem.container = createTag("canvas");
      var containerStyle = this.animationItem.container.style;
      containerStyle.width = "100%";
      containerStyle.height = "100%";
      var origin = "0px 0px 0px";
      containerStyle.transformOrigin = origin;
      containerStyle.mozTransformOrigin = origin;
      containerStyle.webkitTransformOrigin = origin;
      containerStyle["-webkit-transform"] = origin;
      containerStyle.contentVisibility = this.renderConfig.contentVisibility;
      this.animationItem.wrapper.appendChild(this.animationItem.container);
      this.canvasContext = this.animationItem.container.getContext("2d");
      if (this.renderConfig.className) {
        this.animationItem.container.setAttribute("class", this.renderConfig.className);
      }
      if (this.renderConfig.id) {
        this.animationItem.container.setAttribute("id", this.renderConfig.id);
      }
    } else {
      this.canvasContext = this.renderConfig.context;
    }
    this.data = animData;
    this.layers = animData.layers;
    this.transformCanvas = {
      w: animData.w,
      h: animData.h,
      sx: 0,
      sy: 0,
      tx: 0,
      ty: 0
    };
    this.setupGlobalData(animData, document.body);
    this.globalData.canvasContext = this.canvasContext;
    this.globalData.renderer = this;
    this.globalData.isDashed = false;
    this.globalData.progressiveLoad = this.renderConfig.progressiveLoad;
    this.globalData.transformCanvas = this.transformCanvas;
    this.elements = createSizedArray(animData.layers.length);
    this.updateContainerSize();
  };
  CanvasRendererBase.prototype.updateContainerSize = function() {
    this.reset();
    var elementWidth;
    var elementHeight;
    if (this.animationItem.wrapper && this.animationItem.container) {
      elementWidth = this.animationItem.wrapper.offsetWidth;
      elementHeight = this.animationItem.wrapper.offsetHeight;
      this.animationItem.container.setAttribute("width", elementWidth * this.renderConfig.dpr);
      this.animationItem.container.setAttribute("height", elementHeight * this.renderConfig.dpr);
    } else {
      elementWidth = this.canvasContext.canvas.width * this.renderConfig.dpr;
      elementHeight = this.canvasContext.canvas.height * this.renderConfig.dpr;
    }
    var elementRel;
    var animationRel;
    if (this.renderConfig.preserveAspectRatio.indexOf("meet") !== -1 || this.renderConfig.preserveAspectRatio.indexOf("slice") !== -1) {
      var par = this.renderConfig.preserveAspectRatio.split(" ");
      var fillType = par[1] || "meet";
      var pos = par[0] || "xMidYMid";
      var xPos = pos.substr(0, 4);
      var yPos = pos.substr(4);
      elementRel = elementWidth / elementHeight;
      animationRel = this.transformCanvas.w / this.transformCanvas.h;
      if (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice") {
        this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr);
        this.transformCanvas.sy = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr);
      } else {
        this.transformCanvas.sx = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr);
        this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr);
      }
      if (xPos === "xMid" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) {
        this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) / 2 * this.renderConfig.dpr;
      } else if (xPos === "xMax" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) {
        this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) * this.renderConfig.dpr;
      } else {
        this.transformCanvas.tx = 0;
      }
      if (yPos === "YMid" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) {
        this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) / 2 * this.renderConfig.dpr;
      } else if (yPos === "YMax" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) {
        this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) * this.renderConfig.dpr;
      } else {
        this.transformCanvas.ty = 0;
      }
    } else if (this.renderConfig.preserveAspectRatio === "none") {
      this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr);
      this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr);
      this.transformCanvas.tx = 0;
      this.transformCanvas.ty = 0;
    } else {
      this.transformCanvas.sx = this.renderConfig.dpr;
      this.transformCanvas.sy = this.renderConfig.dpr;
      this.transformCanvas.tx = 0;
      this.transformCanvas.ty = 0;
    }
    this.transformCanvas.props = [this.transformCanvas.sx, 0, 0, 0, 0, this.transformCanvas.sy, 0, 0, 0, 0, 1, 0, this.transformCanvas.tx, this.transformCanvas.ty, 0, 1];
    this.ctxTransform(this.transformCanvas.props);
    this.canvasContext.beginPath();
    this.canvasContext.rect(0, 0, this.transformCanvas.w, this.transformCanvas.h);
    this.canvasContext.closePath();
    this.canvasContext.clip();
    this.renderFrame(this.renderedFrame, true);
  };
  CanvasRendererBase.prototype.destroy = function() {
    if (this.renderConfig.clearCanvas && this.animationItem.wrapper) {
      this.animationItem.wrapper.innerText = "";
    }
    var i;
    var len = this.layers ? this.layers.length : 0;
    for (i = len - 1; i >= 0; i -= 1) {
      if (this.elements[i]) {
        this.elements[i].destroy();
      }
    }
    this.elements.length = 0;
    this.globalData.canvasContext = null;
    this.animationItem.container = null;
    this.destroyed = true;
  };
  CanvasRendererBase.prototype.renderFrame = function(num, forceRender) {
    if (this.renderedFrame === num && this.renderConfig.clearCanvas === true && !forceRender || this.destroyed || num === -1) {
      return;
    }
    this.renderedFrame = num;
    this.globalData.frameNum = num - this.animationItem._isFirstFrame;
    this.globalData.frameId += 1;
    this.globalData._mdf = !this.renderConfig.clearCanvas || forceRender;
    this.globalData.projectInterface.currentFrame = num;
    var i;
    var len = this.layers.length;
    if (!this.completeLayers) {
      this.checkLayers(num);
    }
    for (i = 0; i < len; i += 1) {
      if (this.completeLayers || this.elements[i]) {
        this.elements[i].prepareFrame(num - this.layers[i].st);
      }
    }
    if (this.globalData._mdf) {
      if (this.renderConfig.clearCanvas === true) {
        this.canvasContext.clearRect(0, 0, this.transformCanvas.w, this.transformCanvas.h);
      } else {
        this.save();
      }
      for (i = len - 1; i >= 0; i -= 1) {
        if (this.completeLayers || this.elements[i]) {
          this.elements[i].renderFrame();
        }
      }
      if (this.renderConfig.clearCanvas !== true) {
        this.restore();
      }
    }
  };
  CanvasRendererBase.prototype.buildItem = function(pos) {
    var elements = this.elements;
    if (elements[pos] || this.layers[pos].ty === 99) {
      return;
    }
    var element = this.createItem(this.layers[pos], this, this.globalData);
    elements[pos] = element;
    element.initExpressions();
  };
  CanvasRendererBase.prototype.checkPendingElements = function() {
    while (this.pendingElements.length) {
      var element = this.pendingElements.pop();
      element.checkParenting();
    }
  };
  CanvasRendererBase.prototype.hide = function() {
    this.animationItem.container.style.display = "none";
  };
  CanvasRendererBase.prototype.show = function() {
    this.animationItem.container.style.display = "block";
  };
  extendPrototype([CanvasRendererBase, ICompElement, CVBaseElement], CVCompElement);
  CVCompElement.prototype.renderInnerContent = function() {
    var ctx = this.canvasContext;
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(this.data.w, 0);
    ctx.lineTo(this.data.w, this.data.h);
    ctx.lineTo(0, this.data.h);
    ctx.lineTo(0, 0);
    ctx.clip();
    var i;
    var len = this.layers.length;
    for (i = len - 1; i >= 0; i -= 1) {
      if (this.completeLayers || this.elements[i]) {
        this.elements[i].renderFrame();
      }
    }
  };
  CVCompElement.prototype.destroy = function() {
    var i;
    var len = this.layers.length;
    for (i = len - 1; i >= 0; i -= 1) {
      if (this.elements[i]) {
        this.elements[i].destroy();
      }
    }
    this.layers = null;
    this.elements = null;
  };
  CVCompElement.prototype.createComp = function(data2) {
    return new CVCompElement(data2, this.globalData, this);
  };
  extendPrototype([CanvasRendererBase], CanvasRenderer);
  CanvasRenderer.prototype.createComp = function(data2) {
    return new CVCompElement(data2, this.globalData, this);
  };
  registerRenderer("canvas", CanvasRenderer);
  ShapeModifiers.registerModifier("tm", TrimModifier);
  ShapeModifiers.registerModifier("pb", PuckerAndBloatModifier);
  ShapeModifiers.registerModifier("rp", RepeaterModifier);
  ShapeModifiers.registerModifier("rd", RoundCornersModifier);
  const Expressions = function() {
    var ob2 = {};
    ob2.initExpressions = initExpressions;
    function initExpressions(animation) {
      var stackCount = 0;
      var registers = [];
      function pushExpression() {
        stackCount += 1;
      }
      function popExpression() {
        stackCount -= 1;
        if (stackCount === 0) {
          releaseInstances();
        }
      }
      function registerExpressionProperty(expression) {
        if (registers.indexOf(expression) === -1) {
          registers.push(expression);
        }
      }
      function releaseInstances() {
        var i;
        var len = registers.length;
        for (i = 0; i < len; i += 1) {
          registers[i].release();
        }
        registers.length = 0;
      }
      animation.renderer.compInterface = CompExpressionInterface(animation.renderer);
      animation.renderer.globalData.projectInterface.registerComposition(animation.renderer);
      animation.renderer.globalData.pushExpression = pushExpression;
      animation.renderer.globalData.popExpression = popExpression;
      animation.renderer.globalData.registerExpressionProperty = registerExpressionProperty;
    }
    return ob2;
  }();
  ;
  propTypes = {
    SHAPE: "shape"
  };
  const ExpressionManager = function() {
    "use strict";
    var ob = {};
    var Math = BMMath;
    var window = null;
    var document = null;
    var XMLHttpRequest = null;
    var fetch = null;
    var frames = null;
    initialize$2(BMMath);
    function $bm_isInstanceOfArray(arr) {
      return arr.constructor === Array || arr.constructor === Float32Array;
    }
    function isNumerable(tOfV, v) {
      return tOfV === "number" || tOfV === "boolean" || tOfV === "string" || v instanceof Number;
    }
    function $bm_neg(a2) {
      var tOfA = typeof a2;
      if (tOfA === "number" || tOfA === "boolean" || a2 instanceof Number) {
        return -a2;
      }
      if ($bm_isInstanceOfArray(a2)) {
        var i;
        var lenA = a2.length;
        var retArr = [];
        for (i = 0; i < lenA; i += 1) {
          retArr[i] = -a2[i];
        }
        return retArr;
      }
      if (a2.propType) {
        return a2.v;
      }
      return -a2;
    }
    var easeInBez = BezierFactory.getBezierEasing(0.333, 0, 0.833, 0.833, "easeIn").get;
    var easeOutBez = BezierFactory.getBezierEasing(0.167, 0.167, 0.667, 1, "easeOut").get;
    var easeInOutBez = BezierFactory.getBezierEasing(0.33, 0, 0.667, 1, "easeInOut").get;
    function sum(a2, b3) {
      var tOfA = typeof a2;
      var tOfB = typeof b3;
      if (tOfA === "string" || tOfB === "string") {
        return a2 + b3;
      }
      if (isNumerable(tOfA, a2) && isNumerable(tOfB, b3)) {
        return a2 + b3;
      }
      if ($bm_isInstanceOfArray(a2) && isNumerable(tOfB, b3)) {
        a2 = a2.slice(0);
        a2[0] += b3;
        return a2;
      }
      if (isNumerable(tOfA, a2) && $bm_isInstanceOfArray(b3)) {
        b3 = b3.slice(0);
        b3[0] = a2 + b3[0];
        return b3;
      }
      if ($bm_isInstanceOfArray(a2) && $bm_isInstanceOfArray(b3)) {
        var i = 0;
        var lenA = a2.length;
        var lenB = b3.length;
        var retArr = [];
        while (i < lenA || i < lenB) {
          if ((typeof a2[i] === "number" || a2[i] instanceof Number) && (typeof b3[i] === "number" || b3[i] instanceof Number)) {
            retArr[i] = a2[i] + b3[i];
          } else {
            retArr[i] = b3[i] === void 0 ? a2[i] : a2[i] || b3[i];
          }
          i += 1;
        }
        return retArr;
      }
      return 0;
    }
    var add = sum;
    function sub(a2, b3) {
      var tOfA = typeof a2;
      var tOfB = typeof b3;
      if (isNumerable(tOfA, a2) && isNumerable(tOfB, b3)) {
        if (tOfA === "string") {
          a2 = parseInt(a2, 10);
        }
        if (tOfB === "string") {
          b3 = parseInt(b3, 10);
        }
        return a2 - b3;
      }
      if ($bm_isInstanceOfArray(a2) && isNumerable(tOfB, b3)) {
        a2 = a2.slice(0);
        a2[0] -= b3;
        return a2;
      }
      if (isNumerable(tOfA, a2) && $bm_isInstanceOfArray(b3)) {
        b3 = b3.slice(0);
        b3[0] = a2 - b3[0];
        return b3;
      }
      if ($bm_isInstanceOfArray(a2) && $bm_isInstanceOfArray(b3)) {
        var i = 0;
        var lenA = a2.length;
        var lenB = b3.length;
        var retArr = [];
        while (i < lenA || i < lenB) {
          if ((typeof a2[i] === "number" || a2[i] instanceof Number) && (typeof b3[i] === "number" || b3[i] instanceof Number)) {
            retArr[i] = a2[i] - b3[i];
          } else {
            retArr[i] = b3[i] === void 0 ? a2[i] : a2[i] || b3[i];
          }
          i += 1;
        }
        return retArr;
      }
      return 0;
    }
    function mul(a2, b3) {
      var tOfA = typeof a2;
      var tOfB = typeof b3;
      var arr;
      if (isNumerable(tOfA, a2) && isNumerable(tOfB, b3)) {
        return a2 * b3;
      }
      var i;
      var len;
      if ($bm_isInstanceOfArray(a2) && isNumerable(tOfB, b3)) {
        len = a2.length;
        arr = createTypedArray("float32", len);
        for (i = 0; i < len; i += 1) {
          arr[i] = a2[i] * b3;
        }
        return arr;
      }
      if (isNumerable(tOfA, a2) && $bm_isInstanceOfArray(b3)) {
        len = b3.length;
        arr = createTypedArray("float32", len);
        for (i = 0; i < len; i += 1) {
          arr[i] = a2 * b3[i];
        }
        return arr;
      }
      return 0;
    }
    function div(a2, b3) {
      var tOfA = typeof a2;
      var tOfB = typeof b3;
      var arr;
      if (isNumerable(tOfA, a2) && isNumerable(tOfB, b3)) {
        return a2 / b3;
      }
      var i;
      var len;
      if ($bm_isInstanceOfArray(a2) && isNumerable(tOfB, b3)) {
        len = a2.length;
        arr = createTypedArray("float32", len);
        for (i = 0; i < len; i += 1) {
          arr[i] = a2[i] / b3;
        }
        return arr;
      }
      if (isNumerable(tOfA, a2) && $bm_isInstanceOfArray(b3)) {
        len = b3.length;
        arr = createTypedArray("float32", len);
        for (i = 0; i < len; i += 1) {
          arr[i] = a2 / b3[i];
        }
        return arr;
      }
      return 0;
    }
    function mod(a2, b3) {
      if (typeof a2 === "string") {
        a2 = parseInt(a2, 10);
      }
      if (typeof b3 === "string") {
        b3 = parseInt(b3, 10);
      }
      return a2 % b3;
    }
    var $bm_sum = sum;
    var $bm_sub = sub;
    var $bm_mul = mul;
    var $bm_div = div;
    var $bm_mod = mod;
    function clamp(num, min, max2) {
      if (min > max2) {
        var mm = max2;
        max2 = min;
        min = mm;
      }
      return Math.min(Math.max(num, min), max2);
    }
    function radiansToDegrees(val2) {
      return val2 / degToRads;
    }
    var radians_to_degrees = radiansToDegrees;
    function degreesToRadians(val2) {
      return val2 * degToRads;
    }
    var degrees_to_radians = radiansToDegrees;
    var helperLengthArray = [0, 0, 0, 0, 0, 0];
    function length(arr1, arr2) {
      if (typeof arr1 === "number" || arr1 instanceof Number) {
        arr2 = arr2 || 0;
        return Math.abs(arr1 - arr2);
      }
      if (!arr2) {
        arr2 = helperLengthArray;
      }
      var i;
      var len = Math.min(arr1.length, arr2.length);
      var addedLength = 0;
      for (i = 0; i < len; i += 1) {
        addedLength += Math.pow(arr2[i] - arr1[i], 2);
      }
      return Math.sqrt(addedLength);
    }
    function normalize(vec) {
      return div(vec, length(vec));
    }
    function rgbToHsl(val2) {
      var r = val2[0];
      var g3 = val2[1];
      var b3 = val2[2];
      var max2 = Math.max(r, g3, b3);
      var min = Math.min(r, g3, b3);
      var h;
      var s;
      var l2 = (max2 + min) / 2;
      if (max2 === min) {
        h = 0;
        s = 0;
      } else {
        var d = max2 - min;
        s = l2 > 0.5 ? d / (2 - max2 - min) : d / (max2 + min);
        switch (max2) {
          case r:
            h = (g3 - b3) / d + (g3 < b3 ? 6 : 0);
            break;
          case g3:
            h = (b3 - r) / d + 2;
            break;
          case b3:
            h = (r - g3) / d + 4;
            break;
          default:
            break;
        }
        h /= 6;
      }
      return [h, s, l2, val2[3]];
    }
    function hue2rgb(p, q2, t3) {
      if (t3 < 0) t3 += 1;
      if (t3 > 1) t3 -= 1;
      if (t3 < 1 / 6) return p + (q2 - p) * 6 * t3;
      if (t3 < 1 / 2) return q2;
      if (t3 < 2 / 3) return p + (q2 - p) * (2 / 3 - t3) * 6;
      return p;
    }
    function hslToRgb(val2) {
      var h = val2[0];
      var s = val2[1];
      var l2 = val2[2];
      var r;
      var g3;
      var b3;
      if (s === 0) {
        r = l2;
        b3 = l2;
        g3 = l2;
      } else {
        var q2 = l2 < 0.5 ? l2 * (1 + s) : l2 + s - l2 * s;
        var p = 2 * l2 - q2;
        r = hue2rgb(p, q2, h + 1 / 3);
        g3 = hue2rgb(p, q2, h);
        b3 = hue2rgb(p, q2, h - 1 / 3);
      }
      return [r, g3, b3, val2[3]];
    }
    function linear(t3, tMin, tMax, value1, value2) {
      if (value1 === void 0 || value2 === void 0) {
        value1 = tMin;
        value2 = tMax;
        tMin = 0;
        tMax = 1;
      }
      if (tMax < tMin) {
        var _tMin = tMax;
        tMax = tMin;
        tMin = _tMin;
      }
      if (t3 <= tMin) {
        return value1;
      }
      if (t3 >= tMax) {
        return value2;
      }
      var perc = tMax === tMin ? 0 : (t3 - tMin) / (tMax - tMin);
      if (!value1.length) {
        return value1 + (value2 - value1) * perc;
      }
      var i;
      var len = value1.length;
      var arr = createTypedArray("float32", len);
      for (i = 0; i < len; i += 1) {
        arr[i] = value1[i] + (value2[i] - value1[i]) * perc;
      }
      return arr;
    }
    function random(min, max2) {
      if (max2 === void 0) {
        if (min === void 0) {
          min = 0;
          max2 = 1;
        } else {
          max2 = min;
          min = void 0;
        }
      }
      if (max2.length) {
        var i;
        var len = max2.length;
        if (!min) {
          min = createTypedArray("float32", len);
        }
        var arr = createTypedArray("float32", len);
        var rnd = BMMath.random();
        for (i = 0; i < len; i += 1) {
          arr[i] = min[i] + rnd * (max2[i] - min[i]);
        }
        return arr;
      }
      if (min === void 0) {
        min = 0;
      }
      var rndm = BMMath.random();
      return min + rndm * (max2 - min);
    }
    function createPath(points, inTangents, outTangents, closed) {
      var i;
      var len = points.length;
      var path = shapePool.newElement();
      path.setPathData(!!closed, len);
      var arrPlaceholder = [0, 0];
      var inVertexPoint;
      var outVertexPoint;
      for (i = 0; i < len; i += 1) {
        inVertexPoint = inTangents && inTangents[i] ? inTangents[i] : arrPlaceholder;
        outVertexPoint = outTangents && outTangents[i] ? outTangents[i] : arrPlaceholder;
        path.setTripleAt(points[i][0], points[i][1], outVertexPoint[0] + points[i][0], outVertexPoint[1] + points[i][1], inVertexPoint[0] + points[i][0], inVertexPoint[1] + points[i][1], i, true);
      }
      return path;
    }
    function initiateExpression(elem, data, property) {
      var val = data.x;
      var needsVelocity = /velocity(?![\w\d])/.test(val);
      var _needsRandom = val.indexOf("random") !== -1;
      var elemType = elem.data.ty;
      var transform;
      var $bm_transform;
      var content;
      var effect;
      var thisProperty = property;
      thisProperty.valueAtTime = thisProperty.getValueAtTime;
      Object.defineProperty(thisProperty, "value", {
        get: function() {
          return thisProperty.v;
        }
      });
      elem.comp.frameDuration = 1 / elem.comp.globalData.frameRate;
      elem.comp.displayStartTime = 0;
      var inPoint = elem.data.ip / elem.comp.globalData.frameRate;
      var outPoint = elem.data.op / elem.comp.globalData.frameRate;
      var width = elem.data.sw ? elem.data.sw : 0;
      var height = elem.data.sh ? elem.data.sh : 0;
      var name = elem.data.nm;
      var loopIn;
      var loop_in;
      var loopOut;
      var loop_out;
      var smooth;
      var toWorld;
      var fromWorld;
      var fromComp;
      var toComp;
      var fromCompToSurface;
      var position;
      var rotation;
      var anchorPoint;
      var scale;
      var thisLayer;
      var thisComp;
      var mask;
      var valueAtTime;
      var velocityAtTime;
      var scoped_bm_rt;
      var expression_function = eval("[function _expression_function(){" + val + ";scoped_bm_rt=$bm_rt}]")[0];
      var numKeys = property.kf ? data.k.length : 0;
      var active = !this.data || this.data.hd !== true;
      var wiggle = (function wiggle2(freq, amp) {
        var iWiggle;
        var j2;
        var lenWiggle = this.pv.length ? this.pv.length : 1;
        var addedAmps = createTypedArray("float32", lenWiggle);
        freq = 5;
        var iterations = Math.floor(time * freq);
        iWiggle = 0;
        j2 = 0;
        while (iWiggle < iterations) {
          for (j2 = 0; j2 < lenWiggle; j2 += 1) {
            addedAmps[j2] += -amp + amp * 2 * BMMath.random();
          }
          iWiggle += 1;
        }
        var periods = time * freq;
        var perc = periods - Math.floor(periods);
        var arr = createTypedArray("float32", lenWiggle);
        if (lenWiggle > 1) {
          for (j2 = 0; j2 < lenWiggle; j2 += 1) {
            arr[j2] = this.pv[j2] + addedAmps[j2] + (-amp + amp * 2 * BMMath.random()) * perc;
          }
          return arr;
        }
        return this.pv + addedAmps[0] + (-amp + amp * 2 * BMMath.random()) * perc;
      }).bind(this);
      if (thisProperty.loopIn) {
        loopIn = thisProperty.loopIn.bind(thisProperty);
        loop_in = loopIn;
      }
      if (thisProperty.loopOut) {
        loopOut = thisProperty.loopOut.bind(thisProperty);
        loop_out = loopOut;
      }
      if (thisProperty.smooth) {
        smooth = thisProperty.smooth.bind(thisProperty);
      }
      function loopInDuration(type, duration) {
        return loopIn(type, duration, true);
      }
      function loopOutDuration(type, duration) {
        return loopOut(type, duration, true);
      }
      if (this.getValueAtTime) {
        valueAtTime = this.getValueAtTime.bind(this);
      }
      if (this.getVelocityAtTime) {
        velocityAtTime = this.getVelocityAtTime.bind(this);
      }
      var comp = elem.comp.globalData.projectInterface.bind(elem.comp.globalData.projectInterface);
      function lookAt(elem1, elem2) {
        var fVec = [elem2[0] - elem1[0], elem2[1] - elem1[1], elem2[2] - elem1[2]];
        var pitch = Math.atan2(fVec[0], Math.sqrt(fVec[1] * fVec[1] + fVec[2] * fVec[2])) / degToRads;
        var yaw = -Math.atan2(fVec[1], fVec[2]) / degToRads;
        return [yaw, pitch, 0];
      }
      function easeOut(t3, tMin, tMax, val1, val2) {
        return applyEase(easeOutBez, t3, tMin, tMax, val1, val2);
      }
      function easeIn(t3, tMin, tMax, val1, val2) {
        return applyEase(easeInBez, t3, tMin, tMax, val1, val2);
      }
      function ease(t3, tMin, tMax, val1, val2) {
        return applyEase(easeInOutBez, t3, tMin, tMax, val1, val2);
      }
      function applyEase(fn, t3, tMin, tMax, val1, val2) {
        if (val1 === void 0) {
          val1 = tMin;
          val2 = tMax;
        } else {
          t3 = (t3 - tMin) / (tMax - tMin);
        }
        if (t3 > 1) {
          t3 = 1;
        } else if (t3 < 0) {
          t3 = 0;
        }
        var mult = fn(t3);
        if ($bm_isInstanceOfArray(val1)) {
          var iKey;
          var lenKey = val1.length;
          var arr = createTypedArray("float32", lenKey);
          for (iKey = 0; iKey < lenKey; iKey += 1) {
            arr[iKey] = (val2[iKey] - val1[iKey]) * mult + val1[iKey];
          }
          return arr;
        }
        return (val2 - val1) * mult + val1;
      }
      function nearestKey(time2) {
        var iKey;
        var lenKey = data.k.length;
        var index2;
        var keyTime;
        if (!data.k.length || typeof data.k[0] === "number") {
          index2 = 0;
          keyTime = 0;
        } else {
          index2 = -1;
          time2 *= elem.comp.globalData.frameRate;
          if (time2 < data.k[0].t) {
            index2 = 1;
            keyTime = data.k[0].t;
          } else {
            for (iKey = 0; iKey < lenKey - 1; iKey += 1) {
              if (time2 === data.k[iKey].t) {
                index2 = iKey + 1;
                keyTime = data.k[iKey].t;
                break;
              } else if (time2 > data.k[iKey].t && time2 < data.k[iKey + 1].t) {
                if (time2 - data.k[iKey].t > data.k[iKey + 1].t - time2) {
                  index2 = iKey + 2;
                  keyTime = data.k[iKey + 1].t;
                } else {
                  index2 = iKey + 1;
                  keyTime = data.k[iKey].t;
                }
                break;
              }
            }
            if (index2 === -1) {
              index2 = iKey + 1;
              keyTime = data.k[iKey].t;
            }
          }
        }
        var obKey = {};
        obKey.index = index2;
        obKey.time = keyTime / elem.comp.globalData.frameRate;
        return obKey;
      }
      function key(ind) {
        var obKey;
        var iKey;
        var lenKey;
        if (!data.k.length || typeof data.k[0] === "number") {
          throw new Error("The property has no keyframe at index " + ind);
        }
        ind -= 1;
        obKey = {
          time: data.k[ind].t / elem.comp.globalData.frameRate,
          value: []
        };
        var arr = Object.prototype.hasOwnProperty.call(data.k[ind], "s") ? data.k[ind].s : data.k[ind - 1].e;
        lenKey = arr.length;
        for (iKey = 0; iKey < lenKey; iKey += 1) {
          obKey[iKey] = arr[iKey];
          obKey.value[iKey] = arr[iKey];
        }
        return obKey;
      }
      function framesToTime(fr, fps) {
        if (!fps) {
          fps = elem.comp.globalData.frameRate;
        }
        return fr / fps;
      }
      function timeToFrames(t3, fps) {
        if (!t3 && t3 !== 0) {
          t3 = time;
        }
        if (!fps) {
          fps = elem.comp.globalData.frameRate;
        }
        return t3 * fps;
      }
      function seedRandom(seed) {
        BMMath.seedrandom(randSeed + seed);
      }
      function sourceRectAtTime() {
        return elem.sourceRectAtTime();
      }
      function substring(init, end) {
        if (typeof value === "string") {
          if (end === void 0) {
            return value.substring(init);
          }
          return value.substring(init, end);
        }
        return "";
      }
      function substr(init, end) {
        if (typeof value === "string") {
          if (end === void 0) {
            return value.substr(init);
          }
          return value.substr(init, end);
        }
        return "";
      }
      function posterizeTime(framesPerSecond) {
        time = framesPerSecond === 0 ? 0 : Math.floor(time * framesPerSecond) / framesPerSecond;
        value = valueAtTime(time);
      }
      var time;
      var velocity;
      var value;
      var text;
      var textIndex;
      var textTotal;
      var selectorValue;
      var index = elem.data.ind;
      var hasParent = !!(elem.hierarchy && elem.hierarchy.length);
      var parent;
      var randSeed = Math.floor(Math.random() * 1e6);
      var globalData = elem.globalData;
      function executeExpression(_value) {
        value = _value;
        if (this.frameExpressionId === elem.globalData.frameId && this.propType !== "textSelector") {
          return value;
        }
        if (this.propType === "textSelector") {
          textIndex = this.textIndex;
          textTotal = this.textTotal;
          selectorValue = this.selectorValue;
        }
        if (!thisLayer) {
          text = elem.layerInterface.text;
          thisLayer = elem.layerInterface;
          thisComp = elem.comp.compInterface;
          toWorld = thisLayer.toWorld.bind(thisLayer);
          fromWorld = thisLayer.fromWorld.bind(thisLayer);
          fromComp = thisLayer.fromComp.bind(thisLayer);
          toComp = thisLayer.toComp.bind(thisLayer);
          mask = thisLayer.mask ? thisLayer.mask.bind(thisLayer) : null;
          fromCompToSurface = fromComp;
        }
        if (!transform) {
          transform = elem.layerInterface("ADBE Transform Group");
          $bm_transform = transform;
          if (transform) {
            anchorPoint = transform.anchorPoint;
          }
        }
        if (elemType === 4 && !content) {
          content = thisLayer("ADBE Root Vectors Group");
        }
        if (!effect) {
          effect = thisLayer(4);
        }
        hasParent = !!(elem.hierarchy && elem.hierarchy.length);
        if (hasParent && !parent) {
          parent = elem.hierarchy[0].layerInterface;
        }
        time = this.comp.renderedFrame / this.comp.globalData.frameRate;
        if (_needsRandom) {
          seedRandom(randSeed + time);
        }
        if (needsVelocity) {
          velocity = velocityAtTime(time);
        }
        expression_function();
        this.frameExpressionId = elem.globalData.frameId;
        scoped_bm_rt = scoped_bm_rt.propType === propTypes.SHAPE ? scoped_bm_rt.v : scoped_bm_rt;
        return scoped_bm_rt;
      }
      executeExpression.__preventDeadCodeRemoval = [$bm_transform, anchorPoint, time, velocity, inPoint, outPoint, width, height, name, loop_in, loop_out, smooth, toComp, fromCompToSurface, toWorld, fromWorld, mask, position, rotation, scale, thisComp, numKeys, active, wiggle, loopInDuration, loopOutDuration, comp, lookAt, easeOut, easeIn, ease, nearestKey, key, text, textIndex, textTotal, selectorValue, framesToTime, timeToFrames, sourceRectAtTime, substring, substr, posterizeTime, index, globalData];
      return executeExpression;
    }
    ob.initiateExpression = initiateExpression;
    ob.__preventDeadCodeRemoval = [window, document, XMLHttpRequest, fetch, frames, $bm_neg, add, $bm_sum, $bm_sub, $bm_mul, $bm_div, $bm_mod, clamp, radians_to_degrees, degreesToRadians, degrees_to_radians, normalize, rgbToHsl, hslToRgb, linear, random, createPath];
    return ob;
  }();
  const expressionHelpers = /* @__PURE__ */ function() {
    function searchExpressions(elem2, data2, prop) {
      if (data2.x) {
        prop.k = true;
        prop.x = true;
        prop.initiateExpression = ExpressionManager.initiateExpression;
        prop.effectsSequence.push(prop.initiateExpression(elem2, data2, prop).bind(prop));
      }
    }
    function getValueAtTime(frameNum) {
      frameNum *= this.elem.globalData.frameRate;
      frameNum -= this.offsetTime;
      if (frameNum !== this._cachingAtTime.lastFrame) {
        this._cachingAtTime.lastIndex = this._cachingAtTime.lastFrame < frameNum ? this._cachingAtTime.lastIndex : 0;
        this._cachingAtTime.value = this.interpolateValue(frameNum, this._cachingAtTime);
        this._cachingAtTime.lastFrame = frameNum;
      }
      return this._cachingAtTime.value;
    }
    function getSpeedAtTime(frameNum) {
      var delta = -0.01;
      var v12 = this.getValueAtTime(frameNum);
      var v2 = this.getValueAtTime(frameNum + delta);
      var speed = 0;
      if (v12.length) {
        var i;
        for (i = 0; i < v12.length; i += 1) {
          speed += Math.pow(v2[i] - v12[i], 2);
        }
        speed = Math.sqrt(speed) * 100;
      } else {
        speed = 0;
      }
      return speed;
    }
    function getVelocityAtTime(frameNum) {
      if (this.vel !== void 0) {
        return this.vel;
      }
      var delta = -1e-3;
      var v12 = this.getValueAtTime(frameNum);
      var v2 = this.getValueAtTime(frameNum + delta);
      var velocity2;
      if (v12.length) {
        velocity2 = createTypedArray("float32", v12.length);
        var i;
        for (i = 0; i < v12.length; i += 1) {
          velocity2[i] = (v2[i] - v12[i]) / delta;
        }
      } else {
        velocity2 = (v2 - v12) / delta;
      }
      return velocity2;
    }
    function getStaticValueAtTime() {
      return this.pv;
    }
    function setGroupProperty(propertyGroup) {
      this.propertyGroup = propertyGroup;
    }
    return {
      searchExpressions,
      getSpeedAtTime,
      getVelocityAtTime,
      getValueAtTime,
      getStaticValueAtTime,
      setGroupProperty
    };
  }();
  setExpressionsPlugin(Expressions);
  initialize$1();
  initialize();
}
var standalone;
var animationData;
var renderer;
var queryString;
var scripts;
var index2;
var myScript;
var readyStateCheckInterval;
var registeredEffects;
var idPrefix;
var emptyShapeData;
var propTypes;

// node_modules/three/examples/jsm/loaders/LottieLoader.js
var LottieLoader = class extends Loader {
  /**
   * Constructs a new Lottie loader.
   *
   * @deprecated The loader has been deprecated and will be removed with r186. Use lottie-web instead and create your animated texture manually.
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    console.warn("THREE.LottieLoader: The loader has been deprecated and will be removed with r186. Use lottie-web instead and create your animated texture manually.");
  }
  /**
   * Sets the texture quality.
   *
   * @param {number} value - The texture quality.
   */
  setQuality(value2) {
    this._quality = value2;
  }
  /**
   * Starts loading from the given URL and passes the loaded Lottie asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(CanvasTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @returns {CanvasTexture} The Lottie texture.
   */
  load(url, onLoad, onProgress, onError) {
    const quality = this._quality || 1;
    const texture = new CanvasTexture();
    texture.minFilter = NearestFilter;
    texture.generateMipmaps = false;
    texture.colorSpace = SRGBColorSpace;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(text2) {
      const data2 = JSON.parse(text2);
      const container = document.createElement("div");
      container.style.width = data2.w + "px";
      container.style.height = data2.h + "px";
      document.body.appendChild(container);
      const animation = lottie.loadAnimation({
        container,
        animType: "canvas",
        loop: true,
        autoplay: true,
        animationData: data2,
        rendererSettings: { dpr: quality }
      });
      texture.animation = animation;
      texture.image = animation.container;
      animation.addEventListener("enterFrame", function() {
        texture.needsUpdate = true;
      });
      container.style.display = "none";
      if (onLoad !== void 0) {
        onLoad(texture);
      }
    }, onProgress, onError);
    return texture;
  }
};

// node_modules/three/examples/jsm/loaders/MD2Loader.js
var _normalData = [
  [-0.525731, 0, 0.850651],
  [-0.442863, 0.238856, 0.864188],
  [-0.295242, 0, 0.955423],
  [-0.309017, 0.5, 0.809017],
  [-0.16246, 0.262866, 0.951056],
  [0, 0, 1],
  [0, 0.850651, 0.525731],
  [-0.147621, 0.716567, 0.681718],
  [0.147621, 0.716567, 0.681718],
  [0, 0.525731, 0.850651],
  [0.309017, 0.5, 0.809017],
  [0.525731, 0, 0.850651],
  [0.295242, 0, 0.955423],
  [0.442863, 0.238856, 0.864188],
  [0.16246, 0.262866, 0.951056],
  [-0.681718, 0.147621, 0.716567],
  [-0.809017, 0.309017, 0.5],
  [-0.587785, 0.425325, 0.688191],
  [-0.850651, 0.525731, 0],
  [-0.864188, 0.442863, 0.238856],
  [-0.716567, 0.681718, 0.147621],
  [-0.688191, 0.587785, 0.425325],
  [-0.5, 0.809017, 0.309017],
  [-0.238856, 0.864188, 0.442863],
  [-0.425325, 0.688191, 0.587785],
  [-0.716567, 0.681718, -0.147621],
  [-0.5, 0.809017, -0.309017],
  [-0.525731, 0.850651, 0],
  [0, 0.850651, -0.525731],
  [-0.238856, 0.864188, -0.442863],
  [0, 0.955423, -0.295242],
  [-0.262866, 0.951056, -0.16246],
  [0, 1, 0],
  [0, 0.955423, 0.295242],
  [-0.262866, 0.951056, 0.16246],
  [0.238856, 0.864188, 0.442863],
  [0.262866, 0.951056, 0.16246],
  [0.5, 0.809017, 0.309017],
  [0.238856, 0.864188, -0.442863],
  [0.262866, 0.951056, -0.16246],
  [0.5, 0.809017, -0.309017],
  [0.850651, 0.525731, 0],
  [0.716567, 0.681718, 0.147621],
  [0.716567, 0.681718, -0.147621],
  [0.525731, 0.850651, 0],
  [0.425325, 0.688191, 0.587785],
  [0.864188, 0.442863, 0.238856],
  [0.688191, 0.587785, 0.425325],
  [0.809017, 0.309017, 0.5],
  [0.681718, 0.147621, 0.716567],
  [0.587785, 0.425325, 0.688191],
  [0.955423, 0.295242, 0],
  [1, 0, 0],
  [0.951056, 0.16246, 0.262866],
  [0.850651, -0.525731, 0],
  [0.955423, -0.295242, 0],
  [0.864188, -0.442863, 0.238856],
  [0.951056, -0.16246, 0.262866],
  [0.809017, -0.309017, 0.5],
  [0.681718, -0.147621, 0.716567],
  [0.850651, 0, 0.525731],
  [0.864188, 0.442863, -0.238856],
  [0.809017, 0.309017, -0.5],
  [0.951056, 0.16246, -0.262866],
  [0.525731, 0, -0.850651],
  [0.681718, 0.147621, -0.716567],
  [0.681718, -0.147621, -0.716567],
  [0.850651, 0, -0.525731],
  [0.809017, -0.309017, -0.5],
  [0.864188, -0.442863, -0.238856],
  [0.951056, -0.16246, -0.262866],
  [0.147621, 0.716567, -0.681718],
  [0.309017, 0.5, -0.809017],
  [0.425325, 0.688191, -0.587785],
  [0.442863, 0.238856, -0.864188],
  [0.587785, 0.425325, -0.688191],
  [0.688191, 0.587785, -0.425325],
  [-0.147621, 0.716567, -0.681718],
  [-0.309017, 0.5, -0.809017],
  [0, 0.525731, -0.850651],
  [-0.525731, 0, -0.850651],
  [-0.442863, 0.238856, -0.864188],
  [-0.295242, 0, -0.955423],
  [-0.16246, 0.262866, -0.951056],
  [0, 0, -1],
  [0.295242, 0, -0.955423],
  [0.16246, 0.262866, -0.951056],
  [-0.442863, -0.238856, -0.864188],
  [-0.309017, -0.5, -0.809017],
  [-0.16246, -0.262866, -0.951056],
  [0, -0.850651, -0.525731],
  [-0.147621, -0.716567, -0.681718],
  [0.147621, -0.716567, -0.681718],
  [0, -0.525731, -0.850651],
  [0.309017, -0.5, -0.809017],
  [0.442863, -0.238856, -0.864188],
  [0.16246, -0.262866, -0.951056],
  [0.238856, -0.864188, -0.442863],
  [0.5, -0.809017, -0.309017],
  [0.425325, -0.688191, -0.587785],
  [0.716567, -0.681718, -0.147621],
  [0.688191, -0.587785, -0.425325],
  [0.587785, -0.425325, -0.688191],
  [0, -0.955423, -0.295242],
  [0, -1, 0],
  [0.262866, -0.951056, -0.16246],
  [0, -0.850651, 0.525731],
  [0, -0.955423, 0.295242],
  [0.238856, -0.864188, 0.442863],
  [0.262866, -0.951056, 0.16246],
  [0.5, -0.809017, 0.309017],
  [0.716567, -0.681718, 0.147621],
  [0.525731, -0.850651, 0],
  [-0.238856, -0.864188, -0.442863],
  [-0.5, -0.809017, -0.309017],
  [-0.262866, -0.951056, -0.16246],
  [-0.850651, -0.525731, 0],
  [-0.716567, -0.681718, -0.147621],
  [-0.716567, -0.681718, 0.147621],
  [-0.525731, -0.850651, 0],
  [-0.5, -0.809017, 0.309017],
  [-0.238856, -0.864188, 0.442863],
  [-0.262866, -0.951056, 0.16246],
  [-0.864188, -0.442863, 0.238856],
  [-0.809017, -0.309017, 0.5],
  [-0.688191, -0.587785, 0.425325],
  [-0.681718, -0.147621, 0.716567],
  [-0.442863, -0.238856, 0.864188],
  [-0.587785, -0.425325, 0.688191],
  [-0.309017, -0.5, 0.809017],
  [-0.147621, -0.716567, 0.681718],
  [-0.425325, -0.688191, 0.587785],
  [-0.16246, -0.262866, 0.951056],
  [0.442863, -0.238856, 0.864188],
  [0.16246, -0.262866, 0.951056],
  [0.309017, -0.5, 0.809017],
  [0.147621, -0.716567, 0.681718],
  [0, -0.525731, 0.850651],
  [0.425325, -0.688191, 0.587785],
  [0.587785, -0.425325, 0.688191],
  [0.688191, -0.587785, 0.425325],
  [-0.955423, 0.295242, 0],
  [-0.951056, 0.16246, 0.262866],
  [-1, 0, 0],
  [-0.850651, 0, 0.525731],
  [-0.955423, -0.295242, 0],
  [-0.951056, -0.16246, 0.262866],
  [-0.864188, 0.442863, -0.238856],
  [-0.951056, 0.16246, -0.262866],
  [-0.809017, 0.309017, -0.5],
  [-0.864188, -0.442863, -0.238856],
  [-0.951056, -0.16246, -0.262866],
  [-0.809017, -0.309017, -0.5],
  [-0.681718, 0.147621, -0.716567],
  [-0.681718, -0.147621, -0.716567],
  [-0.850651, 0, -0.525731],
  [-0.688191, 0.587785, -0.425325],
  [-0.587785, 0.425325, -0.688191],
  [-0.425325, 0.688191, -0.587785],
  [-0.425325, -0.688191, -0.587785],
  [-0.587785, -0.425325, -0.688191],
  [-0.688191, -0.587785, -0.425325]
];
var MD2Loader = class extends Loader {
  /**
   * Constructs a new MD2 loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded MD2 asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
   * @param {onErrorCallback} [onError] - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(buffer) {
      try {
        onLoad(scope.parse(buffer));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given MD2 data and returns a geometry.
   *
   * @param {ArrayBuffer} buffer - The raw MD2 data as an array buffer.
   * @return {BufferGeometry} The parsed geometry data.
   */
  parse(buffer) {
    const data2 = new DataView(buffer);
    const header = {};
    const headerNames = [
      "ident",
      "version",
      "skinwidth",
      "skinheight",
      "framesize",
      "num_skins",
      "num_vertices",
      "num_st",
      "num_tris",
      "num_glcmds",
      "num_frames",
      "offset_skins",
      "offset_st",
      "offset_tris",
      "offset_frames",
      "offset_glcmds",
      "offset_end"
    ];
    for (let i = 0; i < headerNames.length; i++) {
      header[headerNames[i]] = data2.getInt32(i * 4, true);
    }
    if (header.ident !== 844121161 || header.version !== 8) {
      console.error("Not a valid MD2 file");
      return;
    }
    if (header.offset_end !== data2.byteLength) {
      console.error("Corrupted MD2 file");
      return;
    }
    const geometry = new BufferGeometry();
    const uvsTemp = [];
    let offset = header.offset_st;
    for (let i = 0, l2 = header.num_st; i < l2; i++) {
      const u2 = data2.getInt16(offset + 0, true);
      const v = data2.getInt16(offset + 2, true);
      uvsTemp.push(u2 / header.skinwidth, 1 - v / header.skinheight);
      offset += 4;
    }
    offset = header.offset_tris;
    const vertexIndices = [];
    const uvIndices = [];
    for (let i = 0, l2 = header.num_tris; i < l2; i++) {
      vertexIndices.push(
        data2.getUint16(offset + 0, true),
        data2.getUint16(offset + 2, true),
        data2.getUint16(offset + 4, true)
      );
      uvIndices.push(
        data2.getUint16(offset + 6, true),
        data2.getUint16(offset + 8, true),
        data2.getUint16(offset + 10, true)
      );
      offset += 12;
    }
    const translation = new Vector3();
    const scale2 = new Vector3();
    const frames2 = [];
    offset = header.offset_frames;
    for (let i = 0, l2 = header.num_frames; i < l2; i++) {
      scale2.set(
        data2.getFloat32(offset + 0, true),
        data2.getFloat32(offset + 4, true),
        data2.getFloat32(offset + 8, true)
      );
      translation.set(
        data2.getFloat32(offset + 12, true),
        data2.getFloat32(offset + 16, true),
        data2.getFloat32(offset + 20, true)
      );
      offset += 24;
      const string = [];
      for (let j2 = 0; j2 < 16; j2++) {
        const character = data2.getUint8(offset + j2);
        if (character === 0) break;
        string[j2] = character;
      }
      const frame = {
        name: String.fromCharCode.apply(null, string),
        vertices: [],
        normals: []
      };
      offset += 16;
      for (let j2 = 0; j2 < header.num_vertices; j2++) {
        let x2 = data2.getUint8(offset++);
        let y = data2.getUint8(offset++);
        let z = data2.getUint8(offset++);
        const n2 = _normalData[data2.getUint8(offset++)];
        x2 = x2 * scale2.x + translation.x;
        y = y * scale2.y + translation.y;
        z = z * scale2.z + translation.z;
        frame.vertices.push(x2, z, y);
        frame.normals.push(n2[0], n2[2], n2[1]);
      }
      frames2.push(frame);
    }
    const positions = [];
    const normals = [];
    const uvs = [];
    const verticesTemp = frames2[0].vertices;
    const normalsTemp = frames2[0].normals;
    for (let i = 0, l2 = vertexIndices.length; i < l2; i++) {
      const vertexIndex = vertexIndices[i];
      let stride = vertexIndex * 3;
      const x2 = verticesTemp[stride];
      const y = verticesTemp[stride + 1];
      const z = verticesTemp[stride + 2];
      positions.push(x2, y, z);
      const nx = normalsTemp[stride];
      const ny = normalsTemp[stride + 1];
      const nz = normalsTemp[stride + 2];
      normals.push(nx, ny, nz);
      const uvIndex = uvIndices[i];
      stride = uvIndex * 2;
      const u2 = uvsTemp[stride];
      const v = uvsTemp[stride + 1];
      uvs.push(u2, v);
    }
    geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
    geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    const morphPositions = [];
    const morphNormals = [];
    for (let i = 0, l2 = frames2.length; i < l2; i++) {
      const frame = frames2[i];
      const attributeName = frame.name;
      if (frame.vertices.length > 0) {
        const positions2 = [];
        for (let j2 = 0, jl = vertexIndices.length; j2 < jl; j2++) {
          const vertexIndex = vertexIndices[j2];
          const stride = vertexIndex * 3;
          const x2 = frame.vertices[stride];
          const y = frame.vertices[stride + 1];
          const z = frame.vertices[stride + 2];
          positions2.push(x2, y, z);
        }
        const positionAttribute = new Float32BufferAttribute(positions2, 3);
        positionAttribute.name = attributeName;
        morphPositions.push(positionAttribute);
      }
      if (frame.normals.length > 0) {
        const normals2 = [];
        for (let j2 = 0, jl = vertexIndices.length; j2 < jl; j2++) {
          const vertexIndex = vertexIndices[j2];
          const stride = vertexIndex * 3;
          const nx = frame.normals[stride];
          const ny = frame.normals[stride + 1];
          const nz = frame.normals[stride + 2];
          normals2.push(nx, ny, nz);
        }
        const normalAttribute = new Float32BufferAttribute(normals2, 3);
        normalAttribute.name = attributeName;
        morphNormals.push(normalAttribute);
      }
    }
    geometry.morphAttributes.position = morphPositions;
    geometry.morphAttributes.normal = morphNormals;
    geometry.morphTargetsRelative = false;
    geometry.animations = AnimationClip.CreateClipsFromMorphTargetSequences(frames2, 10, false);
    return geometry;
  }
};

// node_modules/three/examples/jsm/loaders/MDDLoader.js
var MDDLoader = class extends Loader {
  /**
   * Constructs a new MDD loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded MDD asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function({clip:AnimationClip, morphTargets:Array<BufferAttribute>})} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("arraybuffer");
    loader.load(url, function(data2) {
      onLoad(scope.parse(data2));
    }, onProgress, onError);
  }
  /**
   * Parses the given MDD data and returns an object holding the animation clip and the respective
   * morph targets.
   *
   * @param {ArrayBuffer} data - The raw XYZ data as an array buffer.
   * @return {{clip:AnimationClip, morphTargets:Array<BufferAttribute>}} The result object.
   */
  parse(data2) {
    const view = new DataView(data2);
    const totalFrames = view.getUint32(0);
    const totalPoints = view.getUint32(4);
    let offset = 8;
    const times = new Float32Array(totalFrames);
    const values2 = new Float32Array(totalFrames * totalFrames).fill(0);
    for (let i = 0; i < totalFrames; i++) {
      times[i] = view.getFloat32(offset);
      offset += 4;
      values2[totalFrames * i + i] = 1;
    }
    const track = new NumberKeyframeTrack(".morphTargetInfluences", times, values2);
    const clip = new AnimationClip("default", times[times.length - 1], [track]);
    const morphTargets = [];
    for (let i = 0; i < totalFrames; i++) {
      const morphTarget = new Float32Array(totalPoints * 3);
      for (let j2 = 0; j2 < totalPoints; j2++) {
        const stride = j2 * 3;
        morphTarget[stride + 0] = view.getFloat32(offset);
        offset += 4;
        morphTarget[stride + 1] = view.getFloat32(offset);
        offset += 4;
        morphTarget[stride + 2] = view.getFloat32(offset);
        offset += 4;
      }
      const attribute = new BufferAttribute(morphTarget, 3);
      attribute.name = "morph_" + i;
      morphTargets.push(attribute);
    }
    return {
      morphTargets,
      clip
    };
  }
};

// node_modules/three/examples/jsm/loaders/MTLLoader.js
var MTLLoader = class extends Loader {
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded MTL asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(MaterialCreator)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2, path));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Sets the material options.
   *
   * @param {MTLLoader~MaterialOptions} value - The material options.
   * @return {MTLLoader} A reference to this loader.
   */
  setMaterialOptions(value2) {
    this.materialOptions = value2;
    return this;
  }
  /**
   * Parses the given MTL data and returns the resulting material creator.
   *
   * @param {string} text - The raw MTL data as a string.
   * @param {string} path - The URL base path.
   * @return {MaterialCreator} The material creator.
   */
  parse(text2, path) {
    const lines = text2.split("\n");
    let info = {};
    const delimiter_pattern = /\s+/;
    const materialsInfo = {};
    for (let i = 0; i < lines.length; i++) {
      let line2 = lines[i];
      line2 = line2.trim();
      if (line2.length === 0 || line2.charAt(0) === "#") {
        continue;
      }
      const pos = line2.indexOf(" ");
      let key2 = pos >= 0 ? line2.substring(0, pos) : line2;
      key2 = key2.toLowerCase();
      let value2 = pos >= 0 ? line2.substring(pos + 1) : "";
      value2 = value2.trim();
      if (key2 === "newmtl") {
        info = { name: value2 };
        materialsInfo[value2] = info;
      } else {
        if (key2 === "ka" || key2 === "kd" || key2 === "ks" || key2 === "ke") {
          const ss = value2.split(delimiter_pattern, 3);
          info[key2] = [parseFloat(ss[0]), parseFloat(ss[1]), parseFloat(ss[2])];
        } else {
          info[key2] = value2;
        }
      }
    }
    const materialCreator = new MaterialCreator(this.resourcePath || path, this.materialOptions);
    materialCreator.setCrossOrigin(this.crossOrigin);
    materialCreator.setManager(this.manager);
    materialCreator.setMaterials(materialsInfo);
    return materialCreator;
  }
};
var MaterialCreator = class {
  constructor(baseUrl = "", options = {}) {
    this.baseUrl = baseUrl;
    this.options = options;
    this.materialsInfo = {};
    this.materials = {};
    this.materialsArray = [];
    this.nameLookup = {};
    this.crossOrigin = "anonymous";
    this.side = this.options.side !== void 0 ? this.options.side : FrontSide;
    this.wrap = this.options.wrap !== void 0 ? this.options.wrap : RepeatWrapping;
  }
  setCrossOrigin(value2) {
    this.crossOrigin = value2;
    return this;
  }
  setManager(value2) {
    this.manager = value2;
  }
  setMaterials(materialsInfo) {
    this.materialsInfo = this.convert(materialsInfo);
    this.materials = {};
    this.materialsArray = [];
    this.nameLookup = {};
  }
  convert(materialsInfo) {
    if (!this.options) return materialsInfo;
    const converted = {};
    for (const mn2 in materialsInfo) {
      const mat = materialsInfo[mn2];
      const covmat = {};
      converted[mn2] = covmat;
      for (const prop in mat) {
        let save = true;
        let value2 = mat[prop];
        const lprop = prop.toLowerCase();
        switch (lprop) {
          case "kd":
          case "ka":
          case "ks":
            if (this.options && this.options.normalizeRGB) {
              value2 = [value2[0] / 255, value2[1] / 255, value2[2] / 255];
            }
            if (this.options && this.options.ignoreZeroRGBs) {
              if (value2[0] === 0 && value2[1] === 0 && value2[2] === 0) {
                save = false;
              }
            }
            break;
          default:
            break;
        }
        if (save) {
          covmat[lprop] = value2;
        }
      }
    }
    return converted;
  }
  preload() {
    for (const mn2 in this.materialsInfo) {
      this.create(mn2);
    }
  }
  getIndex(materialName) {
    return this.nameLookup[materialName];
  }
  getAsArray() {
    let index2 = 0;
    for (const mn2 in this.materialsInfo) {
      this.materialsArray[index2] = this.create(mn2);
      this.nameLookup[mn2] = index2;
      index2++;
    }
    return this.materialsArray;
  }
  create(materialName) {
    if (this.materials[materialName] === void 0) {
      this.createMaterial_(materialName);
    }
    return this.materials[materialName];
  }
  createMaterial_(materialName) {
    const scope = this;
    const mat = this.materialsInfo[materialName];
    const params = {
      name: materialName,
      side: this.side
    };
    function resolveURL(baseUrl, url) {
      if (typeof url !== "string" || url === "")
        return "";
      if (/^https?:\/\//i.test(url)) return url;
      return baseUrl + url;
    }
    function setMapForType(mapType, value2) {
      if (params[mapType]) return;
      const texParams = scope.getTextureParams(value2, params);
      const map2 = scope.loadTexture(resolveURL(scope.baseUrl, texParams.url));
      map2.repeat.copy(texParams.scale);
      map2.offset.copy(texParams.offset);
      map2.wrapS = scope.wrap;
      map2.wrapT = scope.wrap;
      if (mapType === "map" || mapType === "emissiveMap") {
        map2.colorSpace = SRGBColorSpace;
      }
      params[mapType] = map2;
    }
    for (const prop in mat) {
      const value2 = mat[prop];
      let n2;
      if (value2 === "") continue;
      switch (prop.toLowerCase()) {
        // Ns is material specular exponent
        case "kd":
          params.color = ColorManagement.colorSpaceToWorking(new Color().fromArray(value2), SRGBColorSpace);
          break;
        case "ks":
          params.specular = ColorManagement.colorSpaceToWorking(new Color().fromArray(value2), SRGBColorSpace);
          break;
        case "ke":
          params.emissive = ColorManagement.colorSpaceToWorking(new Color().fromArray(value2), SRGBColorSpace);
          break;
        case "map_kd":
          setMapForType("map", value2);
          break;
        case "map_ks":
          setMapForType("specularMap", value2);
          break;
        case "map_ke":
          setMapForType("emissiveMap", value2);
          break;
        case "norm":
          setMapForType("normalMap", value2);
          break;
        case "map_bump":
        case "bump":
          setMapForType("bumpMap", value2);
          break;
        case "disp":
          setMapForType("displacementMap", value2);
          break;
        case "map_d":
          setMapForType("alphaMap", value2);
          params.transparent = true;
          break;
        case "ns":
          params.shininess = parseFloat(value2);
          break;
        case "d":
          n2 = parseFloat(value2);
          if (n2 < 1) {
            params.opacity = n2;
            params.transparent = true;
          }
          break;
        case "tr":
          n2 = parseFloat(value2);
          if (this.options && this.options.invertTrProperty) n2 = 1 - n2;
          if (n2 > 0) {
            params.opacity = 1 - n2;
            params.transparent = true;
          }
          break;
        default:
          break;
      }
    }
    this.materials[materialName] = new MeshPhongMaterial(params);
    return this.materials[materialName];
  }
  getTextureParams(value2, matParams) {
    const texParams = {
      scale: new Vector2(1, 1),
      offset: new Vector2(0, 0)
    };
    const items = value2.split(/\s+/);
    let pos;
    pos = items.indexOf("-bm");
    if (pos >= 0) {
      matParams.bumpScale = parseFloat(items[pos + 1]);
      items.splice(pos, 2);
    }
    pos = items.indexOf("-mm");
    if (pos >= 0) {
      matParams.displacementBias = parseFloat(items[pos + 1]);
      matParams.displacementScale = parseFloat(items[pos + 2]);
      items.splice(pos, 3);
    }
    pos = items.indexOf("-s");
    if (pos >= 0) {
      texParams.scale.set(parseFloat(items[pos + 1]), parseFloat(items[pos + 2]));
      items.splice(pos, 4);
    }
    pos = items.indexOf("-o");
    if (pos >= 0) {
      texParams.offset.set(parseFloat(items[pos + 1]), parseFloat(items[pos + 2]));
      items.splice(pos, 4);
    }
    texParams.url = items.join(" ").trim();
    return texParams;
  }
  loadTexture(url, mapping, onLoad, onProgress, onError) {
    const manager = this.manager !== void 0 ? this.manager : DefaultLoadingManager;
    let loader = manager.getHandler(url);
    if (loader === null) {
      loader = new TextureLoader(manager);
    }
    if (loader.setCrossOrigin) loader.setCrossOrigin(this.crossOrigin);
    const texture = loader.load(url, onLoad, onProgress, onError);
    if (mapping !== void 0) texture.mapping = mapping;
    return texture;
  }
};

// node_modules/three/examples/jsm/misc/VolumeSlice.js
var VolumeSlice = class {
  /**
   * Constructs a new volume slice.
   *
  	 * @param {Volume} volume - The associated volume.
  	 * @param {number} [index=0] - The index of the slice.
  	 * @param {('x'|'y'|'z')} [axis='z'] - For now only 'x', 'y' or 'z' but later it will change to a normal vector.
   */
  constructor(volume, index2 = 0, axis = "z") {
    const slice2 = this;
    this.volume = volume;
    Object.defineProperty(this, "index", {
      get: function() {
        return index2;
      },
      /**
       * The index of the slice, if changed, will automatically call updateGeometry at the next repaint.
       *
       * @name VolumeSlice#index
       * @type {number}
       * @default 0
       * @param {number} value
       * @return {number}
       */
      set: function(value2) {
        index2 = value2;
        slice2.geometryNeedsUpdate = true;
        return index2;
      }
    });
    this.axis = axis;
    this.canvas = document.createElement("canvas");
    this.ctx;
    this.canvasBuffer = document.createElement("canvas");
    this.ctxBuffer;
    this.updateGeometry();
    const canvasMap = new Texture(this.canvas);
    canvasMap.minFilter = LinearFilter;
    canvasMap.generateMipmaps = false;
    canvasMap.wrapS = canvasMap.wrapT = ClampToEdgeWrapping;
    canvasMap.colorSpace = SRGBColorSpace;
    const material = new MeshBasicMaterial({ map: canvasMap, side: DoubleSide, transparent: true });
    this.mesh = new Mesh(this.geometry, material);
    this.mesh.matrixAutoUpdate = false;
    this.geometryNeedsUpdate = true;
    this.repaint();
    this.iLength = 0;
    this.jLength = 0;
    this.sliceAccess = null;
  }
  /**
   * Refresh the texture and the geometry if geometryNeedsUpdate is set to `true`.
   */
  repaint() {
    if (this.geometryNeedsUpdate) {
      this.updateGeometry();
    }
    const iLength = this.iLength, jLength = this.jLength, sliceAccess = this.sliceAccess, volume = this.volume, canvas = this.canvasBuffer, ctx = this.ctxBuffer;
    const imgData = ctx.getImageData(0, 0, iLength, jLength);
    const data2 = imgData.data;
    const volumeData = volume.data;
    const upperThreshold = volume.upperThreshold;
    const lowerThreshold = volume.lowerThreshold;
    const windowLow = volume.windowLow;
    const windowHigh = volume.windowHigh;
    let pixelCount = 0;
    if (volume.dataType === "label") {
      console.error("THREE.VolumeSlice.repaint: label are not supported yet");
    } else {
      for (let j2 = 0; j2 < jLength; j2++) {
        for (let i = 0; i < iLength; i++) {
          let value2 = volumeData[sliceAccess(i, j2)];
          let alpha = 255;
          alpha = upperThreshold >= value2 ? lowerThreshold <= value2 ? alpha : 0 : 0;
          value2 = Math.floor(255 * (value2 - windowLow) / (windowHigh - windowLow));
          value2 = value2 > 255 ? 255 : value2 < 0 ? 0 : value2 | 0;
          data2[4 * pixelCount] = value2;
          data2[4 * pixelCount + 1] = value2;
          data2[4 * pixelCount + 2] = value2;
          data2[4 * pixelCount + 3] = alpha;
          pixelCount++;
        }
      }
    }
    ctx.putImageData(imgData, 0, 0);
    this.ctx.drawImage(canvas, 0, 0, iLength, jLength, 0, 0, this.canvas.width, this.canvas.height);
    this.mesh.material.map.needsUpdate = true;
  }
  /**
   * Refresh the geometry according to axis and index.
   * @see {@link Volume#extractPerpendicularPlane}
   */
  updateGeometry() {
    const extracted = this.volume.extractPerpendicularPlane(this.axis, this.index);
    this.sliceAccess = extracted.sliceAccess;
    this.jLength = extracted.jLength;
    this.iLength = extracted.iLength;
    this.matrix = extracted.matrix;
    this.canvas.width = extracted.planeWidth;
    this.canvas.height = extracted.planeHeight;
    this.canvasBuffer.width = this.iLength;
    this.canvasBuffer.height = this.jLength;
    this.ctx = this.canvas.getContext("2d");
    this.ctxBuffer = this.canvasBuffer.getContext("2d");
    if (this.geometry) this.geometry.dispose();
    this.geometry = new PlaneGeometry(extracted.planeWidth, extracted.planeHeight);
    if (this.mesh) {
      this.mesh.geometry = this.geometry;
      this.mesh.matrix.identity();
      this.mesh.applyMatrix4(this.matrix);
    }
    this.geometryNeedsUpdate = false;
  }
};

// node_modules/three/examples/jsm/misc/Volume.js
var Volume = class {
  /**
   * Constructs a new volume.
   *
   * @param {number} [xLength] - Width of the volume.
   * @param {number} [yLength] - Length of the volume.
   * @param {number} [zLength] - Depth of the volume.
   * @param {string} [type] - The type of data (uint8, uint16, ...).
   * @param {ArrayBuffer} [arrayBuffer] - The buffer with volume data.
   */
  constructor(xLength, yLength, zLength, type, arrayBuffer) {
    if (xLength !== void 0) {
      this.xLength = Number(xLength) || 1;
      this.yLength = Number(yLength) || 1;
      this.zLength = Number(zLength) || 1;
      this.axisOrder = ["x", "y", "z"];
      this.data;
      switch (type) {
        case "Uint8":
        case "uint8":
        case "uchar":
        case "unsigned char":
        case "uint8_t":
          this.data = new Uint8Array(arrayBuffer);
          break;
        case "Int8":
        case "int8":
        case "signed char":
        case "int8_t":
          this.data = new Int8Array(arrayBuffer);
          break;
        case "Int16":
        case "int16":
        case "short":
        case "short int":
        case "signed short":
        case "signed short int":
        case "int16_t":
          this.data = new Int16Array(arrayBuffer);
          break;
        case "Uint16":
        case "uint16":
        case "ushort":
        case "unsigned short":
        case "unsigned short int":
        case "uint16_t":
          this.data = new Uint16Array(arrayBuffer);
          break;
        case "Int32":
        case "int32":
        case "int":
        case "signed int":
        case "int32_t":
          this.data = new Int32Array(arrayBuffer);
          break;
        case "Uint32":
        case "uint32":
        case "uint":
        case "unsigned int":
        case "uint32_t":
          this.data = new Uint32Array(arrayBuffer);
          break;
        case "longlong":
        case "long long":
        case "long long int":
        case "signed long long":
        case "signed long long int":
        case "int64":
        case "int64_t":
        case "ulonglong":
        case "unsigned long long":
        case "unsigned long long int":
        case "uint64":
        case "uint64_t":
          throw new Error("Error in Volume constructor : this type is not supported in JavaScript");
          break;
        case "Float32":
        case "float32":
        case "float":
          this.data = new Float32Array(arrayBuffer);
          break;
        case "Float64":
        case "float64":
        case "double":
          this.data = new Float64Array(arrayBuffer);
          break;
        default:
          this.data = new Uint8Array(arrayBuffer);
      }
      if (this.data.length !== this.xLength * this.yLength * this.zLength) {
        throw new Error("Error in Volume constructor, lengths are not matching arrayBuffer size");
      }
    }
    this.spacing = [1, 1, 1];
    this.offset = [0, 0, 0];
    this.matrix = new Matrix3();
    this.matrix.identity();
    this.inverseMatrix = new Matrix3();
    let lowerThreshold = -Infinity;
    Object.defineProperty(this, "lowerThreshold", {
      get: function() {
        return lowerThreshold;
      },
      /**
       * The voxels with values under this threshold won't appear in the slices.
       * If changed, geometryNeedsUpdate is automatically set to true on all the slices associated to this volume.
       *
       * @name Volume#lowerThreshold
       * @type {number}
       * @param {number} value
       */
      set: function(value2) {
        lowerThreshold = value2;
        this.sliceList.forEach(function(slice2) {
          slice2.geometryNeedsUpdate = true;
        });
      }
    });
    let upperThreshold = Infinity;
    Object.defineProperty(this, "upperThreshold", {
      get: function() {
        return upperThreshold;
      },
      /**
       * The voxels with values over this threshold won't appear in the slices.
       * If changed, geometryNeedsUpdate is automatically set to true on all the slices associated to this volume
       *
       * @name Volume#upperThreshold
       * @type {number}
       * @param {number} value
       */
      set: function(value2) {
        upperThreshold = value2;
        this.sliceList.forEach(function(slice2) {
          slice2.geometryNeedsUpdate = true;
        });
      }
    });
    this.sliceList = [];
    this.segmentation = false;
    this.RASDimensions = [];
  }
  /**
   * Shortcut for data[access(i,j,k)].
   *
   * @param {number} i - First coordinate.
   * @param {number} j - Second coordinate.
   * @param {number} k - Third coordinate.
   * @returns {number} The value in the data array.
   */
  getData(i, j2, k2) {
    return this.data[k2 * this.xLength * this.yLength + j2 * this.xLength + i];
  }
  /**
   * Compute the index in the data array corresponding to the given coordinates in IJK system.
   *
   * @param {number} i - First coordinate.
   * @param {number} j - Second coordinate.
   * @param {number} k - Third coordinate.
   * @returns {number} The index.
   */
  access(i, j2, k2) {
    return k2 * this.xLength * this.yLength + j2 * this.xLength + i;
  }
  /**
   * Retrieve the IJK coordinates of the voxel corresponding of the given index in the data.
   *
   * @param {number} index - Index of the voxel.
   * @returns {Array<number>} The IJK coordinates as `[x,y,z]`.
   */
  reverseAccess(index2) {
    const z = Math.floor(index2 / (this.yLength * this.xLength));
    const y = Math.floor((index2 - z * this.yLength * this.xLength) / this.xLength);
    const x2 = index2 - z * this.yLength * this.xLength - y * this.xLength;
    return [x2, y, z];
  }
  /**
   * Apply a function to all the voxels, be careful, the value will be replaced.
   *
   * @param {Function} functionToMap A function to apply to every voxel, will be called with the following parameters:
   * value of the voxel, index of the voxel, the data (TypedArray).
   * @param {Object} context - You can specify a context in which call the function, default if this Volume.
   * @returns {Volume} A reference to this instance.
   */
  map(functionToMap, context) {
    const length2 = this.data.length;
    context = context || this;
    for (let i = 0; i < length2; i++) {
      this.data[i] = functionToMap.call(context, this.data[i], i, this.data);
    }
    return this;
  }
  /**
   * Compute the orientation of the slice and returns all the information relative to the geometry such as sliceAccess,
   * the plane matrix (orientation and position in RAS coordinate) and the dimensions of the plane in both coordinate system.
   *
   * @param {('x'|'y'|'z')} axis - The normal axis to the slice.
   * @param {number} RASIndex - The index of the slice.
   * @returns {Object} An object containing all the useful information on the geometry of the slice.
   */
  extractPerpendicularPlane(axis, RASIndex) {
    let firstSpacing, secondSpacing, positionOffset, IJKIndex;
    const axisInIJK = new Vector3(), firstDirection = new Vector3(), secondDirection = new Vector3(), planeMatrix = new Matrix4().identity(), volume = this;
    const dimensions = new Vector3(this.xLength, this.yLength, this.zLength);
    switch (axis) {
      case "x":
        axisInIJK.set(1, 0, 0);
        firstDirection.set(0, 0, -1);
        secondDirection.set(0, -1, 0);
        firstSpacing = this.spacing[this.axisOrder.indexOf("z")];
        secondSpacing = this.spacing[this.axisOrder.indexOf("y")];
        IJKIndex = new Vector3(RASIndex, 0, 0);
        planeMatrix.multiply(new Matrix4().makeRotationY(Math.PI / 2));
        positionOffset = (volume.RASDimensions[0] - 1) / 2;
        planeMatrix.setPosition(new Vector3(RASIndex - positionOffset, 0, 0));
        break;
      case "y":
        axisInIJK.set(0, 1, 0);
        firstDirection.set(1, 0, 0);
        secondDirection.set(0, 0, 1);
        firstSpacing = this.spacing[this.axisOrder.indexOf("x")];
        secondSpacing = this.spacing[this.axisOrder.indexOf("z")];
        IJKIndex = new Vector3(0, RASIndex, 0);
        planeMatrix.multiply(new Matrix4().makeRotationX(-Math.PI / 2));
        positionOffset = (volume.RASDimensions[1] - 1) / 2;
        planeMatrix.setPosition(new Vector3(0, RASIndex - positionOffset, 0));
        break;
      case "z":
      default:
        axisInIJK.set(0, 0, 1);
        firstDirection.set(1, 0, 0);
        secondDirection.set(0, -1, 0);
        firstSpacing = this.spacing[this.axisOrder.indexOf("x")];
        secondSpacing = this.spacing[this.axisOrder.indexOf("y")];
        IJKIndex = new Vector3(0, 0, RASIndex);
        positionOffset = (volume.RASDimensions[2] - 1) / 2;
        planeMatrix.setPosition(new Vector3(0, 0, RASIndex - positionOffset));
        break;
    }
    if (!this.segmentation) {
      firstDirection.applyMatrix4(volume.inverseMatrix).normalize();
      secondDirection.applyMatrix4(volume.inverseMatrix).normalize();
      axisInIJK.applyMatrix4(volume.inverseMatrix).normalize();
    }
    firstDirection.arglet = "i";
    secondDirection.arglet = "j";
    const iLength = Math.floor(Math.abs(firstDirection.dot(dimensions)));
    const jLength = Math.floor(Math.abs(secondDirection.dot(dimensions)));
    const planeWidth = Math.abs(iLength * firstSpacing);
    const planeHeight = Math.abs(jLength * secondSpacing);
    IJKIndex = Math.abs(Math.round(IJKIndex.applyMatrix4(volume.inverseMatrix).dot(axisInIJK)));
    const base = [new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1)];
    const iDirection = [firstDirection, secondDirection, axisInIJK].find(function(x2) {
      return Math.abs(x2.dot(base[0])) > 0.9;
    });
    const jDirection = [firstDirection, secondDirection, axisInIJK].find(function(x2) {
      return Math.abs(x2.dot(base[1])) > 0.9;
    });
    const kDirection = [firstDirection, secondDirection, axisInIJK].find(function(x2) {
      return Math.abs(x2.dot(base[2])) > 0.9;
    });
    function sliceAccess(i, j2) {
      const si = iDirection === axisInIJK ? IJKIndex : iDirection.arglet === "i" ? i : j2;
      const sj = jDirection === axisInIJK ? IJKIndex : jDirection.arglet === "i" ? i : j2;
      const sk = kDirection === axisInIJK ? IJKIndex : kDirection.arglet === "i" ? i : j2;
      const accessI = iDirection.dot(base[0]) > 0 ? si : volume.xLength - 1 - si;
      const accessJ = jDirection.dot(base[1]) > 0 ? sj : volume.yLength - 1 - sj;
      const accessK = kDirection.dot(base[2]) > 0 ? sk : volume.zLength - 1 - sk;
      return volume.access(accessI, accessJ, accessK);
    }
    return {
      iLength,
      jLength,
      sliceAccess,
      matrix: planeMatrix,
      planeWidth,
      planeHeight
    };
  }
  /**
   * Returns a slice corresponding to the given axis and index.
   * The coordinate are given in the Right Anterior Superior coordinate format.
   *
   * @param {('x'|'y'|'z')} axis - The normal axis to the slice.
   * @param {number} index - The index of the slice.
   * @returns {VolumeSlice} The extracted slice.
   */
  extractSlice(axis, index2) {
    const slice2 = new VolumeSlice(this, index2, axis);
    this.sliceList.push(slice2);
    return slice2;
  }
  /**
   * Call repaint on all the slices extracted from this volume.
   *
   * @see {@link VolumeSlice#repaint}
   * @returns {Volume} A reference to this volume.
   */
  repaintAllSlices() {
    this.sliceList.forEach(function(slice2) {
      slice2.repaint();
    });
    return this;
  }
  /**
   * Compute the minimum and the maximum of the data in the volume.
   *
   * @returns {Array<number>} The min/max data as `[min,max]`.
   */
  computeMinMax() {
    let min = Infinity;
    let max2 = -Infinity;
    const datasize = this.data.length;
    let i = 0;
    for (i = 0; i < datasize; i++) {
      if (!isNaN(this.data[i])) {
        const value2 = this.data[i];
        min = Math.min(min, value2);
        max2 = Math.max(max2, value2);
      }
    }
    this.min = min;
    this.max = max2;
    return [min, max2];
  }
};

// node_modules/three/examples/jsm/loaders/NRRDLoader.js
var NRRDLoader = class extends Loader {
  /**
   * Constructs a new NRRD loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded NRRD asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Volume)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(data2) {
      try {
        onLoad(scope.parse(data2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Toggles the segmentation mode.
   *
   * @param {boolean} segmentation - Whether to use segmentation mode or not.
   */
  setSegmentation(segmentation) {
    this.segmentation = segmentation;
  }
  /**
   * Parses the given NRRD data and returns the resulting volume data.
   *
   * @param {ArrayBuffer} data - The raw NRRD data as an array buffer.
   * @return {Volume} The parsed volume.
   */
  parse(data2) {
    let _data = data2;
    let _dataPointer = 0;
    const _nativeLittleEndian = new Int8Array(new Int16Array([1]).buffer)[0] > 0;
    const _littleEndian = true;
    const headerObject = {};
    function scan(type, chunks) {
      let _chunkSize = 1;
      let _array_type = Uint8Array;
      switch (type) {
        // 1 byte data types
        case "uchar":
          break;
        case "schar":
          _array_type = Int8Array;
          break;
        // 2 byte data types
        case "ushort":
          _array_type = Uint16Array;
          _chunkSize = 2;
          break;
        case "sshort":
          _array_type = Int16Array;
          _chunkSize = 2;
          break;
        // 4 byte data types
        case "uint":
          _array_type = Uint32Array;
          _chunkSize = 4;
          break;
        case "sint":
          _array_type = Int32Array;
          _chunkSize = 4;
          break;
        case "float":
          _array_type = Float32Array;
          _chunkSize = 4;
          break;
        case "complex":
          _array_type = Float64Array;
          _chunkSize = 8;
          break;
        case "double":
          _array_type = Float64Array;
          _chunkSize = 8;
          break;
      }
      let _bytes2 = new _array_type(_data.slice(
        _dataPointer,
        _dataPointer += chunks * _chunkSize
      ));
      if (_nativeLittleEndian != _littleEndian) {
        _bytes2 = flipEndianness(_bytes2, _chunkSize);
      }
      return _bytes2;
    }
    function flipEndianness(array, chunkSize) {
      const u82 = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
      for (let i2 = 0; i2 < array.byteLength; i2 += chunkSize) {
        for (let j2 = i2 + chunkSize - 1, k2 = i2; j2 > k2; j2--, k2++) {
          const tmp = u82[k2];
          u82[k2] = u82[j2];
          u82[j2] = tmp;
        }
      }
      return array;
    }
    function parseHeader(header) {
      let data3, field, fn, i2, l2, m, _i, _len;
      const lines = header.split(/\r?\n/);
      for (_i = 0, _len = lines.length; _i < _len; _i++) {
        l2 = lines[_i];
        if (l2.match(/NRRD\d+/)) {
          headerObject.isNrrd = true;
        } else if (!l2.match(/^#/) && (m = l2.match(/(.*):(.*)/))) {
          field = m[1].trim();
          data3 = m[2].trim();
          fn = _fieldFunctions[field];
          if (fn) {
            fn.call(headerObject, data3);
          } else {
            headerObject[field] = data3;
          }
        }
      }
      if (!headerObject.isNrrd) {
        throw new Error("Not an NRRD file");
      }
      if (headerObject.encoding === "bz2" || headerObject.encoding === "bzip2") {
        throw new Error("Bzip is not supported");
      }
      if (!headerObject.vectors) {
        headerObject.vectors = [];
        headerObject.vectors.push([1, 0, 0]);
        headerObject.vectors.push([0, 1, 0]);
        headerObject.vectors.push([0, 0, 1]);
        if (headerObject.spacings) {
          for (i2 = 0; i2 <= 2; i2++) {
            if (!isNaN(headerObject.spacings[i2])) {
              for (let j2 = 0; j2 <= 2; j2++) {
                headerObject.vectors[i2][j2] *= headerObject.spacings[i2];
              }
            }
          }
        }
      }
    }
    function parseDataAsText(data3, start, end) {
      let number = "";
      start = start || 0;
      end = end || data3.length;
      let value2;
      const lengthOfTheResult = headerObject.sizes.reduce(function(previous, current) {
        return previous * current;
      }, 1);
      let base = 10;
      if (headerObject.encoding === "hex") {
        base = 16;
      }
      const result = new headerObject.__array(lengthOfTheResult);
      let resultIndex = 0;
      let parsingFunction = parseInt;
      if (headerObject.__array === Float32Array || headerObject.__array === Float64Array) {
        parsingFunction = parseFloat;
      }
      for (let i2 = start; i2 < end; i2++) {
        value2 = data3[i2];
        if ((value2 < 9 || value2 > 13) && value2 !== 32) {
          number += String.fromCharCode(value2);
        } else {
          if (number !== "") {
            result[resultIndex] = parsingFunction(number, base);
            resultIndex++;
          }
          number = "";
        }
      }
      if (number !== "") {
        result[resultIndex] = parsingFunction(number, base);
        resultIndex++;
      }
      return result;
    }
    const _bytes = scan("uchar", data2.byteLength);
    const _length = _bytes.length;
    let _header = null;
    let _data_start = 0;
    let i;
    for (i = 1; i < _length; i++) {
      if (_bytes[i - 1] == 10 && _bytes[i] == 10) {
        _header = this._parseChars(_bytes, 0, i - 2);
        _data_start = i + 1;
        break;
      }
    }
    parseHeader(_header);
    _data = _bytes.subarray(_data_start);
    if (headerObject.encoding.substring(0, 2) === "gz") {
      _data = gunzipSync(new Uint8Array(_data));
    } else if (headerObject.encoding === "ascii" || headerObject.encoding === "text" || headerObject.encoding === "txt" || headerObject.encoding === "hex") {
      _data = parseDataAsText(_data);
    } else if (headerObject.encoding === "raw") {
      const _copy = new Uint8Array(_data.length);
      for (let i2 = 0; i2 < _data.length; i2++) {
        _copy[i2] = _data[i2];
      }
      _data = _copy;
    }
    _data = _data.buffer;
    const volume = new Volume();
    volume.header = headerObject;
    volume.segmentation = this.segmentation;
    volume.data = new headerObject.__array(_data);
    const min_max = volume.computeMinMax();
    const min = min_max[0];
    const max2 = min_max[1];
    volume.windowLow = min;
    volume.windowHigh = max2;
    volume.dimensions = [headerObject.sizes[0], headerObject.sizes[1], headerObject.sizes[2]];
    volume.xLength = volume.dimensions[0];
    volume.yLength = volume.dimensions[1];
    volume.zLength = volume.dimensions[2];
    if (headerObject.vectors) {
      const xIndex = headerObject.vectors.findIndex((vector) => vector[0] !== 0);
      const yIndex = headerObject.vectors.findIndex((vector) => vector[1] !== 0);
      const zIndex = headerObject.vectors.findIndex((vector) => vector[2] !== 0);
      const axisOrder = [];
      if (xIndex !== yIndex && xIndex !== zIndex && yIndex !== zIndex) {
        axisOrder[xIndex] = "x";
        axisOrder[yIndex] = "y";
        axisOrder[zIndex] = "z";
      } else {
        axisOrder[0] = "x";
        axisOrder[1] = "y";
        axisOrder[2] = "z";
      }
      volume.axisOrder = axisOrder;
    } else {
      volume.axisOrder = ["x", "y", "z"];
    }
    const spacingX = new Vector3().fromArray(headerObject.vectors[0]).length();
    const spacingY = new Vector3().fromArray(headerObject.vectors[1]).length();
    const spacingZ = new Vector3().fromArray(headerObject.vectors[2]).length();
    volume.spacing = [spacingX, spacingY, spacingZ];
    volume.matrix = new Matrix4();
    const transitionMatrix = new Matrix4();
    if (headerObject.space === "left-posterior-superior") {
      transitionMatrix.set(
        -1,
        0,
        0,
        0,
        0,
        -1,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        1
      );
    } else if (headerObject.space === "left-anterior-superior") {
      transitionMatrix.set(
        1,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        -1,
        0,
        0,
        0,
        0,
        1
      );
    }
    if (!headerObject.vectors) {
      volume.matrix.set(
        1,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        1
      );
    } else {
      const v = headerObject.vectors;
      const ijk_to_transition = new Matrix4().set(
        v[0][0],
        v[1][0],
        v[2][0],
        0,
        v[0][1],
        v[1][1],
        v[2][1],
        0,
        v[0][2],
        v[1][2],
        v[2][2],
        0,
        0,
        0,
        0,
        1
      );
      const transition_to_ras = new Matrix4().multiplyMatrices(ijk_to_transition, transitionMatrix);
      volume.matrix = transition_to_ras;
    }
    volume.inverseMatrix = new Matrix4();
    volume.inverseMatrix.copy(volume.matrix).invert();
    volume.RASDimensions = [
      Math.floor(volume.xLength * spacingX),
      Math.floor(volume.yLength * spacingY),
      Math.floor(volume.zLength * spacingZ)
    ];
    if (volume.lowerThreshold === -Infinity) {
      volume.lowerThreshold = min;
    }
    if (volume.upperThreshold === Infinity) {
      volume.upperThreshold = max2;
    }
    return volume;
  }
  _parseChars(array, start, end) {
    if (start === void 0) {
      start = 0;
    }
    if (end === void 0) {
      end = array.length;
    }
    let output = "";
    let i = 0;
    for (i = start; i < end; ++i) {
      output += String.fromCharCode(array[i]);
    }
    return output;
  }
};
var _fieldFunctions = {
  type: function(data2) {
    switch (data2) {
      case "uchar":
      case "unsigned char":
      case "uint8":
      case "uint8_t":
        this.__array = Uint8Array;
        break;
      case "signed char":
      case "int8":
      case "int8_t":
        this.__array = Int8Array;
        break;
      case "short":
      case "short int":
      case "signed short":
      case "signed short int":
      case "int16":
      case "int16_t":
        this.__array = Int16Array;
        break;
      case "ushort":
      case "unsigned short":
      case "unsigned short int":
      case "uint16":
      case "uint16_t":
        this.__array = Uint16Array;
        break;
      case "int":
      case "signed int":
      case "int32":
      case "int32_t":
        this.__array = Int32Array;
        break;
      case "uint":
      case "unsigned int":
      case "uint32":
      case "uint32_t":
        this.__array = Uint32Array;
        break;
      case "float":
        this.__array = Float32Array;
        break;
      case "double":
        this.__array = Float64Array;
        break;
      default:
        throw new Error("Unsupported NRRD data type: " + data2);
    }
    return this.type = data2;
  },
  endian: function(data2) {
    return this.endian = data2;
  },
  encoding: function(data2) {
    return this.encoding = data2;
  },
  dimension: function(data2) {
    return this.dim = parseInt(data2, 10);
  },
  sizes: function(data2) {
    let i;
    return this.sizes = function() {
      const _ref = data2.split(/\s+/);
      const _results = [];
      for (let _i = 0, _len = _ref.length; _i < _len; _i++) {
        i = _ref[_i];
        _results.push(parseInt(i, 10));
      }
      return _results;
    }();
  },
  space: function(data2) {
    return this.space = data2;
  },
  "space origin": function(data2) {
    return this.space_origin = data2.split("(")[1].split(")")[0].split(",");
  },
  "space directions": function(data2) {
    let f, v;
    const parts = data2.match(/\(.*?\)/g);
    return this.vectors = function() {
      const _results = [];
      for (let _i = 0, _len = parts.length; _i < _len; _i++) {
        v = parts[_i];
        _results.push(function() {
          const _ref = v.slice(1, -1).split(/,/);
          const _results2 = [];
          for (let _j = 0, _len2 = _ref.length; _j < _len2; _j++) {
            f = _ref[_j];
            _results2.push(parseFloat(f));
          }
          return _results2;
        }());
      }
      return _results;
    }();
  },
  spacings: function(data2) {
    let f;
    const parts = data2.split(/\s+/);
    return this.spacings = function() {
      const _results = [];
      for (let _i = 0, _len = parts.length; _i < _len; _i++) {
        f = parts[_i];
        _results.push(parseFloat(f));
      }
      return _results;
    }();
  }
};

// node_modules/three/examples/jsm/loaders/OBJLoader.js
var _object_pattern = /^[og]\s*(.+)?/;
var _material_library_pattern = /^mtllib /;
var _material_use_pattern = /^usemtl /;
var _map_use_pattern = /^usemap /;
var _face_vertex_data_separator_pattern = /\s+/;
var _vA = new Vector3();
var _vB = new Vector3();
var _vC = new Vector3();
var _ab = new Vector3();
var _cb = new Vector3();
var _color = new Color();
function ParserState() {
  const state = {
    objects: [],
    object: {},
    vertices: [],
    normals: [],
    colors: [],
    uvs: [],
    materials: {},
    materialLibraries: [],
    startObject: function(name2, fromDeclaration) {
      if (this.object && this.object.fromDeclaration === false) {
        this.object.name = name2;
        this.object.fromDeclaration = fromDeclaration !== false;
        return;
      }
      const previousMaterial = this.object && typeof this.object.currentMaterial === "function" ? this.object.currentMaterial() : void 0;
      if (this.object && typeof this.object._finalize === "function") {
        this.object._finalize(true);
      }
      this.object = {
        name: name2 || "",
        fromDeclaration: fromDeclaration !== false,
        geometry: {
          vertices: [],
          normals: [],
          colors: [],
          uvs: [],
          hasUVIndices: false
        },
        materials: [],
        smooth: true,
        startMaterial: function(name3, libraries) {
          const previous = this._finalize(false);
          if (previous && (previous.inherited || previous.groupCount <= 0)) {
            this.materials.splice(previous.index, 1);
          }
          const material = {
            index: this.materials.length,
            name: name3 || "",
            mtllib: Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : "",
            smooth: previous !== void 0 ? previous.smooth : this.smooth,
            groupStart: previous !== void 0 ? previous.groupEnd : 0,
            groupEnd: -1,
            groupCount: -1,
            inherited: false,
            clone: function(index2) {
              const cloned = {
                index: typeof index2 === "number" ? index2 : this.index,
                name: this.name,
                mtllib: this.mtllib,
                smooth: this.smooth,
                groupStart: 0,
                groupEnd: -1,
                groupCount: -1,
                inherited: false
              };
              cloned.clone = this.clone.bind(cloned);
              return cloned;
            }
          };
          this.materials.push(material);
          return material;
        },
        currentMaterial: function() {
          if (this.materials.length > 0) {
            return this.materials[this.materials.length - 1];
          }
          return void 0;
        },
        _finalize: function(end) {
          const lastMultiMaterial = this.currentMaterial();
          if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) {
            lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
            lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
            lastMultiMaterial.inherited = false;
          }
          if (end && this.materials.length > 1) {
            for (let mi2 = this.materials.length - 1; mi2 >= 0; mi2--) {
              if (this.materials[mi2].groupCount <= 0) {
                this.materials.splice(mi2, 1);
              }
            }
          }
          if (end && this.materials.length === 0) {
            this.materials.push({
              name: "",
              smooth: this.smooth
            });
          }
          return lastMultiMaterial;
        }
      };
      if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === "function") {
        const declared = previousMaterial.clone(0);
        declared.inherited = true;
        this.object.materials.push(declared);
      }
      this.objects.push(this.object);
    },
    finalize: function() {
      if (this.object && typeof this.object._finalize === "function") {
        this.object._finalize(true);
      }
    },
    parseVertexIndex: function(value2, len) {
      const index2 = parseInt(value2, 10);
      return (index2 >= 0 ? index2 - 1 : index2 + len / 3) * 3;
    },
    parseNormalIndex: function(value2, len) {
      const index2 = parseInt(value2, 10);
      return (index2 >= 0 ? index2 - 1 : index2 + len / 3) * 3;
    },
    parseUVIndex: function(value2, len) {
      const index2 = parseInt(value2, 10);
      return (index2 >= 0 ? index2 - 1 : index2 + len / 2) * 2;
    },
    addVertex: function(a2, b3, c2) {
      const src = this.vertices;
      const dst = this.object.geometry.vertices;
      dst.push(src[a2 + 0], src[a2 + 1], src[a2 + 2]);
      dst.push(src[b3 + 0], src[b3 + 1], src[b3 + 2]);
      dst.push(src[c2 + 0], src[c2 + 1], src[c2 + 2]);
    },
    addVertexPoint: function(a2) {
      const src = this.vertices;
      const dst = this.object.geometry.vertices;
      dst.push(src[a2 + 0], src[a2 + 1], src[a2 + 2]);
    },
    addVertexLine: function(a2) {
      const src = this.vertices;
      const dst = this.object.geometry.vertices;
      dst.push(src[a2 + 0], src[a2 + 1], src[a2 + 2]);
    },
    addNormal: function(a2, b3, c2) {
      const src = this.normals;
      const dst = this.object.geometry.normals;
      dst.push(src[a2 + 0], src[a2 + 1], src[a2 + 2]);
      dst.push(src[b3 + 0], src[b3 + 1], src[b3 + 2]);
      dst.push(src[c2 + 0], src[c2 + 1], src[c2 + 2]);
    },
    addFaceNormal: function(a2, b3, c2) {
      const src = this.vertices;
      const dst = this.object.geometry.normals;
      _vA.fromArray(src, a2);
      _vB.fromArray(src, b3);
      _vC.fromArray(src, c2);
      _cb.subVectors(_vC, _vB);
      _ab.subVectors(_vA, _vB);
      _cb.cross(_ab);
      _cb.normalize();
      dst.push(_cb.x, _cb.y, _cb.z);
      dst.push(_cb.x, _cb.y, _cb.z);
      dst.push(_cb.x, _cb.y, _cb.z);
    },
    addColor: function(a2, b3, c2) {
      const src = this.colors;
      const dst = this.object.geometry.colors;
      if (src[a2] !== void 0) dst.push(src[a2 + 0], src[a2 + 1], src[a2 + 2]);
      if (src[b3] !== void 0) dst.push(src[b3 + 0], src[b3 + 1], src[b3 + 2]);
      if (src[c2] !== void 0) dst.push(src[c2 + 0], src[c2 + 1], src[c2 + 2]);
    },
    addUV: function(a2, b3, c2) {
      const src = this.uvs;
      const dst = this.object.geometry.uvs;
      dst.push(src[a2 + 0], src[a2 + 1]);
      dst.push(src[b3 + 0], src[b3 + 1]);
      dst.push(src[c2 + 0], src[c2 + 1]);
    },
    addDefaultUV: function() {
      const dst = this.object.geometry.uvs;
      dst.push(0, 0);
      dst.push(0, 0);
      dst.push(0, 0);
    },
    addUVLine: function(a2) {
      const src = this.uvs;
      const dst = this.object.geometry.uvs;
      dst.push(src[a2 + 0], src[a2 + 1]);
    },
    addFace: function(a2, b3, c2, ua, ub, uc, na, nb, nc) {
      const vLen = this.vertices.length;
      let ia2 = this.parseVertexIndex(a2, vLen);
      let ib = this.parseVertexIndex(b3, vLen);
      let ic = this.parseVertexIndex(c2, vLen);
      this.addVertex(ia2, ib, ic);
      this.addColor(ia2, ib, ic);
      if (na !== void 0 && na !== "") {
        const nLen = this.normals.length;
        ia2 = this.parseNormalIndex(na, nLen);
        ib = this.parseNormalIndex(nb, nLen);
        ic = this.parseNormalIndex(nc, nLen);
        this.addNormal(ia2, ib, ic);
      } else {
        this.addFaceNormal(ia2, ib, ic);
      }
      if (ua !== void 0 && ua !== "") {
        const uvLen = this.uvs.length;
        ia2 = this.parseUVIndex(ua, uvLen);
        ib = this.parseUVIndex(ub, uvLen);
        ic = this.parseUVIndex(uc, uvLen);
        this.addUV(ia2, ib, ic);
        this.object.geometry.hasUVIndices = true;
      } else {
        this.addDefaultUV();
      }
    },
    addPointGeometry: function(vertices) {
      this.object.geometry.type = "Points";
      const vLen = this.vertices.length;
      for (let vi = 0, l2 = vertices.length; vi < l2; vi++) {
        const index2 = this.parseVertexIndex(vertices[vi], vLen);
        this.addVertexPoint(index2);
        this.addColor(index2);
      }
    },
    addLineGeometry: function(vertices, uvs) {
      this.object.geometry.type = "Line";
      const vLen = this.vertices.length;
      const uvLen = this.uvs.length;
      for (let vi = 0, l2 = vertices.length; vi < l2; vi++) {
        this.addVertexLine(this.parseVertexIndex(vertices[vi], vLen));
      }
      for (let uvi = 0, l2 = uvs.length; uvi < l2; uvi++) {
        this.addUVLine(this.parseUVIndex(uvs[uvi], uvLen));
      }
    }
  };
  state.startObject("", false);
  return state;
}
var OBJLoader = class extends Loader {
  /**
   * Constructs a new OBJ loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.materials = null;
  }
  /**
   * Starts loading from the given URL and passes the loaded OBJ asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Group)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Sets the material creator for this OBJ. This object is loaded via {@link MTLLoader}.
   *
   * @param {MaterialCreator} materials - An object that creates the materials for this OBJ.
   * @return {OBJLoader} A reference to this loader.
   */
  setMaterials(materials) {
    this.materials = materials;
    return this;
  }
  /**
   * Parses the given OBJ data and returns the resulting group.
   *
   * @param {string} text - The raw OBJ data as a string.
   * @return {Group} The parsed OBJ.
   */
  parse(text2) {
    const state = new ParserState();
    if (text2.indexOf("\r\n") !== -1) {
      text2 = text2.replace(/\r\n/g, "\n");
    }
    if (text2.indexOf("\\\n") !== -1) {
      text2 = text2.replace(/\\\n/g, "");
    }
    const lines = text2.split("\n");
    let result = [];
    for (let i = 0, l2 = lines.length; i < l2; i++) {
      const line2 = lines[i].trimStart();
      if (line2.length === 0) continue;
      const lineFirstChar = line2.charAt(0);
      if (lineFirstChar === "#") continue;
      if (lineFirstChar === "v") {
        const data2 = line2.split(_face_vertex_data_separator_pattern);
        switch (data2[0]) {
          case "v":
            state.vertices.push(
              parseFloat(data2[1]),
              parseFloat(data2[2]),
              parseFloat(data2[3])
            );
            if (data2.length >= 7) {
              _color.setRGB(
                parseFloat(data2[4]),
                parseFloat(data2[5]),
                parseFloat(data2[6]),
                SRGBColorSpace
              );
              state.colors.push(_color.r, _color.g, _color.b);
            } else {
              state.colors.push(void 0, void 0, void 0);
            }
            break;
          case "vn":
            state.normals.push(
              parseFloat(data2[1]),
              parseFloat(data2[2]),
              parseFloat(data2[3])
            );
            break;
          case "vt":
            state.uvs.push(
              parseFloat(data2[1]),
              parseFloat(data2[2])
            );
            break;
        }
      } else if (lineFirstChar === "f") {
        const lineData = line2.slice(1).trim();
        const vertexData = lineData.split(_face_vertex_data_separator_pattern);
        const faceVertices = [];
        for (let j2 = 0, jl = vertexData.length; j2 < jl; j2++) {
          const vertex = vertexData[j2];
          if (vertex.length > 0) {
            const vertexParts = vertex.split("/");
            faceVertices.push(vertexParts);
          }
        }
        const v12 = faceVertices[0];
        for (let j2 = 1, jl = faceVertices.length - 1; j2 < jl; j2++) {
          const v2 = faceVertices[j2];
          const v3 = faceVertices[j2 + 1];
          state.addFace(
            v12[0],
            v2[0],
            v3[0],
            v12[1],
            v2[1],
            v3[1],
            v12[2],
            v2[2],
            v3[2]
          );
        }
      } else if (lineFirstChar === "l") {
        const lineParts = line2.substring(1).trim().split(" ");
        let lineVertices = [];
        const lineUVs = [];
        if (line2.indexOf("/") === -1) {
          lineVertices = lineParts;
        } else {
          for (let li = 0, llen = lineParts.length; li < llen; li++) {
            const parts = lineParts[li].split("/");
            if (parts[0] !== "") lineVertices.push(parts[0]);
            if (parts[1] !== "") lineUVs.push(parts[1]);
          }
        }
        state.addLineGeometry(lineVertices, lineUVs);
      } else if (lineFirstChar === "p") {
        const lineData = line2.slice(1).trim();
        const pointData = lineData.split(" ");
        state.addPointGeometry(pointData);
      } else if ((result = _object_pattern.exec(line2)) !== null) {
        const name2 = (" " + result[0].slice(1).trim()).slice(1);
        state.startObject(name2);
      } else if (_material_use_pattern.test(line2)) {
        state.object.startMaterial(line2.substring(7).trim(), state.materialLibraries);
      } else if (_material_library_pattern.test(line2)) {
        state.materialLibraries.push(line2.substring(7).trim());
      } else if (_map_use_pattern.test(line2)) {
        console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');
      } else if (lineFirstChar === "s") {
        result = line2.split(" ");
        if (result.length > 1) {
          const value2 = result[1].trim().toLowerCase();
          state.object.smooth = value2 !== "0" && value2 !== "off";
        } else {
          state.object.smooth = true;
        }
        const material = state.object.currentMaterial();
        if (material) material.smooth = state.object.smooth;
      } else {
        if (line2 === "\0") continue;
        console.warn('THREE.OBJLoader: Unexpected line: "' + line2 + '"');
      }
    }
    state.finalize();
    const container = new Group();
    container.materialLibraries = [].concat(state.materialLibraries);
    const hasPrimitives = !(state.objects.length === 1 && state.objects[0].geometry.vertices.length === 0);
    if (hasPrimitives === true) {
      for (let i = 0, l2 = state.objects.length; i < l2; i++) {
        const object = state.objects[i];
        const geometry = object.geometry;
        const materials = object.materials;
        const isLine = geometry.type === "Line";
        const isPoints = geometry.type === "Points";
        let hasVertexColors = false;
        if (geometry.vertices.length === 0) continue;
        const buffergeometry = new BufferGeometry();
        buffergeometry.setAttribute("position", new Float32BufferAttribute(geometry.vertices, 3));
        if (geometry.normals.length > 0) {
          buffergeometry.setAttribute("normal", new Float32BufferAttribute(geometry.normals, 3));
        }
        if (geometry.colors.length > 0) {
          hasVertexColors = true;
          buffergeometry.setAttribute("color", new Float32BufferAttribute(geometry.colors, 3));
        }
        if (geometry.hasUVIndices === true) {
          buffergeometry.setAttribute("uv", new Float32BufferAttribute(geometry.uvs, 2));
        }
        const createdMaterials = [];
        for (let mi2 = 0, miLen = materials.length; mi2 < miLen; mi2++) {
          const sourceMaterial = materials[mi2];
          const materialHash = sourceMaterial.name + "_" + sourceMaterial.smooth + "_" + hasVertexColors;
          let material = state.materials[materialHash];
          if (this.materials !== null) {
            material = this.materials.create(sourceMaterial.name);
            if (isLine && material && !(material instanceof LineBasicMaterial)) {
              const materialLine = new LineBasicMaterial();
              Material.prototype.copy.call(materialLine, material);
              materialLine.color.copy(material.color);
              material = materialLine;
            } else if (isPoints && material && !(material instanceof PointsMaterial)) {
              const materialPoints = new PointsMaterial({ size: 10, sizeAttenuation: false });
              Material.prototype.copy.call(materialPoints, material);
              materialPoints.color.copy(material.color);
              materialPoints.map = material.map;
              material = materialPoints;
            }
          }
          if (material === void 0) {
            if (isLine) {
              material = new LineBasicMaterial();
            } else if (isPoints) {
              material = new PointsMaterial({ size: 1, sizeAttenuation: false });
            } else {
              material = new MeshPhongMaterial();
            }
            material.name = sourceMaterial.name;
            material.flatShading = sourceMaterial.smooth ? false : true;
            material.vertexColors = hasVertexColors;
            state.materials[materialHash] = material;
          }
          createdMaterials.push(material);
        }
        let mesh;
        if (createdMaterials.length > 1) {
          for (let mi2 = 0, miLen = materials.length; mi2 < miLen; mi2++) {
            const sourceMaterial = materials[mi2];
            buffergeometry.addGroup(sourceMaterial.groupStart, sourceMaterial.groupCount, mi2);
          }
          if (isLine) {
            mesh = new LineSegments(buffergeometry, createdMaterials);
          } else if (isPoints) {
            mesh = new Points(buffergeometry, createdMaterials);
          } else {
            mesh = new Mesh(buffergeometry, createdMaterials);
          }
        } else {
          if (isLine) {
            mesh = new LineSegments(buffergeometry, createdMaterials[0]);
          } else if (isPoints) {
            mesh = new Points(buffergeometry, createdMaterials[0]);
          } else {
            mesh = new Mesh(buffergeometry, createdMaterials[0]);
          }
        }
        mesh.name = object.name;
        container.add(mesh);
      }
    } else {
      if (state.vertices.length > 0) {
        const material = new PointsMaterial({ size: 1, sizeAttenuation: false });
        const buffergeometry = new BufferGeometry();
        buffergeometry.setAttribute("position", new Float32BufferAttribute(state.vertices, 3));
        if (state.colors.length > 0 && state.colors[0] !== void 0) {
          buffergeometry.setAttribute("color", new Float32BufferAttribute(state.colors, 3));
          material.vertexColors = true;
        }
        const points = new Points(buffergeometry, material);
        container.add(points);
      }
    }
    return container;
  }
};

// node_modules/three/examples/jsm/loaders/PCDLoader.js
var PCDLoader = class extends Loader {
  /**
   * Constructs a new PCD loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.littleEndian = true;
  }
  /**
   * Starts loading from the given URL and passes the loaded PCD asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Points)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(data2) {
      try {
        onLoad(scope.parse(data2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Get dataview value by field type and size.
   *
   * @param {DataView} dataview - The DataView to read from.
   * @param {number} offset - The offset to start reading from.
   * @param {'F' | 'U' | 'I'} type - Field type.
   * @param {number} size - Field size.
   * @returns {number} Field value.
   */
  _getDataView(dataview, offset, type, size2) {
    switch (type) {
      case "F": {
        if (size2 === 8) {
          return dataview.getFloat64(offset, this.littleEndian);
        }
        return dataview.getFloat32(offset, this.littleEndian);
      }
      case "I": {
        if (size2 === 1) {
          return dataview.getInt8(offset);
        }
        if (size2 === 2) {
          return dataview.getInt16(offset, this.littleEndian);
        }
        return dataview.getInt32(offset, this.littleEndian);
      }
      case "U": {
        if (size2 === 1) {
          return dataview.getUint8(offset);
        }
        if (size2 === 2) {
          return dataview.getUint16(offset, this.littleEndian);
        }
        return dataview.getUint32(offset, this.littleEndian);
      }
    }
  }
  /**
   * Parses the given PCD data and returns a point cloud.
   *
   * @param {ArrayBuffer} data - The raw PCD data as an array buffer.
   * @return {Points} The parsed point cloud.
   */
  parse(data2) {
    function decompressLZF(inData, outLength) {
      const inLength = inData.length;
      const outData = new Uint8Array(outLength);
      let inPtr = 0;
      let outPtr = 0;
      let ctrl;
      let len;
      let ref;
      do {
        ctrl = inData[inPtr++];
        if (ctrl < 1 << 5) {
          ctrl++;
          if (outPtr + ctrl > outLength) throw new Error("Output buffer is not large enough");
          if (inPtr + ctrl > inLength) throw new Error("Invalid compressed data");
          do {
            outData[outPtr++] = inData[inPtr++];
          } while (--ctrl);
        } else {
          len = ctrl >> 5;
          ref = outPtr - ((ctrl & 31) << 8) - 1;
          if (inPtr >= inLength) throw new Error("Invalid compressed data");
          if (len === 7) {
            len += inData[inPtr++];
            if (inPtr >= inLength) throw new Error("Invalid compressed data");
          }
          ref -= inData[inPtr++];
          if (outPtr + len + 2 > outLength) throw new Error("Output buffer is not large enough");
          if (ref < 0) throw new Error("Invalid compressed data");
          if (ref >= outPtr) throw new Error("Invalid compressed data");
          do {
            outData[outPtr++] = outData[ref++];
          } while (--len + 2);
        }
      } while (inPtr < inLength);
      return outData;
    }
    function parseHeader(binaryData) {
      const PCDheader2 = {};
      const buffer = new Uint8Array(binaryData);
      let data3 = "", line2 = "", i = 0, end = false;
      const max2 = buffer.length;
      while (i < max2 && end === false) {
        const char = String.fromCharCode(buffer[i++]);
        if (char === "\n" || char === "\r") {
          if (line2.trim().toLowerCase().startsWith("data")) {
            end = true;
          }
          line2 = "";
        } else {
          line2 += char;
        }
        data3 += char;
      }
      const result1 = data3.search(/[\r\n]DATA\s(\S*)\s/i);
      const result2 = /[\r\n]DATA\s(\S*)\s/i.exec(data3.slice(result1 - 1));
      PCDheader2.data = result2[1];
      PCDheader2.headerLen = result2[0].length + result1;
      PCDheader2.str = data3.slice(0, PCDheader2.headerLen);
      PCDheader2.str = PCDheader2.str.replace(/#.*/gi, "");
      PCDheader2.version = /^VERSION (.*)/im.exec(PCDheader2.str);
      PCDheader2.fields = /^FIELDS (.*)/im.exec(PCDheader2.str);
      PCDheader2.size = /^SIZE (.*)/im.exec(PCDheader2.str);
      PCDheader2.type = /^TYPE (.*)/im.exec(PCDheader2.str);
      PCDheader2.count = /^COUNT (.*)/im.exec(PCDheader2.str);
      PCDheader2.width = /^WIDTH (.*)/im.exec(PCDheader2.str);
      PCDheader2.height = /^HEIGHT (.*)/im.exec(PCDheader2.str);
      PCDheader2.viewpoint = /^VIEWPOINT (.*)/im.exec(PCDheader2.str);
      PCDheader2.points = /^POINTS (.*)/im.exec(PCDheader2.str);
      if (PCDheader2.version !== null)
        PCDheader2.version = parseFloat(PCDheader2.version[1]);
      PCDheader2.fields = PCDheader2.fields !== null ? PCDheader2.fields[1].split(" ") : [];
      if (PCDheader2.type !== null)
        PCDheader2.type = PCDheader2.type[1].split(" ");
      if (PCDheader2.width !== null)
        PCDheader2.width = parseInt(PCDheader2.width[1]);
      if (PCDheader2.height !== null)
        PCDheader2.height = parseInt(PCDheader2.height[1]);
      if (PCDheader2.viewpoint !== null)
        PCDheader2.viewpoint = PCDheader2.viewpoint[1];
      if (PCDheader2.points !== null)
        PCDheader2.points = parseInt(PCDheader2.points[1], 10);
      if (PCDheader2.points === null)
        PCDheader2.points = PCDheader2.width * PCDheader2.height;
      if (PCDheader2.size !== null) {
        PCDheader2.size = PCDheader2.size[1].split(" ").map(function(x2) {
          return parseInt(x2, 10);
        });
      }
      if (PCDheader2.count !== null) {
        PCDheader2.count = PCDheader2.count[1].split(" ").map(function(x2) {
          return parseInt(x2, 10);
        });
      } else {
        PCDheader2.count = [];
        for (let i2 = 0, l2 = PCDheader2.fields.length; i2 < l2; i2++) {
          PCDheader2.count.push(1);
        }
      }
      PCDheader2.offset = {};
      let sizeSum = 0;
      for (let i2 = 0, l2 = PCDheader2.fields.length; i2 < l2; i2++) {
        if (PCDheader2.data === "ascii") {
          PCDheader2.offset[PCDheader2.fields[i2]] = i2;
        } else {
          PCDheader2.offset[PCDheader2.fields[i2]] = sizeSum;
          sizeSum += PCDheader2.size[i2] * PCDheader2.count[i2];
        }
      }
      PCDheader2.rowSize = sizeSum;
      return PCDheader2;
    }
    const PCDheader = parseHeader(data2);
    const position2 = [];
    const normal = [];
    const color = [];
    const intensity = [];
    const label = [];
    const c2 = new Color();
    if (PCDheader.data === "ascii") {
      const offset = PCDheader.offset;
      const textData = new TextDecoder().decode(data2);
      const pcdData = textData.slice(PCDheader.headerLen);
      const lines = pcdData.split("\n");
      for (let i = 0, l2 = lines.length; i < l2; i++) {
        if (lines[i] === "") continue;
        const line2 = lines[i].split(" ");
        if (offset.x !== void 0) {
          position2.push(parseFloat(line2[offset.x]));
          position2.push(parseFloat(line2[offset.y]));
          position2.push(parseFloat(line2[offset.z]));
        }
        if (offset.rgb !== void 0) {
          const rgb_field_index = PCDheader.fields.findIndex((field) => field === "rgb");
          const rgb_type = PCDheader.type[rgb_field_index];
          const float = parseFloat(line2[offset.rgb]);
          let rgb = float;
          if (rgb_type === "F") {
            const farr = new Float32Array(1);
            farr[0] = float;
            rgb = new Int32Array(farr.buffer)[0];
          }
          const r = (rgb >> 16 & 255) / 255;
          const g3 = (rgb >> 8 & 255) / 255;
          const b3 = (rgb >> 0 & 255) / 255;
          c2.setRGB(r, g3, b3, SRGBColorSpace);
          color.push(c2.r, c2.g, c2.b);
        }
        if (offset.normal_x !== void 0) {
          normal.push(parseFloat(line2[offset.normal_x]));
          normal.push(parseFloat(line2[offset.normal_y]));
          normal.push(parseFloat(line2[offset.normal_z]));
        }
        if (offset.intensity !== void 0) {
          intensity.push(parseFloat(line2[offset.intensity]));
        }
        if (offset.label !== void 0) {
          label.push(parseInt(line2[offset.label]));
        }
      }
    }
    if (PCDheader.data === "binary_compressed") {
      const sizes = new Uint32Array(data2.slice(PCDheader.headerLen, PCDheader.headerLen + 8));
      const compressedSize = sizes[0];
      const decompressedSize = sizes[1];
      const decompressed = decompressLZF(new Uint8Array(data2, PCDheader.headerLen + 8, compressedSize), decompressedSize);
      const dataview = new DataView(decompressed.buffer);
      const offset = PCDheader.offset;
      for (let i = 0; i < PCDheader.points; i++) {
        if (offset.x !== void 0) {
          const xIndex = PCDheader.fields.indexOf("x");
          const yIndex = PCDheader.fields.indexOf("y");
          const zIndex = PCDheader.fields.indexOf("z");
          position2.push(this._getDataView(dataview, PCDheader.points * offset.x + PCDheader.size[xIndex] * i, PCDheader.type[xIndex], PCDheader.size[xIndex]));
          position2.push(this._getDataView(dataview, PCDheader.points * offset.y + PCDheader.size[yIndex] * i, PCDheader.type[yIndex], PCDheader.size[yIndex]));
          position2.push(this._getDataView(dataview, PCDheader.points * offset.z + PCDheader.size[zIndex] * i, PCDheader.type[zIndex], PCDheader.size[zIndex]));
        }
        if (offset.rgb !== void 0) {
          const rgbIndex = PCDheader.fields.indexOf("rgb");
          const r = dataview.getUint8(PCDheader.points * offset.rgb + PCDheader.size[rgbIndex] * i + 2) / 255;
          const g3 = dataview.getUint8(PCDheader.points * offset.rgb + PCDheader.size[rgbIndex] * i + 1) / 255;
          const b3 = dataview.getUint8(PCDheader.points * offset.rgb + PCDheader.size[rgbIndex] * i + 0) / 255;
          c2.setRGB(r, g3, b3, SRGBColorSpace);
          color.push(c2.r, c2.g, c2.b);
        }
        if (offset.normal_x !== void 0) {
          const xIndex = PCDheader.fields.indexOf("normal_x");
          const yIndex = PCDheader.fields.indexOf("normal_y");
          const zIndex = PCDheader.fields.indexOf("normal_z");
          normal.push(this._getDataView(dataview, PCDheader.points * offset.normal_x + PCDheader.size[xIndex] * i, PCDheader.type[xIndex], PCDheader.size[xIndex]));
          normal.push(this._getDataView(dataview, PCDheader.points * offset.normal_y + PCDheader.size[yIndex] * i, PCDheader.type[yIndex], PCDheader.size[yIndex]));
          normal.push(this._getDataView(dataview, PCDheader.points * offset.normal_z + PCDheader.size[zIndex] * i, PCDheader.type[zIndex], PCDheader.size[zIndex]));
        }
        if (offset.intensity !== void 0) {
          const intensityIndex = PCDheader.fields.indexOf("intensity");
          intensity.push(this._getDataView(dataview, PCDheader.points * offset.intensity + PCDheader.size[intensityIndex] * i, PCDheader.type[intensityIndex], PCDheader.size[intensityIndex]));
        }
        if (offset.label !== void 0) {
          const labelIndex = PCDheader.fields.indexOf("label");
          label.push(dataview.getInt32(PCDheader.points * offset.label + PCDheader.size[labelIndex] * i, this.littleEndian));
        }
      }
    }
    if (PCDheader.data === "binary") {
      const dataview = new DataView(data2, PCDheader.headerLen);
      const offset = PCDheader.offset;
      for (let i = 0, row = 0; i < PCDheader.points; i++, row += PCDheader.rowSize) {
        if (offset.x !== void 0) {
          const xIndex = PCDheader.fields.indexOf("x");
          const yIndex = PCDheader.fields.indexOf("y");
          const zIndex = PCDheader.fields.indexOf("z");
          position2.push(this._getDataView(dataview, row + offset.x, PCDheader.type[xIndex], PCDheader.size[xIndex]));
          position2.push(this._getDataView(dataview, row + offset.y, PCDheader.type[yIndex], PCDheader.size[yIndex]));
          position2.push(this._getDataView(dataview, row + offset.z, PCDheader.type[zIndex], PCDheader.size[zIndex]));
        }
        if (offset.rgb !== void 0) {
          const r = dataview.getUint8(row + offset.rgb + 2) / 255;
          const g3 = dataview.getUint8(row + offset.rgb + 1) / 255;
          const b3 = dataview.getUint8(row + offset.rgb + 0) / 255;
          c2.setRGB(r, g3, b3, SRGBColorSpace);
          color.push(c2.r, c2.g, c2.b);
        }
        if (offset.normal_x !== void 0) {
          const xIndex = PCDheader.fields.indexOf("normal_x");
          const yIndex = PCDheader.fields.indexOf("normal_y");
          const zIndex = PCDheader.fields.indexOf("normal_z");
          normal.push(this._getDataView(dataview, row + offset.normal_x, PCDheader.type[xIndex], PCDheader.size[xIndex]));
          normal.push(this._getDataView(dataview, row + offset.normal_y, PCDheader.type[yIndex], PCDheader.size[yIndex]));
          normal.push(this._getDataView(dataview, row + offset.normal_z, PCDheader.type[zIndex], PCDheader.size[zIndex]));
        }
        if (offset.intensity !== void 0) {
          const intensityIndex = PCDheader.fields.indexOf("intensity");
          intensity.push(this._getDataView(dataview, row + offset.intensity, PCDheader.type[intensityIndex], PCDheader.size[intensityIndex]));
        }
        if (offset.label !== void 0) {
          label.push(dataview.getInt32(row + offset.label, this.littleEndian));
        }
      }
    }
    const geometry = new BufferGeometry();
    if (position2.length > 0) geometry.setAttribute("position", new Float32BufferAttribute(position2, 3));
    if (normal.length > 0) geometry.setAttribute("normal", new Float32BufferAttribute(normal, 3));
    if (color.length > 0) geometry.setAttribute("color", new Float32BufferAttribute(color, 3));
    if (intensity.length > 0) geometry.setAttribute("intensity", new Float32BufferAttribute(intensity, 1));
    if (label.length > 0) geometry.setAttribute("label", new Int32BufferAttribute(label, 1));
    geometry.computeBoundingSphere();
    const material = new PointsMaterial({ size: 5e-3 });
    if (color.length > 0) {
      material.vertexColors = true;
    }
    return new Points(geometry, material);
  }
};

// node_modules/three/examples/jsm/loaders/PDBLoader.js
var PDBLoader = class extends Loader {
  /**
   * Constructs a new PDB loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded PDB asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Object)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given PDB data and returns an object holding the atoms and
   * bond geometries as well as the raw atom data as JSON.
   *
   * @param {string} text - The raw PDB data as a string.
   * @return {Object} The result object.
   */
  parse(text2) {
    function trim(text3) {
      return text3.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
    }
    function capitalize(text3) {
      return text3.charAt(0).toUpperCase() + text3.slice(1).toLowerCase();
    }
    function hash(s, e) {
      return "s" + Math.min(s, e) + "e" + Math.max(s, e);
    }
    function parseBond(start, length2, satom, i) {
      const eatom = parseInt(lines[i].slice(start, start + length2));
      if (eatom) {
        const h = hash(satom, eatom);
        if (_bhash[h] === void 0) {
          _bonds.push([satom - 1, eatom - 1, 1]);
          _bhash[h] = _bonds.length - 1;
        } else {
        }
      }
    }
    function buildGeometry() {
      const build = {
        geometryAtoms: new BufferGeometry(),
        geometryBonds: new BufferGeometry(),
        json: {
          atoms
        }
      };
      const geometryAtoms = build.geometryAtoms;
      const geometryBonds = build.geometryBonds;
      const verticesAtoms = [];
      const colorsAtoms = [];
      const verticesBonds = [];
      const c2 = new Color();
      for (let i = 0, l2 = atoms.length; i < l2; i++) {
        const atom = atoms[i];
        const x2 = atom[0];
        const y = atom[1];
        const z = atom[2];
        verticesAtoms.push(x2, y, z);
        const r = atom[3][0] / 255;
        const g3 = atom[3][1] / 255;
        const b3 = atom[3][2] / 255;
        c2.setRGB(r, g3, b3, SRGBColorSpace);
        colorsAtoms.push(c2.r, c2.g, c2.b);
      }
      for (let i = 0, l2 = _bonds.length; i < l2; i++) {
        const bond = _bonds[i];
        const start = bond[0];
        const end = bond[1];
        const startAtom = _atomMap[start];
        const endAtom = _atomMap[end];
        let x2 = startAtom[0];
        let y = startAtom[1];
        let z = startAtom[2];
        verticesBonds.push(x2, y, z);
        x2 = endAtom[0];
        y = endAtom[1];
        z = endAtom[2];
        verticesBonds.push(x2, y, z);
      }
      geometryAtoms.setAttribute("position", new Float32BufferAttribute(verticesAtoms, 3));
      geometryAtoms.setAttribute("color", new Float32BufferAttribute(colorsAtoms, 3));
      geometryBonds.setAttribute("position", new Float32BufferAttribute(verticesBonds, 3));
      return build;
    }
    const CPK = { h: [255, 255, 255], he: [217, 255, 255], li: [204, 128, 255], be: [194, 255, 0], b: [255, 181, 181], c: [144, 144, 144], n: [48, 80, 248], o: [255, 13, 13], f: [144, 224, 80], ne: [179, 227, 245], na: [171, 92, 242], mg: [138, 255, 0], al: [191, 166, 166], si: [240, 200, 160], p: [255, 128, 0], s: [255, 255, 48], cl: [31, 240, 31], ar: [128, 209, 227], k: [143, 64, 212], ca: [61, 255, 0], sc: [230, 230, 230], ti: [191, 194, 199], v: [166, 166, 171], cr: [138, 153, 199], mn: [156, 122, 199], fe: [224, 102, 51], co: [240, 144, 160], ni: [80, 208, 80], cu: [200, 128, 51], zn: [125, 128, 176], ga: [194, 143, 143], ge: [102, 143, 143], as: [189, 128, 227], se: [255, 161, 0], br: [166, 41, 41], kr: [92, 184, 209], rb: [112, 46, 176], sr: [0, 255, 0], y: [148, 255, 255], zr: [148, 224, 224], nb: [115, 194, 201], mo: [84, 181, 181], tc: [59, 158, 158], ru: [36, 143, 143], rh: [10, 125, 140], pd: [0, 105, 133], ag: [192, 192, 192], cd: [255, 217, 143], in: [166, 117, 115], sn: [102, 128, 128], sb: [158, 99, 181], te: [212, 122, 0], i: [148, 0, 148], xe: [66, 158, 176], cs: [87, 23, 143], ba: [0, 201, 0], la: [112, 212, 255], ce: [255, 255, 199], pr: [217, 255, 199], nd: [199, 255, 199], pm: [163, 255, 199], sm: [143, 255, 199], eu: [97, 255, 199], gd: [69, 255, 199], tb: [48, 255, 199], dy: [31, 255, 199], ho: [0, 255, 156], er: [0, 230, 117], tm: [0, 212, 82], yb: [0, 191, 56], lu: [0, 171, 36], hf: [77, 194, 255], ta: [77, 166, 255], w: [33, 148, 214], re: [38, 125, 171], os: [38, 102, 150], ir: [23, 84, 135], pt: [208, 208, 224], au: [255, 209, 35], hg: [184, 184, 208], tl: [166, 84, 77], pb: [87, 89, 97], bi: [158, 79, 181], po: [171, 92, 0], at: [117, 79, 69], rn: [66, 130, 150], fr: [66, 0, 102], ra: [0, 125, 0], ac: [112, 171, 250], th: [0, 186, 255], pa: [0, 161, 255], u: [0, 143, 255], np: [0, 128, 255], pu: [0, 107, 255], am: [84, 92, 242], cm: [120, 92, 227], bk: [138, 79, 227], cf: [161, 54, 212], es: [179, 31, 212], fm: [179, 31, 186], md: [179, 13, 166], no: [189, 13, 135], lr: [199, 0, 102], rf: [204, 0, 89], db: [209, 0, 79], sg: [217, 0, 69], bh: [224, 0, 56], hs: [230, 0, 46], mt: [235, 0, 38], ds: [235, 0, 38], rg: [235, 0, 38], cn: [235, 0, 38], uut: [235, 0, 38], uuq: [235, 0, 38], uup: [235, 0, 38], uuh: [235, 0, 38], uus: [235, 0, 38], uuo: [235, 0, 38] };
    const atoms = [];
    const _bonds = [];
    const _bhash = {};
    const _atomMap = {};
    const lines = text2.split("\n");
    for (let i = 0, l2 = lines.length; i < l2; i++) {
      if (lines[i].slice(0, 4) === "ATOM" || lines[i].slice(0, 6) === "HETATM") {
        const x2 = parseFloat(lines[i].slice(30, 37));
        const y = parseFloat(lines[i].slice(38, 45));
        const z = parseFloat(lines[i].slice(46, 53));
        const index2 = parseInt(lines[i].slice(6, 11)) - 1;
        let e = trim(lines[i].slice(76, 78)).toLowerCase();
        if (e === "") {
          e = trim(lines[i].slice(12, 14)).toLowerCase();
        }
        const atomData = [x2, y, z, CPK[e], capitalize(e)];
        atoms.push(atomData);
        _atomMap[index2] = atomData;
      } else if (lines[i].slice(0, 6) === "CONECT") {
        const satom = parseInt(lines[i].slice(6, 11));
        parseBond(11, 5, satom, i);
        parseBond(16, 5, satom, i);
        parseBond(21, 5, satom, i);
        parseBond(26, 5, satom, i);
      }
    }
    return buildGeometry();
  }
};

// node_modules/three/examples/jsm/loaders/PLYLoader.js
var _color2 = new Color();
var PLYLoader = class extends Loader {
  /**
   * Constructs a new PLY loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.propertyNameMapping = {};
    this.customPropertyMapping = {};
  }
  /**
   * Starts loading from the given URL and passes the loaded PLY asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Sets a property name mapping that maps default property names
   * to custom ones. For example, the following maps the properties
   * “diffuse_(red|green|blue)” in the file to standard color names.
   *
   * ```js
   * loader.setPropertyNameMapping( {
   * 	diffuse_red: 'red',
   * 	diffuse_green: 'green',
   * 	diffuse_blue: 'blue'
   * } );
   * ```
   *
   * @param {Object} mapping - The mapping dictionary.
   */
  setPropertyNameMapping(mapping) {
    this.propertyNameMapping = mapping;
  }
  /**
   * Custom properties outside of the defaults for position, uv, normal
   * and color attributes can be added using the setCustomPropertyNameMapping method.
   * For example, the following maps the element properties “custom_property_a”
   * and “custom_property_b” to an attribute “customAttribute” with an item size of 2.
   * Attribute item sizes are set from the number of element properties in the property array.
   *
   * ```js
   * loader.setCustomPropertyNameMapping( {
   *	customAttribute: ['custom_property_a', 'custom_property_b'],
   * } );
   * ```
   * @param {Object} mapping - The mapping dictionary.
   */
  setCustomPropertyNameMapping(mapping) {
    this.customPropertyMapping = mapping;
  }
  /**
   * Parses the given PLY data and returns the resulting geometry.
   *
   * @param {ArrayBuffer} data - The raw PLY data as an array buffer.
   * @return {BufferGeometry} The parsed geometry.
   */
  parse(data2) {
    function parseHeader(data3, headerLength = 0) {
      const patternHeader = /^ply([\s\S]*)end_header(\r\n|\r|\n)/;
      let headerText = "";
      const result = patternHeader.exec(data3);
      if (result !== null) {
        headerText = result[1];
      }
      const header = {
        comments: [],
        elements: [],
        headerLength,
        objInfo: ""
      };
      const lines = headerText.split(/\r\n|\r|\n/);
      let currentElement;
      function make_ply_element_property(propertyValues, propertyNameMapping) {
        const property2 = { type: propertyValues[0] };
        if (property2.type === "list") {
          property2.name = propertyValues[3];
          property2.countType = propertyValues[1];
          property2.itemType = propertyValues[2];
        } else {
          property2.name = propertyValues[1];
        }
        if (property2.name in propertyNameMapping) {
          property2.name = propertyNameMapping[property2.name];
        }
        return property2;
      }
      for (let i = 0; i < lines.length; i++) {
        let line2 = lines[i];
        line2 = line2.trim();
        if (line2 === "") continue;
        const lineValues = line2.split(/\s+/);
        const lineType = lineValues.shift();
        line2 = lineValues.join(" ");
        switch (lineType) {
          case "format":
            header.format = lineValues[0];
            header.version = lineValues[1];
            break;
          case "comment":
            header.comments.push(line2);
            break;
          case "element":
            if (currentElement !== void 0) {
              header.elements.push(currentElement);
            }
            currentElement = {};
            currentElement.name = lineValues[0];
            currentElement.count = parseInt(lineValues[1]);
            currentElement.properties = [];
            break;
          case "property":
            currentElement.properties.push(make_ply_element_property(lineValues, scope.propertyNameMapping));
            break;
          case "obj_info":
            header.objInfo = line2;
            break;
          default:
            console.log("unhandled", lineType, lineValues);
        }
      }
      if (currentElement !== void 0) {
        header.elements.push(currentElement);
      }
      return header;
    }
    function parseASCIINumber(n2, type) {
      switch (type) {
        case "char":
        case "uchar":
        case "short":
        case "ushort":
        case "int":
        case "uint":
        case "int8":
        case "uint8":
        case "int16":
        case "uint16":
        case "int32":
        case "uint32":
          return parseInt(n2);
        case "float":
        case "double":
        case "float32":
        case "float64":
          return parseFloat(n2);
      }
    }
    function parseASCIIElement(properties, tokens) {
      const element = {};
      for (let i = 0; i < properties.length; i++) {
        if (tokens.empty()) return null;
        if (properties[i].type === "list") {
          const list = [];
          const n2 = parseASCIINumber(tokens.next(), properties[i].countType);
          for (let j2 = 0; j2 < n2; j2++) {
            if (tokens.empty()) return null;
            list.push(parseASCIINumber(tokens.next(), properties[i].itemType));
          }
          element[properties[i].name] = list;
        } else {
          element[properties[i].name] = parseASCIINumber(tokens.next(), properties[i].type);
        }
      }
      return element;
    }
    function createBuffer() {
      const buffer = {
        indices: [],
        vertices: [],
        normals: [],
        uvs: [],
        faceVertexUvs: [],
        colors: [],
        faceVertexColors: []
      };
      for (const customProperty of Object.keys(scope.customPropertyMapping)) {
        buffer[customProperty] = [];
      }
      return buffer;
    }
    function mapElementAttributes(properties) {
      const elementNames = properties.map((property2) => {
        return property2.name;
      });
      function findAttrName(names) {
        for (let i = 0, l2 = names.length; i < l2; i++) {
          const name2 = names[i];
          if (elementNames.includes(name2)) return name2;
        }
        return null;
      }
      return {
        attrX: findAttrName(["x", "px", "posx"]) || "x",
        attrY: findAttrName(["y", "py", "posy"]) || "y",
        attrZ: findAttrName(["z", "pz", "posz"]) || "z",
        attrNX: findAttrName(["nx", "normalx"]),
        attrNY: findAttrName(["ny", "normaly"]),
        attrNZ: findAttrName(["nz", "normalz"]),
        attrS: findAttrName(["s", "u", "texture_u", "tx"]),
        attrT: findAttrName(["t", "v", "texture_v", "ty"]),
        attrR: findAttrName(["red", "diffuse_red", "r", "diffuse_r"]),
        attrG: findAttrName(["green", "diffuse_green", "g", "diffuse_g"]),
        attrB: findAttrName(["blue", "diffuse_blue", "b", "diffuse_b"])
      };
    }
    function parseASCII(data3, header) {
      const buffer = createBuffer();
      const patternBody = /end_header\s+(\S[\s\S]*\S|\S)\s*$/;
      let body, matches;
      if ((matches = patternBody.exec(data3)) !== null) {
        body = matches[1].split(/\s+/);
      } else {
        body = [];
      }
      const tokens = new ArrayStream(body);
      loop: for (let i = 0; i < header.elements.length; i++) {
        const elementDesc = header.elements[i];
        const attributeMap = mapElementAttributes(elementDesc.properties);
        for (let j2 = 0; j2 < elementDesc.count; j2++) {
          const element = parseASCIIElement(elementDesc.properties, tokens);
          if (!element) break loop;
          handleElement(buffer, elementDesc.name, element, attributeMap);
        }
      }
      return postProcess(buffer);
    }
    function postProcess(buffer) {
      let geometry2 = new BufferGeometry();
      if (buffer.indices.length > 0) {
        geometry2.setIndex(buffer.indices);
      }
      geometry2.setAttribute("position", new Float32BufferAttribute(buffer.vertices, 3));
      if (buffer.normals.length > 0) {
        geometry2.setAttribute("normal", new Float32BufferAttribute(buffer.normals, 3));
      }
      if (buffer.uvs.length > 0) {
        geometry2.setAttribute("uv", new Float32BufferAttribute(buffer.uvs, 2));
      }
      if (buffer.colors.length > 0) {
        geometry2.setAttribute("color", new Float32BufferAttribute(buffer.colors, 3));
      }
      if (buffer.faceVertexUvs.length > 0 || buffer.faceVertexColors.length > 0) {
        geometry2 = geometry2.toNonIndexed();
        if (buffer.faceVertexUvs.length > 0) geometry2.setAttribute("uv", new Float32BufferAttribute(buffer.faceVertexUvs, 2));
        if (buffer.faceVertexColors.length > 0) geometry2.setAttribute("color", new Float32BufferAttribute(buffer.faceVertexColors, 3));
      }
      for (const customProperty of Object.keys(scope.customPropertyMapping)) {
        if (buffer[customProperty].length > 0) {
          geometry2.setAttribute(
            customProperty,
            new Float32BufferAttribute(
              buffer[customProperty],
              scope.customPropertyMapping[customProperty].length
            )
          );
        }
      }
      geometry2.computeBoundingSphere();
      return geometry2;
    }
    function handleElement(buffer, elementName, element, cacheEntry) {
      if (elementName === "vertex") {
        buffer.vertices.push(element[cacheEntry.attrX], element[cacheEntry.attrY], element[cacheEntry.attrZ]);
        if (cacheEntry.attrNX !== null && cacheEntry.attrNY !== null && cacheEntry.attrNZ !== null) {
          buffer.normals.push(element[cacheEntry.attrNX], element[cacheEntry.attrNY], element[cacheEntry.attrNZ]);
        }
        if (cacheEntry.attrS !== null && cacheEntry.attrT !== null) {
          buffer.uvs.push(element[cacheEntry.attrS], element[cacheEntry.attrT]);
        }
        if (cacheEntry.attrR !== null && cacheEntry.attrG !== null && cacheEntry.attrB !== null) {
          _color2.setRGB(
            element[cacheEntry.attrR] / 255,
            element[cacheEntry.attrG] / 255,
            element[cacheEntry.attrB] / 255,
            SRGBColorSpace
          );
          buffer.colors.push(_color2.r, _color2.g, _color2.b);
        }
        for (const customProperty of Object.keys(scope.customPropertyMapping)) {
          for (const elementProperty of scope.customPropertyMapping[customProperty]) {
            buffer[customProperty].push(element[elementProperty]);
          }
        }
      } else if (elementName === "face") {
        const vertex_indices = element.vertex_indices || element.vertex_index;
        const texcoord = element.texcoord;
        if (vertex_indices.length === 3) {
          buffer.indices.push(vertex_indices[0], vertex_indices[1], vertex_indices[2]);
          if (texcoord && texcoord.length === 6) {
            buffer.faceVertexUvs.push(texcoord[0], texcoord[1]);
            buffer.faceVertexUvs.push(texcoord[2], texcoord[3]);
            buffer.faceVertexUvs.push(texcoord[4], texcoord[5]);
          }
        } else if (vertex_indices.length === 4) {
          buffer.indices.push(vertex_indices[0], vertex_indices[1], vertex_indices[3]);
          buffer.indices.push(vertex_indices[1], vertex_indices[2], vertex_indices[3]);
        }
        if (cacheEntry.attrR !== null && cacheEntry.attrG !== null && cacheEntry.attrB !== null) {
          _color2.setRGB(
            element[cacheEntry.attrR] / 255,
            element[cacheEntry.attrG] / 255,
            element[cacheEntry.attrB] / 255,
            SRGBColorSpace
          );
          buffer.faceVertexColors.push(_color2.r, _color2.g, _color2.b);
          buffer.faceVertexColors.push(_color2.r, _color2.g, _color2.b);
          buffer.faceVertexColors.push(_color2.r, _color2.g, _color2.b);
        }
      }
    }
    function binaryReadElement(at, properties) {
      const element = {};
      let read = 0;
      for (let i = 0; i < properties.length; i++) {
        const property2 = properties[i];
        const valueReader = property2.valueReader;
        if (property2.type === "list") {
          const list = [];
          const n2 = property2.countReader.read(at + read);
          read += property2.countReader.size;
          for (let j2 = 0; j2 < n2; j2++) {
            list.push(valueReader.read(at + read));
            read += valueReader.size;
          }
          element[property2.name] = list;
        } else {
          element[property2.name] = valueReader.read(at + read);
          read += valueReader.size;
        }
      }
      return [element, read];
    }
    function setPropertyBinaryReaders(properties, body, little_endian) {
      function getBinaryReader(dataview, type, little_endian2) {
        switch (type) {
          // correspondences for non-specific length types here match rply:
          case "int8":
          case "char":
            return { read: (at) => {
              return dataview.getInt8(at);
            }, size: 1 };
          case "uint8":
          case "uchar":
            return { read: (at) => {
              return dataview.getUint8(at);
            }, size: 1 };
          case "int16":
          case "short":
            return { read: (at) => {
              return dataview.getInt16(at, little_endian2);
            }, size: 2 };
          case "uint16":
          case "ushort":
            return { read: (at) => {
              return dataview.getUint16(at, little_endian2);
            }, size: 2 };
          case "int32":
          case "int":
            return { read: (at) => {
              return dataview.getInt32(at, little_endian2);
            }, size: 4 };
          case "uint32":
          case "uint":
            return { read: (at) => {
              return dataview.getUint32(at, little_endian2);
            }, size: 4 };
          case "float32":
          case "float":
            return { read: (at) => {
              return dataview.getFloat32(at, little_endian2);
            }, size: 4 };
          case "float64":
          case "double":
            return { read: (at) => {
              return dataview.getFloat64(at, little_endian2);
            }, size: 8 };
        }
      }
      for (let i = 0, l2 = properties.length; i < l2; i++) {
        const property2 = properties[i];
        if (property2.type === "list") {
          property2.countReader = getBinaryReader(body, property2.countType, little_endian);
          property2.valueReader = getBinaryReader(body, property2.itemType, little_endian);
        } else {
          property2.valueReader = getBinaryReader(body, property2.type, little_endian);
        }
      }
    }
    function parseBinary(data3, header) {
      const buffer = createBuffer();
      const little_endian = header.format === "binary_little_endian";
      const body = new DataView(data3, header.headerLength);
      let result, loc = 0;
      for (let currentElement = 0; currentElement < header.elements.length; currentElement++) {
        const elementDesc = header.elements[currentElement];
        const properties = elementDesc.properties;
        const attributeMap = mapElementAttributes(properties);
        setPropertyBinaryReaders(properties, body, little_endian);
        for (let currentElementCount = 0; currentElementCount < elementDesc.count; currentElementCount++) {
          result = binaryReadElement(loc, properties);
          loc += result[1];
          const element = result[0];
          handleElement(buffer, elementDesc.name, element, attributeMap);
        }
      }
      return postProcess(buffer);
    }
    function extractHeaderText(bytes) {
      let i = 0;
      let cont = true;
      let line2 = "";
      const lines = [];
      const startLine = new TextDecoder().decode(bytes.subarray(0, 5));
      const hasCRNL = /^ply\r\n/.test(startLine);
      do {
        const c2 = String.fromCharCode(bytes[i++]);
        if (c2 !== "\n" && c2 !== "\r") {
          line2 += c2;
        } else {
          if (line2 === "end_header") cont = false;
          if (line2 !== "") {
            lines.push(line2);
            line2 = "";
          }
        }
      } while (cont && i < bytes.length);
      if (hasCRNL === true) i++;
      return { headerText: lines.join("\r") + "\r", headerLength: i };
    }
    let geometry;
    const scope = this;
    if (data2 instanceof ArrayBuffer) {
      const bytes = new Uint8Array(data2);
      const { headerText, headerLength } = extractHeaderText(bytes);
      const header = parseHeader(headerText, headerLength);
      if (header.format === "ascii") {
        const text2 = new TextDecoder().decode(bytes);
        geometry = parseASCII(text2, header);
      } else {
        geometry = parseBinary(data2, header);
      }
    } else {
      geometry = parseASCII(data2, parseHeader(data2));
    }
    return geometry;
  }
};
var ArrayStream = class {
  constructor(arr) {
    this.arr = arr;
    this.i = 0;
  }
  empty() {
    return this.i >= this.arr.length;
  }
  next() {
    return this.arr[this.i++];
  }
};

// node_modules/three/examples/jsm/loaders/PVRLoader.js
var PVRLoader = class extends CompressedTextureLoader {
  /**
   * Constructs a new PVR loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Parses the given PVRTC texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @param {boolean} loadMipmaps - Whether to load mipmaps or not. This option is not yet supported by the loader.
   * @return {CompressedTextureLoader~TexData} An object representing the parsed texture data.
   */
  parse(buffer, loadMipmaps) {
    const headerLengthInt = 13;
    const header = new Uint32Array(buffer, 0, headerLengthInt);
    const pvrDatas = {
      buffer,
      header,
      loadMipmaps
    };
    if (header[0] === 55727696) {
      return _parseV3(pvrDatas);
    } else if (header[11] === 559044176) {
      return _parseV2(pvrDatas);
    } else {
      console.error("THREE.PVRLoader: Unknown PVR format.");
    }
  }
};
function _parseV3(pvrDatas) {
  const header = pvrDatas.header;
  let bpp, format;
  const metaLen = header[12], pixelFormat = header[2], height2 = header[6], width2 = header[7], numFaces = header[10], numMipmaps = header[11];
  switch (pixelFormat) {
    case 0:
      bpp = 2;
      format = RGB_PVRTC_2BPPV1_Format;
      break;
    case 1:
      bpp = 2;
      format = RGBA_PVRTC_2BPPV1_Format;
      break;
    case 2:
      bpp = 4;
      format = RGB_PVRTC_4BPPV1_Format;
      break;
    case 3:
      bpp = 4;
      format = RGBA_PVRTC_4BPPV1_Format;
      break;
    default:
      console.error("THREE.PVRLoader: Unsupported PVR format:", pixelFormat);
  }
  pvrDatas.dataPtr = 52 + metaLen;
  pvrDatas.bpp = bpp;
  pvrDatas.format = format;
  pvrDatas.width = width2;
  pvrDatas.height = height2;
  pvrDatas.numSurfaces = numFaces;
  pvrDatas.numMipmaps = numMipmaps;
  pvrDatas.isCubemap = numFaces === 6;
  return _extract(pvrDatas);
}
function _parseV2(pvrDatas) {
  const header = pvrDatas.header;
  const headerLength = header[0], height2 = header[1], width2 = header[2], numMipmaps = header[3], flags = header[4], bitmaskAlpha = header[10], numSurfs = header[12];
  const TYPE_MASK = 255;
  const PVRTC_2 = 24, PVRTC_4 = 25;
  const formatFlags = flags & TYPE_MASK;
  let bpp, format;
  const _hasAlpha = bitmaskAlpha > 0;
  if (formatFlags === PVRTC_4) {
    format = _hasAlpha ? RGBA_PVRTC_4BPPV1_Format : RGB_PVRTC_4BPPV1_Format;
    bpp = 4;
  } else if (formatFlags === PVRTC_2) {
    format = _hasAlpha ? RGBA_PVRTC_2BPPV1_Format : RGB_PVRTC_2BPPV1_Format;
    bpp = 2;
  } else {
    console.error("THREE.PVRLoader: Unknown PVR format:", formatFlags);
  }
  pvrDatas.dataPtr = headerLength;
  pvrDatas.bpp = bpp;
  pvrDatas.format = format;
  pvrDatas.width = width2;
  pvrDatas.height = height2;
  pvrDatas.numSurfaces = numSurfs;
  pvrDatas.numMipmaps = numMipmaps + 1;
  pvrDatas.isCubemap = numSurfs === 6;
  return _extract(pvrDatas);
}
function _extract(pvrDatas) {
  const pvr = {
    mipmaps: [],
    width: pvrDatas.width,
    height: pvrDatas.height,
    format: pvrDatas.format,
    mipmapCount: pvrDatas.numMipmaps,
    isCubemap: pvrDatas.isCubemap
  };
  const buffer = pvrDatas.buffer;
  let dataOffset = pvrDatas.dataPtr, dataSize = 0, blockSize = 0, blockWidth = 0, blockHeight = 0, widthBlocks = 0, heightBlocks = 0;
  const bpp = pvrDatas.bpp, numSurfs = pvrDatas.numSurfaces;
  if (bpp === 2) {
    blockWidth = 8;
    blockHeight = 4;
  } else {
    blockWidth = 4;
    blockHeight = 4;
  }
  blockSize = blockWidth * blockHeight * bpp / 8;
  pvr.mipmaps.length = pvrDatas.numMipmaps * numSurfs;
  let mipLevel = 0;
  while (mipLevel < pvrDatas.numMipmaps) {
    const sWidth = pvrDatas.width >> mipLevel, sHeight = pvrDatas.height >> mipLevel;
    widthBlocks = sWidth / blockWidth;
    heightBlocks = sHeight / blockHeight;
    if (widthBlocks < 2) widthBlocks = 2;
    if (heightBlocks < 2) heightBlocks = 2;
    dataSize = widthBlocks * heightBlocks * blockSize;
    for (let surfIndex = 0; surfIndex < numSurfs; surfIndex++) {
      const byteArray = new Uint8Array(buffer, dataOffset, dataSize);
      const mipmap = {
        data: byteArray,
        width: sWidth,
        height: sHeight
      };
      pvr.mipmaps[surfIndex * pvrDatas.numMipmaps + mipLevel] = mipmap;
      dataOffset += dataSize;
    }
    mipLevel++;
  }
  return pvr;
}

// node_modules/three/examples/jsm/loaders/UltraHDRLoader.js
var SRGB_TO_LINEAR = Array(1024).fill(0).map(
  (_, value2) => Math.pow(value2 / 255 * 0.9478672986 + 0.0521327014, 2.4)
);
var UltraHDRLoader = class extends Loader {
  /**
   * Constructs a new Ultra HDR loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.type = HalfFloatType;
  }
  /**
   * Sets the texture type.
   *
   * @param {(HalfFloatType|FloatType)} value - The texture type to set.
   * @return {RGBELoader} A reference to this loader.
   */
  setDataType(value2) {
    this.type = value2;
    return this;
  }
  /**
   * Parses the given Ultra HDR texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @param {Function} onLoad - The `onLoad` callback.
   */
  parse(buffer, onLoad) {
    const xmpMetadata = {
      version: null,
      baseRenditionIsHDR: null,
      gainMapMin: null,
      gainMapMax: null,
      gamma: null,
      offsetSDR: null,
      offsetHDR: null,
      hdrCapacityMin: null,
      hdrCapacityMax: null
    };
    const textDecoder = new TextDecoder();
    const data2 = new DataView(buffer);
    let byteOffset = 0;
    const sections = [];
    while (byteOffset < data2.byteLength) {
      const byte = data2.getUint8(byteOffset);
      if (byte === 255) {
        const leadingByte = data2.getUint8(byteOffset + 1);
        if ([
          /* Valid section headers */
          216,
          // SOI
          224,
          // APP0
          225,
          // APP1
          226
          // APP2
        ].includes(leadingByte)) {
          sections.push({
            sectionType: leadingByte,
            section: [byte, leadingByte],
            sectionOffset: byteOffset + 2
          });
          byteOffset += 2;
        } else {
          sections[sections.length - 1].section.push(byte, leadingByte);
          byteOffset += 2;
        }
      } else {
        sections[sections.length - 1].section.push(byte);
        byteOffset++;
      }
    }
    let primaryImage, gainmapImage;
    for (let i = 0; i < sections.length; i++) {
      const { sectionType, section, sectionOffset } = sections[i];
      if (sectionType === 224) {
      } else if (sectionType === 225) {
        this._parseXMPMetadata(
          textDecoder.decode(new Uint8Array(section)),
          xmpMetadata
        );
      } else if (sectionType === 226) {
        const sectionData = new DataView(
          new Uint8Array(section.slice(2)).buffer
        );
        const sectionHeader = sectionData.getUint32(2, false);
        if (sectionHeader === 1297106432) {
          const mpfLittleEndian = sectionData.getUint32(6) === 1229531648;
          const mpfBytesOffset = 60;
          const primaryImageSize = sectionData.getUint32(
            mpfBytesOffset,
            mpfLittleEndian
          );
          const primaryImageOffset = sectionData.getUint32(
            mpfBytesOffset + 4,
            mpfLittleEndian
          );
          const gainmapImageSize = sectionData.getUint32(
            mpfBytesOffset + 16,
            mpfLittleEndian
          );
          const gainmapImageOffset = sectionData.getUint32(mpfBytesOffset + 20, mpfLittleEndian) + sectionOffset + 6;
          primaryImage = new Uint8Array(
            data2.buffer,
            primaryImageOffset,
            primaryImageSize
          );
          gainmapImage = new Uint8Array(
            data2.buffer,
            gainmapImageOffset,
            gainmapImageSize
          );
        }
      }
    }
    if (!xmpMetadata.version) {
      throw new Error("THREE.UltraHDRLoader: Not a valid UltraHDR image");
    }
    if (primaryImage && gainmapImage) {
      this._applyGainmapToSDR(
        xmpMetadata,
        primaryImage,
        gainmapImage,
        (hdrBuffer, width2, height2) => {
          onLoad({
            width: width2,
            height: height2,
            data: hdrBuffer,
            format: RGBAFormat,
            type: this.type
          });
        },
        (error) => {
          throw new Error(error);
        }
      );
    } else {
      throw new Error("THREE.UltraHDRLoader: Could not parse UltraHDR images");
    }
  }
  /**
   * Starts loading from the given URL and passes the loaded Ultra HDR texture
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the files to be loaded. This can also be a data URI.
   * @param {function(DataTexture, Object)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {DataTexture} The Ultra HDR texture.
   */
  load(url, onLoad, onProgress, onError) {
    const texture = new DataTexture(
      this.type === HalfFloatType ? new Uint16Array() : new Float32Array(),
      0,
      0,
      RGBAFormat,
      this.type,
      UVMapping,
      ClampToEdgeWrapping,
      ClampToEdgeWrapping,
      LinearFilter,
      LinearMipMapLinearFilter,
      1,
      LinearSRGBColorSpace
    );
    texture.generateMipmaps = true;
    texture.flipY = true;
    const loader = new FileLoader(this.manager);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(this.requestHeader);
    loader.setPath(this.path);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, (buffer) => {
      try {
        this.parse(
          buffer,
          (texData) => {
            texture.image = {
              data: texData.data,
              width: texData.width,
              height: texData.height
            };
            texture.needsUpdate = true;
            if (onLoad) onLoad(texture, texData);
          }
        );
      } catch (error) {
        if (onError) onError(error);
        console.error(error);
      }
    }, onProgress, onError);
    return texture;
  }
  _parseXMPMetadata(xmpDataString, xmpMetadata) {
    const domParser = new DOMParser();
    const xmpXml = domParser.parseFromString(
      xmpDataString.substring(
        xmpDataString.indexOf("<"),
        xmpDataString.lastIndexOf(">") + 1
      ),
      "text/xml"
    );
    const [hasHDRContainerDescriptor] = xmpXml.getElementsByTagName(
      "Container:Directory"
    );
    if (hasHDRContainerDescriptor) {
    } else {
      const [gainmapNode] = xmpXml.getElementsByTagName("rdf:Description");
      xmpMetadata.version = gainmapNode.getAttribute("hdrgm:Version");
      xmpMetadata.baseRenditionIsHDR = gainmapNode.getAttribute("hdrgm:BaseRenditionIsHDR") === "True";
      xmpMetadata.gainMapMin = parseFloat(
        gainmapNode.getAttribute("hdrgm:GainMapMin") || 0
      );
      xmpMetadata.gainMapMax = parseFloat(
        gainmapNode.getAttribute("hdrgm:GainMapMax") || 1
      );
      xmpMetadata.gamma = parseFloat(
        gainmapNode.getAttribute("hdrgm:Gamma") || 1
      );
      xmpMetadata.offsetSDR = parseFloat(
        gainmapNode.getAttribute("hdrgm:OffsetSDR") / (1 / 64)
      );
      xmpMetadata.offsetHDR = parseFloat(
        gainmapNode.getAttribute("hdrgm:OffsetHDR") / (1 / 64)
      );
      xmpMetadata.hdrCapacityMin = parseFloat(
        gainmapNode.getAttribute("hdrgm:HDRCapacityMin") || 0
      );
      xmpMetadata.hdrCapacityMax = parseFloat(
        gainmapNode.getAttribute("hdrgm:HDRCapacityMax") || 1
      );
    }
  }
  _srgbToLinear(value2) {
    if (value2 / 255 < 0.04045) {
      return value2 / 255 * 0.0773993808;
    }
    if (value2 < 1024) {
      return SRGB_TO_LINEAR[~~value2];
    }
    return Math.pow(value2 / 255 * 0.9478672986 + 0.0521327014, 2.4);
  }
  _applyGainmapToSDR(xmpMetadata, sdrBuffer, gainmapBuffer, onSuccess, onError) {
    const getImageDataFromBuffer = (buffer) => new Promise((resolve, reject2) => {
      const imageLoader = document.createElement("img");
      imageLoader.onload = () => {
        const image = {
          width: imageLoader.naturalWidth,
          height: imageLoader.naturalHeight,
          source: imageLoader
        };
        URL.revokeObjectURL(imageLoader.src);
        resolve(image);
      };
      imageLoader.onerror = () => {
        URL.revokeObjectURL(imageLoader.src);
        reject2();
      };
      imageLoader.src = URL.createObjectURL(
        new Blob([buffer], { type: "image/jpeg" })
      );
    });
    Promise.all([
      getImageDataFromBuffer(sdrBuffer),
      getImageDataFromBuffer(gainmapBuffer)
    ]).then(([sdrImage, gainmapImage]) => {
      const sdrImageAspect = sdrImage.width / sdrImage.height;
      const gainmapImageAspect = gainmapImage.width / gainmapImage.height;
      if (sdrImageAspect !== gainmapImageAspect) {
        onError(
          "THREE.UltraHDRLoader Error: Aspect ratio mismatch between SDR and Gainmap images"
        );
        return;
      }
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d", {
        willReadFrequently: true,
        colorSpace: "srgb"
      });
      canvas.width = sdrImage.width;
      canvas.height = sdrImage.height;
      ctx.drawImage(
        gainmapImage.source,
        0,
        0,
        gainmapImage.width,
        gainmapImage.height,
        0,
        0,
        sdrImage.width,
        sdrImage.height
      );
      const gainmapImageData = ctx.getImageData(
        0,
        0,
        sdrImage.width,
        sdrImage.height,
        { colorSpace: "srgb" }
      );
      ctx.drawImage(sdrImage.source, 0, 0);
      const sdrImageData = ctx.getImageData(
        0,
        0,
        sdrImage.width,
        sdrImage.height,
        { colorSpace: "srgb" }
      );
      let hdrBuffer;
      if (this.type === HalfFloatType) {
        hdrBuffer = new Uint16Array(sdrImageData.data.length).fill(23544);
      } else {
        hdrBuffer = new Float32Array(sdrImageData.data.length).fill(255);
      }
      const maxDisplayBoost = Math.sqrt(
        Math.pow(
          /* 1.8 instead of 2 near-perfectly rectifies approximations introduced by precalculated SRGB_TO_LINEAR values */
          1.8,
          xmpMetadata.hdrCapacityMax
        )
      );
      const unclampedWeightFactor = (Math.log2(maxDisplayBoost) - xmpMetadata.hdrCapacityMin) / (xmpMetadata.hdrCapacityMax - xmpMetadata.hdrCapacityMin);
      const weightFactor = Math.min(
        Math.max(unclampedWeightFactor, 0),
        1
      );
      const useGammaOne = xmpMetadata.gamma === 1;
      for (let pixelIndex = 0; pixelIndex < sdrImageData.data.length; pixelIndex += 4) {
        const x2 = pixelIndex / 4 % sdrImage.width;
        const y = Math.floor(pixelIndex / 4 / sdrImage.width);
        for (let channelIndex = 0; channelIndex < 3; channelIndex++) {
          const sdrValue = sdrImageData.data[pixelIndex + channelIndex];
          const gainmapIndex = (y * sdrImage.width + x2) * 4 + channelIndex;
          const gainmapValue = gainmapImageData.data[gainmapIndex] / 255;
          const logRecovery = useGammaOne ? gainmapValue : Math.pow(gainmapValue, 1 / xmpMetadata.gamma);
          const logBoost = xmpMetadata.gainMapMin * (1 - logRecovery) + xmpMetadata.gainMapMax * logRecovery;
          const hdrValue = (sdrValue + xmpMetadata.offsetSDR) * (logBoost * weightFactor === 0 ? 1 : Math.pow(2, logBoost * weightFactor)) - xmpMetadata.offsetHDR;
          const linearHDRValue = Math.min(
            Math.max(this._srgbToLinear(hdrValue), 0),
            65504
          );
          hdrBuffer[pixelIndex + channelIndex] = this.type === HalfFloatType ? DataUtils.toHalfFloat(linearHDRValue) : linearHDRValue;
        }
      }
      onSuccess(hdrBuffer, sdrImage.width, sdrImage.height);
    }).catch(() => {
      throw new Error(
        "THREE.UltraHDRLoader Error: Could not parse UltraHDR images"
      );
    });
  }
};

// node_modules/three/examples/jsm/loaders/RGBMLoader.js
var RGBMLoader = class extends DataTextureLoader {
  /**
   * Constructs a new RGBM loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.type = HalfFloatType;
    this.maxRange = 7;
  }
  /**
   * Sets the texture type.
   *
   * @param {(HalfFloatType|FloatType)} value - The texture type to set.
   * @return {RGBMLoader} A reference to this loader.
   */
  setDataType(value2) {
    this.type = value2;
    return this;
  }
  /**
   * Sets the maximum range.
   *
   * @param {(7|16)} value - The maximum range to set.
   * @return {RGBMLoader} A reference to this loader.
   */
  setMaxRange(value2) {
    this.maxRange = value2;
    return this;
  }
  /**
   * Starts loading from the given URLs and passes the loaded RGBM cube map
   * to the `onLoad()` callback.
   *
   * @param {Array<string>} urls - The paths/URLs of the files to be loaded. This can also be a data URIs.
   * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   * @return {CubeTexture} The cube texture.
   */
  loadCubemap(urls, onLoad, onProgress, onError) {
    const texture = new CubeTexture();
    for (let i = 0; i < 6; i++) {
      texture.images[i] = void 0;
    }
    let loaded = 0;
    const scope = this;
    function loadTexture(i) {
      scope.load(urls[i], function(image) {
        texture.images[i] = image;
        loaded++;
        if (loaded === 6) {
          texture.needsUpdate = true;
          if (onLoad) onLoad(texture);
        }
      }, void 0, onError);
    }
    for (let i = 0; i < urls.length; ++i) {
      loadTexture(i);
    }
    texture.type = this.type;
    texture.format = RGBAFormat;
    texture.minFilter = LinearFilter;
    texture.generateMipmaps = false;
    return texture;
  }
  /**
   * Async version of {@link RGBMLoader#loadCubemap}.
   *
   * @async
   * @param {Array<string>} urls - The paths/URLs of the files to be loaded. This can also be a data URIs.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @return {Promise<CubeTexture>} A Promise that resolves with the loaded cube map.
   */
  loadCubemapAsync(urls, onProgress) {
    return new Promise((resolve, reject2) => {
      this.loadCubemap(urls, resolve, onProgress, reject2);
    });
  }
  /**
   * Parses the given RGBM texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @return {DataTextureLoader~TexData} An object representing the parsed texture data.
   */
  parse(buffer) {
    const img = UPNG.decode(buffer);
    const rgba = UPNG.toRGBA8(img)[0];
    const data2 = new Uint8Array(rgba);
    const size2 = img.width * img.height * 4;
    const output = this.type === HalfFloatType ? new Uint16Array(size2) : new Float32Array(size2);
    for (let i = 0; i < data2.length; i += 4) {
      const r = data2[i + 0] / 255;
      const g3 = data2[i + 1] / 255;
      const b3 = data2[i + 2] / 255;
      const a2 = data2[i + 3] / 255;
      if (this.type === HalfFloatType) {
        output[i + 0] = DataUtils.toHalfFloat(Math.min(r * a2 * this.maxRange, 65504));
        output[i + 1] = DataUtils.toHalfFloat(Math.min(g3 * a2 * this.maxRange, 65504));
        output[i + 2] = DataUtils.toHalfFloat(Math.min(b3 * a2 * this.maxRange, 65504));
        output[i + 3] = DataUtils.toHalfFloat(1);
      } else {
        output[i + 0] = r * a2 * this.maxRange;
        output[i + 1] = g3 * a2 * this.maxRange;
        output[i + 2] = b3 * a2 * this.maxRange;
        output[i + 3] = 1;
      }
    }
    return {
      width: img.width,
      height: img.height,
      data: output,
      format: RGBAFormat,
      type: this.type,
      flipY: true
    };
  }
};
var UPNG = {};
UPNG.toRGBA8 = function(out) {
  var w = out.width, h = out.height;
  if (out.tabs.acTL == null) return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer];
  var frms = [];
  if (out.frames[0].data == null) out.frames[0].data = out.data;
  var len = w * h * 4, img = new Uint8Array(len), empty = new Uint8Array(len), prev = new Uint8Array(len);
  for (var i = 0; i < out.frames.length; i++) {
    var frm = out.frames[i];
    var fx = frm.rect.x, fy = frm.rect.y, fw = frm.rect.width, fh = frm.rect.height;
    var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw, fh, out);
    if (i != 0) for (var j2 = 0; j2 < len; j2++) prev[j2] = img[j2];
    if (frm.blend == 0) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0);
    else if (frm.blend == 1) UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1);
    frms.push(img.buffer.slice(0));
    if (frm.dispose == 1) UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0);
    else if (frm.dispose == 2) for (var j2 = 0; j2 < len; j2++) img[j2] = prev[j2];
  }
  return frms;
};
UPNG.toRGBA8.decodeImage = function(data2, w, h, out) {
  var area = w * h, bpp = UPNG.decode._getBPP(out);
  var bpl = Math.ceil(w * bpp / 8);
  var bf = new Uint8Array(area * 4), bf32 = new Uint32Array(bf.buffer);
  var ctype = out.ctype, depth = out.depth;
  var rs = UPNG._bin.readUshort;
  if (ctype == 6) {
    var qarea = area << 2;
    if (depth == 8) for (var i = 0; i < qarea; i += 4) {
      bf[i] = data2[i];
      bf[i + 1] = data2[i + 1];
      bf[i + 2] = data2[i + 2];
      bf[i + 3] = data2[i + 3];
    }
    if (depth == 16) for (var i = 0; i < qarea; i++) {
      bf[i] = data2[i << 1];
    }
  } else if (ctype == 2) {
    var ts = out.tabs["tRNS"];
    if (ts == null) {
      if (depth == 8) for (var i = 0; i < area; i++) {
        var ti = i * 3;
        bf32[i] = 255 << 24 | data2[ti + 2] << 16 | data2[ti + 1] << 8 | data2[ti];
      }
      if (depth == 16) for (var i = 0; i < area; i++) {
        var ti = i * 6;
        bf32[i] = 255 << 24 | data2[ti + 4] << 16 | data2[ti + 2] << 8 | data2[ti];
      }
    } else {
      var tr = ts[0], tg = ts[1], tb = ts[2];
      if (depth == 8) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 3;
        bf32[i] = 255 << 24 | data2[ti + 2] << 16 | data2[ti + 1] << 8 | data2[ti];
        if (data2[ti] == tr && data2[ti + 1] == tg && data2[ti + 2] == tb) bf[qi + 3] = 0;
      }
      if (depth == 16) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 6;
        bf32[i] = 255 << 24 | data2[ti + 4] << 16 | data2[ti + 2] << 8 | data2[ti];
        if (rs(data2, ti) == tr && rs(data2, ti + 2) == tg && rs(data2, ti + 4) == tb) bf[qi + 3] = 0;
      }
    }
  } else if (ctype == 3) {
    var p = out.tabs["PLTE"], ap = out.tabs["tRNS"], tl = ap ? ap.length : 0;
    if (depth == 1) for (var y = 0; y < h; y++) {
      var s0 = y * bpl, t0 = y * w;
      for (var i = 0; i < w; i++) {
        var qi = t0 + i << 2, j2 = data2[s0 + (i >> 3)] >> 7 - ((i & 7) << 0) & 1, cj = 3 * j2;
        bf[qi] = p[cj];
        bf[qi + 1] = p[cj + 1];
        bf[qi + 2] = p[cj + 2];
        bf[qi + 3] = j2 < tl ? ap[j2] : 255;
      }
    }
    if (depth == 2) for (var y = 0; y < h; y++) {
      var s0 = y * bpl, t0 = y * w;
      for (var i = 0; i < w; i++) {
        var qi = t0 + i << 2, j2 = data2[s0 + (i >> 2)] >> 6 - ((i & 3) << 1) & 3, cj = 3 * j2;
        bf[qi] = p[cj];
        bf[qi + 1] = p[cj + 1];
        bf[qi + 2] = p[cj + 2];
        bf[qi + 3] = j2 < tl ? ap[j2] : 255;
      }
    }
    if (depth == 4) for (var y = 0; y < h; y++) {
      var s0 = y * bpl, t0 = y * w;
      for (var i = 0; i < w; i++) {
        var qi = t0 + i << 2, j2 = data2[s0 + (i >> 1)] >> 4 - ((i & 1) << 2) & 15, cj = 3 * j2;
        bf[qi] = p[cj];
        bf[qi + 1] = p[cj + 1];
        bf[qi + 2] = p[cj + 2];
        bf[qi + 3] = j2 < tl ? ap[j2] : 255;
      }
    }
    if (depth == 8) for (var i = 0; i < area; i++) {
      var qi = i << 2, j2 = data2[i], cj = 3 * j2;
      bf[qi] = p[cj];
      bf[qi + 1] = p[cj + 1];
      bf[qi + 2] = p[cj + 2];
      bf[qi + 3] = j2 < tl ? ap[j2] : 255;
    }
  } else if (ctype == 4) {
    if (depth == 8) for (var i = 0; i < area; i++) {
      var qi = i << 2, di = i << 1, gr = data2[di];
      bf[qi] = gr;
      bf[qi + 1] = gr;
      bf[qi + 2] = gr;
      bf[qi + 3] = data2[di + 1];
    }
    if (depth == 16) for (var i = 0; i < area; i++) {
      var qi = i << 2, di = i << 2, gr = data2[di];
      bf[qi] = gr;
      bf[qi + 1] = gr;
      bf[qi + 2] = gr;
      bf[qi + 3] = data2[di + 2];
    }
  } else if (ctype == 0) {
    var tr = out.tabs["tRNS"] ? out.tabs["tRNS"] : -1;
    for (var y = 0; y < h; y++) {
      var off = y * bpl, to = y * w;
      if (depth == 1) for (var x2 = 0; x2 < w; x2++) {
        var gr = 255 * (data2[off + (x2 >>> 3)] >>> 7 - (x2 & 7) & 1), al = gr == tr * 255 ? 0 : 255;
        bf32[to + x2] = al << 24 | gr << 16 | gr << 8 | gr;
      }
      else if (depth == 2) for (var x2 = 0; x2 < w; x2++) {
        var gr = 85 * (data2[off + (x2 >>> 2)] >>> 6 - ((x2 & 3) << 1) & 3), al = gr == tr * 85 ? 0 : 255;
        bf32[to + x2] = al << 24 | gr << 16 | gr << 8 | gr;
      }
      else if (depth == 4) for (var x2 = 0; x2 < w; x2++) {
        var gr = 17 * (data2[off + (x2 >>> 1)] >>> 4 - ((x2 & 1) << 2) & 15), al = gr == tr * 17 ? 0 : 255;
        bf32[to + x2] = al << 24 | gr << 16 | gr << 8 | gr;
      }
      else if (depth == 8) for (var x2 = 0; x2 < w; x2++) {
        var gr = data2[off + x2], al = gr == tr ? 0 : 255;
        bf32[to + x2] = al << 24 | gr << 16 | gr << 8 | gr;
      }
      else if (depth == 16) for (var x2 = 0; x2 < w; x2++) {
        var gr = data2[off + (x2 << 1)], al = rs(data2, off + (x2 << 1)) == tr ? 0 : 255;
        bf32[to + x2] = al << 24 | gr << 16 | gr << 8 | gr;
      }
    }
  }
  return bf;
};
UPNG.decode = function(buff) {
  var data2 = new Uint8Array(buff), offset = 8, bin = UPNG._bin, rUs = bin.readUshort, rUi = bin.readUint;
  var out = { tabs: {}, frames: [] };
  var dd = new Uint8Array(data2.length), doff = 0;
  var fd2, foff = 0;
  var text2, keyw, bfr;
  var mgck = [137, 80, 78, 71, 13, 10, 26, 10];
  for (var i = 0; i < 8; i++) if (data2[i] != mgck[i]) throw new Error("The input is not a PNG file!");
  while (offset < data2.length) {
    var len = bin.readUint(data2, offset);
    offset += 4;
    var type = bin.readASCII(data2, offset, 4);
    offset += 4;
    if (type == "IHDR") {
      UPNG.decode._IHDR(data2, offset, out);
    } else if (type == "CgBI") {
      out.tabs[type] = data2.slice(offset, offset + 4);
    } else if (type == "IDAT") {
      for (var i = 0; i < len; i++) dd[doff + i] = data2[offset + i];
      doff += len;
    } else if (type == "acTL") {
      out.tabs[type] = { num_frames: rUi(data2, offset), num_plays: rUi(data2, offset + 4) };
      fd2 = new Uint8Array(data2.length);
    } else if (type == "fcTL") {
      if (foff != 0) {
        var fr = out.frames[out.frames.length - 1];
        fr.data = UPNG.decode._decompress(out, fd2.slice(0, foff), fr.rect.width, fr.rect.height);
        foff = 0;
      }
      var rct = { x: rUi(data2, offset + 12), y: rUi(data2, offset + 16), width: rUi(data2, offset + 4), height: rUi(data2, offset + 8) };
      var del = rUs(data2, offset + 22);
      del = rUs(data2, offset + 20) / (del == 0 ? 100 : del);
      var frm = { rect: rct, delay: Math.round(del * 1e3), dispose: data2[offset + 24], blend: data2[offset + 25] };
      out.frames.push(frm);
    } else if (type == "fdAT") {
      for (var i = 0; i < len - 4; i++) fd2[foff + i] = data2[offset + i + 4];
      foff += len - 4;
    } else if (type == "pHYs") {
      out.tabs[type] = [bin.readUint(data2, offset), bin.readUint(data2, offset + 4), data2[offset + 8]];
    } else if (type == "cHRM") {
      out.tabs[type] = [];
      for (var i = 0; i < 8; i++) out.tabs[type].push(bin.readUint(data2, offset + i * 4));
    } else if (type == "tEXt" || type == "zTXt") {
      if (out.tabs[type] == null) out.tabs[type] = {};
      var nz = bin.nextZero(data2, offset);
      keyw = bin.readASCII(data2, offset, nz - offset);
      var tl = offset + len - nz - 1;
      if (type == "tEXt") text2 = bin.readASCII(data2, nz + 1, tl);
      else {
        bfr = UPNG.decode._inflate(data2.slice(nz + 2, nz + 2 + tl));
        text2 = bin.readUTF8(bfr, 0, bfr.length);
      }
      out.tabs[type][keyw] = text2;
    } else if (type == "iTXt") {
      if (out.tabs[type] == null) out.tabs[type] = {};
      var nz = 0, off = offset;
      nz = bin.nextZero(data2, off);
      keyw = bin.readASCII(data2, off, nz - off);
      off = nz + 1;
      var cflag = data2[off];
      off += 2;
      nz = bin.nextZero(data2, off);
      bin.readASCII(data2, off, nz - off);
      off = nz + 1;
      nz = bin.nextZero(data2, off);
      bin.readUTF8(data2, off, nz - off);
      off = nz + 1;
      var tl = len - (off - offset);
      if (cflag == 0) text2 = bin.readUTF8(data2, off, tl);
      else {
        bfr = UPNG.decode._inflate(data2.slice(off, off + tl));
        text2 = bin.readUTF8(bfr, 0, bfr.length);
      }
      out.tabs[type][keyw] = text2;
    } else if (type == "PLTE") {
      out.tabs[type] = bin.readBytes(data2, offset, len);
    } else if (type == "hIST") {
      var pl = out.tabs["PLTE"].length / 3;
      out.tabs[type] = [];
      for (var i = 0; i < pl; i++) out.tabs[type].push(rUs(data2, offset + i * 2));
    } else if (type == "tRNS") {
      if (out.ctype == 3) out.tabs[type] = bin.readBytes(data2, offset, len);
      else if (out.ctype == 0) out.tabs[type] = rUs(data2, offset);
      else if (out.ctype == 2) out.tabs[type] = [rUs(data2, offset), rUs(data2, offset + 2), rUs(data2, offset + 4)];
    } else if (type == "gAMA") out.tabs[type] = bin.readUint(data2, offset) / 1e5;
    else if (type == "sRGB") out.tabs[type] = data2[offset];
    else if (type == "bKGD") {
      if (out.ctype == 0 || out.ctype == 4) out.tabs[type] = [rUs(data2, offset)];
      else if (out.ctype == 2 || out.ctype == 6) out.tabs[type] = [rUs(data2, offset), rUs(data2, offset + 2), rUs(data2, offset + 4)];
      else if (out.ctype == 3) out.tabs[type] = data2[offset];
    } else if (type == "IEND") {
      break;
    }
    offset += len;
    bin.readUint(data2, offset);
    offset += 4;
  }
  if (foff != 0) {
    var fr = out.frames[out.frames.length - 1];
    fr.data = UPNG.decode._decompress(out, fd2.slice(0, foff), fr.rect.width, fr.rect.height);
  }
  out.data = UPNG.decode._decompress(out, dd, out.width, out.height);
  delete out.compress;
  delete out.interlace;
  delete out.filter;
  return out;
};
UPNG.decode._decompress = function(out, dd, w, h) {
  var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), buff = new Uint8Array((bpl + 1 + out.interlace) * h);
  if (out.tabs["CgBI"]) dd = UPNG.inflateRaw(dd, buff);
  else dd = UPNG.decode._inflate(dd, buff);
  if (out.interlace == 0) dd = UPNG.decode._filterZero(dd, out, 0, w, h);
  else if (out.interlace == 1) dd = UPNG.decode._readInterlace(dd, out);
  return dd;
};
UPNG.decode._inflate = function(data2, buff) {
  var out = UPNG["inflateRaw"](new Uint8Array(data2.buffer, 2, data2.length - 6), buff);
  return out;
};
UPNG.inflateRaw = function() {
  var H = {};
  H.H = {};
  H.H.N = function(N, W) {
    var R4 = Uint8Array, i = 0, m = 0, J = 0, h = 0, Q2 = 0, X = 0, u2 = 0, w = 0, d = 0, v, C3;
    if (N[0] == 3 && N[1] == 0) return W ? W : new R4(0);
    var V = H.H, n2 = V.b, A2 = V.e, l2 = V.R, M = V.n, I2 = V.A, e = V.Z, b3 = V.m, Z2 = W == null;
    if (Z2) W = new R4(N.length >>> 2 << 5);
    while (i == 0) {
      i = n2(N, d, 1);
      m = n2(N, d + 1, 2);
      d += 3;
      if (m == 0) {
        if ((d & 7) != 0) d += 8 - (d & 7);
        var D = (d >>> 3) + 4, q2 = N[D - 4] | N[D - 3] << 8;
        if (Z2) W = H.H.W(W, w + q2);
        W.set(new R4(N.buffer, N.byteOffset + D, q2), w);
        d = D + q2 << 3;
        w += q2;
        continue;
      }
      if (Z2) W = H.H.W(W, w + (1 << 17));
      if (m == 1) {
        v = b3.J;
        C3 = b3.h;
        X = (1 << 9) - 1;
        u2 = (1 << 5) - 1;
      }
      if (m == 2) {
        J = A2(N, d, 5) + 257;
        h = A2(N, d + 5, 5) + 1;
        Q2 = A2(N, d + 10, 4) + 4;
        d += 14;
        var j2 = 1;
        for (var c2 = 0; c2 < 38; c2 += 2) {
          b3.Q[c2] = 0;
          b3.Q[c2 + 1] = 0;
        }
        for (var c2 = 0; c2 < Q2; c2++) {
          var K = A2(N, d + c2 * 3, 3);
          b3.Q[(b3.X[c2] << 1) + 1] = K;
          if (K > j2) j2 = K;
        }
        d += 3 * Q2;
        M(b3.Q, j2);
        I2(b3.Q, j2, b3.u);
        v = b3.w;
        C3 = b3.d;
        d = l2(b3.u, (1 << j2) - 1, J + h, N, d, b3.v);
        var r = V.V(b3.v, 0, J, b3.C);
        X = (1 << r) - 1;
        var S = V.V(b3.v, J, h, b3.D);
        u2 = (1 << S) - 1;
        M(b3.C, r);
        I2(b3.C, r, v);
        M(b3.D, S);
        I2(b3.D, S, C3);
      }
      while (true) {
        var T2 = v[e(N, d) & X];
        d += T2 & 15;
        var p = T2 >>> 4;
        if (p >>> 8 == 0) {
          W[w++] = p;
        } else if (p == 256) {
          break;
        } else {
          var z = w + p - 254;
          if (p > 264) {
            var _ = b3.q[p - 257];
            z = w + (_ >>> 3) + A2(N, d, _ & 7);
            d += _ & 7;
          }
          var $2 = C3[e(N, d) & u2];
          d += $2 & 15;
          var s = $2 >>> 4, Y = b3.c[s], a2 = (Y >>> 4) + n2(N, d, Y & 15);
          d += Y & 15;
          while (w < z) {
            W[w] = W[w++ - a2];
            W[w] = W[w++ - a2];
            W[w] = W[w++ - a2];
            W[w] = W[w++ - a2];
          }
          w = z;
        }
      }
    }
    return W.length == w ? W : W.slice(0, w);
  };
  H.H.W = function(N, W) {
    var R4 = N.length;
    if (W <= R4) return N;
    var V = new Uint8Array(R4 << 1);
    V.set(N, 0);
    return V;
  };
  H.H.R = function(N, W, R4, V, n2, A2) {
    var l2 = H.H.e, M = H.H.Z, I2 = 0;
    while (I2 < R4) {
      var e = N[M(V, n2) & W];
      n2 += e & 15;
      var b3 = e >>> 4;
      if (b3 <= 15) {
        A2[I2] = b3;
        I2++;
      } else {
        var Z2 = 0, m = 0;
        if (b3 == 16) {
          m = 3 + l2(V, n2, 2);
          n2 += 2;
          Z2 = A2[I2 - 1];
        } else if (b3 == 17) {
          m = 3 + l2(V, n2, 3);
          n2 += 3;
        } else if (b3 == 18) {
          m = 11 + l2(V, n2, 7);
          n2 += 7;
        }
        var J = I2 + m;
        while (I2 < J) {
          A2[I2] = Z2;
          I2++;
        }
      }
    }
    return n2;
  };
  H.H.V = function(N, W, R4, V) {
    var n2 = 0, A2 = 0, l2 = V.length >>> 1;
    while (A2 < R4) {
      var M = N[A2 + W];
      V[A2 << 1] = 0;
      V[(A2 << 1) + 1] = M;
      if (M > n2) n2 = M;
      A2++;
    }
    while (A2 < l2) {
      V[A2 << 1] = 0;
      V[(A2 << 1) + 1] = 0;
      A2++;
    }
    return n2;
  };
  H.H.n = function(N, W) {
    var R4 = H.H.m, V = N.length, n2, A2, l2, M, I2, e = R4.j;
    for (var M = 0; M <= W; M++) e[M] = 0;
    for (M = 1; M < V; M += 2) e[N[M]]++;
    var b3 = R4.K;
    n2 = 0;
    e[0] = 0;
    for (A2 = 1; A2 <= W; A2++) {
      n2 = n2 + e[A2 - 1] << 1;
      b3[A2] = n2;
    }
    for (l2 = 0; l2 < V; l2 += 2) {
      I2 = N[l2 + 1];
      if (I2 != 0) {
        N[l2] = b3[I2];
        b3[I2]++;
      }
    }
  };
  H.H.A = function(N, W, R4) {
    var V = N.length, n2 = H.H.m, A2 = n2.r;
    for (var l2 = 0; l2 < V; l2 += 2) if (N[l2 + 1] != 0) {
      var M = l2 >> 1, I2 = N[l2 + 1], e = M << 4 | I2, b3 = W - I2, Z2 = N[l2] << b3, m = Z2 + (1 << b3);
      while (Z2 != m) {
        var J = A2[Z2] >>> 15 - W;
        R4[J] = e;
        Z2++;
      }
    }
  };
  H.H.l = function(N, W) {
    var R4 = H.H.m.r, V = 15 - W;
    for (var n2 = 0; n2 < N.length; n2 += 2) {
      var A2 = N[n2] << W - N[n2 + 1];
      N[n2] = R4[A2] >>> V;
    }
  };
  H.H.M = function(N, W, R4) {
    R4 = R4 << (W & 7);
    var V = W >>> 3;
    N[V] |= R4;
    N[V + 1] |= R4 >>> 8;
  };
  H.H.I = function(N, W, R4) {
    R4 = R4 << (W & 7);
    var V = W >>> 3;
    N[V] |= R4;
    N[V + 1] |= R4 >>> 8;
    N[V + 2] |= R4 >>> 16;
  };
  H.H.e = function(N, W, R4) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R4) - 1;
  };
  H.H.b = function(N, W, R4) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R4) - 1;
  };
  H.H.Z = function(N, W) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7);
  };
  H.H.i = function(N, W) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7);
  };
  H.H.m = function() {
    var N = Uint16Array, W = Uint32Array;
    return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 999, 999, 999], T: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0], q: new N(32), p: [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 65535, 65535], z: [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15e3), k: new N(1 << 16), g: new N(1 << 15) };
  }();
  (function() {
    var N = H.H.m, W = 1 << 15;
    for (var R4 = 0; R4 < W; R4++) {
      var V = R4;
      V = (V & 2863311530) >>> 1 | (V & 1431655765) << 1;
      V = (V & 3435973836) >>> 2 | (V & 858993459) << 2;
      V = (V & 4042322160) >>> 4 | (V & 252645135) << 4;
      V = (V & 4278255360) >>> 8 | (V & 16711935) << 8;
      N.r[R4] = (V >>> 16 | V << 16) >>> 17;
    }
    function n2(A2, l2, M) {
      while (l2-- != 0) A2.push(0, M);
    }
    for (var R4 = 0; R4 < 32; R4++) {
      N.q[R4] = N.S[R4] << 3 | N.T[R4];
      N.c[R4] = N.p[R4] << 4 | N.z[R4];
    }
    n2(N._, 144, 8);
    n2(N._, 255 - 143, 9);
    n2(N._, 279 - 255, 7);
    n2(N._, 287 - 279, 8);
    H.H.n(N._, 9);
    H.H.A(N._, 9, N.J);
    H.H.l(N._, 9);
    n2(N.$, 32, 5);
    H.H.n(N.$, 5);
    H.H.A(N.$, 5, N.h);
    H.H.l(N.$, 5);
    n2(N.Q, 19, 0);
    n2(N.C, 286, 0);
    n2(N.D, 30, 0);
    n2(N.v, 320, 0);
  })();
  return H.H.N;
}();
UPNG.decode._readInterlace = function(data2, out) {
  var w = out.width, h = out.height;
  var bpp = UPNG.decode._getBPP(out), cbpp = bpp >> 3, bpl = Math.ceil(w * bpp / 8);
  var img = new Uint8Array(h * bpl);
  var di = 0;
  var starting_row = [0, 0, 4, 0, 2, 0, 1];
  var starting_col = [0, 4, 0, 2, 0, 1, 0];
  var row_increment = [8, 8, 8, 4, 4, 2, 2];
  var col_increment = [8, 8, 4, 4, 2, 2, 1];
  var pass = 0;
  while (pass < 7) {
    var ri = row_increment[pass], ci = col_increment[pass];
    var sw = 0, sh = 0;
    var cr = starting_row[pass];
    while (cr < h) {
      cr += ri;
      sh++;
    }
    var cc = starting_col[pass];
    while (cc < w) {
      cc += ci;
      sw++;
    }
    var bpll = Math.ceil(sw * bpp / 8);
    UPNG.decode._filterZero(data2, out, di, sw, sh);
    var y = 0, row = starting_row[pass];
    var val2;
    while (row < h) {
      var col = starting_col[pass];
      var cdi = di + y * bpll << 3;
      while (col < w) {
        if (bpp == 1) {
          val2 = data2[cdi >> 3];
          val2 = val2 >> 7 - (cdi & 7) & 1;
          img[row * bpl + (col >> 3)] |= val2 << 7 - ((col & 7) << 0);
        }
        if (bpp == 2) {
          val2 = data2[cdi >> 3];
          val2 = val2 >> 6 - (cdi & 7) & 3;
          img[row * bpl + (col >> 2)] |= val2 << 6 - ((col & 3) << 1);
        }
        if (bpp == 4) {
          val2 = data2[cdi >> 3];
          val2 = val2 >> 4 - (cdi & 7) & 15;
          img[row * bpl + (col >> 1)] |= val2 << 4 - ((col & 1) << 2);
        }
        if (bpp >= 8) {
          var ii = row * bpl + col * cbpp;
          for (var j2 = 0; j2 < cbpp; j2++) img[ii + j2] = data2[(cdi >> 3) + j2];
        }
        cdi += bpp;
        col += ci;
      }
      y++;
      row += ri;
    }
    if (sw * sh != 0) di += sh * (1 + bpll);
    pass = pass + 1;
  }
  return img;
};
UPNG.decode._getBPP = function(out) {
  var noc = [1, null, 3, 1, 2, null, 4][out.ctype];
  return noc * out.depth;
};
UPNG.decode._filterZero = function(data2, out, off, w, h) {
  var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), paeth = UPNG.decode._paeth;
  bpp = Math.ceil(bpp / 8);
  var i, di, type = data2[off], x2 = 0;
  if (type > 1) data2[off] = [0, 0, 1][type - 2];
  if (type == 3) for (x2 = bpp; x2 < bpl; x2++) data2[x2 + 1] = data2[x2 + 1] + (data2[x2 + 1 - bpp] >>> 1) & 255;
  for (var y = 0; y < h; y++) {
    i = off + y * bpl;
    di = i + y + 1;
    type = data2[di - 1];
    x2 = 0;
    if (type == 0) for (; x2 < bpl; x2++) data2[i + x2] = data2[di + x2];
    else if (type == 1) {
      for (; x2 < bpp; x2++) data2[i + x2] = data2[di + x2];
      for (; x2 < bpl; x2++) data2[i + x2] = data2[di + x2] + data2[i + x2 - bpp];
    } else if (type == 2) {
      for (; x2 < bpl; x2++) data2[i + x2] = data2[di + x2] + data2[i + x2 - bpl];
    } else if (type == 3) {
      for (; x2 < bpp; x2++) data2[i + x2] = data2[di + x2] + (data2[i + x2 - bpl] >>> 1);
      for (; x2 < bpl; x2++) data2[i + x2] = data2[di + x2] + (data2[i + x2 - bpl] + data2[i + x2 - bpp] >>> 1);
    } else {
      for (; x2 < bpp; x2++) data2[i + x2] = data2[di + x2] + paeth(0, data2[i + x2 - bpl], 0);
      for (; x2 < bpl; x2++) data2[i + x2] = data2[di + x2] + paeth(data2[i + x2 - bpp], data2[i + x2 - bpl], data2[i + x2 - bpp - bpl]);
    }
  }
  return data2;
};
UPNG.decode._paeth = function(a2, b3, c2) {
  var p = a2 + b3 - c2, pa2 = p - a2, pb = p - b3, pc = p - c2;
  if (pa2 * pa2 <= pb * pb && pa2 * pa2 <= pc * pc) return a2;
  else if (pb * pb <= pc * pc) return b3;
  return c2;
};
UPNG.decode._IHDR = function(data2, offset, out) {
  var bin = UPNG._bin;
  out.width = bin.readUint(data2, offset);
  offset += 4;
  out.height = bin.readUint(data2, offset);
  offset += 4;
  out.depth = data2[offset];
  offset++;
  out.ctype = data2[offset];
  offset++;
  out.compress = data2[offset];
  offset++;
  out.filter = data2[offset];
  offset++;
  out.interlace = data2[offset];
  offset++;
};
UPNG._bin = {
  nextZero: function(data2, p) {
    while (data2[p] != 0) p++;
    return p;
  },
  readUshort: function(buff, p) {
    return buff[p] << 8 | buff[p + 1];
  },
  writeUshort: function(buff, p, n2) {
    buff[p] = n2 >> 8 & 255;
    buff[p + 1] = n2 & 255;
  },
  readUint: function(buff, p) {
    return buff[p] * (256 * 256 * 256) + (buff[p + 1] << 16 | buff[p + 2] << 8 | buff[p + 3]);
  },
  writeUint: function(buff, p, n2) {
    buff[p] = n2 >> 24 & 255;
    buff[p + 1] = n2 >> 16 & 255;
    buff[p + 2] = n2 >> 8 & 255;
    buff[p + 3] = n2 & 255;
  },
  readASCII: function(buff, p, l2) {
    var s = "";
    for (var i = 0; i < l2; i++) s += String.fromCharCode(buff[p + i]);
    return s;
  },
  writeASCII: function(data2, p, s) {
    for (var i = 0; i < s.length; i++) data2[p + i] = s.charCodeAt(i);
  },
  readBytes: function(buff, p, l2) {
    var arr = [];
    for (var i = 0; i < l2; i++) arr.push(buff[p + i]);
    return arr;
  },
  pad: function(n2) {
    return n2.length < 2 ? "0" + n2 : n2;
  },
  readUTF8: function(buff, p, l2) {
    var s = "", ns;
    for (var i = 0; i < l2; i++) s += "%" + UPNG._bin.pad(buff[p + i].toString(16));
    try {
      ns = decodeURIComponent(s);
    } catch (e) {
      return UPNG._bin.readASCII(buff, p, l2);
    }
    return ns;
  }
};
UPNG._copyTile = function(sb, sw, sh, tb, tw, th, xoff, yoff, mode) {
  var w = Math.min(sw, tw), h = Math.min(sh, th);
  var si = 0, ti = 0;
  for (var y = 0; y < h; y++)
    for (var x2 = 0; x2 < w; x2++) {
      if (xoff >= 0 && yoff >= 0) {
        si = y * sw + x2 << 2;
        ti = (yoff + y) * tw + xoff + x2 << 2;
      } else {
        si = (-yoff + y) * sw - xoff + x2 << 2;
        ti = y * tw + x2 << 2;
      }
      if (mode == 0) {
        tb[ti] = sb[si];
        tb[ti + 1] = sb[si + 1];
        tb[ti + 2] = sb[si + 2];
        tb[ti + 3] = sb[si + 3];
      } else if (mode == 1) {
        var fa = sb[si + 3] * (1 / 255), fr = sb[si] * fa, fg = sb[si + 1] * fa, fb = sb[si + 2] * fa;
        var ba = tb[ti + 3] * (1 / 255), br = tb[ti] * ba, bg = tb[ti + 1] * ba, bb = tb[ti + 2] * ba;
        var ifa = 1 - fa, oa2 = fa + ba * ifa, ioa = oa2 == 0 ? 0 : 1 / oa2;
        tb[ti + 3] = 255 * oa2;
        tb[ti + 0] = (fr + br * ifa) * ioa;
        tb[ti + 1] = (fg + bg * ifa) * ioa;
        tb[ti + 2] = (fb + bb * ifa) * ioa;
      } else if (mode == 2) {
        var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2];
        var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2];
        if (fa == ba && fr == br && fg == bg && fb == bb) {
          tb[ti] = 0;
          tb[ti + 1] = 0;
          tb[ti + 2] = 0;
          tb[ti + 3] = 0;
        } else {
          tb[ti] = fr;
          tb[ti + 1] = fg;
          tb[ti + 2] = fb;
          tb[ti + 3] = fa;
        }
      } else if (mode == 3) {
        var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2];
        var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2];
        if (fa == ba && fr == br && fg == bg && fb == bb) continue;
        if (fa < 220 && ba > 20) return false;
      }
    }
  return true;
};

// node_modules/three/examples/jsm/loaders/STLLoader.js
var STLLoader = class extends Loader {
  /**
   * Constructs a new STL loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded STL asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given STL data and returns the resulting geometry.
   *
   * @param {ArrayBuffer} data - The raw STL data as an array buffer.
   * @return {BufferGeometry} The parsed geometry.
   */
  parse(data2) {
    function isBinary(data3) {
      const reader = new DataView(data3);
      const face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8;
      const n_faces = reader.getUint32(80, true);
      const expect = 80 + 32 / 8 + n_faces * face_size;
      if (expect === reader.byteLength) {
        return true;
      }
      const solid = [115, 111, 108, 105, 100];
      for (let off = 0; off < 5; off++) {
        if (matchDataViewAt(solid, reader, off)) return false;
      }
      return true;
    }
    function matchDataViewAt(query, reader, offset) {
      for (let i = 0, il = query.length; i < il; i++) {
        if (query[i] !== reader.getUint8(offset + i)) return false;
      }
      return true;
    }
    function parseBinary(data3) {
      const reader = new DataView(data3);
      const faces = reader.getUint32(80, true);
      let r, g3, b3, hasColors = false, colors;
      let defaultR, defaultG, defaultB, alpha;
      for (let index2 = 0; index2 < 80 - 10; index2++) {
        if (reader.getUint32(index2, false) == 1129270351 && reader.getUint8(index2 + 4) == 82 && reader.getUint8(index2 + 5) == 61) {
          hasColors = true;
          colors = new Float32Array(faces * 3 * 3);
          defaultR = reader.getUint8(index2 + 6) / 255;
          defaultG = reader.getUint8(index2 + 7) / 255;
          defaultB = reader.getUint8(index2 + 8) / 255;
          alpha = reader.getUint8(index2 + 9) / 255;
        }
      }
      const dataOffset = 84;
      const faceLength = 12 * 4 + 2;
      const geometry = new BufferGeometry();
      const vertices = new Float32Array(faces * 3 * 3);
      const normals = new Float32Array(faces * 3 * 3);
      const color = new Color();
      for (let face = 0; face < faces; face++) {
        const start = dataOffset + face * faceLength;
        const normalX = reader.getFloat32(start, true);
        const normalY = reader.getFloat32(start + 4, true);
        const normalZ = reader.getFloat32(start + 8, true);
        if (hasColors) {
          const packedColor = reader.getUint16(start + 48, true);
          if ((packedColor & 32768) === 0) {
            r = (packedColor & 31) / 31;
            g3 = (packedColor >> 5 & 31) / 31;
            b3 = (packedColor >> 10 & 31) / 31;
          } else {
            r = defaultR;
            g3 = defaultG;
            b3 = defaultB;
          }
        }
        for (let i = 1; i <= 3; i++) {
          const vertexstart = start + i * 12;
          const componentIdx = face * 3 * 3 + (i - 1) * 3;
          vertices[componentIdx] = reader.getFloat32(vertexstart, true);
          vertices[componentIdx + 1] = reader.getFloat32(vertexstart + 4, true);
          vertices[componentIdx + 2] = reader.getFloat32(vertexstart + 8, true);
          normals[componentIdx] = normalX;
          normals[componentIdx + 1] = normalY;
          normals[componentIdx + 2] = normalZ;
          if (hasColors) {
            color.setRGB(r, g3, b3, SRGBColorSpace);
            colors[componentIdx] = color.r;
            colors[componentIdx + 1] = color.g;
            colors[componentIdx + 2] = color.b;
          }
        }
      }
      geometry.setAttribute("position", new BufferAttribute(vertices, 3));
      geometry.setAttribute("normal", new BufferAttribute(normals, 3));
      if (hasColors) {
        geometry.setAttribute("color", new BufferAttribute(colors, 3));
        geometry.hasColors = true;
        geometry.alpha = alpha;
      }
      return geometry;
    }
    function parseASCII(data3) {
      const geometry = new BufferGeometry();
      const patternSolid = /solid([\s\S]*?)endsolid/g;
      const patternFace = /facet([\s\S]*?)endfacet/g;
      const patternName = /solid\s(.+)/;
      let faceCounter = 0;
      const patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source;
      const patternVertex = new RegExp("vertex" + patternFloat + patternFloat + patternFloat, "g");
      const patternNormal = new RegExp("normal" + patternFloat + patternFloat + patternFloat, "g");
      const vertices = [];
      const normals = [];
      const groupNames = [];
      const normal = new Vector3();
      let result;
      let groupCount = 0;
      let startVertex = 0;
      let endVertex = 0;
      while ((result = patternSolid.exec(data3)) !== null) {
        startVertex = endVertex;
        const solid = result[0];
        const name2 = (result = patternName.exec(solid)) !== null ? result[1] : "";
        groupNames.push(name2);
        while ((result = patternFace.exec(solid)) !== null) {
          let vertexCountPerFace = 0;
          let normalCountPerFace = 0;
          const text2 = result[0];
          while ((result = patternNormal.exec(text2)) !== null) {
            normal.x = parseFloat(result[1]);
            normal.y = parseFloat(result[2]);
            normal.z = parseFloat(result[3]);
            normalCountPerFace++;
          }
          while ((result = patternVertex.exec(text2)) !== null) {
            vertices.push(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
            normals.push(normal.x, normal.y, normal.z);
            vertexCountPerFace++;
            endVertex++;
          }
          if (normalCountPerFace !== 1) {
            console.error("THREE.STLLoader: Something isn't right with the normal of face number " + faceCounter);
          }
          if (vertexCountPerFace !== 3) {
            console.error("THREE.STLLoader: Something isn't right with the vertices of face number " + faceCounter);
          }
          faceCounter++;
        }
        const start = startVertex;
        const count = endVertex - startVertex;
        geometry.userData.groupNames = groupNames;
        geometry.addGroup(start, count, groupCount);
        groupCount++;
      }
      geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
      geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3));
      return geometry;
    }
    function ensureString(buffer) {
      if (typeof buffer !== "string") {
        return new TextDecoder().decode(buffer);
      }
      return buffer;
    }
    function ensureBinary(buffer) {
      if (typeof buffer === "string") {
        const array_buffer = new Uint8Array(buffer.length);
        for (let i = 0; i < buffer.length; i++) {
          array_buffer[i] = buffer.charCodeAt(i) & 255;
        }
        return array_buffer.buffer || array_buffer;
      } else {
        return buffer;
      }
    }
    const binData = ensureBinary(data2);
    return isBinary(binData) ? parseBinary(binData) : parseASCII(ensureString(data2));
  }
};

// node_modules/three/examples/jsm/loaders/SVGLoader.js
var COLOR_SPACE_SVG = SRGBColorSpace;
var SVGLoader = class _SVGLoader extends Loader {
  /**
   * Constructs a new SVG loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.defaultDPI = 90;
    this.defaultUnit = "px";
  }
  /**
   * Starts loading from the given URL and passes the loaded SVG asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function({paths:Array<ShapePath>,xml:string})} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given SVG data and returns the resulting data.
   *
   * @param {string} text - The raw SVG data as a string.
   * @return {{paths:Array<ShapePath>,xml:string}} An object holding an array of shape paths and the
   * SVG XML document.
   */
  parse(text2) {
    const scope = this;
    function parseNode(node, style) {
      if (node.nodeType !== 1) return;
      const transform2 = getNodeTransform(node);
      let isDefsNode = false;
      let path = null;
      switch (node.nodeName) {
        case "svg":
          style = parseStyle(node, style);
          break;
        case "style":
          parseCSSStylesheet(node);
          break;
        case "g":
          style = parseStyle(node, style);
          break;
        case "path":
          style = parseStyle(node, style);
          if (node.hasAttribute("d")) path = parsePathNode(node);
          break;
        case "rect":
          style = parseStyle(node, style);
          path = parseRectNode(node);
          break;
        case "polygon":
          style = parseStyle(node, style);
          path = parsePolygonNode(node);
          break;
        case "polyline":
          style = parseStyle(node, style);
          path = parsePolylineNode(node);
          break;
        case "circle":
          style = parseStyle(node, style);
          path = parseCircleNode(node);
          break;
        case "ellipse":
          style = parseStyle(node, style);
          path = parseEllipseNode(node);
          break;
        case "line":
          style = parseStyle(node, style);
          path = parseLineNode(node);
          break;
        case "defs":
          isDefsNode = true;
          break;
        case "use":
          style = parseStyle(node, style);
          const href = node.getAttributeNS("http://www.w3.org/1999/xlink", "href") || "";
          const usedNodeId = href.substring(1);
          const usedNode = node.viewportElement.getElementById(usedNodeId);
          if (usedNode) {
            parseNode(usedNode, style);
          } else {
            console.warn("SVGLoader: 'use node' references non-existent node id: " + usedNodeId);
          }
          break;
        default:
      }
      if (path) {
        if (style.fill !== void 0 && style.fill !== "none") {
          path.color.setStyle(style.fill, COLOR_SPACE_SVG);
        }
        transformPath(path, currentTransform);
        paths.push(path);
        path.userData = { node, style };
      }
      const childNodes = node.childNodes;
      for (let i = 0; i < childNodes.length; i++) {
        const node2 = childNodes[i];
        if (isDefsNode && node2.nodeName !== "style" && node2.nodeName !== "defs") {
          continue;
        }
        parseNode(node2, style);
      }
      if (transform2) {
        transformStack.pop();
        if (transformStack.length > 0) {
          currentTransform.copy(transformStack[transformStack.length - 1]);
        } else {
          currentTransform.identity();
        }
      }
    }
    function parsePathNode(node) {
      const path = new ShapePath2();
      const point = new Vector2();
      const control = new Vector2();
      const firstPoint = new Vector2();
      let isFirstPoint = true;
      let doSetFirstPoint = false;
      const d = node.getAttribute("d");
      if (d === "" || d === "none") return null;
      const commands = d.match(/[a-df-z][^a-df-z]*/ig);
      for (let i = 0, l2 = commands.length; i < l2; i++) {
        const command = commands[i];
        const type = command.charAt(0);
        const data3 = command.slice(1).trim();
        if (isFirstPoint === true) {
          doSetFirstPoint = true;
          isFirstPoint = false;
        }
        let numbers;
        switch (type) {
          case "M":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 2) {
              point.x = numbers[j2 + 0];
              point.y = numbers[j2 + 1];
              control.x = point.x;
              control.y = point.y;
              if (j2 === 0) {
                path.moveTo(point.x, point.y);
              } else {
                path.lineTo(point.x, point.y);
              }
              if (j2 === 0) firstPoint.copy(point);
            }
            break;
          case "H":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2++) {
              point.x = numbers[j2];
              control.x = point.x;
              control.y = point.y;
              path.lineTo(point.x, point.y);
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "V":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2++) {
              point.y = numbers[j2];
              control.x = point.x;
              control.y = point.y;
              path.lineTo(point.x, point.y);
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "L":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 2) {
              point.x = numbers[j2 + 0];
              point.y = numbers[j2 + 1];
              control.x = point.x;
              control.y = point.y;
              path.lineTo(point.x, point.y);
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "C":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 6) {
              path.bezierCurveTo(
                numbers[j2 + 0],
                numbers[j2 + 1],
                numbers[j2 + 2],
                numbers[j2 + 3],
                numbers[j2 + 4],
                numbers[j2 + 5]
              );
              control.x = numbers[j2 + 2];
              control.y = numbers[j2 + 3];
              point.x = numbers[j2 + 4];
              point.y = numbers[j2 + 5];
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "S":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 4) {
              path.bezierCurveTo(
                getReflection(point.x, control.x),
                getReflection(point.y, control.y),
                numbers[j2 + 0],
                numbers[j2 + 1],
                numbers[j2 + 2],
                numbers[j2 + 3]
              );
              control.x = numbers[j2 + 0];
              control.y = numbers[j2 + 1];
              point.x = numbers[j2 + 2];
              point.y = numbers[j2 + 3];
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "Q":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 4) {
              path.quadraticCurveTo(
                numbers[j2 + 0],
                numbers[j2 + 1],
                numbers[j2 + 2],
                numbers[j2 + 3]
              );
              control.x = numbers[j2 + 0];
              control.y = numbers[j2 + 1];
              point.x = numbers[j2 + 2];
              point.y = numbers[j2 + 3];
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "T":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 2) {
              const rx = getReflection(point.x, control.x);
              const ry = getReflection(point.y, control.y);
              path.quadraticCurveTo(
                rx,
                ry,
                numbers[j2 + 0],
                numbers[j2 + 1]
              );
              control.x = rx;
              control.y = ry;
              point.x = numbers[j2 + 0];
              point.y = numbers[j2 + 1];
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "A":
            numbers = parseFloats(data3, [3, 4], 7);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 7) {
              if (numbers[j2 + 5] == point.x && numbers[j2 + 6] == point.y) continue;
              const start = point.clone();
              point.x = numbers[j2 + 5];
              point.y = numbers[j2 + 6];
              control.x = point.x;
              control.y = point.y;
              parseArcCommand(
                path,
                numbers[j2],
                numbers[j2 + 1],
                numbers[j2 + 2],
                numbers[j2 + 3],
                numbers[j2 + 4],
                start,
                point
              );
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "m":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 2) {
              point.x += numbers[j2 + 0];
              point.y += numbers[j2 + 1];
              control.x = point.x;
              control.y = point.y;
              if (j2 === 0) {
                path.moveTo(point.x, point.y);
              } else {
                path.lineTo(point.x, point.y);
              }
              if (j2 === 0) firstPoint.copy(point);
            }
            break;
          case "h":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2++) {
              point.x += numbers[j2];
              control.x = point.x;
              control.y = point.y;
              path.lineTo(point.x, point.y);
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "v":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2++) {
              point.y += numbers[j2];
              control.x = point.x;
              control.y = point.y;
              path.lineTo(point.x, point.y);
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "l":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 2) {
              point.x += numbers[j2 + 0];
              point.y += numbers[j2 + 1];
              control.x = point.x;
              control.y = point.y;
              path.lineTo(point.x, point.y);
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "c":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 6) {
              path.bezierCurveTo(
                point.x + numbers[j2 + 0],
                point.y + numbers[j2 + 1],
                point.x + numbers[j2 + 2],
                point.y + numbers[j2 + 3],
                point.x + numbers[j2 + 4],
                point.y + numbers[j2 + 5]
              );
              control.x = point.x + numbers[j2 + 2];
              control.y = point.y + numbers[j2 + 3];
              point.x += numbers[j2 + 4];
              point.y += numbers[j2 + 5];
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "s":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 4) {
              path.bezierCurveTo(
                getReflection(point.x, control.x),
                getReflection(point.y, control.y),
                point.x + numbers[j2 + 0],
                point.y + numbers[j2 + 1],
                point.x + numbers[j2 + 2],
                point.y + numbers[j2 + 3]
              );
              control.x = point.x + numbers[j2 + 0];
              control.y = point.y + numbers[j2 + 1];
              point.x += numbers[j2 + 2];
              point.y += numbers[j2 + 3];
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "q":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 4) {
              path.quadraticCurveTo(
                point.x + numbers[j2 + 0],
                point.y + numbers[j2 + 1],
                point.x + numbers[j2 + 2],
                point.y + numbers[j2 + 3]
              );
              control.x = point.x + numbers[j2 + 0];
              control.y = point.y + numbers[j2 + 1];
              point.x += numbers[j2 + 2];
              point.y += numbers[j2 + 3];
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "t":
            numbers = parseFloats(data3);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 2) {
              const rx = getReflection(point.x, control.x);
              const ry = getReflection(point.y, control.y);
              path.quadraticCurveTo(
                rx,
                ry,
                point.x + numbers[j2 + 0],
                point.y + numbers[j2 + 1]
              );
              control.x = rx;
              control.y = ry;
              point.x = point.x + numbers[j2 + 0];
              point.y = point.y + numbers[j2 + 1];
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "a":
            numbers = parseFloats(data3, [3, 4], 7);
            for (let j2 = 0, jl = numbers.length; j2 < jl; j2 += 7) {
              if (numbers[j2 + 5] == 0 && numbers[j2 + 6] == 0) continue;
              const start = point.clone();
              point.x += numbers[j2 + 5];
              point.y += numbers[j2 + 6];
              control.x = point.x;
              control.y = point.y;
              parseArcCommand(
                path,
                numbers[j2],
                numbers[j2 + 1],
                numbers[j2 + 2],
                numbers[j2 + 3],
                numbers[j2 + 4],
                start,
                point
              );
              if (j2 === 0 && doSetFirstPoint === true) firstPoint.copy(point);
            }
            break;
          case "Z":
          case "z":
            path.currentPath.autoClose = true;
            if (path.currentPath.curves.length > 0) {
              point.copy(firstPoint);
              path.currentPath.currentPoint.copy(point);
              isFirstPoint = true;
            }
            break;
          default:
            console.warn(command);
        }
        doSetFirstPoint = false;
      }
      return path;
    }
    function parseCSSStylesheet(node) {
      if (!node.sheet || !node.sheet.cssRules || !node.sheet.cssRules.length) return;
      for (let i = 0; i < node.sheet.cssRules.length; i++) {
        const stylesheet = node.sheet.cssRules[i];
        if (stylesheet.type !== 1) continue;
        const selectorList = stylesheet.selectorText.split(/,/gm).filter(Boolean).map((i2) => i2.trim());
        for (let j2 = 0; j2 < selectorList.length; j2++) {
          const definitions = Object.fromEntries(
            Object.entries(stylesheet.style).filter(([, v]) => v !== "")
          );
          stylesheets[selectorList[j2]] = Object.assign(
            stylesheets[selectorList[j2]] || {},
            definitions
          );
        }
      }
    }
    function parseArcCommand(path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end) {
      if (rx == 0 || ry == 0) {
        path.lineTo(end.x, end.y);
        return;
      }
      x_axis_rotation = x_axis_rotation * Math.PI / 180;
      rx = Math.abs(rx);
      ry = Math.abs(ry);
      const dx2 = (start.x - end.x) / 2;
      const dy2 = (start.y - end.y) / 2;
      const x1p = Math.cos(x_axis_rotation) * dx2 + Math.sin(x_axis_rotation) * dy2;
      const y1p = -Math.sin(x_axis_rotation) * dx2 + Math.cos(x_axis_rotation) * dy2;
      let rxs = rx * rx;
      let rys = ry * ry;
      const x1ps = x1p * x1p;
      const y1ps = y1p * y1p;
      const cr = x1ps / rxs + y1ps / rys;
      if (cr > 1) {
        const s = Math.sqrt(cr);
        rx = s * rx;
        ry = s * ry;
        rxs = rx * rx;
        rys = ry * ry;
      }
      const dq = rxs * y1ps + rys * x1ps;
      const pq = (rxs * rys - dq) / dq;
      let q2 = Math.sqrt(Math.max(0, pq));
      if (large_arc_flag === sweep_flag) q2 = -q2;
      const cxp = q2 * rx * y1p / ry;
      const cyp = -q2 * ry * x1p / rx;
      const cx = Math.cos(x_axis_rotation) * cxp - Math.sin(x_axis_rotation) * cyp + (start.x + end.x) / 2;
      const cy = Math.sin(x_axis_rotation) * cxp + Math.cos(x_axis_rotation) * cyp + (start.y + end.y) / 2;
      const theta = svgAngle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
      const delta = svgAngle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) % (Math.PI * 2);
      path.currentPath.absellipse(cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation);
    }
    function svgAngle(ux, uy, vx, vy) {
      const dot = ux * vx + uy * vy;
      const len = Math.sqrt(ux * ux + uy * uy) * Math.sqrt(vx * vx + vy * vy);
      let ang = Math.acos(Math.max(-1, Math.min(1, dot / len)));
      if (ux * vy - uy * vx < 0) ang = -ang;
      return ang;
    }
    function parseRectNode(node) {
      const x2 = parseFloatWithUnits(node.getAttribute("x") || 0);
      const y = parseFloatWithUnits(node.getAttribute("y") || 0);
      const rx = parseFloatWithUnits(node.getAttribute("rx") || node.getAttribute("ry") || 0);
      const ry = parseFloatWithUnits(node.getAttribute("ry") || node.getAttribute("rx") || 0);
      const w = parseFloatWithUnits(node.getAttribute("width"));
      const h = parseFloatWithUnits(node.getAttribute("height"));
      const bci = 1 - 0.551915024494;
      const path = new ShapePath2();
      path.moveTo(x2 + rx, y);
      path.lineTo(x2 + w - rx, y);
      if (rx !== 0 || ry !== 0) {
        path.bezierCurveTo(
          x2 + w - rx * bci,
          y,
          x2 + w,
          y + ry * bci,
          x2 + w,
          y + ry
        );
      }
      path.lineTo(x2 + w, y + h - ry);
      if (rx !== 0 || ry !== 0) {
        path.bezierCurveTo(
          x2 + w,
          y + h - ry * bci,
          x2 + w - rx * bci,
          y + h,
          x2 + w - rx,
          y + h
        );
      }
      path.lineTo(x2 + rx, y + h);
      if (rx !== 0 || ry !== 0) {
        path.bezierCurveTo(
          x2 + rx * bci,
          y + h,
          x2,
          y + h - ry * bci,
          x2,
          y + h - ry
        );
      }
      path.lineTo(x2, y + ry);
      if (rx !== 0 || ry !== 0) {
        path.bezierCurveTo(x2, y + ry * bci, x2 + rx * bci, y, x2 + rx, y);
      }
      return path;
    }
    function parsePolygonNode(node) {
      function iterator(match, a2, b3) {
        const x2 = parseFloatWithUnits(a2);
        const y = parseFloatWithUnits(b3);
        if (index2 === 0) {
          path.moveTo(x2, y);
        } else {
          path.lineTo(x2, y);
        }
        index2++;
      }
      const regex = /([+-]?\d*\.?\d+(?:e[+-]?\d+)?)(?:,|\s)([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/g;
      const path = new ShapePath2();
      let index2 = 0;
      node.getAttribute("points").replace(regex, iterator);
      path.currentPath.autoClose = true;
      return path;
    }
    function parsePolylineNode(node) {
      function iterator(match, a2, b3) {
        const x2 = parseFloatWithUnits(a2);
        const y = parseFloatWithUnits(b3);
        if (index2 === 0) {
          path.moveTo(x2, y);
        } else {
          path.lineTo(x2, y);
        }
        index2++;
      }
      const regex = /([+-]?\d*\.?\d+(?:e[+-]?\d+)?)(?:,|\s)([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/g;
      const path = new ShapePath2();
      let index2 = 0;
      node.getAttribute("points").replace(regex, iterator);
      path.currentPath.autoClose = false;
      return path;
    }
    function parseCircleNode(node) {
      const x2 = parseFloatWithUnits(node.getAttribute("cx") || 0);
      const y = parseFloatWithUnits(node.getAttribute("cy") || 0);
      const r = parseFloatWithUnits(node.getAttribute("r") || 0);
      const subpath = new Path();
      subpath.absarc(x2, y, r, 0, Math.PI * 2);
      const path = new ShapePath2();
      path.subPaths.push(subpath);
      return path;
    }
    function parseEllipseNode(node) {
      const x2 = parseFloatWithUnits(node.getAttribute("cx") || 0);
      const y = parseFloatWithUnits(node.getAttribute("cy") || 0);
      const rx = parseFloatWithUnits(node.getAttribute("rx") || 0);
      const ry = parseFloatWithUnits(node.getAttribute("ry") || 0);
      const subpath = new Path();
      subpath.absellipse(x2, y, rx, ry, 0, Math.PI * 2);
      const path = new ShapePath2();
      path.subPaths.push(subpath);
      return path;
    }
    function parseLineNode(node) {
      const x1 = parseFloatWithUnits(node.getAttribute("x1") || 0);
      const y1 = parseFloatWithUnits(node.getAttribute("y1") || 0);
      const x2 = parseFloatWithUnits(node.getAttribute("x2") || 0);
      const y2 = parseFloatWithUnits(node.getAttribute("y2") || 0);
      const path = new ShapePath2();
      path.moveTo(x1, y1);
      path.lineTo(x2, y2);
      path.currentPath.autoClose = false;
      return path;
    }
    function parseStyle(node, style) {
      style = Object.assign({}, style);
      let stylesheetStyles = {};
      if (node.hasAttribute("class")) {
        const classSelectors = node.getAttribute("class").split(/\s/).filter(Boolean).map((i) => i.trim());
        for (let i = 0; i < classSelectors.length; i++) {
          stylesheetStyles = Object.assign(stylesheetStyles, stylesheets["." + classSelectors[i]]);
        }
      }
      if (node.hasAttribute("id")) {
        stylesheetStyles = Object.assign(stylesheetStyles, stylesheets["#" + node.getAttribute("id")]);
      }
      function addStyle(svgName, jsName, adjustFunction) {
        if (adjustFunction === void 0) adjustFunction = function copy(v) {
          if (v.startsWith("url")) console.warn("SVGLoader: url access in attributes is not implemented.");
          return v;
        };
        if (node.hasAttribute(svgName)) style[jsName] = adjustFunction(node.getAttribute(svgName));
        if (stylesheetStyles[svgName]) style[jsName] = adjustFunction(stylesheetStyles[svgName]);
        if (node.style && node.style[svgName] !== "") style[jsName] = adjustFunction(node.style[svgName]);
      }
      function clamp2(v) {
        return Math.max(0, Math.min(1, parseFloatWithUnits(v)));
      }
      function positive(v) {
        return Math.max(0, parseFloatWithUnits(v));
      }
      addStyle("fill", "fill");
      addStyle("fill-opacity", "fillOpacity", clamp2);
      addStyle("fill-rule", "fillRule");
      addStyle("opacity", "opacity", clamp2);
      addStyle("stroke", "stroke");
      addStyle("stroke-opacity", "strokeOpacity", clamp2);
      addStyle("stroke-width", "strokeWidth", positive);
      addStyle("stroke-linejoin", "strokeLineJoin");
      addStyle("stroke-linecap", "strokeLineCap");
      addStyle("stroke-miterlimit", "strokeMiterLimit", positive);
      addStyle("visibility", "visibility");
      return style;
    }
    function getReflection(a2, b3) {
      return a2 - (b3 - a2);
    }
    function parseFloats(input, flags, stride) {
      if (typeof input !== "string") {
        throw new TypeError("Invalid input: " + typeof input);
      }
      const RE = {
        SEPARATOR: /[ \t\r\n\,.\-+]/,
        WHITESPACE: /[ \t\r\n]/,
        DIGIT: /[\d]/,
        SIGN: /[-+]/,
        POINT: /\./,
        COMMA: /,/,
        EXP: /e/i,
        FLAGS: /[01]/
      };
      const SEP = 0;
      const INT = 1;
      const FLOAT = 2;
      const EXP = 3;
      let state = SEP;
      let seenComma = true;
      let number = "", exponent = "";
      const result = [];
      function throwSyntaxError(current2, i, partial2) {
        const error = new SyntaxError('Unexpected character "' + current2 + '" at index ' + i + ".");
        error.partial = partial2;
        throw error;
      }
      function newNumber() {
        if (number !== "") {
          if (exponent === "") result.push(Number(number));
          else result.push(Number(number) * Math.pow(10, Number(exponent)));
        }
        number = "";
        exponent = "";
      }
      let current;
      const length2 = input.length;
      for (let i = 0; i < length2; i++) {
        current = input[i];
        if (Array.isArray(flags) && flags.includes(result.length % stride) && RE.FLAGS.test(current)) {
          state = INT;
          number = current;
          newNumber();
          continue;
        }
        if (state === SEP) {
          if (RE.WHITESPACE.test(current)) {
            continue;
          }
          if (RE.DIGIT.test(current) || RE.SIGN.test(current)) {
            state = INT;
            number = current;
            continue;
          }
          if (RE.POINT.test(current)) {
            state = FLOAT;
            number = current;
            continue;
          }
          if (RE.COMMA.test(current)) {
            if (seenComma) {
              throwSyntaxError(current, i, result);
            }
            seenComma = true;
          }
        }
        if (state === INT) {
          if (RE.DIGIT.test(current)) {
            number += current;
            continue;
          }
          if (RE.POINT.test(current)) {
            number += current;
            state = FLOAT;
            continue;
          }
          if (RE.EXP.test(current)) {
            state = EXP;
            continue;
          }
          if (RE.SIGN.test(current) && number.length === 1 && RE.SIGN.test(number[0])) {
            throwSyntaxError(current, i, result);
          }
        }
        if (state === FLOAT) {
          if (RE.DIGIT.test(current)) {
            number += current;
            continue;
          }
          if (RE.EXP.test(current)) {
            state = EXP;
            continue;
          }
          if (RE.POINT.test(current) && number[number.length - 1] === ".") {
            throwSyntaxError(current, i, result);
          }
        }
        if (state === EXP) {
          if (RE.DIGIT.test(current)) {
            exponent += current;
            continue;
          }
          if (RE.SIGN.test(current)) {
            if (exponent === "") {
              exponent += current;
              continue;
            }
            if (exponent.length === 1 && RE.SIGN.test(exponent)) {
              throwSyntaxError(current, i, result);
            }
          }
        }
        if (RE.WHITESPACE.test(current)) {
          newNumber();
          state = SEP;
          seenComma = false;
        } else if (RE.COMMA.test(current)) {
          newNumber();
          state = SEP;
          seenComma = true;
        } else if (RE.SIGN.test(current)) {
          newNumber();
          state = INT;
          number = current;
        } else if (RE.POINT.test(current)) {
          newNumber();
          state = FLOAT;
          number = current;
        } else {
          throwSyntaxError(current, i, result);
        }
      }
      newNumber();
      return result;
    }
    const units = ["mm", "cm", "in", "pt", "pc", "px"];
    const unitConversion = {
      "mm": {
        "mm": 1,
        "cm": 0.1,
        "in": 1 / 25.4,
        "pt": 72 / 25.4,
        "pc": 6 / 25.4,
        "px": -1
      },
      "cm": {
        "mm": 10,
        "cm": 1,
        "in": 1 / 2.54,
        "pt": 72 / 2.54,
        "pc": 6 / 2.54,
        "px": -1
      },
      "in": {
        "mm": 25.4,
        "cm": 2.54,
        "in": 1,
        "pt": 72,
        "pc": 6,
        "px": -1
      },
      "pt": {
        "mm": 25.4 / 72,
        "cm": 2.54 / 72,
        "in": 1 / 72,
        "pt": 1,
        "pc": 6 / 72,
        "px": -1
      },
      "pc": {
        "mm": 25.4 / 6,
        "cm": 2.54 / 6,
        "in": 1 / 6,
        "pt": 72 / 6,
        "pc": 1,
        "px": -1
      },
      "px": {
        "px": 1
      }
    };
    function parseFloatWithUnits(string) {
      let theUnit = "px";
      if (typeof string === "string" || string instanceof String) {
        for (let i = 0, n2 = units.length; i < n2; i++) {
          const u2 = units[i];
          if (string.endsWith(u2)) {
            theUnit = u2;
            string = string.substring(0, string.length - u2.length);
            break;
          }
        }
      }
      let scale2 = void 0;
      if (theUnit === "px" && scope.defaultUnit !== "px") {
        scale2 = unitConversion["in"][scope.defaultUnit] / scope.defaultDPI;
      } else {
        scale2 = unitConversion[theUnit][scope.defaultUnit];
        if (scale2 < 0) {
          scale2 = unitConversion[theUnit]["in"] * scope.defaultDPI;
        }
      }
      return scale2 * parseFloat(string);
    }
    function getNodeTransform(node) {
      if (!(node.hasAttribute("transform") || node.nodeName === "use" && (node.hasAttribute("x") || node.hasAttribute("y")))) {
        return null;
      }
      const transform2 = parseNodeTransform(node);
      if (transformStack.length > 0) {
        transform2.premultiply(transformStack[transformStack.length - 1]);
      }
      currentTransform.copy(transform2);
      transformStack.push(transform2);
      return transform2;
    }
    function parseNodeTransform(node) {
      const transform2 = new Matrix3();
      const currentTransform2 = tempTransform0;
      if (node.nodeName === "use" && (node.hasAttribute("x") || node.hasAttribute("y"))) {
        const tx = parseFloatWithUnits(node.getAttribute("x"));
        const ty = parseFloatWithUnits(node.getAttribute("y"));
        transform2.translate(tx, ty);
      }
      if (node.hasAttribute("transform")) {
        const transformsTexts = node.getAttribute("transform").split(")");
        for (let tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex--) {
          const transformText = transformsTexts[tIndex].trim();
          if (transformText === "") continue;
          const openParPos = transformText.indexOf("(");
          const closeParPos = transformText.length;
          if (openParPos > 0 && openParPos < closeParPos) {
            const transformType = transformText.slice(0, openParPos);
            const array = parseFloats(transformText.slice(openParPos + 1));
            currentTransform2.identity();
            switch (transformType) {
              case "translate":
                if (array.length >= 1) {
                  const tx = array[0];
                  let ty = 0;
                  if (array.length >= 2) {
                    ty = array[1];
                  }
                  currentTransform2.translate(tx, ty);
                }
                break;
              case "rotate":
                if (array.length >= 1) {
                  let angle = 0;
                  let cx = 0;
                  let cy = 0;
                  angle = array[0] * Math.PI / 180;
                  if (array.length >= 3) {
                    cx = array[1];
                    cy = array[2];
                  }
                  tempTransform1.makeTranslation(-cx, -cy);
                  tempTransform2.makeRotation(angle);
                  tempTransform3.multiplyMatrices(tempTransform2, tempTransform1);
                  tempTransform1.makeTranslation(cx, cy);
                  currentTransform2.multiplyMatrices(tempTransform1, tempTransform3);
                }
                break;
              case "scale":
                if (array.length >= 1) {
                  const scaleX = array[0];
                  let scaleY = scaleX;
                  if (array.length >= 2) {
                    scaleY = array[1];
                  }
                  currentTransform2.scale(scaleX, scaleY);
                }
                break;
              case "skewX":
                if (array.length === 1) {
                  currentTransform2.set(
                    1,
                    Math.tan(array[0] * Math.PI / 180),
                    0,
                    0,
                    1,
                    0,
                    0,
                    0,
                    1
                  );
                }
                break;
              case "skewY":
                if (array.length === 1) {
                  currentTransform2.set(
                    1,
                    0,
                    0,
                    Math.tan(array[0] * Math.PI / 180),
                    1,
                    0,
                    0,
                    0,
                    1
                  );
                }
                break;
              case "matrix":
                if (array.length === 6) {
                  currentTransform2.set(
                    array[0],
                    array[2],
                    array[4],
                    array[1],
                    array[3],
                    array[5],
                    0,
                    0,
                    1
                  );
                }
                break;
            }
          }
          transform2.premultiply(currentTransform2);
        }
      }
      return transform2;
    }
    function transformPath(path, m) {
      function transfVec2(v2) {
        tempV3.set(v2.x, v2.y, 1).applyMatrix3(m);
        v2.set(tempV3.x, tempV3.y);
      }
      function transfEllipseGeneric(curve) {
        const a2 = curve.xRadius;
        const b3 = curve.yRadius;
        const cosTheta = Math.cos(curve.aRotation);
        const sinTheta = Math.sin(curve.aRotation);
        const v12 = new Vector3(a2 * cosTheta, a2 * sinTheta, 0);
        const v2 = new Vector3(-b3 * sinTheta, b3 * cosTheta, 0);
        const f1 = v12.applyMatrix3(m);
        const f2 = v2.applyMatrix3(m);
        const mF = tempTransform0.set(
          f1.x,
          f2.x,
          0,
          f1.y,
          f2.y,
          0,
          0,
          0,
          1
        );
        const mFInv = tempTransform1.copy(mF).invert();
        const mFInvT = tempTransform2.copy(mFInv).transpose();
        const mQ = mFInvT.multiply(mFInv);
        const mQe = mQ.elements;
        const ed = eigenDecomposition(mQe[0], mQe[1], mQe[4]);
        const rt1sqrt = Math.sqrt(ed.rt1);
        const rt2sqrt = Math.sqrt(ed.rt2);
        curve.xRadius = 1 / rt1sqrt;
        curve.yRadius = 1 / rt2sqrt;
        curve.aRotation = Math.atan2(ed.sn, ed.cs);
        const isFullEllipse = (curve.aEndAngle - curve.aStartAngle) % (2 * Math.PI) < Number.EPSILON;
        if (!isFullEllipse) {
          const mDsqrt = tempTransform1.set(
            rt1sqrt,
            0,
            0,
            0,
            rt2sqrt,
            0,
            0,
            0,
            1
          );
          const mRT = tempTransform2.set(
            ed.cs,
            ed.sn,
            0,
            -ed.sn,
            ed.cs,
            0,
            0,
            0,
            1
          );
          const mDRF = mDsqrt.multiply(mRT).multiply(mF);
          const transformAngle = (phi) => {
            const { x: cosR, y: sinR } = new Vector3(Math.cos(phi), Math.sin(phi), 0).applyMatrix3(mDRF);
            return Math.atan2(sinR, cosR);
          };
          curve.aStartAngle = transformAngle(curve.aStartAngle);
          curve.aEndAngle = transformAngle(curve.aEndAngle);
          if (isTransformFlipped(m)) {
            curve.aClockwise = !curve.aClockwise;
          }
        }
      }
      function transfEllipseNoSkew(curve) {
        const sx = getTransformScaleX(m);
        const sy = getTransformScaleY(m);
        curve.xRadius *= sx;
        curve.yRadius *= sy;
        const theta = sx > Number.EPSILON ? Math.atan2(m.elements[1], m.elements[0]) : Math.atan2(-m.elements[3], m.elements[4]);
        curve.aRotation += theta;
        if (isTransformFlipped(m)) {
          curve.aStartAngle *= -1;
          curve.aEndAngle *= -1;
          curve.aClockwise = !curve.aClockwise;
        }
      }
      const subPaths = path.subPaths;
      for (let i = 0, n2 = subPaths.length; i < n2; i++) {
        const subPath = subPaths[i];
        const curves = subPath.curves;
        for (let j2 = 0; j2 < curves.length; j2++) {
          const curve = curves[j2];
          if (curve.isLineCurve) {
            transfVec2(curve.v1);
            transfVec2(curve.v2);
          } else if (curve.isCubicBezierCurve) {
            transfVec2(curve.v0);
            transfVec2(curve.v1);
            transfVec2(curve.v2);
            transfVec2(curve.v3);
          } else if (curve.isQuadraticBezierCurve) {
            transfVec2(curve.v0);
            transfVec2(curve.v1);
            transfVec2(curve.v2);
          } else if (curve.isEllipseCurve) {
            tempV2.set(curve.aX, curve.aY);
            transfVec2(tempV2);
            curve.aX = tempV2.x;
            curve.aY = tempV2.y;
            if (isTransformSkewed(m)) {
              transfEllipseGeneric(curve);
            } else {
              transfEllipseNoSkew(curve);
            }
          }
        }
      }
    }
    function isTransformFlipped(m) {
      const te3 = m.elements;
      return te3[0] * te3[4] - te3[1] * te3[3] < 0;
    }
    function isTransformSkewed(m) {
      const te3 = m.elements;
      const basisDot = te3[0] * te3[3] + te3[1] * te3[4];
      if (basisDot === 0) return false;
      const sx = getTransformScaleX(m);
      const sy = getTransformScaleY(m);
      return Math.abs(basisDot / (sx * sy)) > Number.EPSILON;
    }
    function getTransformScaleX(m) {
      const te3 = m.elements;
      return Math.sqrt(te3[0] * te3[0] + te3[1] * te3[1]);
    }
    function getTransformScaleY(m) {
      const te3 = m.elements;
      return Math.sqrt(te3[3] * te3[3] + te3[4] * te3[4]);
    }
    function eigenDecomposition(A2, B2, C3) {
      let rt1, rt2, cs, sn, t3;
      const sm = A2 + C3;
      const df = A2 - C3;
      const rt = Math.sqrt(df * df + 4 * B2 * B2);
      if (sm > 0) {
        rt1 = 0.5 * (sm + rt);
        t3 = 1 / rt1;
        rt2 = A2 * t3 * C3 - B2 * t3 * B2;
      } else if (sm < 0) {
        rt2 = 0.5 * (sm - rt);
      } else {
        rt1 = 0.5 * rt;
        rt2 = -0.5 * rt;
      }
      if (df > 0) {
        cs = df + rt;
      } else {
        cs = df - rt;
      }
      if (Math.abs(cs) > 2 * Math.abs(B2)) {
        t3 = -2 * B2 / cs;
        sn = 1 / Math.sqrt(1 + t3 * t3);
        cs = t3 * sn;
      } else if (Math.abs(B2) === 0) {
        cs = 1;
        sn = 0;
      } else {
        t3 = -0.5 * cs / B2;
        cs = 1 / Math.sqrt(1 + t3 * t3);
        sn = t3 * cs;
      }
      if (df > 0) {
        t3 = cs;
        cs = -sn;
        sn = t3;
      }
      return { rt1, rt2, cs, sn };
    }
    const paths = [];
    const stylesheets = {};
    const transformStack = [];
    const tempTransform0 = new Matrix3();
    const tempTransform1 = new Matrix3();
    const tempTransform2 = new Matrix3();
    const tempTransform3 = new Matrix3();
    const tempV2 = new Vector2();
    const tempV3 = new Vector3();
    const currentTransform = new Matrix3();
    const xml = new DOMParser().parseFromString(text2, "image/svg+xml");
    parseNode(xml.documentElement, {
      fill: "#000",
      fillOpacity: 1,
      strokeOpacity: 1,
      strokeWidth: 1,
      strokeLineJoin: "miter",
      strokeLineCap: "butt",
      strokeMiterLimit: 4
    });
    const data2 = { paths, xml: xml.documentElement };
    return data2;
  }
  /**
   * Creates from the given shape path and array of shapes.
   *
   * @param {ShapePath} shapePath - The shape path.
   * @return {Array<Shape>} An array of shapes.
   */
  static createShapes(shapePath) {
    const BIGNUMBER = 999999999;
    const IntersectionLocationType = {
      ORIGIN: 0,
      DESTINATION: 1,
      BETWEEN: 2,
      LEFT: 3,
      RIGHT: 4,
      BEHIND: 5,
      BEYOND: 6
    };
    const classifyResult = {
      loc: IntersectionLocationType.ORIGIN,
      t: 0
    };
    function findEdgeIntersection(a0, a1, b0, b1) {
      const x1 = a0.x;
      const x2 = a1.x;
      const x3 = b0.x;
      const x4 = b1.x;
      const y1 = a0.y;
      const y2 = a1.y;
      const y3 = b0.y;
      const y4 = b1.y;
      const nom1 = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
      const nom2 = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);
      const denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
      const t1 = nom1 / denom;
      const t22 = nom2 / denom;
      if (denom === 0 && nom1 !== 0 || t1 <= 0 || t1 >= 1 || t22 < 0 || t22 > 1) {
        return null;
      } else if (nom1 === 0 && denom === 0) {
        for (let i = 0; i < 2; i++) {
          classifyPoint(i === 0 ? b0 : b1, a0, a1);
          if (classifyResult.loc == IntersectionLocationType.ORIGIN) {
            const point = i === 0 ? b0 : b1;
            return { x: point.x, y: point.y, t: classifyResult.t };
          } else if (classifyResult.loc == IntersectionLocationType.BETWEEN) {
            const x5 = +(x1 + classifyResult.t * (x2 - x1)).toPrecision(10);
            const y = +(y1 + classifyResult.t * (y2 - y1)).toPrecision(10);
            return { x: x5, y, t: classifyResult.t };
          }
        }
        return null;
      } else {
        for (let i = 0; i < 2; i++) {
          classifyPoint(i === 0 ? b0 : b1, a0, a1);
          if (classifyResult.loc == IntersectionLocationType.ORIGIN) {
            const point = i === 0 ? b0 : b1;
            return { x: point.x, y: point.y, t: classifyResult.t };
          }
        }
        const x5 = +(x1 + t1 * (x2 - x1)).toPrecision(10);
        const y = +(y1 + t1 * (y2 - y1)).toPrecision(10);
        return { x: x5, y, t: t1 };
      }
    }
    function classifyPoint(p, edgeStart, edgeEnd) {
      const ax = edgeEnd.x - edgeStart.x;
      const ay = edgeEnd.y - edgeStart.y;
      const bx = p.x - edgeStart.x;
      const by = p.y - edgeStart.y;
      const sa = ax * by - bx * ay;
      if (p.x === edgeStart.x && p.y === edgeStart.y) {
        classifyResult.loc = IntersectionLocationType.ORIGIN;
        classifyResult.t = 0;
        return;
      }
      if (p.x === edgeEnd.x && p.y === edgeEnd.y) {
        classifyResult.loc = IntersectionLocationType.DESTINATION;
        classifyResult.t = 1;
        return;
      }
      if (sa < -Number.EPSILON) {
        classifyResult.loc = IntersectionLocationType.LEFT;
        return;
      }
      if (sa > Number.EPSILON) {
        classifyResult.loc = IntersectionLocationType.RIGHT;
        return;
      }
      if (ax * bx < 0 || ay * by < 0) {
        classifyResult.loc = IntersectionLocationType.BEHIND;
        return;
      }
      if (Math.sqrt(ax * ax + ay * ay) < Math.sqrt(bx * bx + by * by)) {
        classifyResult.loc = IntersectionLocationType.BEYOND;
        return;
      }
      let t3;
      if (ax !== 0) {
        t3 = bx / ax;
      } else {
        t3 = by / ay;
      }
      classifyResult.loc = IntersectionLocationType.BETWEEN;
      classifyResult.t = t3;
    }
    function getIntersections(path1, path2) {
      const intersectionsRaw = [];
      const intersections = [];
      for (let index2 = 1; index2 < path1.length; index2++) {
        const path1EdgeStart = path1[index2 - 1];
        const path1EdgeEnd = path1[index2];
        for (let index22 = 1; index22 < path2.length; index22++) {
          const path2EdgeStart = path2[index22 - 1];
          const path2EdgeEnd = path2[index22];
          const intersection = findEdgeIntersection(path1EdgeStart, path1EdgeEnd, path2EdgeStart, path2EdgeEnd);
          if (intersection !== null && intersectionsRaw.find((i) => i.t <= intersection.t + Number.EPSILON && i.t >= intersection.t - Number.EPSILON) === void 0) {
            intersectionsRaw.push(intersection);
            intersections.push(new Vector2(intersection.x, intersection.y));
          }
        }
      }
      return intersections;
    }
    function getScanlineIntersections(scanline, boundingBox, paths) {
      const center = new Vector2();
      boundingBox.getCenter(center);
      const allIntersections = [];
      paths.forEach((path) => {
        if (path.boundingBox.containsPoint(center)) {
          const intersections = getIntersections(scanline, path.points);
          intersections.forEach((p) => {
            allIntersections.push({ identifier: path.identifier, isCW: path.isCW, point: p });
          });
        }
      });
      allIntersections.sort((i1, i2) => {
        return i1.point.x - i2.point.x;
      });
      return allIntersections;
    }
    function isHoleTo(simplePath, allPaths, scanlineMinX2, scanlineMaxX2, _fillRule) {
      if (_fillRule === null || _fillRule === void 0 || _fillRule === "") {
        _fillRule = "nonzero";
      }
      const centerBoundingBox = new Vector2();
      simplePath.boundingBox.getCenter(centerBoundingBox);
      const scanline = [new Vector2(scanlineMinX2, centerBoundingBox.y), new Vector2(scanlineMaxX2, centerBoundingBox.y)];
      const scanlineIntersections = getScanlineIntersections(scanline, simplePath.boundingBox, allPaths);
      scanlineIntersections.sort((i1, i2) => {
        return i1.point.x - i2.point.x;
      });
      const baseIntersections = [];
      const otherIntersections = [];
      scanlineIntersections.forEach((i2) => {
        if (i2.identifier === simplePath.identifier) {
          baseIntersections.push(i2);
        } else {
          otherIntersections.push(i2);
        }
      });
      const firstXOfPath = baseIntersections[0].point.x;
      const stack = [];
      let i = 0;
      while (i < otherIntersections.length && otherIntersections[i].point.x < firstXOfPath) {
        if (stack.length > 0 && stack[stack.length - 1] === otherIntersections[i].identifier) {
          stack.pop();
        } else {
          stack.push(otherIntersections[i].identifier);
        }
        i++;
      }
      stack.push(simplePath.identifier);
      if (_fillRule === "evenodd") {
        const isHole = stack.length % 2 === 0 ? true : false;
        const isHoleFor = stack[stack.length - 2];
        return { identifier: simplePath.identifier, isHole, for: isHoleFor };
      } else if (_fillRule === "nonzero") {
        let isHole = true;
        let isHoleFor = null;
        let lastCWValue = null;
        for (let i2 = 0; i2 < stack.length; i2++) {
          const identifier = stack[i2];
          if (isHole) {
            lastCWValue = allPaths[identifier].isCW;
            isHole = false;
            isHoleFor = identifier;
          } else if (lastCWValue !== allPaths[identifier].isCW) {
            lastCWValue = allPaths[identifier].isCW;
            isHole = true;
          }
        }
        return { identifier: simplePath.identifier, isHole, for: isHoleFor };
      } else {
        console.warn('fill-rule: "' + _fillRule + '" is currently not implemented.');
      }
    }
    let scanlineMinX = BIGNUMBER;
    let scanlineMaxX = -BIGNUMBER;
    let simplePaths = shapePath.subPaths.map((p) => {
      const points = p.getPoints();
      let maxY = -BIGNUMBER;
      let minY = BIGNUMBER;
      let maxX = -BIGNUMBER;
      let minX = BIGNUMBER;
      for (let i = 0; i < points.length; i++) {
        const p2 = points[i];
        if (p2.y > maxY) {
          maxY = p2.y;
        }
        if (p2.y < minY) {
          minY = p2.y;
        }
        if (p2.x > maxX) {
          maxX = p2.x;
        }
        if (p2.x < minX) {
          minX = p2.x;
        }
      }
      if (scanlineMaxX <= maxX) {
        scanlineMaxX = maxX + 1;
      }
      if (scanlineMinX >= minX) {
        scanlineMinX = minX - 1;
      }
      return { curves: p.curves, points, isCW: ShapeUtils.isClockWise(points), identifier: -1, boundingBox: new Box2(new Vector2(minX, minY), new Vector2(maxX, maxY)) };
    });
    simplePaths = simplePaths.filter((sp) => sp.points.length > 1);
    for (let identifier = 0; identifier < simplePaths.length; identifier++) {
      simplePaths[identifier].identifier = identifier;
    }
    const isAHole = simplePaths.map((p) => isHoleTo(p, simplePaths, scanlineMinX, scanlineMaxX, shapePath.userData ? shapePath.userData.style.fillRule : void 0));
    const shapesToReturn = [];
    simplePaths.forEach((p) => {
      const amIAHole = isAHole[p.identifier];
      if (!amIAHole.isHole) {
        const shape = new Shape();
        shape.curves = p.curves;
        const holes = isAHole.filter((h) => h.isHole && h.for === p.identifier);
        holes.forEach((h) => {
          const hole = simplePaths[h.identifier];
          const path = new Path();
          path.curves = hole.curves;
          shape.holes.push(path);
        });
        shapesToReturn.push(shape);
      }
    });
    return shapesToReturn;
  }
  /**
   * Returns a stroke style object from the given parameters.
   *
   * @param {number} [width=1] - The stroke width.
   * @param {string} [color='#000'] - The stroke color, as  returned by {@link Color#getStyle}.
   * @param {'round'|'bevel'|'miter'|'miter-limit'} [lineJoin='miter'] - The line join style.
   * @param {'round'|'square'|'butt'} [lineCap='butt'] - The line cap style.
   * @param {number} [miterLimit=4] - Maximum join length, in multiples of the `width` parameter (join is truncated if it exceeds that distance).
   * @return {Object} The style object.
   */
  static getStrokeStyle(width2, color, lineJoin, lineCap, miterLimit) {
    width2 = width2 !== void 0 ? width2 : 1;
    color = color !== void 0 ? color : "#000";
    lineJoin = lineJoin !== void 0 ? lineJoin : "miter";
    lineCap = lineCap !== void 0 ? lineCap : "butt";
    miterLimit = miterLimit !== void 0 ? miterLimit : 4;
    return {
      strokeColor: color,
      strokeWidth: width2,
      strokeLineJoin: lineJoin,
      strokeLineCap: lineCap,
      strokeMiterLimit: miterLimit
    };
  }
  /**
   * Creates a stroke from an array of points.
   *
   * @param {Array<Vector2>} points - The points in 2D space. Minimum 2 points. The path can be open or closed (last point equals to first point).
   * @param {Object} style - Object with SVG properties as returned by `SVGLoader.getStrokeStyle()`, or `SVGLoader.parse()` in the `path.userData.style` object.
   * @param {number} [arcDivisions=12] - Arc divisions for round joins and endcaps.
   * @param {number} [minDistance=0.001] - Points closer to this distance will be merged.
   * @return {?BufferGeometry} The stroke geometry. UV coordinates are generated ('u' along path. 'v' across it, from left to right).
   * Returns `null` if not geometry was generated.
   */
  static pointsToStroke(points, style, arcDivisions, minDistance) {
    const vertices = [];
    const normals = [];
    const uvs = [];
    if (_SVGLoader.pointsToStrokeWithBuffers(points, style, arcDivisions, minDistance, vertices, normals, uvs) === 0) {
      return null;
    }
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3));
    geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
    return geometry;
  }
  /**
   * Creates a stroke from an array of points.
   *
   * @param {Array<Vector2>} points - The points in 2D space. Minimum 2 points.
   * @param {Object} style - Object with SVG properties as returned by `SVGLoader.getStrokeStyle()`, or `SVGLoader.parse()` in the `path.userData.style` object.
   * @param {number} [arcDivisions=12] - Arc divisions for round joins and endcaps.
   * @param {number} [minDistance=0.001] - Points closer to this distance will be merged.
   * @param {Array<number>} vertices - An array holding vertices.
   * @param {Array<number>} normals - An array holding normals.
   * @param {Array<number>} uvs - An array holding uvs.
   * @param {number} [vertexOffset=0] - The vertex offset.
   * @return {number} The number of vertices.
   */
  static pointsToStrokeWithBuffers(points, style, arcDivisions, minDistance, vertices, normals, uvs, vertexOffset) {
    const tempV2_1 = new Vector2();
    const tempV2_2 = new Vector2();
    const tempV2_3 = new Vector2();
    const tempV2_4 = new Vector2();
    const tempV2_5 = new Vector2();
    const tempV2_6 = new Vector2();
    const tempV2_7 = new Vector2();
    const lastPointL = new Vector2();
    const lastPointR = new Vector2();
    const point0L = new Vector2();
    const point0R = new Vector2();
    const currentPointL = new Vector2();
    const currentPointR = new Vector2();
    const nextPointL = new Vector2();
    const nextPointR = new Vector2();
    const innerPoint = new Vector2();
    const outerPoint = new Vector2();
    arcDivisions = arcDivisions !== void 0 ? arcDivisions : 12;
    minDistance = minDistance !== void 0 ? minDistance : 1e-3;
    vertexOffset = vertexOffset !== void 0 ? vertexOffset : 0;
    points = removeDuplicatedPoints(points);
    const numPoints = points.length;
    if (numPoints < 2) return 0;
    const isClosed = points[0].equals(points[numPoints - 1]);
    let currentPoint;
    let previousPoint = points[0];
    let nextPoint;
    const strokeWidth2 = style.strokeWidth / 2;
    const deltaU = 1 / (numPoints - 1);
    let u0 = 0, u1;
    let innerSideModified;
    let joinIsOnLeftSide;
    let isMiter;
    let initialJoinIsOnLeftSide = false;
    let numVertices = 0;
    let currentCoordinate = vertexOffset * 3;
    let currentCoordinateUV = vertexOffset * 2;
    getNormal(points[0], points[1], tempV2_1).multiplyScalar(strokeWidth2);
    lastPointL.copy(points[0]).sub(tempV2_1);
    lastPointR.copy(points[0]).add(tempV2_1);
    point0L.copy(lastPointL);
    point0R.copy(lastPointR);
    for (let iPoint = 1; iPoint < numPoints; iPoint++) {
      currentPoint = points[iPoint];
      if (iPoint === numPoints - 1) {
        if (isClosed) {
          nextPoint = points[1];
        } else nextPoint = void 0;
      } else {
        nextPoint = points[iPoint + 1];
      }
      const normal1 = tempV2_1;
      getNormal(previousPoint, currentPoint, normal1);
      tempV2_3.copy(normal1).multiplyScalar(strokeWidth2);
      currentPointL.copy(currentPoint).sub(tempV2_3);
      currentPointR.copy(currentPoint).add(tempV2_3);
      u1 = u0 + deltaU;
      innerSideModified = false;
      if (nextPoint !== void 0) {
        getNormal(currentPoint, nextPoint, tempV2_2);
        tempV2_3.copy(tempV2_2).multiplyScalar(strokeWidth2);
        nextPointL.copy(currentPoint).sub(tempV2_3);
        nextPointR.copy(currentPoint).add(tempV2_3);
        joinIsOnLeftSide = true;
        tempV2_3.subVectors(nextPoint, previousPoint);
        if (normal1.dot(tempV2_3) < 0) {
          joinIsOnLeftSide = false;
        }
        if (iPoint === 1) initialJoinIsOnLeftSide = joinIsOnLeftSide;
        tempV2_3.subVectors(nextPoint, currentPoint);
        tempV2_3.normalize();
        const dot = Math.abs(normal1.dot(tempV2_3));
        if (dot > Number.EPSILON) {
          const miterSide = strokeWidth2 / dot;
          tempV2_3.multiplyScalar(-miterSide);
          tempV2_4.subVectors(currentPoint, previousPoint);
          tempV2_5.copy(tempV2_4).setLength(miterSide).add(tempV2_3);
          innerPoint.copy(tempV2_5).negate();
          const miterLength2 = tempV2_5.length();
          const segmentLengthPrev = tempV2_4.length();
          tempV2_4.divideScalar(segmentLengthPrev);
          tempV2_6.subVectors(nextPoint, currentPoint);
          const segmentLengthNext = tempV2_6.length();
          tempV2_6.divideScalar(segmentLengthNext);
          if (tempV2_4.dot(innerPoint) < segmentLengthPrev && tempV2_6.dot(innerPoint) < segmentLengthNext) {
            innerSideModified = true;
          }
          outerPoint.copy(tempV2_5).add(currentPoint);
          innerPoint.add(currentPoint);
          isMiter = false;
          if (innerSideModified) {
            if (joinIsOnLeftSide) {
              nextPointR.copy(innerPoint);
              currentPointR.copy(innerPoint);
            } else {
              nextPointL.copy(innerPoint);
              currentPointL.copy(innerPoint);
            }
          } else {
            makeSegmentTriangles();
          }
          switch (style.strokeLineJoin) {
            case "bevel":
              makeSegmentWithBevelJoin(joinIsOnLeftSide, innerSideModified, u1);
              break;
            case "round":
              createSegmentTrianglesWithMiddleSection(joinIsOnLeftSide, innerSideModified);
              if (joinIsOnLeftSide) {
                makeCircularSector(currentPoint, currentPointL, nextPointL, u1, 0);
              } else {
                makeCircularSector(currentPoint, nextPointR, currentPointR, u1, 1);
              }
              break;
            case "miter":
            case "miter-clip":
            default:
              const miterFraction = strokeWidth2 * style.strokeMiterLimit / miterLength2;
              if (miterFraction < 1) {
                if (style.strokeLineJoin !== "miter-clip") {
                  makeSegmentWithBevelJoin(joinIsOnLeftSide, innerSideModified, u1);
                  break;
                } else {
                  createSegmentTrianglesWithMiddleSection(joinIsOnLeftSide, innerSideModified);
                  if (joinIsOnLeftSide) {
                    tempV2_6.subVectors(outerPoint, currentPointL).multiplyScalar(miterFraction).add(currentPointL);
                    tempV2_7.subVectors(outerPoint, nextPointL).multiplyScalar(miterFraction).add(nextPointL);
                    addVertex(currentPointL, u1, 0);
                    addVertex(tempV2_6, u1, 0);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(tempV2_6, u1, 0);
                    addVertex(tempV2_7, u1, 0);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(tempV2_7, u1, 0);
                    addVertex(nextPointL, u1, 0);
                  } else {
                    tempV2_6.subVectors(outerPoint, currentPointR).multiplyScalar(miterFraction).add(currentPointR);
                    tempV2_7.subVectors(outerPoint, nextPointR).multiplyScalar(miterFraction).add(nextPointR);
                    addVertex(currentPointR, u1, 1);
                    addVertex(tempV2_6, u1, 1);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(tempV2_6, u1, 1);
                    addVertex(tempV2_7, u1, 1);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(tempV2_7, u1, 1);
                    addVertex(nextPointR, u1, 1);
                  }
                }
              } else {
                if (innerSideModified) {
                  if (joinIsOnLeftSide) {
                    addVertex(lastPointR, u0, 1);
                    addVertex(lastPointL, u0, 0);
                    addVertex(outerPoint, u1, 0);
                    addVertex(lastPointR, u0, 1);
                    addVertex(outerPoint, u1, 0);
                    addVertex(innerPoint, u1, 1);
                  } else {
                    addVertex(lastPointR, u0, 1);
                    addVertex(lastPointL, u0, 0);
                    addVertex(outerPoint, u1, 1);
                    addVertex(lastPointL, u0, 0);
                    addVertex(innerPoint, u1, 0);
                    addVertex(outerPoint, u1, 1);
                  }
                  if (joinIsOnLeftSide) {
                    nextPointL.copy(outerPoint);
                  } else {
                    nextPointR.copy(outerPoint);
                  }
                } else {
                  if (joinIsOnLeftSide) {
                    addVertex(currentPointL, u1, 0);
                    addVertex(outerPoint, u1, 0);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(outerPoint, u1, 0);
                    addVertex(nextPointL, u1, 0);
                  } else {
                    addVertex(currentPointR, u1, 1);
                    addVertex(outerPoint, u1, 1);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(currentPoint, u1, 0.5);
                    addVertex(outerPoint, u1, 1);
                    addVertex(nextPointR, u1, 1);
                  }
                }
                isMiter = true;
              }
              break;
          }
        } else {
          makeSegmentTriangles();
        }
      } else {
        makeSegmentTriangles();
      }
      if (!isClosed && iPoint === numPoints - 1) {
        addCapGeometry(points[0], point0L, point0R, joinIsOnLeftSide, true, u0);
      }
      u0 = u1;
      previousPoint = currentPoint;
      lastPointL.copy(nextPointL);
      lastPointR.copy(nextPointR);
    }
    if (!isClosed) {
      addCapGeometry(currentPoint, currentPointL, currentPointR, joinIsOnLeftSide, false, u1);
    } else if (innerSideModified && vertices) {
      let lastOuter = outerPoint;
      let lastInner = innerPoint;
      if (initialJoinIsOnLeftSide !== joinIsOnLeftSide) {
        lastOuter = innerPoint;
        lastInner = outerPoint;
      }
      if (joinIsOnLeftSide) {
        if (isMiter || initialJoinIsOnLeftSide) {
          lastInner.toArray(vertices, 0 * 3);
          lastInner.toArray(vertices, 3 * 3);
          if (isMiter) {
            lastOuter.toArray(vertices, 1 * 3);
          }
        }
      } else {
        if (isMiter || !initialJoinIsOnLeftSide) {
          lastInner.toArray(vertices, 1 * 3);
          lastInner.toArray(vertices, 3 * 3);
          if (isMiter) {
            lastOuter.toArray(vertices, 0 * 3);
          }
        }
      }
    }
    return numVertices;
    function getNormal(p1, p2, result) {
      result.subVectors(p2, p1);
      return result.set(-result.y, result.x).normalize();
    }
    function addVertex(position2, u2, v) {
      if (vertices) {
        vertices[currentCoordinate] = position2.x;
        vertices[currentCoordinate + 1] = position2.y;
        vertices[currentCoordinate + 2] = 0;
        if (normals) {
          normals[currentCoordinate] = 0;
          normals[currentCoordinate + 1] = 0;
          normals[currentCoordinate + 2] = 1;
        }
        currentCoordinate += 3;
        if (uvs) {
          uvs[currentCoordinateUV] = u2;
          uvs[currentCoordinateUV + 1] = v;
          currentCoordinateUV += 2;
        }
      }
      numVertices += 3;
    }
    function makeCircularSector(center, p1, p2, u2, v) {
      tempV2_1.copy(p1).sub(center).normalize();
      tempV2_2.copy(p2).sub(center).normalize();
      let angle = Math.PI;
      const dot = tempV2_1.dot(tempV2_2);
      if (Math.abs(dot) < 1) angle = Math.abs(Math.acos(dot));
      angle /= arcDivisions;
      tempV2_3.copy(p1);
      for (let i = 0, il = arcDivisions - 1; i < il; i++) {
        tempV2_4.copy(tempV2_3).rotateAround(center, angle);
        addVertex(tempV2_3, u2, v);
        addVertex(tempV2_4, u2, v);
        addVertex(center, u2, 0.5);
        tempV2_3.copy(tempV2_4);
      }
      addVertex(tempV2_4, u2, v);
      addVertex(p2, u2, v);
      addVertex(center, u2, 0.5);
    }
    function makeSegmentTriangles() {
      addVertex(lastPointR, u0, 1);
      addVertex(lastPointL, u0, 0);
      addVertex(currentPointL, u1, 0);
      addVertex(lastPointR, u0, 1);
      addVertex(currentPointL, u1, 0);
      addVertex(currentPointR, u1, 1);
    }
    function makeSegmentWithBevelJoin(joinIsOnLeftSide2, innerSideModified2, u2) {
      if (innerSideModified2) {
        if (joinIsOnLeftSide2) {
          addVertex(lastPointR, u0, 1);
          addVertex(lastPointL, u0, 0);
          addVertex(currentPointL, u1, 0);
          addVertex(lastPointR, u0, 1);
          addVertex(currentPointL, u1, 0);
          addVertex(innerPoint, u1, 1);
          addVertex(currentPointL, u2, 0);
          addVertex(nextPointL, u2, 0);
          addVertex(innerPoint, u2, 0.5);
        } else {
          addVertex(lastPointR, u0, 1);
          addVertex(lastPointL, u0, 0);
          addVertex(currentPointR, u1, 1);
          addVertex(lastPointL, u0, 0);
          addVertex(innerPoint, u1, 0);
          addVertex(currentPointR, u1, 1);
          addVertex(currentPointR, u2, 1);
          addVertex(innerPoint, u2, 0);
          addVertex(nextPointR, u2, 1);
        }
      } else {
        if (joinIsOnLeftSide2) {
          addVertex(currentPointL, u2, 0);
          addVertex(nextPointL, u2, 0);
          addVertex(currentPoint, u2, 0.5);
        } else {
          addVertex(currentPointR, u2, 1);
          addVertex(nextPointR, u2, 0);
          addVertex(currentPoint, u2, 0.5);
        }
      }
    }
    function createSegmentTrianglesWithMiddleSection(joinIsOnLeftSide2, innerSideModified2) {
      if (innerSideModified2) {
        if (joinIsOnLeftSide2) {
          addVertex(lastPointR, u0, 1);
          addVertex(lastPointL, u0, 0);
          addVertex(currentPointL, u1, 0);
          addVertex(lastPointR, u0, 1);
          addVertex(currentPointL, u1, 0);
          addVertex(innerPoint, u1, 1);
          addVertex(currentPointL, u0, 0);
          addVertex(currentPoint, u1, 0.5);
          addVertex(innerPoint, u1, 1);
          addVertex(currentPoint, u1, 0.5);
          addVertex(nextPointL, u0, 0);
          addVertex(innerPoint, u1, 1);
        } else {
          addVertex(lastPointR, u0, 1);
          addVertex(lastPointL, u0, 0);
          addVertex(currentPointR, u1, 1);
          addVertex(lastPointL, u0, 0);
          addVertex(innerPoint, u1, 0);
          addVertex(currentPointR, u1, 1);
          addVertex(currentPointR, u0, 1);
          addVertex(innerPoint, u1, 0);
          addVertex(currentPoint, u1, 0.5);
          addVertex(currentPoint, u1, 0.5);
          addVertex(innerPoint, u1, 0);
          addVertex(nextPointR, u0, 1);
        }
      }
    }
    function addCapGeometry(center, p1, p2, joinIsOnLeftSide2, start, u2) {
      switch (style.strokeLineCap) {
        case "round":
          if (start) {
            makeCircularSector(center, p2, p1, u2, 0.5);
          } else {
            makeCircularSector(center, p1, p2, u2, 0.5);
          }
          break;
        case "square":
          if (start) {
            tempV2_1.subVectors(p1, center);
            tempV2_2.set(tempV2_1.y, -tempV2_1.x);
            tempV2_3.addVectors(tempV2_1, tempV2_2).add(center);
            tempV2_4.subVectors(tempV2_2, tempV2_1).add(center);
            if (joinIsOnLeftSide2) {
              tempV2_3.toArray(vertices, 1 * 3);
              tempV2_4.toArray(vertices, 0 * 3);
              tempV2_4.toArray(vertices, 3 * 3);
            } else {
              tempV2_3.toArray(vertices, 1 * 3);
              uvs[3 * 2 + 1] === 1 ? tempV2_4.toArray(vertices, 3 * 3) : tempV2_3.toArray(vertices, 3 * 3);
              tempV2_4.toArray(vertices, 0 * 3);
            }
          } else {
            tempV2_1.subVectors(p2, center);
            tempV2_2.set(tempV2_1.y, -tempV2_1.x);
            tempV2_3.addVectors(tempV2_1, tempV2_2).add(center);
            tempV2_4.subVectors(tempV2_2, tempV2_1).add(center);
            const vl = vertices.length;
            if (joinIsOnLeftSide2) {
              tempV2_3.toArray(vertices, vl - 1 * 3);
              tempV2_4.toArray(vertices, vl - 2 * 3);
              tempV2_4.toArray(vertices, vl - 4 * 3);
            } else {
              tempV2_4.toArray(vertices, vl - 2 * 3);
              tempV2_3.toArray(vertices, vl - 1 * 3);
              tempV2_4.toArray(vertices, vl - 4 * 3);
            }
          }
          break;
        case "butt":
        default:
          break;
      }
    }
    function removeDuplicatedPoints(points2) {
      let dupPoints = false;
      for (let i = 1, n2 = points2.length - 1; i < n2; i++) {
        if (points2[i].distanceTo(points2[i + 1]) < minDistance) {
          dupPoints = true;
          break;
        }
      }
      if (!dupPoints) return points2;
      const newPoints = [];
      newPoints.push(points2[0]);
      for (let i = 1, n2 = points2.length - 1; i < n2; i++) {
        if (points2[i].distanceTo(points2[i + 1]) >= minDistance) {
          newPoints.push(points2[i]);
        }
      }
      newPoints.push(points2[points2.length - 1]);
      return newPoints;
    }
  }
};

// node_modules/three/examples/jsm/loaders/TDSLoader.js
var TDSLoader = class extends Loader {
  /**
   * Constructs a new 3DS loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.debug = false;
    this.group = null;
    this.materials = [];
    this.meshes = [];
  }
  /**
   * Starts loading from the given URL and passes the loaded 3DS asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Group)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(data2) {
      try {
        onLoad(scope.parse(data2, path));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given 3DS data and returns the resulting data.
   *
   * @param {ArrayBuffer} arraybuffer - The raw 3DS data as an array buffer.
   * @param {string} path - The asset path.
   * @return {Group} The parsed asset represented as a group.
   */
  parse(arraybuffer, path) {
    this.group = new Group();
    this.materials = [];
    this.meshes = [];
    this.readFile(arraybuffer, path);
    for (let i = 0; i < this.meshes.length; i++) {
      this.group.add(this.meshes[i]);
    }
    return this.group;
  }
  /**
   * Decode file content to read 3ds data.
   *
   * @private
   * @param {ArrayBuffer} arraybuffer - Arraybuffer data to be loaded.
   * @param {string} path - Path for external resources.
   */
  readFile(arraybuffer, path) {
    const data2 = new DataView(arraybuffer);
    const chunk = new Chunk(data2, 0, this.debugMessage);
    if (chunk.id === MLIBMAGIC || chunk.id === CMAGIC || chunk.id === M3DMAGIC) {
      let next = chunk.readChunk();
      while (next) {
        if (next.id === M3D_VERSION) {
          const version = next.readDWord();
          this.debugMessage("3DS file version: " + version);
        } else if (next.id === MDATA) {
          this.readMeshData(next, path);
        } else {
          this.debugMessage("Unknown main chunk: " + next.hexId);
        }
        next = chunk.readChunk();
      }
    }
    this.debugMessage("Parsed " + this.meshes.length + " meshes");
  }
  /**
   * Read mesh data chunk.
   *
   * @private
   * @param {Chunk} chunk - to read mesh from
   * @param {string} path - Path for external resources.
   */
  readMeshData(chunk, path) {
    let next = chunk.readChunk();
    while (next) {
      if (next.id === MESH_VERSION) {
        const version = +next.readDWord();
        this.debugMessage("Mesh Version: " + version);
      } else if (next.id === MASTER_SCALE) {
        const scale2 = next.readFloat();
        this.debugMessage("Master scale: " + scale2);
        this.group.scale.set(scale2, scale2, scale2);
      } else if (next.id === NAMED_OBJECT) {
        this.debugMessage("Named Object");
        this.readNamedObject(next);
      } else if (next.id === MAT_ENTRY) {
        this.debugMessage("Material");
        this.readMaterialEntry(next, path);
      } else {
        this.debugMessage("Unknown MDATA chunk: " + next.hexId);
      }
      next = chunk.readChunk();
    }
  }
  /**
   * Read named object chunk.
   *
   * @private
   * @param {Chunk} chunk - Chunk in use.
   */
  readNamedObject(chunk) {
    const name2 = chunk.readString();
    let next = chunk.readChunk();
    while (next) {
      if (next.id === N_TRI_OBJECT) {
        const mesh = this.readMesh(next);
        mesh.name = name2;
        this.meshes.push(mesh);
      } else {
        this.debugMessage("Unknown named object chunk: " + next.hexId);
      }
      next = chunk.readChunk();
    }
  }
  /**
   * Read material data chunk and add it to the material list.
   *
   * @private
   * @param {Chunk} chunk - Chunk in use.
   * @param {string} path - Path for external resources.
   */
  readMaterialEntry(chunk, path) {
    let next = chunk.readChunk();
    const material = new MeshPhongMaterial();
    while (next) {
      if (next.id === MAT_NAME) {
        material.name = next.readString();
        this.debugMessage("   Name: " + material.name);
      } else if (next.id === MAT_WIRE) {
        this.debugMessage("   Wireframe");
        material.wireframe = true;
      } else if (next.id === MAT_WIRE_SIZE) {
        const value2 = next.readByte();
        material.wireframeLinewidth = value2;
        this.debugMessage("   Wireframe Thickness: " + value2);
      } else if (next.id === MAT_TWO_SIDE) {
        material.side = DoubleSide;
        this.debugMessage("   DoubleSided");
      } else if (next.id === MAT_ADDITIVE) {
        this.debugMessage("   Additive Blending");
        material.blending = AdditiveBlending;
      } else if (next.id === MAT_DIFFUSE) {
        this.debugMessage("   Diffuse Color");
        material.color = this.readColor(next);
      } else if (next.id === MAT_SPECULAR) {
        this.debugMessage("   Specular Color");
        material.specular = this.readColor(next);
      } else if (next.id === MAT_AMBIENT) {
        this.debugMessage("   Ambient color");
        material.color = this.readColor(next);
      } else if (next.id === MAT_SHININESS) {
        const shininess = this.readPercentage(next);
        material.shininess = shininess * 100;
        this.debugMessage("   Shininess : " + shininess);
      } else if (next.id === MAT_TRANSPARENCY) {
        const transparency = this.readPercentage(next);
        material.opacity = 1 - transparency;
        this.debugMessage("  Transparency : " + transparency);
        material.transparent = material.opacity < 1 ? true : false;
      } else if (next.id === MAT_TEXMAP) {
        this.debugMessage("   ColorMap");
        material.map = this.readMap(next, path);
      } else if (next.id === MAT_BUMPMAP) {
        this.debugMessage("   BumpMap");
        material.bumpMap = this.readMap(next, path);
      } else if (next.id === MAT_OPACMAP) {
        this.debugMessage("   OpacityMap");
        material.alphaMap = this.readMap(next, path);
      } else if (next.id === MAT_SPECMAP) {
        this.debugMessage("   SpecularMap");
        material.specularMap = this.readMap(next, path);
      } else {
        this.debugMessage("   Unknown material chunk: " + next.hexId);
      }
      next = chunk.readChunk();
    }
    this.materials[material.name] = material;
  }
  /**
   * Read mesh data chunk.
   *
   * @private
   * @param {Chunk} chunk - Chunk in use.
   * @return {Mesh} - The parsed mesh.
   */
  readMesh(chunk) {
    let next = chunk.readChunk();
    const geometry = new BufferGeometry();
    const material = new MeshPhongMaterial();
    const mesh = new Mesh(geometry, material);
    mesh.name = "mesh";
    while (next) {
      if (next.id === POINT_ARRAY) {
        const points = next.readWord();
        this.debugMessage("   Vertex: " + points);
        const vertices = [];
        for (let i = 0; i < points; i++) {
          vertices.push(next.readFloat());
          vertices.push(next.readFloat());
          vertices.push(next.readFloat());
        }
        geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
      } else if (next.id === FACE_ARRAY) {
        this.readFaceArray(next, mesh);
      } else if (next.id === TEX_VERTS) {
        const texels = next.readWord();
        this.debugMessage("   UV: " + texels);
        const uvs = [];
        for (let i = 0; i < texels; i++) {
          uvs.push(next.readFloat());
          uvs.push(next.readFloat());
        }
        geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
      } else if (next.id === MESH_MATRIX) {
        this.debugMessage("   Transformation Matrix (TODO)");
        const values2 = [];
        for (let i = 0; i < 12; i++) {
          values2[i] = next.readFloat();
        }
        const matrix2 = new Matrix4();
        matrix2.elements[0] = values2[0];
        matrix2.elements[1] = values2[6];
        matrix2.elements[2] = values2[3];
        matrix2.elements[3] = values2[9];
        matrix2.elements[4] = values2[2];
        matrix2.elements[5] = values2[8];
        matrix2.elements[6] = values2[5];
        matrix2.elements[7] = values2[11];
        matrix2.elements[8] = values2[1];
        matrix2.elements[9] = values2[7];
        matrix2.elements[10] = values2[4];
        matrix2.elements[11] = values2[10];
        matrix2.elements[12] = 0;
        matrix2.elements[13] = 0;
        matrix2.elements[14] = 0;
        matrix2.elements[15] = 1;
        matrix2.transpose();
        const inverse2 = new Matrix4();
        inverse2.copy(matrix2).invert();
        geometry.applyMatrix4(inverse2);
        matrix2.decompose(mesh.position, mesh.quaternion, mesh.scale);
      } else {
        this.debugMessage("   Unknown mesh chunk: " + next.hexId);
      }
      next = chunk.readChunk();
    }
    geometry.computeVertexNormals();
    return mesh;
  }
  /**
   * Read face array data chunk.
   *
   * @private
   * @param {Chunk} chunk - Chunk in use.
   * @param {Mesh} mesh - Mesh to be filled with the data read.
   */
  readFaceArray(chunk, mesh) {
    const faces = chunk.readWord();
    this.debugMessage("   Faces: " + faces);
    const index2 = [];
    for (let i = 0; i < faces; ++i) {
      index2.push(chunk.readWord(), chunk.readWord(), chunk.readWord());
      chunk.readWord();
    }
    mesh.geometry.setIndex(index2);
    let materialIndex = 0;
    let start = 0;
    while (!chunk.endOfChunk) {
      const subchunk = chunk.readChunk();
      if (subchunk.id === MSH_MAT_GROUP) {
        this.debugMessage("      Material Group");
        const group = this.readMaterialGroup(subchunk);
        const count = group.index.length * 3;
        mesh.geometry.addGroup(start, count, materialIndex);
        start += count;
        materialIndex++;
        const material = this.materials[group.name];
        if (Array.isArray(mesh.material) === false) mesh.material = [];
        if (material !== void 0) {
          mesh.material.push(material);
        }
      } else {
        this.debugMessage("      Unknown face array chunk: " + subchunk.hexId);
      }
    }
    if (mesh.material.length === 1) mesh.material = mesh.material[0];
  }
  /**
   * Read texture map data chunk.
   *
   * @private
   * @param {Chunk} chunk - Chunk in use.
   * @param {string} path - Path for external resources.
   * @return {Texture} Texture read from this data chunk.
   */
  readMap(chunk, path) {
    let next = chunk.readChunk();
    let texture = {};
    const loader = new TextureLoader(this.manager);
    loader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
    while (next) {
      if (next.id === MAT_MAPNAME) {
        const name2 = next.readString();
        texture = loader.load(name2);
        this.debugMessage("      File: " + path + name2);
      } else if (next.id === MAT_MAP_UOFFSET) {
        texture.offset.x = next.readFloat();
        this.debugMessage("      OffsetX: " + texture.offset.x);
      } else if (next.id === MAT_MAP_VOFFSET) {
        texture.offset.y = next.readFloat();
        this.debugMessage("      OffsetY: " + texture.offset.y);
      } else if (next.id === MAT_MAP_USCALE) {
        texture.repeat.x = next.readFloat();
        this.debugMessage("      RepeatX: " + texture.repeat.x);
      } else if (next.id === MAT_MAP_VSCALE) {
        texture.repeat.y = next.readFloat();
        this.debugMessage("      RepeatY: " + texture.repeat.y);
      } else {
        this.debugMessage("      Unknown map chunk: " + next.hexId);
      }
      next = chunk.readChunk();
    }
    return texture;
  }
  /**
   * Read material group data chunk.
   *
   * @private
   * @param {Chunk} chunk - Chunk in use.
   * @return {Object} Object with name and index of the object.
   */
  readMaterialGroup(chunk) {
    const name2 = chunk.readString();
    const numFaces = chunk.readWord();
    this.debugMessage("         Name: " + name2);
    this.debugMessage("         Faces: " + numFaces);
    const index2 = [];
    for (let i = 0; i < numFaces; ++i) {
      index2.push(chunk.readWord());
    }
    return { name: name2, index: index2 };
  }
  /**
   * Read a color value.
   *
   * @private
   * @param {Chunk} chunk - Chunk.
   * @return {Color} Color value read.
   */
  readColor(chunk) {
    const subChunk = chunk.readChunk();
    const color = new Color();
    if (subChunk.id === COLOR_24 || subChunk.id === LIN_COLOR_24) {
      const r = subChunk.readByte();
      const g3 = subChunk.readByte();
      const b3 = subChunk.readByte();
      color.setRGB(r / 255, g3 / 255, b3 / 255);
      this.debugMessage("      Color: " + color.r + ", " + color.g + ", " + color.b);
    } else if (subChunk.id === COLOR_F || subChunk.id === LIN_COLOR_F) {
      const r = subChunk.readFloat();
      const g3 = subChunk.readFloat();
      const b3 = subChunk.readFloat();
      color.setRGB(r, g3, b3);
      this.debugMessage("      Color: " + color.r + ", " + color.g + ", " + color.b);
    } else {
      this.debugMessage("      Unknown color chunk: " + subChunk.hexId);
    }
    return color;
  }
  /**
   * Read percentage value.
   *
   * @private
   * @param {Chunk} chunk - Chunk to read data from.
   * @return {number} Data read from the dataview.
   */
  readPercentage(chunk) {
    const subChunk = chunk.readChunk();
    switch (subChunk.id) {
      case INT_PERCENTAGE:
        return subChunk.readShort() / 100;
        break;
      case FLOAT_PERCENTAGE:
        return subChunk.readFloat();
        break;
      default:
        this.debugMessage("      Unknown percentage chunk: " + subChunk.hexId);
        return 0;
    }
  }
  /**
   * Print debug message to the console.
   *
   * Is controlled by a flag to show or hide debug messages.
   *
   * @private
   * @param {Object} message - Debug message to print to the console.
   */
  debugMessage(message) {
    if (this.debug) {
      console.log(message);
    }
  }
};
var Chunk = class _Chunk {
  /**
   * Create a new chunk
   *
   * @private
   * @param {DataView} data - DataView to read from.
   * @param {number} position - In data.
   * @param {Function} debugMessage - Logging callback.
   */
  constructor(data2, position2, debugMessage) {
    this.data = data2;
    this.offset = position2;
    this.position = position2;
    this.debugMessage = debugMessage;
    if (this.debugMessage instanceof Function) {
      this.debugMessage = function() {
      };
    }
    this.id = this.readWord();
    this.size = this.readDWord();
    this.end = this.offset + this.size;
    if (this.end > data2.byteLength) {
      this.debugMessage("Bad chunk size for chunk at " + position2);
    }
  }
  /**
   * Reads a sub cchunk.
   *
   * @private
   * @return {Chunk | null} next sub chunk.
   */
  readChunk() {
    if (this.endOfChunk) {
      return null;
    }
    try {
      const next = new _Chunk(this.data, this.position, this.debugMessage);
      this.position += next.size;
      return next;
    } catch (e) {
      this.debugMessage("Unable to read chunk at " + this.position);
      return null;
    }
  }
  /**
   * Returns the ID of this chunk as Hex
   *
   * @private
   * @return {string} hex-string of id
   */
  get hexId() {
    return this.id.toString(16);
  }
  get endOfChunk() {
    return this.position >= this.end;
  }
  /**
   * Read byte value.
   *
   * @private
   * @return {number} Data read from the dataview.
   */
  readByte() {
    const v = this.data.getUint8(this.position, true);
    this.position += 1;
    return v;
  }
  /**
   * Read 32 bit float value.
   *
   * @private
   * @return {number} Data read from the dataview.
   */
  readFloat() {
    try {
      const v = this.data.getFloat32(this.position, true);
      this.position += 4;
      return v;
    } catch (e) {
      this.debugMessage(e + " " + this.position + " " + this.data.byteLength);
      return 0;
    }
  }
  /**
   * Read 32 bit signed integer value.
   *
   * @private
   * @return {number} Data read from the dataview.
   */
  readInt() {
    const v = this.data.getInt32(this.position, true);
    this.position += 4;
    return v;
  }
  /**
   * Read 16 bit signed integer value.
   *
   * @private
   * @return {number} Data read from the dataview.
   */
  readShort() {
    const v = this.data.getInt16(this.position, true);
    this.position += 2;
    return v;
  }
  /**
   * Read 64 bit unsigned integer value.
   *
   * @private
   * @return {number} Data read from the dataview.
   */
  readDWord() {
    const v = this.data.getUint32(this.position, true);
    this.position += 4;
    return v;
  }
  /**
   * Read 32 bit unsigned integer value.
   *
   * @private
   * @return {number} Data read from the dataview.
   */
  readWord() {
    const v = this.data.getUint16(this.position, true);
    this.position += 2;
    return v;
  }
  /**
   * Read NULL terminated ASCII string value from chunk-pos.
   *
   * @private
   * @return {string} Data read from the dataview.
   */
  readString() {
    let s = "";
    let c2 = this.readByte();
    while (c2) {
      s += String.fromCharCode(c2);
      c2 = this.readByte();
    }
    return s;
  }
};
var M3DMAGIC = 19789;
var MLIBMAGIC = 15786;
var CMAGIC = 49725;
var M3D_VERSION = 2;
var COLOR_F = 16;
var COLOR_24 = 17;
var LIN_COLOR_24 = 18;
var LIN_COLOR_F = 19;
var INT_PERCENTAGE = 48;
var FLOAT_PERCENTAGE = 49;
var MDATA = 15677;
var MESH_VERSION = 15678;
var MASTER_SCALE = 256;
var MAT_ENTRY = 45055;
var MAT_NAME = 40960;
var MAT_AMBIENT = 40976;
var MAT_DIFFUSE = 40992;
var MAT_SPECULAR = 41008;
var MAT_SHININESS = 41024;
var MAT_TRANSPARENCY = 41040;
var MAT_TWO_SIDE = 41089;
var MAT_ADDITIVE = 41091;
var MAT_WIRE = 41093;
var MAT_WIRE_SIZE = 41095;
var MAT_TEXMAP = 41472;
var MAT_OPACMAP = 41488;
var MAT_BUMPMAP = 41520;
var MAT_SPECMAP = 41476;
var MAT_MAPNAME = 41728;
var MAT_MAP_USCALE = 41812;
var MAT_MAP_VSCALE = 41814;
var MAT_MAP_UOFFSET = 41816;
var MAT_MAP_VOFFSET = 41818;
var NAMED_OBJECT = 16384;
var N_TRI_OBJECT = 16640;
var POINT_ARRAY = 16656;
var FACE_ARRAY = 16672;
var MSH_MAT_GROUP = 16688;
var TEX_VERTS = 16704;
var MESH_MATRIX = 16736;

// node_modules/three/examples/jsm/libs/utif.module.js
var UTIF = {};
(function() {
  "use strict";
  var W = function a1() {
    function W2(p) {
      this.message = "JPEG error: " + p;
    }
    W2.prototype = new Error();
    W2.prototype.name = "JpegError";
    W2.constructor = W2;
    return W2;
  }(), ak = function ag() {
    var p = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t3 = 4017, ac = 799, ah = 3406, ao = 2276, ar = 1567, ai = 3784, s = 5793, ad = 2896;
    function ak2(Q2) {
      if (Q2 == null) Q2 = {};
      if (Q2.w == null) Q2.w = -1;
      this.V = Q2.n;
      this.N = Q2.w;
    }
    function a5(Q2, h) {
      var f = 0, G2 = [], n2, E, a3 = 16, F;
      while (a3 > 0 && !Q2[a3 - 1]) {
        a3--;
      }
      G2.push({ children: [], index: 0 });
      var C3 = G2[0];
      for (n2 = 0; n2 < a3; n2++) {
        for (E = 0; E < Q2[n2]; E++) {
          C3 = G2.pop();
          C3.children[C3.index] = h[f];
          while (C3.index > 0) {
            C3 = G2.pop();
          }
          C3.index++;
          G2.push(C3);
          while (G2.length <= n2) {
            G2.push(F = { children: [], index: 0 });
            C3.children[C3.index] = F.children;
            C3 = F;
          }
          f++;
        }
        if (n2 + 1 < a3) {
          G2.push(F = { children: [], index: 0 });
          C3.children[C3.index] = F.children;
          C3 = F;
        }
      }
      return G2[0].children;
    }
    function a2(Q2, h, f) {
      return 64 * ((Q2.P + 1) * h + f);
    }
    function a7(Q2, h, f, G2, n2, E, a3, C3, F, d) {
      if (d == null) d = false;
      var T2 = f.m, U = f.Z, z = h, J = 0, V = 0, r = 0, D = 0, a8, q2 = 0, X, O, _, N, e, K, x2 = 0, k2, g3, R4, c2;
      function Y() {
        if (V > 0) {
          V--;
          return J >> V & 1;
        }
        J = Q2[h++];
        if (J === 255) {
          var I2 = Q2[h++];
          if (I2) {
            if (I2 === 220 && d) {
              h += 2;
              var l2 = Z2(Q2, h);
              h += 2;
              if (l2 > 0 && l2 !== f.s) {
                throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", l2);
              }
            } else if (I2 === 217) {
              if (d) {
                var M = q2 * 8;
                if (M > 0 && M < f.s / 10) {
                  throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter", M);
                }
              }
              throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data");
            }
            throw new W("unexpected marker");
          }
        }
        V = 7;
        return J >>> 7;
      }
      function u2(I2) {
        var l2 = I2;
        while (true) {
          l2 = l2[Y()];
          switch (typeof l2) {
            case "number":
              return l2;
            case "object":
              continue;
          }
          throw new W("invalid huffman sequence");
        }
      }
      function m(I2) {
        var e2 = 0;
        while (I2 > 0) {
          e2 = e2 << 1 | Y();
          I2--;
        }
        return e2;
      }
      function j2(I2) {
        if (I2 === 1) {
          return Y() === 1 ? 1 : -1;
        }
        var e2 = m(I2);
        if (e2 >= 1 << I2 - 1) {
          return e2;
        }
        return e2 + (-1 << I2) + 1;
      }
      function v(X2, I2) {
        var l2 = u2(X2.J), M = l2 === 0 ? 0 : j2(l2), N2 = 1;
        X2.D[I2] = X2.Q += M;
        while (N2 < 64) {
          var S = u2(X2.i), i = S & 15, A2 = S >> 4;
          if (i === 0) {
            if (A2 < 15) {
              break;
            }
            N2 += 16;
            continue;
          }
          N2 += A2;
          var o = p[N2];
          X2.D[I2 + o] = j2(i);
          N2++;
        }
      }
      function $2(X2, I2) {
        var l2 = u2(X2.J), M = l2 === 0 ? 0 : j2(l2) << F;
        X2.D[I2] = X2.Q += M;
      }
      function b3(X2, I2) {
        X2.D[I2] |= Y() << F;
      }
      function P(X2, I2) {
        if (r > 0) {
          r--;
          return;
        }
        var N2 = E, l2 = a3;
        while (N2 <= l2) {
          var M = u2(X2.i), S = M & 15, i = M >> 4;
          if (S === 0) {
            if (i < 15) {
              r = m(i) + (1 << i) - 1;
              break;
            }
            N2 += 16;
            continue;
          }
          N2 += i;
          var A2 = p[N2];
          X2.D[I2 + A2] = j2(S) * (1 << F);
          N2++;
        }
      }
      function a4(X2, I2) {
        var N2 = E, l2 = a3, M = 0, S, i;
        while (N2 <= l2) {
          var A2 = I2 + p[N2], o = X2.D[A2] < 0 ? -1 : 1;
          switch (D) {
            case 0:
              i = u2(X2.i);
              S = i & 15;
              M = i >> 4;
              if (S === 0) {
                if (M < 15) {
                  r = m(M) + (1 << M);
                  D = 4;
                } else {
                  M = 16;
                  D = 1;
                }
              } else {
                if (S !== 1) {
                  throw new W("invalid ACn encoding");
                }
                a8 = j2(S);
                D = M ? 2 : 3;
              }
              continue;
            case 1:
            case 2:
              if (X2.D[A2]) {
                X2.D[A2] += o * (Y() << F);
              } else {
                M--;
                if (M === 0) {
                  D = D === 2 ? 3 : 0;
                }
              }
              break;
            case 3:
              if (X2.D[A2]) {
                X2.D[A2] += o * (Y() << F);
              } else {
                X2.D[A2] = a8 << F;
                D = 0;
              }
              break;
            case 4:
              if (X2.D[A2]) {
                X2.D[A2] += o * (Y() << F);
              }
              break;
          }
          N2++;
        }
        if (D === 4) {
          r--;
          if (r === 0) {
            D = 0;
          }
        }
      }
      function H(X2, I2, x3, l2, M) {
        var S = x3 / T2 | 0, i = x3 % T2;
        q2 = S * X2.A + l2;
        var A2 = i * X2.h + M, o = a2(X2, q2, A2);
        I2(X2, o);
      }
      function w(X2, I2, x3) {
        q2 = x3 / X2.P | 0;
        var l2 = x3 % X2.P, M = a2(X2, q2, l2);
        I2(X2, M);
      }
      var y = G2.length;
      if (U) {
        if (E === 0) {
          K = C3 === 0 ? $2 : b3;
        } else {
          K = C3 === 0 ? P : a4;
        }
      } else {
        K = v;
      }
      if (y === 1) {
        g3 = G2[0].P * G2[0].c;
      } else {
        g3 = T2 * f.R;
      }
      while (x2 <= g3) {
        var L = n2 ? Math.min(g3 - x2, n2) : g3;
        if (L > 0) {
          for (O = 0; O < y; O++) {
            G2[O].Q = 0;
          }
          r = 0;
          if (y === 1) {
            X = G2[0];
            for (e = 0; e < L; e++) {
              w(X, K, x2);
              x2++;
            }
          } else {
            for (e = 0; e < L; e++) {
              for (O = 0; O < y; O++) {
                X = G2[O];
                R4 = X.h;
                c2 = X.A;
                for (_ = 0; _ < c2; _++) {
                  for (N = 0; N < R4; N++) {
                    H(X, K, x2, _, N);
                  }
                }
              }
              x2++;
            }
          }
        }
        V = 0;
        k2 = an(Q2, h);
        if (!k2) {
          break;
        }
        if (k2.u) {
          var a6 = L > 0 ? "unexpected" : "excessive";
          h = k2.offset;
        }
        if (k2.M >= 65488 && k2.M <= 65495) {
          h += 2;
        } else {
          break;
        }
      }
      return h - z;
    }
    function al(Q2, h, f) {
      var G2 = Q2.$, n2 = Q2.D, E, a3, C3, F, d, T2, U, z, J, V, Y, u2, m, j2, v, $2, b3;
      if (!G2) {
        throw new W("missing required Quantization Table.");
      }
      for (var r = 0; r < 64; r += 8) {
        J = n2[h + r];
        V = n2[h + r + 1];
        Y = n2[h + r + 2];
        u2 = n2[h + r + 3];
        m = n2[h + r + 4];
        j2 = n2[h + r + 5];
        v = n2[h + r + 6];
        $2 = n2[h + r + 7];
        J *= G2[r];
        if ((V | Y | u2 | m | j2 | v | $2) === 0) {
          b3 = s * J + 512 >> 10;
          f[r] = b3;
          f[r + 1] = b3;
          f[r + 2] = b3;
          f[r + 3] = b3;
          f[r + 4] = b3;
          f[r + 5] = b3;
          f[r + 6] = b3;
          f[r + 7] = b3;
          continue;
        }
        V *= G2[r + 1];
        Y *= G2[r + 2];
        u2 *= G2[r + 3];
        m *= G2[r + 4];
        j2 *= G2[r + 5];
        v *= G2[r + 6];
        $2 *= G2[r + 7];
        E = s * J + 128 >> 8;
        a3 = s * m + 128 >> 8;
        C3 = Y;
        F = v;
        d = ad * (V - $2) + 128 >> 8;
        z = ad * (V + $2) + 128 >> 8;
        T2 = u2 << 4;
        U = j2 << 4;
        E = E + a3 + 1 >> 1;
        a3 = E - a3;
        b3 = C3 * ai + F * ar + 128 >> 8;
        C3 = C3 * ar - F * ai + 128 >> 8;
        F = b3;
        d = d + U + 1 >> 1;
        U = d - U;
        z = z + T2 + 1 >> 1;
        T2 = z - T2;
        E = E + F + 1 >> 1;
        F = E - F;
        a3 = a3 + C3 + 1 >> 1;
        C3 = a3 - C3;
        b3 = d * ao + z * ah + 2048 >> 12;
        d = d * ah - z * ao + 2048 >> 12;
        z = b3;
        b3 = T2 * ac + U * t3 + 2048 >> 12;
        T2 = T2 * t3 - U * ac + 2048 >> 12;
        U = b3;
        f[r] = E + z;
        f[r + 7] = E - z;
        f[r + 1] = a3 + U;
        f[r + 6] = a3 - U;
        f[r + 2] = C3 + T2;
        f[r + 5] = C3 - T2;
        f[r + 3] = F + d;
        f[r + 4] = F - d;
      }
      for (var P = 0; P < 8; ++P) {
        J = f[P];
        V = f[P + 8];
        Y = f[P + 16];
        u2 = f[P + 24];
        m = f[P + 32];
        j2 = f[P + 40];
        v = f[P + 48];
        $2 = f[P + 56];
        if ((V | Y | u2 | m | j2 | v | $2) === 0) {
          b3 = s * J + 8192 >> 14;
          if (b3 < -2040) {
            b3 = 0;
          } else if (b3 >= 2024) {
            b3 = 255;
          } else {
            b3 = b3 + 2056 >> 4;
          }
          n2[h + P] = b3;
          n2[h + P + 8] = b3;
          n2[h + P + 16] = b3;
          n2[h + P + 24] = b3;
          n2[h + P + 32] = b3;
          n2[h + P + 40] = b3;
          n2[h + P + 48] = b3;
          n2[h + P + 56] = b3;
          continue;
        }
        E = s * J + 2048 >> 12;
        a3 = s * m + 2048 >> 12;
        C3 = Y;
        F = v;
        d = ad * (V - $2) + 2048 >> 12;
        z = ad * (V + $2) + 2048 >> 12;
        T2 = u2;
        U = j2;
        E = (E + a3 + 1 >> 1) + 4112;
        a3 = E - a3;
        b3 = C3 * ai + F * ar + 2048 >> 12;
        C3 = C3 * ar - F * ai + 2048 >> 12;
        F = b3;
        d = d + U + 1 >> 1;
        U = d - U;
        z = z + T2 + 1 >> 1;
        T2 = z - T2;
        E = E + F + 1 >> 1;
        F = E - F;
        a3 = a3 + C3 + 1 >> 1;
        C3 = a3 - C3;
        b3 = d * ao + z * ah + 2048 >> 12;
        d = d * ah - z * ao + 2048 >> 12;
        z = b3;
        b3 = T2 * ac + U * t3 + 2048 >> 12;
        T2 = T2 * t3 - U * ac + 2048 >> 12;
        U = b3;
        J = E + z;
        $2 = E - z;
        V = a3 + U;
        v = a3 - U;
        Y = C3 + T2;
        j2 = C3 - T2;
        u2 = F + d;
        m = F - d;
        if (J < 16) {
          J = 0;
        } else if (J >= 4080) {
          J = 255;
        } else {
          J >>= 4;
        }
        if (V < 16) {
          V = 0;
        } else if (V >= 4080) {
          V = 255;
        } else {
          V >>= 4;
        }
        if (Y < 16) {
          Y = 0;
        } else if (Y >= 4080) {
          Y = 255;
        } else {
          Y >>= 4;
        }
        if (u2 < 16) {
          u2 = 0;
        } else if (u2 >= 4080) {
          u2 = 255;
        } else {
          u2 >>= 4;
        }
        if (m < 16) {
          m = 0;
        } else if (m >= 4080) {
          m = 255;
        } else {
          m >>= 4;
        }
        if (j2 < 16) {
          j2 = 0;
        } else if (j2 >= 4080) {
          j2 = 255;
        } else {
          j2 >>= 4;
        }
        if (v < 16) {
          v = 0;
        } else if (v >= 4080) {
          v = 255;
        } else {
          v >>= 4;
        }
        if ($2 < 16) {
          $2 = 0;
        } else if ($2 >= 4080) {
          $2 = 255;
        } else {
          $2 >>= 4;
        }
        n2[h + P] = J;
        n2[h + P + 8] = V;
        n2[h + P + 16] = Y;
        n2[h + P + 24] = u2;
        n2[h + P + 32] = m;
        n2[h + P + 40] = j2;
        n2[h + P + 48] = v;
        n2[h + P + 56] = $2;
      }
    }
    function a0(Q2, h) {
      var f = h.P, G2 = h.c, n2 = new Int16Array(64);
      for (var E = 0; E < G2; E++) {
        for (var a3 = 0; a3 < f; a3++) {
          var C3 = a2(h, E, a3);
          al(h, C3, n2);
        }
      }
      return h.D;
    }
    function an(Q2, h, f) {
      if (f == null) f = h;
      var G2 = Q2.length - 1, n2 = f < h ? f : h;
      if (h >= G2) {
        return null;
      }
      var E = Z2(Q2, h);
      if (E >= 65472 && E <= 65534) {
        return { u: null, M: E, offset: h };
      }
      var a3 = Z2(Q2, n2);
      while (!(a3 >= 65472 && a3 <= 65534)) {
        if (++n2 >= G2) {
          return null;
        }
        a3 = Z2(Q2, n2);
      }
      return { u: E.toString(16), M: a3, offset: n2 };
    }
    ak2.prototype = { parse(Q2, h) {
      if (h == null) h = {};
      var f = h.F, E = 0, a3 = null, C3 = null, F, d, T2 = 0;
      function G2() {
        var o = Z2(Q2, E);
        E += 2;
        var B2 = E + o - 2, V2 = an(Q2, B2, E);
        if (V2 && V2.u) {
          B2 = V2.offset;
        }
        var ab = Q2.subarray(E, B2);
        E += ab.length;
        return ab;
      }
      function n2(F2) {
        var o = Math.ceil(F2.o / 8 / F2.X), B2 = Math.ceil(F2.s / 8 / F2.B);
        for (var Y2 = 0; Y2 < F2.W.length; Y2++) {
          R4 = F2.W[Y2];
          var ab = Math.ceil(Math.ceil(F2.o / 8) * R4.h / F2.X), af = Math.ceil(Math.ceil(F2.s / 8) * R4.A / F2.B), ap = o * R4.h, aq = B2 * R4.A, ae2 = 64 * aq * (ap + 1);
          R4.D = new Int16Array(ae2);
          R4.P = ab;
          R4.c = af;
        }
        F2.m = o;
        F2.R = B2;
      }
      var U = [], z = [], J = [], V = Z2(Q2, E);
      E += 2;
      if (V !== 65496) {
        throw new W("SOI not found");
      }
      V = Z2(Q2, E);
      E += 2;
      markerLoop: while (V !== 65497) {
        var Y, u2, m;
        switch (V) {
          case 65504:
          case 65505:
          case 65506:
          case 65507:
          case 65508:
          case 65509:
          case 65510:
          case 65511:
          case 65512:
          case 65513:
          case 65514:
          case 65515:
          case 65516:
          case 65517:
          case 65518:
          case 65519:
          case 65534:
            var j2 = G2();
            if (V === 65504) {
              if (j2[0] === 74 && j2[1] === 70 && j2[2] === 73 && j2[3] === 70 && j2[4] === 0) {
                a3 = { version: { d: j2[5], T: j2[6] }, K: j2[7], j: j2[8] << 8 | j2[9], H: j2[10] << 8 | j2[11], S: j2[12], I: j2[13], C: j2.subarray(14, 14 + 3 * j2[12] * j2[13]) };
              }
            }
            if (V === 65518) {
              if (j2[0] === 65 && j2[1] === 100 && j2[2] === 111 && j2[3] === 98 && j2[4] === 101) {
                C3 = { version: j2[5] << 8 | j2[6], k: j2[7] << 8 | j2[8], q: j2[9] << 8 | j2[10], a: j2[11] };
              }
            }
            break;
          case 65499:
            var v = Z2(Q2, E), b3;
            E += 2;
            var $2 = v + E - 2;
            while (E < $2) {
              var r = Q2[E++], P = new Uint16Array(64);
              if (r >> 4 === 0) {
                for (u2 = 0; u2 < 64; u2++) {
                  b3 = p[u2];
                  P[b3] = Q2[E++];
                }
              } else if (r >> 4 === 1) {
                for (u2 = 0; u2 < 64; u2++) {
                  b3 = p[u2];
                  P[b3] = Z2(Q2, E);
                  E += 2;
                }
              } else {
                throw new W("DQT - invalid table spec");
              }
              U[r & 15] = P;
            }
            break;
          case 65472:
          case 65473:
          case 65474:
            if (F) {
              throw new W("Only single frame JPEGs supported");
            }
            E += 2;
            F = {};
            F.G = V === 65473;
            F.Z = V === 65474;
            F.precision = Q2[E++];
            var D = Z2(Q2, E), a4, q2 = 0, H = 0;
            E += 2;
            F.s = f || D;
            F.o = Z2(Q2, E);
            E += 2;
            F.W = [];
            F._ = {};
            var a8 = Q2[E++];
            for (Y = 0; Y < a8; Y++) {
              a4 = Q2[E];
              var w = Q2[E + 1] >> 4, y = Q2[E + 1] & 15;
              if (q2 < w) {
                q2 = w;
              }
              if (H < y) {
                H = y;
              }
              var X = Q2[E + 2];
              m = F.W.push({ h: w, A: y, L: X, $: null });
              F._[a4] = m - 1;
              E += 3;
            }
            F.X = q2;
            F.B = H;
            n2(F);
            break;
          case 65476:
            var O = Z2(Q2, E);
            E += 2;
            for (Y = 2; Y < O; ) {
              var _ = Q2[E++], N = new Uint8Array(16), e = 0;
              for (u2 = 0; u2 < 16; u2++, E++) {
                e += N[u2] = Q2[E];
              }
              var K = new Uint8Array(e);
              for (u2 = 0; u2 < e; u2++, E++) {
                K[u2] = Q2[E];
              }
              Y += 17 + e;
              (_ >> 4 === 0 ? J : z)[_ & 15] = a5(N, K);
            }
            break;
          case 65501:
            E += 2;
            d = Z2(Q2, E);
            E += 2;
            break;
          case 65498:
            var x2 = ++T2 === 1 && !f, R4;
            E += 2;
            var k2 = Q2[E++], g3 = [];
            for (Y = 0; Y < k2; Y++) {
              var c2 = Q2[E++], L = F._[c2];
              R4 = F.W[L];
              R4.index = c2;
              var a6 = Q2[E++];
              R4.J = J[a6 >> 4];
              R4.i = z[a6 & 15];
              g3.push(R4);
            }
            var I2 = Q2[E++], l2 = Q2[E++], M = Q2[E++];
            try {
              var S = a7(Q2, E, F, g3, d, I2, l2, M >> 4, M & 15, x2);
              E += S;
            } catch (ex) {
              if (ex instanceof DNLMarkerError) {
                return this.parse(Q2, { F: ex.s });
              } else if (ex instanceof EOIMarkerError) {
                break markerLoop;
              }
              throw ex;
            }
            break;
          case 65500:
            E += 4;
            break;
          case 65535:
            if (Q2[E] !== 255) {
              E--;
            }
            break;
          default:
            var i = an(Q2, E - 2, E - 3);
            if (i && i.u) {
              E = i.offset;
              break;
            }
            if (E >= Q2.length - 1) {
              break markerLoop;
            }
            throw new W("JpegImage.parse - unknown marker: " + V.toString(16));
        }
        V = Z2(Q2, E);
        E += 2;
      }
      this.width = F.o;
      this.height = F.s;
      this.g = a3;
      this.b = C3;
      this.W = [];
      for (Y = 0; Y < F.W.length; Y++) {
        R4 = F.W[Y];
        var A2 = U[R4.L];
        if (A2) {
          R4.$ = A2;
        }
        this.W.push({ index: R4.index, e: a0(F, R4), l: R4.h / F.X, t: R4.A / F.B, P: R4.P, c: R4.c });
      }
      this.p = this.W.length;
      return void 0;
    }, Y(Q2, h, f) {
      if (f == null) f = false;
      var G2 = this.width / Q2, n2 = this.height / h, E, a3, C3, F, d, T2, U, z, J, V, Y = 0, u2, m = this.W.length, j2 = Q2 * h * m, v = new Uint8ClampedArray(j2), $2 = new Uint32Array(Q2), b3 = 4294967288, r;
      for (U = 0; U < m; U++) {
        E = this.W[U];
        a3 = E.l * G2;
        C3 = E.t * n2;
        Y = U;
        u2 = E.e;
        F = E.P + 1 << 3;
        if (a3 !== r) {
          for (d = 0; d < Q2; d++) {
            z = 0 | d * a3;
            $2[d] = (z & b3) << 3 | z & 7;
          }
          r = a3;
        }
        for (T2 = 0; T2 < h; T2++) {
          z = 0 | T2 * C3;
          V = F * (z & b3) | (z & 7) << 3;
          for (d = 0; d < Q2; d++) {
            v[Y] = u2[V + $2[d]];
            Y += m;
          }
        }
      }
      var P = this.V;
      if (!f && m === 4 && !P) {
        P = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]);
      }
      if (P) {
        for (U = 0; U < j2; ) {
          for (z = 0, J = 0; z < m; z++, U++, J += 2) {
            v[U] = (v[U] * P[J] >> 8) + P[J + 1];
          }
        }
      }
      return v;
    }, get f() {
      if (this.b) {
        return !!this.b.a;
      }
      if (this.p === 3) {
        if (this.N === 0) {
          return false;
        } else if (this.W[0].index === 82 && this.W[1].index === 71 && this.W[2].index === 66) {
          return false;
        }
        return true;
      }
      if (this.N === 1) {
        return true;
      }
      return false;
    }, z: function aj(Q2) {
      var h, f, G2;
      for (var n2 = 0, E = Q2.length; n2 < E; n2 += 3) {
        h = Q2[n2];
        f = Q2[n2 + 1];
        G2 = Q2[n2 + 2];
        Q2[n2] = h - 179.456 + 1.402 * G2;
        Q2[n2 + 1] = h + 135.459 - 0.344 * f - 0.714 * G2;
        Q2[n2 + 2] = h - 226.816 + 1.772 * f;
      }
      return Q2;
    }, O: function aa(Q2) {
      var h, f, G2, n2, E = 0;
      for (var a3 = 0, C3 = Q2.length; a3 < C3; a3 += 4) {
        h = Q2[a3];
        f = Q2[a3 + 1];
        G2 = Q2[a3 + 2];
        n2 = Q2[a3 + 3];
        Q2[E++] = -122.67195406894 + f * (-660635669420364e-19 * f + 437130475926232e-18 * G2 - 54080610064599e-18 * h + 48449797120281e-17 * n2 - 0.154362151871126) + G2 * (-957964378445773e-18 * G2 + 817076911346625e-18 * h - 0.00477271405408747 * n2 + 1.53380253221734) + h * (961250184130688e-18 * h - 0.00266257332283933 * n2 + 0.48357088451265) + n2 * (-336197177618394e-18 * n2 + 0.484791561490776);
        Q2[E++] = 107.268039397724 + f * (219927104525741e-19 * f - 640992018297945e-18 * G2 + 659397001245577e-18 * h + 426105652938837e-18 * n2 - 0.176491792462875) + G2 * (-778269941513683e-18 * G2 + 0.00130872261408275 * h + 770482631801132e-18 * n2 - 0.151051492775562) + h * (0.00126935368114843 * h - 0.00265090189010898 * n2 + 0.25802910206845) + n2 * (-318913117588328e-18 * n2 - 0.213742400323665);
        Q2[E++] = -20.810012546947 + f * (-570115196973677e-18 * f - 263409051004589e-19 * G2 + 0.0020741088115012 * h - 0.00288260236853442 * n2 + 0.814272968359295) + G2 * (-153496057440975e-19 * G2 - 132689043961446e-18 * h + 560833691242812e-18 * n2 - 0.195152027534049) + h * (0.00174418132927582 * h - 0.00255243321439347 * n2 + 0.116935020465145) + n2 * (-343531996510555e-18 * n2 + 0.24165260232407);
      }
      return Q2.subarray(0, E);
    }, r: function a3(Q2) {
      var h, f, G2;
      for (var n2 = 0, E = Q2.length; n2 < E; n2 += 4) {
        h = Q2[n2];
        f = Q2[n2 + 1];
        G2 = Q2[n2 + 2];
        Q2[n2] = 434.456 - h - 1.402 * G2;
        Q2[n2 + 1] = 119.541 - h + 0.344 * f + 0.714 * G2;
        Q2[n2 + 2] = 481.816 - h - 1.772 * f;
      }
      return Q2;
    }, U: function as(Q2) {
      var h, f, G2, n2, E = 0;
      for (var a3 = 0, C3 = Q2.length; a3 < C3; a3 += 4) {
        h = Q2[a3];
        f = Q2[a3 + 1];
        G2 = Q2[a3 + 2];
        n2 = Q2[a3 + 3];
        Q2[E++] = 255 + h * (-6747147073602441e-20 * h + 8379262121013727e-19 * f + 2894718188643294e-19 * G2 + 0.003264231057537806 * n2 - 1.1185611867203937) + f * (26374107616089405e-21 * f - 8626949158638572e-20 * G2 - 2748769067499491e-19 * n2 - 0.02155688794978967) + G2 * (-3878099212869363e-20 * G2 - 3267808279485286e-19 * n2 + 0.0686742238595345) - n2 * (3361971776183937e-19 * n2 + 0.7430659151342254);
        Q2[E++] = 255 + h * (13596372813588848e-20 * h + 924537132573585e-18 * f + 10567359618683593e-20 * G2 + 4791864687436512e-19 * n2 - 0.3109689587515875) + f * (-23545346108370344e-20 * f + 2702845253534714e-19 * G2 + 0.0020200308977307156 * n2 - 0.7488052167015494) + G2 * (6834815998235662e-20 * G2 + 15168452363460973e-20 * n2 - 0.09751927774728933) - n2 * (3189131175883281e-19 * n2 + 0.7364883807733168);
        Q2[E++] = 255 + h * (13598650411385307e-21 * h + 12423956175490851e-20 * f + 4751985097583589e-19 * G2 - 36729317476630422e-22 * n2 - 0.05562186980264034) + f * (16141380598724676e-20 * f + 9692239130725186e-19 * G2 + 7782692450036253e-19 * n2 - 0.44015232367526463) + G2 * (5068882914068769e-22 * G2 + 0.0017778369011375071 * n2 - 0.7591454649749609) - n2 * (3435319965105553e-19 * n2 + 0.7063770186160144);
      }
      return Q2.subarray(0, E);
    }, getData: function(Q2) {
      var h = Q2.width, f = Q2.height, G2 = Q2.forceRGB, n2 = Q2.isSourcePDF;
      if (this.p > 4) {
        throw new W("Unsupported color mode");
      }
      var E = this.Y(h, f, n2);
      if (this.p === 1 && G2) {
        var a3 = E.length, C3 = new Uint8ClampedArray(a3 * 3), F = 0;
        for (var d = 0; d < a3; d++) {
          var T2 = E[d];
          C3[F++] = T2;
          C3[F++] = T2;
          C3[F++] = T2;
        }
        return C3;
      } else if (this.p === 3 && this.f) {
        return this.z(E);
      } else if (this.p === 4) {
        if (this.f) {
          if (G2) {
            return this.O(E);
          }
          return this.r(E);
        } else if (G2) {
          return this.U(E);
        }
      }
      return E;
    } };
    return ak2;
  }();
  function a9(p, t3) {
    return p[t3] << 24 >> 24;
  }
  function Z2(p, t3) {
    return p[t3] << 8 | p[t3 + 1];
  }
  function am(p, t3) {
    return (p[t3] << 24 | p[t3 + 1] << 16 | p[t3 + 2] << 8 | p[t3 + 3]) >>> 0;
  }
  UTIF.JpegDecoder = ak;
})();
UTIF.encodeImage = function(rgba, w, h, metadata) {
  var idf = {
    "t256": [w],
    "t257": [h],
    "t258": [8, 8, 8, 8],
    "t259": [1],
    "t262": [2],
    "t273": [1e3],
    // strips offset
    "t277": [4],
    "t278": [h],
    /* rows per strip */
    "t279": [w * h * 4],
    // strip byte counts
    "t282": [[72, 1]],
    "t283": [[72, 1]],
    "t284": [1],
    "t286": [[0, 1]],
    "t287": [[0, 1]],
    "t296": [1],
    "t305": ["Photopea (UTIF.js)"],
    "t338": [1]
  };
  if (metadata) for (var i in metadata) idf[i] = metadata[i];
  var prfx = new Uint8Array(UTIF.encode([idf]));
  var img = new Uint8Array(rgba);
  var data2 = new Uint8Array(1e3 + w * h * 4);
  for (var i = 0; i < prfx.length; i++) data2[i] = prfx[i];
  for (var i = 0; i < img.length; i++) data2[1e3 + i] = img[i];
  return data2.buffer;
};
UTIF.encode = function(ifds) {
  var LE = false;
  var data2 = new Uint8Array(2e4), offset = 4, bin = LE ? UTIF._binLE : UTIF._binBE;
  data2[0] = data2[1] = LE ? 73 : 77;
  bin.writeUshort(data2, 2, 42);
  var ifdo = 8;
  bin.writeUint(data2, offset, ifdo);
  offset += 4;
  for (var i = 0; i < ifds.length; i++) {
    var noffs = UTIF._writeIFD(bin, UTIF._types.basic, data2, ifdo, ifds[i]);
    ifdo = noffs[1];
    if (i < ifds.length - 1) {
      if ((ifdo & 3) != 0) ifdo += 4 - (ifdo & 3);
      bin.writeUint(data2, noffs[0], ifdo);
    }
  }
  return data2.slice(0, ifdo).buffer;
};
UTIF.decode = function(buff, prm) {
  if (prm == null) prm = { parseMN: true, debug: false };
  var data2 = new Uint8Array(buff), offset = 0;
  var id = UTIF._binBE.readASCII(data2, offset, 2);
  offset += 2;
  var bin = id == "II" ? UTIF._binLE : UTIF._binBE;
  var num = bin.readUshort(data2, offset);
  offset += 2;
  var ifdo = bin.readUint(data2, offset);
  offset += 4;
  var ifds = [];
  while (true) {
    var cnt = bin.readUshort(data2, ifdo), typ = bin.readUshort(data2, ifdo + 4);
    if (cnt != 0) {
      if (typ < 1 || 13 < typ) {
        log("error in TIFF");
        break;
      }
    }
    ;
    UTIF._readIFD(bin, data2, ifdo, ifds, 0, prm);
    ifdo = bin.readUint(data2, ifdo + 2 + cnt * 12);
    if (ifdo == 0) break;
  }
  return ifds;
};
UTIF.decodeImage = function(buff, img, ifds) {
  if (img.data) return;
  var data2 = new Uint8Array(buff);
  var id = UTIF._binBE.readASCII(data2, 0, 2);
  if (img["t256"] == null) return;
  img.isLE = id == "II";
  img.width = img["t256"][0];
  img.height = img["t257"][0];
  var cmpr = img["t259"] ? img["t259"][0] : 1;
  var fo = img["t266"] ? img["t266"][0] : 1;
  if (img["t284"] && img["t284"][0] == 2) log("PlanarConfiguration 2 should not be used!");
  if (cmpr == 7 && img["t258"] && img["t258"].length > 3) img["t258"] = img["t258"].slice(0, 3);
  var spp = img["t277"] ? img["t277"][0] : 1;
  var bps = img["t258"] ? img["t258"][0] : 1;
  var bipp = bps * spp;
  if (cmpr == 1 && img["t279"] != null && img["t278"] && img["t262"][0] == 32803) {
    bipp = Math.round(img["t279"][0] * 8 / (img.width * img["t278"][0]));
  }
  if (img["t50885"] && img["t50885"][0] == 4) bipp = img["t258"][0] * 3;
  var bipl = Math.ceil(img.width * bipp / 8) * 8;
  var soff = img["t273"];
  if (soff == null || img["t322"]) soff = img["t324"];
  var bcnt = img["t279"];
  if (cmpr == 1 && soff.length == 1) bcnt = [img.height * (bipl >>> 3)];
  if (bcnt == null || img["t322"]) bcnt = img["t325"];
  var bytes = new Uint8Array(img.height * (bipl >>> 3)), bilen = 0;
  if (img["t322"] != null) {
    var tw = img["t322"][0], th = img["t323"][0];
    var tx = Math.floor((img.width + tw - 1) / tw);
    var ty = Math.floor((img.height + th - 1) / th);
    var tbuff = new Uint8Array(Math.ceil(tw * th * bipp / 8) | 0);
    console.log("====", tx, ty);
    for (var y = 0; y < ty; y++)
      for (var x2 = 0; x2 < tx; x2++) {
        var i = y * tx + x2;
        tbuff.fill(0);
        UTIF.decode._decompress(img, ifds, data2, soff[i], bcnt[i], cmpr, tbuff, 0, fo, tw, th);
        if (cmpr == 6) bytes = tbuff;
        else UTIF._copyTile(tbuff, Math.ceil(tw * bipp / 8) | 0, th, bytes, Math.ceil(img.width * bipp / 8) | 0, img.height, Math.ceil(x2 * tw * bipp / 8) | 0, y * th);
      }
    bilen = bytes.length * 8;
  } else {
    if (soff == null) return;
    var rps = img["t278"] ? img["t278"][0] : img.height;
    rps = Math.min(rps, img.height);
    for (var i = 0; i < soff.length; i++) {
      UTIF.decode._decompress(img, ifds, data2, soff[i], bcnt[i], cmpr, bytes, Math.ceil(bilen / 8) | 0, fo, img.width, rps);
      bilen += bipl * rps;
    }
    bilen = Math.min(bilen, bytes.length * 8);
  }
  img.data = new Uint8Array(bytes.buffer, 0, Math.ceil(bilen / 8) | 0);
};
UTIF.decode._decompress = function(img, ifds, data2, off, len, cmpr, tgt, toff, fo, w, h) {
  if (img["t271"] && img["t271"][0] == "Panasonic" && img["t45"] && img["t45"][0] == 6) cmpr = 34316;
  if (false) {
  } else if (cmpr == 1) for (var j2 = 0; j2 < len; j2++) tgt[toff + j2] = data2[off + j2];
  else if (cmpr == 2) UTIF.decode._decodeG2(data2, off, len, tgt, toff, w, fo);
  else if (cmpr == 3) UTIF.decode._decodeG3(data2, off, len, tgt, toff, w, fo, img["t292"] ? (img["t292"][0] & 1) == 1 : false);
  else if (cmpr == 4) UTIF.decode._decodeG4(data2, off, len, tgt, toff, w, fo);
  else if (cmpr == 5) UTIF.decode._decodeLZW(data2, off, len, tgt, toff, 8);
  else if (cmpr == 6) UTIF.decode._decodeOldJPEG(img, data2, off, len, tgt, toff);
  else if (cmpr == 7 || cmpr == 34892) UTIF.decode._decodeNewJPEG(img, data2, off, len, tgt, toff);
  else if (cmpr == 8 || cmpr == 32946) {
    var src = new Uint8Array(data2.buffer, off + 2, len - 6);
    var bin = UTIF._inflateRaw(src);
    if (toff + bin.length <= tgt.length) tgt.set(bin, toff);
  } else if (cmpr == 9) UTIF.decode._decodeVC5(data2, off, len, tgt, toff, img["t33422"]);
  else if (cmpr == 32767) UTIF.decode._decodeARW(img, data2, off, len, tgt, toff);
  else if (cmpr == 32773) UTIF.decode._decodePackBits(data2, off, len, tgt, toff);
  else if (cmpr == 32809) UTIF.decode._decodeThunder(data2, off, len, tgt, toff);
  else if (cmpr == 34316) UTIF.decode._decodePanasonic(img, data2, off, len, tgt, toff);
  else if (cmpr == 34713)
    UTIF.decode._decodeNikon(img, ifds, data2, off, len, tgt, toff);
  else if (cmpr == 34676) UTIF.decode._decodeLogLuv32(img, data2, off, len, tgt, toff);
  else log("Unknown compression", cmpr);
  var bps = img["t258"] ? Math.min(32, img["t258"][0]) : 1;
  var noc = img["t277"] ? img["t277"][0] : 1, bpp = bps * noc >>> 3, bpl = Math.ceil(bps * noc * w / 8);
  if (bps == 16 && !img.isLE && img["t33422"] == null)
    for (var y = 0; y < h; y++) {
      var roff = toff + y * bpl;
      for (var x2 = 1; x2 < bpl; x2 += 2) {
        var t3 = tgt[roff + x2];
        tgt[roff + x2] = tgt[roff + x2 - 1];
        tgt[roff + x2 - 1] = t3;
      }
    }
  if (img["t317"] && img["t317"][0] == 2) {
    for (var y = 0; y < h; y++) {
      var ntoff = toff + y * bpl;
      if (bps == 16) for (var j2 = bpp; j2 < bpl; j2 += 2) {
        var nv = (tgt[ntoff + j2 + 1] << 8 | tgt[ntoff + j2]) + (tgt[ntoff + j2 - bpp + 1] << 8 | tgt[ntoff + j2 - bpp]);
        tgt[ntoff + j2] = nv & 255;
        tgt[ntoff + j2 + 1] = nv >>> 8 & 255;
      }
      else if (noc == 3) for (var j2 = 3; j2 < bpl; j2 += 3) {
        tgt[ntoff + j2] = tgt[ntoff + j2] + tgt[ntoff + j2 - 3] & 255;
        tgt[ntoff + j2 + 1] = tgt[ntoff + j2 + 1] + tgt[ntoff + j2 - 2] & 255;
        tgt[ntoff + j2 + 2] = tgt[ntoff + j2 + 2] + tgt[ntoff + j2 - 1] & 255;
      }
      else for (var j2 = bpp; j2 < bpl; j2++) tgt[ntoff + j2] = tgt[ntoff + j2] + tgt[ntoff + j2 - bpp] & 255;
    }
  }
};
UTIF.decode._decodePanasonic = function(img, data2, off, len, tgt, toff) {
  var img_buffer = data2.buffer;
  var rawWidth = img["t2"][0];
  var rawHeight = img["t3"][0];
  var bitsPerSample = img["t10"][0];
  var RW2_Format = img["t45"][0];
  var bidx = 0;
  var imageIndex = 0;
  var vpos = 0;
  var byte = 0;
  var arr_a, arr_b;
  var bytes = RW2_Format == 6 ? new Uint32Array(18) : new Uint8Array(16);
  var i, j2, sh, pred = [0, 0], nonz = [0, 0], isOdd, idx = 0, pixel_base;
  var row, col, crow;
  var buffer = new Uint8Array(16384);
  var result = new Uint16Array(tgt.buffer);
  function getDataRaw(bits2) {
    if (vpos == 0) {
      var arr_a2 = new Uint8Array(img_buffer, off + imageIndex + 8184, 16384 - 8184);
      var arr_b2 = new Uint8Array(img_buffer, off + imageIndex, 8184);
      buffer.set(arr_a2);
      buffer.set(arr_b2, arr_a2.length);
      imageIndex += 16384;
    }
    if (RW2_Format == 5) {
      for (i = 0; i < 16; i++) {
        bytes[i] = buffer[vpos++];
        vpos &= 16383;
      }
    } else {
      vpos = vpos - bits2 & 131071;
      byte = vpos >> 3 ^ 16368;
      return (buffer[byte] | buffer[byte + 1] << 8) >> (vpos & 7) & ~(-1 << bits2);
    }
  }
  function getBufferDataRW6(i2) {
    return buffer[vpos + 15 - i2];
  }
  function readPageRW6() {
    bytes[0] = getBufferDataRW6(0) << 6 | getBufferDataRW6(1) >> 2;
    bytes[1] = ((getBufferDataRW6(1) & 3) << 12 | getBufferDataRW6(2) << 4 | getBufferDataRW6(3) >> 4) & 16383;
    bytes[2] = getBufferDataRW6(3) >> 2 & 3;
    bytes[3] = (getBufferDataRW6(3) & 3) << 8 | getBufferDataRW6(4);
    bytes[4] = getBufferDataRW6(5) << 2 | getBufferDataRW6(6) >> 6;
    bytes[5] = (getBufferDataRW6(6) & 63) << 4 | getBufferDataRW6(7) >> 4;
    bytes[6] = getBufferDataRW6(7) >> 2 & 3;
    bytes[7] = (getBufferDataRW6(7) & 3) << 8 | getBufferDataRW6(8);
    bytes[8] = getBufferDataRW6(9) << 2 & 1020 | getBufferDataRW6(10) >> 6;
    bytes[9] = (getBufferDataRW6(10) << 4 | getBufferDataRW6(11) >> 4) & 1023;
    bytes[10] = getBufferDataRW6(11) >> 2 & 3;
    bytes[11] = (getBufferDataRW6(11) & 3) << 8 | getBufferDataRW6(12);
    bytes[12] = (getBufferDataRW6(13) << 2 & 1020 | getBufferDataRW6(14) >> 6) & 1023;
    bytes[13] = (getBufferDataRW6(14) << 4 | getBufferDataRW6(15) >> 4) & 1023;
    vpos += 16;
    byte = 0;
  }
  function readPageRw6_bps12() {
    bytes[0] = getBufferDataRW6(0) << 4 | getBufferDataRW6(1) >> 4;
    bytes[1] = ((getBufferDataRW6(1) & 15) << 8 | getBufferDataRW6(2)) & 4095;
    bytes[2] = getBufferDataRW6(3) >> 6 & 3;
    bytes[3] = (getBufferDataRW6(3) & 63) << 2 | getBufferDataRW6(4) >> 6;
    bytes[4] = (getBufferDataRW6(4) & 63) << 2 | getBufferDataRW6(5) >> 6;
    bytes[5] = (getBufferDataRW6(5) & 63) << 2 | getBufferDataRW6(6) >> 6;
    bytes[6] = getBufferDataRW6(6) >> 4 & 3;
    bytes[7] = (getBufferDataRW6(6) & 15) << 4 | getBufferDataRW6(7) >> 4;
    bytes[8] = (getBufferDataRW6(7) & 15) << 4 | getBufferDataRW6(8) >> 4;
    bytes[9] = (getBufferDataRW6(8) & 15) << 4 | getBufferDataRW6(9) >> 4;
    bytes[10] = getBufferDataRW6(9) >> 2 & 3;
    bytes[11] = (getBufferDataRW6(9) & 3) << 6 | getBufferDataRW6(10) >> 2;
    bytes[12] = (getBufferDataRW6(10) & 3) << 6 | getBufferDataRW6(11) >> 2;
    bytes[13] = (getBufferDataRW6(11) & 3) << 6 | getBufferDataRW6(12) >> 2;
    bytes[14] = getBufferDataRW6(12) & 3;
    bytes[15] = getBufferDataRW6(13);
    bytes[16] = getBufferDataRW6(14);
    bytes[17] = getBufferDataRW6(15);
    vpos += 16;
    byte = 0;
  }
  function resetPredNonzeros() {
    pred[0] = 0;
    pred[1] = 0;
    nonz[0] = 0;
    nonz[1] = 0;
  }
  if (RW2_Format == 7) {
    throw RW2_Format;
  } else if (RW2_Format == 6) {
    var is12bit = bitsPerSample == 12, readPageRw6Fn = is12bit ? readPageRw6_bps12 : readPageRW6, pixelsPerBlock = is12bit ? 14 : 11, pixelbase0 = is12bit ? 128 : 512, pixelbase_compare = is12bit ? 2048 : 8192, spix_compare = is12bit ? 16383 : 65535, pixel_mask = is12bit ? 4095 : 16383, blocksperrow = rawWidth / pixelsPerBlock, rowbytes = blocksperrow * 16, bufferSize = is12bit ? 18 : 14;
    for (row = 0; row < rawHeight - 15; row += 16) {
      var rowstoread = Math.min(16, rawHeight - row);
      var readlen = rowbytes * rowstoread;
      buffer = new Uint8Array(img_buffer, off + bidx, readlen);
      vpos = 0;
      bidx += readlen;
      for (crow = 0, col = 0; crow < rowstoread; crow++, col = 0) {
        idx = (row + crow) * rawWidth;
        for (var rblock = 0; rblock < blocksperrow; rblock++) {
          readPageRw6Fn();
          resetPredNonzeros();
          sh = 0;
          pixel_base = 0;
          for (i = 0; i < pixelsPerBlock; i++) {
            isOdd = i & 1;
            if (i % 3 == 2) {
              var base = byte < bufferSize ? bytes[byte++] : 0;
              if (base == 3) base = 4;
              pixel_base = pixelbase0 << base;
              sh = 1 << base;
            }
            var epixel = byte < bufferSize ? bytes[byte++] : 0;
            if (pred[isOdd]) {
              epixel *= sh;
              if (pixel_base < pixelbase_compare && nonz[isOdd] > pixel_base)
                epixel += nonz[isOdd] - pixel_base;
              nonz[isOdd] = epixel;
            } else {
              pred[isOdd] = epixel;
              if (epixel)
                nonz[isOdd] = epixel;
              else
                epixel = nonz[isOdd];
            }
            result[idx + col++] = epixel - 15 <= spix_compare ? epixel - 15 & spix_compare : epixel + 2147483633 >> 31 & pixel_mask;
          }
        }
      }
    }
  } else if (RW2_Format == 5) {
    var blockSize = bitsPerSample == 12 ? 10 : 9;
    for (row = 0; row < rawHeight; row++) {
      for (col = 0; col < rawWidth; col += blockSize) {
        getDataRaw(0);
        if (bitsPerSample == 12) {
          result[idx++] = ((bytes[1] & 15) << 8) + bytes[0];
          result[idx++] = 16 * bytes[2] + (bytes[1] >> 4);
          result[idx++] = ((bytes[4] & 15) << 8) + bytes[3];
          result[idx++] = 16 * bytes[5] + (bytes[4] >> 4);
          result[idx++] = ((bytes[7] & 15) << 8) + bytes[6];
          result[idx++] = 16 * bytes[8] + (bytes[7] >> 4);
          result[idx++] = ((bytes[10] & 15) << 8) + bytes[9];
          result[idx++] = 16 * bytes[11] + (bytes[10] >> 4);
          result[idx++] = ((bytes[13] & 15) << 8) + bytes[12];
          result[idx++] = 16 * bytes[14] + (bytes[13] >> 4);
        } else if (bitsPerSample == 14) {
          result[idx++] = bytes[0] + ((bytes[1] & 63) << 8);
          result[idx++] = (bytes[1] >> 6) + 4 * bytes[2] + ((bytes[3] & 15) << 10);
          result[idx++] = (bytes[3] >> 4) + 16 * bytes[4] + ((bytes[5] & 3) << 12);
          result[idx++] = ((bytes[5] & 252) >> 2) + (bytes[6] << 6);
          result[idx++] = bytes[7] + ((bytes[8] & 63) << 8);
          result[idx++] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 15) << 10);
          result[idx++] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12);
          result[idx++] = ((bytes[12] & 252) >> 2) + (bytes[13] << 6);
          result[idx++] = bytes[14] + ((bytes[15] & 63) << 8);
        }
      }
    }
  } else if (RW2_Format == 4) {
    for (row = 0; row < rawHeight; row++) {
      for (col = 0; col < rawWidth; col++) {
        i = col % 14;
        isOdd = i & 1;
        if (i == 0) resetPredNonzeros();
        if (i % 3 == 2)
          sh = 4 >> 3 - getDataRaw(2);
        if (nonz[isOdd]) {
          j2 = getDataRaw(8);
          if (j2 != 0) {
            pred[isOdd] -= 128 << sh;
            if (pred[isOdd] < 0 || sh == 4)
              pred[isOdd] &= ~(-1 << sh);
            pred[isOdd] += j2 << sh;
          }
        } else {
          nonz[isOdd] = getDataRaw(8);
          if (nonz[isOdd] || i > 11)
            pred[isOdd] = nonz[isOdd] << 4 | getDataRaw(4);
        }
        result[idx++] = pred[col & 1];
      }
    }
  } else throw RW2_Format;
};
UTIF.decode._decodeVC5 = function() {
  var x2 = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], o, C3, k2, P = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1], V = 24576, ar = 16384, H = 8192, az = ar | H;
  function d(t3) {
    var E = t3[1], h = t3[0][E >>> 3] >>> 7 - (E & 7) & 1;
    t3[1]++;
    return h;
  }
  function ag(t3, E) {
    if (o == null) {
      o = {};
      for (var h = 0; h < x2.length; h += 4) o[x2[h + 1]] = x2.slice(h, h + 4);
    }
    var L = d(t3), g3 = o[L];
    while (g3 == null) {
      L = L << 1 | d(t3);
      g3 = o[L];
    }
    var n2 = g3[3];
    if (n2 != 0) n2 = d(t3) == 0 ? n2 : -n2;
    E[0] = g3[2];
    E[1] = n2;
  }
  function m(t3, E) {
    for (var h = 0; h < E; h++) {
      if ((t3 & 1) == 1) t3++;
      t3 = t3 >>> 1;
    }
    return t3;
  }
  function A2(t3, E) {
    return t3 >> E;
  }
  function O(t3, E, h, L, g3, n2) {
    E[h] = A2(A2(11 * t3[g3] - 4 * t3[g3 + n2] + t3[g3 + n2 + n2] + 4, 3) + t3[L], 1);
    E[h + n2] = A2(A2(5 * t3[g3] + 4 * t3[g3 + n2] - t3[g3 + n2 + n2] + 4, 3) - t3[L], 1);
  }
  function J(t3, E, h, L, g3, n2) {
    var W = t3[g3 - n2] - t3[g3 + n2], j2 = t3[g3], $2 = t3[L];
    E[h] = A2(A2(W + 4, 3) + j2 + $2, 1);
    E[h + n2] = A2(A2(-W + 4, 3) + j2 - $2, 1);
  }
  function y(t3, E, h, L, g3, n2) {
    E[h] = A2(A2(5 * t3[g3] + 4 * t3[g3 - n2] - t3[g3 - n2 - n2] + 4, 3) + t3[L], 1);
    E[h + n2] = A2(A2(11 * t3[g3] - 4 * t3[g3 - n2] + t3[g3 - n2 - n2] + 4, 3) - t3[L], 1);
  }
  function q2(t3) {
    t3 = t3 < 0 ? 0 : t3 > 4095 ? 4095 : t3;
    t3 = k2[t3] >>> 2;
    return t3;
  }
  function av(t3, E, h, L, g3, n2) {
    L = new Uint16Array(L.buffer);
    var W = Date.now(), j2 = UTIF._binBE, $2 = E + h, r, u2, X, I2, ax, a3, R4, ai, aa, ap, ah, ae2, aD, al, i, aE, T2, B2;
    E += 4;
    var a5 = n2[0] == 1;
    while (E < $2) {
      var S = j2.readShort(t3, E), s = j2.readUshort(t3, E + 2);
      E += 4;
      if (S == 12) r = s;
      else if (S == 20) u2 = s;
      else if (S == 21) X = s;
      else if (S == 48) I2 = s;
      else if (S == 53) ax = s;
      else if (S == 35) a3 = s;
      else if (S == 62) R4 = s;
      else if (S == 101) ai = s;
      else if (S == 109) aa = s;
      else if (S == 84) ap = s;
      else if (S == 106) ah = s;
      else if (S == 107) ae2 = s;
      else if (S == 108) aD = s;
      else if (S == 102) al = s;
      else if (S == 104) i = s;
      else if (S == 105) aE = s;
      else {
        var F = S < 0 ? -S : S, D = F & 65280, _ = 0;
        if (F & az) {
          if (F & H) {
            _ = s & 65535;
            _ += (F & 255) << 16;
          } else {
            _ = s & 65535;
          }
        }
        if ((F & V) == V) {
          if (T2 == null) {
            T2 = [];
            for (var M = 0; M < 4; M++) T2[M] = new Int16Array((u2 >>> 1) * (X >>> 1));
            B2 = new Int16Array((u2 >>> 1) * (X >>> 1));
            C3 = new Int16Array(1024);
            for (var M = 0; M < 1024; M++) {
              var aG = M - 512, p = Math.abs(aG), r = Math.floor(768 * p * p * p / (255 * 255 * 255)) + p;
              C3[M] = Math.sign(aG) * r;
            }
            k2 = new Uint16Array(4096);
            var aA = (1 << 16) - 1;
            for (var M = 0; M < 4096; M++) {
              var at = M, a1 = aA * (Math.pow(113, at / 4095) - 1) / 112;
              k2[M] = Math.min(a1, aA);
            }
          }
          var w = T2[R4], v = m(u2, 1 + P[I2]), N = m(X, 1 + P[I2]);
          if (I2 == 0) {
            for (var b3 = 0; b3 < N; b3++) for (var G2 = 0; G2 < v; G2++) {
              var c2 = E + (b3 * v + G2) * 2;
              w[b3 * (u2 >>> 1) + G2] = t3[c2] << 8 | t3[c2 + 1];
            }
          } else {
            var a7 = [t3, E * 8], a4 = [], ay = 0, aw = v * N, f = [0, 0], Q2 = 0, s = 0;
            while (ay < aw) {
              ag(a7, f);
              Q2 = f[0];
              s = f[1];
              while (Q2 > 0) {
                a4[ay++] = s;
                Q2--;
              }
            }
            var l2 = (I2 - 1) % 3, aF = l2 != 1 ? v : 0, a2 = l2 != 0 ? N : 0;
            for (var b3 = 0; b3 < N; b3++) {
              var af = (b3 + a2) * (u2 >>> 1) + aF, au = b3 * v;
              for (var G2 = 0; G2 < v; G2++) w[af + G2] = C3[a4[au + G2] + 512] * ax;
            }
            if (l2 == 2) {
              var i = u2 >>> 1, an = v * 2, a9 = N * 2;
              for (var b3 = 0; b3 < N; b3++) {
                for (var G2 = 0; G2 < an; G2++) {
                  var M = b3 * 2 * i + G2, a6 = b3 * i + G2, e = N * i + a6;
                  if (b3 == 0) O(w, B2, M, e, a6, i);
                  else if (b3 == N - 1) y(w, B2, M, e, a6, i);
                  else J(w, B2, M, e, a6, i);
                }
              }
              var Z2 = w;
              w = B2;
              B2 = Z2;
              for (var b3 = 0; b3 < a9; b3++) {
                for (var G2 = 0; G2 < v; G2++) {
                  var M = b3 * i + 2 * G2, a6 = b3 * i + G2, e = v + a6;
                  if (G2 == 0) O(w, B2, M, e, a6, 1);
                  else if (G2 == v - 1) y(w, B2, M, e, a6, 1);
                  else J(w, B2, M, e, a6, 1);
                }
              }
              var Z2 = w;
              w = B2;
              B2 = Z2;
              var aC = [], aB = 2 - ~~((I2 - 1) / 3);
              for (var K = 0; K < 3; K++) aC[K] = aa >> 14 - K * 2 & 3;
              var a62 = aC[aB];
              if (a62 != 0) for (var b3 = 0; b3 < a9; b3++) for (var G2 = 0; G2 < an; G2++) {
                var M = b3 * i + G2;
                w[M] = w[M] << a62;
              }
            }
          }
          if (I2 == 9 && R4 == 3) {
            var a8 = T2[0], ab = T2[1], aq = T2[2], as = T2[3];
            for (var b3 = 0; b3 < X; b3 += 2) for (var G2 = 0; G2 < u2; G2 += 2) {
              var U = b3 * u2 + G2, c2 = (b3 >>> 1) * (u2 >>> 1) + (G2 >>> 1), z = a8[c2], ao = ab[c2] - 2048, ak = aq[c2] - 2048, ad = as[c2] - 2048, aj = (ao << 1) + z, a0 = (ak << 1) + z, aH = z + ad, am = z - ad;
              if (a5) {
                L[U] = q2(aH);
                L[U + 1] = q2(a0);
                L[U + u2] = q2(aj);
                L[U + u2 + 1] = q2(am);
              } else {
                L[U] = q2(aj);
                L[U + 1] = q2(aH);
                L[U + u2] = q2(am);
                L[U + u2 + 1] = q2(a0);
              }
            }
          }
          E += _ * 4;
        } else if (F == 16388) {
          E += _ * 4;
        } else if (D == 8192 || D == 8448 || D == 9216) {
        } else throw F.toString(16);
      }
    }
    console.log(Date.now() - W);
  }
  return av;
}();
UTIF.decode._decodeLogLuv32 = function(img, data2, off, len, tgt, toff) {
  var w = img.width, qw = w * 4;
  var io = 0, out = new Uint8Array(qw);
  while (io < len) {
    var oo = 0;
    while (oo < qw) {
      var c2 = data2[off + io];
      io++;
      if (c2 < 128) {
        for (var j2 = 0; j2 < c2; j2++) out[oo + j2] = data2[off + io + j2];
        oo += c2;
        io += c2;
      } else {
        c2 = c2 - 126;
        for (var j2 = 0; j2 < c2; j2++) out[oo + j2] = data2[off + io];
        oo += c2;
        io++;
      }
    }
    for (var x2 = 0; x2 < w; x2++) {
      tgt[toff + 0] = out[x2];
      tgt[toff + 1] = out[x2 + w];
      tgt[toff + 2] = out[x2 + w * 2];
      tgt[toff + 4] = out[x2 + w * 3];
      toff += 6;
    }
  }
};
UTIF.decode._ljpeg_diff = function(data2, prm, huff) {
  var getbithuff = UTIF.decode._getbithuff;
  var len, diff;
  len = getbithuff(data2, prm, huff[0], huff);
  diff = getbithuff(data2, prm, len, 0);
  if ((diff & 1 << len - 1) == 0) diff -= (1 << len) - 1;
  return diff;
};
UTIF.decode._decodeARW = function(img, inp, off, src_length, tgt, toff) {
  var raw_width = img["t256"][0], height2 = img["t257"][0], tiff_bps = img["t258"][0];
  var bin = img.isLE ? UTIF._binLE : UTIF._binBE;
  var arw2 = raw_width * height2 == src_length || raw_width * height2 * 1.5 == src_length;
  if (!arw2) {
    height2 += 8;
    var prm = [off, 0, 0, 0];
    var huff = new Uint16Array(32770);
    var tab = [
      3857,
      3856,
      3599,
      3342,
      3085,
      2828,
      2571,
      2314,
      2057,
      1800,
      1543,
      1286,
      1029,
      772,
      771,
      768,
      514,
      513
    ];
    var i, c2, n2, col, row, sum2 = 0;
    var ljpeg_diff = UTIF.decode._ljpeg_diff;
    huff[0] = 15;
    for (n2 = i = 0; i < 18; i++) {
      var lim = 32768 >>> (tab[i] >>> 8);
      for (var c2 = 0; c2 < lim; c2++) huff[++n2] = tab[i];
    }
    for (col = raw_width; col--; )
      for (row = 0; row < height2 + 1; row += 2) {
        if (row == height2) row = 1;
        sum2 += ljpeg_diff(inp, prm, huff);
        if (row < height2) {
          var clr = sum2 & 4095;
          UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps);
        }
      }
    return;
  }
  if (raw_width * height2 * 1.5 == src_length) {
    for (var i = 0; i < src_length; i += 3) {
      var b0 = inp[off + i + 0], b1 = inp[off + i + 1], b22 = inp[off + i + 2];
      tgt[toff + i] = b1 << 4 | b0 >>> 4;
      tgt[toff + i + 1] = b0 << 4 | b22 >>> 4;
      tgt[toff + i + 2] = b22 << 4 | b1 >>> 4;
    }
    return;
  }
  var pix = new Uint16Array(16);
  var row, col, val2, max2, min, imax, imin, sh, bit, i, dp;
  var data2 = new Uint8Array(raw_width + 1);
  for (row = 0; row < height2; row++) {
    for (var j2 = 0; j2 < raw_width; j2++) data2[j2] = inp[off++];
    for (dp = 0, col = 0; col < raw_width - 30; dp += 16) {
      max2 = 2047 & (val2 = bin.readUint(data2, dp));
      min = 2047 & val2 >>> 11;
      imax = 15 & val2 >>> 22;
      imin = 15 & val2 >>> 26;
      for (sh = 0; sh < 4 && 128 << sh <= max2 - min; sh++) ;
      for (bit = 30, i = 0; i < 16; i++)
        if (i == imax) pix[i] = max2;
        else if (i == imin) pix[i] = min;
        else {
          pix[i] = ((bin.readUshort(data2, dp + (bit >> 3)) >>> (bit & 7) & 127) << sh) + min;
          if (pix[i] > 2047) pix[i] = 2047;
          bit += 7;
        }
      for (i = 0; i < 16; i++, col += 2) {
        var clr = pix[i] << 1;
        UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps);
      }
      col -= col & 1 ? 1 : 31;
    }
  }
};
UTIF.decode._decodeNikon = function(img, imgs, data2, off, src_length, tgt, toff) {
  var nikon_tree = [
    [
      0,
      0,
      1,
      5,
      1,
      1,
      1,
      1,
      1,
      1,
      2,
      0,
      0,
      0,
      0,
      0,
      0,
      /* 12-bit lossy */
      5,
      4,
      3,
      6,
      2,
      7,
      1,
      0,
      8,
      9,
      11,
      10,
      12
    ],
    [
      0,
      0,
      1,
      5,
      1,
      1,
      1,
      1,
      1,
      1,
      2,
      0,
      0,
      0,
      0,
      0,
      0,
      /* 12-bit lossy after split */
      57,
      90,
      56,
      39,
      22,
      5,
      4,
      3,
      2,
      1,
      0,
      11,
      12,
      12
    ],
    [
      0,
      0,
      1,
      4,
      2,
      3,
      1,
      2,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      /* 12-bit lossless */
      5,
      4,
      6,
      3,
      7,
      2,
      8,
      1,
      9,
      0,
      10,
      11,
      12
    ],
    [
      0,
      0,
      1,
      4,
      3,
      1,
      1,
      1,
      1,
      1,
      2,
      0,
      0,
      0,
      0,
      0,
      0,
      /* 14-bit lossy */
      5,
      6,
      4,
      7,
      8,
      3,
      9,
      2,
      1,
      0,
      10,
      11,
      12,
      13,
      14
    ],
    [
      0,
      0,
      1,
      5,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      2,
      0,
      0,
      0,
      0,
      0,
      /* 14-bit lossy after split */
      8,
      92,
      75,
      58,
      41,
      7,
      6,
      5,
      4,
      3,
      2,
      1,
      0,
      13,
      14
    ],
    [
      0,
      0,
      1,
      4,
      2,
      2,
      3,
      1,
      2,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      /* 14-bit lossless */
      7,
      6,
      8,
      5,
      9,
      4,
      10,
      3,
      11,
      12,
      2,
      0,
      1,
      13,
      14
    ]
  ];
  var raw_width = img["t256"][0], height2 = img["t257"][0], tiff_bps = img["t258"][0];
  var tree = 0, split = 0;
  var make_decoder = UTIF.decode._make_decoder;
  var getbithuff = UTIF.decode._getbithuff;
  var mn2 = imgs[0].exifIFD.makerNote, md = mn2["t150"] ? mn2["t150"] : mn2["t140"], mdo = 0;
  var ver0 = md[mdo++], ver1 = md[mdo++];
  if (ver0 == 73 || ver1 == 88) mdo += 2110;
  if (ver0 == 70) tree = 2;
  if (tiff_bps == 14) tree += 3;
  var vpred = [[0, 0], [0, 0]], bin = img.isLE ? UTIF._binLE : UTIF._binBE;
  for (var i = 0; i < 2; i++) for (var j2 = 0; j2 < 2; j2++) {
    vpred[i][j2] = bin.readShort(md, mdo);
    mdo += 2;
  }
  var max2 = 1 << tiff_bps & 32767, step = 0;
  var csize = bin.readShort(md, mdo);
  mdo += 2;
  if (csize > 1) step = Math.floor(max2 / (csize - 1));
  if (ver0 == 68 && ver1 == 32 && step > 0) split = bin.readShort(md, 562);
  var i;
  var row, col;
  var len, shl, diff;
  var min_v = 0;
  var hpred = [0, 0];
  var huff = make_decoder(nikon_tree[tree]);
  var prm = [off, 0, 0, 0];
  for (min_v = row = 0; row < height2; row++) {
    if (split && row == split) {
      huff = make_decoder(nikon_tree[tree + 1]);
    }
    for (col = 0; col < raw_width; col++) {
      i = getbithuff(data2, prm, huff[0], huff);
      len = i & 15;
      shl = i >>> 4;
      diff = (getbithuff(data2, prm, len - shl, 0) << 1) + 1 << shl >>> 1;
      if ((diff & 1 << len - 1) == 0)
        diff -= (1 << len) - (shl == 0 ? 1 : 0);
      if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
      else hpred[col & 1] += diff;
      var clr = Math.min(Math.max(hpred[col & 1], 0), (1 << tiff_bps) - 1);
      var bti = (row * raw_width + col) * tiff_bps;
      UTIF.decode._putsF(tgt, bti, clr << 16 - tiff_bps);
    }
  }
};
UTIF.decode._putsF = function(dt, pos, val2) {
  val2 = val2 << 8 - (pos & 7);
  var o = pos >>> 3;
  dt[o] |= val2 >>> 16;
  dt[o + 1] |= val2 >>> 8;
  dt[o + 2] |= val2;
};
UTIF.decode._getbithuff = function(data2, prm, nbits, huff) {
  var zero_after_ff = 0;
  var get_byte = UTIF.decode._get_byte;
  var c2;
  var off = prm[0], bitbuf = prm[1], vbits = prm[2], reset = prm[3];
  if (nbits == 0 || vbits < 0) return 0;
  while (!reset && vbits < nbits && (c2 = data2[off++]) != -1 && !(reset = zero_after_ff && c2 == 255 && data2[off++])) {
    bitbuf = (bitbuf << 8) + c2;
    vbits += 8;
  }
  c2 = bitbuf << 32 - vbits >>> 32 - nbits;
  if (huff) {
    vbits -= huff[c2 + 1] >>> 8;
    c2 = huff[c2 + 1] & 255;
  } else
    vbits -= nbits;
  if (vbits < 0) throw "e";
  prm[0] = off;
  prm[1] = bitbuf;
  prm[2] = vbits;
  prm[3] = reset;
  return c2;
};
UTIF.decode._make_decoder = function(source) {
  var max2, len, h, i, j2;
  var huff = [];
  for (max2 = 16; max2 != 0 && !source[max2]; max2--) ;
  var si = 17;
  huff[0] = max2;
  for (h = len = 1; len <= max2; len++)
    for (i = 0; i < source[len]; i++, ++si)
      for (j2 = 0; j2 < 1 << max2 - len; j2++)
        if (h <= 1 << max2)
          huff[h++] = len << 8 | source[si];
  return huff;
};
UTIF.decode._decodeNewJPEG = function(img, data2, off, len, tgt, toff) {
  len = Math.min(len, data2.length - off);
  var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len);
  if (tables) {
    var SOI = 216, EOI2 = 217, boff = 0;
    for (var i = 0; i < tlen - 1; i++) {
      if (tables[i] == 255 && tables[i + 1] == EOI2) break;
      buff[boff++] = tables[i];
    }
    var byte1 = data2[off], byte2 = data2[off + 1];
    if (byte1 != 255 || byte2 != SOI) {
      buff[boff++] = byte1;
      buff[boff++] = byte2;
    }
    for (var i = 2; i < len; i++) buff[boff++] = data2[off + i];
  } else for (var i = 0; i < len; i++) buff[i] = data2[off + i];
  if (img["t262"][0] == 32803 || img["t259"][0] == 7 && img["t262"][0] == 34892) {
    var bps = img["t258"][0];
    var out = UTIF.LosslessJpegDecode(buff), olen = out.length;
    if (false) {
    } else if (bps == 16) {
      if (img.isLE) for (var i = 0; i < olen; i++) {
        tgt[toff + (i << 1)] = out[i] & 255;
        tgt[toff + (i << 1) + 1] = out[i] >>> 8;
      }
      else for (var i = 0; i < olen; i++) {
        tgt[toff + (i << 1)] = out[i] >>> 8;
        tgt[toff + (i << 1) + 1] = out[i] & 255;
      }
    } else if (bps == 14 || bps == 12 || bps == 10) {
      var rst = 16 - bps;
      for (var i = 0; i < olen; i++) UTIF.decode._putsF(tgt, i * bps, out[i] << rst);
    } else if (bps == 8) {
      for (var i = 0; i < olen; i++) tgt[toff + i] = out[i];
    } else throw new Error("unsupported bit depth " + bps);
  } else {
    var parser = new UTIF.JpegDecoder();
    parser.parse(buff);
    var decoded = parser.getData({ "width": parser.width, "height": parser.height, "forceRGB": true, "isSourcePDF": false });
    for (var i = 0; i < decoded.length; i++) tgt[toff + i] = decoded[i];
  }
  if (img["t262"][0] == 6) img["t262"][0] = 2;
};
UTIF.decode._decodeOldJPEGInit = function(img, data2, off, len) {
  var SOI = 216, EOI2 = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS2 = 218;
  var joff = 0, soff = 0, tables, sosMarker2, isTiled = false, i, j2, k2;
  var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0;
  var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0;
  var soffTag = img["t324"] || img["t273"] || jpgIchgFmt;
  var ycbcrss = img["t530"], ssx = 0, ssy = 0;
  var spp = img["t277"] ? img["t277"][0] : 1;
  var jpgresint = img["t515"];
  if (soffTag) {
    soff = soffTag[0];
    isTiled = soffTag.length > 1;
  }
  if (!isTiled) {
    if (data2[off] == 255 && data2[off + 1] == SOI) return { jpegOffset: off };
    if (jpgIchgFmt != null) {
      if (data2[off + jifoff] == 255 && data2[off + jifoff + 1] == SOI) joff = off + jifoff;
      else log("JPEGInterchangeFormat does not point to SOI");
      if (jpgIchgFmtLen == null) log("JPEGInterchangeFormatLength field is missing");
      else if (jifoff >= soff || jifoff + jiflen <= soff) log("JPEGInterchangeFormatLength field value is invalid");
      if (joff != null) return { jpegOffset: joff };
    }
  }
  if (ycbcrss != null) {
    ssx = ycbcrss[0];
    ssy = ycbcrss[1];
  }
  if (jpgIchgFmt != null) {
    if (jpgIchgFmtLen != null)
      if (jiflen >= 2 && jifoff + jiflen <= soff) {
        if (data2[off + jifoff + jiflen - 2] == 255 && data2[off + jifoff + jiflen - 1] == SOI) tables = new Uint8Array(jiflen - 2);
        else tables = new Uint8Array(jiflen);
        for (i = 0; i < tables.length; i++) tables[i] = data2[off + jifoff + i];
        log("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables");
      } else log("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile");
  }
  if (tables == null) {
    var ooff = 0, out = [];
    out[ooff++] = 255;
    out[ooff++] = SOI;
    var qtables = img["t519"];
    if (qtables == null) throw new Error("JPEGQTables tag is missing");
    for (i = 0; i < qtables.length; i++) {
      out[ooff++] = 255;
      out[ooff++] = DQT;
      out[ooff++] = 0;
      out[ooff++] = 67;
      out[ooff++] = i;
      for (j2 = 0; j2 < 64; j2++) out[ooff++] = data2[off + qtables[i] + j2];
    }
    for (k2 = 0; k2 < 2; k2++) {
      var htables = img[k2 == 0 ? "t520" : "t521"];
      if (htables == null) throw new Error((k2 == 0 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing");
      for (i = 0; i < htables.length; i++) {
        out[ooff++] = 255;
        out[ooff++] = DHT;
        var nc = 19;
        for (j2 = 0; j2 < 16; j2++) nc += data2[off + htables[i] + j2];
        out[ooff++] = nc >>> 8;
        out[ooff++] = nc & 255;
        out[ooff++] = i | k2 << 4;
        for (j2 = 0; j2 < 16; j2++) out[ooff++] = data2[off + htables[i] + j2];
        for (j2 = 0; j2 < nc; j2++) out[ooff++] = data2[off + htables[i] + 16 + j2];
      }
    }
    out[ooff++] = 255;
    out[ooff++] = SOF0;
    out[ooff++] = 0;
    out[ooff++] = 8 + 3 * spp;
    out[ooff++] = 8;
    out[ooff++] = img.height >>> 8 & 255;
    out[ooff++] = img.height & 255;
    out[ooff++] = img.width >>> 8 & 255;
    out[ooff++] = img.width & 255;
    out[ooff++] = spp;
    if (spp == 1) {
      out[ooff++] = 1;
      out[ooff++] = 17;
      out[ooff++] = 0;
    } else for (i = 0; i < 3; i++) {
      out[ooff++] = i + 1;
      out[ooff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15;
      out[ooff++] = i;
    }
    if (jpgresint != null && jpgresint[0] != 0) {
      out[ooff++] = 255;
      out[ooff++] = DRI;
      out[ooff++] = 0;
      out[ooff++] = 4;
      out[ooff++] = jpgresint[0] >>> 8 & 255;
      out[ooff++] = jpgresint[0] & 255;
    }
    tables = new Uint8Array(out);
  }
  var sofpos = -1;
  i = 0;
  while (i < tables.length - 1) {
    if (tables[i] == 255 && tables[i + 1] == SOF0) {
      sofpos = i;
      break;
    }
    i++;
  }
  if (sofpos == -1) {
    var tmptab = new Uint8Array(tables.length + 10 + 3 * spp);
    tmptab.set(tables);
    var tmpoff = tables.length;
    sofpos = tables.length;
    tables = tmptab;
    tables[tmpoff++] = 255;
    tables[tmpoff++] = SOF0;
    tables[tmpoff++] = 0;
    tables[tmpoff++] = 8 + 3 * spp;
    tables[tmpoff++] = 8;
    tables[tmpoff++] = img.height >>> 8 & 255;
    tables[tmpoff++] = img.height & 255;
    tables[tmpoff++] = img.width >>> 8 & 255;
    tables[tmpoff++] = img.width & 255;
    tables[tmpoff++] = spp;
    if (spp == 1) {
      tables[tmpoff++] = 1;
      tables[tmpoff++] = 17;
      tables[tmpoff++] = 0;
    } else for (i = 0; i < 3; i++) {
      tables[tmpoff++] = i + 1;
      tables[tmpoff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15;
      tables[tmpoff++] = i;
    }
  }
  if (data2[soff] == 255 && data2[soff + 1] == SOS2) {
    var soslen = data2[soff + 2] << 8 | data2[soff + 3];
    sosMarker2 = new Uint8Array(soslen + 2);
    sosMarker2[0] = data2[soff];
    sosMarker2[1] = data2[soff + 1];
    sosMarker2[2] = data2[soff + 2];
    sosMarker2[3] = data2[soff + 3];
    for (i = 0; i < soslen - 2; i++) sosMarker2[i + 4] = data2[soff + i + 4];
  } else {
    sosMarker2 = new Uint8Array(2 + 6 + 2 * spp);
    var sosoff = 0;
    sosMarker2[sosoff++] = 255;
    sosMarker2[sosoff++] = SOS2;
    sosMarker2[sosoff++] = 0;
    sosMarker2[sosoff++] = 6 + 2 * spp;
    sosMarker2[sosoff++] = spp;
    if (spp == 1) {
      sosMarker2[sosoff++] = 1;
      sosMarker2[sosoff++] = 0;
    } else for (i = 0; i < 3; i++) {
      sosMarker2[sosoff++] = i + 1;
      sosMarker2[sosoff++] = i << 4 | i;
    }
    sosMarker2[sosoff++] = 0;
    sosMarker2[sosoff++] = 63;
    sosMarker2[sosoff++] = 0;
  }
  return { jpegOffset: off, tables, sosMarker: sosMarker2, sofPosition: sofpos };
};
UTIF.decode._decodeOldJPEG = function(img, data2, off, len, tgt, toff) {
  var i, dlen, tlen, buff, buffoff;
  var jpegData = UTIF.decode._decodeOldJPEGInit(img, data2, off, len);
  if (jpegData.jpegOffset != null) {
    dlen = off + len - jpegData.jpegOffset;
    buff = new Uint8Array(dlen);
    for (i = 0; i < dlen; i++) buff[i] = data2[jpegData.jpegOffset + i];
  } else {
    tlen = jpegData.tables.length;
    buff = new Uint8Array(tlen + jpegData.sosMarker.length + len + 2);
    buff.set(jpegData.tables);
    buffoff = tlen;
    buff[jpegData.sofPosition + 5] = img.height >>> 8 & 255;
    buff[jpegData.sofPosition + 6] = img.height & 255;
    buff[jpegData.sofPosition + 7] = img.width >>> 8 & 255;
    buff[jpegData.sofPosition + 8] = img.width & 255;
    if (data2[off] != 255 || data2[off + 1] != SOS) {
      buff.set(jpegData.sosMarker, buffoff);
      buffoff += sosMarker.length;
    }
    for (i = 0; i < len; i++) buff[buffoff++] = data2[off + i];
    buff[buffoff++] = 255;
    buff[buffoff++] = EOI;
  }
  var parser = new UTIF.JpegDecoder();
  parser.parse(buff);
  var decoded = parser.getData({ "width": parser.width, "height": parser.height, "forceRGB": true, "isSourcePDF": false });
  for (var i = 0; i < decoded.length; i++) tgt[toff + i] = decoded[i];
  if (img["t262"] && img["t262"][0] == 6) img["t262"][0] = 2;
};
UTIF.decode._decodePackBits = function(data2, off, len, tgt, toff) {
  var sa = new Int8Array(data2.buffer), ta = new Int8Array(tgt.buffer), lim = off + len;
  while (off < lim) {
    var n2 = sa[off];
    off++;
    if (n2 >= 0 && n2 < 128) for (var i = 0; i < n2 + 1; i++) {
      ta[toff] = sa[off];
      toff++;
      off++;
    }
    if (n2 >= -127 && n2 < 0) {
      for (var i = 0; i < -n2 + 1; i++) {
        ta[toff] = sa[off];
        toff++;
      }
      off++;
    }
  }
  return toff;
};
UTIF.decode._decodeThunder = function(data2, off, len, tgt, toff) {
  var d2 = [0, 1, 0, -1], d3 = [0, 1, 2, 3, 0, -3, -2, -1];
  var lim = off + len, qoff = toff * 2, px = 0;
  while (off < lim) {
    var b3 = data2[off], msk = b3 >>> 6, n2 = b3 & 63;
    off++;
    if (msk == 3) {
      px = n2 & 15;
      tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1);
      qoff++;
    }
    if (msk == 0) for (var i = 0; i < n2; i++) {
      tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1);
      qoff++;
    }
    if (msk == 2) for (var i = 0; i < 2; i++) {
      var d = n2 >>> 3 * (1 - i) & 7;
      if (d != 4) {
        px += d3[d];
        tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1);
        qoff++;
      }
    }
    if (msk == 1) for (var i = 0; i < 3; i++) {
      var d = n2 >>> 2 * (2 - i) & 3;
      if (d != 2) {
        px += d2[d];
        tgt[qoff >>> 1] |= px << 4 * (1 - qoff & 1);
        qoff++;
      }
    }
  }
};
UTIF.decode._dmap = { "1": 0, "011": 1, "000011": 2, "0000011": 3, "010": -1, "000010": -2, "0000010": -3 };
UTIF.decode._lens = function() {
  var addKeys = function(lens, arr, i0, inc) {
    for (var i = 0; i < arr.length; i++) lens[arr[i]] = i0 + i * inc;
  };
  var termW = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101,101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010,00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010,00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100";
  var termB = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000,0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001,000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111,000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111";
  var makeW = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110,011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011";
  var makeB = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100,0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010,0000001011011,0000001100100,0000001100101";
  var makeA = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111";
  termW = termW.split(",");
  termB = termB.split(",");
  makeW = makeW.split(",");
  makeB = makeB.split(",");
  makeA = makeA.split(",");
  var lensW = {}, lensB = {};
  addKeys(lensW, termW, 0, 1);
  addKeys(lensW, makeW, 64, 64);
  addKeys(lensW, makeA, 1792, 64);
  addKeys(lensB, termB, 0, 1);
  addKeys(lensB, makeB, 64, 64);
  addKeys(lensB, makeA, 1792, 64);
  return [lensW, lensB];
}();
UTIF.decode._decodeG4 = function(data2, off, slen, tgt, toff, w, fo) {
  var U = UTIF.decode, boff = off << 3, len = 0, wrd = "";
  var line2 = [], pline = [];
  for (var i = 0; i < w; i++) pline.push(0);
  pline = U._makeDiff(pline);
  var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b22 = 0, clr = 0;
  var y = 0, mode = "", toRead = 0;
  var bipl = Math.ceil(w / 8) * 8;
  while (boff >>> 3 < off + slen) {
    b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b22 = U._findDiff(pline, b1, clr);
    var bit = 0;
    if (fo == 1) bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1;
    if (fo == 2) bit = data2[boff >>> 3] >>> (boff & 7) & 1;
    boff++;
    wrd += bit;
    if (mode == "H") {
      if (U._lens[clr][wrd] != null) {
        var dl = U._lens[clr][wrd];
        wrd = "";
        len += dl;
        if (dl < 64) {
          U._addNtimes(line2, len, clr);
          a0 += len;
          clr = 1 - clr;
          len = 0;
          toRead--;
          if (toRead == 0) mode = "";
        }
      }
    } else {
      if (wrd == "0001") {
        wrd = "";
        U._addNtimes(line2, b22 - a0, clr);
        a0 = b22;
      }
      if (wrd == "001") {
        wrd = "";
        mode = "H";
        toRead = 2;
      }
      if (U._dmap[wrd] != null) {
        a1 = b1 + U._dmap[wrd];
        U._addNtimes(line2, a1 - a0, clr);
        a0 = a1;
        wrd = "";
        clr = 1 - clr;
      }
    }
    if (line2.length == w && mode == "") {
      U._writeBits(line2, tgt, toff * 8 + y * bipl);
      clr = 0;
      y++;
      a0 = 0;
      pline = U._makeDiff(line2);
      line2 = [];
    }
  }
};
UTIF.decode._findDiff = function(line2, x2, clr) {
  for (var i = 0; i < line2.length; i += 2) if (line2[i] >= x2 && line2[i + 1] == clr) return line2[i];
};
UTIF.decode._makeDiff = function(line2) {
  var out = [];
  if (line2[0] == 1) out.push(0, 1);
  for (var i = 1; i < line2.length; i++) if (line2[i - 1] != line2[i]) out.push(i, line2[i]);
  out.push(line2.length, 0, line2.length, 1);
  return out;
};
UTIF.decode._decodeG2 = function(data2, off, slen, tgt, toff, w, fo) {
  var U = UTIF.decode, boff = off << 3, len = 0, wrd = "";
  var line2 = [];
  var clr = 0;
  var y = 0;
  var bipl = Math.ceil(w / 8) * 8;
  while (boff >>> 3 < off + slen) {
    var bit = 0;
    if (fo == 1) bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1;
    if (fo == 2) bit = data2[boff >>> 3] >>> (boff & 7) & 1;
    boff++;
    wrd += bit;
    len = U._lens[clr][wrd];
    if (len != null) {
      U._addNtimes(line2, len, clr);
      wrd = "";
      if (len < 64) clr = 1 - clr;
      if (line2.length == w) {
        U._writeBits(line2, tgt, toff * 8 + y * bipl);
        line2 = [];
        y++;
        clr = 0;
        if ((boff & 7) != 0) boff += 8 - (boff & 7);
        if (len >= 64) boff += 8;
      }
    }
  }
};
UTIF.decode._decodeG3 = function(data2, off, slen, tgt, toff, w, fo, twoDim) {
  var U = UTIF.decode, boff = off << 3, len = 0, wrd = "";
  var line2 = [], pline = [];
  for (var i = 0; i < w; i++) line2.push(0);
  var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b22 = 0, clr = 0;
  var y = -1, mode = "", toRead = 0, is1D = true;
  var bipl = Math.ceil(w / 8) * 8;
  while (boff >>> 3 < off + slen) {
    b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b22 = U._findDiff(pline, b1, clr);
    var bit = 0;
    if (fo == 1) bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1;
    if (fo == 2) bit = data2[boff >>> 3] >>> (boff & 7) & 1;
    boff++;
    wrd += bit;
    if (is1D) {
      if (U._lens[clr][wrd] != null) {
        var dl = U._lens[clr][wrd];
        wrd = "";
        len += dl;
        if (dl < 64) {
          U._addNtimes(line2, len, clr);
          clr = 1 - clr;
          len = 0;
        }
      }
    } else {
      if (mode == "H") {
        if (U._lens[clr][wrd] != null) {
          var dl = U._lens[clr][wrd];
          wrd = "";
          len += dl;
          if (dl < 64) {
            U._addNtimes(line2, len, clr);
            a0 += len;
            clr = 1 - clr;
            len = 0;
            toRead--;
            if (toRead == 0) mode = "";
          }
        }
      } else {
        if (wrd == "0001") {
          wrd = "";
          U._addNtimes(line2, b22 - a0, clr);
          a0 = b22;
        }
        if (wrd == "001") {
          wrd = "";
          mode = "H";
          toRead = 2;
        }
        if (U._dmap[wrd] != null) {
          a1 = b1 + U._dmap[wrd];
          U._addNtimes(line2, a1 - a0, clr);
          a0 = a1;
          wrd = "";
          clr = 1 - clr;
        }
      }
    }
    if (wrd.endsWith("000000000001")) {
      if (y >= 0) U._writeBits(line2, tgt, toff * 8 + y * bipl);
      if (twoDim) {
        if (fo == 1) is1D = (data2[boff >>> 3] >>> 7 - (boff & 7) & 1) == 1;
        if (fo == 2) is1D = (data2[boff >>> 3] >>> (boff & 7) & 1) == 1;
        boff++;
      }
      wrd = "";
      clr = 0;
      y++;
      a0 = 0;
      pline = U._makeDiff(line2);
      line2 = [];
    }
  }
  if (line2.length == w) U._writeBits(line2, tgt, toff * 8 + y * bipl);
};
UTIF.decode._addNtimes = function(arr, n2, val2) {
  for (var i = 0; i < n2; i++) arr.push(val2);
};
UTIF.decode._writeBits = function(bits2, tgt, boff) {
  for (var i = 0; i < bits2.length; i++) tgt[boff + i >>> 3] |= bits2[i] << 7 - (boff + i & 7);
};
UTIF.decode._decodeLZW = UTIF.decode._decodeLZW = function() {
  var e, U, Z2, u2, K = 0, V = 0, g3 = 0, N = 0, O = function() {
    var S = e >>> 3, A2 = U[S] << 16 | U[S + 1] << 8 | U[S + 2], j2 = A2 >>> 24 - (e & 7) - V & (1 << V) - 1;
    e += V;
    return j2;
  }, h = new Uint32Array(4096 * 4), w = 0, m = function(S) {
    if (S == w) return;
    w = S;
    g3 = 1 << S;
    N = g3 + 1;
    for (var A2 = 0; A2 < N + 1; A2++) {
      h[4 * A2] = h[4 * A2 + 3] = A2;
      h[4 * A2 + 1] = 65535;
      h[4 * A2 + 2] = 1;
    }
  }, i = function(S) {
    V = S + 1;
    K = N + 1;
  }, D = function(S) {
    var A2 = S << 2, j2 = h[A2 + 2], a2 = u2 + j2 - 1;
    while (A2 != 65535) {
      Z2[a2--] = h[A2];
      A2 = h[A2 + 1];
    }
    u2 += j2;
  }, L = function(S, A2) {
    var j2 = K << 2, a2 = S << 2;
    h[j2] = h[(A2 << 2) + 3];
    h[j2 + 1] = a2;
    h[j2 + 2] = h[a2 + 2] + 1;
    h[j2 + 3] = h[a2 + 3];
    K++;
    if (K + 1 == 1 << V && V != 12) V++;
  }, T2 = function(S, A2, j2, a2, n2, q2) {
    e = A2 << 3;
    U = S;
    Z2 = a2;
    u2 = n2;
    var B2 = A2 + j2 << 3, _ = 0, t3 = 0;
    m(q2);
    i(q2);
    while (e < B2 && (_ = O()) != N) {
      if (_ == g3) {
        i(q2);
        _ = O();
        if (_ == N) break;
        D(_);
      } else {
        if (_ < K) {
          D(_);
          L(t3, _);
        } else {
          L(t3, t3);
          D(K - 1);
        }
      }
      t3 = _;
    }
    return u2;
  };
  return T2;
}();
UTIF.tags = {};
UTIF._types = function() {
  var main = new Array(250);
  main.fill(0);
  main = main.concat([0, 0, 0, 0, 4, 3, 3, 3, 3, 3, 0, 0, 3, 0, 0, 0, 3, 0, 0, 2, 2, 2, 2, 4, 3, 0, 0, 3, 4, 4, 3, 3, 5, 5, 3, 2, 5, 5, 0, 0, 0, 0, 4, 4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 5, 5, 3, 0, 3, 3, 4, 4, 4, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  var rest = { 33432: 2, 33434: 5, 33437: 5, 34665: 4, 34850: 3, 34853: 4, 34855: 3, 34864: 3, 34866: 4, 36864: 7, 36867: 2, 36868: 2, 37121: 7, 37377: 10, 37378: 5, 37380: 10, 37381: 5, 37383: 3, 37384: 3, 37385: 3, 37386: 5, 37510: 7, 37520: 2, 37521: 2, 37522: 2, 40960: 7, 40961: 3, 40962: 4, 40963: 4, 40965: 4, 41486: 5, 41487: 5, 41488: 3, 41985: 3, 41986: 3, 41987: 3, 41988: 5, 41989: 3, 41990: 3, 41993: 3, 41994: 3, 41995: 7, 41996: 3, 42032: 2, 42033: 2, 42034: 5, 42036: 2, 42037: 2, 59932: 7 };
  return {
    basic: {
      main,
      rest
    },
    gps: {
      main: [1, 2, 5, 2, 5, 1, 5, 5, 0, 9],
      rest: { 18: 2, 29: 2 }
    }
  };
}();
UTIF._readIFD = function(bin, data2, offset, ifds, depth, prm) {
  var cnt = bin.readUshort(data2, offset);
  offset += 2;
  var ifd = {};
  if (prm.debug) log("   ".repeat(depth), ifds.length - 1, ">>>----------------");
  for (var i = 0; i < cnt; i++) {
    var tag = bin.readUshort(data2, offset);
    offset += 2;
    var type = bin.readUshort(data2, offset);
    offset += 2;
    var num = bin.readUint(data2, offset);
    offset += 4;
    var voff = bin.readUint(data2, offset);
    offset += 4;
    var arr = [];
    if (type == 1 || type == 7) {
      var no = num < 5 ? offset - 4 : voff;
      if (no + num > data2.buffer.byteLength) num = data2.buffer.byteLength - no;
      arr = new Uint8Array(data2.buffer, no, num);
    }
    if (type == 2) {
      var o0 = num < 5 ? offset - 4 : voff, c2 = data2[o0], len = Math.max(0, Math.min(num - 1, data2.length - o0));
      if (c2 < 128 || len == 0) arr.push(bin.readASCII(data2, o0, len));
      else arr = new Uint8Array(data2.buffer, o0, len);
    }
    if (type == 3) {
      for (var j2 = 0; j2 < num; j2++) arr.push(bin.readUshort(data2, (num < 3 ? offset - 4 : voff) + 2 * j2));
    }
    if (type == 4 || type == 13) {
      for (var j2 = 0; j2 < num; j2++) arr.push(bin.readUint(data2, (num < 2 ? offset - 4 : voff) + 4 * j2));
    }
    if (type == 5 || type == 10) {
      var ri = type == 5 ? bin.readUint : bin.readInt;
      for (var j2 = 0; j2 < num; j2++) arr.push([ri(data2, voff + j2 * 8), ri(data2, voff + j2 * 8 + 4)]);
    }
    if (type == 8) {
      for (var j2 = 0; j2 < num; j2++) arr.push(bin.readShort(data2, (num < 3 ? offset - 4 : voff) + 2 * j2));
    }
    if (type == 9) {
      for (var j2 = 0; j2 < num; j2++) arr.push(bin.readInt(data2, (num < 2 ? offset - 4 : voff) + 4 * j2));
    }
    if (type == 11) {
      for (var j2 = 0; j2 < num; j2++) arr.push(bin.readFloat(data2, voff + j2 * 4));
    }
    if (type == 12) {
      for (var j2 = 0; j2 < num; j2++) arr.push(bin.readDouble(data2, voff + j2 * 8));
    }
    if (num != 0 && arr.length == 0) {
      log(tag, "unknown TIFF tag type: ", type, "num:", num);
      if (i == 0) return;
      continue;
    }
    if (prm.debug) log("   ".repeat(depth), tag, type, UTIF.tags[tag], arr);
    ifd["t" + tag] = arr;
    if (tag == 330 && ifd["t272"] && ifd["t272"][0] == "DSLR-A100") {
    } else if (tag == 330 || tag == 34665 || tag == 34853 || tag == 50740 && bin.readUshort(data2, bin.readUint(arr, 0)) < 300 || tag == 61440) {
      var oarr = tag == 50740 ? [bin.readUint(arr, 0)] : arr;
      var subfd = [];
      for (var j2 = 0; j2 < oarr.length; j2++) UTIF._readIFD(bin, data2, oarr[j2], subfd, depth + 1, prm);
      if (tag == 330) ifd.subIFD = subfd;
      if (tag == 34665) ifd.exifIFD = subfd[0];
      if (tag == 34853) ifd.gpsiIFD = subfd[0];
      if (tag == 50740) ifd.dngPrvt = subfd[0];
      if (tag == 61440) ifd.fujiIFD = subfd[0];
    }
    if (tag == 37500 && prm.parseMN) {
      var mn2 = arr;
      if (bin.readASCII(mn2, 0, 5) == "Nikon") ifd.makerNote = UTIF["decode"](mn2.slice(10).buffer)[0];
      else if (bin.readASCII(mn2, 0, 5) == "OLYMP" || bin.readASCII(mn2, 0, 9) == "OM SYSTEM") {
        var inds = [8208, 8224, 8240, 8256, 8272];
        var subsub = [];
        UTIF._readIFD(bin, mn2, mn2[1] == 77 ? 16 : mn2[5] == 85 ? 12 : 8, subsub, depth + 1, prm);
        var obj = ifd.makerNote = subsub.pop();
        for (var j2 = 0; j2 < inds.length; j2++) {
          var k2 = "t" + inds[j2];
          if (obj[k2] == null) continue;
          UTIF._readIFD(bin, mn2, obj[k2][0], subsub, depth + 1, prm);
          obj[k2] = subsub.pop();
        }
        if (obj["t12288"]) {
          UTIF._readIFD(bin, obj["t12288"], 0, subsub, depth + 1, prm);
          obj["t12288"] = subsub.pop();
        }
      } else if (bin.readUshort(data2, voff) < 300 && bin.readUshort(data2, voff + 4) <= 12) {
        var subsub = [];
        UTIF._readIFD(bin, data2, voff, subsub, depth + 1, prm);
        ifd.makerNote = subsub[0];
      }
    }
  }
  ifds.push(ifd);
  if (prm.debug) log("   ".repeat(depth), "<<<---------------");
  return offset;
};
UTIF._writeIFD = function(bin, types, data2, offset, ifd) {
  var keys2 = Object.keys(ifd), knum = keys2.length;
  if (ifd["exifIFD"]) knum--;
  if (ifd["gpsiIFD"]) knum--;
  bin.writeUshort(data2, offset, knum);
  offset += 2;
  var eoff = offset + knum * 12 + 4;
  for (var ki = 0; ki < keys2.length; ki++) {
    var key2 = keys2[ki];
    if (key2 == "t34665" || key2 == "t34853") continue;
    if (key2 == "exifIFD") key2 = "t34665";
    if (key2 == "gpsiIFD") key2 = "t34853";
    var tag = parseInt(key2.slice(1)), type = types.main[tag];
    if (type == null) type = types.rest[tag];
    if (type == null || type == 0) throw new Error("unknown type of tag: " + tag);
    var val2 = ifd[key2];
    if (tag == 34665) {
      var outp = UTIF._writeIFD(bin, types, data2, eoff, ifd["exifIFD"]);
      val2 = [eoff];
      eoff = outp[1];
    }
    if (tag == 34853) {
      var outp = UTIF._writeIFD(bin, UTIF._types.gps, data2, eoff, ifd["gpsiIFD"]);
      val2 = [eoff];
      eoff = outp[1];
    }
    if (type == 2) val2 = val2[0] + "\0";
    var num = val2.length;
    bin.writeUshort(data2, offset, tag);
    offset += 2;
    bin.writeUshort(data2, offset, type);
    offset += 2;
    bin.writeUint(data2, offset, num);
    offset += 4;
    var dlen = [-1, 1, 1, 2, 4, 8, 0, 1, 0, 4, 8, 0, 8][type] * num;
    var toff = offset;
    if (dlen > 4) {
      bin.writeUint(data2, offset, eoff);
      toff = eoff;
    }
    if (type == 1 || type == 7) {
      for (var i = 0; i < num; i++) data2[toff + i] = val2[i];
    } else if (type == 2) {
      bin.writeASCII(data2, toff, val2);
    } else if (type == 3) {
      for (var i = 0; i < num; i++) bin.writeUshort(data2, toff + 2 * i, val2[i]);
    } else if (type == 4) {
      for (var i = 0; i < num; i++) bin.writeUint(data2, toff + 4 * i, val2[i]);
    } else if (type == 5 || type == 10) {
      var wr = type == 5 ? bin.writeUint : bin.writeInt;
      for (var i = 0; i < num; i++) {
        var v = val2[i], nu = v[0], de = v[1];
        if (nu == null) throw "e";
        wr(data2, toff + 8 * i, nu);
        wr(data2, toff + 8 * i + 4, de);
      }
    } else if (type == 9) {
      for (var i = 0; i < num; i++) bin.writeInt(data2, toff + 4 * i, val2[i]);
    } else if (type == 12) {
      for (var i = 0; i < num; i++) bin.writeDouble(data2, toff + 8 * i, val2[i]);
    } else throw type;
    if (dlen > 4) {
      dlen += dlen & 1;
      eoff += dlen;
    }
    offset += 4;
  }
  return [offset, eoff];
};
UTIF.toRGBA8 = function(out, scl) {
  function gamma(x3) {
    return x3 < 31308e-7 ? 12.92 * x3 : 1.055 * Math.pow(x3, 1 / 2.4) - 0.055;
  }
  var w = out.width, h = out.height, area = w * h, qarea = area * 4, data2 = out.data;
  var img = new Uint8Array(area * 4);
  var intp = out["t262"] ? out["t262"][0] : 2, bps = out["t258"] ? Math.min(32, out["t258"][0]) : 1;
  if (out["t262"] == null && bps == 1) intp = 0;
  var smpls = out["t277"] ? out["t277"][0] : out["t258"] ? out["t258"].length : [1, 1, 3, 1, 1, 4, 3][intp];
  var sfmt = out["t339"] ? out["t339"][0] : null;
  if (intp == 1 && bps == 32 && sfmt != 3) throw "e";
  var bpl = Math.ceil(smpls * bps * w / 8);
  if (false) {
  } else if (intp == 0) {
    scl = 1 / 256;
    for (var y = 0; y < h; y++) {
      var off = y * bpl, io = y * w;
      if (bps == 1) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, px = data2[off + (i >> 3)] >> 7 - (i & 7) & 1;
        img[qi] = img[qi + 1] = img[qi + 2] = (1 - px) * 255;
        img[qi + 3] = 255;
      }
      if (bps == 4) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, px = data2[off + (i >> 1)] >> 4 - 4 * (i & 1) & 15;
        img[qi] = img[qi + 1] = img[qi + 2] = (15 - px) * 17;
        img[qi + 3] = 255;
      }
      if (bps == 8) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, px = data2[off + i];
        img[qi] = img[qi + 1] = img[qi + 2] = 255 - px;
        img[qi + 3] = 255;
      }
      if (bps == 16) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, o = off + 2 * i, px = data2[o + 1] << 8 | data2[o];
        img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, 255 - ~~(px * scl));
        img[qi + 3] = 255;
      }
    }
  } else if (intp == 1) {
    if (scl == null) scl = 1 / 256;
    var f32 = (data2.length & 3) == 0 ? new Float32Array(data2.buffer) : null;
    for (var y = 0; y < h; y++) {
      var off = y * bpl, io = y * w;
      if (bps == 1) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, px = data2[off + (i >> 3)] >> 7 - (i & 7) & 1;
        img[qi] = img[qi + 1] = img[qi + 2] = px * 255;
        img[qi + 3] = 255;
      }
      if (bps == 2) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, px = data2[off + (i >> 2)] >> 6 - 2 * (i & 3) & 3;
        img[qi] = img[qi + 1] = img[qi + 2] = px * 85;
        img[qi + 3] = 255;
      }
      if (bps == 8) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, px = data2[off + i * smpls];
        img[qi] = img[qi + 1] = img[qi + 2] = px;
        img[qi + 3] = 255;
      }
      if (bps == 16) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, o = off + 2 * i, px = data2[o + 1] << 8 | data2[o];
        img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, ~~(px * scl));
        img[qi + 3] = 255;
      }
      if (bps == 32) for (var i = 0; i < w; i++) {
        var qi = io + i << 2, o = (off >>> 2) + i, px = f32[o];
        img[qi] = img[qi + 1] = img[qi + 2] = ~~(0.5 + 255 * px);
        img[qi + 3] = 255;
      }
    }
  } else if (intp == 2) {
    if (bps == 8) {
      if (smpls == 1) for (var i = 0; i < area; i++) {
        img[4 * i] = img[4 * i + 1] = img[4 * i + 2] = data2[i];
        img[4 * i + 3] = 255;
      }
      if (smpls == 3) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 3;
        img[qi] = data2[ti];
        img[qi + 1] = data2[ti + 1];
        img[qi + 2] = data2[ti + 2];
        img[qi + 3] = 255;
      }
      if (smpls >= 4) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * smpls;
        img[qi] = data2[ti];
        img[qi + 1] = data2[ti + 1];
        img[qi + 2] = data2[ti + 2];
        img[qi + 3] = data2[ti + 3];
      }
    } else if (bps == 16) {
      if (smpls == 4) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 8 + 1;
        img[qi] = data2[ti];
        img[qi + 1] = data2[ti + 2];
        img[qi + 2] = data2[ti + 4];
        img[qi + 3] = data2[ti + 6];
      }
      if (smpls == 3) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 6 + 1;
        img[qi] = data2[ti];
        img[qi + 1] = data2[ti + 2];
        img[qi + 2] = data2[ti + 4];
        img[qi + 3] = 255;
      }
    } else if (bps == 32) {
      var ndt = new Float32Array(data2.buffer);
      var min = 0;
      for (var i = 0; i < ndt.length; i++) min = Math.min(min, ndt[i]);
      if (min < 0) for (var i = 0; i < data2.length; i += 4) {
        var t3 = data2[i];
        data2[i] = data2[i + 3];
        data2[i + 3] = t3;
        t3 = data2[i + 1];
        data2[i + 1] = data2[i + 2];
        data2[i + 2] = t3;
      }
      var pmap = [];
      for (var i = 0; i < 65536; i++) pmap.push(gamma(i / 65535));
      for (var i = 0; i < ndt.length; i++) {
        var cv = Math.max(0, Math.min(1, ndt[i]));
        ndt[i] = pmap[~~(0.5 + cv * 65535)];
      }
      if (smpls == 3) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 3;
        img[qi] = ~~(0.5 + ndt[ti] * 255);
        img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255);
        img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255);
        img[qi + 3] = 255;
      }
      else if (smpls == 4) for (var i = 0; i < area; i++) {
        var qi = i << 2, ti = i * 4;
        img[qi] = ~~(0.5 + ndt[ti] * 255);
        img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255);
        img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255);
        img[qi + 3] = ~~(0.5 + ndt[ti + 3] * 255);
      }
      else throw smpls;
    } else throw bps;
  } else if (intp == 3) {
    var map2 = out["t320"];
    var cn = 1 << bps;
    var nexta = bps == 8 && smpls > 1 && out["t338"] && out["t338"][0] != 0;
    for (var y = 0; y < h; y++)
      for (var x2 = 0; x2 < w; x2++) {
        var i = y * w + x2;
        var qi = i << 2, mi2 = 0;
        var dof = y * bpl;
        if (false) {
        } else if (bps == 1) mi2 = data2[dof + (x2 >>> 3)] >>> 7 - (x2 & 7) & 1;
        else if (bps == 2) mi2 = data2[dof + (x2 >>> 2)] >>> 6 - 2 * (x2 & 3) & 3;
        else if (bps == 4) mi2 = data2[dof + (x2 >>> 1)] >>> 4 - 4 * (x2 & 1) & 15;
        else if (bps == 8) mi2 = data2[dof + x2 * smpls];
        else throw bps;
        img[qi] = map2[mi2] >> 8;
        img[qi + 1] = map2[cn + mi2] >> 8;
        img[qi + 2] = map2[cn + cn + mi2] >> 8;
        img[qi + 3] = nexta ? data2[dof + x2 * smpls + 1] : 255;
      }
  } else if (intp == 5) {
    var gotAlpha = smpls > 4 ? 1 : 0;
    for (var i = 0; i < area; i++) {
      var qi = i << 2, si = i * smpls;
      if (window.UDOC) {
        var C3 = data2[si], M = data2[si + 1], Y = data2[si + 2], K = data2[si + 3];
        var c2 = UDOC.C.cmykToRgb([C3 * (1 / 255), M * (1 / 255), Y * (1 / 255), K * (1 / 255)]);
        img[qi] = ~~(0.5 + 255 * c2[0]);
        img[qi + 1] = ~~(0.5 + 255 * c2[1]);
        img[qi + 2] = ~~(0.5 + 255 * c2[2]);
      } else {
        var C3 = 255 - data2[si], M = 255 - data2[si + 1], Y = 255 - data2[si + 2], K = (255 - data2[si + 3]) * (1 / 255);
        img[qi] = ~~(C3 * K + 0.5);
        img[qi + 1] = ~~(M * K + 0.5);
        img[qi + 2] = ~~(Y * K + 0.5);
      }
      img[qi + 3] = 255 * (1 - gotAlpha) + data2[si + 4] * gotAlpha;
    }
  } else if (intp == 6 && out["t278"]) {
    var rps = out["t278"][0];
    for (var y = 0; y < h; y += rps) {
      var i = y * w, len = rps * w;
      for (var j2 = 0; j2 < len; j2++) {
        var qi = 4 * (i + j2), si = 3 * i + 4 * (j2 >>> 1);
        var Y = data2[si + (j2 & 1)], Cb = data2[si + 2] - 128, Cr = data2[si + 3] - 128;
        var r = Y + ((Cr >> 2) + (Cr >> 3) + (Cr >> 5));
        var g3 = Y - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5));
        var b3 = Y + (Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6));
        img[qi] = Math.max(0, Math.min(255, r));
        img[qi + 1] = Math.max(0, Math.min(255, g3));
        img[qi + 2] = Math.max(0, Math.min(255, b3));
        img[qi + 3] = 255;
      }
    }
  } else if (intp == 32845) {
    for (var y = 0; y < h; y++)
      for (var x2 = 0; x2 < w; x2++) {
        var si = (y * w + x2) * 6, qi = (y * w + x2) * 4;
        var L = data2[si + 1] << 8 | data2[si];
        var L = Math.pow(2, (L + 0.5) / 256 - 64);
        var u2 = (data2[si + 3] + 0.5) / 410;
        var v = (data2[si + 5] + 0.5) / 410;
        var sX = 9 * u2 / (6 * u2 - 16 * v + 12);
        var sY = 4 * v / (6 * u2 - 16 * v + 12);
        var bY = L;
        var X = sX * bY / sY, Y = bY, Z2 = (1 - sX - sY) * bY / sY;
        var r = 2.69 * X - 1.276 * Y - 0.414 * Z2;
        var g3 = -1.022 * X + 1.978 * Y + 0.044 * Z2;
        var b3 = 0.061 * X - 0.224 * Y + 1.163 * Z2;
        img[qi] = gamma(Math.min(r, 1)) * 255;
        img[qi + 1] = gamma(Math.min(g3, 1)) * 255;
        img[qi + 2] = gamma(Math.min(b3, 1)) * 255;
        img[qi + 3] = 255;
      }
  } else log("Unknown Photometric interpretation: " + intp);
  return img;
};
UTIF.replaceIMG = function(imgs) {
  if (imgs == null) imgs = document.getElementsByTagName("img");
  var sufs = ["tif", "tiff", "dng", "cr2", "nef"];
  for (var i = 0; i < imgs.length; i++) {
    var img = imgs[i], src = img.getAttribute("src");
    if (src == null) continue;
    var suff = src.split(".").pop().toLowerCase();
    if (sufs.indexOf(suff) == -1) continue;
    var xhr = new XMLHttpRequest();
    UTIF._xhrs.push(xhr);
    UTIF._imgs.push(img);
    xhr.open("GET", src);
    xhr.responseType = "arraybuffer";
    xhr.onload = UTIF._imgLoaded;
    xhr.send();
  }
};
UTIF._xhrs = [];
UTIF._imgs = [];
UTIF._imgLoaded = function(e) {
  var ind = UTIF._xhrs.indexOf(e.target), img = UTIF._imgs[ind];
  UTIF._xhrs.splice(ind, 1);
  UTIF._imgs.splice(ind, 1);
  img.setAttribute("src", UTIF.bufferToURI(e.target.response));
};
UTIF.bufferToURI = function(buff) {
  var ifds = UTIF.decode(buff);
  var vsns = ifds, ma = 0, page = vsns[0];
  if (ifds[0].subIFD) vsns = vsns.concat(ifds[0].subIFD);
  for (var i = 0; i < vsns.length; i++) {
    var img = vsns[i];
    if (img["t258"] == null || img["t258"].length < 3) continue;
    var ar = img["t256"] * img["t257"];
    if (ar > ma) {
      ma = ar;
      page = img;
    }
  }
  UTIF.decodeImage(buff, page, ifds);
  var rgba = UTIF.toRGBA8(page), w = page.width, h = page.height;
  var cnv = document.createElement("canvas");
  cnv.width = w;
  cnv.height = h;
  var ctx = cnv.getContext("2d");
  var imgd = new ImageData(new Uint8ClampedArray(rgba.buffer), w, h);
  ctx.putImageData(imgd, 0, 0);
  return cnv.toDataURL();
};
UTIF._binBE = {
  nextZero: function(data2, o) {
    while (data2[o] != 0) o++;
    return o;
  },
  readUshort: function(buff, p) {
    return buff[p] << 8 | buff[p + 1];
  },
  readShort: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    a2[0] = buff[p + 1];
    a2[1] = buff[p + 0];
    return UTIF._binBE.i16[0];
  },
  readInt: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    a2[0] = buff[p + 3];
    a2[1] = buff[p + 2];
    a2[2] = buff[p + 1];
    a2[3] = buff[p + 0];
    return UTIF._binBE.i32[0];
  },
  readUint: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    a2[0] = buff[p + 3];
    a2[1] = buff[p + 2];
    a2[2] = buff[p + 1];
    a2[3] = buff[p + 0];
    return UTIF._binBE.ui32[0];
  },
  readASCII: function(buff, p, l2) {
    var s = "";
    for (var i = 0; i < l2; i++) s += String.fromCharCode(buff[p + i]);
    return s;
  },
  readFloat: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    for (var i = 0; i < 4; i++) a2[i] = buff[p + 3 - i];
    return UTIF._binBE.fl32[0];
  },
  readDouble: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    for (var i = 0; i < 8; i++) a2[i] = buff[p + 7 - i];
    return UTIF._binBE.fl64[0];
  },
  writeUshort: function(buff, p, n2) {
    buff[p] = n2 >> 8 & 255;
    buff[p + 1] = n2 & 255;
  },
  writeInt: function(buff, p, n2) {
    var a2 = UTIF._binBE.ui8;
    UTIF._binBE.i32[0] = n2;
    buff[p + 3] = a2[0];
    buff[p + 2] = a2[1];
    buff[p + 1] = a2[2];
    buff[p + 0] = a2[3];
  },
  writeUint: function(buff, p, n2) {
    buff[p] = n2 >> 24 & 255;
    buff[p + 1] = n2 >> 16 & 255;
    buff[p + 2] = n2 >> 8 & 255;
    buff[p + 3] = n2 >> 0 & 255;
  },
  writeASCII: function(buff, p, s) {
    for (var i = 0; i < s.length; i++) buff[p + i] = s.charCodeAt(i);
  },
  writeDouble: function(buff, p, n2) {
    UTIF._binBE.fl64[0] = n2;
    for (var i = 0; i < 8; i++) buff[p + i] = UTIF._binBE.ui8[7 - i];
  }
};
UTIF._binBE.ui8 = new Uint8Array(8);
UTIF._binBE.i16 = new Int16Array(UTIF._binBE.ui8.buffer);
UTIF._binBE.i32 = new Int32Array(UTIF._binBE.ui8.buffer);
UTIF._binBE.ui32 = new Uint32Array(UTIF._binBE.ui8.buffer);
UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer);
UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer);
UTIF._binLE = {
  nextZero: UTIF._binBE.nextZero,
  readUshort: function(buff, p) {
    return buff[p + 1] << 8 | buff[p];
  },
  readShort: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    a2[0] = buff[p + 0];
    a2[1] = buff[p + 1];
    return UTIF._binBE.i16[0];
  },
  readInt: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    a2[0] = buff[p + 0];
    a2[1] = buff[p + 1];
    a2[2] = buff[p + 2];
    a2[3] = buff[p + 3];
    return UTIF._binBE.i32[0];
  },
  readUint: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    a2[0] = buff[p + 0];
    a2[1] = buff[p + 1];
    a2[2] = buff[p + 2];
    a2[3] = buff[p + 3];
    return UTIF._binBE.ui32[0];
  },
  readASCII: UTIF._binBE.readASCII,
  readFloat: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    for (var i = 0; i < 4; i++) a2[i] = buff[p + i];
    return UTIF._binBE.fl32[0];
  },
  readDouble: function(buff, p) {
    var a2 = UTIF._binBE.ui8;
    for (var i = 0; i < 8; i++) a2[i] = buff[p + i];
    return UTIF._binBE.fl64[0];
  },
  writeUshort: function(buff, p, n2) {
    buff[p] = n2 & 255;
    buff[p + 1] = n2 >> 8 & 255;
  },
  writeInt: function(buff, p, n2) {
    var a2 = UTIF._binBE.ui8;
    UTIF._binBE.i32[0] = n2;
    buff[p + 0] = a2[0];
    buff[p + 1] = a2[1];
    buff[p + 2] = a2[2];
    buff[p + 3] = a2[3];
  },
  writeUint: function(buff, p, n2) {
    buff[p] = n2 >>> 0 & 255;
    buff[p + 1] = n2 >>> 8 & 255;
    buff[p + 2] = n2 >>> 16 & 255;
    buff[p + 3] = n2 >>> 24 & 255;
  },
  writeASCII: UTIF._binBE.writeASCII
};
UTIF._copyTile = function(tb, tw, th, b3, w, h, xoff, yoff) {
  var xlim = Math.min(tw, w - xoff);
  var ylim = Math.min(th, h - yoff);
  for (var y = 0; y < ylim; y++) {
    var tof = (yoff + y) * w + xoff;
    var sof = y * tw;
    for (var x2 = 0; x2 < xlim; x2++) b3[tof + x2] = tb[sof + x2];
  }
};
UTIF._inflateRaw = function() {
  var H = {};
  H.H = {};
  H.H.N = function(N, W) {
    var R4 = Uint8Array, i = 0, m = 0, J = 0, h = 0, Q2 = 0, X = 0, u2 = 0, w = 0, d = 0, v, C3;
    if (N[0] == 3 && N[1] == 0) return W ? W : new R4(0);
    var V = H.H, n2 = V.b, A2 = V.e, l2 = V.R, M = V.n, I2 = V.A, e = V.Z, b3 = V.m, Z2 = W == null;
    if (Z2) W = new R4(N.length >>> 2 << 5);
    while (i == 0) {
      i = n2(N, d, 1);
      m = n2(N, d + 1, 2);
      d += 3;
      if (m == 0) {
        if ((d & 7) != 0) d += 8 - (d & 7);
        var D = (d >>> 3) + 4, q2 = N[D - 4] | N[D - 3] << 8;
        if (Z2) W = H.H.W(W, w + q2);
        W.set(new R4(N.buffer, N.byteOffset + D, q2), w);
        d = D + q2 << 3;
        w += q2;
        continue;
      }
      if (Z2) W = H.H.W(W, w + (1 << 17));
      if (m == 1) {
        v = b3.J;
        C3 = b3.h;
        X = (1 << 9) - 1;
        u2 = (1 << 5) - 1;
      }
      if (m == 2) {
        J = A2(N, d, 5) + 257;
        h = A2(N, d + 5, 5) + 1;
        Q2 = A2(N, d + 10, 4) + 4;
        d += 14;
        var E = d, j2 = 1;
        for (var c2 = 0; c2 < 38; c2 += 2) {
          b3.Q[c2] = 0;
          b3.Q[c2 + 1] = 0;
        }
        for (var c2 = 0; c2 < Q2; c2++) {
          var K = A2(N, d + c2 * 3, 3);
          b3.Q[(b3.X[c2] << 1) + 1] = K;
          if (K > j2) j2 = K;
        }
        d += 3 * Q2;
        M(b3.Q, j2);
        I2(b3.Q, j2, b3.u);
        v = b3.w;
        C3 = b3.d;
        d = l2(b3.u, (1 << j2) - 1, J + h, N, d, b3.v);
        var r = V.V(b3.v, 0, J, b3.C);
        X = (1 << r) - 1;
        var S = V.V(b3.v, J, h, b3.D);
        u2 = (1 << S) - 1;
        M(b3.C, r);
        I2(b3.C, r, v);
        M(b3.D, S);
        I2(b3.D, S, C3);
      }
      while (true) {
        var T2 = v[e(N, d) & X];
        d += T2 & 15;
        var p = T2 >>> 4;
        if (p >>> 8 == 0) {
          W[w++] = p;
        } else if (p == 256) {
          break;
        } else {
          var z = w + p - 254;
          if (p > 264) {
            var _ = b3.q[p - 257];
            z = w + (_ >>> 3) + A2(N, d, _ & 7);
            d += _ & 7;
          }
          var $2 = C3[e(N, d) & u2];
          d += $2 & 15;
          var s = $2 >>> 4, Y = b3.c[s], a2 = (Y >>> 4) + n2(N, d, Y & 15);
          d += Y & 15;
          while (w < z) {
            W[w] = W[w++ - a2];
            W[w] = W[w++ - a2];
            W[w] = W[w++ - a2];
            W[w] = W[w++ - a2];
          }
          w = z;
        }
      }
    }
    return W.length == w ? W : W.slice(0, w);
  };
  H.H.W = function(N, W) {
    var R4 = N.length;
    if (W <= R4) return N;
    var V = new Uint8Array(R4 << 1);
    V.set(N, 0);
    return V;
  };
  H.H.R = function(N, W, R4, V, n2, A2) {
    var l2 = H.H.e, M = H.H.Z, I2 = 0;
    while (I2 < R4) {
      var e = N[M(V, n2) & W];
      n2 += e & 15;
      var b3 = e >>> 4;
      if (b3 <= 15) {
        A2[I2] = b3;
        I2++;
      } else {
        var Z2 = 0, m = 0;
        if (b3 == 16) {
          m = 3 + l2(V, n2, 2);
          n2 += 2;
          Z2 = A2[I2 - 1];
        } else if (b3 == 17) {
          m = 3 + l2(V, n2, 3);
          n2 += 3;
        } else if (b3 == 18) {
          m = 11 + l2(V, n2, 7);
          n2 += 7;
        }
        var J = I2 + m;
        while (I2 < J) {
          A2[I2] = Z2;
          I2++;
        }
      }
    }
    return n2;
  };
  H.H.V = function(N, W, R4, V) {
    var n2 = 0, A2 = 0, l2 = V.length >>> 1;
    while (A2 < R4) {
      var M = N[A2 + W];
      V[A2 << 1] = 0;
      V[(A2 << 1) + 1] = M;
      if (M > n2) n2 = M;
      A2++;
    }
    while (A2 < l2) {
      V[A2 << 1] = 0;
      V[(A2 << 1) + 1] = 0;
      A2++;
    }
    return n2;
  };
  H.H.n = function(N, W) {
    var R4 = H.H.m, V = N.length, n2, A2, l2, M, I2, e = R4.j;
    for (var M = 0; M <= W; M++) e[M] = 0;
    for (M = 1; M < V; M += 2) e[N[M]]++;
    var b3 = R4.K;
    n2 = 0;
    e[0] = 0;
    for (A2 = 1; A2 <= W; A2++) {
      n2 = n2 + e[A2 - 1] << 1;
      b3[A2] = n2;
    }
    for (l2 = 0; l2 < V; l2 += 2) {
      I2 = N[l2 + 1];
      if (I2 != 0) {
        N[l2] = b3[I2];
        b3[I2]++;
      }
    }
  };
  H.H.A = function(N, W, R4) {
    var V = N.length, n2 = H.H.m, A2 = n2.r;
    for (var l2 = 0; l2 < V; l2 += 2) if (N[l2 + 1] != 0) {
      var M = l2 >> 1, I2 = N[l2 + 1], e = M << 4 | I2, b3 = W - I2, Z2 = N[l2] << b3, m = Z2 + (1 << b3);
      while (Z2 != m) {
        var J = A2[Z2] >>> 15 - W;
        R4[J] = e;
        Z2++;
      }
    }
  };
  H.H.l = function(N, W) {
    var R4 = H.H.m.r, V = 15 - W;
    for (var n2 = 0; n2 < N.length; n2 += 2) {
      var A2 = N[n2] << W - N[n2 + 1];
      N[n2] = R4[A2] >>> V;
    }
  };
  H.H.M = function(N, W, R4) {
    R4 = R4 << (W & 7);
    var V = W >>> 3;
    N[V] |= R4;
    N[V + 1] |= R4 >>> 8;
  };
  H.H.I = function(N, W, R4) {
    R4 = R4 << (W & 7);
    var V = W >>> 3;
    N[V] |= R4;
    N[V + 1] |= R4 >>> 8;
    N[V + 2] |= R4 >>> 16;
  };
  H.H.e = function(N, W, R4) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R4) - 1;
  };
  H.H.b = function(N, W, R4) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R4) - 1;
  };
  H.H.Z = function(N, W) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7);
  };
  H.H.i = function(N, W) {
    return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7);
  };
  H.H.m = function() {
    var N = Uint16Array, W = Uint32Array;
    return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 999, 999, 999], T: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0], q: new N(32), p: [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 65535, 65535], z: [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15e3), k: new N(1 << 16), g: new N(1 << 15) };
  }();
  (function() {
    var N = H.H.m, W = 1 << 15;
    for (var R4 = 0; R4 < W; R4++) {
      var V = R4;
      V = (V & 2863311530) >>> 1 | (V & 1431655765) << 1;
      V = (V & 3435973836) >>> 2 | (V & 858993459) << 2;
      V = (V & 4042322160) >>> 4 | (V & 252645135) << 4;
      V = (V & 4278255360) >>> 8 | (V & 16711935) << 8;
      N.r[R4] = (V >>> 16 | V << 16) >>> 17;
    }
    function n2(A2, l2, M) {
      while (l2-- != 0) A2.push(0, M);
    }
    for (var R4 = 0; R4 < 32; R4++) {
      N.q[R4] = N.S[R4] << 3 | N.T[R4];
      N.c[R4] = N.p[R4] << 4 | N.z[R4];
    }
    n2(N._, 144, 8);
    n2(N._, 255 - 143, 9);
    n2(N._, 279 - 255, 7);
    n2(N._, 287 - 279, 8);
    H.H.n(N._, 9);
    H.H.A(N._, 9, N.J);
    H.H.l(N._, 9);
    n2(N.$, 32, 5);
    H.H.n(N.$, 5);
    H.H.A(N.$, 5, N.h);
    H.H.l(N.$, 5);
    n2(N.Q, 19, 0);
    n2(N.C, 286, 0);
    n2(N.D, 30, 0);
    n2(N.v, 320, 0);
  })();
  return H.H.N;
}();
UTIF.LosslessJpegDecode = /* @__PURE__ */ function() {
  var b3, O;
  function l2() {
    return b3[O++];
  }
  function m() {
    return b3[O++] << 8 | b3[O++];
  }
  function a0(h) {
    var V = l2(), I2 = [0, 0, 0, 255], f = [], G2 = 8;
    for (var w = 0; w < 16; w++) f[w] = l2();
    for (var w = 0; w < 16; w++) {
      for (var x2 = 0; x2 < f[w]; x2++) {
        var T2 = z(I2, 0, w + 1, 1);
        I2[T2 + 3] = l2();
      }
    }
    var E = new Uint8Array(1 << G2);
    h[V] = [new Uint8Array(I2), E];
    for (var w = 0; w < 1 << G2; w++) {
      var s = G2, _ = w, Y = 0, F = 0;
      while (I2[Y + 3] == 255 && s != 0) {
        F = _ >> --s & 1;
        Y = I2[Y + F];
      }
      E[w] = Y;
    }
  }
  function z(h, V, I2, f) {
    if (h[V + 3] != 255) return 0;
    if (I2 == 0) return V;
    for (var w = 0; w < 2; w++) {
      if (h[V + w] == 0) {
        h[V + w] = h.length;
        h.push(0, 0, f, 255);
      }
      var x2 = z(h, h[V + w], I2 - 1, f + 1);
      if (x2 != 0) return x2;
    }
    return 0;
  }
  function i(h) {
    var V = h.b, I2 = h.f;
    while (V < 25 && h.a < h.d) {
      var f = h.data[h.a++];
      if (f == 255 && !h.c) h.a++;
      I2 = I2 << 8 | f;
      V += 8;
    }
    if (V < 0) throw "e";
    h.b = V;
    h.f = I2;
  }
  function H(h, V) {
    if (V.b < h) i(V);
    return V.f >> (V.b -= h) & 65535 >> 16 - h;
  }
  function g3(h, V) {
    var I2 = h[0], f = 0, w = 255, x2 = 0;
    if (V.b < 16) i(V);
    var T2 = V.f >> V.b - 8 & 255;
    f = h[1][T2];
    w = I2[f + 3];
    V.b -= I2[f + 2];
    while (w == 255) {
      x2 = V.f >> --V.b & 1;
      f = I2[f + x2];
      w = I2[f + 3];
    }
    return w;
  }
  function P(h, V) {
    if (h < 32768 >> 16 - V) h += -(1 << V) + 1;
    return h;
  }
  function a2(h, V) {
    var I2 = g3(h, V);
    if (I2 == 0) return 0;
    if (I2 == 16) return -32768;
    var f = H(I2, V);
    return P(f, I2);
  }
  function X(h, V, I2, f, w, x2) {
    var T2 = 0;
    for (var G2 = 0; G2 < x2; G2++) {
      var s = G2 * V;
      for (var _ = 0; _ < V; _ += w) {
        T2++;
        for (var Y = 0; Y < w; Y++) h[s + _ + Y] = a2(f[Y], I2);
      }
      if (I2.e != 0 && T2 % I2.e == 0 && G2 != 0) {
        var F = I2.a, t3 = I2.data;
        while (t3[F] != 255 || !(208 <= t3[F + 1] && t3[F + 1] <= 215)) F--;
        I2.a = F + 2;
        I2.f = 0;
        I2.b = 0;
      }
    }
  }
  function o(h, V) {
    return P(H(h, V), h);
  }
  function a1(h, V, I2, f, w) {
    var x2 = b3.length - O;
    for (var T2 = 0; T2 < x2; T2 += 4) {
      var G2 = b3[O + T2];
      b3[O + T2] = b3[O + T2 + 3];
      b3[O + T2 + 3] = G2;
      var G2 = b3[O + T2 + 1];
      b3[O + T2 + 1] = b3[O + T2 + 2];
      b3[O + T2 + 2] = G2;
    }
    for (var E = 0; E < w; E++) {
      var s = 32768, _ = 32768;
      for (var Y = 0; Y < V; Y += 2) {
        var F = g3(f, I2), t3 = g3(f, I2);
        if (F != 0) s += o(F, I2);
        if (t3 != 0) _ += o(t3, I2);
        h[E * V + Y] = s & 65535;
        h[E * V + Y + 1] = _ & 65535;
      }
    }
  }
  function C3(h) {
    b3 = h;
    O = 0;
    if (m() != 65496) throw "e";
    var V = [], I2 = 0, f = 0, w = 0, x2 = [], T2 = [], G2 = [], E = 0, s = 0, _ = 0;
    while (true) {
      var Y = m();
      if (Y == 65535) {
        O--;
        continue;
      }
      var F = m();
      if (Y == 65475) {
        f = l2();
        s = m();
        _ = m();
        E = l2();
        for (var t3 = 0; t3 < E; t3++) {
          var a3 = l2(), J = l2(), r = l2();
          if (r != 0) throw "e";
          V[a3] = [t3, J >> 4, J & 15];
        }
      } else if (Y == 65476) {
        var a32 = O + F - 2;
        while (O < a32) a0(T2);
      } else if (Y == 65498) {
        O++;
        for (var t3 = 0; t3 < E; t3++) {
          var a5 = l2(), v = V[a5];
          G2[v[0]] = T2[l2() >>> 4];
          x2[v[0]] = v.slice(1);
        }
        I2 = l2();
        O += 2;
        break;
      } else if (Y == 65501) {
        w = m();
      } else {
        O += F - 2;
      }
    }
    var a4 = f > 8 ? Uint16Array : Uint8Array, $2 = new a4(s * _ * E), M = { b: 0, f: 0, c: I2 == 8, a: O, data: b3, d: b3.length, e: w };
    if (M.c) a1($2, _ * E, M, G2[0], s);
    else {
      var c2 = [], p = 0, D = 0;
      for (var t3 = 0; t3 < E; t3++) {
        var N = x2[t3], S = N[0], K = N[1];
        if (S > p) p = S;
        if (K > D) D = K;
        c2.push(S * K);
      }
      if (p != 1 || D != 1) {
        if (E != 3 || c2[1] != 1 || c2[2] != 1) throw "e";
        if (p != 2 || D != 1 && D != 2) throw "e";
        var u2 = [], Z2 = 0;
        for (var t3 = 0; t3 < E; t3++) {
          for (var R4 = 0; R4 < c2[t3]; R4++) u2.push(G2[t3]);
          Z2 += c2[t3];
        }
        var B2 = _ / p, e = s / D, d = B2 * e;
        X($2, B2 * Z2, M, u2, Z2, e);
        j2($2, I2, B2, e, Z2 - 2, Z2, Z2, f);
        var A2 = new Uint16Array(d * c2[0]);
        if (p == 2 && D == 2) {
          for (var t3 = 0; t3 < d; t3++) {
            A2[4 * t3] = $2[6 * t3];
            A2[4 * t3 + 1] = $2[6 * t3 + 1];
            A2[4 * t3 + 2] = $2[6 * t3 + 2];
            A2[4 * t3 + 3] = $2[6 * t3 + 3];
          }
          j2(A2, I2, B2 * 4, e, 0, 1, 1, f);
          for (var t3 = 0; t3 < d; t3++) {
            $2[6 * t3] = A2[4 * t3];
            $2[6 * t3 + 1] = A2[4 * t3 + 1];
            $2[6 * t3 + 2] = A2[4 * t3 + 2];
            $2[6 * t3 + 3] = A2[4 * t3 + 3];
          }
        }
        if (p == 2 && D == 1) {
          for (var t3 = 0; t3 < d; t3++) {
            A2[2 * t3] = $2[4 * t3];
            A2[2 * t3 + 1] = $2[4 * t3 + 1];
          }
          j2(A2, I2, B2 * 2, e, 0, 1, 1, f);
          for (var t3 = 0; t3 < d; t3++) {
            $2[4 * t3] = A2[2 * t3];
            $2[4 * t3 + 1] = A2[2 * t3 + 1];
          }
        }
        var n2 = $2.slice(0);
        for (var K = 0; K < s; K++) {
          if (D == 2) for (var S = 0; S < _; S++) {
            var q2 = (K * _ + S) * E, k2 = ((K >>> 1) * B2 + (S >>> 1)) * Z2, y = (K & 1) * 2 + (S & 1);
            $2[q2] = n2[k2 + y];
            $2[q2 + 1] = n2[k2 + 4];
            $2[q2 + 2] = n2[k2 + 5];
          }
          else for (var S = 0; S < _; S++) {
            var q2 = (K * _ + S) * E, k2 = (K * B2 + (S >>> 1)) * Z2, y = S & 1;
            $2[q2] = n2[k2 + y];
            $2[q2 + 1] = n2[k2 + 2];
            $2[q2 + 2] = n2[k2 + 3];
          }
        }
      } else {
        X($2, _ * E, M, G2, E, s);
        if (w == 0) j2($2, I2, _, s, 0, E, E, f);
        else {
          var U = Math.floor(w / _);
          for (var K = 0; K < s; K += U) {
            var L = $2.slice(K * _ * E, (K + U) * _ * E);
            j2(L, I2, _, U, 0, E, E, f);
            $2.set(L, K * _ * E);
          }
        }
      }
    }
    return $2;
  }
  function j2(h, V, I2, f, w, x2, G2, E) {
    var s = I2 * G2;
    for (var _ = w; _ < x2; _++) h[_] += 1 << E - 1;
    for (var Y = G2; Y < s; Y += G2) for (var _ = w; _ < x2; _++) h[Y + _] += h[Y + _ - G2];
    for (var F = 1; F < f; F++) {
      var t3 = F * s;
      for (var _ = w; _ < x2; _++) h[t3 + _] += h[t3 + _ - s];
      for (var Y = G2; Y < s; Y += G2) {
        for (var _ = w; _ < x2; _++) {
          var a3 = t3 + Y + _, J = a3 - s, r = h[a3 - G2], Q2 = 0;
          if (V == 0) Q2 = 0;
          else if (V == 1) Q2 = r;
          else if (V == 2) Q2 = h[J];
          else if (V == 3) Q2 = h[J - G2];
          else if (V == 4) Q2 = r + (h[J] - h[J - G2]);
          else if (V == 5) Q2 = r + (h[J] - h[J - G2] >>> 1);
          else if (V == 6) Q2 = h[J] + (r - h[J - G2] >>> 1);
          else if (V == 7) Q2 = r + h[J] >>> 1;
          else throw V;
          h[a3] += Q2;
        }
      }
    }
  }
  return C3;
}();
(function() {
  var G2 = 0, F = 1, i = 2, b3 = 3, J = 4, N = 5, E = 6, s = 7, c2 = 8, T2 = 9, a3 = 10, f = 11, q2 = 12, M = 13, m = 14, x2 = 15, L = 16, $2 = 17, p = 18;
  function a5(t3) {
    var Z2 = UTIF._binBE.readUshort, u2 = { b: Z2(t3, 0), i: t3[2], C: t3[3], u: t3[4], q: Z2(t3, 5), k: Z2(t3, 7), e: Z2(t3, 9), l: Z2(t3, 11), s: t3[13], d: Z2(t3, 14) };
    if (u2.b != 18771 || u2.i > 1 || u2.q < 6 || u2.q % 6 || u2.e < 768 || u2.e % 24 || u2.l != 768 || u2.k < u2.l || u2.k % u2.l || u2.k - u2.e >= u2.l || u2.s > 16 || u2.s != u2.k / u2.l || u2.s != Math.ceil(u2.e / u2.l) || u2.d != u2.q / 6 || u2.u != 12 && u2.u != 14 && u2.u != 16 || u2.C != 16 && u2.C != 0) {
      throw "Invalid data";
    }
    if (u2.i == 0) {
      throw "Not implemented. We need this file!";
    }
    u2.h = u2.C == 16;
    u2.m = (u2.h ? u2.l * 2 / 3 : u2.l >>> 1) | 0;
    u2.A = u2.m + 2;
    u2.f = 64;
    u2.g = (1 << u2.u) - 1;
    u2.n = 4 * u2.u;
    return u2;
  }
  function a7(t3, Z2) {
    var u2 = new Array(Z2.s), e = 4 * Z2.s, Q2 = 16 + e;
    if (e & 12) Q2 += 16 - (e & 12);
    for (var V = 0, O = 16; V < Z2.s; O += 4) {
      var o = UTIF._binBE.readUint(t3, O);
      u2[V] = t3.slice(Q2, Q2 + o);
      u2[V].j = 0;
      u2[V].a = 0;
      Q2 += o;
      V++;
    }
    if (Q2 != t3.length) throw "Invalid data";
    return u2;
  }
  function a6(t3, Z2) {
    for (var u2 = -Z2[4], e = 0; u2 <= Z2[4]; e++, u2++) {
      t3[e] = u2 <= -Z2[3] ? -4 : u2 <= -Z2[2] ? -3 : u2 <= -Z2[1] ? -2 : u2 < -Z2[0] ? -1 : u2 <= Z2[0] ? 0 : u2 < Z2[1] ? 1 : u2 < Z2[2] ? 2 : u2 < Z2[3] ? 3 : 4;
    }
  }
  function a1(t3, Z2, u2) {
    var e = [Z2, 3 * Z2 + 18, 5 * Z2 + 67, 7 * Z2 + 276, u2];
    t3.o = Z2;
    t3.w = (e[4] + 2 * Z2) / (2 * Z2 + 1) + 1 | 0;
    t3.v = Math.ceil(Math.log2(t3.w));
    t3.t = 9;
    a6(t3.c, e);
  }
  function a2(t3) {
    var Z2 = { c: new Int8Array(2 << t3.u) };
    a1(Z2, 0, t3.g);
    return Z2;
  }
  function D(t3) {
    var Z2 = [[], [], []], u2 = Math.max(2, t3.w + 32 >>> 6);
    for (var e = 0; e < 3; e++) {
      for (var Q2 = 0; Q2 < 41; Q2++) {
        Z2[e][Q2] = [u2, 1];
      }
    }
    return Z2;
  }
  function a4(t3) {
    for (var Z2 = -1, u2 = 0; !u2; Z2++) {
      u2 = t3[t3.j] >>> 7 - t3.a & 1;
      t3.a++;
      t3.a &= 7;
      if (!t3.a) t3.j++;
    }
    return Z2;
  }
  function K(t3, Z2) {
    var u2 = 0, e = 8 - t3.a, Q2 = t3.j, V = t3.a;
    if (Z2) {
      if (Z2 >= e) {
        do {
          u2 <<= e;
          Z2 -= e;
          u2 |= t3[t3.j] & (1 << e) - 1;
          t3.j++;
          e = 8;
        } while (Z2 >= 8);
      }
      if (Z2) {
        u2 <<= Z2;
        e -= Z2;
        u2 |= t3[t3.j] >>> e & (1 << Z2) - 1;
      }
      t3.a = 8 - e;
    }
    return u2;
  }
  function a0(t3, Z2) {
    var u2 = 0;
    if (Z2 < t3) {
      while (u2 <= 14 && Z2 << ++u2 < t3) ;
    }
    return u2;
  }
  function r(t3, Z2, u2, e, Q2, V, O, o) {
    if (o == null) o = 0;
    var X = V + 1, k2 = X % 2, j2 = 0, I2 = 0, a10 = 0, l2, R4, w = e[Q2], S = e[Q2 - 1], H = e[Q2 - 2][X], g3 = S[X - 1], Y = S[X], P = S[X + 1], A2 = w[X - 1], v = w[X + 1], y = Math.abs, d, C3, n2, h;
    if (k2) {
      d = y(P - Y);
      C3 = y(H - Y);
      n2 = y(g3 - Y);
    }
    if (k2) {
      h = d > n2 && C3 < d ? H + g3 : d < n2 && C3 < n2 ? H + P : P + g3;
      h = h + 2 * Y >>> 2;
      if (o) {
        w[X] = h;
        return;
      }
      l2 = Z2.t * Z2.c[t3.g + Y - H] + Z2.c[t3.g + g3 - Y];
    } else {
      h = Y > g3 && Y > P || Y < g3 && Y < P ? v + A2 + 2 * Y >>> 2 : A2 + v >>> 1;
      l2 = Z2.t * Z2.c[t3.g + Y - g3] + Z2.c[t3.g + g3 - A2];
    }
    R4 = y(l2);
    var W = a4(u2);
    if (W < t3.n - Z2.v - 1) {
      var z = a0(O[R4][0], O[R4][1]);
      a10 = K(u2, z) + (W << z);
    } else {
      a10 = K(u2, Z2.v) + 1;
    }
    a10 = a10 & 1 ? -1 - (a10 >>> 1) : a10 >>> 1;
    O[R4][0] += y(a10);
    if (O[R4][1] == t3.f) {
      O[R4][0] >>>= 1;
      O[R4][1] >>>= 1;
    }
    O[R4][1]++;
    h = l2 < 0 ? h - a10 : h + a10;
    if (t3.i) {
      if (h < 0) h += Z2.w;
      else if (h > t3.g) h -= Z2.w;
    }
    w[X] = h >= 0 ? Math.min(h, t3.g) : 0;
  }
  function U(t3, Z2, u2) {
    var e = t3[0].length;
    for (var Q2 = Z2; Q2 <= u2; Q2++) {
      t3[Q2][0] = t3[Q2 - 1][1];
      t3[Q2][e - 1] = t3[Q2 - 1][e - 2];
    }
  }
  function B2(t3) {
    U(t3, s, q2);
    U(t3, i, J);
    U(t3, x2, $2);
  }
  function _(t3, Z2, u2, e, Q2, V, O, o, X, k2, j2, I2, a10) {
    var l2 = 0, R4 = 1, w = Q2 < M && Q2 > J;
    while (R4 < t3.m) {
      if (l2 < t3.m) {
        r(t3, Z2, u2, e, Q2, l2, O[X], t3.h && (w && k2 || !w && (j2 || (l2 & I2) == a10)));
        r(t3, Z2, u2, e, V, l2, O[X], t3.h && (!w && k2 || w && (j2 || (l2 & I2) == a10)));
        l2 += 2;
      }
      if (l2 > 8) {
        r(t3, Z2, u2, e, Q2, R4, o[X]);
        r(t3, Z2, u2, e, V, R4, o[X]);
        R4 += 2;
      }
    }
    B2(e);
  }
  function a8(t3, Z2, u2, e, Q2, V) {
    _(t3, Z2, u2, e, i, s, Q2, V, 0, 0, 1, 0, 8);
    _(t3, Z2, u2, e, c2, x2, Q2, V, 1, 0, 1, 0, 8);
    _(t3, Z2, u2, e, b3, T2, Q2, V, 2, 1, 0, 3, 0);
    _(t3, Z2, u2, e, a3, L, Q2, V, 0, 0, 0, 3, 2);
    _(t3, Z2, u2, e, J, f, Q2, V, 1, 0, 0, 3, 2);
    _(t3, Z2, u2, e, q2, $2, Q2, V, 2, 1, 0, 3, 0);
  }
  function a9(t3, Z2, u2, e, Q2, V) {
    var O = V.length, o = t3.l;
    if (Q2 + 1 == t3.s) o = t3.e - Q2 * t3.l;
    var X = 6 * t3.e * e + Q2 * t3.l;
    for (var k2 = 0; k2 < 6; k2++) {
      for (var j2 = 0; j2 < o; j2++) {
        var I2 = V[k2 % O][j2 % O], a10;
        if (I2 == 0) {
          a10 = i + (k2 >>> 1);
        } else if (I2 == 2) {
          a10 = x2 + (k2 >>> 1);
        } else {
          a10 = s + k2;
        }
        var l2 = t3.h ? (j2 * 2 / 3 & 2147483646 | j2 % 3 & 1) + (j2 % 3 >>> 1) : j2 >>> 1;
        Z2[X + j2] = u2[a10][l2 + 1];
      }
      X += t3.e;
    }
  }
  UTIF._decompressRAF = function(t3, Z2) {
    var u2 = a5(t3), e = a7(t3, u2), Q2 = a2(u2), V = new Int16Array(u2.e * u2.q);
    if (Z2 == null) {
      Z2 = u2.h ? [[1, 1, 0, 1, 1, 2], [1, 1, 2, 1, 1, 0], [2, 0, 1, 0, 2, 1], [1, 1, 2, 1, 1, 0], [1, 1, 0, 1, 1, 2], [0, 2, 1, 2, 0, 1]] : [[0, 1], [3, 2]];
    }
    var O = [[G2, b3], [F, J], [N, f], [E, q2], [M, L], [m, $2]], o = [];
    for (var X = 0; X < p; X++) {
      o[X] = new Uint16Array(u2.A);
    }
    for (var k2 = 0; k2 < u2.s; k2++) {
      var j2 = D(Q2), I2 = D(Q2);
      for (var X = 0; X < p; X++) {
        for (var a10 = 0; a10 < u2.A; a10++) {
          o[X][a10] = 0;
        }
      }
      for (var l2 = 0; l2 < u2.d; l2++) {
        a8(u2, Q2, e[k2], o, j2, I2);
        for (var X = 0; X < 6; X++) {
          for (var a10 = 0; a10 < u2.A; a10++) {
            o[O[X][0]][a10] = o[O[X][1]][a10];
          }
        }
        a9(u2, V, o, l2, k2, Z2);
        for (var X = i; X < p; X++) {
          if ([N, E, M, m].indexOf(X) == -1) {
            for (var a10 = 0; a10 < u2.A; a10++) {
              o[X][a10] = 0;
            }
          }
        }
        B2(o);
      }
    }
    return V;
  };
})();
var utif_module_default = UTIF;

// node_modules/three/examples/jsm/loaders/TIFFLoader.js
var TIFFLoader = class extends DataTextureLoader {
  /**
   * Constructs a new TIFF loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Parses the given TIFF texture data.
   *
   * @param {ArrayBuffer} buffer - The raw texture data.
   * @return {DataTextureLoader~TexData} An object representing the parsed texture data.
   */
  parse(buffer) {
    const ifds = utif_module_default.decode(buffer);
    utif_module_default.decodeImage(buffer, ifds[0]);
    const rgba = utif_module_default.toRGBA8(ifds[0]);
    return {
      width: ifds[0].width,
      height: ifds[0].height,
      data: rgba,
      flipY: true,
      magFilter: LinearFilter,
      minFilter: LinearMipmapLinearFilter
    };
  }
};

// node_modules/three/examples/jsm/libs/opentype.module.js
if (!String.prototype.codePointAt) {
  (function() {
    var defineProperty = function() {
      try {
        var object = {};
        var $defineProperty = Object.defineProperty;
        var result = $defineProperty(object, object, object) && $defineProperty;
      } catch (error) {
      }
      return result;
    }();
    var codePointAt = function(position2) {
      if (this == null) {
        throw TypeError();
      }
      var string = String(this);
      var size2 = string.length;
      var index2 = position2 ? Number(position2) : 0;
      if (index2 != index2) {
        index2 = 0;
      }
      if (index2 < 0 || index2 >= size2) {
        return void 0;
      }
      var first2 = string.charCodeAt(index2);
      var second;
      if (
        // check if it’s the start of a surrogate pair
        first2 >= 55296 && first2 <= 56319 && // high surrogate
        size2 > index2 + 1
      ) {
        second = string.charCodeAt(index2 + 1);
        if (second >= 56320 && second <= 57343) {
          return (first2 - 55296) * 1024 + second - 56320 + 65536;
        }
      }
      return first2;
    };
    if (defineProperty) {
      defineProperty(String.prototype, "codePointAt", {
        "value": codePointAt,
        "configurable": true,
        "writable": true
      });
    } else {
      String.prototype.codePointAt = codePointAt;
    }
  })();
}
var TINF_OK = 0;
var TINF_DATA_ERROR = -3;
function Tree() {
  this.table = new Uint16Array(16);
  this.trans = new Uint16Array(288);
}
function Data(source, dest) {
  this.source = source;
  this.sourceIndex = 0;
  this.tag = 0;
  this.bitcount = 0;
  this.dest = dest;
  this.destLen = 0;
  this.ltree = new Tree();
  this.dtree = new Tree();
}
var sltree = new Tree();
var sdtree = new Tree();
var length_bits = new Uint8Array(30);
var length_base = new Uint16Array(30);
var dist_bits = new Uint8Array(30);
var dist_base = new Uint16Array(30);
var clcidx = new Uint8Array([
  16,
  17,
  18,
  0,
  8,
  7,
  9,
  6,
  10,
  5,
  11,
  4,
  12,
  3,
  13,
  2,
  14,
  1,
  15
]);
var code_tree = new Tree();
var lengths = new Uint8Array(288 + 32);
function tinf_build_bits_base(bits2, base, delta, first2) {
  var i, sum2;
  for (i = 0; i < delta; ++i) {
    bits2[i] = 0;
  }
  for (i = 0; i < 30 - delta; ++i) {
    bits2[i + delta] = i / delta | 0;
  }
  for (sum2 = first2, i = 0; i < 30; ++i) {
    base[i] = sum2;
    sum2 += 1 << bits2[i];
  }
}
function tinf_build_fixed_trees(lt, dt) {
  var i;
  for (i = 0; i < 7; ++i) {
    lt.table[i] = 0;
  }
  lt.table[7] = 24;
  lt.table[8] = 152;
  lt.table[9] = 112;
  for (i = 0; i < 24; ++i) {
    lt.trans[i] = 256 + i;
  }
  for (i = 0; i < 144; ++i) {
    lt.trans[24 + i] = i;
  }
  for (i = 0; i < 8; ++i) {
    lt.trans[24 + 144 + i] = 280 + i;
  }
  for (i = 0; i < 112; ++i) {
    lt.trans[24 + 144 + 8 + i] = 144 + i;
  }
  for (i = 0; i < 5; ++i) {
    dt.table[i] = 0;
  }
  dt.table[5] = 32;
  for (i = 0; i < 32; ++i) {
    dt.trans[i] = i;
  }
}
var offs = new Uint16Array(16);
function tinf_build_tree(t3, lengths2, off, num) {
  var i, sum2;
  for (i = 0; i < 16; ++i) {
    t3.table[i] = 0;
  }
  for (i = 0; i < num; ++i) {
    t3.table[lengths2[off + i]]++;
  }
  t3.table[0] = 0;
  for (sum2 = 0, i = 0; i < 16; ++i) {
    offs[i] = sum2;
    sum2 += t3.table[i];
  }
  for (i = 0; i < num; ++i) {
    if (lengths2[off + i]) {
      t3.trans[offs[lengths2[off + i]]++] = i;
    }
  }
}
function tinf_getbit(d) {
  if (!d.bitcount--) {
    d.tag = d.source[d.sourceIndex++];
    d.bitcount = 7;
  }
  var bit = d.tag & 1;
  d.tag >>>= 1;
  return bit;
}
function tinf_read_bits(d, num, base) {
  if (!num) {
    return base;
  }
  while (d.bitcount < 24) {
    d.tag |= d.source[d.sourceIndex++] << d.bitcount;
    d.bitcount += 8;
  }
  var val2 = d.tag & 65535 >>> 16 - num;
  d.tag >>>= num;
  d.bitcount -= num;
  return val2 + base;
}
function tinf_decode_symbol(d, t3) {
  while (d.bitcount < 24) {
    d.tag |= d.source[d.sourceIndex++] << d.bitcount;
    d.bitcount += 8;
  }
  var sum2 = 0, cur = 0, len = 0;
  var tag = d.tag;
  do {
    cur = 2 * cur + (tag & 1);
    tag >>>= 1;
    ++len;
    sum2 += t3.table[len];
    cur -= t3.table[len];
  } while (cur >= 0);
  d.tag = tag;
  d.bitcount -= len;
  return t3.trans[sum2 + cur];
}
function tinf_decode_trees(d, lt, dt) {
  var hlit, hdist, hclen;
  var i, num, length2;
  hlit = tinf_read_bits(d, 5, 257);
  hdist = tinf_read_bits(d, 5, 1);
  hclen = tinf_read_bits(d, 4, 4);
  for (i = 0; i < 19; ++i) {
    lengths[i] = 0;
  }
  for (i = 0; i < hclen; ++i) {
    var clen2 = tinf_read_bits(d, 3, 0);
    lengths[clcidx[i]] = clen2;
  }
  tinf_build_tree(code_tree, lengths, 0, 19);
  for (num = 0; num < hlit + hdist; ) {
    var sym = tinf_decode_symbol(d, code_tree);
    switch (sym) {
      case 16:
        var prev = lengths[num - 1];
        for (length2 = tinf_read_bits(d, 2, 3); length2; --length2) {
          lengths[num++] = prev;
        }
        break;
      case 17:
        for (length2 = tinf_read_bits(d, 3, 3); length2; --length2) {
          lengths[num++] = 0;
        }
        break;
      case 18:
        for (length2 = tinf_read_bits(d, 7, 11); length2; --length2) {
          lengths[num++] = 0;
        }
        break;
      default:
        lengths[num++] = sym;
        break;
    }
  }
  tinf_build_tree(lt, lengths, 0, hlit);
  tinf_build_tree(dt, lengths, hlit, hdist);
}
function tinf_inflate_block_data(d, lt, dt) {
  while (1) {
    var sym = tinf_decode_symbol(d, lt);
    if (sym === 256) {
      return TINF_OK;
    }
    if (sym < 256) {
      d.dest[d.destLen++] = sym;
    } else {
      var length2, dist, offs2;
      var i;
      sym -= 257;
      length2 = tinf_read_bits(d, length_bits[sym], length_base[sym]);
      dist = tinf_decode_symbol(d, dt);
      offs2 = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]);
      for (i = offs2; i < offs2 + length2; ++i) {
        d.dest[d.destLen++] = d.dest[i];
      }
    }
  }
}
function tinf_inflate_uncompressed_block(d) {
  var length2, invlength;
  var i;
  while (d.bitcount > 8) {
    d.sourceIndex--;
    d.bitcount -= 8;
  }
  length2 = d.source[d.sourceIndex + 1];
  length2 = 256 * length2 + d.source[d.sourceIndex];
  invlength = d.source[d.sourceIndex + 3];
  invlength = 256 * invlength + d.source[d.sourceIndex + 2];
  if (length2 !== (~invlength & 65535)) {
    return TINF_DATA_ERROR;
  }
  d.sourceIndex += 4;
  for (i = length2; i; --i) {
    d.dest[d.destLen++] = d.source[d.sourceIndex++];
  }
  d.bitcount = 0;
  return TINF_OK;
}
function tinf_uncompress(source, dest) {
  var d = new Data(source, dest);
  var bfinal, btype, res;
  do {
    bfinal = tinf_getbit(d);
    btype = tinf_read_bits(d, 2, 0);
    switch (btype) {
      case 0:
        res = tinf_inflate_uncompressed_block(d);
        break;
      case 1:
        res = tinf_inflate_block_data(d, sltree, sdtree);
        break;
      case 2:
        tinf_decode_trees(d, d.ltree, d.dtree);
        res = tinf_inflate_block_data(d, d.ltree, d.dtree);
        break;
      default:
        res = TINF_DATA_ERROR;
    }
    if (res !== TINF_OK) {
      throw new Error("Data error");
    }
  } while (!bfinal);
  if (d.destLen < d.dest.length) {
    if (typeof d.dest.slice === "function") {
      return d.dest.slice(0, d.destLen);
    } else {
      return d.dest.subarray(0, d.destLen);
    }
  }
  return d.dest;
}
tinf_build_fixed_trees(sltree, sdtree);
tinf_build_bits_base(length_bits, length_base, 4, 3);
tinf_build_bits_base(dist_bits, dist_base, 2, 1);
length_bits[28] = 0;
length_base[28] = 258;
var tinyInflate = tinf_uncompress;
function derive(v0, v12, v2, v3, t3) {
  return Math.pow(1 - t3, 3) * v0 + 3 * Math.pow(1 - t3, 2) * t3 * v12 + 3 * (1 - t3) * Math.pow(t3, 2) * v2 + Math.pow(t3, 3) * v3;
}
function BoundingBox() {
  this.x1 = Number.NaN;
  this.y1 = Number.NaN;
  this.x2 = Number.NaN;
  this.y2 = Number.NaN;
}
BoundingBox.prototype.isEmpty = function() {
  return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2);
};
BoundingBox.prototype.addPoint = function(x2, y) {
  if (typeof x2 === "number") {
    if (isNaN(this.x1) || isNaN(this.x2)) {
      this.x1 = x2;
      this.x2 = x2;
    }
    if (x2 < this.x1) {
      this.x1 = x2;
    }
    if (x2 > this.x2) {
      this.x2 = x2;
    }
  }
  if (typeof y === "number") {
    if (isNaN(this.y1) || isNaN(this.y2)) {
      this.y1 = y;
      this.y2 = y;
    }
    if (y < this.y1) {
      this.y1 = y;
    }
    if (y > this.y2) {
      this.y2 = y;
    }
  }
};
BoundingBox.prototype.addX = function(x2) {
  this.addPoint(x2, null);
};
BoundingBox.prototype.addY = function(y) {
  this.addPoint(null, y);
};
BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x3, y) {
  var p0 = [x0, y0];
  var p1 = [x1, y1];
  var p2 = [x2, y2];
  var p3 = [x3, y];
  this.addPoint(x0, y0);
  this.addPoint(x3, y);
  for (var i = 0; i <= 1; i++) {
    var b3 = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
    var a2 = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
    var c2 = 3 * p1[i] - 3 * p0[i];
    if (a2 === 0) {
      if (b3 === 0) {
        continue;
      }
      var t3 = -c2 / b3;
      if (0 < t3 && t3 < 1) {
        if (i === 0) {
          this.addX(derive(p0[i], p1[i], p2[i], p3[i], t3));
        }
        if (i === 1) {
          this.addY(derive(p0[i], p1[i], p2[i], p3[i], t3));
        }
      }
      continue;
    }
    var b2ac = Math.pow(b3, 2) - 4 * c2 * a2;
    if (b2ac < 0) {
      continue;
    }
    var t1 = (-b3 + Math.sqrt(b2ac)) / (2 * a2);
    if (0 < t1 && t1 < 1) {
      if (i === 0) {
        this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1));
      }
      if (i === 1) {
        this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1));
      }
    }
    var t22 = (-b3 - Math.sqrt(b2ac)) / (2 * a2);
    if (0 < t22 && t22 < 1) {
      if (i === 0) {
        this.addX(derive(p0[i], p1[i], p2[i], p3[i], t22));
      }
      if (i === 1) {
        this.addY(derive(p0[i], p1[i], p2[i], p3[i], t22));
      }
    }
  }
};
BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x2, y) {
  var cp1x = x0 + 2 / 3 * (x1 - x0);
  var cp1y = y0 + 2 / 3 * (y1 - y0);
  var cp2x = cp1x + 1 / 3 * (x2 - x0);
  var cp2y = cp1y + 1 / 3 * (y - y0);
  this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x2, y);
};
function Path2() {
  this.commands = [];
  this.fill = "black";
  this.stroke = null;
  this.strokeWidth = 1;
}
Path2.prototype.moveTo = function(x2, y) {
  this.commands.push({
    type: "M",
    x: x2,
    y
  });
};
Path2.prototype.lineTo = function(x2, y) {
  this.commands.push({
    type: "L",
    x: x2,
    y
  });
};
Path2.prototype.curveTo = Path2.prototype.bezierCurveTo = function(x1, y1, x2, y2, x3, y) {
  this.commands.push({
    type: "C",
    x1,
    y1,
    x2,
    y2,
    x: x3,
    y
  });
};
Path2.prototype.quadTo = Path2.prototype.quadraticCurveTo = function(x1, y1, x2, y) {
  this.commands.push({
    type: "Q",
    x1,
    y1,
    x: x2,
    y
  });
};
Path2.prototype.close = Path2.prototype.closePath = function() {
  this.commands.push({
    type: "Z"
  });
};
Path2.prototype.extend = function(pathOrCommands) {
  if (pathOrCommands.commands) {
    pathOrCommands = pathOrCommands.commands;
  } else if (pathOrCommands instanceof BoundingBox) {
    var box = pathOrCommands;
    this.moveTo(box.x1, box.y1);
    this.lineTo(box.x2, box.y1);
    this.lineTo(box.x2, box.y2);
    this.lineTo(box.x1, box.y2);
    this.close();
    return;
  }
  Array.prototype.push.apply(this.commands, pathOrCommands);
};
Path2.prototype.getBoundingBox = function() {
  var box = new BoundingBox();
  var startX = 0;
  var startY = 0;
  var prevX = 0;
  var prevY = 0;
  for (var i = 0; i < this.commands.length; i++) {
    var cmd = this.commands[i];
    switch (cmd.type) {
      case "M":
        box.addPoint(cmd.x, cmd.y);
        startX = prevX = cmd.x;
        startY = prevY = cmd.y;
        break;
      case "L":
        box.addPoint(cmd.x, cmd.y);
        prevX = cmd.x;
        prevY = cmd.y;
        break;
      case "Q":
        box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y);
        prevX = cmd.x;
        prevY = cmd.y;
        break;
      case "C":
        box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
        prevX = cmd.x;
        prevY = cmd.y;
        break;
      case "Z":
        prevX = startX;
        prevY = startY;
        break;
      default:
        throw new Error("Unexpected path command " + cmd.type);
    }
  }
  if (box.isEmpty()) {
    box.addPoint(0, 0);
  }
  return box;
};
Path2.prototype.draw = function(ctx) {
  ctx.beginPath();
  for (var i = 0; i < this.commands.length; i += 1) {
    var cmd = this.commands[i];
    if (cmd.type === "M") {
      ctx.moveTo(cmd.x, cmd.y);
    } else if (cmd.type === "L") {
      ctx.lineTo(cmd.x, cmd.y);
    } else if (cmd.type === "C") {
      ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
    } else if (cmd.type === "Q") {
      ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
    } else if (cmd.type === "Z") {
      ctx.closePath();
    }
  }
  if (this.fill) {
    ctx.fillStyle = this.fill;
    ctx.fill();
  }
  if (this.stroke) {
    ctx.strokeStyle = this.stroke;
    ctx.lineWidth = this.strokeWidth;
    ctx.stroke();
  }
};
Path2.prototype.toPathData = function(decimalPlaces) {
  decimalPlaces = decimalPlaces !== void 0 ? decimalPlaces : 2;
  function floatToString(v) {
    if (Math.round(v) === v) {
      return "" + Math.round(v);
    } else {
      return v.toFixed(decimalPlaces);
    }
  }
  function packValues() {
    var arguments$1 = arguments;
    var s = "";
    for (var i2 = 0; i2 < arguments.length; i2 += 1) {
      var v = arguments$1[i2];
      if (v >= 0 && i2 > 0) {
        s += " ";
      }
      s += floatToString(v);
    }
    return s;
  }
  var d = "";
  for (var i = 0; i < this.commands.length; i += 1) {
    var cmd = this.commands[i];
    if (cmd.type === "M") {
      d += "M" + packValues(cmd.x, cmd.y);
    } else if (cmd.type === "L") {
      d += "L" + packValues(cmd.x, cmd.y);
    } else if (cmd.type === "C") {
      d += "C" + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
    } else if (cmd.type === "Q") {
      d += "Q" + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y);
    } else if (cmd.type === "Z") {
      d += "Z";
    }
  }
  return d;
};
Path2.prototype.toSVG = function(decimalPlaces) {
  var svg = '<path d="';
  svg += this.toPathData(decimalPlaces);
  svg += '"';
  if (this.fill && this.fill !== "black") {
    if (this.fill === null) {
      svg += ' fill="none"';
    } else {
      svg += ' fill="' + this.fill + '"';
    }
  }
  if (this.stroke) {
    svg += ' stroke="' + this.stroke + '" stroke-width="' + this.strokeWidth + '"';
  }
  svg += "/>";
  return svg;
};
Path2.prototype.toDOMElement = function(decimalPlaces) {
  var temporaryPath = this.toPathData(decimalPlaces);
  var newPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
  newPath.setAttribute("d", temporaryPath);
  return newPath;
};
function fail(message) {
  throw new Error(message);
}
function argument(predicate, message) {
  if (!predicate) {
    fail(message);
  }
}
var check = { fail, argument, assert: argument };
var LIMIT16 = 32768;
var LIMIT32 = 2147483648;
var decode = {};
var encode = {};
var sizeOf = {};
function constant(v) {
  return function() {
    return v;
  };
}
encode.BYTE = function(v) {
  check.argument(v >= 0 && v <= 255, "Byte value should be between 0 and 255.");
  return [v];
};
sizeOf.BYTE = constant(1);
encode.CHAR = function(v) {
  return [v.charCodeAt(0)];
};
sizeOf.CHAR = constant(1);
encode.CHARARRAY = function(v) {
  if (typeof v === "undefined") {
    v = "";
    console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name.");
  }
  var b3 = [];
  for (var i = 0; i < v.length; i += 1) {
    b3[i] = v.charCodeAt(i);
  }
  return b3;
};
sizeOf.CHARARRAY = function(v) {
  if (typeof v === "undefined") {
    return 0;
  }
  return v.length;
};
encode.USHORT = function(v) {
  return [v >> 8 & 255, v & 255];
};
sizeOf.USHORT = constant(2);
encode.SHORT = function(v) {
  if (v >= LIMIT16) {
    v = -(2 * LIMIT16 - v);
  }
  return [v >> 8 & 255, v & 255];
};
sizeOf.SHORT = constant(2);
encode.UINT24 = function(v) {
  return [v >> 16 & 255, v >> 8 & 255, v & 255];
};
sizeOf.UINT24 = constant(3);
encode.ULONG = function(v) {
  return [v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255];
};
sizeOf.ULONG = constant(4);
encode.LONG = function(v) {
  if (v >= LIMIT32) {
    v = -(2 * LIMIT32 - v);
  }
  return [v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255];
};
sizeOf.LONG = constant(4);
encode.FIXED = encode.ULONG;
sizeOf.FIXED = sizeOf.ULONG;
encode.FWORD = encode.SHORT;
sizeOf.FWORD = sizeOf.SHORT;
encode.UFWORD = encode.USHORT;
sizeOf.UFWORD = sizeOf.USHORT;
encode.LONGDATETIME = function(v) {
  return [0, 0, 0, 0, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255];
};
sizeOf.LONGDATETIME = constant(8);
encode.TAG = function(v) {
  check.argument(v.length === 4, "Tag should be exactly 4 ASCII characters.");
  return [
    v.charCodeAt(0),
    v.charCodeAt(1),
    v.charCodeAt(2),
    v.charCodeAt(3)
  ];
};
sizeOf.TAG = constant(4);
encode.Card8 = encode.BYTE;
sizeOf.Card8 = sizeOf.BYTE;
encode.Card16 = encode.USHORT;
sizeOf.Card16 = sizeOf.USHORT;
encode.OffSize = encode.BYTE;
sizeOf.OffSize = sizeOf.BYTE;
encode.SID = encode.USHORT;
sizeOf.SID = sizeOf.USHORT;
encode.NUMBER = function(v) {
  if (v >= -107 && v <= 107) {
    return [v + 139];
  } else if (v >= 108 && v <= 1131) {
    v = v - 108;
    return [(v >> 8) + 247, v & 255];
  } else if (v >= -1131 && v <= -108) {
    v = -v - 108;
    return [(v >> 8) + 251, v & 255];
  } else if (v >= -32768 && v <= 32767) {
    return encode.NUMBER16(v);
  } else {
    return encode.NUMBER32(v);
  }
};
sizeOf.NUMBER = function(v) {
  return encode.NUMBER(v).length;
};
encode.NUMBER16 = function(v) {
  return [28, v >> 8 & 255, v & 255];
};
sizeOf.NUMBER16 = constant(3);
encode.NUMBER32 = function(v) {
  return [29, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255];
};
sizeOf.NUMBER32 = constant(5);
encode.REAL = function(v) {
  var value2 = v.toString();
  var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value2);
  if (m) {
    var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length));
    value2 = (Math.round(v * epsilon) / epsilon).toString();
  }
  var nibbles = "";
  for (var i = 0, ii = value2.length; i < ii; i += 1) {
    var c2 = value2[i];
    if (c2 === "e") {
      nibbles += value2[++i] === "-" ? "c" : "b";
    } else if (c2 === ".") {
      nibbles += "a";
    } else if (c2 === "-") {
      nibbles += "e";
    } else {
      nibbles += c2;
    }
  }
  nibbles += nibbles.length & 1 ? "f" : "ff";
  var out = [30];
  for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) {
    out.push(parseInt(nibbles.substr(i$1, 2), 16));
  }
  return out;
};
sizeOf.REAL = function(v) {
  return encode.REAL(v).length;
};
encode.NAME = encode.CHARARRAY;
sizeOf.NAME = sizeOf.CHARARRAY;
encode.STRING = encode.CHARARRAY;
sizeOf.STRING = sizeOf.CHARARRAY;
decode.UTF8 = function(data2, offset, numBytes) {
  var codePoints = [];
  var numChars = numBytes;
  for (var j2 = 0; j2 < numChars; j2++, offset += 1) {
    codePoints[j2] = data2.getUint8(offset);
  }
  return String.fromCharCode.apply(null, codePoints);
};
decode.UTF16 = function(data2, offset, numBytes) {
  var codePoints = [];
  var numChars = numBytes / 2;
  for (var j2 = 0; j2 < numChars; j2++, offset += 2) {
    codePoints[j2] = data2.getUint16(offset);
  }
  return String.fromCharCode.apply(null, codePoints);
};
encode.UTF16 = function(v) {
  var b3 = [];
  for (var i = 0; i < v.length; i += 1) {
    var codepoint = v.charCodeAt(i);
    b3[b3.length] = codepoint >> 8 & 255;
    b3[b3.length] = codepoint & 255;
  }
  return b3;
};
sizeOf.UTF16 = function(v) {
  return v.length * 2;
};
var eightBitMacEncodings = {
  "x-mac-croatian": (
    // Python: 'mac_croatian'
    "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
  ),
  "x-mac-cyrillic": (
    // Python: 'mac_cyrillic'
    "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю"
  ),
  "x-mac-gaelic": (
    // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT
    "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ"
  ),
  "x-mac-greek": (
    // Python: 'mac_greek'
    "Ä¹²É³ÖÜ΅àâä΄¨çéèêë£™îï•½‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­"
  ),
  "x-mac-icelandic": (
    // Python: 'mac_iceland'
    "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  ),
  "x-mac-inuit": (
    // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT
    "ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł"
  ),
  "x-mac-ce": (
    // Python: 'mac_latin2'
    "ÄĀāÉĄÖÜáąČäčĆćéŹźĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņŃ¬√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
  ),
  macintosh: (
    // Python: 'mac_roman'
    "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›ﬁﬂ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  ),
  "x-mac-romanian": (
    // Python: 'mac_romanian'
    "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  ),
  "x-mac-turkish": (
    // Python: 'mac_turkish'
    "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"
  )
};
decode.MACSTRING = function(dataView, offset, dataLength, encoding) {
  var table2 = eightBitMacEncodings[encoding];
  if (table2 === void 0) {
    return void 0;
  }
  var result = "";
  for (var i = 0; i < dataLength; i++) {
    var c2 = dataView.getUint8(offset + i);
    if (c2 <= 127) {
      result += String.fromCharCode(c2);
    } else {
      result += table2[c2 & 127];
    }
  }
  return result;
};
var macEncodingTableCache = typeof WeakMap === "function" && /* @__PURE__ */ new WeakMap();
var macEncodingCacheKeys;
var getMacEncodingTable = function(encoding) {
  if (!macEncodingCacheKeys) {
    macEncodingCacheKeys = {};
    for (var e in eightBitMacEncodings) {
      macEncodingCacheKeys[e] = new String(e);
    }
  }
  var cacheKey = macEncodingCacheKeys[encoding];
  if (cacheKey === void 0) {
    return void 0;
  }
  if (macEncodingTableCache) {
    var cachedTable = macEncodingTableCache.get(cacheKey);
    if (cachedTable !== void 0) {
      return cachedTable;
    }
  }
  var decodingTable = eightBitMacEncodings[encoding];
  if (decodingTable === void 0) {
    return void 0;
  }
  var encodingTable = {};
  for (var i = 0; i < decodingTable.length; i++) {
    encodingTable[decodingTable.charCodeAt(i)] = i + 128;
  }
  if (macEncodingTableCache) {
    macEncodingTableCache.set(cacheKey, encodingTable);
  }
  return encodingTable;
};
encode.MACSTRING = function(str, encoding) {
  var table2 = getMacEncodingTable(encoding);
  if (table2 === void 0) {
    return void 0;
  }
  var result = [];
  for (var i = 0; i < str.length; i++) {
    var c2 = str.charCodeAt(i);
    if (c2 >= 128) {
      c2 = table2[c2];
      if (c2 === void 0) {
        return void 0;
      }
    }
    result[i] = c2;
  }
  return result;
};
sizeOf.MACSTRING = function(str, encoding) {
  var b3 = encode.MACSTRING(str, encoding);
  if (b3 !== void 0) {
    return b3.length;
  } else {
    return 0;
  }
};
function isByteEncodable(value2) {
  return value2 >= -128 && value2 <= 127;
}
function encodeVarDeltaRunAsZeroes(deltas, pos, result) {
  var runLength = 0;
  var numDeltas = deltas.length;
  while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) {
    ++pos;
    ++runLength;
  }
  result.push(128 | runLength - 1);
  return pos;
}
function encodeVarDeltaRunAsBytes(deltas, offset, result) {
  var runLength = 0;
  var numDeltas = deltas.length;
  var pos = offset;
  while (pos < numDeltas && runLength < 64) {
    var value2 = deltas[pos];
    if (!isByteEncodable(value2)) {
      break;
    }
    if (value2 === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) {
      break;
    }
    ++pos;
    ++runLength;
  }
  result.push(runLength - 1);
  for (var i = offset; i < pos; ++i) {
    result.push(deltas[i] + 256 & 255);
  }
  return pos;
}
function encodeVarDeltaRunAsWords(deltas, offset, result) {
  var runLength = 0;
  var numDeltas = deltas.length;
  var pos = offset;
  while (pos < numDeltas && runLength < 64) {
    var value2 = deltas[pos];
    if (value2 === 0) {
      break;
    }
    if (isByteEncodable(value2) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) {
      break;
    }
    ++pos;
    ++runLength;
  }
  result.push(64 | runLength - 1);
  for (var i = offset; i < pos; ++i) {
    var val2 = deltas[i];
    result.push(val2 + 65536 >> 8 & 255, val2 + 256 & 255);
  }
  return pos;
}
encode.VARDELTAS = function(deltas) {
  var pos = 0;
  var result = [];
  while (pos < deltas.length) {
    var value2 = deltas[pos];
    if (value2 === 0) {
      pos = encodeVarDeltaRunAsZeroes(deltas, pos, result);
    } else if (value2 >= -128 && value2 <= 127) {
      pos = encodeVarDeltaRunAsBytes(deltas, pos, result);
    } else {
      pos = encodeVarDeltaRunAsWords(deltas, pos, result);
    }
  }
  return result;
};
encode.INDEX = function(l2) {
  var offset = 1;
  var offsets = [offset];
  var data2 = [];
  for (var i = 0; i < l2.length; i += 1) {
    var v = encode.OBJECT(l2[i]);
    Array.prototype.push.apply(data2, v);
    offset += v.length;
    offsets.push(offset);
  }
  if (data2.length === 0) {
    return [0, 0];
  }
  var encodedOffsets = [];
  var offSize = 1 + Math.floor(Math.log(offset) / Math.log(2)) / 8 | 0;
  var offsetEncoder = [void 0, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize];
  for (var i$1 = 0; i$1 < offsets.length; i$1 += 1) {
    var encodedOffset = offsetEncoder(offsets[i$1]);
    Array.prototype.push.apply(encodedOffsets, encodedOffset);
  }
  return Array.prototype.concat(
    encode.Card16(l2.length),
    encode.OffSize(offSize),
    encodedOffsets,
    data2
  );
};
sizeOf.INDEX = function(v) {
  return encode.INDEX(v).length;
};
encode.DICT = function(m) {
  var d = [];
  var keys2 = Object.keys(m);
  var length2 = keys2.length;
  for (var i = 0; i < length2; i += 1) {
    var k2 = parseInt(keys2[i], 0);
    var v = m[k2];
    d = d.concat(encode.OPERAND(v.value, v.type));
    d = d.concat(encode.OPERATOR(k2));
  }
  return d;
};
sizeOf.DICT = function(m) {
  return encode.DICT(m).length;
};
encode.OPERATOR = function(v) {
  if (v < 1200) {
    return [v];
  } else {
    return [12, v - 1200];
  }
};
encode.OPERAND = function(v, type) {
  var d = [];
  if (Array.isArray(type)) {
    for (var i = 0; i < type.length; i += 1) {
      check.argument(v.length === type.length, "Not enough arguments given for type" + type);
      d = d.concat(encode.OPERAND(v[i], type[i]));
    }
  } else {
    if (type === "SID") {
      d = d.concat(encode.NUMBER(v));
    } else if (type === "offset") {
      d = d.concat(encode.NUMBER32(v));
    } else if (type === "number") {
      d = d.concat(encode.NUMBER(v));
    } else if (type === "real") {
      d = d.concat(encode.REAL(v));
    } else {
      throw new Error("Unknown operand type " + type);
    }
  }
  return d;
};
encode.OP = encode.BYTE;
sizeOf.OP = sizeOf.BYTE;
var wmm = typeof WeakMap === "function" && /* @__PURE__ */ new WeakMap();
encode.CHARSTRING = function(ops) {
  if (wmm) {
    var cachedValue = wmm.get(ops);
    if (cachedValue !== void 0) {
      return cachedValue;
    }
  }
  var d = [];
  var length2 = ops.length;
  for (var i = 0; i < length2; i += 1) {
    var op = ops[i];
    d = d.concat(encode[op.type](op.value));
  }
  if (wmm) {
    wmm.set(ops, d);
  }
  return d;
};
sizeOf.CHARSTRING = function(ops) {
  return encode.CHARSTRING(ops).length;
};
encode.OBJECT = function(v) {
  var encodingFunction = encode[v.type];
  check.argument(encodingFunction !== void 0, "No encoding function for type " + v.type);
  return encodingFunction(v.value);
};
sizeOf.OBJECT = function(v) {
  var sizeOfFunction = sizeOf[v.type];
  check.argument(sizeOfFunction !== void 0, "No sizeOf function for type " + v.type);
  return sizeOfFunction(v.value);
};
encode.TABLE = function(table2) {
  var d = [];
  var length2 = table2.fields.length;
  var subtables = [];
  var subtableOffsets = [];
  for (var i = 0; i < length2; i += 1) {
    var field = table2.fields[i];
    var encodingFunction = encode[field.type];
    check.argument(encodingFunction !== void 0, "No encoding function for field type " + field.type + " (" + field.name + ")");
    var value2 = table2[field.name];
    if (value2 === void 0) {
      value2 = field.value;
    }
    var bytes = encodingFunction(value2);
    if (field.type === "TABLE") {
      subtableOffsets.push(d.length);
      d = d.concat([0, 0]);
      subtables.push(bytes);
    } else {
      d = d.concat(bytes);
    }
  }
  for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) {
    var o = subtableOffsets[i$1];
    var offset = d.length;
    check.argument(offset < 65536, "Table " + table2.tableName + " too big.");
    d[o] = offset >> 8;
    d[o + 1] = offset & 255;
    d = d.concat(subtables[i$1]);
  }
  return d;
};
sizeOf.TABLE = function(table2) {
  var numBytes = 0;
  var length2 = table2.fields.length;
  for (var i = 0; i < length2; i += 1) {
    var field = table2.fields[i];
    var sizeOfFunction = sizeOf[field.type];
    check.argument(sizeOfFunction !== void 0, "No sizeOf function for field type " + field.type + " (" + field.name + ")");
    var value2 = table2[field.name];
    if (value2 === void 0) {
      value2 = field.value;
    }
    numBytes += sizeOfFunction(value2);
    if (field.type === "TABLE") {
      numBytes += 2;
    }
  }
  return numBytes;
};
encode.RECORD = encode.TABLE;
sizeOf.RECORD = sizeOf.TABLE;
encode.LITERAL = function(v) {
  return v;
};
sizeOf.LITERAL = function(v) {
  return v.length;
};
function Table(tableName, fields, options) {
  if (fields.length && (fields[0].name !== "coverageFormat" || fields[0].value === 1)) {
    for (var i = 0; i < fields.length; i += 1) {
      var field = fields[i];
      this[field.name] = field.value;
    }
  }
  this.tableName = tableName;
  this.fields = fields;
  if (options) {
    var optionKeys = Object.keys(options);
    for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) {
      var k2 = optionKeys[i$1];
      var v = options[k2];
      if (this[k2] !== void 0) {
        this[k2] = v;
      }
    }
  }
}
Table.prototype.encode = function() {
  return encode.TABLE(this);
};
Table.prototype.sizeOf = function() {
  return sizeOf.TABLE(this);
};
function ushortList(itemName, list, count) {
  if (count === void 0) {
    count = list.length;
  }
  var fields = new Array(list.length + 1);
  fields[0] = { name: itemName + "Count", type: "USHORT", value: count };
  for (var i = 0; i < list.length; i++) {
    fields[i + 1] = { name: itemName + i, type: "USHORT", value: list[i] };
  }
  return fields;
}
function tableList(itemName, records, itemCallback) {
  var count = records.length;
  var fields = new Array(count + 1);
  fields[0] = { name: itemName + "Count", type: "USHORT", value: count };
  for (var i = 0; i < count; i++) {
    fields[i + 1] = { name: itemName + i, type: "TABLE", value: itemCallback(records[i], i) };
  }
  return fields;
}
function recordList(itemName, records, itemCallback) {
  var count = records.length;
  var fields = [];
  fields[0] = { name: itemName + "Count", type: "USHORT", value: count };
  for (var i = 0; i < count; i++) {
    fields = fields.concat(itemCallback(records[i], i));
  }
  return fields;
}
function Coverage(coverageTable) {
  if (coverageTable.format === 1) {
    Table.call(
      this,
      "coverageTable",
      [{ name: "coverageFormat", type: "USHORT", value: 1 }].concat(ushortList("glyph", coverageTable.glyphs))
    );
  } else if (coverageTable.format === 2) {
    Table.call(
      this,
      "coverageTable",
      [{ name: "coverageFormat", type: "USHORT", value: 2 }].concat(recordList("rangeRecord", coverageTable.ranges, function(RangeRecord) {
        return [
          { name: "startGlyphID", type: "USHORT", value: RangeRecord.start },
          { name: "endGlyphID", type: "USHORT", value: RangeRecord.end },
          { name: "startCoverageIndex", type: "USHORT", value: RangeRecord.index }
        ];
      }))
    );
  } else {
    check.assert(false, "Coverage format must be 1 or 2.");
  }
}
Coverage.prototype = Object.create(Table.prototype);
Coverage.prototype.constructor = Coverage;
function ScriptList(scriptListTable) {
  Table.call(
    this,
    "scriptListTable",
    recordList("scriptRecord", scriptListTable, function(scriptRecord, i) {
      var script = scriptRecord.script;
      var defaultLangSys = script.defaultLangSys;
      check.assert(!!defaultLangSys, "Unable to write GSUB: script " + scriptRecord.tag + " has no default language system.");
      return [
        { name: "scriptTag" + i, type: "TAG", value: scriptRecord.tag },
        { name: "script" + i, type: "TABLE", value: new Table("scriptTable", [
          { name: "defaultLangSys", type: "TABLE", value: new Table("defaultLangSys", [
            { name: "lookupOrder", type: "USHORT", value: 0 },
            { name: "reqFeatureIndex", type: "USHORT", value: defaultLangSys.reqFeatureIndex }
          ].concat(ushortList("featureIndex", defaultLangSys.featureIndexes))) }
        ].concat(recordList("langSys", script.langSysRecords, function(langSysRecord, i2) {
          var langSys = langSysRecord.langSys;
          return [
            { name: "langSysTag" + i2, type: "TAG", value: langSysRecord.tag },
            { name: "langSys" + i2, type: "TABLE", value: new Table("langSys", [
              { name: "lookupOrder", type: "USHORT", value: 0 },
              { name: "reqFeatureIndex", type: "USHORT", value: langSys.reqFeatureIndex }
            ].concat(ushortList("featureIndex", langSys.featureIndexes))) }
          ];
        }))) }
      ];
    })
  );
}
ScriptList.prototype = Object.create(Table.prototype);
ScriptList.prototype.constructor = ScriptList;
function FeatureList(featureListTable) {
  Table.call(
    this,
    "featureListTable",
    recordList("featureRecord", featureListTable, function(featureRecord, i) {
      var feature = featureRecord.feature;
      return [
        { name: "featureTag" + i, type: "TAG", value: featureRecord.tag },
        { name: "feature" + i, type: "TABLE", value: new Table("featureTable", [
          { name: "featureParams", type: "USHORT", value: feature.featureParams }
        ].concat(ushortList("lookupListIndex", feature.lookupListIndexes))) }
      ];
    })
  );
}
FeatureList.prototype = Object.create(Table.prototype);
FeatureList.prototype.constructor = FeatureList;
function LookupList(lookupListTable, subtableMakers2) {
  Table.call(this, "lookupListTable", tableList("lookup", lookupListTable, function(lookupTable) {
    var subtableCallback = subtableMakers2[lookupTable.lookupType];
    check.assert(!!subtableCallback, "Unable to write GSUB lookup type " + lookupTable.lookupType + " tables.");
    return new Table("lookupTable", [
      { name: "lookupType", type: "USHORT", value: lookupTable.lookupType },
      { name: "lookupFlag", type: "USHORT", value: lookupTable.lookupFlag }
    ].concat(tableList("subtable", lookupTable.subtables, subtableCallback)));
  }));
}
LookupList.prototype = Object.create(Table.prototype);
LookupList.prototype.constructor = LookupList;
var table = {
  Table,
  Record: Table,
  Coverage,
  ScriptList,
  FeatureList,
  LookupList,
  ushortList,
  tableList,
  recordList
};
function getByte(dataView, offset) {
  return dataView.getUint8(offset);
}
function getUShort(dataView, offset) {
  return dataView.getUint16(offset, false);
}
function getShort(dataView, offset) {
  return dataView.getInt16(offset, false);
}
function getULong(dataView, offset) {
  return dataView.getUint32(offset, false);
}
function getFixed(dataView, offset) {
  var decimal = dataView.getInt16(offset, false);
  var fraction = dataView.getUint16(offset + 2, false);
  return decimal + fraction / 65535;
}
function getTag(dataView, offset) {
  var tag = "";
  for (var i = offset; i < offset + 4; i += 1) {
    tag += String.fromCharCode(dataView.getInt8(i));
  }
  return tag;
}
function getOffset(dataView, offset, offSize) {
  var v = 0;
  for (var i = 0; i < offSize; i += 1) {
    v <<= 8;
    v += dataView.getUint8(offset + i);
  }
  return v;
}
function getBytes(dataView, startOffset, endOffset) {
  var bytes = [];
  for (var i = startOffset; i < endOffset; i += 1) {
    bytes.push(dataView.getUint8(i));
  }
  return bytes;
}
function bytesToString(bytes) {
  var s = "";
  for (var i = 0; i < bytes.length; i += 1) {
    s += String.fromCharCode(bytes[i]);
  }
  return s;
}
var typeOffsets = {
  byte: 1,
  uShort: 2,
  short: 2,
  uLong: 4,
  fixed: 4,
  longDateTime: 8,
  tag: 4
};
function Parser(data2, offset) {
  this.data = data2;
  this.offset = offset;
  this.relativeOffset = 0;
}
Parser.prototype.parseByte = function() {
  var v = this.data.getUint8(this.offset + this.relativeOffset);
  this.relativeOffset += 1;
  return v;
};
Parser.prototype.parseChar = function() {
  var v = this.data.getInt8(this.offset + this.relativeOffset);
  this.relativeOffset += 1;
  return v;
};
Parser.prototype.parseCard8 = Parser.prototype.parseByte;
Parser.prototype.parseUShort = function() {
  var v = this.data.getUint16(this.offset + this.relativeOffset);
  this.relativeOffset += 2;
  return v;
};
Parser.prototype.parseCard16 = Parser.prototype.parseUShort;
Parser.prototype.parseSID = Parser.prototype.parseUShort;
Parser.prototype.parseOffset16 = Parser.prototype.parseUShort;
Parser.prototype.parseShort = function() {
  var v = this.data.getInt16(this.offset + this.relativeOffset);
  this.relativeOffset += 2;
  return v;
};
Parser.prototype.parseF2Dot14 = function() {
  var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384;
  this.relativeOffset += 2;
  return v;
};
Parser.prototype.parseULong = function() {
  var v = getULong(this.data, this.offset + this.relativeOffset);
  this.relativeOffset += 4;
  return v;
};
Parser.prototype.parseOffset32 = Parser.prototype.parseULong;
Parser.prototype.parseFixed = function() {
  var v = getFixed(this.data, this.offset + this.relativeOffset);
  this.relativeOffset += 4;
  return v;
};
Parser.prototype.parseString = function(length2) {
  var dataView = this.data;
  var offset = this.offset + this.relativeOffset;
  var string = "";
  this.relativeOffset += length2;
  for (var i = 0; i < length2; i++) {
    string += String.fromCharCode(dataView.getUint8(offset + i));
  }
  return string;
};
Parser.prototype.parseTag = function() {
  return this.parseString(4);
};
Parser.prototype.parseLongDateTime = function() {
  var v = getULong(this.data, this.offset + this.relativeOffset + 4);
  v -= 2082844800;
  this.relativeOffset += 8;
  return v;
};
Parser.prototype.parseVersion = function(minorBase) {
  var major = getUShort(this.data, this.offset + this.relativeOffset);
  var minor = getUShort(this.data, this.offset + this.relativeOffset + 2);
  this.relativeOffset += 4;
  if (minorBase === void 0) {
    minorBase = 4096;
  }
  return major + minor / minorBase / 10;
};
Parser.prototype.skip = function(type, amount) {
  if (amount === void 0) {
    amount = 1;
  }
  this.relativeOffset += typeOffsets[type] * amount;
};
Parser.prototype.parseULongList = function(count) {
  if (count === void 0) {
    count = this.parseULong();
  }
  var offsets = new Array(count);
  var dataView = this.data;
  var offset = this.offset + this.relativeOffset;
  for (var i = 0; i < count; i++) {
    offsets[i] = dataView.getUint32(offset);
    offset += 4;
  }
  this.relativeOffset += count * 4;
  return offsets;
};
Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(count) {
  if (count === void 0) {
    count = this.parseUShort();
  }
  var offsets = new Array(count);
  var dataView = this.data;
  var offset = this.offset + this.relativeOffset;
  for (var i = 0; i < count; i++) {
    offsets[i] = dataView.getUint16(offset);
    offset += 2;
  }
  this.relativeOffset += count * 2;
  return offsets;
};
Parser.prototype.parseShortList = function(count) {
  var list = new Array(count);
  var dataView = this.data;
  var offset = this.offset + this.relativeOffset;
  for (var i = 0; i < count; i++) {
    list[i] = dataView.getInt16(offset);
    offset += 2;
  }
  this.relativeOffset += count * 2;
  return list;
};
Parser.prototype.parseByteList = function(count) {
  var list = new Array(count);
  var dataView = this.data;
  var offset = this.offset + this.relativeOffset;
  for (var i = 0; i < count; i++) {
    list[i] = dataView.getUint8(offset++);
  }
  this.relativeOffset += count;
  return list;
};
Parser.prototype.parseList = function(count, itemCallback) {
  if (!itemCallback) {
    itemCallback = count;
    count = this.parseUShort();
  }
  var list = new Array(count);
  for (var i = 0; i < count; i++) {
    list[i] = itemCallback.call(this);
  }
  return list;
};
Parser.prototype.parseList32 = function(count, itemCallback) {
  if (!itemCallback) {
    itemCallback = count;
    count = this.parseULong();
  }
  var list = new Array(count);
  for (var i = 0; i < count; i++) {
    list[i] = itemCallback.call(this);
  }
  return list;
};
Parser.prototype.parseRecordList = function(count, recordDescription) {
  if (!recordDescription) {
    recordDescription = count;
    count = this.parseUShort();
  }
  var records = new Array(count);
  var fields = Object.keys(recordDescription);
  for (var i = 0; i < count; i++) {
    var rec = {};
    for (var j2 = 0; j2 < fields.length; j2++) {
      var fieldName = fields[j2];
      var fieldType = recordDescription[fieldName];
      rec[fieldName] = fieldType.call(this);
    }
    records[i] = rec;
  }
  return records;
};
Parser.prototype.parseRecordList32 = function(count, recordDescription) {
  if (!recordDescription) {
    recordDescription = count;
    count = this.parseULong();
  }
  var records = new Array(count);
  var fields = Object.keys(recordDescription);
  for (var i = 0; i < count; i++) {
    var rec = {};
    for (var j2 = 0; j2 < fields.length; j2++) {
      var fieldName = fields[j2];
      var fieldType = recordDescription[fieldName];
      rec[fieldName] = fieldType.call(this);
    }
    records[i] = rec;
  }
  return records;
};
Parser.prototype.parseStruct = function(description) {
  if (typeof description === "function") {
    return description.call(this);
  } else {
    var fields = Object.keys(description);
    var struct = {};
    for (var j2 = 0; j2 < fields.length; j2++) {
      var fieldName = fields[j2];
      var fieldType = description[fieldName];
      struct[fieldName] = fieldType.call(this);
    }
    return struct;
  }
};
Parser.prototype.parseValueRecord = function(valueFormat) {
  if (valueFormat === void 0) {
    valueFormat = this.parseUShort();
  }
  if (valueFormat === 0) {
    return;
  }
  var valueRecord = {};
  if (valueFormat & 1) {
    valueRecord.xPlacement = this.parseShort();
  }
  if (valueFormat & 2) {
    valueRecord.yPlacement = this.parseShort();
  }
  if (valueFormat & 4) {
    valueRecord.xAdvance = this.parseShort();
  }
  if (valueFormat & 8) {
    valueRecord.yAdvance = this.parseShort();
  }
  if (valueFormat & 16) {
    valueRecord.xPlaDevice = void 0;
    this.parseShort();
  }
  if (valueFormat & 32) {
    valueRecord.yPlaDevice = void 0;
    this.parseShort();
  }
  if (valueFormat & 64) {
    valueRecord.xAdvDevice = void 0;
    this.parseShort();
  }
  if (valueFormat & 128) {
    valueRecord.yAdvDevice = void 0;
    this.parseShort();
  }
  return valueRecord;
};
Parser.prototype.parseValueRecordList = function() {
  var valueFormat = this.parseUShort();
  var valueCount = this.parseUShort();
  var values2 = new Array(valueCount);
  for (var i = 0; i < valueCount; i++) {
    values2[i] = this.parseValueRecord(valueFormat);
  }
  return values2;
};
Parser.prototype.parsePointer = function(description) {
  var structOffset = this.parseOffset16();
  if (structOffset > 0) {
    return new Parser(this.data, this.offset + structOffset).parseStruct(description);
  }
  return void 0;
};
Parser.prototype.parsePointer32 = function(description) {
  var structOffset = this.parseOffset32();
  if (structOffset > 0) {
    return new Parser(this.data, this.offset + structOffset).parseStruct(description);
  }
  return void 0;
};
Parser.prototype.parseListOfLists = function(itemCallback) {
  var offsets = this.parseOffset16List();
  var count = offsets.length;
  var relativeOffset = this.relativeOffset;
  var list = new Array(count);
  for (var i = 0; i < count; i++) {
    var start = offsets[i];
    if (start === 0) {
      list[i] = void 0;
      continue;
    }
    this.relativeOffset = start;
    if (itemCallback) {
      var subOffsets = this.parseOffset16List();
      var subList = new Array(subOffsets.length);
      for (var j2 = 0; j2 < subOffsets.length; j2++) {
        this.relativeOffset = start + subOffsets[j2];
        subList[j2] = itemCallback.call(this);
      }
      list[i] = subList;
    } else {
      list[i] = this.parseUShortList();
    }
  }
  this.relativeOffset = relativeOffset;
  return list;
};
Parser.prototype.parseCoverage = function() {
  var startOffset = this.offset + this.relativeOffset;
  var format = this.parseUShort();
  var count = this.parseUShort();
  if (format === 1) {
    return {
      format: 1,
      glyphs: this.parseUShortList(count)
    };
  } else if (format === 2) {
    var ranges = new Array(count);
    for (var i = 0; i < count; i++) {
      ranges[i] = {
        start: this.parseUShort(),
        end: this.parseUShort(),
        index: this.parseUShort()
      };
    }
    return {
      format: 2,
      ranges
    };
  }
  throw new Error("0x" + startOffset.toString(16) + ": Coverage format must be 1 or 2.");
};
Parser.prototype.parseClassDef = function() {
  var startOffset = this.offset + this.relativeOffset;
  var format = this.parseUShort();
  if (format === 1) {
    return {
      format: 1,
      startGlyph: this.parseUShort(),
      classes: this.parseUShortList()
    };
  } else if (format === 2) {
    return {
      format: 2,
      ranges: this.parseRecordList({
        start: Parser.uShort,
        end: Parser.uShort,
        classId: Parser.uShort
      })
    };
  }
  throw new Error("0x" + startOffset.toString(16) + ": ClassDef format must be 1 or 2.");
};
Parser.list = function(count, itemCallback) {
  return function() {
    return this.parseList(count, itemCallback);
  };
};
Parser.list32 = function(count, itemCallback) {
  return function() {
    return this.parseList32(count, itemCallback);
  };
};
Parser.recordList = function(count, recordDescription) {
  return function() {
    return this.parseRecordList(count, recordDescription);
  };
};
Parser.recordList32 = function(count, recordDescription) {
  return function() {
    return this.parseRecordList32(count, recordDescription);
  };
};
Parser.pointer = function(description) {
  return function() {
    return this.parsePointer(description);
  };
};
Parser.pointer32 = function(description) {
  return function() {
    return this.parsePointer32(description);
  };
};
Parser.tag = Parser.prototype.parseTag;
Parser.byte = Parser.prototype.parseByte;
Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort;
Parser.uShortList = Parser.prototype.parseUShortList;
Parser.uLong = Parser.offset32 = Parser.prototype.parseULong;
Parser.uLongList = Parser.prototype.parseULongList;
Parser.struct = Parser.prototype.parseStruct;
Parser.coverage = Parser.prototype.parseCoverage;
Parser.classDef = Parser.prototype.parseClassDef;
var langSysTable = {
  reserved: Parser.uShort,
  reqFeatureIndex: Parser.uShort,
  featureIndexes: Parser.uShortList
};
Parser.prototype.parseScriptList = function() {
  return this.parsePointer(Parser.recordList({
    tag: Parser.tag,
    script: Parser.pointer({
      defaultLangSys: Parser.pointer(langSysTable),
      langSysRecords: Parser.recordList({
        tag: Parser.tag,
        langSys: Parser.pointer(langSysTable)
      })
    })
  })) || [];
};
Parser.prototype.parseFeatureList = function() {
  return this.parsePointer(Parser.recordList({
    tag: Parser.tag,
    feature: Parser.pointer({
      featureParams: Parser.offset16,
      lookupListIndexes: Parser.uShortList
    })
  })) || [];
};
Parser.prototype.parseLookupList = function(lookupTableParsers) {
  return this.parsePointer(Parser.list(Parser.pointer(function() {
    var lookupType = this.parseUShort();
    check.argument(1 <= lookupType && lookupType <= 9, "GPOS/GSUB lookup type " + lookupType + " unknown.");
    var lookupFlag = this.parseUShort();
    var useMarkFilteringSet = lookupFlag & 16;
    return {
      lookupType,
      lookupFlag,
      subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])),
      markFilteringSet: useMarkFilteringSet ? this.parseUShort() : void 0
    };
  }))) || [];
};
Parser.prototype.parseFeatureVariationsList = function() {
  return this.parsePointer32(function() {
    var majorVersion = this.parseUShort();
    var minorVersion = this.parseUShort();
    check.argument(majorVersion === 1 && minorVersion < 1, "GPOS/GSUB feature variations table unknown.");
    var featureVariations = this.parseRecordList32({
      conditionSetOffset: Parser.offset32,
      featureTableSubstitutionOffset: Parser.offset32
    });
    return featureVariations;
  }) || [];
};
var parse = {
  getByte,
  getCard8: getByte,
  getUShort,
  getCard16: getUShort,
  getShort,
  getULong,
  getFixed,
  getTag,
  getOffset,
  getBytes,
  bytesToString,
  Parser
};
function parseCmapTableFormat12(cmap2, p) {
  p.parseUShort();
  cmap2.length = p.parseULong();
  cmap2.language = p.parseULong();
  var groupCount;
  cmap2.groupCount = groupCount = p.parseULong();
  cmap2.glyphIndexMap = {};
  for (var i = 0; i < groupCount; i += 1) {
    var startCharCode = p.parseULong();
    var endCharCode = p.parseULong();
    var startGlyphId = p.parseULong();
    for (var c2 = startCharCode; c2 <= endCharCode; c2 += 1) {
      cmap2.glyphIndexMap[c2] = startGlyphId;
      startGlyphId++;
    }
  }
}
function parseCmapTableFormat4(cmap2, p, data2, start, offset) {
  cmap2.length = p.parseUShort();
  cmap2.language = p.parseUShort();
  var segCount;
  cmap2.segCount = segCount = p.parseUShort() >> 1;
  p.skip("uShort", 3);
  cmap2.glyphIndexMap = {};
  var endCountParser = new parse.Parser(data2, start + offset + 14);
  var startCountParser = new parse.Parser(data2, start + offset + 16 + segCount * 2);
  var idDeltaParser = new parse.Parser(data2, start + offset + 16 + segCount * 4);
  var idRangeOffsetParser = new parse.Parser(data2, start + offset + 16 + segCount * 6);
  var glyphIndexOffset = start + offset + 16 + segCount * 8;
  for (var i = 0; i < segCount - 1; i += 1) {
    var glyphIndex = void 0;
    var endCount = endCountParser.parseUShort();
    var startCount = startCountParser.parseUShort();
    var idDelta = idDeltaParser.parseShort();
    var idRangeOffset = idRangeOffsetParser.parseUShort();
    for (var c2 = startCount; c2 <= endCount; c2 += 1) {
      if (idRangeOffset !== 0) {
        glyphIndexOffset = idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2;
        glyphIndexOffset += idRangeOffset;
        glyphIndexOffset += (c2 - startCount) * 2;
        glyphIndex = parse.getUShort(data2, glyphIndexOffset);
        if (glyphIndex !== 0) {
          glyphIndex = glyphIndex + idDelta & 65535;
        }
      } else {
        glyphIndex = c2 + idDelta & 65535;
      }
      cmap2.glyphIndexMap[c2] = glyphIndex;
    }
  }
}
function parseCmapTable(data2, start) {
  var cmap2 = {};
  cmap2.version = parse.getUShort(data2, start);
  check.argument(cmap2.version === 0, "cmap table version should be 0.");
  cmap2.numTables = parse.getUShort(data2, start + 2);
  var offset = -1;
  for (var i = cmap2.numTables - 1; i >= 0; i -= 1) {
    var platformId = parse.getUShort(data2, start + 4 + i * 8);
    var encodingId = parse.getUShort(data2, start + 4 + i * 8 + 2);
    if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10) || platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4)) {
      offset = parse.getULong(data2, start + 4 + i * 8 + 4);
      break;
    }
  }
  if (offset === -1) {
    throw new Error("No valid cmap sub-tables found.");
  }
  var p = new parse.Parser(data2, start + offset);
  cmap2.format = p.parseUShort();
  if (cmap2.format === 12) {
    parseCmapTableFormat12(cmap2, p);
  } else if (cmap2.format === 4) {
    parseCmapTableFormat4(cmap2, p, data2, start, offset);
  } else {
    throw new Error("Only format 4 and 12 cmap tables are supported (found format " + cmap2.format + ").");
  }
  return cmap2;
}
function addSegment(t3, code, glyphIndex) {
  t3.segments.push({
    end: code,
    start: code,
    delta: -(code - glyphIndex),
    offset: 0,
    glyphIndex
  });
}
function addTerminatorSegment(t3) {
  t3.segments.push({
    end: 65535,
    start: 65535,
    delta: 1,
    offset: 0
  });
}
function makeCmapTable(glyphs) {
  var isPlan0Only = true;
  var i;
  for (i = glyphs.length - 1; i > 0; i -= 1) {
    var g3 = glyphs.get(i);
    if (g3.unicode > 65535) {
      console.log("Adding CMAP format 12 (needed!)");
      isPlan0Only = false;
      break;
    }
  }
  var cmapTable = [
    { name: "version", type: "USHORT", value: 0 },
    { name: "numTables", type: "USHORT", value: isPlan0Only ? 1 : 2 },
    // CMAP 4 header
    { name: "platformID", type: "USHORT", value: 3 },
    { name: "encodingID", type: "USHORT", value: 1 },
    { name: "offset", type: "ULONG", value: isPlan0Only ? 12 : 12 + 8 }
  ];
  if (!isPlan0Only) {
    cmapTable = cmapTable.concat([
      // CMAP 12 header
      { name: "cmap12PlatformID", type: "USHORT", value: 3 },
      // We encode only for PlatformID = 3 (Windows) because it is supported everywhere
      { name: "cmap12EncodingID", type: "USHORT", value: 10 },
      { name: "cmap12Offset", type: "ULONG", value: 0 }
    ]);
  }
  cmapTable = cmapTable.concat([
    // CMAP 4 Subtable
    { name: "format", type: "USHORT", value: 4 },
    { name: "cmap4Length", type: "USHORT", value: 0 },
    { name: "language", type: "USHORT", value: 0 },
    { name: "segCountX2", type: "USHORT", value: 0 },
    { name: "searchRange", type: "USHORT", value: 0 },
    { name: "entrySelector", type: "USHORT", value: 0 },
    { name: "rangeShift", type: "USHORT", value: 0 }
  ]);
  var t3 = new table.Table("cmap", cmapTable);
  t3.segments = [];
  for (i = 0; i < glyphs.length; i += 1) {
    var glyph = glyphs.get(i);
    for (var j2 = 0; j2 < glyph.unicodes.length; j2 += 1) {
      addSegment(t3, glyph.unicodes[j2], i);
    }
    t3.segments = t3.segments.sort(function(a2, b3) {
      return a2.start - b3.start;
    });
  }
  addTerminatorSegment(t3);
  var segCount = t3.segments.length;
  var segCountToRemove = 0;
  var endCounts = [];
  var startCounts = [];
  var idDeltas = [];
  var idRangeOffsets = [];
  var glyphIds = [];
  var cmap12Groups = [];
  for (i = 0; i < segCount; i += 1) {
    var segment = t3.segments[i];
    if (segment.end <= 65535 && segment.start <= 65535) {
      endCounts = endCounts.concat({ name: "end_" + i, type: "USHORT", value: segment.end });
      startCounts = startCounts.concat({ name: "start_" + i, type: "USHORT", value: segment.start });
      idDeltas = idDeltas.concat({ name: "idDelta_" + i, type: "SHORT", value: segment.delta });
      idRangeOffsets = idRangeOffsets.concat({ name: "idRangeOffset_" + i, type: "USHORT", value: segment.offset });
      if (segment.glyphId !== void 0) {
        glyphIds = glyphIds.concat({ name: "glyph_" + i, type: "USHORT", value: segment.glyphId });
      }
    } else {
      segCountToRemove += 1;
    }
    if (!isPlan0Only && segment.glyphIndex !== void 0) {
      cmap12Groups = cmap12Groups.concat({ name: "cmap12Start_" + i, type: "ULONG", value: segment.start });
      cmap12Groups = cmap12Groups.concat({ name: "cmap12End_" + i, type: "ULONG", value: segment.end });
      cmap12Groups = cmap12Groups.concat({ name: "cmap12Glyph_" + i, type: "ULONG", value: segment.glyphIndex });
    }
  }
  t3.segCountX2 = (segCount - segCountToRemove) * 2;
  t3.searchRange = Math.pow(2, Math.floor(Math.log(segCount - segCountToRemove) / Math.log(2))) * 2;
  t3.entrySelector = Math.log(t3.searchRange / 2) / Math.log(2);
  t3.rangeShift = t3.segCountX2 - t3.searchRange;
  t3.fields = t3.fields.concat(endCounts);
  t3.fields.push({ name: "reservedPad", type: "USHORT", value: 0 });
  t3.fields = t3.fields.concat(startCounts);
  t3.fields = t3.fields.concat(idDeltas);
  t3.fields = t3.fields.concat(idRangeOffsets);
  t3.fields = t3.fields.concat(glyphIds);
  t3.cmap4Length = 14 + // Subtable header
  endCounts.length * 2 + 2 + // reservedPad
  startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2;
  if (!isPlan0Only) {
    var cmap12Length = 16 + // Subtable header
    cmap12Groups.length * 4;
    t3.cmap12Offset = 12 + 2 * 2 + 4 + t3.cmap4Length;
    t3.fields = t3.fields.concat([
      { name: "cmap12Format", type: "USHORT", value: 12 },
      { name: "cmap12Reserved", type: "USHORT", value: 0 },
      { name: "cmap12Length", type: "ULONG", value: cmap12Length },
      { name: "cmap12Language", type: "ULONG", value: 0 },
      { name: "cmap12nGroups", type: "ULONG", value: cmap12Groups.length / 3 }
    ]);
    t3.fields = t3.fields.concat(cmap12Groups);
  }
  return t3;
}
var cmap = { parse: parseCmapTable, make: makeCmapTable };
var cffStandardStrings = [
  ".notdef",
  "space",
  "exclam",
  "quotedbl",
  "numbersign",
  "dollar",
  "percent",
  "ampersand",
  "quoteright",
  "parenleft",
  "parenright",
  "asterisk",
  "plus",
  "comma",
  "hyphen",
  "period",
  "slash",
  "zero",
  "one",
  "two",
  "three",
  "four",
  "five",
  "six",
  "seven",
  "eight",
  "nine",
  "colon",
  "semicolon",
  "less",
  "equal",
  "greater",
  "question",
  "at",
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
  "bracketleft",
  "backslash",
  "bracketright",
  "asciicircum",
  "underscore",
  "quoteleft",
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
  "braceleft",
  "bar",
  "braceright",
  "asciitilde",
  "exclamdown",
  "cent",
  "sterling",
  "fraction",
  "yen",
  "florin",
  "section",
  "currency",
  "quotesingle",
  "quotedblleft",
  "guillemotleft",
  "guilsinglleft",
  "guilsinglright",
  "fi",
  "fl",
  "endash",
  "dagger",
  "daggerdbl",
  "periodcentered",
  "paragraph",
  "bullet",
  "quotesinglbase",
  "quotedblbase",
  "quotedblright",
  "guillemotright",
  "ellipsis",
  "perthousand",
  "questiondown",
  "grave",
  "acute",
  "circumflex",
  "tilde",
  "macron",
  "breve",
  "dotaccent",
  "dieresis",
  "ring",
  "cedilla",
  "hungarumlaut",
  "ogonek",
  "caron",
  "emdash",
  "AE",
  "ordfeminine",
  "Lslash",
  "Oslash",
  "OE",
  "ordmasculine",
  "ae",
  "dotlessi",
  "lslash",
  "oslash",
  "oe",
  "germandbls",
  "onesuperior",
  "logicalnot",
  "mu",
  "trademark",
  "Eth",
  "onehalf",
  "plusminus",
  "Thorn",
  "onequarter",
  "divide",
  "brokenbar",
  "degree",
  "thorn",
  "threequarters",
  "twosuperior",
  "registered",
  "minus",
  "eth",
  "multiply",
  "threesuperior",
  "copyright",
  "Aacute",
  "Acircumflex",
  "Adieresis",
  "Agrave",
  "Aring",
  "Atilde",
  "Ccedilla",
  "Eacute",
  "Ecircumflex",
  "Edieresis",
  "Egrave",
  "Iacute",
  "Icircumflex",
  "Idieresis",
  "Igrave",
  "Ntilde",
  "Oacute",
  "Ocircumflex",
  "Odieresis",
  "Ograve",
  "Otilde",
  "Scaron",
  "Uacute",
  "Ucircumflex",
  "Udieresis",
  "Ugrave",
  "Yacute",
  "Ydieresis",
  "Zcaron",
  "aacute",
  "acircumflex",
  "adieresis",
  "agrave",
  "aring",
  "atilde",
  "ccedilla",
  "eacute",
  "ecircumflex",
  "edieresis",
  "egrave",
  "iacute",
  "icircumflex",
  "idieresis",
  "igrave",
  "ntilde",
  "oacute",
  "ocircumflex",
  "odieresis",
  "ograve",
  "otilde",
  "scaron",
  "uacute",
  "ucircumflex",
  "udieresis",
  "ugrave",
  "yacute",
  "ydieresis",
  "zcaron",
  "exclamsmall",
  "Hungarumlautsmall",
  "dollaroldstyle",
  "dollarsuperior",
  "ampersandsmall",
  "Acutesmall",
  "parenleftsuperior",
  "parenrightsuperior",
  "266 ff",
  "onedotenleader",
  "zerooldstyle",
  "oneoldstyle",
  "twooldstyle",
  "threeoldstyle",
  "fouroldstyle",
  "fiveoldstyle",
  "sixoldstyle",
  "sevenoldstyle",
  "eightoldstyle",
  "nineoldstyle",
  "commasuperior",
  "threequartersemdash",
  "periodsuperior",
  "questionsmall",
  "asuperior",
  "bsuperior",
  "centsuperior",
  "dsuperior",
  "esuperior",
  "isuperior",
  "lsuperior",
  "msuperior",
  "nsuperior",
  "osuperior",
  "rsuperior",
  "ssuperior",
  "tsuperior",
  "ff",
  "ffi",
  "ffl",
  "parenleftinferior",
  "parenrightinferior",
  "Circumflexsmall",
  "hyphensuperior",
  "Gravesmall",
  "Asmall",
  "Bsmall",
  "Csmall",
  "Dsmall",
  "Esmall",
  "Fsmall",
  "Gsmall",
  "Hsmall",
  "Ismall",
  "Jsmall",
  "Ksmall",
  "Lsmall",
  "Msmall",
  "Nsmall",
  "Osmall",
  "Psmall",
  "Qsmall",
  "Rsmall",
  "Ssmall",
  "Tsmall",
  "Usmall",
  "Vsmall",
  "Wsmall",
  "Xsmall",
  "Ysmall",
  "Zsmall",
  "colonmonetary",
  "onefitted",
  "rupiah",
  "Tildesmall",
  "exclamdownsmall",
  "centoldstyle",
  "Lslashsmall",
  "Scaronsmall",
  "Zcaronsmall",
  "Dieresissmall",
  "Brevesmall",
  "Caronsmall",
  "Dotaccentsmall",
  "Macronsmall",
  "figuredash",
  "hypheninferior",
  "Ogoneksmall",
  "Ringsmall",
  "Cedillasmall",
  "questiondownsmall",
  "oneeighth",
  "threeeighths",
  "fiveeighths",
  "seveneighths",
  "onethird",
  "twothirds",
  "zerosuperior",
  "foursuperior",
  "fivesuperior",
  "sixsuperior",
  "sevensuperior",
  "eightsuperior",
  "ninesuperior",
  "zeroinferior",
  "oneinferior",
  "twoinferior",
  "threeinferior",
  "fourinferior",
  "fiveinferior",
  "sixinferior",
  "seveninferior",
  "eightinferior",
  "nineinferior",
  "centinferior",
  "dollarinferior",
  "periodinferior",
  "commainferior",
  "Agravesmall",
  "Aacutesmall",
  "Acircumflexsmall",
  "Atildesmall",
  "Adieresissmall",
  "Aringsmall",
  "AEsmall",
  "Ccedillasmall",
  "Egravesmall",
  "Eacutesmall",
  "Ecircumflexsmall",
  "Edieresissmall",
  "Igravesmall",
  "Iacutesmall",
  "Icircumflexsmall",
  "Idieresissmall",
  "Ethsmall",
  "Ntildesmall",
  "Ogravesmall",
  "Oacutesmall",
  "Ocircumflexsmall",
  "Otildesmall",
  "Odieresissmall",
  "OEsmall",
  "Oslashsmall",
  "Ugravesmall",
  "Uacutesmall",
  "Ucircumflexsmall",
  "Udieresissmall",
  "Yacutesmall",
  "Thornsmall",
  "Ydieresissmall",
  "001.000",
  "001.001",
  "001.002",
  "001.003",
  "Black",
  "Bold",
  "Book",
  "Light",
  "Medium",
  "Regular",
  "Roman",
  "Semibold"
];
var cffStandardEncoding = [
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "space",
  "exclam",
  "quotedbl",
  "numbersign",
  "dollar",
  "percent",
  "ampersand",
  "quoteright",
  "parenleft",
  "parenright",
  "asterisk",
  "plus",
  "comma",
  "hyphen",
  "period",
  "slash",
  "zero",
  "one",
  "two",
  "three",
  "four",
  "five",
  "six",
  "seven",
  "eight",
  "nine",
  "colon",
  "semicolon",
  "less",
  "equal",
  "greater",
  "question",
  "at",
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
  "bracketleft",
  "backslash",
  "bracketright",
  "asciicircum",
  "underscore",
  "quoteleft",
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
  "braceleft",
  "bar",
  "braceright",
  "asciitilde",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "exclamdown",
  "cent",
  "sterling",
  "fraction",
  "yen",
  "florin",
  "section",
  "currency",
  "quotesingle",
  "quotedblleft",
  "guillemotleft",
  "guilsinglleft",
  "guilsinglright",
  "fi",
  "fl",
  "",
  "endash",
  "dagger",
  "daggerdbl",
  "periodcentered",
  "",
  "paragraph",
  "bullet",
  "quotesinglbase",
  "quotedblbase",
  "quotedblright",
  "guillemotright",
  "ellipsis",
  "perthousand",
  "",
  "questiondown",
  "",
  "grave",
  "acute",
  "circumflex",
  "tilde",
  "macron",
  "breve",
  "dotaccent",
  "dieresis",
  "",
  "ring",
  "cedilla",
  "",
  "hungarumlaut",
  "ogonek",
  "caron",
  "emdash",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "AE",
  "",
  "ordfeminine",
  "",
  "",
  "",
  "",
  "Lslash",
  "Oslash",
  "OE",
  "ordmasculine",
  "",
  "",
  "",
  "",
  "",
  "ae",
  "",
  "",
  "",
  "dotlessi",
  "",
  "",
  "lslash",
  "oslash",
  "oe",
  "germandbls"
];
var cffExpertEncoding = [
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "space",
  "exclamsmall",
  "Hungarumlautsmall",
  "",
  "dollaroldstyle",
  "dollarsuperior",
  "ampersandsmall",
  "Acutesmall",
  "parenleftsuperior",
  "parenrightsuperior",
  "twodotenleader",
  "onedotenleader",
  "comma",
  "hyphen",
  "period",
  "fraction",
  "zerooldstyle",
  "oneoldstyle",
  "twooldstyle",
  "threeoldstyle",
  "fouroldstyle",
  "fiveoldstyle",
  "sixoldstyle",
  "sevenoldstyle",
  "eightoldstyle",
  "nineoldstyle",
  "colon",
  "semicolon",
  "commasuperior",
  "threequartersemdash",
  "periodsuperior",
  "questionsmall",
  "",
  "asuperior",
  "bsuperior",
  "centsuperior",
  "dsuperior",
  "esuperior",
  "",
  "",
  "isuperior",
  "",
  "",
  "lsuperior",
  "msuperior",
  "nsuperior",
  "osuperior",
  "",
  "",
  "rsuperior",
  "ssuperior",
  "tsuperior",
  "",
  "ff",
  "fi",
  "fl",
  "ffi",
  "ffl",
  "parenleftinferior",
  "",
  "parenrightinferior",
  "Circumflexsmall",
  "hyphensuperior",
  "Gravesmall",
  "Asmall",
  "Bsmall",
  "Csmall",
  "Dsmall",
  "Esmall",
  "Fsmall",
  "Gsmall",
  "Hsmall",
  "Ismall",
  "Jsmall",
  "Ksmall",
  "Lsmall",
  "Msmall",
  "Nsmall",
  "Osmall",
  "Psmall",
  "Qsmall",
  "Rsmall",
  "Ssmall",
  "Tsmall",
  "Usmall",
  "Vsmall",
  "Wsmall",
  "Xsmall",
  "Ysmall",
  "Zsmall",
  "colonmonetary",
  "onefitted",
  "rupiah",
  "Tildesmall",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "exclamdownsmall",
  "centoldstyle",
  "Lslashsmall",
  "",
  "",
  "Scaronsmall",
  "Zcaronsmall",
  "Dieresissmall",
  "Brevesmall",
  "Caronsmall",
  "",
  "Dotaccentsmall",
  "",
  "",
  "Macronsmall",
  "",
  "",
  "figuredash",
  "hypheninferior",
  "",
  "",
  "Ogoneksmall",
  "Ringsmall",
  "Cedillasmall",
  "",
  "",
  "",
  "onequarter",
  "onehalf",
  "threequarters",
  "questiondownsmall",
  "oneeighth",
  "threeeighths",
  "fiveeighths",
  "seveneighths",
  "onethird",
  "twothirds",
  "",
  "",
  "zerosuperior",
  "onesuperior",
  "twosuperior",
  "threesuperior",
  "foursuperior",
  "fivesuperior",
  "sixsuperior",
  "sevensuperior",
  "eightsuperior",
  "ninesuperior",
  "zeroinferior",
  "oneinferior",
  "twoinferior",
  "threeinferior",
  "fourinferior",
  "fiveinferior",
  "sixinferior",
  "seveninferior",
  "eightinferior",
  "nineinferior",
  "centinferior",
  "dollarinferior",
  "periodinferior",
  "commainferior",
  "Agravesmall",
  "Aacutesmall",
  "Acircumflexsmall",
  "Atildesmall",
  "Adieresissmall",
  "Aringsmall",
  "AEsmall",
  "Ccedillasmall",
  "Egravesmall",
  "Eacutesmall",
  "Ecircumflexsmall",
  "Edieresissmall",
  "Igravesmall",
  "Iacutesmall",
  "Icircumflexsmall",
  "Idieresissmall",
  "Ethsmall",
  "Ntildesmall",
  "Ogravesmall",
  "Oacutesmall",
  "Ocircumflexsmall",
  "Otildesmall",
  "Odieresissmall",
  "OEsmall",
  "Oslashsmall",
  "Ugravesmall",
  "Uacutesmall",
  "Ucircumflexsmall",
  "Udieresissmall",
  "Yacutesmall",
  "Thornsmall",
  "Ydieresissmall"
];
var standardNames = [
  ".notdef",
  ".null",
  "nonmarkingreturn",
  "space",
  "exclam",
  "quotedbl",
  "numbersign",
  "dollar",
  "percent",
  "ampersand",
  "quotesingle",
  "parenleft",
  "parenright",
  "asterisk",
  "plus",
  "comma",
  "hyphen",
  "period",
  "slash",
  "zero",
  "one",
  "two",
  "three",
  "four",
  "five",
  "six",
  "seven",
  "eight",
  "nine",
  "colon",
  "semicolon",
  "less",
  "equal",
  "greater",
  "question",
  "at",
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
  "bracketleft",
  "backslash",
  "bracketright",
  "asciicircum",
  "underscore",
  "grave",
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z",
  "braceleft",
  "bar",
  "braceright",
  "asciitilde",
  "Adieresis",
  "Aring",
  "Ccedilla",
  "Eacute",
  "Ntilde",
  "Odieresis",
  "Udieresis",
  "aacute",
  "agrave",
  "acircumflex",
  "adieresis",
  "atilde",
  "aring",
  "ccedilla",
  "eacute",
  "egrave",
  "ecircumflex",
  "edieresis",
  "iacute",
  "igrave",
  "icircumflex",
  "idieresis",
  "ntilde",
  "oacute",
  "ograve",
  "ocircumflex",
  "odieresis",
  "otilde",
  "uacute",
  "ugrave",
  "ucircumflex",
  "udieresis",
  "dagger",
  "degree",
  "cent",
  "sterling",
  "section",
  "bullet",
  "paragraph",
  "germandbls",
  "registered",
  "copyright",
  "trademark",
  "acute",
  "dieresis",
  "notequal",
  "AE",
  "Oslash",
  "infinity",
  "plusminus",
  "lessequal",
  "greaterequal",
  "yen",
  "mu",
  "partialdiff",
  "summation",
  "product",
  "pi",
  "integral",
  "ordfeminine",
  "ordmasculine",
  "Omega",
  "ae",
  "oslash",
  "questiondown",
  "exclamdown",
  "logicalnot",
  "radical",
  "florin",
  "approxequal",
  "Delta",
  "guillemotleft",
  "guillemotright",
  "ellipsis",
  "nonbreakingspace",
  "Agrave",
  "Atilde",
  "Otilde",
  "OE",
  "oe",
  "endash",
  "emdash",
  "quotedblleft",
  "quotedblright",
  "quoteleft",
  "quoteright",
  "divide",
  "lozenge",
  "ydieresis",
  "Ydieresis",
  "fraction",
  "currency",
  "guilsinglleft",
  "guilsinglright",
  "fi",
  "fl",
  "daggerdbl",
  "periodcentered",
  "quotesinglbase",
  "quotedblbase",
  "perthousand",
  "Acircumflex",
  "Ecircumflex",
  "Aacute",
  "Edieresis",
  "Egrave",
  "Iacute",
  "Icircumflex",
  "Idieresis",
  "Igrave",
  "Oacute",
  "Ocircumflex",
  "apple",
  "Ograve",
  "Uacute",
  "Ucircumflex",
  "Ugrave",
  "dotlessi",
  "circumflex",
  "tilde",
  "macron",
  "breve",
  "dotaccent",
  "ring",
  "cedilla",
  "hungarumlaut",
  "ogonek",
  "caron",
  "Lslash",
  "lslash",
  "Scaron",
  "scaron",
  "Zcaron",
  "zcaron",
  "brokenbar",
  "Eth",
  "eth",
  "Yacute",
  "yacute",
  "Thorn",
  "thorn",
  "minus",
  "multiply",
  "onesuperior",
  "twosuperior",
  "threesuperior",
  "onehalf",
  "onequarter",
  "threequarters",
  "franc",
  "Gbreve",
  "gbreve",
  "Idotaccent",
  "Scedilla",
  "scedilla",
  "Cacute",
  "cacute",
  "Ccaron",
  "ccaron",
  "dcroat"
];
function DefaultEncoding(font) {
  this.font = font;
}
DefaultEncoding.prototype.charToGlyphIndex = function(c2) {
  var code = c2.codePointAt(0);
  var glyphs = this.font.glyphs;
  if (glyphs) {
    for (var i = 0; i < glyphs.length; i += 1) {
      var glyph = glyphs.get(i);
      for (var j2 = 0; j2 < glyph.unicodes.length; j2 += 1) {
        if (glyph.unicodes[j2] === code) {
          return i;
        }
      }
    }
  }
  return null;
};
function CmapEncoding(cmap2) {
  this.cmap = cmap2;
}
CmapEncoding.prototype.charToGlyphIndex = function(c2) {
  return this.cmap.glyphIndexMap[c2.codePointAt(0)] || 0;
};
function CffEncoding(encoding, charset) {
  this.encoding = encoding;
  this.charset = charset;
}
CffEncoding.prototype.charToGlyphIndex = function(s) {
  var code = s.codePointAt(0);
  var charName = this.encoding[code];
  return this.charset.indexOf(charName);
};
function GlyphNames(post2) {
  switch (post2.version) {
    case 1:
      this.names = standardNames.slice();
      break;
    case 2:
      this.names = new Array(post2.numberOfGlyphs);
      for (var i = 0; i < post2.numberOfGlyphs; i++) {
        if (post2.glyphNameIndex[i] < standardNames.length) {
          this.names[i] = standardNames[post2.glyphNameIndex[i]];
        } else {
          this.names[i] = post2.names[post2.glyphNameIndex[i] - standardNames.length];
        }
      }
      break;
    case 2.5:
      this.names = new Array(post2.numberOfGlyphs);
      for (var i$1 = 0; i$1 < post2.numberOfGlyphs; i$1++) {
        this.names[i$1] = standardNames[i$1 + post2.glyphNameIndex[i$1]];
      }
      break;
    case 3:
      this.names = [];
      break;
    default:
      this.names = [];
      break;
  }
}
GlyphNames.prototype.nameToGlyphIndex = function(name2) {
  return this.names.indexOf(name2);
};
GlyphNames.prototype.glyphIndexToName = function(gid) {
  return this.names[gid];
};
function addGlyphNamesAll(font) {
  var glyph;
  var glyphIndexMap = font.tables.cmap.glyphIndexMap;
  var charCodes = Object.keys(glyphIndexMap);
  for (var i = 0; i < charCodes.length; i += 1) {
    var c2 = charCodes[i];
    var glyphIndex = glyphIndexMap[c2];
    glyph = font.glyphs.get(glyphIndex);
    glyph.addUnicode(parseInt(c2));
  }
  for (var i$1 = 0; i$1 < font.glyphs.length; i$1 += 1) {
    glyph = font.glyphs.get(i$1);
    if (font.cffEncoding) {
      if (font.isCIDFont) {
        glyph.name = "gid" + i$1;
      } else {
        glyph.name = font.cffEncoding.charset[i$1];
      }
    } else if (font.glyphNames.names) {
      glyph.name = font.glyphNames.glyphIndexToName(i$1);
    }
  }
}
function addGlyphNamesToUnicodeMap(font) {
  font._IndexToUnicodeMap = {};
  var glyphIndexMap = font.tables.cmap.glyphIndexMap;
  var charCodes = Object.keys(glyphIndexMap);
  for (var i = 0; i < charCodes.length; i += 1) {
    var c2 = charCodes[i];
    var glyphIndex = glyphIndexMap[c2];
    if (font._IndexToUnicodeMap[glyphIndex] === void 0) {
      font._IndexToUnicodeMap[glyphIndex] = {
        unicodes: [parseInt(c2)]
      };
    } else {
      font._IndexToUnicodeMap[glyphIndex].unicodes.push(parseInt(c2));
    }
  }
}
function addGlyphNames(font, opt) {
  if (opt.lowMemory) {
    addGlyphNamesToUnicodeMap(font);
  } else {
    addGlyphNamesAll(font);
  }
}
function line(ctx, x1, y1, x2, y2) {
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.stroke();
}
var draw = { line };
function getPathDefinition(glyph, path) {
  var _path = path || new Path2();
  return {
    configurable: true,
    get: function() {
      if (typeof _path === "function") {
        _path = _path();
      }
      return _path;
    },
    set: function(p) {
      _path = p;
    }
  };
}
function Glyph(options) {
  this.bindConstructorValues(options);
}
Glyph.prototype.bindConstructorValues = function(options) {
  this.index = options.index || 0;
  this.name = options.name || null;
  this.unicode = options.unicode || void 0;
  this.unicodes = options.unicodes || options.unicode !== void 0 ? [options.unicode] : [];
  if ("xMin" in options) {
    this.xMin = options.xMin;
  }
  if ("yMin" in options) {
    this.yMin = options.yMin;
  }
  if ("xMax" in options) {
    this.xMax = options.xMax;
  }
  if ("yMax" in options) {
    this.yMax = options.yMax;
  }
  if ("advanceWidth" in options) {
    this.advanceWidth = options.advanceWidth;
  }
  Object.defineProperty(this, "path", getPathDefinition(this, options.path));
};
Glyph.prototype.addUnicode = function(unicode) {
  if (this.unicodes.length === 0) {
    this.unicode = unicode;
  }
  this.unicodes.push(unicode);
};
Glyph.prototype.getBoundingBox = function() {
  return this.path.getBoundingBox();
};
Glyph.prototype.getPath = function(x2, y, fontSize, options, font) {
  x2 = x2 !== void 0 ? x2 : 0;
  y = y !== void 0 ? y : 0;
  fontSize = fontSize !== void 0 ? fontSize : 72;
  var commands;
  var hPoints;
  if (!options) {
    options = {};
  }
  var xScale = options.xScale;
  var yScale = options.yScale;
  if (options.hinting && font && font.hinting) {
    hPoints = this.path && font.hinting.exec(this, fontSize);
  }
  if (hPoints) {
    commands = font.hinting.getCommands(hPoints);
    x2 = Math.round(x2);
    y = Math.round(y);
    xScale = yScale = 1;
  } else {
    commands = this.path.commands;
    var scale2 = 1 / (this.path.unitsPerEm || 1e3) * fontSize;
    if (xScale === void 0) {
      xScale = scale2;
    }
    if (yScale === void 0) {
      yScale = scale2;
    }
  }
  var p = new Path2();
  for (var i = 0; i < commands.length; i += 1) {
    var cmd = commands[i];
    if (cmd.type === "M") {
      p.moveTo(x2 + cmd.x * xScale, y + -cmd.y * yScale);
    } else if (cmd.type === "L") {
      p.lineTo(x2 + cmd.x * xScale, y + -cmd.y * yScale);
    } else if (cmd.type === "Q") {
      p.quadraticCurveTo(
        x2 + cmd.x1 * xScale,
        y + -cmd.y1 * yScale,
        x2 + cmd.x * xScale,
        y + -cmd.y * yScale
      );
    } else if (cmd.type === "C") {
      p.curveTo(
        x2 + cmd.x1 * xScale,
        y + -cmd.y1 * yScale,
        x2 + cmd.x2 * xScale,
        y + -cmd.y2 * yScale,
        x2 + cmd.x * xScale,
        y + -cmd.y * yScale
      );
    } else if (cmd.type === "Z") {
      p.closePath();
    }
  }
  return p;
};
Glyph.prototype.getContours = function() {
  if (this.points === void 0) {
    return [];
  }
  var contours = [];
  var currentContour = [];
  for (var i = 0; i < this.points.length; i += 1) {
    var pt = this.points[i];
    currentContour.push(pt);
    if (pt.lastPointOfContour) {
      contours.push(currentContour);
      currentContour = [];
    }
  }
  check.argument(currentContour.length === 0, "There are still points left in the current contour.");
  return contours;
};
Glyph.prototype.getMetrics = function() {
  var commands = this.path.commands;
  var xCoords = [];
  var yCoords = [];
  for (var i = 0; i < commands.length; i += 1) {
    var cmd = commands[i];
    if (cmd.type !== "Z") {
      xCoords.push(cmd.x);
      yCoords.push(cmd.y);
    }
    if (cmd.type === "Q" || cmd.type === "C") {
      xCoords.push(cmd.x1);
      yCoords.push(cmd.y1);
    }
    if (cmd.type === "C") {
      xCoords.push(cmd.x2);
      yCoords.push(cmd.y2);
    }
  }
  var metrics = {
    xMin: Math.min.apply(null, xCoords),
    yMin: Math.min.apply(null, yCoords),
    xMax: Math.max.apply(null, xCoords),
    yMax: Math.max.apply(null, yCoords),
    leftSideBearing: this.leftSideBearing
  };
  if (!isFinite(metrics.xMin)) {
    metrics.xMin = 0;
  }
  if (!isFinite(metrics.xMax)) {
    metrics.xMax = this.advanceWidth;
  }
  if (!isFinite(metrics.yMin)) {
    metrics.yMin = 0;
  }
  if (!isFinite(metrics.yMax)) {
    metrics.yMax = 0;
  }
  metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin);
  return metrics;
};
Glyph.prototype.draw = function(ctx, x2, y, fontSize, options) {
  this.getPath(x2, y, fontSize, options).draw(ctx);
};
Glyph.prototype.drawPoints = function(ctx, x2, y, fontSize) {
  function drawCircles(l2, x3, y2, scale3) {
    ctx.beginPath();
    for (var j2 = 0; j2 < l2.length; j2 += 1) {
      ctx.moveTo(x3 + l2[j2].x * scale3, y2 + l2[j2].y * scale3);
      ctx.arc(x3 + l2[j2].x * scale3, y2 + l2[j2].y * scale3, 2, 0, Math.PI * 2, false);
    }
    ctx.closePath();
    ctx.fill();
  }
  x2 = x2 !== void 0 ? x2 : 0;
  y = y !== void 0 ? y : 0;
  fontSize = fontSize !== void 0 ? fontSize : 24;
  var scale2 = 1 / this.path.unitsPerEm * fontSize;
  var blueCircles = [];
  var redCircles = [];
  var path = this.path;
  for (var i = 0; i < path.commands.length; i += 1) {
    var cmd = path.commands[i];
    if (cmd.x !== void 0) {
      blueCircles.push({ x: cmd.x, y: -cmd.y });
    }
    if (cmd.x1 !== void 0) {
      redCircles.push({ x: cmd.x1, y: -cmd.y1 });
    }
    if (cmd.x2 !== void 0) {
      redCircles.push({ x: cmd.x2, y: -cmd.y2 });
    }
  }
  ctx.fillStyle = "blue";
  drawCircles(blueCircles, x2, y, scale2);
  ctx.fillStyle = "red";
  drawCircles(redCircles, x2, y, scale2);
};
Glyph.prototype.drawMetrics = function(ctx, x2, y, fontSize) {
  var scale2;
  x2 = x2 !== void 0 ? x2 : 0;
  y = y !== void 0 ? y : 0;
  fontSize = fontSize !== void 0 ? fontSize : 24;
  scale2 = 1 / this.path.unitsPerEm * fontSize;
  ctx.lineWidth = 1;
  ctx.strokeStyle = "black";
  draw.line(ctx, x2, -1e4, x2, 1e4);
  draw.line(ctx, -1e4, y, 1e4, y);
  var xMin = this.xMin || 0;
  var yMin = this.yMin || 0;
  var xMax = this.xMax || 0;
  var yMax = this.yMax || 0;
  var advanceWidth = this.advanceWidth || 0;
  ctx.strokeStyle = "blue";
  draw.line(ctx, x2 + xMin * scale2, -1e4, x2 + xMin * scale2, 1e4);
  draw.line(ctx, x2 + xMax * scale2, -1e4, x2 + xMax * scale2, 1e4);
  draw.line(ctx, -1e4, y + -yMin * scale2, 1e4, y + -yMin * scale2);
  draw.line(ctx, -1e4, y + -yMax * scale2, 1e4, y + -yMax * scale2);
  ctx.strokeStyle = "green";
  draw.line(ctx, x2 + advanceWidth * scale2, -1e4, x2 + advanceWidth * scale2, 1e4);
};
function defineDependentProperty(glyph, externalName, internalName) {
  Object.defineProperty(glyph, externalName, {
    get: function() {
      glyph.path;
      return glyph[internalName];
    },
    set: function(newValue) {
      glyph[internalName] = newValue;
    },
    enumerable: true,
    configurable: true
  });
}
function GlyphSet(font, glyphs) {
  this.font = font;
  this.glyphs = {};
  if (Array.isArray(glyphs)) {
    for (var i = 0; i < glyphs.length; i++) {
      var glyph = glyphs[i];
      glyph.path.unitsPerEm = font.unitsPerEm;
      this.glyphs[i] = glyph;
    }
  }
  this.length = glyphs && glyphs.length || 0;
}
GlyphSet.prototype.get = function(index2) {
  if (this.glyphs[index2] === void 0) {
    this.font._push(index2);
    if (typeof this.glyphs[index2] === "function") {
      this.glyphs[index2] = this.glyphs[index2]();
    }
    var glyph = this.glyphs[index2];
    var unicodeObj = this.font._IndexToUnicodeMap[index2];
    if (unicodeObj) {
      for (var j2 = 0; j2 < unicodeObj.unicodes.length; j2++) {
        glyph.addUnicode(unicodeObj.unicodes[j2]);
      }
    }
    if (this.font.cffEncoding) {
      if (this.font.isCIDFont) {
        glyph.name = "gid" + index2;
      } else {
        glyph.name = this.font.cffEncoding.charset[index2];
      }
    } else if (this.font.glyphNames.names) {
      glyph.name = this.font.glyphNames.glyphIndexToName(index2);
    }
    this.glyphs[index2].advanceWidth = this.font._hmtxTableData[index2].advanceWidth;
    this.glyphs[index2].leftSideBearing = this.font._hmtxTableData[index2].leftSideBearing;
  } else {
    if (typeof this.glyphs[index2] === "function") {
      this.glyphs[index2] = this.glyphs[index2]();
    }
  }
  return this.glyphs[index2];
};
GlyphSet.prototype.push = function(index2, loader) {
  this.glyphs[index2] = loader;
  this.length++;
};
function glyphLoader(font, index2) {
  return new Glyph({ index: index2, font });
}
function ttfGlyphLoader(font, index2, parseGlyph2, data2, position2, buildPath2) {
  return function() {
    var glyph = new Glyph({ index: index2, font });
    glyph.path = function() {
      parseGlyph2(glyph, data2, position2);
      var path = buildPath2(font.glyphs, glyph);
      path.unitsPerEm = font.unitsPerEm;
      return path;
    };
    defineDependentProperty(glyph, "xMin", "_xMin");
    defineDependentProperty(glyph, "xMax", "_xMax");
    defineDependentProperty(glyph, "yMin", "_yMin");
    defineDependentProperty(glyph, "yMax", "_yMax");
    return glyph;
  };
}
function cffGlyphLoader(font, index2, parseCFFCharstring2, charstring) {
  return function() {
    var glyph = new Glyph({ index: index2, font });
    glyph.path = function() {
      var path = parseCFFCharstring2(font, glyph, charstring);
      path.unitsPerEm = font.unitsPerEm;
      return path;
    };
    return glyph;
  };
}
var glyphset = { GlyphSet, glyphLoader, ttfGlyphLoader, cffGlyphLoader };
function equals(a2, b3) {
  if (a2 === b3) {
    return true;
  } else if (Array.isArray(a2) && Array.isArray(b3)) {
    if (a2.length !== b3.length) {
      return false;
    }
    for (var i = 0; i < a2.length; i += 1) {
      if (!equals(a2[i], b3[i])) {
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
}
function calcCFFSubroutineBias(subrs) {
  var bias;
  if (subrs.length < 1240) {
    bias = 107;
  } else if (subrs.length < 33900) {
    bias = 1131;
  } else {
    bias = 32768;
  }
  return bias;
}
function parseCFFIndex(data2, start, conversionFn) {
  var offsets = [];
  var objects = [];
  var count = parse.getCard16(data2, start);
  var objectOffset;
  var endOffset;
  if (count !== 0) {
    var offsetSize = parse.getByte(data2, start + 2);
    objectOffset = start + (count + 1) * offsetSize + 2;
    var pos = start + 3;
    for (var i = 0; i < count + 1; i += 1) {
      offsets.push(parse.getOffset(data2, pos, offsetSize));
      pos += offsetSize;
    }
    endOffset = objectOffset + offsets[count];
  } else {
    endOffset = start + 2;
  }
  for (var i$1 = 0; i$1 < offsets.length - 1; i$1 += 1) {
    var value2 = parse.getBytes(data2, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]);
    if (conversionFn) {
      value2 = conversionFn(value2);
    }
    objects.push(value2);
  }
  return { objects, startOffset: start, endOffset };
}
function parseCFFIndexLowMemory(data2, start) {
  var offsets = [];
  var count = parse.getCard16(data2, start);
  var objectOffset;
  var endOffset;
  if (count !== 0) {
    var offsetSize = parse.getByte(data2, start + 2);
    objectOffset = start + (count + 1) * offsetSize + 2;
    var pos = start + 3;
    for (var i = 0; i < count + 1; i += 1) {
      offsets.push(parse.getOffset(data2, pos, offsetSize));
      pos += offsetSize;
    }
    endOffset = objectOffset + offsets[count];
  } else {
    endOffset = start + 2;
  }
  return { offsets, startOffset: start, endOffset };
}
function getCffIndexObject(i, offsets, data2, start, conversionFn) {
  var count = parse.getCard16(data2, start);
  var objectOffset = 0;
  if (count !== 0) {
    var offsetSize = parse.getByte(data2, start + 2);
    objectOffset = start + (count + 1) * offsetSize + 2;
  }
  var value2 = parse.getBytes(data2, objectOffset + offsets[i], objectOffset + offsets[i + 1]);
  if (conversionFn) {
    value2 = conversionFn(value2);
  }
  return value2;
}
function parseFloatOperand(parser) {
  var s = "";
  var eof = 15;
  var lookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "E", "E-", null, "-"];
  while (true) {
    var b3 = parser.parseByte();
    var n1 = b3 >> 4;
    var n2 = b3 & 15;
    if (n1 === eof) {
      break;
    }
    s += lookup[n1];
    if (n2 === eof) {
      break;
    }
    s += lookup[n2];
  }
  return parseFloat(s);
}
function parseOperand(parser, b0) {
  var b1;
  var b22;
  var b3;
  var b42;
  if (b0 === 28) {
    b1 = parser.parseByte();
    b22 = parser.parseByte();
    return b1 << 8 | b22;
  }
  if (b0 === 29) {
    b1 = parser.parseByte();
    b22 = parser.parseByte();
    b3 = parser.parseByte();
    b42 = parser.parseByte();
    return b1 << 24 | b22 << 16 | b3 << 8 | b42;
  }
  if (b0 === 30) {
    return parseFloatOperand(parser);
  }
  if (b0 >= 32 && b0 <= 246) {
    return b0 - 139;
  }
  if (b0 >= 247 && b0 <= 250) {
    b1 = parser.parseByte();
    return (b0 - 247) * 256 + b1 + 108;
  }
  if (b0 >= 251 && b0 <= 254) {
    b1 = parser.parseByte();
    return -(b0 - 251) * 256 - b1 - 108;
  }
  throw new Error("Invalid b0 " + b0);
}
function entriesToObject(entries) {
  var o = {};
  for (var i = 0; i < entries.length; i += 1) {
    var key2 = entries[i][0];
    var values2 = entries[i][1];
    var value2 = void 0;
    if (values2.length === 1) {
      value2 = values2[0];
    } else {
      value2 = values2;
    }
    if (o.hasOwnProperty(key2) && !isNaN(o[key2])) {
      throw new Error("Object " + o + " already has key " + key2);
    }
    o[key2] = value2;
  }
  return o;
}
function parseCFFDict(data2, start, size2) {
  start = start !== void 0 ? start : 0;
  var parser = new parse.Parser(data2, start);
  var entries = [];
  var operands = [];
  size2 = size2 !== void 0 ? size2 : data2.length;
  while (parser.relativeOffset < size2) {
    var op = parser.parseByte();
    if (op <= 21) {
      if (op === 12) {
        op = 1200 + parser.parseByte();
      }
      entries.push([op, operands]);
      operands = [];
    } else {
      operands.push(parseOperand(parser, op));
    }
  }
  return entriesToObject(entries);
}
function getCFFString(strings, index2) {
  if (index2 <= 390) {
    index2 = cffStandardStrings[index2];
  } else {
    index2 = strings[index2 - 391];
  }
  return index2;
}
function interpretDict(dict, meta2, strings) {
  var newDict = {};
  var value2;
  for (var i = 0; i < meta2.length; i += 1) {
    var m = meta2[i];
    if (Array.isArray(m.type)) {
      var values2 = [];
      values2.length = m.type.length;
      for (var j2 = 0; j2 < m.type.length; j2++) {
        value2 = dict[m.op] !== void 0 ? dict[m.op][j2] : void 0;
        if (value2 === void 0) {
          value2 = m.value !== void 0 && m.value[j2] !== void 0 ? m.value[j2] : null;
        }
        if (m.type[j2] === "SID") {
          value2 = getCFFString(strings, value2);
        }
        values2[j2] = value2;
      }
      newDict[m.name] = values2;
    } else {
      value2 = dict[m.op];
      if (value2 === void 0) {
        value2 = m.value !== void 0 ? m.value : null;
      }
      if (m.type === "SID") {
        value2 = getCFFString(strings, value2);
      }
      newDict[m.name] = value2;
    }
  }
  return newDict;
}
function parseCFFHeader(data2, start) {
  var header = {};
  header.formatMajor = parse.getCard8(data2, start);
  header.formatMinor = parse.getCard8(data2, start + 1);
  header.size = parse.getCard8(data2, start + 2);
  header.offsetSize = parse.getCard8(data2, start + 3);
  header.startOffset = start;
  header.endOffset = start + 4;
  return header;
}
var TOP_DICT_META = [
  { name: "version", op: 0, type: "SID" },
  { name: "notice", op: 1, type: "SID" },
  { name: "copyright", op: 1200, type: "SID" },
  { name: "fullName", op: 2, type: "SID" },
  { name: "familyName", op: 3, type: "SID" },
  { name: "weight", op: 4, type: "SID" },
  { name: "isFixedPitch", op: 1201, type: "number", value: 0 },
  { name: "italicAngle", op: 1202, type: "number", value: 0 },
  { name: "underlinePosition", op: 1203, type: "number", value: -100 },
  { name: "underlineThickness", op: 1204, type: "number", value: 50 },
  { name: "paintType", op: 1205, type: "number", value: 0 },
  { name: "charstringType", op: 1206, type: "number", value: 2 },
  {
    name: "fontMatrix",
    op: 1207,
    type: ["real", "real", "real", "real", "real", "real"],
    value: [1e-3, 0, 0, 1e-3, 0, 0]
  },
  { name: "uniqueId", op: 13, type: "number" },
  { name: "fontBBox", op: 5, type: ["number", "number", "number", "number"], value: [0, 0, 0, 0] },
  { name: "strokeWidth", op: 1208, type: "number", value: 0 },
  { name: "xuid", op: 14, type: [], value: null },
  { name: "charset", op: 15, type: "offset", value: 0 },
  { name: "encoding", op: 16, type: "offset", value: 0 },
  { name: "charStrings", op: 17, type: "offset", value: 0 },
  { name: "private", op: 18, type: ["number", "offset"], value: [0, 0] },
  { name: "ros", op: 1230, type: ["SID", "SID", "number"] },
  { name: "cidFontVersion", op: 1231, type: "number", value: 0 },
  { name: "cidFontRevision", op: 1232, type: "number", value: 0 },
  { name: "cidFontType", op: 1233, type: "number", value: 0 },
  { name: "cidCount", op: 1234, type: "number", value: 8720 },
  { name: "uidBase", op: 1235, type: "number" },
  { name: "fdArray", op: 1236, type: "offset" },
  { name: "fdSelect", op: 1237, type: "offset" },
  { name: "fontName", op: 1238, type: "SID" }
];
var PRIVATE_DICT_META = [
  { name: "subrs", op: 19, type: "offset", value: 0 },
  { name: "defaultWidthX", op: 20, type: "number", value: 0 },
  { name: "nominalWidthX", op: 21, type: "number", value: 0 }
];
function parseCFFTopDict(data2, strings) {
  var dict = parseCFFDict(data2, 0, data2.byteLength);
  return interpretDict(dict, TOP_DICT_META, strings);
}
function parseCFFPrivateDict(data2, start, size2, strings) {
  var dict = parseCFFDict(data2, start, size2);
  return interpretDict(dict, PRIVATE_DICT_META, strings);
}
function gatherCFFTopDicts(data2, start, cffIndex, strings) {
  var topDictArray = [];
  for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) {
    var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer);
    var topDict = parseCFFTopDict(topDictData, strings);
    topDict._subrs = [];
    topDict._subrsBias = 0;
    topDict._defaultWidthX = 0;
    topDict._nominalWidthX = 0;
    var privateSize = topDict.private[0];
    var privateOffset = topDict.private[1];
    if (privateSize !== 0 && privateOffset !== 0) {
      var privateDict = parseCFFPrivateDict(data2, privateOffset + start, privateSize, strings);
      topDict._defaultWidthX = privateDict.defaultWidthX;
      topDict._nominalWidthX = privateDict.nominalWidthX;
      if (privateDict.subrs !== 0) {
        var subrOffset = privateOffset + privateDict.subrs;
        var subrIndex = parseCFFIndex(data2, subrOffset + start);
        topDict._subrs = subrIndex.objects;
        topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs);
      }
      topDict._privateDict = privateDict;
    }
    topDictArray.push(topDict);
  }
  return topDictArray;
}
function parseCFFCharset(data2, start, nGlyphs, strings) {
  var sid;
  var count;
  var parser = new parse.Parser(data2, start);
  nGlyphs -= 1;
  var charset = [".notdef"];
  var format = parser.parseCard8();
  if (format === 0) {
    for (var i = 0; i < nGlyphs; i += 1) {
      sid = parser.parseSID();
      charset.push(getCFFString(strings, sid));
    }
  } else if (format === 1) {
    while (charset.length <= nGlyphs) {
      sid = parser.parseSID();
      count = parser.parseCard8();
      for (var i$1 = 0; i$1 <= count; i$1 += 1) {
        charset.push(getCFFString(strings, sid));
        sid += 1;
      }
    }
  } else if (format === 2) {
    while (charset.length <= nGlyphs) {
      sid = parser.parseSID();
      count = parser.parseCard16();
      for (var i$2 = 0; i$2 <= count; i$2 += 1) {
        charset.push(getCFFString(strings, sid));
        sid += 1;
      }
    }
  } else {
    throw new Error("Unknown charset format " + format);
  }
  return charset;
}
function parseCFFEncoding(data2, start, charset) {
  var code;
  var enc = {};
  var parser = new parse.Parser(data2, start);
  var format = parser.parseCard8();
  if (format === 0) {
    var nCodes = parser.parseCard8();
    for (var i = 0; i < nCodes; i += 1) {
      code = parser.parseCard8();
      enc[code] = i;
    }
  } else if (format === 1) {
    var nRanges = parser.parseCard8();
    code = 1;
    for (var i$1 = 0; i$1 < nRanges; i$1 += 1) {
      var first2 = parser.parseCard8();
      var nLeft = parser.parseCard8();
      for (var j2 = first2; j2 <= first2 + nLeft; j2 += 1) {
        enc[j2] = code;
        code += 1;
      }
    }
  } else {
    throw new Error("Unknown encoding format " + format);
  }
  return new CffEncoding(enc, charset);
}
function parseCFFCharstring(font, glyph, code) {
  var c1x;
  var c1y;
  var c2x;
  var c2y;
  var p = new Path2();
  var stack = [];
  var nStems = 0;
  var haveWidth = false;
  var open = false;
  var x2 = 0;
  var y = 0;
  var subrs;
  var subrsBias;
  var defaultWidthX;
  var nominalWidthX;
  if (font.isCIDFont) {
    var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index];
    var fdDict = font.tables.cff.topDict._fdArray[fdIndex];
    subrs = fdDict._subrs;
    subrsBias = fdDict._subrsBias;
    defaultWidthX = fdDict._defaultWidthX;
    nominalWidthX = fdDict._nominalWidthX;
  } else {
    subrs = font.tables.cff.topDict._subrs;
    subrsBias = font.tables.cff.topDict._subrsBias;
    defaultWidthX = font.tables.cff.topDict._defaultWidthX;
    nominalWidthX = font.tables.cff.topDict._nominalWidthX;
  }
  var width2 = defaultWidthX;
  function newContour(x3, y2) {
    if (open) {
      p.closePath();
    }
    p.moveTo(x3, y2);
    open = true;
  }
  function parseStems() {
    var hasWidthArg;
    hasWidthArg = stack.length % 2 !== 0;
    if (hasWidthArg && !haveWidth) {
      width2 = stack.shift() + nominalWidthX;
    }
    nStems += stack.length >> 1;
    stack.length = 0;
    haveWidth = true;
  }
  function parse2(code2) {
    var b1;
    var b22;
    var b3;
    var b42;
    var codeIndex;
    var subrCode;
    var jpx;
    var jpy;
    var c3x;
    var c3y;
    var c4x;
    var c4y;
    var i = 0;
    while (i < code2.length) {
      var v = code2[i];
      i += 1;
      switch (v) {
        case 1:
          parseStems();
          break;
        case 3:
          parseStems();
          break;
        case 4:
          if (stack.length > 1 && !haveWidth) {
            width2 = stack.shift() + nominalWidthX;
            haveWidth = true;
          }
          y += stack.pop();
          newContour(x2, y);
          break;
        case 5:
          while (stack.length > 0) {
            x2 += stack.shift();
            y += stack.shift();
            p.lineTo(x2, y);
          }
          break;
        case 6:
          while (stack.length > 0) {
            x2 += stack.shift();
            p.lineTo(x2, y);
            if (stack.length === 0) {
              break;
            }
            y += stack.shift();
            p.lineTo(x2, y);
          }
          break;
        case 7:
          while (stack.length > 0) {
            y += stack.shift();
            p.lineTo(x2, y);
            if (stack.length === 0) {
              break;
            }
            x2 += stack.shift();
            p.lineTo(x2, y);
          }
          break;
        case 8:
          while (stack.length > 0) {
            c1x = x2 + stack.shift();
            c1y = y + stack.shift();
            c2x = c1x + stack.shift();
            c2y = c1y + stack.shift();
            x2 = c2x + stack.shift();
            y = c2y + stack.shift();
            p.curveTo(c1x, c1y, c2x, c2y, x2, y);
          }
          break;
        case 10:
          codeIndex = stack.pop() + subrsBias;
          subrCode = subrs[codeIndex];
          if (subrCode) {
            parse2(subrCode);
          }
          break;
        case 11:
          return;
        case 12:
          v = code2[i];
          i += 1;
          switch (v) {
            case 35:
              c1x = x2 + stack.shift();
              c1y = y + stack.shift();
              c2x = c1x + stack.shift();
              c2y = c1y + stack.shift();
              jpx = c2x + stack.shift();
              jpy = c2y + stack.shift();
              c3x = jpx + stack.shift();
              c3y = jpy + stack.shift();
              c4x = c3x + stack.shift();
              c4y = c3y + stack.shift();
              x2 = c4x + stack.shift();
              y = c4y + stack.shift();
              stack.shift();
              p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
              p.curveTo(c3x, c3y, c4x, c4y, x2, y);
              break;
            case 34:
              c1x = x2 + stack.shift();
              c1y = y;
              c2x = c1x + stack.shift();
              c2y = c1y + stack.shift();
              jpx = c2x + stack.shift();
              jpy = c2y;
              c3x = jpx + stack.shift();
              c3y = c2y;
              c4x = c3x + stack.shift();
              c4y = y;
              x2 = c4x + stack.shift();
              p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
              p.curveTo(c3x, c3y, c4x, c4y, x2, y);
              break;
            case 36:
              c1x = x2 + stack.shift();
              c1y = y + stack.shift();
              c2x = c1x + stack.shift();
              c2y = c1y + stack.shift();
              jpx = c2x + stack.shift();
              jpy = c2y;
              c3x = jpx + stack.shift();
              c3y = c2y;
              c4x = c3x + stack.shift();
              c4y = c3y + stack.shift();
              x2 = c4x + stack.shift();
              p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
              p.curveTo(c3x, c3y, c4x, c4y, x2, y);
              break;
            case 37:
              c1x = x2 + stack.shift();
              c1y = y + stack.shift();
              c2x = c1x + stack.shift();
              c2y = c1y + stack.shift();
              jpx = c2x + stack.shift();
              jpy = c2y + stack.shift();
              c3x = jpx + stack.shift();
              c3y = jpy + stack.shift();
              c4x = c3x + stack.shift();
              c4y = c3y + stack.shift();
              if (Math.abs(c4x - x2) > Math.abs(c4y - y)) {
                x2 = c4x + stack.shift();
              } else {
                y = c4y + stack.shift();
              }
              p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
              p.curveTo(c3x, c3y, c4x, c4y, x2, y);
              break;
            default:
              console.log("Glyph " + glyph.index + ": unknown operator 1200" + v);
              stack.length = 0;
          }
          break;
        case 14:
          if (stack.length > 0 && !haveWidth) {
            width2 = stack.shift() + nominalWidthX;
            haveWidth = true;
          }
          if (open) {
            p.closePath();
            open = false;
          }
          break;
        case 18:
          parseStems();
          break;
        case 19:
        // hintmask
        case 20:
          parseStems();
          i += nStems + 7 >> 3;
          break;
        case 21:
          if (stack.length > 2 && !haveWidth) {
            width2 = stack.shift() + nominalWidthX;
            haveWidth = true;
          }
          y += stack.pop();
          x2 += stack.pop();
          newContour(x2, y);
          break;
        case 22:
          if (stack.length > 1 && !haveWidth) {
            width2 = stack.shift() + nominalWidthX;
            haveWidth = true;
          }
          x2 += stack.pop();
          newContour(x2, y);
          break;
        case 23:
          parseStems();
          break;
        case 24:
          while (stack.length > 2) {
            c1x = x2 + stack.shift();
            c1y = y + stack.shift();
            c2x = c1x + stack.shift();
            c2y = c1y + stack.shift();
            x2 = c2x + stack.shift();
            y = c2y + stack.shift();
            p.curveTo(c1x, c1y, c2x, c2y, x2, y);
          }
          x2 += stack.shift();
          y += stack.shift();
          p.lineTo(x2, y);
          break;
        case 25:
          while (stack.length > 6) {
            x2 += stack.shift();
            y += stack.shift();
            p.lineTo(x2, y);
          }
          c1x = x2 + stack.shift();
          c1y = y + stack.shift();
          c2x = c1x + stack.shift();
          c2y = c1y + stack.shift();
          x2 = c2x + stack.shift();
          y = c2y + stack.shift();
          p.curveTo(c1x, c1y, c2x, c2y, x2, y);
          break;
        case 26:
          if (stack.length % 2) {
            x2 += stack.shift();
          }
          while (stack.length > 0) {
            c1x = x2;
            c1y = y + stack.shift();
            c2x = c1x + stack.shift();
            c2y = c1y + stack.shift();
            x2 = c2x;
            y = c2y + stack.shift();
            p.curveTo(c1x, c1y, c2x, c2y, x2, y);
          }
          break;
        case 27:
          if (stack.length % 2) {
            y += stack.shift();
          }
          while (stack.length > 0) {
            c1x = x2 + stack.shift();
            c1y = y;
            c2x = c1x + stack.shift();
            c2y = c1y + stack.shift();
            x2 = c2x + stack.shift();
            y = c2y;
            p.curveTo(c1x, c1y, c2x, c2y, x2, y);
          }
          break;
        case 28:
          b1 = code2[i];
          b22 = code2[i + 1];
          stack.push((b1 << 24 | b22 << 16) >> 16);
          i += 2;
          break;
        case 29:
          codeIndex = stack.pop() + font.gsubrsBias;
          subrCode = font.gsubrs[codeIndex];
          if (subrCode) {
            parse2(subrCode);
          }
          break;
        case 30:
          while (stack.length > 0) {
            c1x = x2;
            c1y = y + stack.shift();
            c2x = c1x + stack.shift();
            c2y = c1y + stack.shift();
            x2 = c2x + stack.shift();
            y = c2y + (stack.length === 1 ? stack.shift() : 0);
            p.curveTo(c1x, c1y, c2x, c2y, x2, y);
            if (stack.length === 0) {
              break;
            }
            c1x = x2 + stack.shift();
            c1y = y;
            c2x = c1x + stack.shift();
            c2y = c1y + stack.shift();
            y = c2y + stack.shift();
            x2 = c2x + (stack.length === 1 ? stack.shift() : 0);
            p.curveTo(c1x, c1y, c2x, c2y, x2, y);
          }
          break;
        case 31:
          while (stack.length > 0) {
            c1x = x2 + stack.shift();
            c1y = y;
            c2x = c1x + stack.shift();
            c2y = c1y + stack.shift();
            y = c2y + stack.shift();
            x2 = c2x + (stack.length === 1 ? stack.shift() : 0);
            p.curveTo(c1x, c1y, c2x, c2y, x2, y);
            if (stack.length === 0) {
              break;
            }
            c1x = x2;
            c1y = y + stack.shift();
            c2x = c1x + stack.shift();
            c2y = c1y + stack.shift();
            x2 = c2x + stack.shift();
            y = c2y + (stack.length === 1 ? stack.shift() : 0);
            p.curveTo(c1x, c1y, c2x, c2y, x2, y);
          }
          break;
        default:
          if (v < 32) {
            console.log("Glyph " + glyph.index + ": unknown operator " + v);
          } else if (v < 247) {
            stack.push(v - 139);
          } else if (v < 251) {
            b1 = code2[i];
            i += 1;
            stack.push((v - 247) * 256 + b1 + 108);
          } else if (v < 255) {
            b1 = code2[i];
            i += 1;
            stack.push(-(v - 251) * 256 - b1 - 108);
          } else {
            b1 = code2[i];
            b22 = code2[i + 1];
            b3 = code2[i + 2];
            b42 = code2[i + 3];
            i += 4;
            stack.push((b1 << 24 | b22 << 16 | b3 << 8 | b42) / 65536);
          }
      }
    }
  }
  parse2(code);
  glyph.advanceWidth = width2;
  return p;
}
function parseCFFFDSelect(data2, start, nGlyphs, fdArrayCount) {
  var fdSelect = [];
  var fdIndex;
  var parser = new parse.Parser(data2, start);
  var format = parser.parseCard8();
  if (format === 0) {
    for (var iGid = 0; iGid < nGlyphs; iGid++) {
      fdIndex = parser.parseCard8();
      if (fdIndex >= fdArrayCount) {
        throw new Error("CFF table CID Font FDSelect has bad FD index value " + fdIndex + " (FD count " + fdArrayCount + ")");
      }
      fdSelect.push(fdIndex);
    }
  } else if (format === 3) {
    var nRanges = parser.parseCard16();
    var first2 = parser.parseCard16();
    if (first2 !== 0) {
      throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID " + first2);
    }
    var next;
    for (var iRange = 0; iRange < nRanges; iRange++) {
      fdIndex = parser.parseCard8();
      next = parser.parseCard16();
      if (fdIndex >= fdArrayCount) {
        throw new Error("CFF table CID Font FDSelect has bad FD index value " + fdIndex + " (FD count " + fdArrayCount + ")");
      }
      if (next > nGlyphs) {
        throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID " + next);
      }
      for (; first2 < next; first2++) {
        fdSelect.push(fdIndex);
      }
      first2 = next;
    }
    if (next !== nGlyphs) {
      throw new Error("CFF Table CID Font FDSelect format 3 range has bad final GID " + next);
    }
  } else {
    throw new Error("CFF Table CID Font FDSelect table has unsupported format " + format);
  }
  return fdSelect;
}
function parseCFFTable(data2, start, font, opt) {
  font.tables.cff = {};
  var header = parseCFFHeader(data2, start);
  var nameIndex = parseCFFIndex(data2, header.endOffset, parse.bytesToString);
  var topDictIndex = parseCFFIndex(data2, nameIndex.endOffset);
  var stringIndex = parseCFFIndex(data2, topDictIndex.endOffset, parse.bytesToString);
  var globalSubrIndex = parseCFFIndex(data2, stringIndex.endOffset);
  font.gsubrs = globalSubrIndex.objects;
  font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs);
  var topDictArray = gatherCFFTopDicts(data2, start, topDictIndex.objects, stringIndex.objects);
  if (topDictArray.length !== 1) {
    throw new Error("CFF table has too many fonts in 'FontSet' - count of fonts NameIndex.length = " + topDictArray.length);
  }
  var topDict = topDictArray[0];
  font.tables.cff.topDict = topDict;
  if (topDict._privateDict) {
    font.defaultWidthX = topDict._privateDict.defaultWidthX;
    font.nominalWidthX = topDict._privateDict.nominalWidthX;
  }
  if (topDict.ros[0] !== void 0 && topDict.ros[1] !== void 0) {
    font.isCIDFont = true;
  }
  if (font.isCIDFont) {
    var fdArrayOffset = topDict.fdArray;
    var fdSelectOffset = topDict.fdSelect;
    if (fdArrayOffset === 0 || fdSelectOffset === 0) {
      throw new Error("Font is marked as a CID font, but FDArray and/or FDSelect information is missing");
    }
    fdArrayOffset += start;
    var fdArrayIndex = parseCFFIndex(data2, fdArrayOffset);
    var fdArray = gatherCFFTopDicts(data2, start, fdArrayIndex.objects, stringIndex.objects);
    topDict._fdArray = fdArray;
    fdSelectOffset += start;
    topDict._fdSelect = parseCFFFDSelect(data2, fdSelectOffset, font.numGlyphs, fdArray.length);
  }
  var privateDictOffset = start + topDict.private[1];
  var privateDict = parseCFFPrivateDict(data2, privateDictOffset, topDict.private[0], stringIndex.objects);
  font.defaultWidthX = privateDict.defaultWidthX;
  font.nominalWidthX = privateDict.nominalWidthX;
  if (privateDict.subrs !== 0) {
    var subrOffset = privateDictOffset + privateDict.subrs;
    var subrIndex = parseCFFIndex(data2, subrOffset);
    font.subrs = subrIndex.objects;
    font.subrsBias = calcCFFSubroutineBias(font.subrs);
  } else {
    font.subrs = [];
    font.subrsBias = 0;
  }
  var charStringsIndex;
  if (opt.lowMemory) {
    charStringsIndex = parseCFFIndexLowMemory(data2, start + topDict.charStrings);
    font.nGlyphs = charStringsIndex.offsets.length;
  } else {
    charStringsIndex = parseCFFIndex(data2, start + topDict.charStrings);
    font.nGlyphs = charStringsIndex.objects.length;
  }
  var charset = parseCFFCharset(data2, start + topDict.charset, font.nGlyphs, stringIndex.objects);
  if (topDict.encoding === 0) {
    font.cffEncoding = new CffEncoding(cffStandardEncoding, charset);
  } else if (topDict.encoding === 1) {
    font.cffEncoding = new CffEncoding(cffExpertEncoding, charset);
  } else {
    font.cffEncoding = parseCFFEncoding(data2, start + topDict.encoding, charset);
  }
  font.encoding = font.encoding || font.cffEncoding;
  font.glyphs = new glyphset.GlyphSet(font);
  if (opt.lowMemory) {
    font._push = function(i2) {
      var charString2 = getCffIndexObject(i2, charStringsIndex.offsets, data2, start + topDict.charStrings);
      font.glyphs.push(i2, glyphset.cffGlyphLoader(font, i2, parseCFFCharstring, charString2));
    };
  } else {
    for (var i = 0; i < font.nGlyphs; i += 1) {
      var charString = charStringsIndex.objects[i];
      font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString));
    }
  }
}
function encodeString(s, strings) {
  var sid;
  var i = cffStandardStrings.indexOf(s);
  if (i >= 0) {
    sid = i;
  }
  i = strings.indexOf(s);
  if (i >= 0) {
    sid = i + cffStandardStrings.length;
  } else {
    sid = cffStandardStrings.length + strings.length;
    strings.push(s);
  }
  return sid;
}
function makeHeader() {
  return new table.Record("Header", [
    { name: "major", type: "Card8", value: 1 },
    { name: "minor", type: "Card8", value: 0 },
    { name: "hdrSize", type: "Card8", value: 4 },
    { name: "major", type: "Card8", value: 1 }
  ]);
}
function makeNameIndex(fontNames) {
  var t3 = new table.Record("Name INDEX", [
    { name: "names", type: "INDEX", value: [] }
  ]);
  t3.names = [];
  for (var i = 0; i < fontNames.length; i += 1) {
    t3.names.push({ name: "name_" + i, type: "NAME", value: fontNames[i] });
  }
  return t3;
}
function makeDict(meta2, attrs, strings) {
  var m = {};
  for (var i = 0; i < meta2.length; i += 1) {
    var entry = meta2[i];
    var value2 = attrs[entry.name];
    if (value2 !== void 0 && !equals(value2, entry.value)) {
      if (entry.type === "SID") {
        value2 = encodeString(value2, strings);
      }
      m[entry.op] = { name: entry.name, type: entry.type, value: value2 };
    }
  }
  return m;
}
function makeTopDict(attrs, strings) {
  var t3 = new table.Record("Top DICT", [
    { name: "dict", type: "DICT", value: {} }
  ]);
  t3.dict = makeDict(TOP_DICT_META, attrs, strings);
  return t3;
}
function makeTopDictIndex(topDict) {
  var t3 = new table.Record("Top DICT INDEX", [
    { name: "topDicts", type: "INDEX", value: [] }
  ]);
  t3.topDicts = [{ name: "topDict_0", type: "TABLE", value: topDict }];
  return t3;
}
function makeStringIndex(strings) {
  var t3 = new table.Record("String INDEX", [
    { name: "strings", type: "INDEX", value: [] }
  ]);
  t3.strings = [];
  for (var i = 0; i < strings.length; i += 1) {
    t3.strings.push({ name: "string_" + i, type: "STRING", value: strings[i] });
  }
  return t3;
}
function makeGlobalSubrIndex() {
  return new table.Record("Global Subr INDEX", [
    { name: "subrs", type: "INDEX", value: [] }
  ]);
}
function makeCharsets(glyphNames, strings) {
  var t3 = new table.Record("Charsets", [
    { name: "format", type: "Card8", value: 0 }
  ]);
  for (var i = 0; i < glyphNames.length; i += 1) {
    var glyphName = glyphNames[i];
    var glyphSID = encodeString(glyphName, strings);
    t3.fields.push({ name: "glyph_" + i, type: "SID", value: glyphSID });
  }
  return t3;
}
function glyphToOps(glyph) {
  var ops = [];
  var path = glyph.path;
  ops.push({ name: "width", type: "NUMBER", value: glyph.advanceWidth });
  var x2 = 0;
  var y = 0;
  for (var i = 0; i < path.commands.length; i += 1) {
    var dx = void 0;
    var dy = void 0;
    var cmd = path.commands[i];
    if (cmd.type === "Q") {
      var _13 = 1 / 3;
      var _23 = 2 / 3;
      cmd = {
        type: "C",
        x: cmd.x,
        y: cmd.y,
        x1: Math.round(_13 * x2 + _23 * cmd.x1),
        y1: Math.round(_13 * y + _23 * cmd.y1),
        x2: Math.round(_13 * cmd.x + _23 * cmd.x1),
        y2: Math.round(_13 * cmd.y + _23 * cmd.y1)
      };
    }
    if (cmd.type === "M") {
      dx = Math.round(cmd.x - x2);
      dy = Math.round(cmd.y - y);
      ops.push({ name: "dx", type: "NUMBER", value: dx });
      ops.push({ name: "dy", type: "NUMBER", value: dy });
      ops.push({ name: "rmoveto", type: "OP", value: 21 });
      x2 = Math.round(cmd.x);
      y = Math.round(cmd.y);
    } else if (cmd.type === "L") {
      dx = Math.round(cmd.x - x2);
      dy = Math.round(cmd.y - y);
      ops.push({ name: "dx", type: "NUMBER", value: dx });
      ops.push({ name: "dy", type: "NUMBER", value: dy });
      ops.push({ name: "rlineto", type: "OP", value: 5 });
      x2 = Math.round(cmd.x);
      y = Math.round(cmd.y);
    } else if (cmd.type === "C") {
      var dx1 = Math.round(cmd.x1 - x2);
      var dy1 = Math.round(cmd.y1 - y);
      var dx2 = Math.round(cmd.x2 - cmd.x1);
      var dy2 = Math.round(cmd.y2 - cmd.y1);
      dx = Math.round(cmd.x - cmd.x2);
      dy = Math.round(cmd.y - cmd.y2);
      ops.push({ name: "dx1", type: "NUMBER", value: dx1 });
      ops.push({ name: "dy1", type: "NUMBER", value: dy1 });
      ops.push({ name: "dx2", type: "NUMBER", value: dx2 });
      ops.push({ name: "dy2", type: "NUMBER", value: dy2 });
      ops.push({ name: "dx", type: "NUMBER", value: dx });
      ops.push({ name: "dy", type: "NUMBER", value: dy });
      ops.push({ name: "rrcurveto", type: "OP", value: 8 });
      x2 = Math.round(cmd.x);
      y = Math.round(cmd.y);
    }
  }
  ops.push({ name: "endchar", type: "OP", value: 14 });
  return ops;
}
function makeCharStringsIndex(glyphs) {
  var t3 = new table.Record("CharStrings INDEX", [
    { name: "charStrings", type: "INDEX", value: [] }
  ]);
  for (var i = 0; i < glyphs.length; i += 1) {
    var glyph = glyphs.get(i);
    var ops = glyphToOps(glyph);
    t3.charStrings.push({ name: glyph.name, type: "CHARSTRING", value: ops });
  }
  return t3;
}
function makePrivateDict(attrs, strings) {
  var t3 = new table.Record("Private DICT", [
    { name: "dict", type: "DICT", value: {} }
  ]);
  t3.dict = makeDict(PRIVATE_DICT_META, attrs, strings);
  return t3;
}
function makeCFFTable(glyphs, options) {
  var t3 = new table.Table("CFF ", [
    { name: "header", type: "RECORD" },
    { name: "nameIndex", type: "RECORD" },
    { name: "topDictIndex", type: "RECORD" },
    { name: "stringIndex", type: "RECORD" },
    { name: "globalSubrIndex", type: "RECORD" },
    { name: "charsets", type: "RECORD" },
    { name: "charStringsIndex", type: "RECORD" },
    { name: "privateDict", type: "RECORD" }
  ]);
  var fontScale = 1 / options.unitsPerEm;
  var attrs = {
    version: options.version,
    fullName: options.fullName,
    familyName: options.familyName,
    weight: options.weightName,
    fontBBox: options.fontBBox || [0, 0, 0, 0],
    fontMatrix: [fontScale, 0, 0, fontScale, 0, 0],
    charset: 999,
    encoding: 0,
    charStrings: 999,
    private: [0, 999]
  };
  var privateAttrs = {};
  var glyphNames = [];
  var glyph;
  for (var i = 1; i < glyphs.length; i += 1) {
    glyph = glyphs.get(i);
    glyphNames.push(glyph.name);
  }
  var strings = [];
  t3.header = makeHeader();
  t3.nameIndex = makeNameIndex([options.postScriptName]);
  var topDict = makeTopDict(attrs, strings);
  t3.topDictIndex = makeTopDictIndex(topDict);
  t3.globalSubrIndex = makeGlobalSubrIndex();
  t3.charsets = makeCharsets(glyphNames, strings);
  t3.charStringsIndex = makeCharStringsIndex(glyphs);
  t3.privateDict = makePrivateDict(privateAttrs, strings);
  t3.stringIndex = makeStringIndex(strings);
  var startOffset = t3.header.sizeOf() + t3.nameIndex.sizeOf() + t3.topDictIndex.sizeOf() + t3.stringIndex.sizeOf() + t3.globalSubrIndex.sizeOf();
  attrs.charset = startOffset;
  attrs.encoding = 0;
  attrs.charStrings = attrs.charset + t3.charsets.sizeOf();
  attrs.private[1] = attrs.charStrings + t3.charStringsIndex.sizeOf();
  topDict = makeTopDict(attrs, strings);
  t3.topDictIndex = makeTopDictIndex(topDict);
  return t3;
}
var cff = { parse: parseCFFTable, make: makeCFFTable };
function parseHeadTable(data2, start) {
  var head2 = {};
  var p = new parse.Parser(data2, start);
  head2.version = p.parseVersion();
  head2.fontRevision = Math.round(p.parseFixed() * 1e3) / 1e3;
  head2.checkSumAdjustment = p.parseULong();
  head2.magicNumber = p.parseULong();
  check.argument(head2.magicNumber === 1594834165, "Font header has wrong magic number.");
  head2.flags = p.parseUShort();
  head2.unitsPerEm = p.parseUShort();
  head2.created = p.parseLongDateTime();
  head2.modified = p.parseLongDateTime();
  head2.xMin = p.parseShort();
  head2.yMin = p.parseShort();
  head2.xMax = p.parseShort();
  head2.yMax = p.parseShort();
  head2.macStyle = p.parseUShort();
  head2.lowestRecPPEM = p.parseUShort();
  head2.fontDirectionHint = p.parseShort();
  head2.indexToLocFormat = p.parseShort();
  head2.glyphDataFormat = p.parseShort();
  return head2;
}
function makeHeadTable(options) {
  var timestamp = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3) + 2082844800;
  var createdTimestamp = timestamp;
  if (options.createdTimestamp) {
    createdTimestamp = options.createdTimestamp + 2082844800;
  }
  return new table.Table("head", [
    { name: "version", type: "FIXED", value: 65536 },
    { name: "fontRevision", type: "FIXED", value: 65536 },
    { name: "checkSumAdjustment", type: "ULONG", value: 0 },
    { name: "magicNumber", type: "ULONG", value: 1594834165 },
    { name: "flags", type: "USHORT", value: 0 },
    { name: "unitsPerEm", type: "USHORT", value: 1e3 },
    { name: "created", type: "LONGDATETIME", value: createdTimestamp },
    { name: "modified", type: "LONGDATETIME", value: timestamp },
    { name: "xMin", type: "SHORT", value: 0 },
    { name: "yMin", type: "SHORT", value: 0 },
    { name: "xMax", type: "SHORT", value: 0 },
    { name: "yMax", type: "SHORT", value: 0 },
    { name: "macStyle", type: "USHORT", value: 0 },
    { name: "lowestRecPPEM", type: "USHORT", value: 0 },
    { name: "fontDirectionHint", type: "SHORT", value: 2 },
    { name: "indexToLocFormat", type: "SHORT", value: 0 },
    { name: "glyphDataFormat", type: "SHORT", value: 0 }
  ], options);
}
var head = { parse: parseHeadTable, make: makeHeadTable };
function parseHheaTable(data2, start) {
  var hhea2 = {};
  var p = new parse.Parser(data2, start);
  hhea2.version = p.parseVersion();
  hhea2.ascender = p.parseShort();
  hhea2.descender = p.parseShort();
  hhea2.lineGap = p.parseShort();
  hhea2.advanceWidthMax = p.parseUShort();
  hhea2.minLeftSideBearing = p.parseShort();
  hhea2.minRightSideBearing = p.parseShort();
  hhea2.xMaxExtent = p.parseShort();
  hhea2.caretSlopeRise = p.parseShort();
  hhea2.caretSlopeRun = p.parseShort();
  hhea2.caretOffset = p.parseShort();
  p.relativeOffset += 8;
  hhea2.metricDataFormat = p.parseShort();
  hhea2.numberOfHMetrics = p.parseUShort();
  return hhea2;
}
function makeHheaTable(options) {
  return new table.Table("hhea", [
    { name: "version", type: "FIXED", value: 65536 },
    { name: "ascender", type: "FWORD", value: 0 },
    { name: "descender", type: "FWORD", value: 0 },
    { name: "lineGap", type: "FWORD", value: 0 },
    { name: "advanceWidthMax", type: "UFWORD", value: 0 },
    { name: "minLeftSideBearing", type: "FWORD", value: 0 },
    { name: "minRightSideBearing", type: "FWORD", value: 0 },
    { name: "xMaxExtent", type: "FWORD", value: 0 },
    { name: "caretSlopeRise", type: "SHORT", value: 1 },
    { name: "caretSlopeRun", type: "SHORT", value: 0 },
    { name: "caretOffset", type: "SHORT", value: 0 },
    { name: "reserved1", type: "SHORT", value: 0 },
    { name: "reserved2", type: "SHORT", value: 0 },
    { name: "reserved3", type: "SHORT", value: 0 },
    { name: "reserved4", type: "SHORT", value: 0 },
    { name: "metricDataFormat", type: "SHORT", value: 0 },
    { name: "numberOfHMetrics", type: "USHORT", value: 0 }
  ], options);
}
var hhea = { parse: parseHheaTable, make: makeHheaTable };
function parseHmtxTableAll(data2, start, numMetrics, numGlyphs, glyphs) {
  var advanceWidth;
  var leftSideBearing;
  var p = new parse.Parser(data2, start);
  for (var i = 0; i < numGlyphs; i += 1) {
    if (i < numMetrics) {
      advanceWidth = p.parseUShort();
      leftSideBearing = p.parseShort();
    }
    var glyph = glyphs.get(i);
    glyph.advanceWidth = advanceWidth;
    glyph.leftSideBearing = leftSideBearing;
  }
}
function parseHmtxTableOnLowMemory(font, data2, start, numMetrics, numGlyphs) {
  font._hmtxTableData = {};
  var advanceWidth;
  var leftSideBearing;
  var p = new parse.Parser(data2, start);
  for (var i = 0; i < numGlyphs; i += 1) {
    if (i < numMetrics) {
      advanceWidth = p.parseUShort();
      leftSideBearing = p.parseShort();
    }
    font._hmtxTableData[i] = {
      advanceWidth,
      leftSideBearing
    };
  }
}
function parseHmtxTable(font, data2, start, numMetrics, numGlyphs, glyphs, opt) {
  if (opt.lowMemory) {
    parseHmtxTableOnLowMemory(font, data2, start, numMetrics, numGlyphs);
  } else {
    parseHmtxTableAll(data2, start, numMetrics, numGlyphs, glyphs);
  }
}
function makeHmtxTable(glyphs) {
  var t3 = new table.Table("hmtx", []);
  for (var i = 0; i < glyphs.length; i += 1) {
    var glyph = glyphs.get(i);
    var advanceWidth = glyph.advanceWidth || 0;
    var leftSideBearing = glyph.leftSideBearing || 0;
    t3.fields.push({ name: "advanceWidth_" + i, type: "USHORT", value: advanceWidth });
    t3.fields.push({ name: "leftSideBearing_" + i, type: "SHORT", value: leftSideBearing });
  }
  return t3;
}
var hmtx = { parse: parseHmtxTable, make: makeHmtxTable };
function makeLtagTable(tags) {
  var result = new table.Table("ltag", [
    { name: "version", type: "ULONG", value: 1 },
    { name: "flags", type: "ULONG", value: 0 },
    { name: "numTags", type: "ULONG", value: tags.length }
  ]);
  var stringPool = "";
  var stringPoolOffset = 12 + tags.length * 4;
  for (var i = 0; i < tags.length; ++i) {
    var pos = stringPool.indexOf(tags[i]);
    if (pos < 0) {
      pos = stringPool.length;
      stringPool += tags[i];
    }
    result.fields.push({ name: "offset " + i, type: "USHORT", value: stringPoolOffset + pos });
    result.fields.push({ name: "length " + i, type: "USHORT", value: tags[i].length });
  }
  result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool });
  return result;
}
function parseLtagTable(data2, start) {
  var p = new parse.Parser(data2, start);
  var tableVersion = p.parseULong();
  check.argument(tableVersion === 1, "Unsupported ltag table version.");
  p.skip("uLong", 1);
  var numTags = p.parseULong();
  var tags = [];
  for (var i = 0; i < numTags; i++) {
    var tag = "";
    var offset = start + p.parseUShort();
    var length2 = p.parseUShort();
    for (var j2 = offset; j2 < offset + length2; ++j2) {
      tag += String.fromCharCode(data2.getInt8(j2));
    }
    tags.push(tag);
  }
  return tags;
}
var ltag = { make: makeLtagTable, parse: parseLtagTable };
function parseMaxpTable(data2, start) {
  var maxp2 = {};
  var p = new parse.Parser(data2, start);
  maxp2.version = p.parseVersion();
  maxp2.numGlyphs = p.parseUShort();
  if (maxp2.version === 1) {
    maxp2.maxPoints = p.parseUShort();
    maxp2.maxContours = p.parseUShort();
    maxp2.maxCompositePoints = p.parseUShort();
    maxp2.maxCompositeContours = p.parseUShort();
    maxp2.maxZones = p.parseUShort();
    maxp2.maxTwilightPoints = p.parseUShort();
    maxp2.maxStorage = p.parseUShort();
    maxp2.maxFunctionDefs = p.parseUShort();
    maxp2.maxInstructionDefs = p.parseUShort();
    maxp2.maxStackElements = p.parseUShort();
    maxp2.maxSizeOfInstructions = p.parseUShort();
    maxp2.maxComponentElements = p.parseUShort();
    maxp2.maxComponentDepth = p.parseUShort();
  }
  return maxp2;
}
function makeMaxpTable(numGlyphs) {
  return new table.Table("maxp", [
    { name: "version", type: "FIXED", value: 20480 },
    { name: "numGlyphs", type: "USHORT", value: numGlyphs }
  ]);
}
var maxp = { parse: parseMaxpTable, make: makeMaxpTable };
var nameTableNames = [
  "copyright",
  // 0
  "fontFamily",
  // 1
  "fontSubfamily",
  // 2
  "uniqueID",
  // 3
  "fullName",
  // 4
  "version",
  // 5
  "postScriptName",
  // 6
  "trademark",
  // 7
  "manufacturer",
  // 8
  "designer",
  // 9
  "description",
  // 10
  "manufacturerURL",
  // 11
  "designerURL",
  // 12
  "license",
  // 13
  "licenseURL",
  // 14
  "reserved",
  // 15
  "preferredFamily",
  // 16
  "preferredSubfamily",
  // 17
  "compatibleFullName",
  // 18
  "sampleText",
  // 19
  "postScriptFindFontName",
  // 20
  "wwsFamily",
  // 21
  "wwsSubfamily"
  // 22
];
var macLanguages = {
  0: "en",
  1: "fr",
  2: "de",
  3: "it",
  4: "nl",
  5: "sv",
  6: "es",
  7: "da",
  8: "pt",
  9: "no",
  10: "he",
  11: "ja",
  12: "ar",
  13: "fi",
  14: "el",
  15: "is",
  16: "mt",
  17: "tr",
  18: "hr",
  19: "zh-Hant",
  20: "ur",
  21: "hi",
  22: "th",
  23: "ko",
  24: "lt",
  25: "pl",
  26: "hu",
  27: "es",
  28: "lv",
  29: "se",
  30: "fo",
  31: "fa",
  32: "ru",
  33: "zh",
  34: "nl-BE",
  35: "ga",
  36: "sq",
  37: "ro",
  38: "cz",
  39: "sk",
  40: "si",
  41: "yi",
  42: "sr",
  43: "mk",
  44: "bg",
  45: "uk",
  46: "be",
  47: "uz",
  48: "kk",
  49: "az-Cyrl",
  50: "az-Arab",
  51: "hy",
  52: "ka",
  53: "mo",
  54: "ky",
  55: "tg",
  56: "tk",
  57: "mn-CN",
  58: "mn",
  59: "ps",
  60: "ks",
  61: "ku",
  62: "sd",
  63: "bo",
  64: "ne",
  65: "sa",
  66: "mr",
  67: "bn",
  68: "as",
  69: "gu",
  70: "pa",
  71: "or",
  72: "ml",
  73: "kn",
  74: "ta",
  75: "te",
  76: "si",
  77: "my",
  78: "km",
  79: "lo",
  80: "vi",
  81: "id",
  82: "tl",
  83: "ms",
  84: "ms-Arab",
  85: "am",
  86: "ti",
  87: "om",
  88: "so",
  89: "sw",
  90: "rw",
  91: "rn",
  92: "ny",
  93: "mg",
  94: "eo",
  128: "cy",
  129: "eu",
  130: "ca",
  131: "la",
  132: "qu",
  133: "gn",
  134: "ay",
  135: "tt",
  136: "ug",
  137: "dz",
  138: "jv",
  139: "su",
  140: "gl",
  141: "af",
  142: "br",
  143: "iu",
  144: "gd",
  145: "gv",
  146: "ga",
  147: "to",
  148: "el-polyton",
  149: "kl",
  150: "az",
  151: "nn"
};
var macLanguageToScript = {
  0: 0,
  // langEnglish → smRoman
  1: 0,
  // langFrench → smRoman
  2: 0,
  // langGerman → smRoman
  3: 0,
  // langItalian → smRoman
  4: 0,
  // langDutch → smRoman
  5: 0,
  // langSwedish → smRoman
  6: 0,
  // langSpanish → smRoman
  7: 0,
  // langDanish → smRoman
  8: 0,
  // langPortuguese → smRoman
  9: 0,
  // langNorwegian → smRoman
  10: 5,
  // langHebrew → smHebrew
  11: 1,
  // langJapanese → smJapanese
  12: 4,
  // langArabic → smArabic
  13: 0,
  // langFinnish → smRoman
  14: 6,
  // langGreek → smGreek
  15: 0,
  // langIcelandic → smRoman (modified)
  16: 0,
  // langMaltese → smRoman
  17: 0,
  // langTurkish → smRoman (modified)
  18: 0,
  // langCroatian → smRoman (modified)
  19: 2,
  // langTradChinese → smTradChinese
  20: 4,
  // langUrdu → smArabic
  21: 9,
  // langHindi → smDevanagari
  22: 21,
  // langThai → smThai
  23: 3,
  // langKorean → smKorean
  24: 29,
  // langLithuanian → smCentralEuroRoman
  25: 29,
  // langPolish → smCentralEuroRoman
  26: 29,
  // langHungarian → smCentralEuroRoman
  27: 29,
  // langEstonian → smCentralEuroRoman
  28: 29,
  // langLatvian → smCentralEuroRoman
  29: 0,
  // langSami → smRoman
  30: 0,
  // langFaroese → smRoman (modified)
  31: 4,
  // langFarsi → smArabic (modified)
  32: 7,
  // langRussian → smCyrillic
  33: 25,
  // langSimpChinese → smSimpChinese
  34: 0,
  // langFlemish → smRoman
  35: 0,
  // langIrishGaelic → smRoman (modified)
  36: 0,
  // langAlbanian → smRoman
  37: 0,
  // langRomanian → smRoman (modified)
  38: 29,
  // langCzech → smCentralEuroRoman
  39: 29,
  // langSlovak → smCentralEuroRoman
  40: 0,
  // langSlovenian → smRoman (modified)
  41: 5,
  // langYiddish → smHebrew
  42: 7,
  // langSerbian → smCyrillic
  43: 7,
  // langMacedonian → smCyrillic
  44: 7,
  // langBulgarian → smCyrillic
  45: 7,
  // langUkrainian → smCyrillic (modified)
  46: 7,
  // langByelorussian → smCyrillic
  47: 7,
  // langUzbek → smCyrillic
  48: 7,
  // langKazakh → smCyrillic
  49: 7,
  // langAzerbaijani → smCyrillic
  50: 4,
  // langAzerbaijanAr → smArabic
  51: 24,
  // langArmenian → smArmenian
  52: 23,
  // langGeorgian → smGeorgian
  53: 7,
  // langMoldavian → smCyrillic
  54: 7,
  // langKirghiz → smCyrillic
  55: 7,
  // langTajiki → smCyrillic
  56: 7,
  // langTurkmen → smCyrillic
  57: 27,
  // langMongolian → smMongolian
  58: 7,
  // langMongolianCyr → smCyrillic
  59: 4,
  // langPashto → smArabic
  60: 4,
  // langKurdish → smArabic
  61: 4,
  // langKashmiri → smArabic
  62: 4,
  // langSindhi → smArabic
  63: 26,
  // langTibetan → smTibetan
  64: 9,
  // langNepali → smDevanagari
  65: 9,
  // langSanskrit → smDevanagari
  66: 9,
  // langMarathi → smDevanagari
  67: 13,
  // langBengali → smBengali
  68: 13,
  // langAssamese → smBengali
  69: 11,
  // langGujarati → smGujarati
  70: 10,
  // langPunjabi → smGurmukhi
  71: 12,
  // langOriya → smOriya
  72: 17,
  // langMalayalam → smMalayalam
  73: 16,
  // langKannada → smKannada
  74: 14,
  // langTamil → smTamil
  75: 15,
  // langTelugu → smTelugu
  76: 18,
  // langSinhalese → smSinhalese
  77: 19,
  // langBurmese → smBurmese
  78: 20,
  // langKhmer → smKhmer
  79: 22,
  // langLao → smLao
  80: 30,
  // langVietnamese → smVietnamese
  81: 0,
  // langIndonesian → smRoman
  82: 0,
  // langTagalog → smRoman
  83: 0,
  // langMalayRoman → smRoman
  84: 4,
  // langMalayArabic → smArabic
  85: 28,
  // langAmharic → smEthiopic
  86: 28,
  // langTigrinya → smEthiopic
  87: 28,
  // langOromo → smEthiopic
  88: 0,
  // langSomali → smRoman
  89: 0,
  // langSwahili → smRoman
  90: 0,
  // langKinyarwanda → smRoman
  91: 0,
  // langRundi → smRoman
  92: 0,
  // langNyanja → smRoman
  93: 0,
  // langMalagasy → smRoman
  94: 0,
  // langEsperanto → smRoman
  128: 0,
  // langWelsh → smRoman (modified)
  129: 0,
  // langBasque → smRoman
  130: 0,
  // langCatalan → smRoman
  131: 0,
  // langLatin → smRoman
  132: 0,
  // langQuechua → smRoman
  133: 0,
  // langGuarani → smRoman
  134: 0,
  // langAymara → smRoman
  135: 7,
  // langTatar → smCyrillic
  136: 4,
  // langUighur → smArabic
  137: 26,
  // langDzongkha → smTibetan
  138: 0,
  // langJavaneseRom → smRoman
  139: 0,
  // langSundaneseRom → smRoman
  140: 0,
  // langGalician → smRoman
  141: 0,
  // langAfrikaans → smRoman
  142: 0,
  // langBreton → smRoman (modified)
  143: 28,
  // langInuktitut → smEthiopic (modified)
  144: 0,
  // langScottishGaelic → smRoman (modified)
  145: 0,
  // langManxGaelic → smRoman (modified)
  146: 0,
  // langIrishGaelicScript → smRoman (modified)
  147: 0,
  // langTongan → smRoman
  148: 6,
  // langGreekAncient → smRoman
  149: 0,
  // langGreenlandic → smRoman
  150: 0,
  // langAzerbaijanRoman → smRoman
  151: 0
  // langNynorsk → smRoman
};
var windowsLanguages = {
  1078: "af",
  1052: "sq",
  1156: "gsw",
  1118: "am",
  5121: "ar-DZ",
  15361: "ar-BH",
  3073: "ar",
  2049: "ar-IQ",
  11265: "ar-JO",
  13313: "ar-KW",
  12289: "ar-LB",
  4097: "ar-LY",
  6145: "ary",
  8193: "ar-OM",
  16385: "ar-QA",
  1025: "ar-SA",
  10241: "ar-SY",
  7169: "aeb",
  14337: "ar-AE",
  9217: "ar-YE",
  1067: "hy",
  1101: "as",
  2092: "az-Cyrl",
  1068: "az",
  1133: "ba",
  1069: "eu",
  1059: "be",
  2117: "bn",
  1093: "bn-IN",
  8218: "bs-Cyrl",
  5146: "bs",
  1150: "br",
  1026: "bg",
  1027: "ca",
  3076: "zh-HK",
  5124: "zh-MO",
  2052: "zh",
  4100: "zh-SG",
  1028: "zh-TW",
  1155: "co",
  1050: "hr",
  4122: "hr-BA",
  1029: "cs",
  1030: "da",
  1164: "prs",
  1125: "dv",
  2067: "nl-BE",
  1043: "nl",
  3081: "en-AU",
  10249: "en-BZ",
  4105: "en-CA",
  9225: "en-029",
  16393: "en-IN",
  6153: "en-IE",
  8201: "en-JM",
  17417: "en-MY",
  5129: "en-NZ",
  13321: "en-PH",
  18441: "en-SG",
  7177: "en-ZA",
  11273: "en-TT",
  2057: "en-GB",
  1033: "en",
  12297: "en-ZW",
  1061: "et",
  1080: "fo",
  1124: "fil",
  1035: "fi",
  2060: "fr-BE",
  3084: "fr-CA",
  1036: "fr",
  5132: "fr-LU",
  6156: "fr-MC",
  4108: "fr-CH",
  1122: "fy",
  1110: "gl",
  1079: "ka",
  3079: "de-AT",
  1031: "de",
  5127: "de-LI",
  4103: "de-LU",
  2055: "de-CH",
  1032: "el",
  1135: "kl",
  1095: "gu",
  1128: "ha",
  1037: "he",
  1081: "hi",
  1038: "hu",
  1039: "is",
  1136: "ig",
  1057: "id",
  1117: "iu",
  2141: "iu-Latn",
  2108: "ga",
  1076: "xh",
  1077: "zu",
  1040: "it",
  2064: "it-CH",
  1041: "ja",
  1099: "kn",
  1087: "kk",
  1107: "km",
  1158: "quc",
  1159: "rw",
  1089: "sw",
  1111: "kok",
  1042: "ko",
  1088: "ky",
  1108: "lo",
  1062: "lv",
  1063: "lt",
  2094: "dsb",
  1134: "lb",
  1071: "mk",
  2110: "ms-BN",
  1086: "ms",
  1100: "ml",
  1082: "mt",
  1153: "mi",
  1146: "arn",
  1102: "mr",
  1148: "moh",
  1104: "mn",
  2128: "mn-CN",
  1121: "ne",
  1044: "nb",
  2068: "nn",
  1154: "oc",
  1096: "or",
  1123: "ps",
  1045: "pl",
  1046: "pt",
  2070: "pt-PT",
  1094: "pa",
  1131: "qu-BO",
  2155: "qu-EC",
  3179: "qu",
  1048: "ro",
  1047: "rm",
  1049: "ru",
  9275: "smn",
  4155: "smj-NO",
  5179: "smj",
  3131: "se-FI",
  1083: "se",
  2107: "se-SE",
  8251: "sms",
  6203: "sma-NO",
  7227: "sms",
  1103: "sa",
  7194: "sr-Cyrl-BA",
  3098: "sr",
  6170: "sr-Latn-BA",
  2074: "sr-Latn",
  1132: "nso",
  1074: "tn",
  1115: "si",
  1051: "sk",
  1060: "sl",
  11274: "es-AR",
  16394: "es-BO",
  13322: "es-CL",
  9226: "es-CO",
  5130: "es-CR",
  7178: "es-DO",
  12298: "es-EC",
  17418: "es-SV",
  4106: "es-GT",
  18442: "es-HN",
  2058: "es-MX",
  19466: "es-NI",
  6154: "es-PA",
  15370: "es-PY",
  10250: "es-PE",
  20490: "es-PR",
  // Microsoft has defined two different language codes for
  // “Spanish with modern sorting” and “Spanish with traditional
  // sorting”. This makes sense for collation APIs, and it would be
  // possible to express this in BCP 47 language tags via Unicode
  // extensions (eg., es-u-co-trad is Spanish with traditional
  // sorting). However, for storing names in fonts, the distinction
  // does not make sense, so we give “es” in both cases.
  3082: "es",
  1034: "es",
  21514: "es-US",
  14346: "es-UY",
  8202: "es-VE",
  2077: "sv-FI",
  1053: "sv",
  1114: "syr",
  1064: "tg",
  2143: "tzm",
  1097: "ta",
  1092: "tt",
  1098: "te",
  1054: "th",
  1105: "bo",
  1055: "tr",
  1090: "tk",
  1152: "ug",
  1058: "uk",
  1070: "hsb",
  1056: "ur",
  2115: "uz-Cyrl",
  1091: "uz",
  1066: "vi",
  1106: "cy",
  1160: "wo",
  1157: "sah",
  1144: "ii",
  1130: "yo"
};
function getLanguageCode(platformID, languageID, ltag2) {
  switch (platformID) {
    case 0:
      if (languageID === 65535) {
        return "und";
      } else if (ltag2) {
        return ltag2[languageID];
      }
      break;
    case 1:
      return macLanguages[languageID];
    case 3:
      return windowsLanguages[languageID];
  }
  return void 0;
}
var utf16 = "utf-16";
var macScriptEncodings = {
  0: "macintosh",
  // smRoman
  1: "x-mac-japanese",
  // smJapanese
  2: "x-mac-chinesetrad",
  // smTradChinese
  3: "x-mac-korean",
  // smKorean
  6: "x-mac-greek",
  // smGreek
  7: "x-mac-cyrillic",
  // smCyrillic
  9: "x-mac-devanagai",
  // smDevanagari
  10: "x-mac-gurmukhi",
  // smGurmukhi
  11: "x-mac-gujarati",
  // smGujarati
  12: "x-mac-oriya",
  // smOriya
  13: "x-mac-bengali",
  // smBengali
  14: "x-mac-tamil",
  // smTamil
  15: "x-mac-telugu",
  // smTelugu
  16: "x-mac-kannada",
  // smKannada
  17: "x-mac-malayalam",
  // smMalayalam
  18: "x-mac-sinhalese",
  // smSinhalese
  19: "x-mac-burmese",
  // smBurmese
  20: "x-mac-khmer",
  // smKhmer
  21: "x-mac-thai",
  // smThai
  22: "x-mac-lao",
  // smLao
  23: "x-mac-georgian",
  // smGeorgian
  24: "x-mac-armenian",
  // smArmenian
  25: "x-mac-chinesesimp",
  // smSimpChinese
  26: "x-mac-tibetan",
  // smTibetan
  27: "x-mac-mongolian",
  // smMongolian
  28: "x-mac-ethiopic",
  // smEthiopic
  29: "x-mac-ce",
  // smCentralEuroRoman
  30: "x-mac-vietnamese",
  // smVietnamese
  31: "x-mac-extarabic"
  // smExtArabic
};
var macLanguageEncodings = {
  15: "x-mac-icelandic",
  // langIcelandic
  17: "x-mac-turkish",
  // langTurkish
  18: "x-mac-croatian",
  // langCroatian
  24: "x-mac-ce",
  // langLithuanian
  25: "x-mac-ce",
  // langPolish
  26: "x-mac-ce",
  // langHungarian
  27: "x-mac-ce",
  // langEstonian
  28: "x-mac-ce",
  // langLatvian
  30: "x-mac-icelandic",
  // langFaroese
  37: "x-mac-romanian",
  // langRomanian
  38: "x-mac-ce",
  // langCzech
  39: "x-mac-ce",
  // langSlovak
  40: "x-mac-ce",
  // langSlovenian
  143: "x-mac-inuit",
  // langInuktitut
  146: "x-mac-gaelic"
  // langIrishGaelicScript
};
function getEncoding(platformID, encodingID, languageID) {
  switch (platformID) {
    case 0:
      return utf16;
    case 1:
      return macLanguageEncodings[languageID] || macScriptEncodings[encodingID];
    case 3:
      if (encodingID === 1 || encodingID === 10) {
        return utf16;
      }
      break;
  }
  return void 0;
}
function parseNameTable(data2, start, ltag2) {
  var name2 = {};
  var p = new parse.Parser(data2, start);
  var format = p.parseUShort();
  var count = p.parseUShort();
  var stringOffset2 = p.offset + p.parseUShort();
  for (var i = 0; i < count; i++) {
    var platformID = p.parseUShort();
    var encodingID = p.parseUShort();
    var languageID = p.parseUShort();
    var nameID = p.parseUShort();
    var property2 = nameTableNames[nameID] || nameID;
    var byteLength = p.parseUShort();
    var offset = p.parseUShort();
    var language = getLanguageCode(platformID, languageID, ltag2);
    var encoding = getEncoding(platformID, encodingID, languageID);
    if (encoding !== void 0 && language !== void 0) {
      var text2 = void 0;
      if (encoding === utf16) {
        text2 = decode.UTF16(data2, stringOffset2 + offset, byteLength);
      } else {
        text2 = decode.MACSTRING(data2, stringOffset2 + offset, byteLength, encoding);
      }
      if (text2) {
        var translations = name2[property2];
        if (translations === void 0) {
          translations = name2[property2] = {};
        }
        translations[language] = text2;
      }
    }
  }
  var langTagCount = 0;
  if (format === 1) {
    langTagCount = p.parseUShort();
  }
  return name2;
}
function reverseDict(dict) {
  var result = {};
  for (var key2 in dict) {
    result[dict[key2]] = parseInt(key2);
  }
  return result;
}
function makeNameRecord(platformID, encodingID, languageID, nameID, length2, offset) {
  return new table.Record("NameRecord", [
    { name: "platformID", type: "USHORT", value: platformID },
    { name: "encodingID", type: "USHORT", value: encodingID },
    { name: "languageID", type: "USHORT", value: languageID },
    { name: "nameID", type: "USHORT", value: nameID },
    { name: "length", type: "USHORT", value: length2 },
    { name: "offset", type: "USHORT", value: offset }
  ]);
}
function findSubArray(needle, haystack) {
  var needleLength = needle.length;
  var limit = haystack.length - needleLength + 1;
  loop:
    for (var pos = 0; pos < limit; pos++) {
      for (; pos < limit; pos++) {
        for (var k2 = 0; k2 < needleLength; k2++) {
          if (haystack[pos + k2] !== needle[k2]) {
            continue loop;
          }
        }
        return pos;
      }
    }
  return -1;
}
function addStringToPool(s, pool) {
  var offset = findSubArray(s, pool);
  if (offset < 0) {
    offset = pool.length;
    var i = 0;
    var len = s.length;
    for (; i < len; ++i) {
      pool.push(s[i]);
    }
  }
  return offset;
}
function makeNameTable(names, ltag2) {
  var nameID;
  var nameIDs = [];
  var namesWithNumericKeys = {};
  var nameTableIds = reverseDict(nameTableNames);
  for (var key2 in names) {
    var id = nameTableIds[key2];
    if (id === void 0) {
      id = key2;
    }
    nameID = parseInt(id);
    if (isNaN(nameID)) {
      throw new Error('Name table entry "' + key2 + '" does not exist, see nameTableNames for complete list.');
    }
    namesWithNumericKeys[nameID] = names[key2];
    nameIDs.push(nameID);
  }
  var macLanguageIds = reverseDict(macLanguages);
  var windowsLanguageIds = reverseDict(windowsLanguages);
  var nameRecords = [];
  var stringPool = [];
  for (var i = 0; i < nameIDs.length; i++) {
    nameID = nameIDs[i];
    var translations = namesWithNumericKeys[nameID];
    for (var lang in translations) {
      var text2 = translations[lang];
      var macPlatform = 1;
      var macLanguage = macLanguageIds[lang];
      var macScript = macLanguageToScript[macLanguage];
      var macEncoding = getEncoding(macPlatform, macScript, macLanguage);
      var macName = encode.MACSTRING(text2, macEncoding);
      if (macName === void 0) {
        macPlatform = 0;
        macLanguage = ltag2.indexOf(lang);
        if (macLanguage < 0) {
          macLanguage = ltag2.length;
          ltag2.push(lang);
        }
        macScript = 4;
        macName = encode.UTF16(text2);
      }
      var macNameOffset = addStringToPool(macName, stringPool);
      nameRecords.push(makeNameRecord(
        macPlatform,
        macScript,
        macLanguage,
        nameID,
        macName.length,
        macNameOffset
      ));
      var winLanguage = windowsLanguageIds[lang];
      if (winLanguage !== void 0) {
        var winName = encode.UTF16(text2);
        var winNameOffset = addStringToPool(winName, stringPool);
        nameRecords.push(makeNameRecord(
          3,
          1,
          winLanguage,
          nameID,
          winName.length,
          winNameOffset
        ));
      }
    }
  }
  nameRecords.sort(function(a2, b3) {
    return a2.platformID - b3.platformID || a2.encodingID - b3.encodingID || a2.languageID - b3.languageID || a2.nameID - b3.nameID;
  });
  var t3 = new table.Table("name", [
    { name: "format", type: "USHORT", value: 0 },
    { name: "count", type: "USHORT", value: nameRecords.length },
    { name: "stringOffset", type: "USHORT", value: 6 + nameRecords.length * 12 }
  ]);
  for (var r = 0; r < nameRecords.length; r++) {
    t3.fields.push({ name: "record_" + r, type: "RECORD", value: nameRecords[r] });
  }
  t3.fields.push({ name: "strings", type: "LITERAL", value: stringPool });
  return t3;
}
var _name = { parse: parseNameTable, make: makeNameTable };
var unicodeRanges = [
  { begin: 0, end: 127 },
  // Basic Latin
  { begin: 128, end: 255 },
  // Latin-1 Supplement
  { begin: 256, end: 383 },
  // Latin Extended-A
  { begin: 384, end: 591 },
  // Latin Extended-B
  { begin: 592, end: 687 },
  // IPA Extensions
  { begin: 688, end: 767 },
  // Spacing Modifier Letters
  { begin: 768, end: 879 },
  // Combining Diacritical Marks
  { begin: 880, end: 1023 },
  // Greek and Coptic
  { begin: 11392, end: 11519 },
  // Coptic
  { begin: 1024, end: 1279 },
  // Cyrillic
  { begin: 1328, end: 1423 },
  // Armenian
  { begin: 1424, end: 1535 },
  // Hebrew
  { begin: 42240, end: 42559 },
  // Vai
  { begin: 1536, end: 1791 },
  // Arabic
  { begin: 1984, end: 2047 },
  // NKo
  { begin: 2304, end: 2431 },
  // Devanagari
  { begin: 2432, end: 2559 },
  // Bengali
  { begin: 2560, end: 2687 },
  // Gurmukhi
  { begin: 2688, end: 2815 },
  // Gujarati
  { begin: 2816, end: 2943 },
  // Oriya
  { begin: 2944, end: 3071 },
  // Tamil
  { begin: 3072, end: 3199 },
  // Telugu
  { begin: 3200, end: 3327 },
  // Kannada
  { begin: 3328, end: 3455 },
  // Malayalam
  { begin: 3584, end: 3711 },
  // Thai
  { begin: 3712, end: 3839 },
  // Lao
  { begin: 4256, end: 4351 },
  // Georgian
  { begin: 6912, end: 7039 },
  // Balinese
  { begin: 4352, end: 4607 },
  // Hangul Jamo
  { begin: 7680, end: 7935 },
  // Latin Extended Additional
  { begin: 7936, end: 8191 },
  // Greek Extended
  { begin: 8192, end: 8303 },
  // General Punctuation
  { begin: 8304, end: 8351 },
  // Superscripts And Subscripts
  { begin: 8352, end: 8399 },
  // Currency Symbol
  { begin: 8400, end: 8447 },
  // Combining Diacritical Marks For Symbols
  { begin: 8448, end: 8527 },
  // Letterlike Symbols
  { begin: 8528, end: 8591 },
  // Number Forms
  { begin: 8592, end: 8703 },
  // Arrows
  { begin: 8704, end: 8959 },
  // Mathematical Operators
  { begin: 8960, end: 9215 },
  // Miscellaneous Technical
  { begin: 9216, end: 9279 },
  // Control Pictures
  { begin: 9280, end: 9311 },
  // Optical Character Recognition
  { begin: 9312, end: 9471 },
  // Enclosed Alphanumerics
  { begin: 9472, end: 9599 },
  // Box Drawing
  { begin: 9600, end: 9631 },
  // Block Elements
  { begin: 9632, end: 9727 },
  // Geometric Shapes
  { begin: 9728, end: 9983 },
  // Miscellaneous Symbols
  { begin: 9984, end: 10175 },
  // Dingbats
  { begin: 12288, end: 12351 },
  // CJK Symbols And Punctuation
  { begin: 12352, end: 12447 },
  // Hiragana
  { begin: 12448, end: 12543 },
  // Katakana
  { begin: 12544, end: 12591 },
  // Bopomofo
  { begin: 12592, end: 12687 },
  // Hangul Compatibility Jamo
  { begin: 43072, end: 43135 },
  // Phags-pa
  { begin: 12800, end: 13055 },
  // Enclosed CJK Letters And Months
  { begin: 13056, end: 13311 },
  // CJK Compatibility
  { begin: 44032, end: 55215 },
  // Hangul Syllables
  { begin: 55296, end: 57343 },
  // Non-Plane 0 *
  { begin: 67840, end: 67871 },
  // Phoenicia
  { begin: 19968, end: 40959 },
  // CJK Unified Ideographs
  { begin: 57344, end: 63743 },
  // Private Use Area (plane 0)
  { begin: 12736, end: 12783 },
  // CJK Strokes
  { begin: 64256, end: 64335 },
  // Alphabetic Presentation Forms
  { begin: 64336, end: 65023 },
  // Arabic Presentation Forms-A
  { begin: 65056, end: 65071 },
  // Combining Half Marks
  { begin: 65040, end: 65055 },
  // Vertical Forms
  { begin: 65104, end: 65135 },
  // Small Form Variants
  { begin: 65136, end: 65279 },
  // Arabic Presentation Forms-B
  { begin: 65280, end: 65519 },
  // Halfwidth And Fullwidth Forms
  { begin: 65520, end: 65535 },
  // Specials
  { begin: 3840, end: 4095 },
  // Tibetan
  { begin: 1792, end: 1871 },
  // Syriac
  { begin: 1920, end: 1983 },
  // Thaana
  { begin: 3456, end: 3583 },
  // Sinhala
  { begin: 4096, end: 4255 },
  // Myanmar
  { begin: 4608, end: 4991 },
  // Ethiopic
  { begin: 5024, end: 5119 },
  // Cherokee
  { begin: 5120, end: 5759 },
  // Unified Canadian Aboriginal Syllabics
  { begin: 5760, end: 5791 },
  // Ogham
  { begin: 5792, end: 5887 },
  // Runic
  { begin: 6016, end: 6143 },
  // Khmer
  { begin: 6144, end: 6319 },
  // Mongolian
  { begin: 10240, end: 10495 },
  // Braille Patterns
  { begin: 40960, end: 42127 },
  // Yi Syllables
  { begin: 5888, end: 5919 },
  // Tagalog
  { begin: 66304, end: 66351 },
  // Old Italic
  { begin: 66352, end: 66383 },
  // Gothic
  { begin: 66560, end: 66639 },
  // Deseret
  { begin: 118784, end: 119039 },
  // Byzantine Musical Symbols
  { begin: 119808, end: 120831 },
  // Mathematical Alphanumeric Symbols
  { begin: 1044480, end: 1048573 },
  // Private Use (plane 15)
  { begin: 65024, end: 65039 },
  // Variation Selectors
  { begin: 917504, end: 917631 },
  // Tags
  { begin: 6400, end: 6479 },
  // Limbu
  { begin: 6480, end: 6527 },
  // Tai Le
  { begin: 6528, end: 6623 },
  // New Tai Lue
  { begin: 6656, end: 6687 },
  // Buginese
  { begin: 11264, end: 11359 },
  // Glagolitic
  { begin: 11568, end: 11647 },
  // Tifinagh
  { begin: 19904, end: 19967 },
  // Yijing Hexagram Symbols
  { begin: 43008, end: 43055 },
  // Syloti Nagri
  { begin: 65536, end: 65663 },
  // Linear B Syllabary
  { begin: 65856, end: 65935 },
  // Ancient Greek Numbers
  { begin: 66432, end: 66463 },
  // Ugaritic
  { begin: 66464, end: 66527 },
  // Old Persian
  { begin: 66640, end: 66687 },
  // Shavian
  { begin: 66688, end: 66735 },
  // Osmanya
  { begin: 67584, end: 67647 },
  // Cypriot Syllabary
  { begin: 68096, end: 68191 },
  // Kharoshthi
  { begin: 119552, end: 119647 },
  // Tai Xuan Jing Symbols
  { begin: 73728, end: 74751 },
  // Cuneiform
  { begin: 119648, end: 119679 },
  // Counting Rod Numerals
  { begin: 7040, end: 7103 },
  // Sundanese
  { begin: 7168, end: 7247 },
  // Lepcha
  { begin: 7248, end: 7295 },
  // Ol Chiki
  { begin: 43136, end: 43231 },
  // Saurashtra
  { begin: 43264, end: 43311 },
  // Kayah Li
  { begin: 43312, end: 43359 },
  // Rejang
  { begin: 43520, end: 43615 },
  // Cham
  { begin: 65936, end: 65999 },
  // Ancient Symbols
  { begin: 66e3, end: 66047 },
  // Phaistos Disc
  { begin: 66208, end: 66271 },
  // Carian
  { begin: 127024, end: 127135 }
  // Domino Tiles
];
function getUnicodeRange(unicode) {
  for (var i = 0; i < unicodeRanges.length; i += 1) {
    var range = unicodeRanges[i];
    if (unicode >= range.begin && unicode < range.end) {
      return i;
    }
  }
  return -1;
}
function parseOS2Table(data2, start) {
  var os22 = {};
  var p = new parse.Parser(data2, start);
  os22.version = p.parseUShort();
  os22.xAvgCharWidth = p.parseShort();
  os22.usWeightClass = p.parseUShort();
  os22.usWidthClass = p.parseUShort();
  os22.fsType = p.parseUShort();
  os22.ySubscriptXSize = p.parseShort();
  os22.ySubscriptYSize = p.parseShort();
  os22.ySubscriptXOffset = p.parseShort();
  os22.ySubscriptYOffset = p.parseShort();
  os22.ySuperscriptXSize = p.parseShort();
  os22.ySuperscriptYSize = p.parseShort();
  os22.ySuperscriptXOffset = p.parseShort();
  os22.ySuperscriptYOffset = p.parseShort();
  os22.yStrikeoutSize = p.parseShort();
  os22.yStrikeoutPosition = p.parseShort();
  os22.sFamilyClass = p.parseShort();
  os22.panose = [];
  for (var i = 0; i < 10; i++) {
    os22.panose[i] = p.parseByte();
  }
  os22.ulUnicodeRange1 = p.parseULong();
  os22.ulUnicodeRange2 = p.parseULong();
  os22.ulUnicodeRange3 = p.parseULong();
  os22.ulUnicodeRange4 = p.parseULong();
  os22.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte());
  os22.fsSelection = p.parseUShort();
  os22.usFirstCharIndex = p.parseUShort();
  os22.usLastCharIndex = p.parseUShort();
  os22.sTypoAscender = p.parseShort();
  os22.sTypoDescender = p.parseShort();
  os22.sTypoLineGap = p.parseShort();
  os22.usWinAscent = p.parseUShort();
  os22.usWinDescent = p.parseUShort();
  if (os22.version >= 1) {
    os22.ulCodePageRange1 = p.parseULong();
    os22.ulCodePageRange2 = p.parseULong();
  }
  if (os22.version >= 2) {
    os22.sxHeight = p.parseShort();
    os22.sCapHeight = p.parseShort();
    os22.usDefaultChar = p.parseUShort();
    os22.usBreakChar = p.parseUShort();
    os22.usMaxContent = p.parseUShort();
  }
  return os22;
}
function makeOS2Table(options) {
  return new table.Table("OS/2", [
    { name: "version", type: "USHORT", value: 3 },
    { name: "xAvgCharWidth", type: "SHORT", value: 0 },
    { name: "usWeightClass", type: "USHORT", value: 0 },
    { name: "usWidthClass", type: "USHORT", value: 0 },
    { name: "fsType", type: "USHORT", value: 0 },
    { name: "ySubscriptXSize", type: "SHORT", value: 650 },
    { name: "ySubscriptYSize", type: "SHORT", value: 699 },
    { name: "ySubscriptXOffset", type: "SHORT", value: 0 },
    { name: "ySubscriptYOffset", type: "SHORT", value: 140 },
    { name: "ySuperscriptXSize", type: "SHORT", value: 650 },
    { name: "ySuperscriptYSize", type: "SHORT", value: 699 },
    { name: "ySuperscriptXOffset", type: "SHORT", value: 0 },
    { name: "ySuperscriptYOffset", type: "SHORT", value: 479 },
    { name: "yStrikeoutSize", type: "SHORT", value: 49 },
    { name: "yStrikeoutPosition", type: "SHORT", value: 258 },
    { name: "sFamilyClass", type: "SHORT", value: 0 },
    { name: "bFamilyType", type: "BYTE", value: 0 },
    { name: "bSerifStyle", type: "BYTE", value: 0 },
    { name: "bWeight", type: "BYTE", value: 0 },
    { name: "bProportion", type: "BYTE", value: 0 },
    { name: "bContrast", type: "BYTE", value: 0 },
    { name: "bStrokeVariation", type: "BYTE", value: 0 },
    { name: "bArmStyle", type: "BYTE", value: 0 },
    { name: "bLetterform", type: "BYTE", value: 0 },
    { name: "bMidline", type: "BYTE", value: 0 },
    { name: "bXHeight", type: "BYTE", value: 0 },
    { name: "ulUnicodeRange1", type: "ULONG", value: 0 },
    { name: "ulUnicodeRange2", type: "ULONG", value: 0 },
    { name: "ulUnicodeRange3", type: "ULONG", value: 0 },
    { name: "ulUnicodeRange4", type: "ULONG", value: 0 },
    { name: "achVendID", type: "CHARARRAY", value: "XXXX" },
    { name: "fsSelection", type: "USHORT", value: 0 },
    { name: "usFirstCharIndex", type: "USHORT", value: 0 },
    { name: "usLastCharIndex", type: "USHORT", value: 0 },
    { name: "sTypoAscender", type: "SHORT", value: 0 },
    { name: "sTypoDescender", type: "SHORT", value: 0 },
    { name: "sTypoLineGap", type: "SHORT", value: 0 },
    { name: "usWinAscent", type: "USHORT", value: 0 },
    { name: "usWinDescent", type: "USHORT", value: 0 },
    { name: "ulCodePageRange1", type: "ULONG", value: 0 },
    { name: "ulCodePageRange2", type: "ULONG", value: 0 },
    { name: "sxHeight", type: "SHORT", value: 0 },
    { name: "sCapHeight", type: "SHORT", value: 0 },
    { name: "usDefaultChar", type: "USHORT", value: 0 },
    { name: "usBreakChar", type: "USHORT", value: 0 },
    { name: "usMaxContext", type: "USHORT", value: 0 }
  ], options);
}
var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges, getUnicodeRange };
function parsePostTable(data2, start) {
  var post2 = {};
  var p = new parse.Parser(data2, start);
  post2.version = p.parseVersion();
  post2.italicAngle = p.parseFixed();
  post2.underlinePosition = p.parseShort();
  post2.underlineThickness = p.parseShort();
  post2.isFixedPitch = p.parseULong();
  post2.minMemType42 = p.parseULong();
  post2.maxMemType42 = p.parseULong();
  post2.minMemType1 = p.parseULong();
  post2.maxMemType1 = p.parseULong();
  switch (post2.version) {
    case 1:
      post2.names = standardNames.slice();
      break;
    case 2:
      post2.numberOfGlyphs = p.parseUShort();
      post2.glyphNameIndex = new Array(post2.numberOfGlyphs);
      for (var i = 0; i < post2.numberOfGlyphs; i++) {
        post2.glyphNameIndex[i] = p.parseUShort();
      }
      post2.names = [];
      for (var i$1 = 0; i$1 < post2.numberOfGlyphs; i$1++) {
        if (post2.glyphNameIndex[i$1] >= standardNames.length) {
          var nameLength = p.parseChar();
          post2.names.push(p.parseString(nameLength));
        }
      }
      break;
    case 2.5:
      post2.numberOfGlyphs = p.parseUShort();
      post2.offset = new Array(post2.numberOfGlyphs);
      for (var i$2 = 0; i$2 < post2.numberOfGlyphs; i$2++) {
        post2.offset[i$2] = p.parseChar();
      }
      break;
  }
  return post2;
}
function makePostTable() {
  return new table.Table("post", [
    { name: "version", type: "FIXED", value: 196608 },
    { name: "italicAngle", type: "FIXED", value: 0 },
    { name: "underlinePosition", type: "FWORD", value: 0 },
    { name: "underlineThickness", type: "FWORD", value: 0 },
    { name: "isFixedPitch", type: "ULONG", value: 0 },
    { name: "minMemType42", type: "ULONG", value: 0 },
    { name: "maxMemType42", type: "ULONG", value: 0 },
    { name: "minMemType1", type: "ULONG", value: 0 },
    { name: "maxMemType1", type: "ULONG", value: 0 }
  ]);
}
var post = { parse: parsePostTable, make: makePostTable };
var subtableParsers = new Array(9);
subtableParsers[1] = function parseLookup1() {
  var start = this.offset + this.relativeOffset;
  var substFormat = this.parseUShort();
  if (substFormat === 1) {
    return {
      substFormat: 1,
      coverage: this.parsePointer(Parser.coverage),
      deltaGlyphId: this.parseUShort()
    };
  } else if (substFormat === 2) {
    return {
      substFormat: 2,
      coverage: this.parsePointer(Parser.coverage),
      substitute: this.parseOffset16List()
    };
  }
  check.assert(false, "0x" + start.toString(16) + ": lookup type 1 format must be 1 or 2.");
};
subtableParsers[2] = function parseLookup2() {
  var substFormat = this.parseUShort();
  check.argument(substFormat === 1, "GSUB Multiple Substitution Subtable identifier-format must be 1");
  return {
    substFormat,
    coverage: this.parsePointer(Parser.coverage),
    sequences: this.parseListOfLists()
  };
};
subtableParsers[3] = function parseLookup3() {
  var substFormat = this.parseUShort();
  check.argument(substFormat === 1, "GSUB Alternate Substitution Subtable identifier-format must be 1");
  return {
    substFormat,
    coverage: this.parsePointer(Parser.coverage),
    alternateSets: this.parseListOfLists()
  };
};
subtableParsers[4] = function parseLookup4() {
  var substFormat = this.parseUShort();
  check.argument(substFormat === 1, "GSUB ligature table identifier-format must be 1");
  return {
    substFormat,
    coverage: this.parsePointer(Parser.coverage),
    ligatureSets: this.parseListOfLists(function() {
      return {
        ligGlyph: this.parseUShort(),
        components: this.parseUShortList(this.parseUShort() - 1)
      };
    })
  };
};
var lookupRecordDesc = {
  sequenceIndex: Parser.uShort,
  lookupListIndex: Parser.uShort
};
subtableParsers[5] = function parseLookup5() {
  var start = this.offset + this.relativeOffset;
  var substFormat = this.parseUShort();
  if (substFormat === 1) {
    return {
      substFormat,
      coverage: this.parsePointer(Parser.coverage),
      ruleSets: this.parseListOfLists(function() {
        var glyphCount2 = this.parseUShort();
        var substCount2 = this.parseUShort();
        return {
          input: this.parseUShortList(glyphCount2 - 1),
          lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc)
        };
      })
    };
  } else if (substFormat === 2) {
    return {
      substFormat,
      coverage: this.parsePointer(Parser.coverage),
      classDef: this.parsePointer(Parser.classDef),
      classSets: this.parseListOfLists(function() {
        var glyphCount2 = this.parseUShort();
        var substCount2 = this.parseUShort();
        return {
          classes: this.parseUShortList(glyphCount2 - 1),
          lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc)
        };
      })
    };
  } else if (substFormat === 3) {
    var glyphCount = this.parseUShort();
    var substCount = this.parseUShort();
    return {
      substFormat,
      coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)),
      lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
    };
  }
  check.assert(false, "0x" + start.toString(16) + ": lookup type 5 format must be 1, 2 or 3.");
};
subtableParsers[6] = function parseLookup6() {
  var start = this.offset + this.relativeOffset;
  var substFormat = this.parseUShort();
  if (substFormat === 1) {
    return {
      substFormat: 1,
      coverage: this.parsePointer(Parser.coverage),
      chainRuleSets: this.parseListOfLists(function() {
        return {
          backtrack: this.parseUShortList(),
          input: this.parseUShortList(this.parseShort() - 1),
          lookahead: this.parseUShortList(),
          lookupRecords: this.parseRecordList(lookupRecordDesc)
        };
      })
    };
  } else if (substFormat === 2) {
    return {
      substFormat: 2,
      coverage: this.parsePointer(Parser.coverage),
      backtrackClassDef: this.parsePointer(Parser.classDef),
      inputClassDef: this.parsePointer(Parser.classDef),
      lookaheadClassDef: this.parsePointer(Parser.classDef),
      chainClassSet: this.parseListOfLists(function() {
        return {
          backtrack: this.parseUShortList(),
          input: this.parseUShortList(this.parseShort() - 1),
          lookahead: this.parseUShortList(),
          lookupRecords: this.parseRecordList(lookupRecordDesc)
        };
      })
    };
  } else if (substFormat === 3) {
    return {
      substFormat: 3,
      backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
      inputCoverage: this.parseList(Parser.pointer(Parser.coverage)),
      lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
      lookupRecords: this.parseRecordList(lookupRecordDesc)
    };
  }
  check.assert(false, "0x" + start.toString(16) + ": lookup type 6 format must be 1, 2 or 3.");
};
subtableParsers[7] = function parseLookup7() {
  var substFormat = this.parseUShort();
  check.argument(substFormat === 1, "GSUB Extension Substitution subtable identifier-format must be 1");
  var extensionLookupType = this.parseUShort();
  var extensionParser = new Parser(this.data, this.offset + this.parseULong());
  return {
    substFormat: 1,
    lookupType: extensionLookupType,
    extension: subtableParsers[extensionLookupType].call(extensionParser)
  };
};
subtableParsers[8] = function parseLookup8() {
  var substFormat = this.parseUShort();
  check.argument(substFormat === 1, "GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1");
  return {
    substFormat,
    coverage: this.parsePointer(Parser.coverage),
    backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
    lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
    substitutes: this.parseUShortList()
  };
};
function parseGsubTable(data2, start) {
  start = start || 0;
  var p = new Parser(data2, start);
  var tableVersion = p.parseVersion(1);
  check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GSUB table version.");
  if (tableVersion === 1) {
    return {
      version: tableVersion,
      scripts: p.parseScriptList(),
      features: p.parseFeatureList(),
      lookups: p.parseLookupList(subtableParsers)
    };
  } else {
    return {
      version: tableVersion,
      scripts: p.parseScriptList(),
      features: p.parseFeatureList(),
      lookups: p.parseLookupList(subtableParsers),
      variations: p.parseFeatureVariationsList()
    };
  }
}
var subtableMakers = new Array(9);
subtableMakers[1] = function makeLookup1(subtable) {
  if (subtable.substFormat === 1) {
    return new table.Table("substitutionTable", [
      { name: "substFormat", type: "USHORT", value: 1 },
      { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) },
      { name: "deltaGlyphID", type: "USHORT", value: subtable.deltaGlyphId }
    ]);
  } else {
    return new table.Table("substitutionTable", [
      { name: "substFormat", type: "USHORT", value: 2 },
      { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }
    ].concat(table.ushortList("substitute", subtable.substitute)));
  }
};
subtableMakers[2] = function makeLookup2(subtable) {
  check.assert(subtable.substFormat === 1, "Lookup type 2 substFormat must be 1.");
  return new table.Table("substitutionTable", [
    { name: "substFormat", type: "USHORT", value: 1 },
    { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }
  ].concat(table.tableList("seqSet", subtable.sequences, function(sequenceSet) {
    return new table.Table("sequenceSetTable", table.ushortList("sequence", sequenceSet));
  })));
};
subtableMakers[3] = function makeLookup3(subtable) {
  check.assert(subtable.substFormat === 1, "Lookup type 3 substFormat must be 1.");
  return new table.Table("substitutionTable", [
    { name: "substFormat", type: "USHORT", value: 1 },
    { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }
  ].concat(table.tableList("altSet", subtable.alternateSets, function(alternateSet) {
    return new table.Table("alternateSetTable", table.ushortList("alternate", alternateSet));
  })));
};
subtableMakers[4] = function makeLookup4(subtable) {
  check.assert(subtable.substFormat === 1, "Lookup type 4 substFormat must be 1.");
  return new table.Table("substitutionTable", [
    { name: "substFormat", type: "USHORT", value: 1 },
    { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }
  ].concat(table.tableList("ligSet", subtable.ligatureSets, function(ligatureSet) {
    return new table.Table("ligatureSetTable", table.tableList("ligature", ligatureSet, function(ligature) {
      return new table.Table(
        "ligatureTable",
        [{ name: "ligGlyph", type: "USHORT", value: ligature.ligGlyph }].concat(table.ushortList("component", ligature.components, ligature.components.length + 1))
      );
    }));
  })));
};
subtableMakers[6] = function makeLookup6(subtable) {
  if (subtable.substFormat === 1) {
    var returnTable = new table.Table("chainContextTable", [
      { name: "substFormat", type: "USHORT", value: subtable.substFormat },
      { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }
    ].concat(table.tableList("chainRuleSet", subtable.chainRuleSets, function(chainRuleSet) {
      return new table.Table("chainRuleSetTable", table.tableList("chainRule", chainRuleSet, function(chainRule) {
        var tableData2 = table.ushortList("backtrackGlyph", chainRule.backtrack, chainRule.backtrack.length).concat(table.ushortList("inputGlyph", chainRule.input, chainRule.input.length + 1)).concat(table.ushortList("lookaheadGlyph", chainRule.lookahead, chainRule.lookahead.length)).concat(table.ushortList("substitution", [], chainRule.lookupRecords.length));
        chainRule.lookupRecords.forEach(function(record, i) {
          tableData2 = tableData2.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex });
        });
        return new table.Table("chainRuleTable", tableData2);
      }));
    })));
    return returnTable;
  } else if (subtable.substFormat === 2) {
    check.assert(false, "lookup type 6 format 2 is not yet supported.");
  } else if (subtable.substFormat === 3) {
    var tableData = [
      { name: "substFormat", type: "USHORT", value: subtable.substFormat }
    ];
    tableData.push({ name: "backtrackGlyphCount", type: "USHORT", value: subtable.backtrackCoverage.length });
    subtable.backtrackCoverage.forEach(function(coverage, i) {
      tableData.push({ name: "backtrackCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) });
    });
    tableData.push({ name: "inputGlyphCount", type: "USHORT", value: subtable.inputCoverage.length });
    subtable.inputCoverage.forEach(function(coverage, i) {
      tableData.push({ name: "inputCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) });
    });
    tableData.push({ name: "lookaheadGlyphCount", type: "USHORT", value: subtable.lookaheadCoverage.length });
    subtable.lookaheadCoverage.forEach(function(coverage, i) {
      tableData.push({ name: "lookaheadCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) });
    });
    tableData.push({ name: "substitutionCount", type: "USHORT", value: subtable.lookupRecords.length });
    subtable.lookupRecords.forEach(function(record, i) {
      tableData = tableData.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex });
    });
    var returnTable$1 = new table.Table("chainContextTable", tableData);
    return returnTable$1;
  }
  check.assert(false, "lookup type 6 format must be 1, 2 or 3.");
};
function makeGsubTable(gsub2) {
  return new table.Table("GSUB", [
    { name: "version", type: "ULONG", value: 65536 },
    { name: "scripts", type: "TABLE", value: new table.ScriptList(gsub2.scripts) },
    { name: "features", type: "TABLE", value: new table.FeatureList(gsub2.features) },
    { name: "lookups", type: "TABLE", value: new table.LookupList(gsub2.lookups, subtableMakers) }
  ]);
}
var gsub = { parse: parseGsubTable, make: makeGsubTable };
function parseMetaTable(data2, start) {
  var p = new parse.Parser(data2, start);
  var tableVersion = p.parseULong();
  check.argument(tableVersion === 1, "Unsupported META table version.");
  p.parseULong();
  p.parseULong();
  var numDataMaps = p.parseULong();
  var tags = {};
  for (var i = 0; i < numDataMaps; i++) {
    var tag = p.parseTag();
    var dataOffset = p.parseULong();
    var dataLength = p.parseULong();
    var text2 = decode.UTF8(data2, start + dataOffset, dataLength);
    tags[tag] = text2;
  }
  return tags;
}
function makeMetaTable(tags) {
  var numTags = Object.keys(tags).length;
  var stringPool = "";
  var stringPoolOffset = 16 + numTags * 12;
  var result = new table.Table("meta", [
    { name: "version", type: "ULONG", value: 1 },
    { name: "flags", type: "ULONG", value: 0 },
    { name: "offset", type: "ULONG", value: stringPoolOffset },
    { name: "numTags", type: "ULONG", value: numTags }
  ]);
  for (var tag in tags) {
    var pos = stringPool.length;
    stringPool += tags[tag];
    result.fields.push({ name: "tag " + tag, type: "TAG", value: tag });
    result.fields.push({ name: "offset " + tag, type: "ULONG", value: stringPoolOffset + pos });
    result.fields.push({ name: "length " + tag, type: "ULONG", value: tags[tag].length });
  }
  result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool });
  return result;
}
var meta = { parse: parseMetaTable, make: makeMetaTable };
function parseColrTable(data2, start) {
  var p = new Parser(data2, start);
  var version = p.parseUShort();
  check.argument(version === 0, "Only COLRv0 supported.");
  var numBaseGlyphRecords = p.parseUShort();
  var baseGlyphRecordsOffset = p.parseOffset32();
  var layerRecordsOffset = p.parseOffset32();
  var numLayerRecords = p.parseUShort();
  p.relativeOffset = baseGlyphRecordsOffset;
  var baseGlyphRecords = p.parseRecordList(numBaseGlyphRecords, {
    glyphID: Parser.uShort,
    firstLayerIndex: Parser.uShort,
    numLayers: Parser.uShort
  });
  p.relativeOffset = layerRecordsOffset;
  var layerRecords = p.parseRecordList(numLayerRecords, {
    glyphID: Parser.uShort,
    paletteIndex: Parser.uShort
  });
  return {
    version,
    baseGlyphRecords,
    layerRecords
  };
}
function makeColrTable(ref) {
  var version = ref.version;
  if (version === void 0) version = 0;
  var baseGlyphRecords = ref.baseGlyphRecords;
  if (baseGlyphRecords === void 0) baseGlyphRecords = [];
  var layerRecords = ref.layerRecords;
  if (layerRecords === void 0) layerRecords = [];
  check.argument(version === 0, "Only COLRv0 supported.");
  var baseGlyphRecordsOffset = 14;
  var layerRecordsOffset = baseGlyphRecordsOffset + baseGlyphRecords.length * 6;
  return new table.Table("COLR", [
    { name: "version", type: "USHORT", value: version },
    { name: "numBaseGlyphRecords", type: "USHORT", value: baseGlyphRecords.length },
    { name: "baseGlyphRecordsOffset", type: "ULONG", value: baseGlyphRecordsOffset },
    { name: "layerRecordsOffset", type: "ULONG", value: layerRecordsOffset },
    { name: "numLayerRecords", type: "USHORT", value: layerRecords.length }
  ].concat(
    baseGlyphRecords.map(function(glyph, i) {
      return [
        { name: "glyphID_" + i, type: "USHORT", value: glyph.glyphID },
        { name: "firstLayerIndex_" + i, type: "USHORT", value: glyph.firstLayerIndex },
        { name: "numLayers_" + i, type: "USHORT", value: glyph.numLayers }
      ];
    }).flat(),
    layerRecords.map(function(layer, i) {
      return [
        { name: "LayerGlyphID_" + i, type: "USHORT", value: layer.glyphID },
        { name: "paletteIndex_" + i, type: "USHORT", value: layer.paletteIndex }
      ];
    }).flat()
  ));
}
var colr = { parse: parseColrTable, make: makeColrTable };
function parseCpalTable(data2, start) {
  var p = new Parser(data2, start);
  var version = p.parseShort();
  var numPaletteEntries = p.parseShort();
  var numPalettes = p.parseShort();
  var numColorRecords = p.parseShort();
  var colorRecordsArrayOffset = p.parseOffset32();
  var colorRecordIndices = p.parseUShortList(numPalettes);
  p.relativeOffset = colorRecordsArrayOffset;
  var colorRecords = p.parseULongList(numColorRecords);
  return {
    version,
    numPaletteEntries,
    colorRecords,
    colorRecordIndices
  };
}
function makeCpalTable(ref) {
  var version = ref.version;
  if (version === void 0) version = 0;
  var numPaletteEntries = ref.numPaletteEntries;
  if (numPaletteEntries === void 0) numPaletteEntries = 0;
  var colorRecords = ref.colorRecords;
  if (colorRecords === void 0) colorRecords = [];
  var colorRecordIndices = ref.colorRecordIndices;
  if (colorRecordIndices === void 0) colorRecordIndices = [0];
  check.argument(version === 0, "Only CPALv0 are supported.");
  check.argument(colorRecords.length, "No colorRecords given.");
  check.argument(colorRecordIndices.length, "No colorRecordIndices given.");
  check.argument(!numPaletteEntries && colorRecordIndices.length == 1, "Can't infer numPaletteEntries on multiple colorRecordIndices");
  return new table.Table("CPAL", [
    { name: "version", type: "USHORT", value: version },
    { name: "numPaletteEntries", type: "USHORT", value: numPaletteEntries || colorRecords.length },
    { name: "numPalettes", type: "USHORT", value: colorRecordIndices.length },
    { name: "numColorRecords", type: "USHORT", value: colorRecords.length },
    { name: "colorRecordsArrayOffset", type: "ULONG", value: 12 + 2 * colorRecordIndices.length }
  ].concat(
    colorRecordIndices.map(function(palette, i) {
      return { name: "colorRecordIndices_" + i, type: "USHORT", value: palette };
    }),
    colorRecords.map(function(color, i) {
      return { name: "colorRecords_" + i, type: "ULONG", value: color };
    })
  ));
}
var cpal = { parse: parseCpalTable, make: makeCpalTable };
function log2(v) {
  return Math.log(v) / Math.log(2) | 0;
}
function computeCheckSum(bytes) {
  while (bytes.length % 4 !== 0) {
    bytes.push(0);
  }
  var sum2 = 0;
  for (var i = 0; i < bytes.length; i += 4) {
    sum2 += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3];
  }
  sum2 %= Math.pow(2, 32);
  return sum2;
}
function makeTableRecord(tag, checkSum, offset, length2) {
  return new table.Record("Table Record", [
    { name: "tag", type: "TAG", value: tag !== void 0 ? tag : "" },
    { name: "checkSum", type: "ULONG", value: checkSum !== void 0 ? checkSum : 0 },
    { name: "offset", type: "ULONG", value: offset !== void 0 ? offset : 0 },
    { name: "length", type: "ULONG", value: length2 !== void 0 ? length2 : 0 }
  ]);
}
function makeSfntTable(tables) {
  var sfnt2 = new table.Table("sfnt", [
    { name: "version", type: "TAG", value: "OTTO" },
    { name: "numTables", type: "USHORT", value: 0 },
    { name: "searchRange", type: "USHORT", value: 0 },
    { name: "entrySelector", type: "USHORT", value: 0 },
    { name: "rangeShift", type: "USHORT", value: 0 }
  ]);
  sfnt2.tables = tables;
  sfnt2.numTables = tables.length;
  var highestPowerOf2 = Math.pow(2, log2(sfnt2.numTables));
  sfnt2.searchRange = 16 * highestPowerOf2;
  sfnt2.entrySelector = log2(highestPowerOf2);
  sfnt2.rangeShift = sfnt2.numTables * 16 - sfnt2.searchRange;
  var recordFields = [];
  var tableFields = [];
  var offset = sfnt2.sizeOf() + makeTableRecord().sizeOf() * sfnt2.numTables;
  while (offset % 4 !== 0) {
    offset += 1;
    tableFields.push({ name: "padding", type: "BYTE", value: 0 });
  }
  for (var i = 0; i < tables.length; i += 1) {
    var t3 = tables[i];
    check.argument(t3.tableName.length === 4, "Table name" + t3.tableName + " is invalid.");
    var tableLength = t3.sizeOf();
    var tableRecord = makeTableRecord(t3.tableName, computeCheckSum(t3.encode()), offset, tableLength);
    recordFields.push({ name: tableRecord.tag + " Table Record", type: "RECORD", value: tableRecord });
    tableFields.push({ name: t3.tableName + " table", type: "RECORD", value: t3 });
    offset += tableLength;
    check.argument(!isNaN(offset), "Something went wrong calculating the offset.");
    while (offset % 4 !== 0) {
      offset += 1;
      tableFields.push({ name: "padding", type: "BYTE", value: 0 });
    }
  }
  recordFields.sort(function(r1, r2) {
    if (r1.value.tag > r2.value.tag) {
      return 1;
    } else {
      return -1;
    }
  });
  sfnt2.fields = sfnt2.fields.concat(recordFields);
  sfnt2.fields = sfnt2.fields.concat(tableFields);
  return sfnt2;
}
function metricsForChar(font, chars, notFoundMetrics) {
  for (var i = 0; i < chars.length; i += 1) {
    var glyphIndex = font.charToGlyphIndex(chars[i]);
    if (glyphIndex > 0) {
      var glyph = font.glyphs.get(glyphIndex);
      return glyph.getMetrics();
    }
  }
  return notFoundMetrics;
}
function average(vs) {
  var sum2 = 0;
  for (var i = 0; i < vs.length; i += 1) {
    sum2 += vs[i];
  }
  return sum2 / vs.length;
}
function fontToSfntTable(font) {
  var xMins = [];
  var yMins = [];
  var xMaxs = [];
  var yMaxs = [];
  var advanceWidths = [];
  var leftSideBearings = [];
  var rightSideBearings = [];
  var firstCharIndex;
  var lastCharIndex = 0;
  var ulUnicodeRange1 = 0;
  var ulUnicodeRange2 = 0;
  var ulUnicodeRange3 = 0;
  var ulUnicodeRange4 = 0;
  for (var i = 0; i < font.glyphs.length; i += 1) {
    var glyph = font.glyphs.get(i);
    var unicode = glyph.unicode | 0;
    if (isNaN(glyph.advanceWidth)) {
      throw new Error("Glyph " + glyph.name + " (" + i + "): advanceWidth is not a number.");
    }
    if (firstCharIndex > unicode || firstCharIndex === void 0) {
      if (unicode > 0) {
        firstCharIndex = unicode;
      }
    }
    if (lastCharIndex < unicode) {
      lastCharIndex = unicode;
    }
    var position2 = os2.getUnicodeRange(unicode);
    if (position2 < 32) {
      ulUnicodeRange1 |= 1 << position2;
    } else if (position2 < 64) {
      ulUnicodeRange2 |= 1 << position2 - 32;
    } else if (position2 < 96) {
      ulUnicodeRange3 |= 1 << position2 - 64;
    } else if (position2 < 123) {
      ulUnicodeRange4 |= 1 << position2 - 96;
    } else {
      throw new Error("Unicode ranges bits > 123 are reserved for internal usage");
    }
    if (glyph.name === ".notdef") {
      continue;
    }
    var metrics = glyph.getMetrics();
    xMins.push(metrics.xMin);
    yMins.push(metrics.yMin);
    xMaxs.push(metrics.xMax);
    yMaxs.push(metrics.yMax);
    leftSideBearings.push(metrics.leftSideBearing);
    rightSideBearings.push(metrics.rightSideBearing);
    advanceWidths.push(glyph.advanceWidth);
  }
  var globals = {
    xMin: Math.min.apply(null, xMins),
    yMin: Math.min.apply(null, yMins),
    xMax: Math.max.apply(null, xMaxs),
    yMax: Math.max.apply(null, yMaxs),
    advanceWidthMax: Math.max.apply(null, advanceWidths),
    advanceWidthAvg: average(advanceWidths),
    minLeftSideBearing: Math.min.apply(null, leftSideBearings),
    maxLeftSideBearing: Math.max.apply(null, leftSideBearings),
    minRightSideBearing: Math.min.apply(null, rightSideBearings)
  };
  globals.ascender = font.ascender;
  globals.descender = font.descender;
  var headTable = head.make({
    flags: 3,
    // 00000011 (baseline for font at y=0; left sidebearing point at x=0)
    unitsPerEm: font.unitsPerEm,
    xMin: globals.xMin,
    yMin: globals.yMin,
    xMax: globals.xMax,
    yMax: globals.yMax,
    lowestRecPPEM: 3,
    createdTimestamp: font.createdTimestamp
  });
  var hheaTable = hhea.make({
    ascender: globals.ascender,
    descender: globals.descender,
    advanceWidthMax: globals.advanceWidthMax,
    minLeftSideBearing: globals.minLeftSideBearing,
    minRightSideBearing: globals.minRightSideBearing,
    xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin),
    numberOfHMetrics: font.glyphs.length
  });
  var maxpTable = maxp.make(font.glyphs.length);
  var os2Table = os2.make(Object.assign({
    xAvgCharWidth: Math.round(globals.advanceWidthAvg),
    usFirstCharIndex: firstCharIndex,
    usLastCharIndex: lastCharIndex,
    ulUnicodeRange1,
    ulUnicodeRange2,
    ulUnicodeRange3,
    ulUnicodeRange4,
    // See http://typophile.com/node/13081 for more info on vertical metrics.
    // We get metrics for typical characters (such as "x" for xHeight).
    // We provide some fallback characters if characters are unavailable: their
    // ordering was chosen experimentally.
    sTypoAscender: globals.ascender,
    sTypoDescender: globals.descender,
    sTypoLineGap: 0,
    usWinAscent: globals.yMax,
    usWinDescent: Math.abs(globals.yMin),
    ulCodePageRange1: 1,
    // FIXME: hard-code Latin 1 support for now
    sxHeight: metricsForChar(font, "xyvw", { yMax: Math.round(globals.ascender / 2) }).yMax,
    sCapHeight: metricsForChar(font, "HIKLEFJMNTZBDPRAGOQSUVWXY", globals).yMax,
    usDefaultChar: font.hasChar(" ") ? 32 : 0,
    // Use space as the default character, if available.
    usBreakChar: font.hasChar(" ") ? 32 : 0
    // Use space as the break character, if available.
  }, font.tables.os2));
  var hmtxTable = hmtx.make(font.glyphs);
  var cmapTable = cmap.make(font.glyphs);
  var englishFamilyName = font.getEnglishName("fontFamily");
  var englishStyleName = font.getEnglishName("fontSubfamily");
  var englishFullName = englishFamilyName + " " + englishStyleName;
  var postScriptName = font.getEnglishName("postScriptName");
  if (!postScriptName) {
    postScriptName = englishFamilyName.replace(/\s/g, "") + "-" + englishStyleName;
  }
  var names = {};
  for (var n2 in font.names) {
    names[n2] = font.names[n2];
  }
  if (!names.uniqueID) {
    names.uniqueID = { en: font.getEnglishName("manufacturer") + ":" + englishFullName };
  }
  if (!names.postScriptName) {
    names.postScriptName = { en: postScriptName };
  }
  if (!names.preferredFamily) {
    names.preferredFamily = font.names.fontFamily;
  }
  if (!names.preferredSubfamily) {
    names.preferredSubfamily = font.names.fontSubfamily;
  }
  var languageTags = [];
  var nameTable = _name.make(names, languageTags);
  var ltagTable = languageTags.length > 0 ? ltag.make(languageTags) : void 0;
  var postTable = post.make();
  var cffTable = cff.make(font.glyphs, {
    version: font.getEnglishName("version"),
    fullName: englishFullName,
    familyName: englishFamilyName,
    weightName: englishStyleName,
    postScriptName,
    unitsPerEm: font.unitsPerEm,
    fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax]
  });
  var metaTable = font.metas && Object.keys(font.metas).length > 0 ? meta.make(font.metas) : void 0;
  var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable];
  if (ltagTable) {
    tables.push(ltagTable);
  }
  if (font.tables.gsub) {
    tables.push(gsub.make(font.tables.gsub));
  }
  if (font.tables.cpal) {
    tables.push(cpal.make(font.tables.cpal));
  }
  if (font.tables.colr) {
    tables.push(colr.make(font.tables.colr));
  }
  if (metaTable) {
    tables.push(metaTable);
  }
  var sfntTable = makeSfntTable(tables);
  var bytes = sfntTable.encode();
  var checkSum = computeCheckSum(bytes);
  var tableFields = sfntTable.fields;
  var checkSumAdjusted = false;
  for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) {
    if (tableFields[i$1].name === "head table") {
      tableFields[i$1].value.checkSumAdjustment = 2981146554 - checkSum;
      checkSumAdjusted = true;
      break;
    }
  }
  if (!checkSumAdjusted) {
    throw new Error("Could not find head table with checkSum to adjust.");
  }
  return sfntTable;
}
var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum };
function searchTag(arr, tag) {
  var imin = 0;
  var imax = arr.length - 1;
  while (imin <= imax) {
    var imid = imin + imax >>> 1;
    var val2 = arr[imid].tag;
    if (val2 === tag) {
      return imid;
    } else if (val2 < tag) {
      imin = imid + 1;
    } else {
      imax = imid - 1;
    }
  }
  return -imin - 1;
}
function binSearch(arr, value2) {
  var imin = 0;
  var imax = arr.length - 1;
  while (imin <= imax) {
    var imid = imin + imax >>> 1;
    var val2 = arr[imid];
    if (val2 === value2) {
      return imid;
    } else if (val2 < value2) {
      imin = imid + 1;
    } else {
      imax = imid - 1;
    }
  }
  return -imin - 1;
}
function searchRange(ranges, value2) {
  var range;
  var imin = 0;
  var imax = ranges.length - 1;
  while (imin <= imax) {
    var imid = imin + imax >>> 1;
    range = ranges[imid];
    var start = range.start;
    if (start === value2) {
      return range;
    } else if (start < value2) {
      imin = imid + 1;
    } else {
      imax = imid - 1;
    }
  }
  if (imin > 0) {
    range = ranges[imin - 1];
    if (value2 > range.end) {
      return 0;
    }
    return range;
  }
}
function Layout(font, tableName) {
  this.font = font;
  this.tableName = tableName;
}
Layout.prototype = {
  /**
   * Binary search an object by "tag" property
   * @instance
   * @function searchTag
   * @memberof opentype.Layout
   * @param  {Array} arr
   * @param  {string} tag
   * @return {number}
   */
  searchTag,
  /**
   * Binary search in a list of numbers
   * @instance
   * @function binSearch
   * @memberof opentype.Layout
   * @param  {Array} arr
   * @param  {number} value
   * @return {number}
   */
  binSearch,
  /**
   * Get or create the Layout table (GSUB, GPOS etc).
   * @param  {boolean} create - Whether to create a new one.
   * @return {Object} The GSUB or GPOS table.
   */
  getTable: function(create) {
    var layout = this.font.tables[this.tableName];
    if (!layout && create) {
      layout = this.font.tables[this.tableName] = this.createDefaultTable();
    }
    return layout;
  },
  /**
   * Returns all scripts in the substitution table.
   * @instance
   * @return {Array}
   */
  getScriptNames: function() {
    var layout = this.getTable();
    if (!layout) {
      return [];
    }
    return layout.scripts.map(function(script) {
      return script.tag;
    });
  },
  /**
   * Returns the best bet for a script name.
   * Returns 'DFLT' if it exists.
   * If not, returns 'latn' if it exists.
   * If neither exist, returns undefined.
   */
  getDefaultScriptName: function() {
    var layout = this.getTable();
    if (!layout) {
      return;
    }
    var hasLatn = false;
    for (var i = 0; i < layout.scripts.length; i++) {
      var name2 = layout.scripts[i].tag;
      if (name2 === "DFLT") {
        return name2;
      }
      if (name2 === "latn") {
        hasLatn = true;
      }
    }
    if (hasLatn) {
      return "latn";
    }
  },
  /**
   * Returns all LangSysRecords in the given script.
   * @instance
   * @param {string} [script='DFLT']
   * @param {boolean} create - forces the creation of this script table if it doesn't exist.
   * @return {Object} An object with tag and script properties.
   */
  getScriptTable: function(script, create) {
    var layout = this.getTable(create);
    if (layout) {
      script = script || "DFLT";
      var scripts = layout.scripts;
      var pos = searchTag(layout.scripts, script);
      if (pos >= 0) {
        return scripts[pos].script;
      } else if (create) {
        var scr = {
          tag: script,
          script: {
            defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] },
            langSysRecords: []
          }
        };
        scripts.splice(-1 - pos, 0, scr);
        return scr.script;
      }
    }
  },
  /**
   * Returns a language system table
   * @instance
   * @param {string} [script='DFLT']
   * @param {string} [language='dlft']
   * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist.
   * @return {Object}
   */
  getLangSysTable: function(script, language, create) {
    var scriptTable = this.getScriptTable(script, create);
    if (scriptTable) {
      if (!language || language === "dflt" || language === "DFLT") {
        return scriptTable.defaultLangSys;
      }
      var pos = searchTag(scriptTable.langSysRecords, language);
      if (pos >= 0) {
        return scriptTable.langSysRecords[pos].langSys;
      } else if (create) {
        var langSysRecord = {
          tag: language,
          langSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }
        };
        scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord);
        return langSysRecord.langSys;
      }
    }
  },
  /**
   * Get a specific feature table.
   * @instance
   * @param {string} [script='DFLT']
   * @param {string} [language='dlft']
   * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm
   * @param {boolean} create - forces the creation of the feature table if it doesn't exist.
   * @return {Object}
   */
  getFeatureTable: function(script, language, feature, create) {
    var langSysTable2 = this.getLangSysTable(script, language, create);
    if (langSysTable2) {
      var featureRecord;
      var featIndexes = langSysTable2.featureIndexes;
      var allFeatures = this.font.tables[this.tableName].features;
      for (var i = 0; i < featIndexes.length; i++) {
        featureRecord = allFeatures[featIndexes[i]];
        if (featureRecord.tag === feature) {
          return featureRecord.feature;
        }
      }
      if (create) {
        var index2 = allFeatures.length;
        check.assert(index2 === 0 || feature >= allFeatures[index2 - 1].tag, "Features must be added in alphabetical order.");
        featureRecord = {
          tag: feature,
          feature: { params: 0, lookupListIndexes: [] }
        };
        allFeatures.push(featureRecord);
        featIndexes.push(index2);
        return featureRecord.feature;
      }
    }
  },
  /**
   * Get the lookup tables of a given type for a script/language/feature.
   * @instance
   * @param {string} [script='DFLT']
   * @param {string} [language='dlft']
   * @param {string} feature - 4-letter feature code
   * @param {number} lookupType - 1 to 9
   * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables.
   * @return {Object[]}
   */
  getLookupTables: function(script, language, feature, lookupType, create) {
    var featureTable = this.getFeatureTable(script, language, feature, create);
    var tables = [];
    if (featureTable) {
      var lookupTable;
      var lookupListIndexes = featureTable.lookupListIndexes;
      var allLookups = this.font.tables[this.tableName].lookups;
      for (var i = 0; i < lookupListIndexes.length; i++) {
        lookupTable = allLookups[lookupListIndexes[i]];
        if (lookupTable.lookupType === lookupType) {
          tables.push(lookupTable);
        }
      }
      if (tables.length === 0 && create) {
        lookupTable = {
          lookupType,
          lookupFlag: 0,
          subtables: [],
          markFilteringSet: void 0
        };
        var index2 = allLookups.length;
        allLookups.push(lookupTable);
        lookupListIndexes.push(index2);
        return [lookupTable];
      }
    }
    return tables;
  },
  /**
   * Find a glyph in a class definition table
   * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table
   * @param {object} classDefTable - an OpenType Layout class definition table
   * @param {number} glyphIndex - the index of the glyph to find
   * @returns {number} -1 if not found
   */
  getGlyphClass: function(classDefTable, glyphIndex) {
    switch (classDefTable.format) {
      case 1:
        if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) {
          return classDefTable.classes[glyphIndex - classDefTable.startGlyph];
        }
        return 0;
      case 2:
        var range = searchRange(classDefTable.ranges, glyphIndex);
        return range ? range.classId : 0;
    }
  },
  /**
   * Find a glyph in a coverage table
   * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-table
   * @param {object} coverageTable - an OpenType Layout coverage table
   * @param {number} glyphIndex - the index of the glyph to find
   * @returns {number} -1 if not found
   */
  getCoverageIndex: function(coverageTable, glyphIndex) {
    switch (coverageTable.format) {
      case 1:
        var index2 = binSearch(coverageTable.glyphs, glyphIndex);
        return index2 >= 0 ? index2 : -1;
      case 2:
        var range = searchRange(coverageTable.ranges, glyphIndex);
        return range ? range.index + glyphIndex - range.start : -1;
    }
  },
  /**
   * Returns the list of glyph indexes of a coverage table.
   * Format 1: the list is stored raw
   * Format 2: compact list as range records.
   * @instance
   * @param  {Object} coverageTable
   * @return {Array}
   */
  expandCoverage: function(coverageTable) {
    if (coverageTable.format === 1) {
      return coverageTable.glyphs;
    } else {
      var glyphs = [];
      var ranges = coverageTable.ranges;
      for (var i = 0; i < ranges.length; i++) {
        var range = ranges[i];
        var start = range.start;
        var end = range.end;
        for (var j2 = start; j2 <= end; j2++) {
          glyphs.push(j2);
        }
      }
      return glyphs;
    }
  }
};
function Position(font) {
  Layout.call(this, font, "gpos");
}
Position.prototype = Layout.prototype;
Position.prototype.init = function() {
  var script = this.getDefaultScriptName();
  this.defaultKerningTables = this.getKerningTables(script);
};
Position.prototype.getKerningValue = function(kerningLookups, leftIndex, rightIndex) {
  for (var i = 0; i < kerningLookups.length; i++) {
    var subtables = kerningLookups[i].subtables;
    for (var j2 = 0; j2 < subtables.length; j2++) {
      var subtable = subtables[j2];
      var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex);
      if (covIndex < 0) {
        continue;
      }
      switch (subtable.posFormat) {
        case 1:
          var pairSet = subtable.pairSets[covIndex];
          for (var k2 = 0; k2 < pairSet.length; k2++) {
            var pair = pairSet[k2];
            if (pair.secondGlyph === rightIndex) {
              return pair.value1 && pair.value1.xAdvance || 0;
            }
          }
          break;
        // left glyph found, not right glyph - try next subtable
        case 2:
          var class1 = this.getGlyphClass(subtable.classDef1, leftIndex);
          var class2 = this.getGlyphClass(subtable.classDef2, rightIndex);
          var pair$1 = subtable.classRecords[class1][class2];
          return pair$1.value1 && pair$1.value1.xAdvance || 0;
      }
    }
  }
  return 0;
};
Position.prototype.getKerningTables = function(script, language) {
  if (this.font.tables.gpos) {
    return this.getLookupTables(script, language, "kern", 2);
  }
};
function Substitution(font) {
  Layout.call(this, font, "gsub");
}
function arraysEqual(ar1, ar2) {
  var n2 = ar1.length;
  if (n2 !== ar2.length) {
    return false;
  }
  for (var i = 0; i < n2; i++) {
    if (ar1[i] !== ar2[i]) {
      return false;
    }
  }
  return true;
}
function getSubstFormat(lookupTable, format, defaultSubtable) {
  var subtables = lookupTable.subtables;
  for (var i = 0; i < subtables.length; i++) {
    var subtable = subtables[i];
    if (subtable.substFormat === format) {
      return subtable;
    }
  }
  if (defaultSubtable) {
    subtables.push(defaultSubtable);
    return defaultSubtable;
  }
  return void 0;
}
Substitution.prototype = Layout.prototype;
Substitution.prototype.createDefaultTable = function() {
  return {
    version: 1,
    scripts: [{
      tag: "DFLT",
      script: {
        defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] },
        langSysRecords: []
      }
    }],
    features: [],
    lookups: []
  };
};
Substitution.prototype.getSingle = function(feature, script, language) {
  var substitutions = [];
  var lookupTables = this.getLookupTables(script, language, feature, 1);
  for (var idx = 0; idx < lookupTables.length; idx++) {
    var subtables = lookupTables[idx].subtables;
    for (var i = 0; i < subtables.length; i++) {
      var subtable = subtables[i];
      var glyphs = this.expandCoverage(subtable.coverage);
      var j2 = void 0;
      if (subtable.substFormat === 1) {
        var delta = subtable.deltaGlyphId;
        for (j2 = 0; j2 < glyphs.length; j2++) {
          var glyph = glyphs[j2];
          substitutions.push({ sub: glyph, by: glyph + delta });
        }
      } else {
        var substitute = subtable.substitute;
        for (j2 = 0; j2 < glyphs.length; j2++) {
          substitutions.push({ sub: glyphs[j2], by: substitute[j2] });
        }
      }
    }
  }
  return substitutions;
};
Substitution.prototype.getMultiple = function(feature, script, language) {
  var substitutions = [];
  var lookupTables = this.getLookupTables(script, language, feature, 2);
  for (var idx = 0; idx < lookupTables.length; idx++) {
    var subtables = lookupTables[idx].subtables;
    for (var i = 0; i < subtables.length; i++) {
      var subtable = subtables[i];
      var glyphs = this.expandCoverage(subtable.coverage);
      var j2 = void 0;
      for (j2 = 0; j2 < glyphs.length; j2++) {
        var glyph = glyphs[j2];
        var replacements = subtable.sequences[j2];
        substitutions.push({ sub: glyph, by: replacements });
      }
    }
  }
  return substitutions;
};
Substitution.prototype.getAlternates = function(feature, script, language) {
  var alternates = [];
  var lookupTables = this.getLookupTables(script, language, feature, 3);
  for (var idx = 0; idx < lookupTables.length; idx++) {
    var subtables = lookupTables[idx].subtables;
    for (var i = 0; i < subtables.length; i++) {
      var subtable = subtables[i];
      var glyphs = this.expandCoverage(subtable.coverage);
      var alternateSets = subtable.alternateSets;
      for (var j2 = 0; j2 < glyphs.length; j2++) {
        alternates.push({ sub: glyphs[j2], by: alternateSets[j2] });
      }
    }
  }
  return alternates;
};
Substitution.prototype.getLigatures = function(feature, script, language) {
  var ligatures = [];
  var lookupTables = this.getLookupTables(script, language, feature, 4);
  for (var idx = 0; idx < lookupTables.length; idx++) {
    var subtables = lookupTables[idx].subtables;
    for (var i = 0; i < subtables.length; i++) {
      var subtable = subtables[i];
      var glyphs = this.expandCoverage(subtable.coverage);
      var ligatureSets = subtable.ligatureSets;
      for (var j2 = 0; j2 < glyphs.length; j2++) {
        var startGlyph = glyphs[j2];
        var ligSet = ligatureSets[j2];
        for (var k2 = 0; k2 < ligSet.length; k2++) {
          var lig = ligSet[k2];
          ligatures.push({
            sub: [startGlyph].concat(lig.components),
            by: lig.ligGlyph
          });
        }
      }
    }
  }
  return ligatures;
};
Substitution.prototype.addSingle = function(feature, substitution, script, language) {
  var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0];
  var subtable = getSubstFormat(lookupTable, 2, {
    // lookup type 1 subtable, format 2, coverage format 1
    substFormat: 2,
    coverage: { format: 1, glyphs: [] },
    substitute: []
  });
  check.assert(subtable.coverage.format === 1, "Single: unable to modify coverage table format " + subtable.coverage.format);
  var coverageGlyph = substitution.sub;
  var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
  if (pos < 0) {
    pos = -1 - pos;
    subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
    subtable.substitute.splice(pos, 0, 0);
  }
  subtable.substitute[pos] = substitution.by;
};
Substitution.prototype.addMultiple = function(feature, substitution, script, language) {
  check.assert(substitution.by instanceof Array && substitution.by.length > 1, 'Multiple: "by" must be an array of two or more ids');
  var lookupTable = this.getLookupTables(script, language, feature, 2, true)[0];
  var subtable = getSubstFormat(lookupTable, 1, {
    // lookup type 2 subtable, format 1, coverage format 1
    substFormat: 1,
    coverage: { format: 1, glyphs: [] },
    sequences: []
  });
  check.assert(subtable.coverage.format === 1, "Multiple: unable to modify coverage table format " + subtable.coverage.format);
  var coverageGlyph = substitution.sub;
  var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
  if (pos < 0) {
    pos = -1 - pos;
    subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
    subtable.sequences.splice(pos, 0, 0);
  }
  subtable.sequences[pos] = substitution.by;
};
Substitution.prototype.addAlternate = function(feature, substitution, script, language) {
  var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0];
  var subtable = getSubstFormat(lookupTable, 1, {
    // lookup type 3 subtable, format 1, coverage format 1
    substFormat: 1,
    coverage: { format: 1, glyphs: [] },
    alternateSets: []
  });
  check.assert(subtable.coverage.format === 1, "Alternate: unable to modify coverage table format " + subtable.coverage.format);
  var coverageGlyph = substitution.sub;
  var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
  if (pos < 0) {
    pos = -1 - pos;
    subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
    subtable.alternateSets.splice(pos, 0, 0);
  }
  subtable.alternateSets[pos] = substitution.by;
};
Substitution.prototype.addLigature = function(feature, ligature, script, language) {
  var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0];
  var subtable = lookupTable.subtables[0];
  if (!subtable) {
    subtable = {
      // lookup type 4 subtable, format 1, coverage format 1
      substFormat: 1,
      coverage: { format: 1, glyphs: [] },
      ligatureSets: []
    };
    lookupTable.subtables[0] = subtable;
  }
  check.assert(subtable.coverage.format === 1, "Ligature: unable to modify coverage table format " + subtable.coverage.format);
  var coverageGlyph = ligature.sub[0];
  var ligComponents = ligature.sub.slice(1);
  var ligatureTable = {
    ligGlyph: ligature.by,
    components: ligComponents
  };
  var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
  if (pos >= 0) {
    var ligatureSet = subtable.ligatureSets[pos];
    for (var i = 0; i < ligatureSet.length; i++) {
      if (arraysEqual(ligatureSet[i].components, ligComponents)) {
        return;
      }
    }
    ligatureSet.push(ligatureTable);
  } else {
    pos = -1 - pos;
    subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
    subtable.ligatureSets.splice(pos, 0, [ligatureTable]);
  }
};
Substitution.prototype.getFeature = function(feature, script, language) {
  if (/ss\d\d/.test(feature)) {
    return this.getSingle(feature, script, language);
  }
  switch (feature) {
    case "aalt":
    case "salt":
      return this.getSingle(feature, script, language).concat(this.getAlternates(feature, script, language));
    case "dlig":
    case "liga":
    case "rlig":
      return this.getLigatures(feature, script, language);
    case "ccmp":
      return this.getMultiple(feature, script, language).concat(this.getLigatures(feature, script, language));
    case "stch":
      return this.getMultiple(feature, script, language);
  }
  return void 0;
};
Substitution.prototype.add = function(feature, sub2, script, language) {
  if (/ss\d\d/.test(feature)) {
    return this.addSingle(feature, sub2, script, language);
  }
  switch (feature) {
    case "aalt":
    case "salt":
      if (typeof sub2.by === "number") {
        return this.addSingle(feature, sub2, script, language);
      }
      return this.addAlternate(feature, sub2, script, language);
    case "dlig":
    case "liga":
    case "rlig":
      return this.addLigature(feature, sub2, script, language);
    case "ccmp":
      if (sub2.by instanceof Array) {
        return this.addMultiple(feature, sub2, script, language);
      }
      return this.addLigature(feature, sub2, script, language);
  }
  return void 0;
};
function checkArgument(expression, message) {
  if (!expression) {
    throw message;
  }
}
function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) {
  var v;
  if ((flag & shortVectorBitMask) > 0) {
    v = p.parseByte();
    if ((flag & sameBitMask) === 0) {
      v = -v;
    }
    v = previousValue + v;
  } else {
    if ((flag & sameBitMask) > 0) {
      v = previousValue;
    } else {
      v = previousValue + p.parseShort();
    }
  }
  return v;
}
function parseGlyph(glyph, data2, start) {
  var p = new parse.Parser(data2, start);
  glyph.numberOfContours = p.parseShort();
  glyph._xMin = p.parseShort();
  glyph._yMin = p.parseShort();
  glyph._xMax = p.parseShort();
  glyph._yMax = p.parseShort();
  var flags;
  var flag;
  if (glyph.numberOfContours > 0) {
    var endPointIndices = glyph.endPointIndices = [];
    for (var i = 0; i < glyph.numberOfContours; i += 1) {
      endPointIndices.push(p.parseUShort());
    }
    glyph.instructionLength = p.parseUShort();
    glyph.instructions = [];
    for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) {
      glyph.instructions.push(p.parseByte());
    }
    var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1;
    flags = [];
    for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) {
      flag = p.parseByte();
      flags.push(flag);
      if ((flag & 8) > 0) {
        var repeatCount = p.parseByte();
        for (var j2 = 0; j2 < repeatCount; j2 += 1) {
          flags.push(flag);
          i$2 += 1;
        }
      }
    }
    check.argument(flags.length === numberOfCoordinates, "Bad flags.");
    if (endPointIndices.length > 0) {
      var points = [];
      var point;
      if (numberOfCoordinates > 0) {
        for (var i$3 = 0; i$3 < numberOfCoordinates; i$3 += 1) {
          flag = flags[i$3];
          point = {};
          point.onCurve = !!(flag & 1);
          point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0;
          points.push(point);
        }
        var px = 0;
        for (var i$4 = 0; i$4 < numberOfCoordinates; i$4 += 1) {
          flag = flags[i$4];
          point = points[i$4];
          point.x = parseGlyphCoordinate(p, flag, px, 2, 16);
          px = point.x;
        }
        var py = 0;
        for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) {
          flag = flags[i$5];
          point = points[i$5];
          point.y = parseGlyphCoordinate(p, flag, py, 4, 32);
          py = point.y;
        }
      }
      glyph.points = points;
    } else {
      glyph.points = [];
    }
  } else if (glyph.numberOfContours === 0) {
    glyph.points = [];
  } else {
    glyph.isComposite = true;
    glyph.points = [];
    glyph.components = [];
    var moreComponents = true;
    while (moreComponents) {
      flags = p.parseUShort();
      var component = {
        glyphIndex: p.parseUShort(),
        xScale: 1,
        scale01: 0,
        scale10: 0,
        yScale: 1,
        dx: 0,
        dy: 0
      };
      if ((flags & 1) > 0) {
        if ((flags & 2) > 0) {
          component.dx = p.parseShort();
          component.dy = p.parseShort();
        } else {
          component.matchedPoints = [p.parseUShort(), p.parseUShort()];
        }
      } else {
        if ((flags & 2) > 0) {
          component.dx = p.parseChar();
          component.dy = p.parseChar();
        } else {
          component.matchedPoints = [p.parseByte(), p.parseByte()];
        }
      }
      if ((flags & 8) > 0) {
        component.xScale = component.yScale = p.parseF2Dot14();
      } else if ((flags & 64) > 0) {
        component.xScale = p.parseF2Dot14();
        component.yScale = p.parseF2Dot14();
      } else if ((flags & 128) > 0) {
        component.xScale = p.parseF2Dot14();
        component.scale01 = p.parseF2Dot14();
        component.scale10 = p.parseF2Dot14();
        component.yScale = p.parseF2Dot14();
      }
      glyph.components.push(component);
      moreComponents = !!(flags & 32);
    }
    if (flags & 256) {
      glyph.instructionLength = p.parseUShort();
      glyph.instructions = [];
      for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) {
        glyph.instructions.push(p.parseByte());
      }
    }
  }
}
function transformPoints(points, transform2) {
  var newPoints = [];
  for (var i = 0; i < points.length; i += 1) {
    var pt = points[i];
    var newPt = {
      x: transform2.xScale * pt.x + transform2.scale01 * pt.y + transform2.dx,
      y: transform2.scale10 * pt.x + transform2.yScale * pt.y + transform2.dy,
      onCurve: pt.onCurve,
      lastPointOfContour: pt.lastPointOfContour
    };
    newPoints.push(newPt);
  }
  return newPoints;
}
function getContours(points) {
  var contours = [];
  var currentContour = [];
  for (var i = 0; i < points.length; i += 1) {
    var pt = points[i];
    currentContour.push(pt);
    if (pt.lastPointOfContour) {
      contours.push(currentContour);
      currentContour = [];
    }
  }
  check.argument(currentContour.length === 0, "There are still points left in the current contour.");
  return contours;
}
function getPath(points) {
  var p = new Path2();
  if (!points) {
    return p;
  }
  var contours = getContours(points);
  for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) {
    var contour = contours[contourIndex];
    var prev = null;
    var curr = contour[contour.length - 1];
    var next = contour[0];
    if (curr.onCurve) {
      p.moveTo(curr.x, curr.y);
    } else {
      if (next.onCurve) {
        p.moveTo(next.x, next.y);
      } else {
        var start = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 };
        p.moveTo(start.x, start.y);
      }
    }
    for (var i = 0; i < contour.length; ++i) {
      prev = curr;
      curr = next;
      next = contour[(i + 1) % contour.length];
      if (curr.onCurve) {
        p.lineTo(curr.x, curr.y);
      } else {
        var prev2 = prev;
        var next2 = next;
        if (!prev.onCurve) {
          prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 };
        }
        if (!next.onCurve) {
          next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 };
        }
        p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y);
      }
    }
    p.closePath();
  }
  return p;
}
function buildPath(glyphs, glyph) {
  if (glyph.isComposite) {
    for (var j2 = 0; j2 < glyph.components.length; j2 += 1) {
      var component = glyph.components[j2];
      var componentGlyph = glyphs.get(component.glyphIndex);
      componentGlyph.getPath();
      if (componentGlyph.points) {
        var transformedPoints = void 0;
        if (component.matchedPoints === void 0) {
          transformedPoints = transformPoints(componentGlyph.points, component);
        } else {
          if (component.matchedPoints[0] > glyph.points.length - 1 || component.matchedPoints[1] > componentGlyph.points.length - 1) {
            throw Error("Matched points out of range in " + glyph.name);
          }
          var firstPt = glyph.points[component.matchedPoints[0]];
          var secondPt = componentGlyph.points[component.matchedPoints[1]];
          var transform2 = {
            xScale: component.xScale,
            scale01: component.scale01,
            scale10: component.scale10,
            yScale: component.yScale,
            dx: 0,
            dy: 0
          };
          secondPt = transformPoints([secondPt], transform2)[0];
          transform2.dx = firstPt.x - secondPt.x;
          transform2.dy = firstPt.y - secondPt.y;
          transformedPoints = transformPoints(componentGlyph.points, transform2);
        }
        glyph.points = glyph.points.concat(transformedPoints);
      }
    }
  }
  return getPath(glyph.points);
}
function parseGlyfTableAll(data2, start, loca2, font) {
  var glyphs = new glyphset.GlyphSet(font);
  for (var i = 0; i < loca2.length - 1; i += 1) {
    var offset = loca2[i];
    var nextOffset = loca2[i + 1];
    if (offset !== nextOffset) {
      glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data2, start + offset, buildPath));
    } else {
      glyphs.push(i, glyphset.glyphLoader(font, i));
    }
  }
  return glyphs;
}
function parseGlyfTableOnLowMemory(data2, start, loca2, font) {
  var glyphs = new glyphset.GlyphSet(font);
  font._push = function(i) {
    var offset = loca2[i];
    var nextOffset = loca2[i + 1];
    if (offset !== nextOffset) {
      glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data2, start + offset, buildPath));
    } else {
      glyphs.push(i, glyphset.glyphLoader(font, i));
    }
  };
  return glyphs;
}
function parseGlyfTable(data2, start, loca2, font, opt) {
  if (opt.lowMemory) {
    return parseGlyfTableOnLowMemory(data2, start, loca2, font);
  } else {
    return parseGlyfTableAll(data2, start, loca2, font);
  }
}
var glyf = { getPath, parse: parseGlyfTable };
var instructionTable;
var exec;
var execGlyph;
var execComponent;
function Hinting(font) {
  this.font = font;
  this.getCommands = function(hPoints) {
    return glyf.getPath(hPoints).commands;
  };
  this._fpgmState = this._prepState = void 0;
  this._errorState = 0;
}
function roundOff(v) {
  return v;
}
function roundToGrid(v) {
  return Math.sign(v) * Math.round(Math.abs(v));
}
function roundToDoubleGrid(v) {
  return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2;
}
function roundToHalfGrid(v) {
  return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5);
}
function roundUpToGrid(v) {
  return Math.sign(v) * Math.ceil(Math.abs(v));
}
function roundDownToGrid(v) {
  return Math.sign(v) * Math.floor(Math.abs(v));
}
var roundSuper = function(v) {
  var period = this.srPeriod;
  var phase = this.srPhase;
  var threshold = this.srThreshold;
  var sign = 1;
  if (v < 0) {
    v = -v;
    sign = -1;
  }
  v += threshold - phase;
  v = Math.trunc(v / period) * period;
  v += phase;
  if (v < 0) {
    return phase * sign;
  }
  return v * sign;
};
var xUnitVector = {
  x: 1,
  y: 0,
  axis: "x",
  // Gets the projected distance between two points.
  // o1/o2 ... if true, respective original position is used.
  distance: function(p1, p2, o1, o2) {
    return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x);
  },
  // Moves point p so the moved position has the same relative
  // position to the moved positions of rp1 and rp2 than the
  // original positions had.
  //
  // See APPENDIX on INTERPOLATE at the bottom of this file.
  interpolate: function(p, rp1, rp2, pv) {
    var do1;
    var do2;
    var doa1;
    var doa2;
    var dm1;
    var dm2;
    var dt;
    if (!pv || pv === this) {
      do1 = p.xo - rp1.xo;
      do2 = p.xo - rp2.xo;
      dm1 = rp1.x - rp1.xo;
      dm2 = rp2.x - rp2.xo;
      doa1 = Math.abs(do1);
      doa2 = Math.abs(do2);
      dt = doa1 + doa2;
      if (dt === 0) {
        p.x = p.xo + (dm1 + dm2) / 2;
        return;
      }
      p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt;
      return;
    }
    do1 = pv.distance(p, rp1, true, true);
    do2 = pv.distance(p, rp2, true, true);
    dm1 = pv.distance(rp1, rp1, false, true);
    dm2 = pv.distance(rp2, rp2, false, true);
    doa1 = Math.abs(do1);
    doa2 = Math.abs(do2);
    dt = doa1 + doa2;
    if (dt === 0) {
      xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
      return;
    }
    xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
  },
  // Slope of line normal to this
  normalSlope: Number.NEGATIVE_INFINITY,
  // Sets the point 'p' relative to point 'rp'
  // by the distance 'd'.
  //
  // See APPENDIX on SETRELATIVE at the bottom of this file.
  //
  // p   ... point to set
  // rp  ... reference point
  // d   ... distance on projection vector
  // pv  ... projection vector (undefined = this)
  // org ... if true, uses the original position of rp as reference.
  setRelative: function(p, rp, d, pv, org) {
    if (!pv || pv === this) {
      p.x = (org ? rp.xo : rp.x) + d;
      return;
    }
    var rpx = org ? rp.xo : rp.x;
    var rpy = org ? rp.yo : rp.y;
    var rpdx = rpx + d * pv.x;
    var rpdy = rpy + d * pv.y;
    p.x = rpdx + (p.y - rpdy) / pv.normalSlope;
  },
  // Slope of vector line.
  slope: 0,
  // Touches the point p.
  touch: function(p) {
    p.xTouched = true;
  },
  // Tests if a point p is touched.
  touched: function(p) {
    return p.xTouched;
  },
  // Untouches the point p.
  untouch: function(p) {
    p.xTouched = false;
  }
};
var yUnitVector = {
  x: 0,
  y: 1,
  axis: "y",
  // Gets the projected distance between two points.
  // o1/o2 ... if true, respective original position is used.
  distance: function(p1, p2, o1, o2) {
    return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y);
  },
  // Moves point p so the moved position has the same relative
  // position to the moved positions of rp1 and rp2 than the
  // original positions had.
  //
  // See APPENDIX on INTERPOLATE at the bottom of this file.
  interpolate: function(p, rp1, rp2, pv) {
    var do1;
    var do2;
    var doa1;
    var doa2;
    var dm1;
    var dm2;
    var dt;
    if (!pv || pv === this) {
      do1 = p.yo - rp1.yo;
      do2 = p.yo - rp2.yo;
      dm1 = rp1.y - rp1.yo;
      dm2 = rp2.y - rp2.yo;
      doa1 = Math.abs(do1);
      doa2 = Math.abs(do2);
      dt = doa1 + doa2;
      if (dt === 0) {
        p.y = p.yo + (dm1 + dm2) / 2;
        return;
      }
      p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt;
      return;
    }
    do1 = pv.distance(p, rp1, true, true);
    do2 = pv.distance(p, rp2, true, true);
    dm1 = pv.distance(rp1, rp1, false, true);
    dm2 = pv.distance(rp2, rp2, false, true);
    doa1 = Math.abs(do1);
    doa2 = Math.abs(do2);
    dt = doa1 + doa2;
    if (dt === 0) {
      yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
      return;
    }
    yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
  },
  // Slope of line normal to this.
  normalSlope: 0,
  // Sets the point 'p' relative to point 'rp'
  // by the distance 'd'
  //
  // See APPENDIX on SETRELATIVE at the bottom of this file.
  //
  // p   ... point to set
  // rp  ... reference point
  // d   ... distance on projection vector
  // pv  ... projection vector (undefined = this)
  // org ... if true, uses the original position of rp as reference.
  setRelative: function(p, rp, d, pv, org) {
    if (!pv || pv === this) {
      p.y = (org ? rp.yo : rp.y) + d;
      return;
    }
    var rpx = org ? rp.xo : rp.x;
    var rpy = org ? rp.yo : rp.y;
    var rpdx = rpx + d * pv.x;
    var rpdy = rpy + d * pv.y;
    p.y = rpdy + pv.normalSlope * (p.x - rpdx);
  },
  // Slope of vector line.
  slope: Number.POSITIVE_INFINITY,
  // Touches the point p.
  touch: function(p) {
    p.yTouched = true;
  },
  // Tests if a point p is touched.
  touched: function(p) {
    return p.yTouched;
  },
  // Untouches the point p.
  untouch: function(p) {
    p.yTouched = false;
  }
};
Object.freeze(xUnitVector);
Object.freeze(yUnitVector);
function UnitVector(x2, y) {
  this.x = x2;
  this.y = y;
  this.axis = void 0;
  this.slope = y / x2;
  this.normalSlope = -x2 / y;
  Object.freeze(this);
}
UnitVector.prototype.distance = function(p1, p2, o1, o2) {
  return this.x * xUnitVector.distance(p1, p2, o1, o2) + this.y * yUnitVector.distance(p1, p2, o1, o2);
};
UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) {
  var dm1;
  var dm2;
  var do1;
  var do2;
  var doa1;
  var doa2;
  var dt;
  do1 = pv.distance(p, rp1, true, true);
  do2 = pv.distance(p, rp2, true, true);
  dm1 = pv.distance(rp1, rp1, false, true);
  dm2 = pv.distance(rp2, rp2, false, true);
  doa1 = Math.abs(do1);
  doa2 = Math.abs(do2);
  dt = doa1 + doa2;
  if (dt === 0) {
    this.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
    return;
  }
  this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
};
UnitVector.prototype.setRelative = function(p, rp, d, pv, org) {
  pv = pv || this;
  var rpx = org ? rp.xo : rp.x;
  var rpy = org ? rp.yo : rp.y;
  var rpdx = rpx + d * pv.x;
  var rpdy = rpy + d * pv.y;
  var pvns = pv.normalSlope;
  var fvs = this.slope;
  var px = p.x;
  var py = p.y;
  p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns);
  p.y = fvs * (p.x - px) + py;
};
UnitVector.prototype.touch = function(p) {
  p.xTouched = true;
  p.yTouched = true;
};
function getUnitVector(x2, y) {
  var d = Math.sqrt(x2 * x2 + y * y);
  x2 /= d;
  y /= d;
  if (x2 === 1 && y === 0) {
    return xUnitVector;
  } else if (x2 === 0 && y === 1) {
    return yUnitVector;
  } else {
    return new UnitVector(x2, y);
  }
}
function HPoint(x2, y, lastPointOfContour, onCurve) {
  this.x = this.xo = Math.round(x2 * 64) / 64;
  this.y = this.yo = Math.round(y * 64) / 64;
  this.lastPointOfContour = lastPointOfContour;
  this.onCurve = onCurve;
  this.prevPointOnContour = void 0;
  this.nextPointOnContour = void 0;
  this.xTouched = false;
  this.yTouched = false;
  Object.preventExtensions(this);
}
HPoint.prototype.nextTouched = function(v) {
  var p = this.nextPointOnContour;
  while (!v.touched(p) && p !== this) {
    p = p.nextPointOnContour;
  }
  return p;
};
HPoint.prototype.prevTouched = function(v) {
  var p = this.prevPointOnContour;
  while (!v.touched(p) && p !== this) {
    p = p.prevPointOnContour;
  }
  return p;
};
var HPZero = Object.freeze(new HPoint(0, 0));
var defaultState = {
  cvCutIn: 17 / 16,
  // control value cut in
  deltaBase: 9,
  deltaShift: 0.125,
  loop: 1,
  // loops some instructions
  minDis: 1,
  // minimum distance
  autoFlip: true
};
function State(env, prog) {
  this.env = env;
  this.stack = [];
  this.prog = prog;
  switch (env) {
    case "glyf":
      this.zp0 = this.zp1 = this.zp2 = 1;
      this.rp0 = this.rp1 = this.rp2 = 0;
    /* fall through */
    case "prep":
      this.fv = this.pv = this.dpv = xUnitVector;
      this.round = roundToGrid;
  }
}
Hinting.prototype.exec = function(glyph, ppem) {
  if (typeof ppem !== "number") {
    throw new Error("Point size is not a number!");
  }
  if (this._errorState > 2) {
    return;
  }
  var font = this.font;
  var prepState = this._prepState;
  if (!prepState || prepState.ppem !== ppem) {
    var fpgmState = this._fpgmState;
    if (!fpgmState) {
      State.prototype = defaultState;
      fpgmState = this._fpgmState = new State("fpgm", font.tables.fpgm);
      fpgmState.funcs = [];
      fpgmState.font = font;
      if (exports.DEBUG) {
        console.log("---EXEC FPGM---");
        fpgmState.step = -1;
      }
      try {
        exec(fpgmState);
      } catch (e) {
        console.log("Hinting error in FPGM:" + e);
        this._errorState = 3;
        return;
      }
    }
    State.prototype = fpgmState;
    prepState = this._prepState = new State("prep", font.tables.prep);
    prepState.ppem = ppem;
    var oCvt = font.tables.cvt;
    if (oCvt) {
      var cvt = prepState.cvt = new Array(oCvt.length);
      var scale2 = ppem / font.unitsPerEm;
      for (var c2 = 0; c2 < oCvt.length; c2++) {
        cvt[c2] = oCvt[c2] * scale2;
      }
    } else {
      prepState.cvt = [];
    }
    if (exports.DEBUG) {
      console.log("---EXEC PREP---");
      prepState.step = -1;
    }
    try {
      exec(prepState);
    } catch (e) {
      if (this._errorState < 2) {
        console.log("Hinting error in PREP:" + e);
      }
      this._errorState = 2;
    }
  }
  if (this._errorState > 1) {
    return;
  }
  try {
    return execGlyph(glyph, prepState);
  } catch (e) {
    if (this._errorState < 1) {
      console.log("Hinting error:" + e);
      console.log("Note: further hinting errors are silenced");
    }
    this._errorState = 1;
    return void 0;
  }
};
execGlyph = function(glyph, prepState) {
  var xScale = prepState.ppem / prepState.font.unitsPerEm;
  var yScale = xScale;
  var components = glyph.components;
  var contours;
  var gZone;
  var state;
  State.prototype = prepState;
  if (!components) {
    state = new State("glyf", glyph.instructions);
    if (exports.DEBUG) {
      console.log("---EXEC GLYPH---");
      state.step = -1;
    }
    execComponent(glyph, state, xScale, yScale);
    gZone = state.gZone;
  } else {
    var font = prepState.font;
    gZone = [];
    contours = [];
    for (var i = 0; i < components.length; i++) {
      var c2 = components[i];
      var cg = font.glyphs.get(c2.glyphIndex);
      state = new State("glyf", cg.instructions);
      if (exports.DEBUG) {
        console.log("---EXEC COMP " + i + "---");
        state.step = -1;
      }
      execComponent(cg, state, xScale, yScale);
      var dx = Math.round(c2.dx * xScale);
      var dy = Math.round(c2.dy * yScale);
      var gz = state.gZone;
      var cc = state.contours;
      for (var pi3 = 0; pi3 < gz.length; pi3++) {
        var p = gz[pi3];
        p.xTouched = p.yTouched = false;
        p.xo = p.x = p.x + dx;
        p.yo = p.y = p.y + dy;
      }
      var gLen = gZone.length;
      gZone.push.apply(gZone, gz);
      for (var j2 = 0; j2 < cc.length; j2++) {
        contours.push(cc[j2] + gLen);
      }
    }
    if (glyph.instructions && !state.inhibitGridFit) {
      state = new State("glyf", glyph.instructions);
      state.gZone = state.z0 = state.z1 = state.z2 = gZone;
      state.contours = contours;
      gZone.push(
        new HPoint(0, 0),
        new HPoint(Math.round(glyph.advanceWidth * xScale), 0)
      );
      if (exports.DEBUG) {
        console.log("---EXEC COMPOSITE---");
        state.step = -1;
      }
      exec(state);
      gZone.length -= 2;
    }
  }
  return gZone;
};
execComponent = function(glyph, state, xScale, yScale) {
  var points = glyph.points || [];
  var pLen = points.length;
  var gZone = state.gZone = state.z0 = state.z1 = state.z2 = [];
  var contours = state.contours = [];
  var cp;
  for (var i = 0; i < pLen; i++) {
    cp = points[i];
    gZone[i] = new HPoint(
      cp.x * xScale,
      cp.y * yScale,
      cp.lastPointOfContour,
      cp.onCurve
    );
  }
  var sp;
  var np;
  for (var i$1 = 0; i$1 < pLen; i$1++) {
    cp = gZone[i$1];
    if (!sp) {
      sp = cp;
      contours.push(i$1);
    }
    if (cp.lastPointOfContour) {
      cp.nextPointOnContour = sp;
      sp.prevPointOnContour = cp;
      sp = void 0;
    } else {
      np = gZone[i$1 + 1];
      cp.nextPointOnContour = np;
      np.prevPointOnContour = cp;
    }
  }
  if (state.inhibitGridFit) {
    return;
  }
  if (exports.DEBUG) {
    console.log("PROCESSING GLYPH", state.stack);
    for (var i$2 = 0; i$2 < pLen; i$2++) {
      console.log(i$2, gZone[i$2].x, gZone[i$2].y);
    }
  }
  gZone.push(
    new HPoint(0, 0),
    new HPoint(Math.round(glyph.advanceWidth * xScale), 0)
  );
  exec(state);
  gZone.length -= 2;
  if (exports.DEBUG) {
    console.log("FINISHED GLYPH", state.stack);
    for (var i$3 = 0; i$3 < pLen; i$3++) {
      console.log(i$3, gZone[i$3].x, gZone[i$3].y);
    }
  }
};
exec = function(state) {
  var prog = state.prog;
  if (!prog) {
    return;
  }
  var pLen = prog.length;
  var ins;
  for (state.ip = 0; state.ip < pLen; state.ip++) {
    if (exports.DEBUG) {
      state.step++;
    }
    ins = instructionTable[prog[state.ip]];
    if (!ins) {
      throw new Error(
        "unknown instruction: 0x" + Number(prog[state.ip]).toString(16)
      );
    }
    ins(state);
  }
};
function initTZone(state) {
  var tZone = state.tZone = new Array(state.gZone.length);
  for (var i = 0; i < tZone.length; i++) {
    tZone[i] = new HPoint(0, 0);
  }
}
function skip(state, handleElse) {
  var prog = state.prog;
  var ip = state.ip;
  var nesting = 1;
  var ins;
  do {
    ins = prog[++ip];
    if (ins === 88) {
      nesting++;
    } else if (ins === 89) {
      nesting--;
    } else if (ins === 64) {
      ip += prog[ip + 1] + 1;
    } else if (ins === 65) {
      ip += 2 * prog[ip + 1] + 1;
    } else if (ins >= 176 && ins <= 183) {
      ip += ins - 176 + 1;
    } else if (ins >= 184 && ins <= 191) {
      ip += (ins - 184 + 1) * 2;
    } else if (handleElse && nesting === 1 && ins === 27) {
      break;
    }
  } while (nesting > 0);
  state.ip = ip;
}
function SVTCA(v, state) {
  if (exports.DEBUG) {
    console.log(state.step, "SVTCA[" + v.axis + "]");
  }
  state.fv = state.pv = state.dpv = v;
}
function SPVTCA(v, state) {
  if (exports.DEBUG) {
    console.log(state.step, "SPVTCA[" + v.axis + "]");
  }
  state.pv = state.dpv = v;
}
function SFVTCA(v, state) {
  if (exports.DEBUG) {
    console.log(state.step, "SFVTCA[" + v.axis + "]");
  }
  state.fv = v;
}
function SPVTL(a2, state) {
  var stack = state.stack;
  var p2i = stack.pop();
  var p1i = stack.pop();
  var p2 = state.z2[p2i];
  var p1 = state.z1[p1i];
  if (exports.DEBUG) {
    console.log("SPVTL[" + a2 + "]", p2i, p1i);
  }
  var dx;
  var dy;
  if (!a2) {
    dx = p1.x - p2.x;
    dy = p1.y - p2.y;
  } else {
    dx = p2.y - p1.y;
    dy = p1.x - p2.x;
  }
  state.pv = state.dpv = getUnitVector(dx, dy);
}
function SFVTL(a2, state) {
  var stack = state.stack;
  var p2i = stack.pop();
  var p1i = stack.pop();
  var p2 = state.z2[p2i];
  var p1 = state.z1[p1i];
  if (exports.DEBUG) {
    console.log("SFVTL[" + a2 + "]", p2i, p1i);
  }
  var dx;
  var dy;
  if (!a2) {
    dx = p1.x - p2.x;
    dy = p1.y - p2.y;
  } else {
    dx = p2.y - p1.y;
    dy = p1.x - p2.x;
  }
  state.fv = getUnitVector(dx, dy);
}
function SPVFS(state) {
  var stack = state.stack;
  var y = stack.pop();
  var x2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SPVFS[]", y, x2);
  }
  state.pv = state.dpv = getUnitVector(x2, y);
}
function SFVFS(state) {
  var stack = state.stack;
  var y = stack.pop();
  var x2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SPVFS[]", y, x2);
  }
  state.fv = getUnitVector(x2, y);
}
function GPV(state) {
  var stack = state.stack;
  var pv = state.pv;
  if (exports.DEBUG) {
    console.log(state.step, "GPV[]");
  }
  stack.push(pv.x * 16384);
  stack.push(pv.y * 16384);
}
function GFV(state) {
  var stack = state.stack;
  var fv = state.fv;
  if (exports.DEBUG) {
    console.log(state.step, "GFV[]");
  }
  stack.push(fv.x * 16384);
  stack.push(fv.y * 16384);
}
function SFVTPV(state) {
  state.fv = state.pv;
  if (exports.DEBUG) {
    console.log(state.step, "SFVTPV[]");
  }
}
function ISECT(state) {
  var stack = state.stack;
  var pa0i = stack.pop();
  var pa1i = stack.pop();
  var pb0i = stack.pop();
  var pb1i = stack.pop();
  var pi3 = stack.pop();
  var z0 = state.z0;
  var z1 = state.z1;
  var pa0 = z0[pa0i];
  var pa1 = z0[pa1i];
  var pb0 = z1[pb0i];
  var pb1 = z1[pb1i];
  var p = state.z2[pi3];
  if (exports.DEBUG) {
    console.log("ISECT[], ", pa0i, pa1i, pb0i, pb1i, pi3);
  }
  var x1 = pa0.x;
  var y1 = pa0.y;
  var x2 = pa1.x;
  var y2 = pa1.y;
  var x3 = pb0.x;
  var y3 = pb0.y;
  var x4 = pb1.x;
  var y4 = pb1.y;
  var div2 = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  var f1 = x1 * y2 - y1 * x2;
  var f2 = x3 * y4 - y3 * x4;
  p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div2;
  p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div2;
}
function SRP0(state) {
  state.rp0 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SRP0[]", state.rp0);
  }
}
function SRP1(state) {
  state.rp1 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SRP1[]", state.rp1);
  }
}
function SRP2(state) {
  state.rp2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SRP2[]", state.rp2);
  }
}
function SZP0(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SZP0[]", n2);
  }
  state.zp0 = n2;
  switch (n2) {
    case 0:
      if (!state.tZone) {
        initTZone(state);
      }
      state.z0 = state.tZone;
      break;
    case 1:
      state.z0 = state.gZone;
      break;
    default:
      throw new Error("Invalid zone pointer");
  }
}
function SZP1(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SZP1[]", n2);
  }
  state.zp1 = n2;
  switch (n2) {
    case 0:
      if (!state.tZone) {
        initTZone(state);
      }
      state.z1 = state.tZone;
      break;
    case 1:
      state.z1 = state.gZone;
      break;
    default:
      throw new Error("Invalid zone pointer");
  }
}
function SZP2(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SZP2[]", n2);
  }
  state.zp2 = n2;
  switch (n2) {
    case 0:
      if (!state.tZone) {
        initTZone(state);
      }
      state.z2 = state.tZone;
      break;
    case 1:
      state.z2 = state.gZone;
      break;
    default:
      throw new Error("Invalid zone pointer");
  }
}
function SZPS(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SZPS[]", n2);
  }
  state.zp0 = state.zp1 = state.zp2 = n2;
  switch (n2) {
    case 0:
      if (!state.tZone) {
        initTZone(state);
      }
      state.z0 = state.z1 = state.z2 = state.tZone;
      break;
    case 1:
      state.z0 = state.z1 = state.z2 = state.gZone;
      break;
    default:
      throw new Error("Invalid zone pointer");
  }
}
function SLOOP(state) {
  state.loop = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SLOOP[]", state.loop);
  }
}
function RTG(state) {
  if (exports.DEBUG) {
    console.log(state.step, "RTG[]");
  }
  state.round = roundToGrid;
}
function RTHG(state) {
  if (exports.DEBUG) {
    console.log(state.step, "RTHG[]");
  }
  state.round = roundToHalfGrid;
}
function SMD(state) {
  var d = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SMD[]", d);
  }
  state.minDis = d / 64;
}
function ELSE(state) {
  if (exports.DEBUG) {
    console.log(state.step, "ELSE[]");
  }
  skip(state, false);
}
function JMPR(state) {
  var o = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "JMPR[]", o);
  }
  state.ip += o - 1;
}
function SCVTCI(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SCVTCI[]", n2);
  }
  state.cvCutIn = n2 / 64;
}
function DUP(state) {
  var stack = state.stack;
  if (exports.DEBUG) {
    console.log(state.step, "DUP[]");
  }
  stack.push(stack[stack.length - 1]);
}
function POP(state) {
  if (exports.DEBUG) {
    console.log(state.step, "POP[]");
  }
  state.stack.pop();
}
function CLEAR(state) {
  if (exports.DEBUG) {
    console.log(state.step, "CLEAR[]");
  }
  state.stack.length = 0;
}
function SWAP(state) {
  var stack = state.stack;
  var a2 = stack.pop();
  var b3 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SWAP[]");
  }
  stack.push(a2);
  stack.push(b3);
}
function DEPTH(state) {
  var stack = state.stack;
  if (exports.DEBUG) {
    console.log(state.step, "DEPTH[]");
  }
  stack.push(stack.length);
}
function LOOPCALL(state) {
  var stack = state.stack;
  var fn = stack.pop();
  var c2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "LOOPCALL[]", fn, c2);
  }
  var cip = state.ip;
  var cprog = state.prog;
  state.prog = state.funcs[fn];
  for (var i = 0; i < c2; i++) {
    exec(state);
    if (exports.DEBUG) {
      console.log(
        ++state.step,
        i + 1 < c2 ? "next loopcall" : "done loopcall",
        i
      );
    }
  }
  state.ip = cip;
  state.prog = cprog;
}
function CALL(state) {
  var fn = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "CALL[]", fn);
  }
  var cip = state.ip;
  var cprog = state.prog;
  state.prog = state.funcs[fn];
  exec(state);
  state.ip = cip;
  state.prog = cprog;
  if (exports.DEBUG) {
    console.log(++state.step, "returning from", fn);
  }
}
function CINDEX(state) {
  var stack = state.stack;
  var k2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "CINDEX[]", k2);
  }
  stack.push(stack[stack.length - k2]);
}
function MINDEX(state) {
  var stack = state.stack;
  var k2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "MINDEX[]", k2);
  }
  stack.push(stack.splice(stack.length - k2, 1)[0]);
}
function FDEF(state) {
  if (state.env !== "fpgm") {
    throw new Error("FDEF not allowed here");
  }
  var stack = state.stack;
  var prog = state.prog;
  var ip = state.ip;
  var fn = stack.pop();
  var ipBegin = ip;
  if (exports.DEBUG) {
    console.log(state.step, "FDEF[]", fn);
  }
  while (prog[++ip] !== 45) {
  }
  state.ip = ip;
  state.funcs[fn] = prog.slice(ipBegin + 1, ip);
}
function MDAP(round, state) {
  var pi3 = state.stack.pop();
  var p = state.z0[pi3];
  var fv = state.fv;
  var pv = state.pv;
  if (exports.DEBUG) {
    console.log(state.step, "MDAP[" + round + "]", pi3);
  }
  var d = pv.distance(p, HPZero);
  if (round) {
    d = state.round(d);
  }
  fv.setRelative(p, HPZero, d, pv);
  fv.touch(p);
  state.rp0 = state.rp1 = pi3;
}
function IUP(v, state) {
  var z2 = state.z2;
  var pLen = z2.length - 2;
  var cp;
  var pp;
  var np;
  if (exports.DEBUG) {
    console.log(state.step, "IUP[" + v.axis + "]");
  }
  for (var i = 0; i < pLen; i++) {
    cp = z2[i];
    if (v.touched(cp)) {
      continue;
    }
    pp = cp.prevTouched(v);
    if (pp === cp) {
      continue;
    }
    np = cp.nextTouched(v);
    if (pp === np) {
      v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true);
    }
    v.interpolate(cp, pp, np, v);
  }
}
function SHP(a2, state) {
  var stack = state.stack;
  var rpi = a2 ? state.rp1 : state.rp2;
  var rp = (a2 ? state.z0 : state.z1)[rpi];
  var fv = state.fv;
  var pv = state.pv;
  var loop = state.loop;
  var z2 = state.z2;
  while (loop--) {
    var pi3 = stack.pop();
    var p = z2[pi3];
    var d = pv.distance(rp, rp, false, true);
    fv.setRelative(p, p, d, pv);
    fv.touch(p);
    if (exports.DEBUG) {
      console.log(
        state.step,
        (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHP[" + (a2 ? "rp1" : "rp2") + "]",
        pi3
      );
    }
  }
  state.loop = 1;
}
function SHC(a2, state) {
  var stack = state.stack;
  var rpi = a2 ? state.rp1 : state.rp2;
  var rp = (a2 ? state.z0 : state.z1)[rpi];
  var fv = state.fv;
  var pv = state.pv;
  var ci = stack.pop();
  var sp = state.z2[state.contours[ci]];
  var p = sp;
  if (exports.DEBUG) {
    console.log(state.step, "SHC[" + a2 + "]", ci);
  }
  var d = pv.distance(rp, rp, false, true);
  do {
    if (p !== rp) {
      fv.setRelative(p, p, d, pv);
    }
    p = p.nextPointOnContour;
  } while (p !== sp);
}
function SHZ(a2, state) {
  var stack = state.stack;
  var rpi = a2 ? state.rp1 : state.rp2;
  var rp = (a2 ? state.z0 : state.z1)[rpi];
  var fv = state.fv;
  var pv = state.pv;
  var e = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SHZ[" + a2 + "]", e);
  }
  var z;
  switch (e) {
    case 0:
      z = state.tZone;
      break;
    case 1:
      z = state.gZone;
      break;
    default:
      throw new Error("Invalid zone");
  }
  var p;
  var d = pv.distance(rp, rp, false, true);
  var pLen = z.length - 2;
  for (var i = 0; i < pLen; i++) {
    p = z[i];
    fv.setRelative(p, p, d, pv);
  }
}
function SHPIX(state) {
  var stack = state.stack;
  var loop = state.loop;
  var fv = state.fv;
  var d = stack.pop() / 64;
  var z2 = state.z2;
  while (loop--) {
    var pi3 = stack.pop();
    var p = z2[pi3];
    if (exports.DEBUG) {
      console.log(
        state.step,
        (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHPIX[]",
        pi3,
        d
      );
    }
    fv.setRelative(p, p, d);
    fv.touch(p);
  }
  state.loop = 1;
}
function IP(state) {
  var stack = state.stack;
  var rp1i = state.rp1;
  var rp2i = state.rp2;
  var loop = state.loop;
  var rp1 = state.z0[rp1i];
  var rp2 = state.z1[rp2i];
  var fv = state.fv;
  var pv = state.dpv;
  var z2 = state.z2;
  while (loop--) {
    var pi3 = stack.pop();
    var p = z2[pi3];
    if (exports.DEBUG) {
      console.log(
        state.step,
        (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "IP[]",
        pi3,
        rp1i,
        "<->",
        rp2i
      );
    }
    fv.interpolate(p, rp1, rp2, pv);
    fv.touch(p);
  }
  state.loop = 1;
}
function MSIRP(a2, state) {
  var stack = state.stack;
  var d = stack.pop() / 64;
  var pi3 = stack.pop();
  var p = state.z1[pi3];
  var rp0 = state.z0[state.rp0];
  var fv = state.fv;
  var pv = state.pv;
  fv.setRelative(p, rp0, d, pv);
  fv.touch(p);
  if (exports.DEBUG) {
    console.log(state.step, "MSIRP[" + a2 + "]", d, pi3);
  }
  state.rp1 = state.rp0;
  state.rp2 = pi3;
  if (a2) {
    state.rp0 = pi3;
  }
}
function ALIGNRP(state) {
  var stack = state.stack;
  var rp0i = state.rp0;
  var rp0 = state.z0[rp0i];
  var loop = state.loop;
  var fv = state.fv;
  var pv = state.pv;
  var z1 = state.z1;
  while (loop--) {
    var pi3 = stack.pop();
    var p = z1[pi3];
    if (exports.DEBUG) {
      console.log(
        state.step,
        (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "ALIGNRP[]",
        pi3
      );
    }
    fv.setRelative(p, rp0, 0, pv);
    fv.touch(p);
  }
  state.loop = 1;
}
function RTDG(state) {
  if (exports.DEBUG) {
    console.log(state.step, "RTDG[]");
  }
  state.round = roundToDoubleGrid;
}
function MIAP(round, state) {
  var stack = state.stack;
  var n2 = stack.pop();
  var pi3 = stack.pop();
  var p = state.z0[pi3];
  var fv = state.fv;
  var pv = state.pv;
  var cv = state.cvt[n2];
  if (exports.DEBUG) {
    console.log(
      state.step,
      "MIAP[" + round + "]",
      n2,
      "(",
      cv,
      ")",
      pi3
    );
  }
  var d = pv.distance(p, HPZero);
  if (round) {
    if (Math.abs(d - cv) < state.cvCutIn) {
      d = cv;
    }
    d = state.round(d);
  }
  fv.setRelative(p, HPZero, d, pv);
  if (state.zp0 === 0) {
    p.xo = p.x;
    p.yo = p.y;
  }
  fv.touch(p);
  state.rp0 = state.rp1 = pi3;
}
function NPUSHB(state) {
  var prog = state.prog;
  var ip = state.ip;
  var stack = state.stack;
  var n2 = prog[++ip];
  if (exports.DEBUG) {
    console.log(state.step, "NPUSHB[]", n2);
  }
  for (var i = 0; i < n2; i++) {
    stack.push(prog[++ip]);
  }
  state.ip = ip;
}
function NPUSHW(state) {
  var ip = state.ip;
  var prog = state.prog;
  var stack = state.stack;
  var n2 = prog[++ip];
  if (exports.DEBUG) {
    console.log(state.step, "NPUSHW[]", n2);
  }
  for (var i = 0; i < n2; i++) {
    var w = prog[++ip] << 8 | prog[++ip];
    if (w & 32768) {
      w = -((w ^ 65535) + 1);
    }
    stack.push(w);
  }
  state.ip = ip;
}
function WS(state) {
  var stack = state.stack;
  var store = state.store;
  if (!store) {
    store = state.store = [];
  }
  var v = stack.pop();
  var l2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "WS", v, l2);
  }
  store[l2] = v;
}
function RS(state) {
  var stack = state.stack;
  var store = state.store;
  var l2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "RS", l2);
  }
  var v = store && store[l2] || 0;
  stack.push(v);
}
function WCVTP(state) {
  var stack = state.stack;
  var v = stack.pop();
  var l2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "WCVTP", v, l2);
  }
  state.cvt[l2] = v / 64;
}
function RCVT(state) {
  var stack = state.stack;
  var cvte = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "RCVT", cvte);
  }
  stack.push(state.cvt[cvte] * 64);
}
function GC(a2, state) {
  var stack = state.stack;
  var pi3 = stack.pop();
  var p = state.z2[pi3];
  if (exports.DEBUG) {
    console.log(state.step, "GC[" + a2 + "]", pi3);
  }
  stack.push(state.dpv.distance(p, HPZero, a2, false) * 64);
}
function MD(a2, state) {
  var stack = state.stack;
  var pi22 = stack.pop();
  var pi1 = stack.pop();
  var p2 = state.z1[pi22];
  var p1 = state.z0[pi1];
  var d = state.dpv.distance(p1, p2, a2, a2);
  if (exports.DEBUG) {
    console.log(state.step, "MD[" + a2 + "]", pi22, pi1, "->", d);
  }
  state.stack.push(Math.round(d * 64));
}
function MPPEM(state) {
  if (exports.DEBUG) {
    console.log(state.step, "MPPEM[]");
  }
  state.stack.push(state.ppem);
}
function FLIPON(state) {
  if (exports.DEBUG) {
    console.log(state.step, "FLIPON[]");
  }
  state.autoFlip = true;
}
function LT(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "LT[]", e2, e1);
  }
  stack.push(e1 < e2 ? 1 : 0);
}
function LTEQ(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "LTEQ[]", e2, e1);
  }
  stack.push(e1 <= e2 ? 1 : 0);
}
function GT(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "GT[]", e2, e1);
  }
  stack.push(e1 > e2 ? 1 : 0);
}
function GTEQ(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "GTEQ[]", e2, e1);
  }
  stack.push(e1 >= e2 ? 1 : 0);
}
function EQ(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "EQ[]", e2, e1);
  }
  stack.push(e2 === e1 ? 1 : 0);
}
function NEQ(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "NEQ[]", e2, e1);
  }
  stack.push(e2 !== e1 ? 1 : 0);
}
function ODD(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "ODD[]", n2);
  }
  stack.push(Math.trunc(n2) % 2 ? 1 : 0);
}
function EVEN(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "EVEN[]", n2);
  }
  stack.push(Math.trunc(n2) % 2 ? 0 : 1);
}
function IF(state) {
  var test = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "IF[]", test);
  }
  if (!test) {
    skip(state, true);
    if (exports.DEBUG) {
      console.log(state.step, "EIF[]");
    }
  }
}
function EIF(state) {
  if (exports.DEBUG) {
    console.log(state.step, "EIF[]");
  }
}
function AND(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "AND[]", e2, e1);
  }
  stack.push(e2 && e1 ? 1 : 0);
}
function OR(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "OR[]", e2, e1);
  }
  stack.push(e2 || e1 ? 1 : 0);
}
function NOT(state) {
  var stack = state.stack;
  var e = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "NOT[]", e);
  }
  stack.push(e ? 0 : 1);
}
function DELTAP123(b3, state) {
  var stack = state.stack;
  var n2 = stack.pop();
  var fv = state.fv;
  var pv = state.pv;
  var ppem = state.ppem;
  var base = state.deltaBase + (b3 - 1) * 16;
  var ds = state.deltaShift;
  var z0 = state.z0;
  if (exports.DEBUG) {
    console.log(state.step, "DELTAP[" + b3 + "]", n2, stack);
  }
  for (var i = 0; i < n2; i++) {
    var pi3 = stack.pop();
    var arg = stack.pop();
    var appem = base + ((arg & 240) >> 4);
    if (appem !== ppem) {
      continue;
    }
    var mag = (arg & 15) - 8;
    if (mag >= 0) {
      mag++;
    }
    if (exports.DEBUG) {
      console.log(state.step, "DELTAPFIX", pi3, "by", mag * ds);
    }
    var p = z0[pi3];
    fv.setRelative(p, p, mag * ds, pv);
  }
}
function SDB(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SDB[]", n2);
  }
  state.deltaBase = n2;
}
function SDS(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SDS[]", n2);
  }
  state.deltaShift = Math.pow(0.5, n2);
}
function ADD(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  var n1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "ADD[]", n2, n1);
  }
  stack.push(n1 + n2);
}
function SUB(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  var n1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SUB[]", n2, n1);
  }
  stack.push(n1 - n2);
}
function DIV(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  var n1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "DIV[]", n2, n1);
  }
  stack.push(n1 * 64 / n2);
}
function MUL(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  var n1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "MUL[]", n2, n1);
  }
  stack.push(n1 * n2 / 64);
}
function ABS(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "ABS[]", n2);
  }
  stack.push(Math.abs(n2));
}
function NEG(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "NEG[]", n2);
  }
  stack.push(-n2);
}
function FLOOR(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "FLOOR[]", n2);
  }
  stack.push(Math.floor(n2 / 64) * 64);
}
function CEILING(state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "CEILING[]", n2);
  }
  stack.push(Math.ceil(n2 / 64) * 64);
}
function ROUND(dt, state) {
  var stack = state.stack;
  var n2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "ROUND[]");
  }
  stack.push(state.round(n2 / 64) * 64);
}
function WCVTF(state) {
  var stack = state.stack;
  var v = stack.pop();
  var l2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "WCVTF[]", v, l2);
  }
  state.cvt[l2] = v * state.ppem / state.font.unitsPerEm;
}
function DELTAC123(b3, state) {
  var stack = state.stack;
  var n2 = stack.pop();
  var ppem = state.ppem;
  var base = state.deltaBase + (b3 - 1) * 16;
  var ds = state.deltaShift;
  if (exports.DEBUG) {
    console.log(state.step, "DELTAC[" + b3 + "]", n2, stack);
  }
  for (var i = 0; i < n2; i++) {
    var c2 = stack.pop();
    var arg = stack.pop();
    var appem = base + ((arg & 240) >> 4);
    if (appem !== ppem) {
      continue;
    }
    var mag = (arg & 15) - 8;
    if (mag >= 0) {
      mag++;
    }
    var delta = mag * ds;
    if (exports.DEBUG) {
      console.log(state.step, "DELTACFIX", c2, "by", delta);
    }
    state.cvt[c2] += delta;
  }
}
function SROUND(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SROUND[]", n2);
  }
  state.round = roundSuper;
  var period;
  switch (n2 & 192) {
    case 0:
      period = 0.5;
      break;
    case 64:
      period = 1;
      break;
    case 128:
      period = 2;
      break;
    default:
      throw new Error("invalid SROUND value");
  }
  state.srPeriod = period;
  switch (n2 & 48) {
    case 0:
      state.srPhase = 0;
      break;
    case 16:
      state.srPhase = 0.25 * period;
      break;
    case 32:
      state.srPhase = 0.5 * period;
      break;
    case 48:
      state.srPhase = 0.75 * period;
      break;
    default:
      throw new Error("invalid SROUND value");
  }
  n2 &= 15;
  if (n2 === 0) {
    state.srThreshold = 0;
  } else {
    state.srThreshold = (n2 / 8 - 0.5) * period;
  }
}
function S45ROUND(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "S45ROUND[]", n2);
  }
  state.round = roundSuper;
  var period;
  switch (n2 & 192) {
    case 0:
      period = Math.sqrt(2) / 2;
      break;
    case 64:
      period = Math.sqrt(2);
      break;
    case 128:
      period = 2 * Math.sqrt(2);
      break;
    default:
      throw new Error("invalid S45ROUND value");
  }
  state.srPeriod = period;
  switch (n2 & 48) {
    case 0:
      state.srPhase = 0;
      break;
    case 16:
      state.srPhase = 0.25 * period;
      break;
    case 32:
      state.srPhase = 0.5 * period;
      break;
    case 48:
      state.srPhase = 0.75 * period;
      break;
    default:
      throw new Error("invalid S45ROUND value");
  }
  n2 &= 15;
  if (n2 === 0) {
    state.srThreshold = 0;
  } else {
    state.srThreshold = (n2 / 8 - 0.5) * period;
  }
}
function ROFF(state) {
  if (exports.DEBUG) {
    console.log(state.step, "ROFF[]");
  }
  state.round = roundOff;
}
function RUTG(state) {
  if (exports.DEBUG) {
    console.log(state.step, "RUTG[]");
  }
  state.round = roundUpToGrid;
}
function RDTG(state) {
  if (exports.DEBUG) {
    console.log(state.step, "RDTG[]");
  }
  state.round = roundDownToGrid;
}
function SCANCTRL(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SCANCTRL[]", n2);
  }
}
function SDPVTL(a2, state) {
  var stack = state.stack;
  var p2i = stack.pop();
  var p1i = stack.pop();
  var p2 = state.z2[p2i];
  var p1 = state.z1[p1i];
  if (exports.DEBUG) {
    console.log(state.step, "SDPVTL[" + a2 + "]", p2i, p1i);
  }
  var dx;
  var dy;
  if (!a2) {
    dx = p1.x - p2.x;
    dy = p1.y - p2.y;
  } else {
    dx = p2.y - p1.y;
    dy = p1.x - p2.x;
  }
  state.dpv = getUnitVector(dx, dy);
}
function GETINFO(state) {
  var stack = state.stack;
  var sel = stack.pop();
  var r = 0;
  if (exports.DEBUG) {
    console.log(state.step, "GETINFO[]", sel);
  }
  if (sel & 1) {
    r = 35;
  }
  if (sel & 32) {
    r |= 4096;
  }
  stack.push(r);
}
function ROLL(state) {
  var stack = state.stack;
  var a2 = stack.pop();
  var b3 = stack.pop();
  var c2 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "ROLL[]");
  }
  stack.push(b3);
  stack.push(a2);
  stack.push(c2);
}
function MAX(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "MAX[]", e2, e1);
  }
  stack.push(Math.max(e1, e2));
}
function MIN(state) {
  var stack = state.stack;
  var e2 = stack.pop();
  var e1 = stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "MIN[]", e2, e1);
  }
  stack.push(Math.min(e1, e2));
}
function SCANTYPE(state) {
  var n2 = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "SCANTYPE[]", n2);
  }
}
function INSTCTRL(state) {
  var s = state.stack.pop();
  var v = state.stack.pop();
  if (exports.DEBUG) {
    console.log(state.step, "INSTCTRL[]", s, v);
  }
  switch (s) {
    case 1:
      state.inhibitGridFit = !!v;
      return;
    case 2:
      state.ignoreCvt = !!v;
      return;
    default:
      throw new Error("invalid INSTCTRL[] selector");
  }
}
function PUSHB(n2, state) {
  var stack = state.stack;
  var prog = state.prog;
  var ip = state.ip;
  if (exports.DEBUG) {
    console.log(state.step, "PUSHB[" + n2 + "]");
  }
  for (var i = 0; i < n2; i++) {
    stack.push(prog[++ip]);
  }
  state.ip = ip;
}
function PUSHW(n2, state) {
  var ip = state.ip;
  var prog = state.prog;
  var stack = state.stack;
  if (exports.DEBUG) {
    console.log(state.ip, "PUSHW[" + n2 + "]");
  }
  for (var i = 0; i < n2; i++) {
    var w = prog[++ip] << 8 | prog[++ip];
    if (w & 32768) {
      w = -((w ^ 65535) + 1);
    }
    stack.push(w);
  }
  state.ip = ip;
}
function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) {
  var stack = state.stack;
  var cvte = indirect && stack.pop();
  var pi3 = stack.pop();
  var rp0i = state.rp0;
  var rp = state.z0[rp0i];
  var p = state.z1[pi3];
  var md = state.minDis;
  var fv = state.fv;
  var pv = state.dpv;
  var od;
  var d;
  var sign;
  var cv;
  d = od = pv.distance(p, rp, true, true);
  sign = d >= 0 ? 1 : -1;
  d = Math.abs(d);
  if (indirect) {
    cv = state.cvt[cvte];
    if (ro && Math.abs(d - cv) < state.cvCutIn) {
      d = cv;
    }
  }
  if (keepD && d < md) {
    d = md;
  }
  if (ro) {
    d = state.round(d);
  }
  fv.setRelative(p, rp, sign * d, pv);
  fv.touch(p);
  if (exports.DEBUG) {
    console.log(
      state.step,
      (indirect ? "MIRP[" : "MDRP[") + (setRp0 ? "M" : "m") + (keepD ? ">" : "_") + (ro ? "R" : "_") + (dt === 0 ? "Gr" : dt === 1 ? "Bl" : dt === 2 ? "Wh" : "") + "]",
      indirect ? cvte + "(" + state.cvt[cvte] + "," + cv + ")" : "",
      pi3,
      "(d =",
      od,
      "->",
      sign * d,
      ")"
    );
  }
  state.rp1 = state.rp0;
  state.rp2 = pi3;
  if (setRp0) {
    state.rp0 = pi3;
  }
}
instructionTable = [
  /* 0x00 */
  SVTCA.bind(void 0, yUnitVector),
  /* 0x01 */
  SVTCA.bind(void 0, xUnitVector),
  /* 0x02 */
  SPVTCA.bind(void 0, yUnitVector),
  /* 0x03 */
  SPVTCA.bind(void 0, xUnitVector),
  /* 0x04 */
  SFVTCA.bind(void 0, yUnitVector),
  /* 0x05 */
  SFVTCA.bind(void 0, xUnitVector),
  /* 0x06 */
  SPVTL.bind(void 0, 0),
  /* 0x07 */
  SPVTL.bind(void 0, 1),
  /* 0x08 */
  SFVTL.bind(void 0, 0),
  /* 0x09 */
  SFVTL.bind(void 0, 1),
  /* 0x0A */
  SPVFS,
  /* 0x0B */
  SFVFS,
  /* 0x0C */
  GPV,
  /* 0x0D */
  GFV,
  /* 0x0E */
  SFVTPV,
  /* 0x0F */
  ISECT,
  /* 0x10 */
  SRP0,
  /* 0x11 */
  SRP1,
  /* 0x12 */
  SRP2,
  /* 0x13 */
  SZP0,
  /* 0x14 */
  SZP1,
  /* 0x15 */
  SZP2,
  /* 0x16 */
  SZPS,
  /* 0x17 */
  SLOOP,
  /* 0x18 */
  RTG,
  /* 0x19 */
  RTHG,
  /* 0x1A */
  SMD,
  /* 0x1B */
  ELSE,
  /* 0x1C */
  JMPR,
  /* 0x1D */
  SCVTCI,
  /* 0x1E */
  void 0,
  // TODO SSWCI
  /* 0x1F */
  void 0,
  // TODO SSW
  /* 0x20 */
  DUP,
  /* 0x21 */
  POP,
  /* 0x22 */
  CLEAR,
  /* 0x23 */
  SWAP,
  /* 0x24 */
  DEPTH,
  /* 0x25 */
  CINDEX,
  /* 0x26 */
  MINDEX,
  /* 0x27 */
  void 0,
  // TODO ALIGNPTS
  /* 0x28 */
  void 0,
  /* 0x29 */
  void 0,
  // TODO UTP
  /* 0x2A */
  LOOPCALL,
  /* 0x2B */
  CALL,
  /* 0x2C */
  FDEF,
  /* 0x2D */
  void 0,
  // ENDF (eaten by FDEF)
  /* 0x2E */
  MDAP.bind(void 0, 0),
  /* 0x2F */
  MDAP.bind(void 0, 1),
  /* 0x30 */
  IUP.bind(void 0, yUnitVector),
  /* 0x31 */
  IUP.bind(void 0, xUnitVector),
  /* 0x32 */
  SHP.bind(void 0, 0),
  /* 0x33 */
  SHP.bind(void 0, 1),
  /* 0x34 */
  SHC.bind(void 0, 0),
  /* 0x35 */
  SHC.bind(void 0, 1),
  /* 0x36 */
  SHZ.bind(void 0, 0),
  /* 0x37 */
  SHZ.bind(void 0, 1),
  /* 0x38 */
  SHPIX,
  /* 0x39 */
  IP,
  /* 0x3A */
  MSIRP.bind(void 0, 0),
  /* 0x3B */
  MSIRP.bind(void 0, 1),
  /* 0x3C */
  ALIGNRP,
  /* 0x3D */
  RTDG,
  /* 0x3E */
  MIAP.bind(void 0, 0),
  /* 0x3F */
  MIAP.bind(void 0, 1),
  /* 0x40 */
  NPUSHB,
  /* 0x41 */
  NPUSHW,
  /* 0x42 */
  WS,
  /* 0x43 */
  RS,
  /* 0x44 */
  WCVTP,
  /* 0x45 */
  RCVT,
  /* 0x46 */
  GC.bind(void 0, 0),
  /* 0x47 */
  GC.bind(void 0, 1),
  /* 0x48 */
  void 0,
  // TODO SCFS
  /* 0x49 */
  MD.bind(void 0, 0),
  /* 0x4A */
  MD.bind(void 0, 1),
  /* 0x4B */
  MPPEM,
  /* 0x4C */
  void 0,
  // TODO MPS
  /* 0x4D */
  FLIPON,
  /* 0x4E */
  void 0,
  // TODO FLIPOFF
  /* 0x4F */
  void 0,
  // TODO DEBUG
  /* 0x50 */
  LT,
  /* 0x51 */
  LTEQ,
  /* 0x52 */
  GT,
  /* 0x53 */
  GTEQ,
  /* 0x54 */
  EQ,
  /* 0x55 */
  NEQ,
  /* 0x56 */
  ODD,
  /* 0x57 */
  EVEN,
  /* 0x58 */
  IF,
  /* 0x59 */
  EIF,
  /* 0x5A */
  AND,
  /* 0x5B */
  OR,
  /* 0x5C */
  NOT,
  /* 0x5D */
  DELTAP123.bind(void 0, 1),
  /* 0x5E */
  SDB,
  /* 0x5F */
  SDS,
  /* 0x60 */
  ADD,
  /* 0x61 */
  SUB,
  /* 0x62 */
  DIV,
  /* 0x63 */
  MUL,
  /* 0x64 */
  ABS,
  /* 0x65 */
  NEG,
  /* 0x66 */
  FLOOR,
  /* 0x67 */
  CEILING,
  /* 0x68 */
  ROUND.bind(void 0, 0),
  /* 0x69 */
  ROUND.bind(void 0, 1),
  /* 0x6A */
  ROUND.bind(void 0, 2),
  /* 0x6B */
  ROUND.bind(void 0, 3),
  /* 0x6C */
  void 0,
  // TODO NROUND[ab]
  /* 0x6D */
  void 0,
  // TODO NROUND[ab]
  /* 0x6E */
  void 0,
  // TODO NROUND[ab]
  /* 0x6F */
  void 0,
  // TODO NROUND[ab]
  /* 0x70 */
  WCVTF,
  /* 0x71 */
  DELTAP123.bind(void 0, 2),
  /* 0x72 */
  DELTAP123.bind(void 0, 3),
  /* 0x73 */
  DELTAC123.bind(void 0, 1),
  /* 0x74 */
  DELTAC123.bind(void 0, 2),
  /* 0x75 */
  DELTAC123.bind(void 0, 3),
  /* 0x76 */
  SROUND,
  /* 0x77 */
  S45ROUND,
  /* 0x78 */
  void 0,
  // TODO JROT[]
  /* 0x79 */
  void 0,
  // TODO JROF[]
  /* 0x7A */
  ROFF,
  /* 0x7B */
  void 0,
  /* 0x7C */
  RUTG,
  /* 0x7D */
  RDTG,
  /* 0x7E */
  POP,
  // actually SANGW, supposed to do only a pop though
  /* 0x7F */
  POP,
  // actually AA, supposed to do only a pop though
  /* 0x80 */
  void 0,
  // TODO FLIPPT
  /* 0x81 */
  void 0,
  // TODO FLIPRGON
  /* 0x82 */
  void 0,
  // TODO FLIPRGOFF
  /* 0x83 */
  void 0,
  /* 0x84 */
  void 0,
  /* 0x85 */
  SCANCTRL,
  /* 0x86 */
  SDPVTL.bind(void 0, 0),
  /* 0x87 */
  SDPVTL.bind(void 0, 1),
  /* 0x88 */
  GETINFO,
  /* 0x89 */
  void 0,
  // TODO IDEF
  /* 0x8A */
  ROLL,
  /* 0x8B */
  MAX,
  /* 0x8C */
  MIN,
  /* 0x8D */
  SCANTYPE,
  /* 0x8E */
  INSTCTRL,
  /* 0x8F */
  void 0,
  /* 0x90 */
  void 0,
  /* 0x91 */
  void 0,
  /* 0x92 */
  void 0,
  /* 0x93 */
  void 0,
  /* 0x94 */
  void 0,
  /* 0x95 */
  void 0,
  /* 0x96 */
  void 0,
  /* 0x97 */
  void 0,
  /* 0x98 */
  void 0,
  /* 0x99 */
  void 0,
  /* 0x9A */
  void 0,
  /* 0x9B */
  void 0,
  /* 0x9C */
  void 0,
  /* 0x9D */
  void 0,
  /* 0x9E */
  void 0,
  /* 0x9F */
  void 0,
  /* 0xA0 */
  void 0,
  /* 0xA1 */
  void 0,
  /* 0xA2 */
  void 0,
  /* 0xA3 */
  void 0,
  /* 0xA4 */
  void 0,
  /* 0xA5 */
  void 0,
  /* 0xA6 */
  void 0,
  /* 0xA7 */
  void 0,
  /* 0xA8 */
  void 0,
  /* 0xA9 */
  void 0,
  /* 0xAA */
  void 0,
  /* 0xAB */
  void 0,
  /* 0xAC */
  void 0,
  /* 0xAD */
  void 0,
  /* 0xAE */
  void 0,
  /* 0xAF */
  void 0,
  /* 0xB0 */
  PUSHB.bind(void 0, 1),
  /* 0xB1 */
  PUSHB.bind(void 0, 2),
  /* 0xB2 */
  PUSHB.bind(void 0, 3),
  /* 0xB3 */
  PUSHB.bind(void 0, 4),
  /* 0xB4 */
  PUSHB.bind(void 0, 5),
  /* 0xB5 */
  PUSHB.bind(void 0, 6),
  /* 0xB6 */
  PUSHB.bind(void 0, 7),
  /* 0xB7 */
  PUSHB.bind(void 0, 8),
  /* 0xB8 */
  PUSHW.bind(void 0, 1),
  /* 0xB9 */
  PUSHW.bind(void 0, 2),
  /* 0xBA */
  PUSHW.bind(void 0, 3),
  /* 0xBB */
  PUSHW.bind(void 0, 4),
  /* 0xBC */
  PUSHW.bind(void 0, 5),
  /* 0xBD */
  PUSHW.bind(void 0, 6),
  /* 0xBE */
  PUSHW.bind(void 0, 7),
  /* 0xBF */
  PUSHW.bind(void 0, 8),
  /* 0xC0 */
  MDRP_MIRP.bind(void 0, 0, 0, 0, 0, 0),
  /* 0xC1 */
  MDRP_MIRP.bind(void 0, 0, 0, 0, 0, 1),
  /* 0xC2 */
  MDRP_MIRP.bind(void 0, 0, 0, 0, 0, 2),
  /* 0xC3 */
  MDRP_MIRP.bind(void 0, 0, 0, 0, 0, 3),
  /* 0xC4 */
  MDRP_MIRP.bind(void 0, 0, 0, 0, 1, 0),
  /* 0xC5 */
  MDRP_MIRP.bind(void 0, 0, 0, 0, 1, 1),
  /* 0xC6 */
  MDRP_MIRP.bind(void 0, 0, 0, 0, 1, 2),
  /* 0xC7 */
  MDRP_MIRP.bind(void 0, 0, 0, 0, 1, 3),
  /* 0xC8 */
  MDRP_MIRP.bind(void 0, 0, 0, 1, 0, 0),
  /* 0xC9 */
  MDRP_MIRP.bind(void 0, 0, 0, 1, 0, 1),
  /* 0xCA */
  MDRP_MIRP.bind(void 0, 0, 0, 1, 0, 2),
  /* 0xCB */
  MDRP_MIRP.bind(void 0, 0, 0, 1, 0, 3),
  /* 0xCC */
  MDRP_MIRP.bind(void 0, 0, 0, 1, 1, 0),
  /* 0xCD */
  MDRP_MIRP.bind(void 0, 0, 0, 1, 1, 1),
  /* 0xCE */
  MDRP_MIRP.bind(void 0, 0, 0, 1, 1, 2),
  /* 0xCF */
  MDRP_MIRP.bind(void 0, 0, 0, 1, 1, 3),
  /* 0xD0 */
  MDRP_MIRP.bind(void 0, 0, 1, 0, 0, 0),
  /* 0xD1 */
  MDRP_MIRP.bind(void 0, 0, 1, 0, 0, 1),
  /* 0xD2 */
  MDRP_MIRP.bind(void 0, 0, 1, 0, 0, 2),
  /* 0xD3 */
  MDRP_MIRP.bind(void 0, 0, 1, 0, 0, 3),
  /* 0xD4 */
  MDRP_MIRP.bind(void 0, 0, 1, 0, 1, 0),
  /* 0xD5 */
  MDRP_MIRP.bind(void 0, 0, 1, 0, 1, 1),
  /* 0xD6 */
  MDRP_MIRP.bind(void 0, 0, 1, 0, 1, 2),
  /* 0xD7 */
  MDRP_MIRP.bind(void 0, 0, 1, 0, 1, 3),
  /* 0xD8 */
  MDRP_MIRP.bind(void 0, 0, 1, 1, 0, 0),
  /* 0xD9 */
  MDRP_MIRP.bind(void 0, 0, 1, 1, 0, 1),
  /* 0xDA */
  MDRP_MIRP.bind(void 0, 0, 1, 1, 0, 2),
  /* 0xDB */
  MDRP_MIRP.bind(void 0, 0, 1, 1, 0, 3),
  /* 0xDC */
  MDRP_MIRP.bind(void 0, 0, 1, 1, 1, 0),
  /* 0xDD */
  MDRP_MIRP.bind(void 0, 0, 1, 1, 1, 1),
  /* 0xDE */
  MDRP_MIRP.bind(void 0, 0, 1, 1, 1, 2),
  /* 0xDF */
  MDRP_MIRP.bind(void 0, 0, 1, 1, 1, 3),
  /* 0xE0 */
  MDRP_MIRP.bind(void 0, 1, 0, 0, 0, 0),
  /* 0xE1 */
  MDRP_MIRP.bind(void 0, 1, 0, 0, 0, 1),
  /* 0xE2 */
  MDRP_MIRP.bind(void 0, 1, 0, 0, 0, 2),
  /* 0xE3 */
  MDRP_MIRP.bind(void 0, 1, 0, 0, 0, 3),
  /* 0xE4 */
  MDRP_MIRP.bind(void 0, 1, 0, 0, 1, 0),
  /* 0xE5 */
  MDRP_MIRP.bind(void 0, 1, 0, 0, 1, 1),
  /* 0xE6 */
  MDRP_MIRP.bind(void 0, 1, 0, 0, 1, 2),
  /* 0xE7 */
  MDRP_MIRP.bind(void 0, 1, 0, 0, 1, 3),
  /* 0xE8 */
  MDRP_MIRP.bind(void 0, 1, 0, 1, 0, 0),
  /* 0xE9 */
  MDRP_MIRP.bind(void 0, 1, 0, 1, 0, 1),
  /* 0xEA */
  MDRP_MIRP.bind(void 0, 1, 0, 1, 0, 2),
  /* 0xEB */
  MDRP_MIRP.bind(void 0, 1, 0, 1, 0, 3),
  /* 0xEC */
  MDRP_MIRP.bind(void 0, 1, 0, 1, 1, 0),
  /* 0xED */
  MDRP_MIRP.bind(void 0, 1, 0, 1, 1, 1),
  /* 0xEE */
  MDRP_MIRP.bind(void 0, 1, 0, 1, 1, 2),
  /* 0xEF */
  MDRP_MIRP.bind(void 0, 1, 0, 1, 1, 3),
  /* 0xF0 */
  MDRP_MIRP.bind(void 0, 1, 1, 0, 0, 0),
  /* 0xF1 */
  MDRP_MIRP.bind(void 0, 1, 1, 0, 0, 1),
  /* 0xF2 */
  MDRP_MIRP.bind(void 0, 1, 1, 0, 0, 2),
  /* 0xF3 */
  MDRP_MIRP.bind(void 0, 1, 1, 0, 0, 3),
  /* 0xF4 */
  MDRP_MIRP.bind(void 0, 1, 1, 0, 1, 0),
  /* 0xF5 */
  MDRP_MIRP.bind(void 0, 1, 1, 0, 1, 1),
  /* 0xF6 */
  MDRP_MIRP.bind(void 0, 1, 1, 0, 1, 2),
  /* 0xF7 */
  MDRP_MIRP.bind(void 0, 1, 1, 0, 1, 3),
  /* 0xF8 */
  MDRP_MIRP.bind(void 0, 1, 1, 1, 0, 0),
  /* 0xF9 */
  MDRP_MIRP.bind(void 0, 1, 1, 1, 0, 1),
  /* 0xFA */
  MDRP_MIRP.bind(void 0, 1, 1, 1, 0, 2),
  /* 0xFB */
  MDRP_MIRP.bind(void 0, 1, 1, 1, 0, 3),
  /* 0xFC */
  MDRP_MIRP.bind(void 0, 1, 1, 1, 1, 0),
  /* 0xFD */
  MDRP_MIRP.bind(void 0, 1, 1, 1, 1, 1),
  /* 0xFE */
  MDRP_MIRP.bind(void 0, 1, 1, 1, 1, 2),
  /* 0xFF */
  MDRP_MIRP.bind(void 0, 1, 1, 1, 1, 3)
];
function Token(char) {
  this.char = char;
  this.state = {};
  this.activeState = null;
}
function ContextRange(startIndex, endOffset, contextName) {
  this.contextName = contextName;
  this.startIndex = startIndex;
  this.endOffset = endOffset;
}
function ContextChecker(contextName, checkStart, checkEnd) {
  this.contextName = contextName;
  this.openRange = null;
  this.ranges = [];
  this.checkStart = checkStart;
  this.checkEnd = checkEnd;
}
function ContextParams(context, currentIndex) {
  this.context = context;
  this.index = currentIndex;
  this.length = context.length;
  this.current = context[currentIndex];
  this.backtrack = context.slice(0, currentIndex);
  this.lookahead = context.slice(currentIndex + 1);
}
function Event(eventId) {
  this.eventId = eventId;
  this.subscribers = [];
}
function initializeCoreEvents(events) {
  var this$1 = this;
  var coreEvents = [
    "start",
    "end",
    "next",
    "newToken",
    "contextStart",
    "contextEnd",
    "insertToken",
    "removeToken",
    "removeRange",
    "replaceToken",
    "replaceRange",
    "composeRUD",
    "updateContextsRanges"
  ];
  coreEvents.forEach(function(eventId) {
    Object.defineProperty(this$1.events, eventId, {
      value: new Event(eventId)
    });
  });
  if (!!events) {
    coreEvents.forEach(function(eventId) {
      var event = events[eventId];
      if (typeof event === "function") {
        this$1.events[eventId].subscribe(event);
      }
    });
  }
  var requiresContextUpdate = [
    "insertToken",
    "removeToken",
    "removeRange",
    "replaceToken",
    "replaceRange",
    "composeRUD"
  ];
  requiresContextUpdate.forEach(function(eventId) {
    this$1.events[eventId].subscribe(
      this$1.updateContextsRanges
    );
  });
}
function Tokenizer(events) {
  this.tokens = [];
  this.registeredContexts = {};
  this.contextCheckers = [];
  this.events = {};
  this.registeredModifiers = [];
  initializeCoreEvents.call(this, events);
}
Token.prototype.setState = function(key2, value2) {
  this.state[key2] = value2;
  this.activeState = { key: key2, value: this.state[key2] };
  return this.activeState;
};
Token.prototype.getState = function(stateId) {
  return this.state[stateId] || null;
};
Tokenizer.prototype.inboundIndex = function(index2) {
  return index2 >= 0 && index2 < this.tokens.length;
};
Tokenizer.prototype.composeRUD = function(RUDs) {
  var this$1 = this;
  var silent = true;
  var state = RUDs.map(function(RUD) {
    return this$1[RUD[0]].apply(this$1, RUD.slice(1).concat(silent));
  });
  var hasFAILObject = function(obj) {
    return typeof obj === "object" && obj.hasOwnProperty("FAIL");
  };
  if (state.every(hasFAILObject)) {
    return {
      FAIL: "composeRUD: one or more operations hasn't completed successfully",
      report: state.filter(hasFAILObject)
    };
  }
  this.dispatch("composeRUD", [state.filter(function(op) {
    return !hasFAILObject(op);
  })]);
};
Tokenizer.prototype.replaceRange = function(startIndex, offset, tokens, silent) {
  offset = offset !== null ? offset : this.tokens.length;
  var isTokenType = tokens.every(function(token) {
    return token instanceof Token;
  });
  if (!isNaN(startIndex) && this.inboundIndex(startIndex) && isTokenType) {
    var replaced = this.tokens.splice.apply(
      this.tokens,
      [startIndex, offset].concat(tokens)
    );
    if (!silent) {
      this.dispatch("replaceToken", [startIndex, offset, tokens]);
    }
    return [replaced, tokens];
  } else {
    return { FAIL: "replaceRange: invalid tokens or startIndex." };
  }
};
Tokenizer.prototype.replaceToken = function(index2, token, silent) {
  if (!isNaN(index2) && this.inboundIndex(index2) && token instanceof Token) {
    var replaced = this.tokens.splice(index2, 1, token);
    if (!silent) {
      this.dispatch("replaceToken", [index2, token]);
    }
    return [replaced[0], token];
  } else {
    return { FAIL: "replaceToken: invalid token or index." };
  }
};
Tokenizer.prototype.removeRange = function(startIndex, offset, silent) {
  offset = !isNaN(offset) ? offset : this.tokens.length;
  var tokens = this.tokens.splice(startIndex, offset);
  if (!silent) {
    this.dispatch("removeRange", [tokens, startIndex, offset]);
  }
  return tokens;
};
Tokenizer.prototype.removeToken = function(index2, silent) {
  if (!isNaN(index2) && this.inboundIndex(index2)) {
    var token = this.tokens.splice(index2, 1);
    if (!silent) {
      this.dispatch("removeToken", [token, index2]);
    }
    return token;
  } else {
    return { FAIL: "removeToken: invalid token index." };
  }
};
Tokenizer.prototype.insertToken = function(tokens, index2, silent) {
  var tokenType = tokens.every(
    function(token) {
      return token instanceof Token;
    }
  );
  if (tokenType) {
    this.tokens.splice.apply(
      this.tokens,
      [index2, 0].concat(tokens)
    );
    if (!silent) {
      this.dispatch("insertToken", [tokens, index2]);
    }
    return tokens;
  } else {
    return { FAIL: "insertToken: invalid token(s)." };
  }
};
Tokenizer.prototype.registerModifier = function(modifierId, condition, modifier) {
  this.events.newToken.subscribe(function(token, contextParams) {
    var conditionParams = [token, contextParams];
    var canApplyModifier = condition === null || condition.apply(this, conditionParams) === true;
    var modifierParams = [token, contextParams];
    if (canApplyModifier) {
      var newStateValue = modifier.apply(this, modifierParams);
      token.setState(modifierId, newStateValue);
    }
  });
  this.registeredModifiers.push(modifierId);
};
Event.prototype.subscribe = function(eventHandler) {
  if (typeof eventHandler === "function") {
    return this.subscribers.push(eventHandler) - 1;
  } else {
    return { FAIL: "invalid '" + this.eventId + "' event handler" };
  }
};
Event.prototype.unsubscribe = function(subsId) {
  this.subscribers.splice(subsId, 1);
};
ContextParams.prototype.setCurrentIndex = function(index2) {
  this.index = index2;
  this.current = this.context[index2];
  this.backtrack = this.context.slice(0, index2);
  this.lookahead = this.context.slice(index2 + 1);
};
ContextParams.prototype.get = function(offset) {
  switch (true) {
    case offset === 0:
      return this.current;
    case (offset < 0 && Math.abs(offset) <= this.backtrack.length):
      return this.backtrack.slice(offset)[0];
    case (offset > 0 && offset <= this.lookahead.length):
      return this.lookahead[offset - 1];
    default:
      return null;
  }
};
Tokenizer.prototype.rangeToText = function(range) {
  if (range instanceof ContextRange) {
    return this.getRangeTokens(range).map(function(token) {
      return token.char;
    }).join("");
  }
};
Tokenizer.prototype.getText = function() {
  return this.tokens.map(function(token) {
    return token.char;
  }).join("");
};
Tokenizer.prototype.getContext = function(contextName) {
  var context = this.registeredContexts[contextName];
  return !!context ? context : null;
};
Tokenizer.prototype.on = function(eventName, eventHandler) {
  var event = this.events[eventName];
  if (!!event) {
    return event.subscribe(eventHandler);
  } else {
    return null;
  }
};
Tokenizer.prototype.dispatch = function(eventName, args) {
  var this$1 = this;
  var event = this.events[eventName];
  if (event instanceof Event) {
    event.subscribers.forEach(function(subscriber) {
      subscriber.apply(this$1, args || []);
    });
  }
};
Tokenizer.prototype.registerContextChecker = function(contextName, contextStartCheck, contextEndCheck) {
  if (!!this.getContext(contextName)) {
    return {
      FAIL: "context name '" + contextName + "' is already registered."
    };
  }
  if (typeof contextStartCheck !== "function") {
    return {
      FAIL: "missing context start check."
    };
  }
  if (typeof contextEndCheck !== "function") {
    return {
      FAIL: "missing context end check."
    };
  }
  var contextCheckers = new ContextChecker(
    contextName,
    contextStartCheck,
    contextEndCheck
  );
  this.registeredContexts[contextName] = contextCheckers;
  this.contextCheckers.push(contextCheckers);
  return contextCheckers;
};
Tokenizer.prototype.getRangeTokens = function(range) {
  var endIndex = range.startIndex + range.endOffset;
  return [].concat(
    this.tokens.slice(range.startIndex, endIndex)
  );
};
Tokenizer.prototype.getContextRanges = function(contextName) {
  var context = this.getContext(contextName);
  if (!!context) {
    return context.ranges;
  } else {
    return { FAIL: "context checker '" + contextName + "' is not registered." };
  }
};
Tokenizer.prototype.resetContextsRanges = function() {
  var registeredContexts = this.registeredContexts;
  for (var contextName in registeredContexts) {
    if (registeredContexts.hasOwnProperty(contextName)) {
      var context = registeredContexts[contextName];
      context.ranges = [];
    }
  }
};
Tokenizer.prototype.updateContextsRanges = function() {
  this.resetContextsRanges();
  var chars = this.tokens.map(function(token) {
    return token.char;
  });
  for (var i = 0; i < chars.length; i++) {
    var contextParams = new ContextParams(chars, i);
    this.runContextCheck(contextParams);
  }
  this.dispatch("updateContextsRanges", [this.registeredContexts]);
};
Tokenizer.prototype.setEndOffset = function(offset, contextName) {
  var startIndex = this.getContext(contextName).openRange.startIndex;
  var range = new ContextRange(startIndex, offset, contextName);
  var ranges = this.getContext(contextName).ranges;
  range.rangeId = contextName + "." + ranges.length;
  ranges.push(range);
  this.getContext(contextName).openRange = null;
  return range;
};
Tokenizer.prototype.runContextCheck = function(contextParams) {
  var this$1 = this;
  var index2 = contextParams.index;
  this.contextCheckers.forEach(function(contextChecker) {
    var contextName = contextChecker.contextName;
    var openRange = this$1.getContext(contextName).openRange;
    if (!openRange && contextChecker.checkStart(contextParams)) {
      openRange = new ContextRange(index2, null, contextName);
      this$1.getContext(contextName).openRange = openRange;
      this$1.dispatch("contextStart", [contextName, index2]);
    }
    if (!!openRange && contextChecker.checkEnd(contextParams)) {
      var offset = index2 - openRange.startIndex + 1;
      var range = this$1.setEndOffset(offset, contextName);
      this$1.dispatch("contextEnd", [contextName, range]);
    }
  });
};
Tokenizer.prototype.tokenize = function(text2) {
  this.tokens = [];
  this.resetContextsRanges();
  var chars = Array.from(text2);
  this.dispatch("start");
  for (var i = 0; i < chars.length; i++) {
    var char = chars[i];
    var contextParams = new ContextParams(chars, i);
    this.dispatch("next", [contextParams]);
    this.runContextCheck(contextParams);
    var token = new Token(char);
    this.tokens.push(token);
    this.dispatch("newToken", [token, contextParams]);
  }
  this.dispatch("end", [this.tokens]);
  return this.tokens;
};
function isArabicChar(c2) {
  return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c2);
}
function isIsolatedArabicChar(char) {
  return /[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char);
}
function isTashkeelArabicChar(char) {
  return /[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char);
}
function isLatinChar(c2) {
  return /[A-z]/.test(c2);
}
function isWhiteSpace(c2) {
  return /\s/.test(c2);
}
function FeatureQuery(font) {
  this.font = font;
  this.features = {};
}
function SubstitutionAction(action) {
  this.id = action.id;
  this.tag = action.tag;
  this.substitution = action.substitution;
}
function lookupCoverage(glyphIndex, coverage) {
  if (!glyphIndex) {
    return -1;
  }
  switch (coverage.format) {
    case 1:
      return coverage.glyphs.indexOf(glyphIndex);
    case 2:
      var ranges = coverage.ranges;
      for (var i = 0; i < ranges.length; i++) {
        var range = ranges[i];
        if (glyphIndex >= range.start && glyphIndex <= range.end) {
          var offset = glyphIndex - range.start;
          return range.index + offset;
        }
      }
      break;
    default:
      return -1;
  }
  return -1;
}
function singleSubstitutionFormat1(glyphIndex, subtable) {
  var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage);
  if (substituteIndex === -1) {
    return null;
  }
  return glyphIndex + subtable.deltaGlyphId;
}
function singleSubstitutionFormat2(glyphIndex, subtable) {
  var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage);
  if (substituteIndex === -1) {
    return null;
  }
  return subtable.substitute[substituteIndex];
}
function lookupCoverageList(coverageList, contextParams) {
  var lookupList = [];
  for (var i = 0; i < coverageList.length; i++) {
    var coverage = coverageList[i];
    var glyphIndex = contextParams.current;
    glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex;
    var lookupIndex = lookupCoverage(glyphIndex, coverage);
    if (lookupIndex !== -1) {
      lookupList.push(lookupIndex);
    }
  }
  if (lookupList.length !== coverageList.length) {
    return -1;
  }
  return lookupList;
}
function chainingSubstitutionFormat3(contextParams, subtable) {
  var lookupsCount = subtable.inputCoverage.length + subtable.lookaheadCoverage.length + subtable.backtrackCoverage.length;
  if (contextParams.context.length < lookupsCount) {
    return [];
  }
  var inputLookups = lookupCoverageList(
    subtable.inputCoverage,
    contextParams
  );
  if (inputLookups === -1) {
    return [];
  }
  var lookaheadOffset = subtable.inputCoverage.length - 1;
  if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) {
    return [];
  }
  var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset);
  while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) {
    lookaheadContext.shift();
  }
  var lookaheadParams = new ContextParams(lookaheadContext, 0);
  var lookaheadLookups = lookupCoverageList(
    subtable.lookaheadCoverage,
    lookaheadParams
  );
  var backtrackContext = [].concat(contextParams.backtrack);
  backtrackContext.reverse();
  while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) {
    backtrackContext.shift();
  }
  if (backtrackContext.length < subtable.backtrackCoverage.length) {
    return [];
  }
  var backtrackParams = new ContextParams(backtrackContext, 0);
  var backtrackLookups = lookupCoverageList(
    subtable.backtrackCoverage,
    backtrackParams
  );
  var contextRulesMatch = inputLookups.length === subtable.inputCoverage.length && lookaheadLookups.length === subtable.lookaheadCoverage.length && backtrackLookups.length === subtable.backtrackCoverage.length;
  var substitutions = [];
  if (contextRulesMatch) {
    for (var i = 0; i < subtable.lookupRecords.length; i++) {
      var lookupRecord = subtable.lookupRecords[i];
      var lookupListIndex = lookupRecord.lookupListIndex;
      var lookupTable = this.getLookupByIndex(lookupListIndex);
      for (var s = 0; s < lookupTable.subtables.length; s++) {
        var subtable$1 = lookupTable.subtables[s];
        var lookup = this.getLookupMethod(lookupTable, subtable$1);
        var substitutionType = this.getSubstitutionType(lookupTable, subtable$1);
        if (substitutionType === "12") {
          for (var n2 = 0; n2 < inputLookups.length; n2++) {
            var glyphIndex = contextParams.get(n2);
            var substitution = lookup(glyphIndex);
            if (substitution) {
              substitutions.push(substitution);
            }
          }
        }
      }
    }
  }
  return substitutions;
}
function ligatureSubstitutionFormat1(contextParams, subtable) {
  var glyphIndex = contextParams.current;
  var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage);
  if (ligSetIndex === -1) {
    return null;
  }
  var ligature;
  var ligatureSet = subtable.ligatureSets[ligSetIndex];
  for (var s = 0; s < ligatureSet.length; s++) {
    ligature = ligatureSet[s];
    for (var l2 = 0; l2 < ligature.components.length; l2++) {
      var lookaheadItem = contextParams.lookahead[l2];
      var component = ligature.components[l2];
      if (lookaheadItem !== component) {
        break;
      }
      if (l2 === ligature.components.length - 1) {
        return ligature;
      }
    }
  }
  return null;
}
function decompositionSubstitutionFormat1(glyphIndex, subtable) {
  var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage);
  if (substituteIndex === -1) {
    return null;
  }
  return subtable.sequences[substituteIndex];
}
FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function() {
  var scripts = this.font.tables.gsub.scripts;
  for (var s = 0; s < scripts.length; s++) {
    var script = scripts[s];
    if (script.tag === "DFLT") {
      return script.script.defaultLangSys.featureIndexes;
    }
  }
  return [];
};
FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) {
  var tables = this.font.tables;
  if (!tables.gsub) {
    return [];
  }
  if (!scriptTag) {
    return this.getDefaultScriptFeaturesIndexes();
  }
  var scripts = this.font.tables.gsub.scripts;
  for (var i = 0; i < scripts.length; i++) {
    var script = scripts[i];
    if (script.tag === scriptTag && script.script.defaultLangSys) {
      return script.script.defaultLangSys.featureIndexes;
    } else {
      var langSysRecords = script.langSysRecords;
      if (!!langSysRecords) {
        for (var j2 = 0; j2 < langSysRecords.length; j2++) {
          var langSysRecord = langSysRecords[j2];
          if (langSysRecord.tag === scriptTag) {
            var langSys = langSysRecord.langSys;
            return langSys.featureIndexes;
          }
        }
      }
    }
  }
  return this.getDefaultScriptFeaturesIndexes();
};
FeatureQuery.prototype.mapTagsToFeatures = function(features, scriptTag) {
  var tags = {};
  for (var i = 0; i < features.length; i++) {
    var tag = features[i].tag;
    var feature = features[i].feature;
    tags[tag] = feature;
  }
  this.features[scriptTag].tags = tags;
};
FeatureQuery.prototype.getScriptFeatures = function(scriptTag) {
  var features = this.features[scriptTag];
  if (this.features.hasOwnProperty(scriptTag)) {
    return features;
  }
  var featuresIndexes = this.getScriptFeaturesIndexes(scriptTag);
  if (!featuresIndexes) {
    return null;
  }
  var gsub2 = this.font.tables.gsub;
  features = featuresIndexes.map(function(index2) {
    return gsub2.features[index2];
  });
  this.features[scriptTag] = features;
  this.mapTagsToFeatures(features, scriptTag);
  return features;
};
FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) {
  var lookupType = lookupTable.lookupType.toString();
  var substFormat = subtable.substFormat.toString();
  return lookupType + substFormat;
};
FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) {
  var this$1 = this;
  var substitutionType = this.getSubstitutionType(lookupTable, subtable);
  switch (substitutionType) {
    case "11":
      return function(glyphIndex) {
        return singleSubstitutionFormat1.apply(
          this$1,
          [glyphIndex, subtable]
        );
      };
    case "12":
      return function(glyphIndex) {
        return singleSubstitutionFormat2.apply(
          this$1,
          [glyphIndex, subtable]
        );
      };
    case "63":
      return function(contextParams) {
        return chainingSubstitutionFormat3.apply(
          this$1,
          [contextParams, subtable]
        );
      };
    case "41":
      return function(contextParams) {
        return ligatureSubstitutionFormat1.apply(
          this$1,
          [contextParams, subtable]
        );
      };
    case "21":
      return function(glyphIndex) {
        return decompositionSubstitutionFormat1.apply(
          this$1,
          [glyphIndex, subtable]
        );
      };
    default:
      throw new Error(
        "lookupType: " + lookupTable.lookupType + " - substFormat: " + subtable.substFormat + " is not yet supported"
      );
  }
};
FeatureQuery.prototype.lookupFeature = function(query) {
  var contextParams = query.contextParams;
  var currentIndex = contextParams.index;
  var feature = this.getFeature({
    tag: query.tag,
    script: query.script
  });
  if (!feature) {
    return new Error(
      "font '" + this.font.names.fullName.en + "' doesn't support feature '" + query.tag + "' for script '" + query.script + "'."
    );
  }
  var lookups = this.getFeatureLookups(feature);
  var substitutions = [].concat(contextParams.context);
  for (var l2 = 0; l2 < lookups.length; l2++) {
    var lookupTable = lookups[l2];
    var subtables = this.getLookupSubtables(lookupTable);
    for (var s = 0; s < subtables.length; s++) {
      var subtable = subtables[s];
      var substType = this.getSubstitutionType(lookupTable, subtable);
      var lookup = this.getLookupMethod(lookupTable, subtable);
      var substitution = void 0;
      switch (substType) {
        case "11":
          substitution = lookup(contextParams.current);
          if (substitution) {
            substitutions.splice(currentIndex, 1, new SubstitutionAction({
              id: 11,
              tag: query.tag,
              substitution
            }));
          }
          break;
        case "12":
          substitution = lookup(contextParams.current);
          if (substitution) {
            substitutions.splice(currentIndex, 1, new SubstitutionAction({
              id: 12,
              tag: query.tag,
              substitution
            }));
          }
          break;
        case "63":
          substitution = lookup(contextParams);
          if (Array.isArray(substitution) && substitution.length) {
            substitutions.splice(currentIndex, 1, new SubstitutionAction({
              id: 63,
              tag: query.tag,
              substitution
            }));
          }
          break;
        case "41":
          substitution = lookup(contextParams);
          if (substitution) {
            substitutions.splice(currentIndex, 1, new SubstitutionAction({
              id: 41,
              tag: query.tag,
              substitution
            }));
          }
          break;
        case "21":
          substitution = lookup(contextParams.current);
          if (substitution) {
            substitutions.splice(currentIndex, 1, new SubstitutionAction({
              id: 21,
              tag: query.tag,
              substitution
            }));
          }
          break;
      }
      contextParams = new ContextParams(substitutions, currentIndex);
      if (Array.isArray(substitution) && !substitution.length) {
        continue;
      }
      substitution = null;
    }
  }
  return substitutions.length ? substitutions : null;
};
FeatureQuery.prototype.supports = function(query) {
  if (!query.script) {
    return false;
  }
  this.getScriptFeatures(query.script);
  var supportedScript = this.features.hasOwnProperty(query.script);
  if (!query.tag) {
    return supportedScript;
  }
  var supportedFeature = this.features[query.script].some(function(feature) {
    return feature.tag === query.tag;
  });
  return supportedScript && supportedFeature;
};
FeatureQuery.prototype.getLookupSubtables = function(lookupTable) {
  return lookupTable.subtables || null;
};
FeatureQuery.prototype.getLookupByIndex = function(index2) {
  var lookups = this.font.tables.gsub.lookups;
  return lookups[index2] || null;
};
FeatureQuery.prototype.getFeatureLookups = function(feature) {
  return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this));
};
FeatureQuery.prototype.getFeature = function getFeature(query) {
  if (!this.font) {
    return { FAIL: "No font was found" };
  }
  if (!this.features.hasOwnProperty(query.script)) {
    this.getScriptFeatures(query.script);
  }
  var scriptFeatures = this.features[query.script];
  if (!scriptFeatures) {
    return { FAIL: "No feature for script " + query.script };
  }
  if (!scriptFeatures.tags[query.tag]) {
    return null;
  }
  return this.features[query.script].tags[query.tag];
};
function arabicWordStartCheck(contextParams) {
  var char = contextParams.current;
  var prevChar = contextParams.get(-1);
  return (
    // ? arabic first char
    prevChar === null && isArabicChar(char) || // ? arabic char preceded with a non arabic char
    !isArabicChar(prevChar) && isArabicChar(char)
  );
}
function arabicWordEndCheck(contextParams) {
  var nextChar = contextParams.get(1);
  return (
    // ? last arabic char
    nextChar === null || // ? next char is not arabic
    !isArabicChar(nextChar)
  );
}
var arabicWordCheck = {
  startCheck: arabicWordStartCheck,
  endCheck: arabicWordEndCheck
};
function arabicSentenceStartCheck(contextParams) {
  var char = contextParams.current;
  var prevChar = contextParams.get(-1);
  return (
    // ? an arabic char preceded with a non arabic char
    (isArabicChar(char) || isTashkeelArabicChar(char)) && !isArabicChar(prevChar)
  );
}
function arabicSentenceEndCheck(contextParams) {
  var nextChar = contextParams.get(1);
  switch (true) {
    case nextChar === null:
      return true;
    case (!isArabicChar(nextChar) && !isTashkeelArabicChar(nextChar)):
      var nextIsWhitespace = isWhiteSpace(nextChar);
      if (!nextIsWhitespace) {
        return true;
      }
      if (nextIsWhitespace) {
        var arabicCharAhead = false;
        arabicCharAhead = contextParams.lookahead.some(
          function(c2) {
            return isArabicChar(c2) || isTashkeelArabicChar(c2);
          }
        );
        if (!arabicCharAhead) {
          return true;
        }
      }
      break;
    default:
      return false;
  }
}
var arabicSentenceCheck = {
  startCheck: arabicSentenceStartCheck,
  endCheck: arabicSentenceEndCheck
};
function singleSubstitutionFormat1$1(action, tokens, index2) {
  tokens[index2].setState(action.tag, action.substitution);
}
function singleSubstitutionFormat2$1(action, tokens, index2) {
  tokens[index2].setState(action.tag, action.substitution);
}
function chainingSubstitutionFormat3$1(action, tokens, index2) {
  action.substitution.forEach(function(subst, offset) {
    var token = tokens[index2 + offset];
    token.setState(action.tag, subst);
  });
}
function ligatureSubstitutionFormat1$1(action, tokens, index2) {
  var token = tokens[index2];
  token.setState(action.tag, action.substitution.ligGlyph);
  var compsCount = action.substitution.components.length;
  for (var i = 0; i < compsCount; i++) {
    token = tokens[index2 + i + 1];
    token.setState("deleted", true);
  }
}
var SUBSTITUTIONS = {
  11: singleSubstitutionFormat1$1,
  12: singleSubstitutionFormat2$1,
  63: chainingSubstitutionFormat3$1,
  41: ligatureSubstitutionFormat1$1
};
function applySubstitution(action, tokens, index2) {
  if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) {
    SUBSTITUTIONS[action.id](action, tokens, index2);
  }
}
function willConnectPrev(charContextParams) {
  var backtrack = [].concat(charContextParams.backtrack);
  for (var i = backtrack.length - 1; i >= 0; i--) {
    var prevChar = backtrack[i];
    var isolated = isIsolatedArabicChar(prevChar);
    var tashkeel = isTashkeelArabicChar(prevChar);
    if (!isolated && !tashkeel) {
      return true;
    }
    if (isolated) {
      return false;
    }
  }
  return false;
}
function willConnectNext(charContextParams) {
  if (isIsolatedArabicChar(charContextParams.current)) {
    return false;
  }
  for (var i = 0; i < charContextParams.lookahead.length; i++) {
    var nextChar = charContextParams.lookahead[i];
    var tashkeel = isTashkeelArabicChar(nextChar);
    if (!tashkeel) {
      return true;
    }
  }
  return false;
}
function arabicPresentationForms(range) {
  var this$1 = this;
  var script = "arab";
  var tags = this.featuresTags[script];
  var tokens = this.tokenizer.getRangeTokens(range);
  if (tokens.length === 1) {
    return;
  }
  var contextParams = new ContextParams(
    tokens.map(
      function(token) {
        return token.getState("glyphIndex");
      }
    ),
    0
  );
  var charContextParams = new ContextParams(
    tokens.map(
      function(token) {
        return token.char;
      }
    ),
    0
  );
  tokens.forEach(function(token, index2) {
    if (isTashkeelArabicChar(token.char)) {
      return;
    }
    contextParams.setCurrentIndex(index2);
    charContextParams.setCurrentIndex(index2);
    var CONNECT = 0;
    if (willConnectPrev(charContextParams)) {
      CONNECT |= 1;
    }
    if (willConnectNext(charContextParams)) {
      CONNECT |= 2;
    }
    var tag;
    switch (CONNECT) {
      case 1:
        tag = "fina";
        break;
      case 2:
        tag = "init";
        break;
      case 3:
        tag = "medi";
        break;
    }
    if (tags.indexOf(tag) === -1) {
      return;
    }
    var substitutions = this$1.query.lookupFeature({
      tag,
      script,
      contextParams
    });
    if (substitutions instanceof Error) {
      return console.info(substitutions.message);
    }
    substitutions.forEach(function(action, index3) {
      if (action instanceof SubstitutionAction) {
        applySubstitution(action, tokens, index3);
        contextParams.context[index3] = action.substitution;
      }
    });
  });
}
function getContextParams(tokens, index2) {
  var context = tokens.map(function(token) {
    return token.activeState.value;
  });
  return new ContextParams(context, index2 || 0);
}
function arabicRequiredLigatures(range) {
  var this$1 = this;
  var script = "arab";
  var tokens = this.tokenizer.getRangeTokens(range);
  var contextParams = getContextParams(tokens);
  contextParams.context.forEach(function(glyphIndex, index2) {
    contextParams.setCurrentIndex(index2);
    var substitutions = this$1.query.lookupFeature({
      tag: "rlig",
      script,
      contextParams
    });
    if (substitutions.length) {
      substitutions.forEach(
        function(action) {
          return applySubstitution(action, tokens, index2);
        }
      );
      contextParams = getContextParams(tokens);
    }
  });
}
function latinWordStartCheck(contextParams) {
  var char = contextParams.current;
  var prevChar = contextParams.get(-1);
  return (
    // ? latin first char
    prevChar === null && isLatinChar(char) || // ? latin char preceded with a non latin char
    !isLatinChar(prevChar) && isLatinChar(char)
  );
}
function latinWordEndCheck(contextParams) {
  var nextChar = contextParams.get(1);
  return (
    // ? last latin char
    nextChar === null || // ? next char is not latin
    !isLatinChar(nextChar)
  );
}
var latinWordCheck = {
  startCheck: latinWordStartCheck,
  endCheck: latinWordEndCheck
};
function getContextParams$1(tokens, index2) {
  var context = tokens.map(function(token) {
    return token.activeState.value;
  });
  return new ContextParams(context, index2 || 0);
}
function latinLigature(range) {
  var this$1 = this;
  var script = "latn";
  var tokens = this.tokenizer.getRangeTokens(range);
  var contextParams = getContextParams$1(tokens);
  contextParams.context.forEach(function(glyphIndex, index2) {
    contextParams.setCurrentIndex(index2);
    var substitutions = this$1.query.lookupFeature({
      tag: "liga",
      script,
      contextParams
    });
    if (substitutions.length) {
      substitutions.forEach(
        function(action) {
          return applySubstitution(action, tokens, index2);
        }
      );
      contextParams = getContextParams$1(tokens);
    }
  });
}
function Bidi(baseDir) {
  this.baseDir = baseDir || "ltr";
  this.tokenizer = new Tokenizer();
  this.featuresTags = {};
}
Bidi.prototype.setText = function(text2) {
  this.text = text2;
};
Bidi.prototype.contextChecks = {
  latinWordCheck,
  arabicWordCheck,
  arabicSentenceCheck
};
function registerContextChecker(checkId) {
  var check2 = this.contextChecks[checkId + "Check"];
  return this.tokenizer.registerContextChecker(
    checkId,
    check2.startCheck,
    check2.endCheck
  );
}
function tokenizeText() {
  registerContextChecker.call(this, "latinWord");
  registerContextChecker.call(this, "arabicWord");
  registerContextChecker.call(this, "arabicSentence");
  return this.tokenizer.tokenize(this.text);
}
function reverseArabicSentences() {
  var this$1 = this;
  var ranges = this.tokenizer.getContextRanges("arabicSentence");
  ranges.forEach(function(range) {
    var rangeTokens = this$1.tokenizer.getRangeTokens(range);
    this$1.tokenizer.replaceRange(
      range.startIndex,
      range.endOffset,
      rangeTokens.reverse()
    );
  });
}
Bidi.prototype.registerFeatures = function(script, tags) {
  var this$1 = this;
  var supportedTags = tags.filter(
    function(tag) {
      return this$1.query.supports({ script, tag });
    }
  );
  if (!this.featuresTags.hasOwnProperty(script)) {
    this.featuresTags[script] = supportedTags;
  } else {
    this.featuresTags[script] = this.featuresTags[script].concat(supportedTags);
  }
};
Bidi.prototype.applyFeatures = function(font, features) {
  if (!font) {
    throw new Error(
      "No valid font was provided to apply features"
    );
  }
  if (!this.query) {
    this.query = new FeatureQuery(font);
  }
  for (var f = 0; f < features.length; f++) {
    var feature = features[f];
    if (!this.query.supports({ script: feature.script })) {
      continue;
    }
    this.registerFeatures(feature.script, feature.tags);
  }
};
Bidi.prototype.registerModifier = function(modifierId, condition, modifier) {
  this.tokenizer.registerModifier(modifierId, condition, modifier);
};
function checkGlyphIndexStatus() {
  if (this.tokenizer.registeredModifiers.indexOf("glyphIndex") === -1) {
    throw new Error(
      "glyphIndex modifier is required to apply arabic presentation features."
    );
  }
}
function applyArabicPresentationForms() {
  var this$1 = this;
  var script = "arab";
  if (!this.featuresTags.hasOwnProperty(script)) {
    return;
  }
  checkGlyphIndexStatus.call(this);
  var ranges = this.tokenizer.getContextRanges("arabicWord");
  ranges.forEach(function(range) {
    arabicPresentationForms.call(this$1, range);
  });
}
function applyArabicRequireLigatures() {
  var this$1 = this;
  var script = "arab";
  if (!this.featuresTags.hasOwnProperty(script)) {
    return;
  }
  var tags = this.featuresTags[script];
  if (tags.indexOf("rlig") === -1) {
    return;
  }
  checkGlyphIndexStatus.call(this);
  var ranges = this.tokenizer.getContextRanges("arabicWord");
  ranges.forEach(function(range) {
    arabicRequiredLigatures.call(this$1, range);
  });
}
function applyLatinLigatures() {
  var this$1 = this;
  var script = "latn";
  if (!this.featuresTags.hasOwnProperty(script)) {
    return;
  }
  var tags = this.featuresTags[script];
  if (tags.indexOf("liga") === -1) {
    return;
  }
  checkGlyphIndexStatus.call(this);
  var ranges = this.tokenizer.getContextRanges("latinWord");
  ranges.forEach(function(range) {
    latinLigature.call(this$1, range);
  });
}
Bidi.prototype.checkContextReady = function(contextId) {
  return !!this.tokenizer.getContext(contextId);
};
Bidi.prototype.applyFeaturesToContexts = function() {
  if (this.checkContextReady("arabicWord")) {
    applyArabicPresentationForms.call(this);
    applyArabicRequireLigatures.call(this);
  }
  if (this.checkContextReady("latinWord")) {
    applyLatinLigatures.call(this);
  }
  if (this.checkContextReady("arabicSentence")) {
    reverseArabicSentences.call(this);
  }
};
Bidi.prototype.processText = function(text2) {
  if (!this.text || this.text !== text2) {
    this.setText(text2);
    tokenizeText.call(this);
    this.applyFeaturesToContexts();
  }
};
Bidi.prototype.getBidiText = function(text2) {
  this.processText(text2);
  return this.tokenizer.getText();
};
Bidi.prototype.getTextGlyphs = function(text2) {
  this.processText(text2);
  var indexes = [];
  for (var i = 0; i < this.tokenizer.tokens.length; i++) {
    var token = this.tokenizer.tokens[i];
    if (token.state.deleted) {
      continue;
    }
    var index2 = token.activeState.value;
    indexes.push(Array.isArray(index2) ? index2[0] : index2);
  }
  return indexes;
};
function Font2(options) {
  options = options || {};
  options.tables = options.tables || {};
  if (!options.empty) {
    checkArgument(options.familyName, "When creating a new Font object, familyName is required.");
    checkArgument(options.styleName, "When creating a new Font object, styleName is required.");
    checkArgument(options.unitsPerEm, "When creating a new Font object, unitsPerEm is required.");
    checkArgument(options.ascender, "When creating a new Font object, ascender is required.");
    checkArgument(options.descender <= 0, "When creating a new Font object, negative descender value is required.");
    this.names = {
      fontFamily: { en: options.familyName || " " },
      fontSubfamily: { en: options.styleName || " " },
      fullName: { en: options.fullName || options.familyName + " " + options.styleName },
      // postScriptName may not contain any whitespace
      postScriptName: { en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, "") },
      designer: { en: options.designer || " " },
      designerURL: { en: options.designerURL || " " },
      manufacturer: { en: options.manufacturer || " " },
      manufacturerURL: { en: options.manufacturerURL || " " },
      license: { en: options.license || " " },
      licenseURL: { en: options.licenseURL || " " },
      version: { en: options.version || "Version 0.1" },
      description: { en: options.description || " " },
      copyright: { en: options.copyright || " " },
      trademark: { en: options.trademark || " " }
    };
    this.unitsPerEm = options.unitsPerEm || 1e3;
    this.ascender = options.ascender;
    this.descender = options.descender;
    this.createdTimestamp = options.createdTimestamp;
    this.tables = Object.assign(options.tables, {
      os2: Object.assign({
        usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM,
        usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM,
        fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR
      }, options.tables.os2)
    });
  }
  this.supported = true;
  this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []);
  this.encoding = new DefaultEncoding(this);
  this.position = new Position(this);
  this.substitution = new Substitution(this);
  this.tables = this.tables || {};
  this._push = null;
  this._hmtxTableData = {};
  Object.defineProperty(this, "hinting", {
    get: function() {
      if (this._hinting) {
        return this._hinting;
      }
      if (this.outlinesFormat === "truetype") {
        return this._hinting = new Hinting(this);
      }
    }
  });
}
Font2.prototype.hasChar = function(c2) {
  return this.encoding.charToGlyphIndex(c2) !== null;
};
Font2.prototype.charToGlyphIndex = function(s) {
  return this.encoding.charToGlyphIndex(s);
};
Font2.prototype.charToGlyph = function(c2) {
  var glyphIndex = this.charToGlyphIndex(c2);
  var glyph = this.glyphs.get(glyphIndex);
  if (!glyph) {
    glyph = this.glyphs.get(0);
  }
  return glyph;
};
Font2.prototype.updateFeatures = function(options) {
  return this.defaultRenderOptions.features.map(function(feature) {
    if (feature.script === "latn") {
      return {
        script: "latn",
        tags: feature.tags.filter(function(tag) {
          return options[tag];
        })
      };
    } else {
      return feature;
    }
  });
};
Font2.prototype.stringToGlyphs = function(s, options) {
  var this$1 = this;
  var bidi = new Bidi();
  var charToGlyphIndexMod = function(token) {
    return this$1.charToGlyphIndex(token.char);
  };
  bidi.registerModifier("glyphIndex", null, charToGlyphIndexMod);
  var features = options ? this.updateFeatures(options.features) : this.defaultRenderOptions.features;
  bidi.applyFeatures(this, features);
  var indexes = bidi.getTextGlyphs(s);
  var length2 = indexes.length;
  var glyphs = new Array(length2);
  var notdef = this.glyphs.get(0);
  for (var i = 0; i < length2; i += 1) {
    glyphs[i] = this.glyphs.get(indexes[i]) || notdef;
  }
  return glyphs;
};
Font2.prototype.nameToGlyphIndex = function(name2) {
  return this.glyphNames.nameToGlyphIndex(name2);
};
Font2.prototype.nameToGlyph = function(name2) {
  var glyphIndex = this.nameToGlyphIndex(name2);
  var glyph = this.glyphs.get(glyphIndex);
  if (!glyph) {
    glyph = this.glyphs.get(0);
  }
  return glyph;
};
Font2.prototype.glyphIndexToName = function(gid) {
  if (!this.glyphNames.glyphIndexToName) {
    return "";
  }
  return this.glyphNames.glyphIndexToName(gid);
};
Font2.prototype.getKerningValue = function(leftGlyph, rightGlyph) {
  leftGlyph = leftGlyph.index || leftGlyph;
  rightGlyph = rightGlyph.index || rightGlyph;
  var gposKerning = this.position.defaultKerningTables;
  if (gposKerning) {
    return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph);
  }
  return this.kerningPairs[leftGlyph + "," + rightGlyph] || 0;
};
Font2.prototype.defaultRenderOptions = {
  kerning: true,
  features: [
    /**
     * these 4 features are required to render Arabic text properly
     * and shouldn't be turned off when rendering arabic text.
     */
    { script: "arab", tags: ["init", "medi", "fina", "rlig"] },
    { script: "latn", tags: ["liga", "rlig"] }
  ]
};
Font2.prototype.forEachGlyph = function(text2, x2, y, fontSize, options, callback) {
  x2 = x2 !== void 0 ? x2 : 0;
  y = y !== void 0 ? y : 0;
  fontSize = fontSize !== void 0 ? fontSize : 72;
  options = Object.assign({}, this.defaultRenderOptions, options);
  var fontScale = 1 / this.unitsPerEm * fontSize;
  var glyphs = this.stringToGlyphs(text2, options);
  var kerningLookups;
  if (options.kerning) {
    var script = options.script || this.position.getDefaultScriptName();
    kerningLookups = this.position.getKerningTables(script, options.language);
  }
  for (var i = 0; i < glyphs.length; i += 1) {
    var glyph = glyphs[i];
    callback.call(this, glyph, x2, y, fontSize, options);
    if (glyph.advanceWidth) {
      x2 += glyph.advanceWidth * fontScale;
    }
    if (options.kerning && i < glyphs.length - 1) {
      var kerningValue = kerningLookups ? this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : this.getKerningValue(glyph, glyphs[i + 1]);
      x2 += kerningValue * fontScale;
    }
    if (options.letterSpacing) {
      x2 += options.letterSpacing * fontSize;
    } else if (options.tracking) {
      x2 += options.tracking / 1e3 * fontSize;
    }
  }
  return x2;
};
Font2.prototype.getPath = function(text2, x2, y, fontSize, options) {
  var fullPath = new Path2();
  this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
    var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this);
    fullPath.extend(glyphPath);
  });
  return fullPath;
};
Font2.prototype.getPaths = function(text2, x2, y, fontSize, options) {
  var glyphPaths = [];
  this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
    var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this);
    glyphPaths.push(glyphPath);
  });
  return glyphPaths;
};
Font2.prototype.getAdvanceWidth = function(text2, fontSize, options) {
  return this.forEachGlyph(text2, 0, 0, fontSize, options, function() {
  });
};
Font2.prototype.draw = function(ctx, text2, x2, y, fontSize, options) {
  this.getPath(text2, x2, y, fontSize, options).draw(ctx);
};
Font2.prototype.drawPoints = function(ctx, text2, x2, y, fontSize, options) {
  this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
    glyph.drawPoints(ctx, gX, gY, gFontSize);
  });
};
Font2.prototype.drawMetrics = function(ctx, text2, x2, y, fontSize, options) {
  this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
    glyph.drawMetrics(ctx, gX, gY, gFontSize);
  });
};
Font2.prototype.getEnglishName = function(name2) {
  var translations = this.names[name2];
  if (translations) {
    return translations.en;
  }
};
Font2.prototype.validate = function() {
  var _this = this;
  function assert(predicate, message) {
  }
  function assertNamePresent(name2) {
    var englishName = _this.getEnglishName(name2);
    assert(englishName && englishName.trim().length > 0);
  }
  assertNamePresent("fontFamily");
  assertNamePresent("weightName");
  assertNamePresent("manufacturer");
  assertNamePresent("copyright");
  assertNamePresent("version");
  assert(this.unitsPerEm > 0);
};
Font2.prototype.toTables = function() {
  return sfnt.fontToTable(this);
};
Font2.prototype.toBuffer = function() {
  console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.");
  return this.toArrayBuffer();
};
Font2.prototype.toArrayBuffer = function() {
  var sfntTable = this.toTables();
  var bytes = sfntTable.encode();
  var buffer = new ArrayBuffer(bytes.length);
  var intArray = new Uint8Array(buffer);
  for (var i = 0; i < bytes.length; i++) {
    intArray[i] = bytes[i];
  }
  return buffer;
};
Font2.prototype.download = function(fileName) {
  var familyName = this.getEnglishName("fontFamily");
  var styleName = this.getEnglishName("fontSubfamily");
  fileName = fileName || familyName.replace(/\s/g, "") + "-" + styleName + ".otf";
  var arrayBuffer = this.toArrayBuffer();
  window.URL = window.URL || window.webkitURL;
  if (window.URL) {
    var dataView = new DataView(arrayBuffer);
    var blob = new Blob([dataView], { type: "font/opentype" });
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    var event = document.createEvent("MouseEvents");
    event.initEvent("click", true, false);
    link.dispatchEvent(event);
  } else {
    console.warn("Font file could not be downloaded. Try using a different browser.");
  }
};
Font2.prototype.fsSelectionValues = {
  ITALIC: 1,
  //1
  UNDERSCORE: 2,
  //2
  NEGATIVE: 4,
  //4
  OUTLINED: 8,
  //8
  STRIKEOUT: 16,
  //16
  BOLD: 32,
  //32
  REGULAR: 64,
  //64
  USER_TYPO_METRICS: 128,
  //128
  WWS: 256,
  //256
  OBLIQUE: 512
  //512
};
Font2.prototype.usWidthClasses = {
  ULTRA_CONDENSED: 1,
  EXTRA_CONDENSED: 2,
  CONDENSED: 3,
  SEMI_CONDENSED: 4,
  MEDIUM: 5,
  SEMI_EXPANDED: 6,
  EXPANDED: 7,
  EXTRA_EXPANDED: 8,
  ULTRA_EXPANDED: 9
};
Font2.prototype.usWeightClasses = {
  THIN: 100,
  EXTRA_LIGHT: 200,
  LIGHT: 300,
  NORMAL: 400,
  MEDIUM: 500,
  SEMI_BOLD: 600,
  BOLD: 700,
  EXTRA_BOLD: 800,
  BLACK: 900
};
function addName(name2, names) {
  var nameString = JSON.stringify(name2);
  var nameID = 256;
  for (var nameKey in names) {
    var n2 = parseInt(nameKey);
    if (!n2 || n2 < 256) {
      continue;
    }
    if (JSON.stringify(names[nameKey]) === nameString) {
      return n2;
    }
    if (nameID <= n2) {
      nameID = n2 + 1;
    }
  }
  names[nameID] = name2;
  return nameID;
}
function makeFvarAxis(n2, axis, names) {
  var nameID = addName(axis.name, names);
  return [
    { name: "tag_" + n2, type: "TAG", value: axis.tag },
    { name: "minValue_" + n2, type: "FIXED", value: axis.minValue << 16 },
    { name: "defaultValue_" + n2, type: "FIXED", value: axis.defaultValue << 16 },
    { name: "maxValue_" + n2, type: "FIXED", value: axis.maxValue << 16 },
    { name: "flags_" + n2, type: "USHORT", value: 0 },
    { name: "nameID_" + n2, type: "USHORT", value: nameID }
  ];
}
function parseFvarAxis(data2, start, names) {
  var axis = {};
  var p = new parse.Parser(data2, start);
  axis.tag = p.parseTag();
  axis.minValue = p.parseFixed();
  axis.defaultValue = p.parseFixed();
  axis.maxValue = p.parseFixed();
  p.skip("uShort", 1);
  axis.name = names[p.parseUShort()] || {};
  return axis;
}
function makeFvarInstance(n2, inst, axes, names) {
  var nameID = addName(inst.name, names);
  var fields = [
    { name: "nameID_" + n2, type: "USHORT", value: nameID },
    { name: "flags_" + n2, type: "USHORT", value: 0 }
  ];
  for (var i = 0; i < axes.length; ++i) {
    var axisTag = axes[i].tag;
    fields.push({
      name: "axis_" + n2 + " " + axisTag,
      type: "FIXED",
      value: inst.coordinates[axisTag] << 16
    });
  }
  return fields;
}
function parseFvarInstance(data2, start, axes, names) {
  var inst = {};
  var p = new parse.Parser(data2, start);
  inst.name = names[p.parseUShort()] || {};
  p.skip("uShort", 1);
  inst.coordinates = {};
  for (var i = 0; i < axes.length; ++i) {
    inst.coordinates[axes[i].tag] = p.parseFixed();
  }
  return inst;
}
function makeFvarTable(fvar2, names) {
  var result = new table.Table("fvar", [
    { name: "version", type: "ULONG", value: 65536 },
    { name: "offsetToData", type: "USHORT", value: 0 },
    { name: "countSizePairs", type: "USHORT", value: 2 },
    { name: "axisCount", type: "USHORT", value: fvar2.axes.length },
    { name: "axisSize", type: "USHORT", value: 20 },
    { name: "instanceCount", type: "USHORT", value: fvar2.instances.length },
    { name: "instanceSize", type: "USHORT", value: 4 + fvar2.axes.length * 4 }
  ]);
  result.offsetToData = result.sizeOf();
  for (var i = 0; i < fvar2.axes.length; i++) {
    result.fields = result.fields.concat(makeFvarAxis(i, fvar2.axes[i], names));
  }
  for (var j2 = 0; j2 < fvar2.instances.length; j2++) {
    result.fields = result.fields.concat(makeFvarInstance(j2, fvar2.instances[j2], fvar2.axes, names));
  }
  return result;
}
function parseFvarTable(data2, start, names) {
  var p = new parse.Parser(data2, start);
  var tableVersion = p.parseULong();
  check.argument(tableVersion === 65536, "Unsupported fvar table version.");
  var offsetToData = p.parseOffset16();
  p.skip("uShort", 1);
  var axisCount = p.parseUShort();
  var axisSize = p.parseUShort();
  var instanceCount = p.parseUShort();
  var instanceSize = p.parseUShort();
  var axes = [];
  for (var i = 0; i < axisCount; i++) {
    axes.push(parseFvarAxis(data2, start + offsetToData + i * axisSize, names));
  }
  var instances = [];
  var instanceStart = start + offsetToData + axisCount * axisSize;
  for (var j2 = 0; j2 < instanceCount; j2++) {
    instances.push(parseFvarInstance(data2, instanceStart + j2 * instanceSize, axes, names));
  }
  return { axes, instances };
}
var fvar = { make: makeFvarTable, parse: parseFvarTable };
var attachList = function() {
  return {
    coverage: this.parsePointer(Parser.coverage),
    attachPoints: this.parseList(Parser.pointer(Parser.uShortList))
  };
};
var caretValue = function() {
  var format = this.parseUShort();
  check.argument(
    format === 1 || format === 2 || format === 3,
    "Unsupported CaretValue table version."
  );
  if (format === 1) {
    return { coordinate: this.parseShort() };
  } else if (format === 2) {
    return { pointindex: this.parseShort() };
  } else if (format === 3) {
    return { coordinate: this.parseShort() };
  }
};
var ligGlyph = function() {
  return this.parseList(Parser.pointer(caretValue));
};
var ligCaretList = function() {
  return {
    coverage: this.parsePointer(Parser.coverage),
    ligGlyphs: this.parseList(Parser.pointer(ligGlyph))
  };
};
var markGlyphSets = function() {
  this.parseUShort();
  return this.parseList(Parser.pointer(Parser.coverage));
};
function parseGDEFTable(data2, start) {
  start = start || 0;
  var p = new Parser(data2, start);
  var tableVersion = p.parseVersion(1);
  check.argument(
    tableVersion === 1 || tableVersion === 1.2 || tableVersion === 1.3,
    "Unsupported GDEF table version."
  );
  var gdef2 = {
    version: tableVersion,
    classDef: p.parsePointer(Parser.classDef),
    attachList: p.parsePointer(attachList),
    ligCaretList: p.parsePointer(ligCaretList),
    markAttachClassDef: p.parsePointer(Parser.classDef)
  };
  if (tableVersion >= 1.2) {
    gdef2.markGlyphSets = p.parsePointer(markGlyphSets);
  }
  return gdef2;
}
var gdef = { parse: parseGDEFTable };
var subtableParsers$1 = new Array(10);
subtableParsers$1[1] = function parseLookup12() {
  var start = this.offset + this.relativeOffset;
  var posformat = this.parseUShort();
  if (posformat === 1) {
    return {
      posFormat: 1,
      coverage: this.parsePointer(Parser.coverage),
      value: this.parseValueRecord()
    };
  } else if (posformat === 2) {
    return {
      posFormat: 2,
      coverage: this.parsePointer(Parser.coverage),
      values: this.parseValueRecordList()
    };
  }
  check.assert(false, "0x" + start.toString(16) + ": GPOS lookup type 1 format must be 1 or 2.");
};
subtableParsers$1[2] = function parseLookup22() {
  var start = this.offset + this.relativeOffset;
  var posFormat = this.parseUShort();
  check.assert(posFormat === 1 || posFormat === 2, "0x" + start.toString(16) + ": GPOS lookup type 2 format must be 1 or 2.");
  var coverage = this.parsePointer(Parser.coverage);
  var valueFormat1 = this.parseUShort();
  var valueFormat2 = this.parseUShort();
  if (posFormat === 1) {
    return {
      posFormat,
      coverage,
      valueFormat1,
      valueFormat2,
      pairSets: this.parseList(Parser.pointer(Parser.list(function() {
        return {
          // pairValueRecord
          secondGlyph: this.parseUShort(),
          value1: this.parseValueRecord(valueFormat1),
          value2: this.parseValueRecord(valueFormat2)
        };
      })))
    };
  } else if (posFormat === 2) {
    var classDef1 = this.parsePointer(Parser.classDef);
    var classDef2 = this.parsePointer(Parser.classDef);
    var class1Count = this.parseUShort();
    var class2Count = this.parseUShort();
    return {
      // Class Pair Adjustment
      posFormat,
      coverage,
      valueFormat1,
      valueFormat2,
      classDef1,
      classDef2,
      class1Count,
      class2Count,
      classRecords: this.parseList(class1Count, Parser.list(class2Count, function() {
        return {
          value1: this.parseValueRecord(valueFormat1),
          value2: this.parseValueRecord(valueFormat2)
        };
      }))
    };
  }
};
subtableParsers$1[3] = function parseLookup32() {
  return { error: "GPOS Lookup 3 not supported" };
};
subtableParsers$1[4] = function parseLookup42() {
  return { error: "GPOS Lookup 4 not supported" };
};
subtableParsers$1[5] = function parseLookup52() {
  return { error: "GPOS Lookup 5 not supported" };
};
subtableParsers$1[6] = function parseLookup62() {
  return { error: "GPOS Lookup 6 not supported" };
};
subtableParsers$1[7] = function parseLookup72() {
  return { error: "GPOS Lookup 7 not supported" };
};
subtableParsers$1[8] = function parseLookup82() {
  return { error: "GPOS Lookup 8 not supported" };
};
subtableParsers$1[9] = function parseLookup9() {
  return { error: "GPOS Lookup 9 not supported" };
};
function parseGposTable(data2, start) {
  start = start || 0;
  var p = new Parser(data2, start);
  var tableVersion = p.parseVersion(1);
  check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GPOS table version " + tableVersion);
  if (tableVersion === 1) {
    return {
      version: tableVersion,
      scripts: p.parseScriptList(),
      features: p.parseFeatureList(),
      lookups: p.parseLookupList(subtableParsers$1)
    };
  } else {
    return {
      version: tableVersion,
      scripts: p.parseScriptList(),
      features: p.parseFeatureList(),
      lookups: p.parseLookupList(subtableParsers$1),
      variations: p.parseFeatureVariationsList()
    };
  }
}
var subtableMakers$1 = new Array(10);
function makeGposTable(gpos2) {
  return new table.Table("GPOS", [
    { name: "version", type: "ULONG", value: 65536 },
    { name: "scripts", type: "TABLE", value: new table.ScriptList(gpos2.scripts) },
    { name: "features", type: "TABLE", value: new table.FeatureList(gpos2.features) },
    { name: "lookups", type: "TABLE", value: new table.LookupList(gpos2.lookups, subtableMakers$1) }
  ]);
}
var gpos = { parse: parseGposTable, make: makeGposTable };
function parseWindowsKernTable(p) {
  var pairs = {};
  p.skip("uShort");
  var subtableVersion = p.parseUShort();
  check.argument(subtableVersion === 0, "Unsupported kern sub-table version.");
  p.skip("uShort", 2);
  var nPairs = p.parseUShort();
  p.skip("uShort", 3);
  for (var i = 0; i < nPairs; i += 1) {
    var leftIndex = p.parseUShort();
    var rightIndex = p.parseUShort();
    var value2 = p.parseShort();
    pairs[leftIndex + "," + rightIndex] = value2;
  }
  return pairs;
}
function parseMacKernTable(p) {
  var pairs = {};
  p.skip("uShort");
  var nTables = p.parseULong();
  if (nTables > 1) {
    console.warn("Only the first kern subtable is supported.");
  }
  p.skip("uLong");
  var coverage = p.parseUShort();
  var subtableVersion = coverage & 255;
  p.skip("uShort");
  if (subtableVersion === 0) {
    var nPairs = p.parseUShort();
    p.skip("uShort", 3);
    for (var i = 0; i < nPairs; i += 1) {
      var leftIndex = p.parseUShort();
      var rightIndex = p.parseUShort();
      var value2 = p.parseShort();
      pairs[leftIndex + "," + rightIndex] = value2;
    }
  }
  return pairs;
}
function parseKernTable(data2, start) {
  var p = new parse.Parser(data2, start);
  var tableVersion = p.parseUShort();
  if (tableVersion === 0) {
    return parseWindowsKernTable(p);
  } else if (tableVersion === 1) {
    return parseMacKernTable(p);
  } else {
    throw new Error("Unsupported kern table version (" + tableVersion + ").");
  }
}
var kern = { parse: parseKernTable };
function parseLocaTable(data2, start, numGlyphs, shortVersion) {
  var p = new parse.Parser(data2, start);
  var parseFn = shortVersion ? p.parseUShort : p.parseULong;
  var glyphOffsets = [];
  for (var i = 0; i < numGlyphs + 1; i += 1) {
    var glyphOffset = parseFn.call(p);
    if (shortVersion) {
      glyphOffset *= 2;
    }
    glyphOffsets.push(glyphOffset);
  }
  return glyphOffsets;
}
var loca = { parse: parseLocaTable };
function loadFromUrl(url, callback) {
  var request = new XMLHttpRequest();
  request.open("get", url, true);
  request.responseType = "arraybuffer";
  request.onload = function() {
    if (request.response) {
      return callback(null, request.response);
    } else {
      return callback("Font could not be loaded: " + request.statusText);
    }
  };
  request.onerror = function() {
    callback("Font could not be loaded");
  };
  request.send();
}
function parseOpenTypeTableEntries(data2, numTables) {
  var tableEntries = [];
  var p = 12;
  for (var i = 0; i < numTables; i += 1) {
    var tag = parse.getTag(data2, p);
    var checksum = parse.getULong(data2, p + 4);
    var offset = parse.getULong(data2, p + 8);
    var length2 = parse.getULong(data2, p + 12);
    tableEntries.push({ tag, checksum, offset, length: length2, compression: false });
    p += 16;
  }
  return tableEntries;
}
function parseWOFFTableEntries(data2, numTables) {
  var tableEntries = [];
  var p = 44;
  for (var i = 0; i < numTables; i += 1) {
    var tag = parse.getTag(data2, p);
    var offset = parse.getULong(data2, p + 4);
    var compLength = parse.getULong(data2, p + 8);
    var origLength = parse.getULong(data2, p + 12);
    var compression = void 0;
    if (compLength < origLength) {
      compression = "WOFF";
    } else {
      compression = false;
    }
    tableEntries.push({
      tag,
      offset,
      compression,
      compressedLength: compLength,
      length: origLength
    });
    p += 20;
  }
  return tableEntries;
}
function uncompressTable(data2, tableEntry) {
  if (tableEntry.compression === "WOFF") {
    var inBuffer = new Uint8Array(data2.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2);
    var outBuffer = new Uint8Array(tableEntry.length);
    tinyInflate(inBuffer, outBuffer);
    if (outBuffer.byteLength !== tableEntry.length) {
      throw new Error("Decompression error: " + tableEntry.tag + " decompressed length doesn't match recorded length");
    }
    var view = new DataView(outBuffer.buffer, 0);
    return { data: view, offset: 0 };
  } else {
    return { data: data2, offset: tableEntry.offset };
  }
}
function parseBuffer(buffer, opt) {
  opt = opt === void 0 || opt === null ? {} : opt;
  var indexToLocFormat;
  var ltagTable;
  var font = new Font2({ empty: true });
  var data2 = new DataView(buffer, 0);
  var numTables;
  var tableEntries = [];
  var signature = parse.getTag(data2, 0);
  if (signature === String.fromCharCode(0, 1, 0, 0) || signature === "true" || signature === "typ1") {
    font.outlinesFormat = "truetype";
    numTables = parse.getUShort(data2, 4);
    tableEntries = parseOpenTypeTableEntries(data2, numTables);
  } else if (signature === "OTTO") {
    font.outlinesFormat = "cff";
    numTables = parse.getUShort(data2, 4);
    tableEntries = parseOpenTypeTableEntries(data2, numTables);
  } else if (signature === "wOFF") {
    var flavor = parse.getTag(data2, 4);
    if (flavor === String.fromCharCode(0, 1, 0, 0)) {
      font.outlinesFormat = "truetype";
    } else if (flavor === "OTTO") {
      font.outlinesFormat = "cff";
    } else {
      throw new Error("Unsupported OpenType flavor " + signature);
    }
    numTables = parse.getUShort(data2, 12);
    tableEntries = parseWOFFTableEntries(data2, numTables);
  } else {
    throw new Error("Unsupported OpenType signature " + signature);
  }
  var cffTableEntry;
  var fvarTableEntry;
  var glyfTableEntry;
  var gdefTableEntry;
  var gposTableEntry;
  var gsubTableEntry;
  var hmtxTableEntry;
  var kernTableEntry;
  var locaTableEntry;
  var nameTableEntry;
  var metaTableEntry;
  var p;
  for (var i = 0; i < numTables; i += 1) {
    var tableEntry = tableEntries[i];
    var table2 = void 0;
    switch (tableEntry.tag) {
      case "cmap":
        table2 = uncompressTable(data2, tableEntry);
        font.tables.cmap = cmap.parse(table2.data, table2.offset);
        font.encoding = new CmapEncoding(font.tables.cmap);
        break;
      case "cvt ":
        table2 = uncompressTable(data2, tableEntry);
        p = new parse.Parser(table2.data, table2.offset);
        font.tables.cvt = p.parseShortList(tableEntry.length / 2);
        break;
      case "fvar":
        fvarTableEntry = tableEntry;
        break;
      case "fpgm":
        table2 = uncompressTable(data2, tableEntry);
        p = new parse.Parser(table2.data, table2.offset);
        font.tables.fpgm = p.parseByteList(tableEntry.length);
        break;
      case "head":
        table2 = uncompressTable(data2, tableEntry);
        font.tables.head = head.parse(table2.data, table2.offset);
        font.unitsPerEm = font.tables.head.unitsPerEm;
        indexToLocFormat = font.tables.head.indexToLocFormat;
        break;
      case "hhea":
        table2 = uncompressTable(data2, tableEntry);
        font.tables.hhea = hhea.parse(table2.data, table2.offset);
        font.ascender = font.tables.hhea.ascender;
        font.descender = font.tables.hhea.descender;
        font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics;
        break;
      case "hmtx":
        hmtxTableEntry = tableEntry;
        break;
      case "ltag":
        table2 = uncompressTable(data2, tableEntry);
        ltagTable = ltag.parse(table2.data, table2.offset);
        break;
      case "COLR":
        table2 = uncompressTable(data2, tableEntry);
        font.tables.colr = colr.parse(table2.data, table2.offset);
        break;
      case "CPAL":
        table2 = uncompressTable(data2, tableEntry);
        font.tables.cpal = cpal.parse(table2.data, table2.offset);
        break;
      case "maxp":
        table2 = uncompressTable(data2, tableEntry);
        font.tables.maxp = maxp.parse(table2.data, table2.offset);
        font.numGlyphs = font.tables.maxp.numGlyphs;
        break;
      case "name":
        nameTableEntry = tableEntry;
        break;
      case "OS/2":
        table2 = uncompressTable(data2, tableEntry);
        font.tables.os2 = os2.parse(table2.data, table2.offset);
        break;
      case "post":
        table2 = uncompressTable(data2, tableEntry);
        font.tables.post = post.parse(table2.data, table2.offset);
        font.glyphNames = new GlyphNames(font.tables.post);
        break;
      case "prep":
        table2 = uncompressTable(data2, tableEntry);
        p = new parse.Parser(table2.data, table2.offset);
        font.tables.prep = p.parseByteList(tableEntry.length);
        break;
      case "glyf":
        glyfTableEntry = tableEntry;
        break;
      case "loca":
        locaTableEntry = tableEntry;
        break;
      case "CFF ":
        cffTableEntry = tableEntry;
        break;
      case "kern":
        kernTableEntry = tableEntry;
        break;
      case "GDEF":
        gdefTableEntry = tableEntry;
        break;
      case "GPOS":
        gposTableEntry = tableEntry;
        break;
      case "GSUB":
        gsubTableEntry = tableEntry;
        break;
      case "meta":
        metaTableEntry = tableEntry;
        break;
    }
  }
  var nameTable = uncompressTable(data2, nameTableEntry);
  font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable);
  font.names = font.tables.name;
  if (glyfTableEntry && locaTableEntry) {
    var shortVersion = indexToLocFormat === 0;
    var locaTable = uncompressTable(data2, locaTableEntry);
    var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion);
    var glyfTable = uncompressTable(data2, glyfTableEntry);
    font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font, opt);
  } else if (cffTableEntry) {
    var cffTable = uncompressTable(data2, cffTableEntry);
    cff.parse(cffTable.data, cffTable.offset, font, opt);
  } else {
    throw new Error("Font doesn't contain TrueType or CFF outlines.");
  }
  var hmtxTable = uncompressTable(data2, hmtxTableEntry);
  hmtx.parse(font, hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs, opt);
  addGlyphNames(font, opt);
  if (kernTableEntry) {
    var kernTable = uncompressTable(data2, kernTableEntry);
    font.kerningPairs = kern.parse(kernTable.data, kernTable.offset);
  } else {
    font.kerningPairs = {};
  }
  if (gdefTableEntry) {
    var gdefTable = uncompressTable(data2, gdefTableEntry);
    font.tables.gdef = gdef.parse(gdefTable.data, gdefTable.offset);
  }
  if (gposTableEntry) {
    var gposTable = uncompressTable(data2, gposTableEntry);
    font.tables.gpos = gpos.parse(gposTable.data, gposTable.offset);
    font.position.init();
  }
  if (gsubTableEntry) {
    var gsubTable = uncompressTable(data2, gsubTableEntry);
    font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset);
  }
  if (fvarTableEntry) {
    var fvarTable = uncompressTable(data2, fvarTableEntry);
    font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names);
  }
  if (metaTableEntry) {
    var metaTable = uncompressTable(data2, metaTableEntry);
    font.tables.meta = meta.parse(metaTable.data, metaTable.offset);
    font.metas = font.tables.meta;
  }
  return font;
}
function load(url, callback, opt) {
  opt = opt === void 0 || opt === null ? {} : opt;
  return new Promise(function(resolve, reject2) {
    loadFromUrl(url, function(err2, arrayBuffer) {
      if (err2) {
        if (callback) {
          return callback(err2);
        } else {
          reject2(err2);
        }
      }
      var font;
      try {
        font = parseBuffer(arrayBuffer, opt);
      } catch (e) {
        if (callback) {
          return callback(e, null);
        } else {
          reject2(e);
        }
      }
      if (callback) {
        return callback(null, font);
      } else {
        resolve(font);
      }
    });
  });
}
var opentype = Object.freeze({
  __proto__: null,
  Font: Font2,
  Glyph,
  Path: Path2,
  BoundingBox,
  _parse: parse,
  parse: parseBuffer,
  load
});
var opentype_module_default = opentype;

// node_modules/three/examples/jsm/loaders/TTFLoader.js
var TTFLoader = class extends Loader {
  /**
   * Constructs a new TTF loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
    this.reversed = false;
  }
  /**
   * Starts loading from the given URL and passes the loaded TTF asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Object)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(buffer) {
      try {
        onLoad(scope.parse(buffer));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given TTF data and returns a JSON for creating a font.
   *
   * @param {ArrayBuffer} arraybuffer - The raw TTF data as an array buffer.
   * @return {Object} The result JSON.
   */
  parse(arraybuffer) {
    function convert(font, reversed) {
      const round = Math.round;
      const glyphs = {};
      const scale2 = 1e5 / ((font.unitsPerEm || 2048) * 72);
      const glyphIndexMap = font.encoding.cmap.glyphIndexMap;
      const unicodes = Object.keys(glyphIndexMap);
      for (let i = 0; i < unicodes.length; i++) {
        const unicode = unicodes[i];
        const glyph = font.glyphs.glyphs[glyphIndexMap[unicode]];
        if (unicode !== void 0) {
          const token = {
            ha: round(glyph.advanceWidth * scale2),
            x_min: round(glyph.xMin * scale2),
            x_max: round(glyph.xMax * scale2),
            o: ""
          };
          if (reversed) {
            glyph.path.commands = reverseCommands(glyph.path.commands);
          }
          glyph.path.commands.forEach(function(command) {
            if (command.type.toLowerCase() === "c") {
              command.type = "b";
            }
            token.o += command.type.toLowerCase() + " ";
            if (command.x !== void 0 && command.y !== void 0) {
              token.o += round(command.x * scale2) + " " + round(command.y * scale2) + " ";
            }
            if (command.x1 !== void 0 && command.y1 !== void 0) {
              token.o += round(command.x1 * scale2) + " " + round(command.y1 * scale2) + " ";
            }
            if (command.x2 !== void 0 && command.y2 !== void 0) {
              token.o += round(command.x2 * scale2) + " " + round(command.y2 * scale2) + " ";
            }
          });
          glyphs[String.fromCodePoint(glyph.unicode)] = token;
        }
      }
      return {
        glyphs,
        familyName: font.getEnglishName("fullName"),
        ascender: round(font.ascender * scale2),
        descender: round(font.descender * scale2),
        underlinePosition: font.tables.post.underlinePosition,
        underlineThickness: font.tables.post.underlineThickness,
        boundingBox: {
          xMin: font.tables.head.xMin,
          xMax: font.tables.head.xMax,
          yMin: font.tables.head.yMin,
          yMax: font.tables.head.yMax
        },
        resolution: 1e3,
        original_font_information: font.tables.name
      };
    }
    function reverseCommands(commands) {
      const paths = [];
      let path;
      commands.forEach(function(c2) {
        if (c2.type.toLowerCase() === "m") {
          path = [c2];
          paths.push(path);
        } else if (c2.type.toLowerCase() !== "z") {
          path.push(c2);
        }
      });
      const reversed = [];
      paths.forEach(function(p) {
        const result = {
          type: "m",
          x: p[p.length - 1].x,
          y: p[p.length - 1].y
        };
        reversed.push(result);
        for (let i = p.length - 1; i > 0; i--) {
          const command = p[i];
          const result2 = { type: command.type };
          if (command.x2 !== void 0 && command.y2 !== void 0) {
            result2.x1 = command.x2;
            result2.y1 = command.y2;
            result2.x2 = command.x1;
            result2.y2 = command.y1;
          } else if (command.x1 !== void 0 && command.y1 !== void 0) {
            result2.x1 = command.x1;
            result2.y1 = command.y1;
          }
          result2.x = p[i - 1].x;
          result2.y = p[i - 1].y;
          reversed.push(result2);
        }
      });
      return reversed;
    }
    return convert(opentype_module_default.parse(arraybuffer), this.reversed);
  }
};

// node_modules/three/examples/jsm/loaders/USDZLoader.js
var USDAParser = class {
  parse(text2) {
    const data2 = {};
    const lines = text2.split("\n");
    let string = null;
    let target = data2;
    const stack = [data2];
    for (const line2 of lines) {
      if (line2.includes("=")) {
        const assignment = line2.split("=");
        const lhs = assignment[0].trim();
        const rhs = assignment[1].trim();
        if (rhs.endsWith("{")) {
          const group = {};
          stack.push(group);
          target[lhs] = group;
          target = group;
        } else if (rhs.endsWith("(")) {
          const values2 = rhs.slice(0, -1);
          target[lhs] = values2;
          const meta2 = {};
          stack.push(meta2);
          target = meta2;
        } else {
          target[lhs] = rhs;
        }
      } else if (line2.endsWith("{")) {
        const group = target[string] || {};
        stack.push(group);
        target[string] = group;
        target = group;
      } else if (line2.endsWith("}")) {
        stack.pop();
        if (stack.length === 0) continue;
        target = stack[stack.length - 1];
      } else if (line2.endsWith("(")) {
        const meta2 = {};
        stack.push(meta2);
        string = line2.split("(")[0].trim() || string;
        target[string] = meta2;
        target = meta2;
      } else if (line2.endsWith(")")) {
        stack.pop();
        target = stack[stack.length - 1];
      } else {
        string = line2.trim();
      }
    }
    return data2;
  }
};
var USDZLoader = class extends Loader {
  /**
   * Constructs a new USDZ loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded USDZ asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Group)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given USDZ data and returns the resulting group.
   *
   * @param {ArrayBuffer} buffer - The raw USDZ data as an array buffer.
   * @return {Group} The parsed asset as a group.
   */
  parse(buffer) {
    const parser = new USDAParser();
    function parseAssets(zip2) {
      const data2 = {};
      const loader = new FileLoader();
      loader.setResponseType("arraybuffer");
      for (const filename in zip2) {
        if (filename.endsWith("png")) {
          const blob = new Blob([zip2[filename]], { type: "image/png" });
          data2[filename] = URL.createObjectURL(blob);
        }
        if (filename.endsWith("usd") || filename.endsWith("usda")) {
          if (isCrateFile(zip2[filename])) {
            throw Error("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.");
          }
          const text3 = strFromU8(zip2[filename]);
          data2[filename] = parser.parse(text3);
        }
      }
      return data2;
    }
    function isCrateFile(buffer2) {
      const fileHeader = buffer2.slice(0, 7);
      const crateHeader = new Uint8Array([80, 88, 82, 45, 85, 83, 68, 67]);
      return fileHeader.every((value2, index2) => value2 === crateHeader[index2]);
    }
    function findUSD(zip2) {
      if (zip2.length < 1) return void 0;
      const firstFileName = Object.keys(zip2)[0];
      let isCrate = false;
      if (firstFileName.endsWith("usda")) return zip2[firstFileName];
      if (firstFileName.endsWith("usdc")) {
        isCrate = true;
      } else if (firstFileName.endsWith("usd")) {
        if (!isCrateFile(zip2[firstFileName])) {
          return zip2[firstFileName];
        } else {
          isCrate = true;
        }
      }
      if (isCrate) {
        throw Error("THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.");
      }
    }
    const zip = unzipSync(new Uint8Array(buffer));
    const assets = parseAssets(zip);
    const file = findUSD(zip);
    const text2 = strFromU8(file);
    const root = parser.parse(text2);
    function findMeshGeometry(data2) {
      if (!data2) return void 0;
      if ("prepend references" in data2) {
        const reference = data2["prepend references"];
        const parts = reference.split("@");
        const path = parts[1].replace(/^.\//, "");
        const id = parts[2].replace(/^<\//, "").replace(/>$/, "");
        return findGeometry(assets[path], id);
      }
      return findGeometry(data2);
    }
    function findGeometry(data2, id) {
      if (!data2) return void 0;
      if (id !== void 0) {
        const def = `def Mesh "${id}"`;
        if (def in data2) {
          return data2[def];
        }
      }
      for (const name2 in data2) {
        const object = data2[name2];
        if (name2.startsWith("def Mesh")) {
          return object;
        }
        if (typeof object === "object") {
          const geometry = findGeometry(object);
          if (geometry) return geometry;
        }
      }
    }
    function buildGeometry(data2) {
      if (!data2) return void 0;
      const geometry = new BufferGeometry();
      let indices = null;
      let counts = null;
      let uvs = null;
      let positionsLength = -1;
      if ("int[] faceVertexIndices" in data2) {
        indices = JSON.parse(data2["int[] faceVertexIndices"]);
      }
      if ("int[] faceVertexCounts" in data2) {
        counts = JSON.parse(data2["int[] faceVertexCounts"]);
        indices = toTriangleIndices(indices, counts);
      }
      if ("point3f[] points" in data2) {
        const positions = JSON.parse(data2["point3f[] points"].replace(/[()]*/g, ""));
        positionsLength = positions.length;
        let attribute = new BufferAttribute(new Float32Array(positions), 3);
        if (indices !== null) attribute = toFlatBufferAttribute(attribute, indices);
        geometry.setAttribute("position", attribute);
      }
      if ("float2[] primvars:st" in data2) {
        data2["texCoord2f[] primvars:st"] = data2["float2[] primvars:st"];
      }
      if ("texCoord2f[] primvars:st" in data2) {
        uvs = JSON.parse(data2["texCoord2f[] primvars:st"].replace(/[()]*/g, ""));
        let attribute = new BufferAttribute(new Float32Array(uvs), 2);
        if (indices !== null) attribute = toFlatBufferAttribute(attribute, indices);
        geometry.setAttribute("uv", attribute);
      }
      if ("int[] primvars:st:indices" in data2 && uvs !== null) {
        const attribute = new BufferAttribute(new Float32Array(uvs), 2);
        let indices2 = JSON.parse(data2["int[] primvars:st:indices"]);
        indices2 = toTriangleIndices(indices2, counts);
        geometry.setAttribute("uv", toFlatBufferAttribute(attribute, indices2));
      }
      if ("normal3f[] normals" in data2) {
        const normals = JSON.parse(data2["normal3f[] normals"].replace(/[()]*/g, ""));
        let attribute = new BufferAttribute(new Float32Array(normals), 3);
        if (normals.length === positionsLength) {
          if (indices !== null) attribute = toFlatBufferAttribute(attribute, indices);
        } else {
          let indices2 = Array.from(Array(normals.length / 3).keys());
          indices2 = toTriangleIndices(indices2, counts);
          attribute = toFlatBufferAttribute(attribute, indices2);
        }
        geometry.setAttribute("normal", attribute);
      } else {
        geometry.computeVertexNormals();
      }
      return geometry;
    }
    function toTriangleIndices(rawIndices, counts) {
      const indices = [];
      for (let i = 0; i < counts.length; i++) {
        const count = counts[i];
        const stride = i * count;
        if (count === 3) {
          const a2 = rawIndices[stride + 0];
          const b3 = rawIndices[stride + 1];
          const c2 = rawIndices[stride + 2];
          indices.push(a2, b3, c2);
        } else if (count === 4) {
          const a2 = rawIndices[stride + 0];
          const b3 = rawIndices[stride + 1];
          const c2 = rawIndices[stride + 2];
          const d = rawIndices[stride + 3];
          indices.push(a2, b3, c2);
          indices.push(a2, c2, d);
        } else {
          console.warn("THREE.USDZLoader: Face vertex count of %s unsupported.", count);
        }
      }
      return indices;
    }
    function toFlatBufferAttribute(attribute, indices) {
      const array = attribute.array;
      const itemSize = attribute.itemSize;
      const array2 = new array.constructor(indices.length * itemSize);
      let index2 = 0, index22 = 0;
      for (let i = 0, l2 = indices.length; i < l2; i++) {
        index2 = indices[i] * itemSize;
        for (let j2 = 0; j2 < itemSize; j2++) {
          array2[index22++] = array[index2++];
        }
      }
      return new BufferAttribute(array2, itemSize);
    }
    function findMeshMaterial(data2) {
      if (!data2) return void 0;
      if ("rel material:binding" in data2) {
        const reference = data2["rel material:binding"];
        const id = reference.replace(/^<\//, "").replace(/>$/, "");
        const parts = id.split("/");
        return findMaterial(root, ` "${parts[1]}"`);
      }
      return findMaterial(data2);
    }
    function findMaterial(data2, id = "") {
      for (const name2 in data2) {
        const object = data2[name2];
        if (name2.startsWith("def Material" + id)) {
          return object;
        }
        if (typeof object === "object") {
          const material = findMaterial(object, id);
          if (material) return material;
        }
      }
    }
    function setTextureParams(map2, data_value) {
      if (data_value["float inputs:rotation"]) {
        map2.rotation = parseFloat(data_value["float inputs:rotation"]);
      }
      if (data_value["float2 inputs:scale"]) {
        map2.repeat = new Vector2().fromArray(JSON.parse("[" + data_value["float2 inputs:scale"].replace(/[()]*/g, "") + "]"));
      }
      if (data_value["float2 inputs:translation"]) {
        map2.offset = new Vector2().fromArray(JSON.parse("[" + data_value["float2 inputs:translation"].replace(/[()]*/g, "") + "]"));
      }
    }
    function buildMaterial2(data2) {
      const material = new MeshPhysicalMaterial();
      if (data2 !== void 0) {
        const surfaceConnection = data2["token outputs:surface.connect"];
        const surfaceName = /(\w+).output/.exec(surfaceConnection)[1];
        const surface = data2[`def Shader "${surfaceName}"`];
        if (surface !== void 0) {
          if ("color3f inputs:diffuseColor.connect" in surface) {
            const path = surface["color3f inputs:diffuseColor.connect"];
            const sampler = findTexture(root, /(\w+).output/.exec(path)[1]);
            material.map = buildTexture(sampler);
            material.map.colorSpace = SRGBColorSpace;
            if ('def Shader "Transform2d_diffuse"' in data2) {
              setTextureParams(material.map, data2['def Shader "Transform2d_diffuse"']);
            }
          } else if ("color3f inputs:diffuseColor" in surface) {
            const color = surface["color3f inputs:diffuseColor"].replace(/[()]*/g, "");
            material.color.fromArray(JSON.parse("[" + color + "]"));
          }
          if ("color3f inputs:emissiveColor.connect" in surface) {
            const path = surface["color3f inputs:emissiveColor.connect"];
            const sampler = findTexture(root, /(\w+).output/.exec(path)[1]);
            material.emissiveMap = buildTexture(sampler);
            material.emissiveMap.colorSpace = SRGBColorSpace;
            material.emissive.set(16777215);
            if ('def Shader "Transform2d_emissive"' in data2) {
              setTextureParams(material.emissiveMap, data2['def Shader "Transform2d_emissive"']);
            }
          } else if ("color3f inputs:emissiveColor" in surface) {
            const color = surface["color3f inputs:emissiveColor"].replace(/[()]*/g, "");
            material.emissive.fromArray(JSON.parse("[" + color + "]"));
          }
          if ("normal3f inputs:normal.connect" in surface) {
            const path = surface["normal3f inputs:normal.connect"];
            const sampler = findTexture(root, /(\w+).output/.exec(path)[1]);
            material.normalMap = buildTexture(sampler);
            material.normalMap.colorSpace = NoColorSpace;
            if ('def Shader "Transform2d_normal"' in data2) {
              setTextureParams(material.normalMap, data2['def Shader "Transform2d_normal"']);
            }
          }
          if ("float inputs:roughness.connect" in surface) {
            const path = surface["float inputs:roughness.connect"];
            const sampler = findTexture(root, /(\w+).output/.exec(path)[1]);
            material.roughness = 1;
            material.roughnessMap = buildTexture(sampler);
            material.roughnessMap.colorSpace = NoColorSpace;
            if ('def Shader "Transform2d_roughness"' in data2) {
              setTextureParams(material.roughnessMap, data2['def Shader "Transform2d_roughness"']);
            }
          } else if ("float inputs:roughness" in surface) {
            material.roughness = parseFloat(surface["float inputs:roughness"]);
          }
          if ("float inputs:metallic.connect" in surface) {
            const path = surface["float inputs:metallic.connect"];
            const sampler = findTexture(root, /(\w+).output/.exec(path)[1]);
            material.metalness = 1;
            material.metalnessMap = buildTexture(sampler);
            material.metalnessMap.colorSpace = NoColorSpace;
            if ('def Shader "Transform2d_metallic"' in data2) {
              setTextureParams(material.metalnessMap, data2['def Shader "Transform2d_metallic"']);
            }
          } else if ("float inputs:metallic" in surface) {
            material.metalness = parseFloat(surface["float inputs:metallic"]);
          }
          if ("float inputs:clearcoat.connect" in surface) {
            const path = surface["float inputs:clearcoat.connect"];
            const sampler = findTexture(root, /(\w+).output/.exec(path)[1]);
            material.clearcoat = 1;
            material.clearcoatMap = buildTexture(sampler);
            material.clearcoatMap.colorSpace = NoColorSpace;
            if ('def Shader "Transform2d_clearcoat"' in data2) {
              setTextureParams(material.clearcoatMap, data2['def Shader "Transform2d_clearcoat"']);
            }
          } else if ("float inputs:clearcoat" in surface) {
            material.clearcoat = parseFloat(surface["float inputs:clearcoat"]);
          }
          if ("float inputs:clearcoatRoughness.connect" in surface) {
            const path = surface["float inputs:clearcoatRoughness.connect"];
            const sampler = findTexture(root, /(\w+).output/.exec(path)[1]);
            material.clearcoatRoughness = 1;
            material.clearcoatRoughnessMap = buildTexture(sampler);
            material.clearcoatRoughnessMap.colorSpace = NoColorSpace;
            if ('def Shader "Transform2d_clearcoatRoughness"' in data2) {
              setTextureParams(material.clearcoatRoughnessMap, data2['def Shader "Transform2d_clearcoatRoughness"']);
            }
          } else if ("float inputs:clearcoatRoughness" in surface) {
            material.clearcoatRoughness = parseFloat(surface["float inputs:clearcoatRoughness"]);
          }
          if ("float inputs:ior" in surface) {
            material.ior = parseFloat(surface["float inputs:ior"]);
          }
          if ("float inputs:occlusion.connect" in surface) {
            const path = surface["float inputs:occlusion.connect"];
            const sampler = findTexture(root, /(\w+).output/.exec(path)[1]);
            material.aoMap = buildTexture(sampler);
            material.aoMap.colorSpace = NoColorSpace;
            if ('def Shader "Transform2d_occlusion"' in data2) {
              setTextureParams(material.aoMap, data2['def Shader "Transform2d_occlusion"']);
            }
          }
        }
      }
      return material;
    }
    function findTexture(data2, id) {
      for (const name2 in data2) {
        const object = data2[name2];
        if (name2.startsWith(`def Shader "${id}"`)) {
          return object;
        }
        if (typeof object === "object") {
          const texture = findTexture(object, id);
          if (texture) return texture;
        }
      }
    }
    function buildTexture(data2) {
      if ("asset inputs:file" in data2) {
        const path = data2["asset inputs:file"].replace(/@*/g, "").trim();
        const loader = new TextureLoader();
        const texture = loader.load(assets[path]);
        const map2 = {
          '"clamp"': ClampToEdgeWrapping,
          '"mirror"': MirroredRepeatWrapping,
          '"repeat"': RepeatWrapping
        };
        if ("token inputs:wrapS" in data2) {
          texture.wrapS = map2[data2["token inputs:wrapS"]];
        }
        if ("token inputs:wrapT" in data2) {
          texture.wrapT = map2[data2["token inputs:wrapT"]];
        }
        return texture;
      }
      return null;
    }
    function buildObject(data2) {
      const geometry = buildGeometry(findMeshGeometry(data2));
      const material = buildMaterial2(findMeshMaterial(data2));
      const mesh = geometry ? new Mesh(geometry, material) : new Object3D();
      if ("matrix4d xformOp:transform" in data2) {
        const array = JSON.parse("[" + data2["matrix4d xformOp:transform"].replace(/[()]*/g, "") + "]");
        mesh.matrix.fromArray(array);
        mesh.matrix.decompose(mesh.position, mesh.quaternion, mesh.scale);
      }
      return mesh;
    }
    function buildHierarchy(data2, group2) {
      for (const name2 in data2) {
        if (name2.startsWith("def Scope")) {
          buildHierarchy(data2[name2], group2);
        } else if (name2.startsWith("def Xform")) {
          const mesh = buildObject(data2[name2]);
          if (/def Xform "(\w+)"/.test(name2)) {
            mesh.name = /def Xform "(\w+)"/.exec(name2)[1];
          }
          group2.add(mesh);
          buildHierarchy(data2[name2], mesh);
        }
      }
    }
    const group = new Group();
    buildHierarchy(root, group);
    return group;
  }
};

// node_modules/three/examples/jsm/loaders/VOXLoader.js
var VOXLoader = class extends Loader {
  /**
   * Starts loading from the given URL and passes the loaded VOX asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Array<Object>)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.load(url, function(buffer) {
      try {
        onLoad(scope.parse(buffer));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given VOX data and returns the resulting chunks.
   *
   * @param {ArrayBuffer} buffer - The raw VOX data as an array buffer.
   * @return {Array<Object>} The parsed chunks.
   */
  parse(buffer) {
    const data2 = new DataView(buffer);
    const id = data2.getUint32(0, true);
    const version = data2.getUint32(4, true);
    if (id !== 542658390) {
      console.error("THREE.VOXLoader: Invalid VOX file.");
      return;
    }
    if (version !== 150) {
      console.error("THREE.VOXLoader: Invalid VOX file. Unsupported version:", version);
      return;
    }
    const DEFAULT_PALETTE = [
      0,
      4294967295,
      4291624959,
      4288282623,
      4284940287,
      4281597951,
      4278255615,
      4294954239,
      4291611903,
      4288269567,
      4284927231,
      4281584895,
      4278242559,
      4294941183,
      4291598847,
      4288256511,
      4284914175,
      4281571839,
      4278229503,
      4294928127,
      4291585791,
      4288243455,
      4284901119,
      4281558783,
      4278216447,
      4294915071,
      4291572735,
      4288230399,
      4284888063,
      4281545727,
      4278203391,
      4294902015,
      4291559679,
      4288217343,
      4284875007,
      4281532671,
      4278190335,
      4294967244,
      4291624908,
      4288282572,
      4284940236,
      4281597900,
      4278255564,
      4294954188,
      4291611852,
      4288269516,
      4284927180,
      4281584844,
      4278242508,
      4294941132,
      4291598796,
      4288256460,
      4284914124,
      4281571788,
      4278229452,
      4294928076,
      4291585740,
      4288243404,
      4284901068,
      4281558732,
      4278216396,
      4294915020,
      4291572684,
      4288230348,
      4284888012,
      4281545676,
      4278203340,
      4294901964,
      4291559628,
      4288217292,
      4284874956,
      4281532620,
      4278190284,
      4294967193,
      4291624857,
      4288282521,
      4284940185,
      4281597849,
      4278255513,
      4294954137,
      4291611801,
      4288269465,
      4284927129,
      4281584793,
      4278242457,
      4294941081,
      4291598745,
      4288256409,
      4284914073,
      4281571737,
      4278229401,
      4294928025,
      4291585689,
      4288243353,
      4284901017,
      4281558681,
      4278216345,
      4294914969,
      4291572633,
      4288230297,
      4284887961,
      4281545625,
      4278203289,
      4294901913,
      4291559577,
      4288217241,
      4284874905,
      4281532569,
      4278190233,
      4294967142,
      4291624806,
      4288282470,
      4284940134,
      4281597798,
      4278255462,
      4294954086,
      4291611750,
      4288269414,
      4284927078,
      4281584742,
      4278242406,
      4294941030,
      4291598694,
      4288256358,
      4284914022,
      4281571686,
      4278229350,
      4294927974,
      4291585638,
      4288243302,
      4284900966,
      4281558630,
      4278216294,
      4294914918,
      4291572582,
      4288230246,
      4284887910,
      4281545574,
      4278203238,
      4294901862,
      4291559526,
      4288217190,
      4284874854,
      4281532518,
      4278190182,
      4294967091,
      4291624755,
      4288282419,
      4284940083,
      4281597747,
      4278255411,
      4294954035,
      4291611699,
      4288269363,
      4284927027,
      4281584691,
      4278242355,
      4294940979,
      4291598643,
      4288256307,
      4284913971,
      4281571635,
      4278229299,
      4294927923,
      4291585587,
      4288243251,
      4284900915,
      4281558579,
      4278216243,
      4294914867,
      4291572531,
      4288230195,
      4284887859,
      4281545523,
      4278203187,
      4294901811,
      4291559475,
      4288217139,
      4284874803,
      4281532467,
      4278190131,
      4294967040,
      4291624704,
      4288282368,
      4284940032,
      4281597696,
      4278255360,
      4294953984,
      4291611648,
      4288269312,
      4284926976,
      4281584640,
      4278242304,
      4294940928,
      4291598592,
      4288256256,
      4284913920,
      4281571584,
      4278229248,
      4294927872,
      4291585536,
      4288243200,
      4284900864,
      4281558528,
      4278216192,
      4294914816,
      4291572480,
      4288230144,
      4284887808,
      4281545472,
      4278203136,
      4294901760,
      4291559424,
      4288217088,
      4284874752,
      4281532416,
      4278190318,
      4278190301,
      4278190267,
      4278190250,
      4278190216,
      4278190199,
      4278190165,
      4278190148,
      4278190114,
      4278190097,
      4278251008,
      4278246656,
      4278237952,
      4278233600,
      4278224896,
      4278220544,
      4278211840,
      4278207488,
      4278198784,
      4278194432,
      4293787648,
      4292673536,
      4290445312,
      4289331200,
      4287102976,
      4285988864,
      4283760640,
      4282646528,
      4280418304,
      4279304192,
      4293848814,
      4292730333,
      4290493371,
      4289374890,
      4287137928,
      4286019447,
      4283782485,
      4282664004,
      4280427042,
      4279308561
    ];
    let i = 8;
    let chunk;
    const chunks = [];
    while (i < data2.byteLength) {
      let id2 = "";
      for (let j2 = 0; j2 < 4; j2++) {
        id2 += String.fromCharCode(data2.getUint8(i++));
      }
      const chunkSize = data2.getUint32(i, true);
      i += 4;
      i += 4;
      if (id2 === "SIZE") {
        const x2 = data2.getUint32(i, true);
        i += 4;
        const y = data2.getUint32(i, true);
        i += 4;
        const z = data2.getUint32(i, true);
        i += 4;
        chunk = {
          palette: DEFAULT_PALETTE,
          size: { x: x2, y, z }
        };
        chunks.push(chunk);
        i += chunkSize - 3 * 4;
      } else if (id2 === "XYZI") {
        const numVoxels = data2.getUint32(i, true);
        i += 4;
        chunk.data = new Uint8Array(buffer, i, numVoxels * 4);
        i += numVoxels * 4;
      } else if (id2 === "RGBA") {
        const palette = [0];
        for (let j2 = 0; j2 < 256; j2++) {
          palette[j2 + 1] = data2.getUint32(i, true);
          i += 4;
        }
        chunk.palette = palette;
      } else {
        i += chunkSize;
      }
    }
    return chunks;
  }
};
var VOXMesh = class extends Mesh {
  /**
   * Constructs a new VOX mesh.
   *
   * @param {Object} chunk - A VOX chunk loaded via {@link VOXLoader}.
   */
  constructor(chunk) {
    const data2 = chunk.data;
    const size2 = chunk.size;
    const palette = chunk.palette;
    const vertices = [];
    const colors = [];
    const nx = [0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1];
    const px = [1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0];
    const py = [0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1];
    const ny = [0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0];
    const nz = [0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0];
    const pz = [0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1];
    const _color5 = new Color();
    function add2(tile, x2, y, z, r, g3, b3) {
      x2 -= size2.x / 2;
      y -= size2.z / 2;
      z += size2.y / 2;
      for (let i = 0; i < 18; i += 3) {
        _color5.setRGB(r, g3, b3, SRGBColorSpace);
        vertices.push(tile[i + 0] + x2, tile[i + 1] + y, tile[i + 2] + z);
        colors.push(_color5.r, _color5.g, _color5.b);
      }
    }
    const offsety = size2.x;
    const offsetz = size2.x * size2.y;
    const array = new Uint8Array(size2.x * size2.y * size2.z);
    for (let j2 = 0; j2 < data2.length; j2 += 4) {
      const x2 = data2[j2 + 0];
      const y = data2[j2 + 1];
      const z = data2[j2 + 2];
      const index2 = x2 + y * offsety + z * offsetz;
      array[index2] = 255;
    }
    let hasColors = false;
    for (let j2 = 0; j2 < data2.length; j2 += 4) {
      const x2 = data2[j2 + 0];
      const y = data2[j2 + 1];
      const z = data2[j2 + 2];
      const c2 = data2[j2 + 3];
      const hex = palette[c2];
      const r = (hex >> 0 & 255) / 255;
      const g3 = (hex >> 8 & 255) / 255;
      const b3 = (hex >> 16 & 255) / 255;
      if (r > 0 || g3 > 0 || b3 > 0) hasColors = true;
      const index2 = x2 + y * offsety + z * offsetz;
      if (array[index2 + 1] === 0 || x2 === size2.x - 1) add2(px, x2, z, -y, r, g3, b3);
      if (array[index2 - 1] === 0 || x2 === 0) add2(nx, x2, z, -y, r, g3, b3);
      if (array[index2 + offsety] === 0 || y === size2.y - 1) add2(ny, x2, z, -y, r, g3, b3);
      if (array[index2 - offsety] === 0 || y === 0) add2(py, x2, z, -y, r, g3, b3);
      if (array[index2 + offsetz] === 0 || z === size2.z - 1) add2(pz, x2, z, -y, r, g3, b3);
      if (array[index2 - offsetz] === 0 || z === 0) add2(nz, x2, z, -y, r, g3, b3);
    }
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    geometry.computeVertexNormals();
    const material = new MeshStandardMaterial();
    if (hasColors) {
      geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
      material.vertexColors = true;
    }
    super(geometry, material);
  }
};
var VOXData3DTexture = class extends Data3DTexture {
  /**
   * Constructs a new VOX 3D texture.
   *
   * @param {Object} chunk - A VOX chunk loaded via {@link VOXLoader}.
   */
  constructor(chunk) {
    const data2 = chunk.data;
    const size2 = chunk.size;
    const offsety = size2.x;
    const offsetz = size2.x * size2.y;
    const array = new Uint8Array(size2.x * size2.y * size2.z);
    for (let j2 = 0; j2 < data2.length; j2 += 4) {
      const x2 = data2[j2 + 0];
      const y = data2[j2 + 1];
      const z = data2[j2 + 2];
      const index2 = x2 + y * offsety + z * offsetz;
      array[index2] = 255;
    }
    super(array, size2.x, size2.y, size2.z);
    this.format = RedFormat;
    this.minFilter = NearestFilter;
    this.magFilter = LinearFilter;
    this.unpackAlignment = 1;
    this.needsUpdate = true;
  }
};

// node_modules/three/examples/jsm/libs/chevrotain.module.min.js
var R2 = (t3, e) => () => (e || (e = { exports: {} }, t3(e.exports, e)), e.exports);
var Er = R2((Pt) => {
  "use strict";
  Object.defineProperty(Pt, "__esModule", { value: true });
  Pt.VERSION = void 0;
  Pt.VERSION = "9.0.1";
});
var k = R2((exports, module) => {
  "use strict";
  var __spreadArray = exports && exports.__spreadArray || function(t3, e) {
    for (var r = 0, n2 = e.length, i = t3.length; r < n2; r++, i++) t3[i] = e[r];
    return t3;
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.toFastProperties = exports.timer = exports.peek = exports.isES2015MapSupported = exports.PRINT_WARNING = exports.PRINT_ERROR = exports.packArray = exports.IDENTITY = exports.NOOP = exports.merge = exports.groupBy = exports.defaults = exports.assignNoOverwrite = exports.assign = exports.zipObject = exports.sortBy = exports.indexOf = exports.some = exports.difference = exports.every = exports.isObject = exports.isRegExp = exports.isArray = exports.partial = exports.uniq = exports.compact = exports.reduce = exports.findAll = exports.find = exports.cloneObj = exports.cloneArr = exports.contains = exports.has = exports.pick = exports.reject = exports.filter = exports.dropRight = exports.drop = exports.isFunction = exports.isUndefined = exports.isString = exports.forEach = exports.last = exports.first = exports.flatten = exports.map = exports.mapValues = exports.values = exports.keys = exports.isEmpty = void 0;
  function isEmpty(t3) {
    return t3 && t3.length === 0;
  }
  exports.isEmpty = isEmpty;
  function keys(t3) {
    return t3 == null ? [] : Object.keys(t3);
  }
  exports.keys = keys;
  function values(t3) {
    for (var e = [], r = Object.keys(t3), n2 = 0; n2 < r.length; n2++) e.push(t3[r[n2]]);
    return e;
  }
  exports.values = values;
  function mapValues(t3, e) {
    for (var r = [], n2 = keys(t3), i = 0; i < n2.length; i++) {
      var a2 = n2[i];
      r.push(e.call(null, t3[a2], a2));
    }
    return r;
  }
  exports.mapValues = mapValues;
  function map(t3, e) {
    for (var r = [], n2 = 0; n2 < t3.length; n2++) r.push(e.call(null, t3[n2], n2));
    return r;
  }
  exports.map = map;
  function flatten(t3) {
    for (var e = [], r = 0; r < t3.length; r++) {
      var n2 = t3[r];
      Array.isArray(n2) ? e = e.concat(flatten(n2)) : e.push(n2);
    }
    return e;
  }
  exports.flatten = flatten;
  function first(t3) {
    return isEmpty(t3) ? void 0 : t3[0];
  }
  exports.first = first;
  function last(t3) {
    var e = t3 && t3.length;
    return e ? t3[e - 1] : void 0;
  }
  exports.last = last;
  function forEach(t3, e) {
    if (Array.isArray(t3)) for (var r = 0; r < t3.length; r++) e.call(null, t3[r], r);
    else if (isObject(t3)) for (var n2 = keys(t3), r = 0; r < n2.length; r++) {
      var i = n2[r], a2 = t3[i];
      e.call(null, a2, i);
    }
    else throw Error("non exhaustive match");
  }
  exports.forEach = forEach;
  function isString(t3) {
    return typeof t3 == "string";
  }
  exports.isString = isString;
  function isUndefined(t3) {
    return t3 === void 0;
  }
  exports.isUndefined = isUndefined;
  function isFunction(t3) {
    return t3 instanceof Function;
  }
  exports.isFunction = isFunction;
  function drop(t3, e) {
    return e === void 0 && (e = 1), t3.slice(e, t3.length);
  }
  exports.drop = drop;
  function dropRight(t3, e) {
    return e === void 0 && (e = 1), t3.slice(0, t3.length - e);
  }
  exports.dropRight = dropRight;
  function filter(t3, e) {
    var r = [];
    if (Array.isArray(t3)) for (var n2 = 0; n2 < t3.length; n2++) {
      var i = t3[n2];
      e.call(null, i) && r.push(i);
    }
    return r;
  }
  exports.filter = filter;
  function reject(t3, e) {
    return filter(t3, function(r) {
      return !e(r);
    });
  }
  exports.reject = reject;
  function pick(t3, e) {
    for (var r = Object.keys(t3), n2 = {}, i = 0; i < r.length; i++) {
      var a2 = r[i], o = t3[a2];
      e(o) && (n2[a2] = o);
    }
    return n2;
  }
  exports.pick = pick;
  function has(t3, e) {
    return isObject(t3) ? t3.hasOwnProperty(e) : false;
  }
  exports.has = has;
  function contains(t3, e) {
    return find(t3, function(r) {
      return r === e;
    }) !== void 0;
  }
  exports.contains = contains;
  function cloneArr(t3) {
    for (var e = [], r = 0; r < t3.length; r++) e.push(t3[r]);
    return e;
  }
  exports.cloneArr = cloneArr;
  function cloneObj(t3) {
    var e = {};
    for (var r in t3) Object.prototype.hasOwnProperty.call(t3, r) && (e[r] = t3[r]);
    return e;
  }
  exports.cloneObj = cloneObj;
  function find(t3, e) {
    for (var r = 0; r < t3.length; r++) {
      var n2 = t3[r];
      if (e.call(null, n2)) return n2;
    }
  }
  exports.find = find;
  function findAll(t3, e) {
    for (var r = [], n2 = 0; n2 < t3.length; n2++) {
      var i = t3[n2];
      e.call(null, i) && r.push(i);
    }
    return r;
  }
  exports.findAll = findAll;
  function reduce(t3, e, r) {
    for (var n2 = Array.isArray(t3), i = n2 ? t3 : values(t3), a2 = n2 ? [] : keys(t3), o = r, s = 0; s < i.length; s++) o = e.call(null, o, i[s], n2 ? s : a2[s]);
    return o;
  }
  exports.reduce = reduce;
  function compact(t3) {
    return reject(t3, function(e) {
      return e == null;
    });
  }
  exports.compact = compact;
  function uniq(t3, e) {
    e === void 0 && (e = function(n2) {
      return n2;
    });
    var r = [];
    return reduce(t3, function(n2, i) {
      var a2 = e(i);
      return contains(r, a2) ? n2 : (r.push(a2), n2.concat(i));
    }, []);
  }
  exports.uniq = uniq;
  function partial(t3) {
    for (var e = [], r = 1; r < arguments.length; r++) e[r - 1] = arguments[r];
    var n2 = [null], i = n2.concat(e);
    return Function.bind.apply(t3, i);
  }
  exports.partial = partial;
  function isArray(t3) {
    return Array.isArray(t3);
  }
  exports.isArray = isArray;
  function isRegExp(t3) {
    return t3 instanceof RegExp;
  }
  exports.isRegExp = isRegExp;
  function isObject(t3) {
    return t3 instanceof Object;
  }
  exports.isObject = isObject;
  function every(t3, e) {
    for (var r = 0; r < t3.length; r++) if (!e(t3[r], r)) return false;
    return true;
  }
  exports.every = every;
  function difference(t3, e) {
    return reject(t3, function(r) {
      return contains(e, r);
    });
  }
  exports.difference = difference;
  function some(t3, e) {
    for (var r = 0; r < t3.length; r++) if (e(t3[r])) return true;
    return false;
  }
  exports.some = some;
  function indexOf(t3, e) {
    for (var r = 0; r < t3.length; r++) if (t3[r] === e) return r;
    return -1;
  }
  exports.indexOf = indexOf;
  function sortBy(t3, e) {
    var r = cloneArr(t3);
    return r.sort(function(n2, i) {
      return e(n2) - e(i);
    }), r;
  }
  exports.sortBy = sortBy;
  function zipObject(t3, e) {
    if (t3.length !== e.length) throw Error("can't zipObject with different number of keys and values!");
    for (var r = {}, n2 = 0; n2 < t3.length; n2++) r[t3[n2]] = e[n2];
    return r;
  }
  exports.zipObject = zipObject;
  function assign(t3) {
    for (var e = [], r = 1; r < arguments.length; r++) e[r - 1] = arguments[r];
    for (var n2 = 0; n2 < e.length; n2++) for (var i = e[n2], a2 = keys(i), o = 0; o < a2.length; o++) {
      var s = a2[o];
      t3[s] = i[s];
    }
    return t3;
  }
  exports.assign = assign;
  function assignNoOverwrite(t3) {
    for (var e = [], r = 1; r < arguments.length; r++) e[r - 1] = arguments[r];
    for (var n2 = 0; n2 < e.length; n2++) for (var i = e[n2], a2 = keys(i), o = 0; o < a2.length; o++) {
      var s = a2[o];
      has(t3, s) || (t3[s] = i[s]);
    }
    return t3;
  }
  exports.assignNoOverwrite = assignNoOverwrite;
  function defaults() {
    for (var t3 = [], e = 0; e < arguments.length; e++) t3[e] = arguments[e];
    return assignNoOverwrite.apply(void 0, __spreadArray([{}], t3));
  }
  exports.defaults = defaults;
  function groupBy(t3, e) {
    var r = {};
    return forEach(t3, function(n2) {
      var i = e(n2), a2 = r[i];
      a2 ? a2.push(n2) : r[i] = [n2];
    }), r;
  }
  exports.groupBy = groupBy;
  function merge(t3, e) {
    for (var r = cloneObj(t3), n2 = keys(e), i = 0; i < n2.length; i++) {
      var a2 = n2[i], o = e[a2];
      r[a2] = o;
    }
    return r;
  }
  exports.merge = merge;
  function NOOP() {
  }
  exports.NOOP = NOOP;
  function IDENTITY(t3) {
    return t3;
  }
  exports.IDENTITY = IDENTITY;
  function packArray(t3) {
    for (var e = [], r = 0; r < t3.length; r++) {
      var n2 = t3[r];
      e.push(n2 !== void 0 ? n2 : void 0);
    }
    return e;
  }
  exports.packArray = packArray;
  function PRINT_ERROR(t3) {
    console && console.error && console.error("Error: " + t3);
  }
  exports.PRINT_ERROR = PRINT_ERROR;
  function PRINT_WARNING(t3) {
    console && console.warn && console.warn("Warning: " + t3);
  }
  exports.PRINT_WARNING = PRINT_WARNING;
  function isES2015MapSupported() {
    return typeof Map == "function";
  }
  exports.isES2015MapSupported = isES2015MapSupported;
  function peek(t3) {
    return t3[t3.length - 1];
  }
  exports.peek = peek;
  function timer(t3) {
    var e = (/* @__PURE__ */ new Date()).getTime(), r = t3(), n2 = (/* @__PURE__ */ new Date()).getTime(), i = n2 - e;
    return { time: i, value: r };
  }
  exports.timer = timer;
  function toFastProperties(toBecomeFast) {
    function FakeConstructor() {
    }
    FakeConstructor.prototype = toBecomeFast;
    var fakeInstance = new FakeConstructor();
    function fakeAccess() {
      return typeof fakeInstance.bar;
    }
    return fakeAccess(), fakeAccess(), toBecomeFast;
    eval(toBecomeFast);
  }
  exports.toFastProperties = toFastProperties;
});
var xt2 = R2((sn, St) => {
  (function(t3, e) {
    typeof define == "function" && define.amd ? define([], e) : typeof St == "object" && St.exports ? St.exports = e() : t3.regexpToAst = e();
  })(typeof self != "undefined" ? self : sn, function() {
    function t3() {
    }
    t3.prototype.saveState = function() {
      return { idx: this.idx, input: this.input, groupIdx: this.groupIdx };
    }, t3.prototype.restoreState = function(u2) {
      this.idx = u2.idx, this.input = u2.input, this.groupIdx = u2.groupIdx;
    }, t3.prototype.pattern = function(u2) {
      this.idx = 0, this.input = u2, this.groupIdx = 0, this.consumeChar("/");
      var d = this.disjunction();
      this.consumeChar("/");
      for (var A2 = { type: "Flags", loc: { begin: this.idx, end: u2.length }, global: false, ignoreCase: false, multiLine: false, unicode: false, sticky: false }; this.isRegExpFlag(); ) switch (this.popChar()) {
        case "g":
          o(A2, "global");
          break;
        case "i":
          o(A2, "ignoreCase");
          break;
        case "m":
          o(A2, "multiLine");
          break;
        case "u":
          o(A2, "unicode");
          break;
        case "y":
          o(A2, "sticky");
          break;
      }
      if (this.idx !== this.input.length) throw Error("Redundant input: " + this.input.substring(this.idx));
      return { type: "Pattern", flags: A2, value: d, loc: this.loc(0) };
    }, t3.prototype.disjunction = function() {
      var u2 = [], d = this.idx;
      for (u2.push(this.alternative()); this.peekChar() === "|"; ) this.consumeChar("|"), u2.push(this.alternative());
      return { type: "Disjunction", value: u2, loc: this.loc(d) };
    }, t3.prototype.alternative = function() {
      for (var u2 = [], d = this.idx; this.isTerm(); ) u2.push(this.term());
      return { type: "Alternative", value: u2, loc: this.loc(d) };
    }, t3.prototype.term = function() {
      return this.isAssertion() ? this.assertion() : this.atom();
    }, t3.prototype.assertion = function() {
      var u2 = this.idx;
      switch (this.popChar()) {
        case "^":
          return { type: "StartAnchor", loc: this.loc(u2) };
        case "$":
          return { type: "EndAnchor", loc: this.loc(u2) };
        case "\\":
          switch (this.popChar()) {
            case "b":
              return { type: "WordBoundary", loc: this.loc(u2) };
            case "B":
              return { type: "NonWordBoundary", loc: this.loc(u2) };
          }
          throw Error("Invalid Assertion Escape");
        case "(":
          this.consumeChar("?");
          var d;
          switch (this.popChar()) {
            case "=":
              d = "Lookahead";
              break;
            case "!":
              d = "NegativeLookahead";
              break;
          }
          s(d);
          var A2 = this.disjunction();
          return this.consumeChar(")"), { type: d, value: A2, loc: this.loc(u2) };
      }
      c2();
    }, t3.prototype.quantifier = function(u2) {
      var d, A2 = this.idx;
      switch (this.popChar()) {
        case "*":
          d = { atLeast: 0, atMost: Infinity };
          break;
        case "+":
          d = { atLeast: 1, atMost: Infinity };
          break;
        case "?":
          d = { atLeast: 0, atMost: 1 };
          break;
        case "{":
          var _ = this.integerIncludingZero();
          switch (this.popChar()) {
            case "}":
              d = { atLeast: _, atMost: _ };
              break;
            case ",":
              var g3;
              this.isDigit() ? (g3 = this.integerIncludingZero(), d = { atLeast: _, atMost: g3 }) : d = { atLeast: _, atMost: Infinity }, this.consumeChar("}");
              break;
          }
          if (u2 === true && d === void 0) return;
          s(d);
          break;
      }
      if (!(u2 === true && d === void 0)) return s(d), this.peekChar(0) === "?" ? (this.consumeChar("?"), d.greedy = false) : d.greedy = true, d.type = "Quantifier", d.loc = this.loc(A2), d;
    }, t3.prototype.atom = function() {
      var u2, d = this.idx;
      switch (this.peekChar()) {
        case ".":
          u2 = this.dotAll();
          break;
        case "\\":
          u2 = this.atomEscape();
          break;
        case "[":
          u2 = this.characterClass();
          break;
        case "(":
          u2 = this.group();
          break;
      }
      return u2 === void 0 && this.isPatternCharacter() && (u2 = this.patternCharacter()), s(u2), u2.loc = this.loc(d), this.isQuantifier() && (u2.quantifier = this.quantifier()), u2;
    }, t3.prototype.dotAll = function() {
      return this.consumeChar("."), { type: "Set", complement: true, value: [i(`
`), i("\r"), i("\u2028"), i("\u2029")] };
    }, t3.prototype.atomEscape = function() {
      switch (this.consumeChar("\\"), this.peekChar()) {
        case "1":
        case "2":
        case "3":
        case "4":
        case "5":
        case "6":
        case "7":
        case "8":
        case "9":
          return this.decimalEscapeAtom();
        case "d":
        case "D":
        case "s":
        case "S":
        case "w":
        case "W":
          return this.characterClassEscape();
        case "f":
        case "n":
        case "r":
        case "t":
        case "v":
          return this.controlEscapeAtom();
        case "c":
          return this.controlLetterEscapeAtom();
        case "0":
          return this.nulCharacterAtom();
        case "x":
          return this.hexEscapeSequenceAtom();
        case "u":
          return this.regExpUnicodeEscapeSequenceAtom();
        default:
          return this.identityEscapeAtom();
      }
    }, t3.prototype.decimalEscapeAtom = function() {
      var u2 = this.positiveInteger();
      return { type: "GroupBackReference", value: u2 };
    }, t3.prototype.characterClassEscape = function() {
      var u2, d = false;
      switch (this.popChar()) {
        case "d":
          u2 = p;
          break;
        case "D":
          u2 = p, d = true;
          break;
        case "s":
          u2 = m;
          break;
        case "S":
          u2 = m, d = true;
          break;
        case "w":
          u2 = l2;
          break;
        case "W":
          u2 = l2, d = true;
          break;
      }
      return s(u2), { type: "Set", value: u2, complement: d };
    }, t3.prototype.controlEscapeAtom = function() {
      var u2;
      switch (this.popChar()) {
        case "f":
          u2 = i("\f");
          break;
        case "n":
          u2 = i(`
`);
          break;
        case "r":
          u2 = i("\r");
          break;
        case "t":
          u2 = i("	");
          break;
        case "v":
          u2 = i("\v");
          break;
      }
      return s(u2), { type: "Character", value: u2 };
    }, t3.prototype.controlLetterEscapeAtom = function() {
      this.consumeChar("c");
      var u2 = this.popChar();
      if (/[a-zA-Z]/.test(u2) === false) throw Error("Invalid ");
      var d = u2.toUpperCase().charCodeAt(0) - 64;
      return { type: "Character", value: d };
    }, t3.prototype.nulCharacterAtom = function() {
      return this.consumeChar("0"), { type: "Character", value: i("\0") };
    }, t3.prototype.hexEscapeSequenceAtom = function() {
      return this.consumeChar("x"), this.parseHexDigits(2);
    }, t3.prototype.regExpUnicodeEscapeSequenceAtom = function() {
      return this.consumeChar("u"), this.parseHexDigits(4);
    }, t3.prototype.identityEscapeAtom = function() {
      var u2 = this.popChar();
      return { type: "Character", value: i(u2) };
    }, t3.prototype.classPatternCharacterAtom = function() {
      switch (this.peekChar()) {
        case `
`:
        case "\r":
        case "\u2028":
        case "\u2029":
        case "\\":
        case "]":
          throw Error("TBD");
        default:
          var u2 = this.popChar();
          return { type: "Character", value: i(u2) };
      }
    }, t3.prototype.characterClass = function() {
      var u2 = [], d = false;
      for (this.consumeChar("["), this.peekChar(0) === "^" && (this.consumeChar("^"), d = true); this.isClassAtom(); ) {
        var A2 = this.classAtom(), _ = A2.type === "Character";
        if (_ && this.isRangeDash()) {
          this.consumeChar("-");
          var g3 = this.classAtom(), y = g3.type === "Character";
          if (y) {
            if (g3.value < A2.value) throw Error("Range out of order in character class");
            u2.push({ from: A2.value, to: g3.value });
          } else a2(A2.value, u2), u2.push(i("-")), a2(g3.value, u2);
        } else a2(A2.value, u2);
      }
      return this.consumeChar("]"), { type: "Set", complement: d, value: u2 };
    }, t3.prototype.classAtom = function() {
      switch (this.peekChar()) {
        case "]":
        case `
`:
        case "\r":
        case "\u2028":
        case "\u2029":
          throw Error("TBD");
        case "\\":
          return this.classEscape();
        default:
          return this.classPatternCharacterAtom();
      }
    }, t3.prototype.classEscape = function() {
      switch (this.consumeChar("\\"), this.peekChar()) {
        case "b":
          return this.consumeChar("b"), { type: "Character", value: i("\b") };
        case "d":
        case "D":
        case "s":
        case "S":
        case "w":
        case "W":
          return this.characterClassEscape();
        case "f":
        case "n":
        case "r":
        case "t":
        case "v":
          return this.controlEscapeAtom();
        case "c":
          return this.controlLetterEscapeAtom();
        case "0":
          return this.nulCharacterAtom();
        case "x":
          return this.hexEscapeSequenceAtom();
        case "u":
          return this.regExpUnicodeEscapeSequenceAtom();
        default:
          return this.identityEscapeAtom();
      }
    }, t3.prototype.group = function() {
      var u2 = true;
      switch (this.consumeChar("("), this.peekChar(0)) {
        case "?":
          this.consumeChar("?"), this.consumeChar(":"), u2 = false;
          break;
        default:
          this.groupIdx++;
          break;
      }
      var d = this.disjunction();
      this.consumeChar(")");
      var A2 = { type: "Group", capturing: u2, value: d };
      return u2 && (A2.idx = this.groupIdx), A2;
    }, t3.prototype.positiveInteger = function() {
      var u2 = this.popChar();
      if (n2.test(u2) === false) throw Error("Expecting a positive integer");
      for (; r.test(this.peekChar(0)); ) u2 += this.popChar();
      return parseInt(u2, 10);
    }, t3.prototype.integerIncludingZero = function() {
      var u2 = this.popChar();
      if (r.test(u2) === false) throw Error("Expecting an integer");
      for (; r.test(this.peekChar(0)); ) u2 += this.popChar();
      return parseInt(u2, 10);
    }, t3.prototype.patternCharacter = function() {
      var u2 = this.popChar();
      switch (u2) {
        case `
`:
        case "\r":
        case "\u2028":
        case "\u2029":
        case "^":
        case "$":
        case "\\":
        case ".":
        case "*":
        case "+":
        case "?":
        case "(":
        case ")":
        case "[":
        case "|":
          throw Error("TBD");
        default:
          return { type: "Character", value: i(u2) };
      }
    }, t3.prototype.isRegExpFlag = function() {
      switch (this.peekChar(0)) {
        case "g":
        case "i":
        case "m":
        case "u":
        case "y":
          return true;
        default:
          return false;
      }
    }, t3.prototype.isRangeDash = function() {
      return this.peekChar() === "-" && this.isClassAtom(1);
    }, t3.prototype.isDigit = function() {
      return r.test(this.peekChar(0));
    }, t3.prototype.isClassAtom = function(u2) {
      switch (u2 === void 0 && (u2 = 0), this.peekChar(u2)) {
        case "]":
        case `
`:
        case "\r":
        case "\u2028":
        case "\u2029":
          return false;
        default:
          return true;
      }
    }, t3.prototype.isTerm = function() {
      return this.isAtom() || this.isAssertion();
    }, t3.prototype.isAtom = function() {
      if (this.isPatternCharacter()) return true;
      switch (this.peekChar(0)) {
        case ".":
        case "\\":
        case "[":
        case "(":
          return true;
        default:
          return false;
      }
    }, t3.prototype.isAssertion = function() {
      switch (this.peekChar(0)) {
        case "^":
        case "$":
          return true;
        case "\\":
          switch (this.peekChar(1)) {
            case "b":
            case "B":
              return true;
            default:
              return false;
          }
        case "(":
          return this.peekChar(1) === "?" && (this.peekChar(2) === "=" || this.peekChar(2) === "!");
        default:
          return false;
      }
    }, t3.prototype.isQuantifier = function() {
      var u2 = this.saveState();
      try {
        return this.quantifier(true) !== void 0;
      } catch (d) {
        return false;
      } finally {
        this.restoreState(u2);
      }
    }, t3.prototype.isPatternCharacter = function() {
      switch (this.peekChar()) {
        case "^":
        case "$":
        case "\\":
        case ".":
        case "*":
        case "+":
        case "?":
        case "(":
        case ")":
        case "[":
        case "|":
        case "/":
        case `
`:
        case "\r":
        case "\u2028":
        case "\u2029":
          return false;
        default:
          return true;
      }
    }, t3.prototype.parseHexDigits = function(u2) {
      for (var d = "", A2 = 0; A2 < u2; A2++) {
        var _ = this.popChar();
        if (e.test(_) === false) throw Error("Expecting a HexDecimal digits");
        d += _;
      }
      var g3 = parseInt(d, 16);
      return { type: "Character", value: g3 };
    }, t3.prototype.peekChar = function(u2) {
      return u2 === void 0 && (u2 = 0), this.input[this.idx + u2];
    }, t3.prototype.popChar = function() {
      var u2 = this.peekChar(0);
      return this.consumeChar(), u2;
    }, t3.prototype.consumeChar = function(u2) {
      if (u2 !== void 0 && this.input[this.idx] !== u2) throw Error("Expected: '" + u2 + "' but found: '" + this.input[this.idx] + "' at offset: " + this.idx);
      if (this.idx >= this.input.length) throw Error("Unexpected end of input");
      this.idx++;
    }, t3.prototype.loc = function(u2) {
      return { begin: u2, end: this.idx };
    };
    var e = /[0-9a-fA-F]/, r = /[0-9]/, n2 = /[1-9]/;
    function i(u2) {
      return u2.charCodeAt(0);
    }
    function a2(u2, d) {
      u2.length !== void 0 ? u2.forEach(function(A2) {
        d.push(A2);
      }) : d.push(u2);
    }
    function o(u2, d) {
      if (u2[d] === true) throw "duplicate flag " + d;
      u2[d] = true;
    }
    function s(u2) {
      if (u2 === void 0) throw Error("Internal Error - Should never get here!");
    }
    function c2() {
      throw Error("Internal Error - Should never get here!");
    }
    var f, p = [];
    for (f = i("0"); f <= i("9"); f++) p.push(f);
    var l2 = [i("_")].concat(p);
    for (f = i("a"); f <= i("z"); f++) l2.push(f);
    for (f = i("A"); f <= i("Z"); f++) l2.push(f);
    var m = [i(" "), i("\f"), i(`
`), i("\r"), i("	"), i("\v"), i("	"), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i("\u2028"), i("\u2029"), i(" "), i(" "), i("　"), i("\uFEFF")];
    function v() {
    }
    return v.prototype.visitChildren = function(u2) {
      for (var d in u2) {
        var A2 = u2[d];
        u2.hasOwnProperty(d) && (A2.type !== void 0 ? this.visit(A2) : Array.isArray(A2) && A2.forEach(function(_) {
          this.visit(_);
        }, this));
      }
    }, v.prototype.visit = function(u2) {
      switch (u2.type) {
        case "Pattern":
          this.visitPattern(u2);
          break;
        case "Flags":
          this.visitFlags(u2);
          break;
        case "Disjunction":
          this.visitDisjunction(u2);
          break;
        case "Alternative":
          this.visitAlternative(u2);
          break;
        case "StartAnchor":
          this.visitStartAnchor(u2);
          break;
        case "EndAnchor":
          this.visitEndAnchor(u2);
          break;
        case "WordBoundary":
          this.visitWordBoundary(u2);
          break;
        case "NonWordBoundary":
          this.visitNonWordBoundary(u2);
          break;
        case "Lookahead":
          this.visitLookahead(u2);
          break;
        case "NegativeLookahead":
          this.visitNegativeLookahead(u2);
          break;
        case "Character":
          this.visitCharacter(u2);
          break;
        case "Set":
          this.visitSet(u2);
          break;
        case "Group":
          this.visitGroup(u2);
          break;
        case "GroupBackReference":
          this.visitGroupBackReference(u2);
          break;
        case "Quantifier":
          this.visitQuantifier(u2);
          break;
      }
      this.visitChildren(u2);
    }, v.prototype.visitPattern = function(u2) {
    }, v.prototype.visitFlags = function(u2) {
    }, v.prototype.visitDisjunction = function(u2) {
    }, v.prototype.visitAlternative = function(u2) {
    }, v.prototype.visitStartAnchor = function(u2) {
    }, v.prototype.visitEndAnchor = function(u2) {
    }, v.prototype.visitWordBoundary = function(u2) {
    }, v.prototype.visitNonWordBoundary = function(u2) {
    }, v.prototype.visitLookahead = function(u2) {
    }, v.prototype.visitNegativeLookahead = function(u2) {
    }, v.prototype.visitCharacter = function(u2) {
    }, v.prototype.visitSet = function(u2) {
    }, v.prototype.visitGroup = function(u2) {
    }, v.prototype.visitGroupBackReference = function(u2) {
    }, v.prototype.visitQuantifier = function(u2) {
    }, { RegExpParser: t3, BaseRegExpVisitor: v, VERSION: "0.5.0" };
  });
});
var Lt = R2((He) => {
  "use strict";
  Object.defineProperty(He, "__esModule", { value: true });
  He.clearRegExpParserCache = He.getRegExpAst = void 0;
  var Ga = xt2(), Ct2 = {}, Wa = new Ga.RegExpParser();
  function Ba(t3) {
    var e = t3.toString();
    if (Ct2.hasOwnProperty(e)) return Ct2[e];
    var r = Wa.pattern(e);
    return Ct2[e] = r, r;
  }
  He.getRegExpAst = Ba;
  function qa() {
    Ct2 = {};
  }
  He.clearRegExpParserCache = qa;
});
var pn = R2((re) => {
  "use strict";
  var ja = re && re.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(re, "__esModule", { value: true });
  re.canMatchCharCode = re.firstCharOptimizedIndices = re.getOptimizedStartCodesIndices = re.failedOptimizationPrefixMsg = void 0;
  var un = xt2(), pe = k(), cn = Lt(), Ce = Tr(), ln2 = "Complement Sets are not supported for first char optimization";
  re.failedOptimizationPrefixMsg = `Unable to use "first char" lexer optimizations:
`;
  function Va(t3, e) {
    e === void 0 && (e = false);
    try {
      var r = cn.getRegExpAst(t3), n2 = Mt(r.value, {}, r.flags.ignoreCase);
      return n2;
    } catch (a2) {
      if (a2.message === ln2) e && pe.PRINT_WARNING("" + re.failedOptimizationPrefixMsg + ("	Unable to optimize: < " + t3.toString() + ` >
`) + `	Complement Sets cannot be automatically optimized.
	This will disable the lexer's first char optimizations.
	See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);
      else {
        var i = "";
        e && (i = `
	This will disable the lexer's first char optimizations.
	See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`), pe.PRINT_ERROR(re.failedOptimizationPrefixMsg + `
` + ("	Failed parsing: < " + t3.toString() + ` >
`) + ("	Using the regexp-to-ast library version: " + un.VERSION + `
`) + "	Please open an issue at: https://github.com/bd82/regexp-to-ast/issues" + i);
      }
    }
    return [];
  }
  re.getOptimizedStartCodesIndices = Va;
  function Mt(t3, e, r) {
    switch (t3.type) {
      case "Disjunction":
        for (var n2 = 0; n2 < t3.value.length; n2++) Mt(t3.value[n2], e, r);
        break;
      case "Alternative":
        for (var i = t3.value, n2 = 0; n2 < i.length; n2++) {
          var a2 = i[n2];
          switch (a2.type) {
            case "EndAnchor":
            case "GroupBackReference":
            case "Lookahead":
            case "NegativeLookahead":
            case "StartAnchor":
            case "WordBoundary":
            case "NonWordBoundary":
              continue;
          }
          var o = a2;
          switch (o.type) {
            case "Character":
              bt(o.value, e, r);
              break;
            case "Set":
              if (o.complement === true) throw Error(ln2);
              pe.forEach(o.value, function(f) {
                if (typeof f == "number") bt(f, e, r);
                else {
                  var p = f;
                  if (r === true) for (var l2 = p.from; l2 <= p.to; l2++) bt(l2, e, r);
                  else {
                    for (var l2 = p.from; l2 <= p.to && l2 < Ce.minOptimizationVal; l2++) bt(l2, e, r);
                    if (p.to >= Ce.minOptimizationVal) for (var m = p.from >= Ce.minOptimizationVal ? p.from : Ce.minOptimizationVal, v = p.to, u2 = Ce.charCodeToOptimizedIndex(m), d = Ce.charCodeToOptimizedIndex(v), A2 = u2; A2 <= d; A2++) e[A2] = A2;
                  }
                }
              });
              break;
            case "Group":
              Mt(o.value, e, r);
              break;
            default:
              throw Error("Non Exhaustive Match");
          }
          var s = o.quantifier !== void 0 && o.quantifier.atLeast === 0;
          if (o.type === "Group" && yr(o) === false || o.type !== "Group" && s === false) break;
        }
        break;
      default:
        throw Error("non exhaustive match!");
    }
    return pe.values(e);
  }
  re.firstCharOptimizedIndices = Mt;
  function bt(t3, e, r) {
    var n2 = Ce.charCodeToOptimizedIndex(t3);
    e[n2] = n2, r === true && Ka(t3, e);
  }
  function Ka(t3, e) {
    var r = String.fromCharCode(t3), n2 = r.toUpperCase();
    if (n2 !== r) {
      var i = Ce.charCodeToOptimizedIndex(n2.charCodeAt(0));
      e[i] = i;
    } else {
      var a2 = r.toLowerCase();
      if (a2 !== r) {
        var i = Ce.charCodeToOptimizedIndex(a2.charCodeAt(0));
        e[i] = i;
      }
    }
  }
  function fn(t3, e) {
    return pe.find(t3.value, function(r) {
      if (typeof r == "number") return pe.contains(e, r);
      var n2 = r;
      return pe.find(e, function(i) {
        return n2.from <= i && i <= n2.to;
      }) !== void 0;
    });
  }
  function yr(t3) {
    return t3.quantifier && t3.quantifier.atLeast === 0 ? true : t3.value ? pe.isArray(t3.value) ? pe.every(t3.value, yr) : yr(t3.value) : false;
  }
  var za = function(t3) {
    ja(e, t3);
    function e(r) {
      var n2 = t3.call(this) || this;
      return n2.targetCharCodes = r, n2.found = false, n2;
    }
    return e.prototype.visitChildren = function(r) {
      if (this.found !== true) {
        switch (r.type) {
          case "Lookahead":
            this.visitLookahead(r);
            return;
          case "NegativeLookahead":
            this.visitNegativeLookahead(r);
            return;
        }
        t3.prototype.visitChildren.call(this, r);
      }
    }, e.prototype.visitCharacter = function(r) {
      pe.contains(this.targetCharCodes, r.value) && (this.found = true);
    }, e.prototype.visitSet = function(r) {
      r.complement ? fn(r, this.targetCharCodes) === void 0 && (this.found = true) : fn(r, this.targetCharCodes) !== void 0 && (this.found = true);
    }, e;
  }(un.BaseRegExpVisitor);
  function Ha(t3, e) {
    if (e instanceof RegExp) {
      var r = cn.getRegExpAst(e), n2 = new za(t3);
      return n2.visit(r), n2.found;
    } else return pe.find(e, function(i) {
      return pe.contains(t3, i.charCodeAt(0));
    }) !== void 0;
  }
  re.canMatchCharCode = Ha;
});
var Tr = R2((T2) => {
  "use strict";
  var hn2 = T2 && T2.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(T2, "__esModule", { value: true });
  T2.charCodeToOptimizedIndex = T2.minOptimizationVal = T2.buildLineBreakIssueMessage = T2.LineTerminatorOptimizedTester = T2.isShortPattern = T2.isCustomPattern = T2.cloneEmptyGroups = T2.performWarningRuntimeChecks = T2.performRuntimeChecks = T2.addStickyFlag = T2.addStartOfInput = T2.findUnreachablePatterns = T2.findModesThatDoNotExist = T2.findInvalidGroupType = T2.findDuplicatePatterns = T2.findUnsupportedFlags = T2.findStartOfInputAnchor = T2.findEmptyMatchRegExps = T2.findEndOfInputAnchor = T2.findInvalidPatterns = T2.findMissingPatterns = T2.validatePatterns = T2.analyzeTokenTypes = T2.enableSticky = T2.disableSticky = T2.SUPPORT_STICKY = T2.MODES = T2.DEFAULT_MODE = void 0;
  var dn = xt2(), F = ft(), h = k(), Ye = pn(), vn = Lt(), Ae2 = "PATTERN";
  T2.DEFAULT_MODE = "defaultMode";
  T2.MODES = "modes";
  T2.SUPPORT_STICKY = typeof new RegExp("(?:)").sticky == "boolean";
  function Ya() {
    T2.SUPPORT_STICKY = false;
  }
  T2.disableSticky = Ya;
  function Xa() {
    T2.SUPPORT_STICKY = true;
  }
  T2.enableSticky = Xa;
  function Za(t3, e) {
    e = h.defaults(e, { useSticky: T2.SUPPORT_STICKY, debug: false, safeMode: false, positionTracking: "full", lineTerminatorCharacters: ["\r", `
`], tracer: function(g3, y) {
      return y();
    } });
    var r = e.tracer;
    r("initCharCodeToOptimizedIndexMap", function() {
      $a();
    });
    var n2;
    r("Reject Lexer.NA", function() {
      n2 = h.reject(t3, function(g3) {
        return g3[Ae2] === F.Lexer.NA;
      });
    });
    var i = false, a2;
    r("Transform Patterns", function() {
      i = false, a2 = h.map(n2, function(g3) {
        var y = g3[Ae2];
        if (h.isRegExp(y)) {
          var b3 = y.source;
          return b3.length === 1 && b3 !== "^" && b3 !== "$" && b3 !== "." && !y.ignoreCase ? b3 : b3.length === 2 && b3[0] === "\\" && !h.contains(["d", "D", "s", "S", "t", "r", "n", "t", "0", "c", "b", "B", "f", "v", "w", "W"], b3[1]) ? b3[1] : e.useSticky ? gr(y) : _r(y);
        } else {
          if (h.isFunction(y)) return i = true, { exec: y };
          if (h.has(y, "exec")) return i = true, y;
          if (typeof y == "string") {
            if (y.length === 1) return y;
            var L = y.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"), se = new RegExp(L);
            return e.useSticky ? gr(se) : _r(se);
          } else throw Error("non exhaustive match");
        }
      });
    });
    var o, s, c2, f, p;
    r("misc mapping", function() {
      o = h.map(n2, function(g3) {
        return g3.tokenTypeIdx;
      }), s = h.map(n2, function(g3) {
        var y = g3.GROUP;
        if (y !== F.Lexer.SKIPPED) {
          if (h.isString(y)) return y;
          if (h.isUndefined(y)) return false;
          throw Error("non exhaustive match");
        }
      }), c2 = h.map(n2, function(g3) {
        var y = g3.LONGER_ALT;
        if (y) {
          var b3 = h.indexOf(n2, y);
          return b3;
        }
      }), f = h.map(n2, function(g3) {
        return g3.PUSH_MODE;
      }), p = h.map(n2, function(g3) {
        return h.has(g3, "POP_MODE");
      });
    });
    var l2;
    r("Line Terminator Handling", function() {
      var g3 = Tn(e.lineTerminatorCharacters);
      l2 = h.map(n2, function(y) {
        return false;
      }), e.positionTracking !== "onlyOffset" && (l2 = h.map(n2, function(y) {
        if (h.has(y, "LINE_BREAKS")) return y.LINE_BREAKS;
        if (En(y, g3) === false) return Ye.canMatchCharCode(g3, y.PATTERN);
      }));
    });
    var m, v, u2, d;
    r("Misc Mapping #2", function() {
      m = h.map(n2, Ar), v = h.map(a2, mn2), u2 = h.reduce(n2, function(g3, y) {
        var b3 = y.GROUP;
        return h.isString(b3) && b3 !== F.Lexer.SKIPPED && (g3[b3] = []), g3;
      }, {}), d = h.map(a2, function(g3, y) {
        return { pattern: a2[y], longerAlt: c2[y], canLineTerminator: l2[y], isCustom: m[y], short: v[y], group: s[y], push: f[y], pop: p[y], tokenTypeIdx: o[y], tokenType: n2[y] };
      });
    });
    var A2 = true, _ = [];
    return e.safeMode || r("First Char Optimization", function() {
      _ = h.reduce(n2, function(g3, y, b3) {
        if (typeof y.PATTERN == "string") {
          var L = y.PATTERN.charCodeAt(0), se = Or(L);
          Rr(g3, se, d[b3]);
        } else if (h.isArray(y.START_CHARS_HINT)) {
          var fe;
          h.forEach(y.START_CHARS_HINT, function(ue2) {
            var Q2 = typeof ue2 == "string" ? ue2.charCodeAt(0) : ue2, te3 = Or(Q2);
            fe !== te3 && (fe = te3, Rr(g3, te3, d[b3]));
          });
        } else if (h.isRegExp(y.PATTERN)) if (y.PATTERN.unicode) A2 = false, e.ensureOptimizations && h.PRINT_ERROR("" + Ye.failedOptimizationPrefixMsg + ("	Unable to analyze < " + y.PATTERN.toString() + ` > pattern.
`) + `	The regexp unicode flag is not currently supported by the regexp-to-ast library.
	This will disable the lexer's first char optimizations.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);
        else {
          var Z2 = Ye.getOptimizedStartCodesIndices(y.PATTERN, e.ensureOptimizations);
          h.isEmpty(Z2) && (A2 = false), h.forEach(Z2, function(ue2) {
            Rr(g3, ue2, d[b3]);
          });
        }
        else e.ensureOptimizations && h.PRINT_ERROR("" + Ye.failedOptimizationPrefixMsg + ("	TokenType: <" + y.name + `> is using a custom token pattern without providing <start_chars_hint> parameter.
`) + `	This will disable the lexer's first char optimizations.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`), A2 = false;
        return g3;
      }, []);
    }), r("ArrayPacking", function() {
      _ = h.packArray(_);
    }), { emptyGroups: u2, patternIdxToConfig: d, charCodeToPatternIdxToConfig: _, hasCustom: i, canBeOptimized: A2 };
  }
  T2.analyzeTokenTypes = Za;
  function Ja(t3, e) {
    var r = [], n2 = yn(t3);
    r = r.concat(n2.errors);
    var i = _n2(n2.valid), a2 = i.valid;
    return r = r.concat(i.errors), r = r.concat(Qa(a2)), r = r.concat(gn(a2)), r = r.concat(An(a2, e)), r = r.concat(Rn(a2)), r;
  }
  T2.validatePatterns = Ja;
  function Qa(t3) {
    var e = [], r = h.filter(t3, function(n2) {
      return h.isRegExp(n2[Ae2]);
    });
    return e = e.concat(On(r)), e = e.concat(In2(r)), e = e.concat(kn(r)), e = e.concat(Pn(r)), e = e.concat(Nn(r)), e;
  }
  function yn(t3) {
    var e = h.filter(t3, function(i) {
      return !h.has(i, Ae2);
    }), r = h.map(e, function(i) {
      return { message: "Token Type: ->" + i.name + "<- missing static 'PATTERN' property", type: F.LexerDefinitionErrorType.MISSING_PATTERN, tokenTypes: [i] };
    }), n2 = h.difference(t3, e);
    return { errors: r, valid: n2 };
  }
  T2.findMissingPatterns = yn;
  function _n2(t3) {
    var e = h.filter(t3, function(i) {
      var a2 = i[Ae2];
      return !h.isRegExp(a2) && !h.isFunction(a2) && !h.has(a2, "exec") && !h.isString(a2);
    }), r = h.map(e, function(i) {
      return { message: "Token Type: ->" + i.name + "<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", type: F.LexerDefinitionErrorType.INVALID_PATTERN, tokenTypes: [i] };
    }), n2 = h.difference(t3, e);
    return { errors: r, valid: n2 };
  }
  T2.findInvalidPatterns = _n2;
  var eo = /[^\\][\$]/;
  function On(t3) {
    var e = function(i) {
      hn2(a2, i);
      function a2() {
        var o = i !== null && i.apply(this, arguments) || this;
        return o.found = false, o;
      }
      return a2.prototype.visitEndAnchor = function(o) {
        this.found = true;
      }, a2;
    }(dn.BaseRegExpVisitor), r = h.filter(t3, function(i) {
      var a2 = i[Ae2];
      try {
        var o = vn.getRegExpAst(a2), s = new e();
        return s.visit(o), s.found;
      } catch (c2) {
        return eo.test(a2.source);
      }
    }), n2 = h.map(r, function(i) {
      return { message: `Unexpected RegExp Anchor Error:
	Token Type: ->` + i.name + `<- static 'PATTERN' cannot contain end of input anchor '$'
	See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.`, type: F.LexerDefinitionErrorType.EOI_ANCHOR_FOUND, tokenTypes: [i] };
    });
    return n2;
  }
  T2.findEndOfInputAnchor = On;
  function Nn(t3) {
    var e = h.filter(t3, function(n2) {
      var i = n2[Ae2];
      return i.test("");
    }), r = h.map(e, function(n2) {
      return { message: "Token Type: ->" + n2.name + "<- static 'PATTERN' must not match an empty string", type: F.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, tokenTypes: [n2] };
    });
    return r;
  }
  T2.findEmptyMatchRegExps = Nn;
  var to = /[^\\[][\^]|^\^/;
  function In2(t3) {
    var e = function(i) {
      hn2(a2, i);
      function a2() {
        var o = i !== null && i.apply(this, arguments) || this;
        return o.found = false, o;
      }
      return a2.prototype.visitStartAnchor = function(o) {
        this.found = true;
      }, a2;
    }(dn.BaseRegExpVisitor), r = h.filter(t3, function(i) {
      var a2 = i[Ae2];
      try {
        var o = vn.getRegExpAst(a2), s = new e();
        return s.visit(o), s.found;
      } catch (c2) {
        return to.test(a2.source);
      }
    }), n2 = h.map(r, function(i) {
      return { message: `Unexpected RegExp Anchor Error:
	Token Type: ->` + i.name + `<- static 'PATTERN' cannot contain start of input anchor '^'
	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.`, type: F.LexerDefinitionErrorType.SOI_ANCHOR_FOUND, tokenTypes: [i] };
    });
    return n2;
  }
  T2.findStartOfInputAnchor = In2;
  function kn(t3) {
    var e = h.filter(t3, function(n2) {
      var i = n2[Ae2];
      return i instanceof RegExp && (i.multiline || i.global);
    }), r = h.map(e, function(n2) {
      return { message: "Token Type: ->" + n2.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", type: F.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, tokenTypes: [n2] };
    });
    return r;
  }
  T2.findUnsupportedFlags = kn;
  function Pn(t3) {
    var e = [], r = h.map(t3, function(a2) {
      return h.reduce(t3, function(o, s) {
        return a2.PATTERN.source === s.PATTERN.source && !h.contains(e, s) && s.PATTERN !== F.Lexer.NA && (e.push(s), o.push(s)), o;
      }, []);
    });
    r = h.compact(r);
    var n2 = h.filter(r, function(a2) {
      return a2.length > 1;
    }), i = h.map(n2, function(a2) {
      var o = h.map(a2, function(c2) {
        return c2.name;
      }), s = h.first(a2).PATTERN;
      return { message: "The same RegExp pattern ->" + s + "<-" + ("has been used in all of the following Token Types: " + o.join(", ") + " <-"), type: F.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, tokenTypes: a2 };
    });
    return i;
  }
  T2.findDuplicatePatterns = Pn;
  function gn(t3) {
    var e = h.filter(t3, function(n2) {
      if (!h.has(n2, "GROUP")) return false;
      var i = n2.GROUP;
      return i !== F.Lexer.SKIPPED && i !== F.Lexer.NA && !h.isString(i);
    }), r = h.map(e, function(n2) {
      return { message: "Token Type: ->" + n2.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", type: F.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, tokenTypes: [n2] };
    });
    return r;
  }
  T2.findInvalidGroupType = gn;
  function An(t3, e) {
    var r = h.filter(t3, function(i) {
      return i.PUSH_MODE !== void 0 && !h.contains(e, i.PUSH_MODE);
    }), n2 = h.map(r, function(i) {
      var a2 = "Token Type: ->" + i.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + i.PUSH_MODE + "<-which does not exist";
      return { message: a2, type: F.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, tokenTypes: [i] };
    });
    return n2;
  }
  T2.findModesThatDoNotExist = An;
  function Rn(t3) {
    var e = [], r = h.reduce(t3, function(n2, i, a2) {
      var o = i.PATTERN;
      return o === F.Lexer.NA || (h.isString(o) ? n2.push({ str: o, idx: a2, tokenType: i }) : h.isRegExp(o) && no(o) && n2.push({ str: o.source, idx: a2, tokenType: i })), n2;
    }, []);
    return h.forEach(t3, function(n2, i) {
      h.forEach(r, function(a2) {
        var o = a2.str, s = a2.idx, c2 = a2.tokenType;
        if (i < s && ro(o, n2.PATTERN)) {
          var f = "Token: ->" + c2.name + `<- can never be matched.
` + ("Because it appears AFTER the Token Type ->" + n2.name + "<-") + `in the lexer's definition.
See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;
          e.push({ message: f, type: F.LexerDefinitionErrorType.UNREACHABLE_PATTERN, tokenTypes: [n2, c2] });
        }
      });
    }), e;
  }
  T2.findUnreachablePatterns = Rn;
  function ro(t3, e) {
    if (h.isRegExp(e)) {
      var r = e.exec(t3);
      return r !== null && r.index === 0;
    } else {
      if (h.isFunction(e)) return e(t3, 0, [], {});
      if (h.has(e, "exec")) return e.exec(t3, 0, [], {});
      if (typeof e == "string") return e === t3;
      throw Error("non exhaustive match");
    }
  }
  function no(t3) {
    var e = [".", "\\", "[", "]", "|", "^", "$", "(", ")", "?", "*", "+", "{"];
    return h.find(e, function(r) {
      return t3.source.indexOf(r) !== -1;
    }) === void 0;
  }
  function _r(t3) {
    var e = t3.ignoreCase ? "i" : "";
    return new RegExp("^(?:" + t3.source + ")", e);
  }
  T2.addStartOfInput = _r;
  function gr(t3) {
    var e = t3.ignoreCase ? "iy" : "y";
    return new RegExp("" + t3.source, e);
  }
  T2.addStickyFlag = gr;
  function io(t3, e, r) {
    var n2 = [];
    return h.has(t3, T2.DEFAULT_MODE) || n2.push({ message: "A MultiMode Lexer cannot be initialized without a <" + T2.DEFAULT_MODE + `> property in its definition
`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE }), h.has(t3, T2.MODES) || n2.push({ message: "A MultiMode Lexer cannot be initialized without a <" + T2.MODES + `> property in its definition
`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY }), h.has(t3, T2.MODES) && h.has(t3, T2.DEFAULT_MODE) && !h.has(t3.modes, t3.defaultMode) && n2.push({ message: "A MultiMode Lexer cannot be initialized with a " + T2.DEFAULT_MODE + ": <" + t3.defaultMode + `>which does not exist
`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST }), h.has(t3, T2.MODES) && h.forEach(t3.modes, function(i, a2) {
      h.forEach(i, function(o, s) {
        h.isUndefined(o) && n2.push({ message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + ("<" + a2 + "> at index: <" + s + `>
`), type: F.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED });
      });
    }), n2;
  }
  T2.performRuntimeChecks = io;
  function ao(t3, e, r) {
    var n2 = [], i = false, a2 = h.compact(h.flatten(h.mapValues(t3.modes, function(c2) {
      return c2;
    }))), o = h.reject(a2, function(c2) {
      return c2[Ae2] === F.Lexer.NA;
    }), s = Tn(r);
    return e && h.forEach(o, function(c2) {
      var f = En(c2, s);
      if (f !== false) {
        var p = Sn2(c2, f), l2 = { message: p, type: f.issue, tokenType: c2 };
        n2.push(l2);
      } else h.has(c2, "LINE_BREAKS") ? c2.LINE_BREAKS === true && (i = true) : Ye.canMatchCharCode(s, c2.PATTERN) && (i = true);
    }), e && !i && n2.push({ message: `Warning: No LINE_BREAKS Found.
	This Lexer has been defined to track line and column information,
	But none of the Token Types can be identified as matching a line terminator.
	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS
	for details.`, type: F.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS }), n2;
  }
  T2.performWarningRuntimeChecks = ao;
  function oo(t3) {
    var e = {}, r = h.keys(t3);
    return h.forEach(r, function(n2) {
      var i = t3[n2];
      if (h.isArray(i)) e[n2] = [];
      else throw Error("non exhaustive match");
    }), e;
  }
  T2.cloneEmptyGroups = oo;
  function Ar(t3) {
    var e = t3.PATTERN;
    if (h.isRegExp(e)) return false;
    if (h.isFunction(e)) return true;
    if (h.has(e, "exec")) return true;
    if (h.isString(e)) return false;
    throw Error("non exhaustive match");
  }
  T2.isCustomPattern = Ar;
  function mn2(t3) {
    return h.isString(t3) && t3.length === 1 ? t3.charCodeAt(0) : false;
  }
  T2.isShortPattern = mn2;
  T2.LineTerminatorOptimizedTester = { test: function(t3) {
    for (var e = t3.length, r = this.lastIndex; r < e; r++) {
      var n2 = t3.charCodeAt(r);
      if (n2 === 10) return this.lastIndex = r + 1, true;
      if (n2 === 13) return t3.charCodeAt(r + 1) === 10 ? this.lastIndex = r + 2 : this.lastIndex = r + 1, true;
    }
    return false;
  }, lastIndex: 0 };
  function En(t3, e) {
    if (h.has(t3, "LINE_BREAKS")) return false;
    if (h.isRegExp(t3.PATTERN)) {
      try {
        Ye.canMatchCharCode(e, t3.PATTERN);
      } catch (r) {
        return { issue: F.LexerDefinitionErrorType.IDENTIFY_TERMINATOR, errMsg: r.message };
      }
      return false;
    } else {
      if (h.isString(t3.PATTERN)) return false;
      if (Ar(t3)) return { issue: F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK };
      throw Error("non exhaustive match");
    }
  }
  function Sn2(t3, e) {
    if (e.issue === F.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) return `Warning: unable to identify line terminator usage in pattern.
` + ("	The problem is in the <" + t3.name + `> Token Type
`) + ("	 Root cause: " + e.errMsg + `.
`) + "	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";
    if (e.issue === F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK) return `Warning: A Custom Token Pattern should specify the <line_breaks> option.
` + ("	The problem is in the <" + t3.name + `> Token Type
`) + "	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";
    throw Error("non exhaustive match");
  }
  T2.buildLineBreakIssueMessage = Sn2;
  function Tn(t3) {
    var e = h.map(t3, function(r) {
      return h.isString(r) && r.length > 0 ? r.charCodeAt(0) : r;
    });
    return e;
  }
  function Rr(t3, e, r) {
    t3[e] === void 0 ? t3[e] = [r] : t3[e].push(r);
  }
  T2.minOptimizationVal = 256;
  var Ft2 = [];
  function Or(t3) {
    return t3 < T2.minOptimizationVal ? t3 : Ft2[t3];
  }
  T2.charCodeToOptimizedIndex = Or;
  function $a() {
    if (h.isEmpty(Ft2)) {
      Ft2 = new Array(65536);
      for (var t3 = 0; t3 < 65536; t3++) Ft2[t3] = t3 > 255 ? 255 + ~~(t3 / 255) : t3;
    }
  }
});
var Xe = R2((N) => {
  "use strict";
  Object.defineProperty(N, "__esModule", { value: true });
  N.isTokenType = N.hasExtendingTokensTypesMapProperty = N.hasExtendingTokensTypesProperty = N.hasCategoriesProperty = N.hasShortKeyProperty = N.singleAssignCategoriesToksMap = N.assignCategoriesMapProp = N.assignCategoriesTokensProp = N.assignTokenDefaultProps = N.expandCategories = N.augmentTokenTypes = N.tokenIdxToClass = N.tokenShortNameIdx = N.tokenStructuredMatcherNoCategories = N.tokenStructuredMatcher = void 0;
  var V = k();
  function so(t3, e) {
    var r = t3.tokenTypeIdx;
    return r === e.tokenTypeIdx ? true : e.isParent === true && e.categoryMatchesMap[r] === true;
  }
  N.tokenStructuredMatcher = so;
  function uo(t3, e) {
    return t3.tokenTypeIdx === e.tokenTypeIdx;
  }
  N.tokenStructuredMatcherNoCategories = uo;
  N.tokenShortNameIdx = 1;
  N.tokenIdxToClass = {};
  function co(t3) {
    var e = xn2(t3);
    Cn(e), Mn(e), Ln(e), V.forEach(e, function(r) {
      r.isParent = r.categoryMatches.length > 0;
    });
  }
  N.augmentTokenTypes = co;
  function xn2(t3) {
    for (var e = V.cloneArr(t3), r = t3, n2 = true; n2; ) {
      r = V.compact(V.flatten(V.map(r, function(a2) {
        return a2.CATEGORIES;
      })));
      var i = V.difference(r, e);
      e = e.concat(i), V.isEmpty(i) ? n2 = false : r = i;
    }
    return e;
  }
  N.expandCategories = xn2;
  function Cn(t3) {
    V.forEach(t3, function(e) {
      bn(e) || (N.tokenIdxToClass[N.tokenShortNameIdx] = e, e.tokenTypeIdx = N.tokenShortNameIdx++), Nr(e) && !V.isArray(e.CATEGORIES) && (e.CATEGORIES = [e.CATEGORIES]), Nr(e) || (e.CATEGORIES = []), Fn(e) || (e.categoryMatches = []), wn(e) || (e.categoryMatchesMap = {});
    });
  }
  N.assignTokenDefaultProps = Cn;
  function Ln(t3) {
    V.forEach(t3, function(e) {
      e.categoryMatches = [], V.forEach(e.categoryMatchesMap, function(r, n2) {
        e.categoryMatches.push(N.tokenIdxToClass[n2].tokenTypeIdx);
      });
    });
  }
  N.assignCategoriesTokensProp = Ln;
  function Mn(t3) {
    V.forEach(t3, function(e) {
      Ir([], e);
    });
  }
  N.assignCategoriesMapProp = Mn;
  function Ir(t3, e) {
    V.forEach(t3, function(r) {
      e.categoryMatchesMap[r.tokenTypeIdx] = true;
    }), V.forEach(e.CATEGORIES, function(r) {
      var n2 = t3.concat(e);
      V.contains(n2, r) || Ir(n2, r);
    });
  }
  N.singleAssignCategoriesToksMap = Ir;
  function bn(t3) {
    return V.has(t3, "tokenTypeIdx");
  }
  N.hasShortKeyProperty = bn;
  function Nr(t3) {
    return V.has(t3, "CATEGORIES");
  }
  N.hasCategoriesProperty = Nr;
  function Fn(t3) {
    return V.has(t3, "categoryMatches");
  }
  N.hasExtendingTokensTypesProperty = Fn;
  function wn(t3) {
    return V.has(t3, "categoryMatchesMap");
  }
  N.hasExtendingTokensTypesMapProperty = wn;
  function lo(t3) {
    return V.has(t3, "tokenTypeIdx");
  }
  N.isTokenType = lo;
});
var kr = R2((wt2) => {
  "use strict";
  Object.defineProperty(wt2, "__esModule", { value: true });
  wt2.defaultLexerErrorProvider = void 0;
  wt2.defaultLexerErrorProvider = { buildUnableToPopLexerModeMessage: function(t3) {
    return "Unable to pop Lexer Mode after encountering Token ->" + t3.image + "<- The Mode Stack is empty";
  }, buildUnexpectedCharactersMessage: function(t3, e, r, n2, i) {
    return "unexpected character: ->" + t3.charAt(e) + "<- at offset: " + e + "," + (" skipped " + r + " characters.");
  } };
});
var ft = R2((qe) => {
  "use strict";
  Object.defineProperty(qe, "__esModule", { value: true });
  qe.Lexer = qe.LexerDefinitionErrorType = void 0;
  var Ee = Tr(), w = k(), fo = Xe(), po = kr(), ho = Lt(), vo;
  (function(t3) {
    t3[t3.MISSING_PATTERN = 0] = "MISSING_PATTERN", t3[t3.INVALID_PATTERN = 1] = "INVALID_PATTERN", t3[t3.EOI_ANCHOR_FOUND = 2] = "EOI_ANCHOR_FOUND", t3[t3.UNSUPPORTED_FLAGS_FOUND = 3] = "UNSUPPORTED_FLAGS_FOUND", t3[t3.DUPLICATE_PATTERNS_FOUND = 4] = "DUPLICATE_PATTERNS_FOUND", t3[t3.INVALID_GROUP_TYPE_FOUND = 5] = "INVALID_GROUP_TYPE_FOUND", t3[t3.PUSH_MODE_DOES_NOT_EXIST = 6] = "PUSH_MODE_DOES_NOT_EXIST", t3[t3.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE", t3[t3.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY", t3[t3.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST", t3[t3.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED", t3[t3.SOI_ANCHOR_FOUND = 11] = "SOI_ANCHOR_FOUND", t3[t3.EMPTY_MATCH_PATTERN = 12] = "EMPTY_MATCH_PATTERN", t3[t3.NO_LINE_BREAKS_FLAGS = 13] = "NO_LINE_BREAKS_FLAGS", t3[t3.UNREACHABLE_PATTERN = 14] = "UNREACHABLE_PATTERN", t3[t3.IDENTIFY_TERMINATOR = 15] = "IDENTIFY_TERMINATOR", t3[t3.CUSTOM_LINE_BREAK = 16] = "CUSTOM_LINE_BREAK";
  })(vo = qe.LexerDefinitionErrorType || (qe.LexerDefinitionErrorType = {}));
  var pt = { deferDefinitionErrorsHandling: false, positionTracking: "full", lineTerminatorsPattern: /\n|\r\n?/g, lineTerminatorCharacters: [`
`, "\r"], ensureOptimizations: false, safeMode: false, errorMessageProvider: po.defaultLexerErrorProvider, traceInitPerf: false, skipValidations: false };
  Object.freeze(pt);
  var mo = function() {
    function t3(e, r) {
      var n2 = this;
      if (r === void 0 && (r = pt), this.lexerDefinition = e, this.lexerDefinitionErrors = [], this.lexerDefinitionWarning = [], this.patternIdxToConfig = {}, this.charCodeToPatternIdxToConfig = {}, this.modes = [], this.emptyGroups = {}, this.config = void 0, this.trackStartLines = true, this.trackEndLines = true, this.hasCustom = false, this.canModeBeOptimized = {}, typeof r == "boolean") throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object.
a boolean 2nd argument is no longer supported`);
      this.config = w.merge(pt, r);
      var i = this.config.traceInitPerf;
      i === true ? (this.traceInitMaxIdent = Infinity, this.traceInitPerf = true) : typeof i == "number" && (this.traceInitMaxIdent = i, this.traceInitPerf = true), this.traceInitIndent = -1, this.TRACE_INIT("Lexer Constructor", function() {
        var a2, o = true;
        n2.TRACE_INIT("Lexer Config handling", function() {
          if (n2.config.lineTerminatorsPattern === pt.lineTerminatorsPattern) n2.config.lineTerminatorsPattern = Ee.LineTerminatorOptimizedTester;
          else if (n2.config.lineTerminatorCharacters === pt.lineTerminatorCharacters) throw Error(`Error: Missing <lineTerminatorCharacters> property on the Lexer config.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);
          if (r.safeMode && r.ensureOptimizations) throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');
          n2.trackStartLines = /full|onlyStart/i.test(n2.config.positionTracking), n2.trackEndLines = /full/i.test(n2.config.positionTracking), w.isArray(e) ? (a2 = { modes: {} }, a2.modes[Ee.DEFAULT_MODE] = w.cloneArr(e), a2[Ee.DEFAULT_MODE] = Ee.DEFAULT_MODE) : (o = false, a2 = w.cloneObj(e));
        }), n2.config.skipValidations === false && (n2.TRACE_INIT("performRuntimeChecks", function() {
          n2.lexerDefinitionErrors = n2.lexerDefinitionErrors.concat(Ee.performRuntimeChecks(a2, n2.trackStartLines, n2.config.lineTerminatorCharacters));
        }), n2.TRACE_INIT("performWarningRuntimeChecks", function() {
          n2.lexerDefinitionWarning = n2.lexerDefinitionWarning.concat(Ee.performWarningRuntimeChecks(a2, n2.trackStartLines, n2.config.lineTerminatorCharacters));
        })), a2.modes = a2.modes ? a2.modes : {}, w.forEach(a2.modes, function(p, l2) {
          a2.modes[l2] = w.reject(p, function(m) {
            return w.isUndefined(m);
          });
        });
        var s = w.keys(a2.modes);
        if (w.forEach(a2.modes, function(p, l2) {
          n2.TRACE_INIT("Mode: <" + l2 + "> processing", function() {
            if (n2.modes.push(l2), n2.config.skipValidations === false && n2.TRACE_INIT("validatePatterns", function() {
              n2.lexerDefinitionErrors = n2.lexerDefinitionErrors.concat(Ee.validatePatterns(p, s));
            }), w.isEmpty(n2.lexerDefinitionErrors)) {
              fo.augmentTokenTypes(p);
              var m;
              n2.TRACE_INIT("analyzeTokenTypes", function() {
                m = Ee.analyzeTokenTypes(p, { lineTerminatorCharacters: n2.config.lineTerminatorCharacters, positionTracking: r.positionTracking, ensureOptimizations: r.ensureOptimizations, safeMode: r.safeMode, tracer: n2.TRACE_INIT.bind(n2) });
              }), n2.patternIdxToConfig[l2] = m.patternIdxToConfig, n2.charCodeToPatternIdxToConfig[l2] = m.charCodeToPatternIdxToConfig, n2.emptyGroups = w.merge(n2.emptyGroups, m.emptyGroups), n2.hasCustom = m.hasCustom || n2.hasCustom, n2.canModeBeOptimized[l2] = m.canBeOptimized;
            }
          });
        }), n2.defaultMode = a2.defaultMode, !w.isEmpty(n2.lexerDefinitionErrors) && !n2.config.deferDefinitionErrorsHandling) {
          var c2 = w.map(n2.lexerDefinitionErrors, function(p) {
            return p.message;
          }), f = c2.join(`-----------------------
`);
          throw new Error(`Errors detected in definition of Lexer:
` + f);
        }
        w.forEach(n2.lexerDefinitionWarning, function(p) {
          w.PRINT_WARNING(p.message);
        }), n2.TRACE_INIT("Choosing sub-methods implementations", function() {
          if (Ee.SUPPORT_STICKY ? (n2.chopInput = w.IDENTITY, n2.match = n2.matchWithTest) : (n2.updateLastIndex = w.NOOP, n2.match = n2.matchWithExec), o && (n2.handleModes = w.NOOP), n2.trackStartLines === false && (n2.computeNewColumn = w.IDENTITY), n2.trackEndLines === false && (n2.updateTokenEndLineColumnLocation = w.NOOP), /full/i.test(n2.config.positionTracking)) n2.createTokenInstance = n2.createFullToken;
          else if (/onlyStart/i.test(n2.config.positionTracking)) n2.createTokenInstance = n2.createStartOnlyToken;
          else if (/onlyOffset/i.test(n2.config.positionTracking)) n2.createTokenInstance = n2.createOffsetOnlyToken;
          else throw Error('Invalid <positionTracking> config option: "' + n2.config.positionTracking + '"');
          n2.hasCustom ? (n2.addToken = n2.addTokenUsingPush, n2.handlePayload = n2.handlePayloadWithCustom) : (n2.addToken = n2.addTokenUsingMemberAccess, n2.handlePayload = n2.handlePayloadNoCustom);
        }), n2.TRACE_INIT("Failed Optimization Warnings", function() {
          var p = w.reduce(n2.canModeBeOptimized, function(l2, m, v) {
            return m === false && l2.push(v), l2;
          }, []);
          if (r.ensureOptimizations && !w.isEmpty(p)) throw Error("Lexer Modes: < " + p.join(", ") + ` > cannot be optimized.
	 Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.
	 Or inspect the console log for details on how to resolve these issues.`);
        }), n2.TRACE_INIT("clearRegExpParserCache", function() {
          ho.clearRegExpParserCache();
        }), n2.TRACE_INIT("toFastProperties", function() {
          w.toFastProperties(n2);
        });
      });
    }
    return t3.prototype.tokenize = function(e, r) {
      if (r === void 0 && (r = this.defaultMode), !w.isEmpty(this.lexerDefinitionErrors)) {
        var n2 = w.map(this.lexerDefinitionErrors, function(o) {
          return o.message;
        }), i = n2.join(`-----------------------
`);
        throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer:
` + i);
      }
      var a2 = this.tokenizeInternal(e, r);
      return a2;
    }, t3.prototype.tokenizeInternal = function(e, r) {
      var n2 = this, i, a2, o, s, c2, f, p, l2, m, v, u2, d, A2, _, g3, y = e, b3 = y.length, L = 0, se = 0, fe = this.hasCustom ? 0 : Math.floor(e.length / 10), Z2 = new Array(fe), ue2 = [], Q2 = this.trackStartLines ? 1 : void 0, te3 = this.trackStartLines ? 1 : void 0, xe = Ee.cloneEmptyGroups(this.emptyGroups), it2 = this.trackStartLines, at = this.config.lineTerminatorsPattern, Ke = 0, we2 = [], ot = [], It = [], Qr = [];
      Object.freeze(Qr);
      var st = void 0;
      function Jr() {
        return we2;
      }
      function en2(J) {
        var lt = Ee.charCodeToOptimizedIndex(J), ze = ot[lt];
        return ze === void 0 ? Qr : ze;
      }
      var wa = function(J) {
        if (It.length === 1 && J.tokenType.PUSH_MODE === void 0) {
          var lt = n2.config.errorMessageProvider.buildUnableToPopLexerModeMessage(J);
          ue2.push({ offset: J.startOffset, line: J.startLine !== void 0 ? J.startLine : void 0, column: J.startColumn !== void 0 ? J.startColumn : void 0, length: J.image.length, message: lt });
        } else {
          It.pop();
          var ze = w.last(It);
          we2 = n2.patternIdxToConfig[ze], ot = n2.charCodeToPatternIdxToConfig[ze], Ke = we2.length;
          var Ua = n2.canModeBeOptimized[ze] && n2.config.safeMode === false;
          ot && Ua ? st = en2 : st = Jr;
        }
      };
      function tn(J) {
        It.push(J), ot = this.charCodeToPatternIdxToConfig[J], we2 = this.patternIdxToConfig[J], Ke = we2.length, Ke = we2.length;
        var lt = this.canModeBeOptimized[J] && this.config.safeMode === false;
        ot && lt ? st = en2 : st = Jr;
      }
      tn.call(this, r);
      for (var me; L < b3; ) {
        c2 = null;
        var rn2 = y.charCodeAt(L), nn2 = st(rn2), Da = nn2.length;
        for (i = 0; i < Da; i++) {
          me = nn2[i];
          var De = me.pattern;
          f = null;
          var ut = me.short;
          if (ut !== false ? rn2 === ut && (c2 = De) : me.isCustom === true ? (g3 = De.exec(y, L, Z2, xe), g3 !== null ? (c2 = g3[0], g3.payload !== void 0 && (f = g3.payload)) : c2 = null) : (this.updateLastIndex(De, L), c2 = this.match(De, e, L)), c2 !== null) {
            if (s = me.longerAlt, s !== void 0) {
              var fr = we2[s], pr = fr.pattern;
              p = null, fr.isCustom === true ? (g3 = pr.exec(y, L, Z2, xe), g3 !== null ? (o = g3[0], g3.payload !== void 0 && (p = g3.payload)) : o = null) : (this.updateLastIndex(pr, L), o = this.match(pr, e, L)), o && o.length > c2.length && (c2 = o, f = p, me = fr);
            }
            break;
          }
        }
        if (c2 !== null) {
          if (l2 = c2.length, m = me.group, m !== void 0 && (v = me.tokenTypeIdx, u2 = this.createTokenInstance(c2, L, v, me.tokenType, Q2, te3, l2), this.handlePayload(u2, f), m === false ? se = this.addToken(Z2, se, u2) : xe[m].push(u2)), e = this.chopInput(e, l2), L = L + l2, te3 = this.computeNewColumn(te3, l2), it2 === true && me.canLineTerminator === true) {
            var kt = 0, hr = void 0, dr = void 0;
            at.lastIndex = 0;
            do
              hr = at.test(c2), hr === true && (dr = at.lastIndex - 1, kt++);
            while (hr === true);
            kt !== 0 && (Q2 = Q2 + kt, te3 = l2 - dr, this.updateTokenEndLineColumnLocation(u2, m, dr, kt, Q2, te3, l2));
          }
          this.handleModes(me, wa, tn, u2);
        } else {
          for (var vr = L, an = Q2, on2 = te3, ct2 = false; !ct2 && L < b3; ) for (A2 = y.charCodeAt(L), e = this.chopInput(e, 1), L++, a2 = 0; a2 < Ke; a2++) {
            var mr = we2[a2], De = mr.pattern, ut = mr.short;
            if (ut !== false ? y.charCodeAt(L) === ut && (ct2 = true) : mr.isCustom === true ? ct2 = De.exec(y, L, Z2, xe) !== null : (this.updateLastIndex(De, L), ct2 = De.exec(e) !== null), ct2 === true) break;
          }
          d = L - vr, _ = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(y, vr, d, an, on2), ue2.push({ offset: vr, line: an, column: on2, length: d, message: _ });
        }
      }
      return this.hasCustom || (Z2.length = se), { tokens: Z2, groups: xe, errors: ue2 };
    }, t3.prototype.handleModes = function(e, r, n2, i) {
      if (e.pop === true) {
        var a2 = e.push;
        r(i), a2 !== void 0 && n2.call(this, a2);
      } else e.push !== void 0 && n2.call(this, e.push);
    }, t3.prototype.chopInput = function(e, r) {
      return e.substring(r);
    }, t3.prototype.updateLastIndex = function(e, r) {
      e.lastIndex = r;
    }, t3.prototype.updateTokenEndLineColumnLocation = function(e, r, n2, i, a2, o, s) {
      var c2, f;
      r !== void 0 && (c2 = n2 === s - 1, f = c2 ? -1 : 0, i === 1 && c2 === true || (e.endLine = a2 + f, e.endColumn = o - 1 + -f));
    }, t3.prototype.computeNewColumn = function(e, r) {
      return e + r;
    }, t3.prototype.createTokenInstance = function() {
      for (var e = [], r = 0; r < arguments.length; r++) e[r] = arguments[r];
      return null;
    }, t3.prototype.createOffsetOnlyToken = function(e, r, n2, i) {
      return { image: e, startOffset: r, tokenTypeIdx: n2, tokenType: i };
    }, t3.prototype.createStartOnlyToken = function(e, r, n2, i, a2, o) {
      return { image: e, startOffset: r, startLine: a2, startColumn: o, tokenTypeIdx: n2, tokenType: i };
    }, t3.prototype.createFullToken = function(e, r, n2, i, a2, o, s) {
      return { image: e, startOffset: r, endOffset: r + s - 1, startLine: a2, endLine: a2, startColumn: o, endColumn: o + s - 1, tokenTypeIdx: n2, tokenType: i };
    }, t3.prototype.addToken = function(e, r, n2) {
      return 666;
    }, t3.prototype.addTokenUsingPush = function(e, r, n2) {
      return e.push(n2), r;
    }, t3.prototype.addTokenUsingMemberAccess = function(e, r, n2) {
      return e[r] = n2, r++, r;
    }, t3.prototype.handlePayload = function(e, r) {
    }, t3.prototype.handlePayloadNoCustom = function(e, r) {
    }, t3.prototype.handlePayloadWithCustom = function(e, r) {
      r !== null && (e.payload = r);
    }, t3.prototype.match = function(e, r, n2) {
      return null;
    }, t3.prototype.matchWithTest = function(e, r, n2) {
      var i = e.test(r);
      return i === true ? r.substring(n2, e.lastIndex) : null;
    }, t3.prototype.matchWithExec = function(e, r) {
      var n2 = e.exec(r);
      return n2 !== null ? n2[0] : n2;
    }, t3.prototype.TRACE_INIT = function(e, r) {
      if (this.traceInitPerf === true) {
        this.traceInitIndent++;
        var n2 = new Array(this.traceInitIndent + 1).join("	");
        this.traceInitIndent < this.traceInitMaxIdent && console.log(n2 + "--> <" + e + ">");
        var i = w.timer(r), a2 = i.time, o = i.value, s = a2 > 10 ? console.warn : console.log;
        return this.traceInitIndent < this.traceInitMaxIdent && s(n2 + "<-- <" + e + "> time: " + a2 + "ms"), this.traceInitIndent--, o;
      } else return r();
    }, t3.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.", t3.NA = /NOT_APPLICABLE/, t3;
  }();
  qe.Lexer = mo;
});
var Ue = R2((H) => {
  "use strict";
  Object.defineProperty(H, "__esModule", { value: true });
  H.tokenMatcher = H.createTokenInstance = H.EOF = H.createToken = H.hasTokenLabel = H.tokenName = H.tokenLabel = void 0;
  var Te = k(), Eo = ft(), Pr = Xe();
  function To(t3) {
    return Dn2(t3) ? t3.LABEL : t3.name;
  }
  H.tokenLabel = To;
  function yo(t3) {
    return t3.name;
  }
  H.tokenName = yo;
  function Dn2(t3) {
    return Te.isString(t3.LABEL) && t3.LABEL !== "";
  }
  H.hasTokenLabel = Dn2;
  var _o = "parent", Un2 = "categories", Gn = "label", Wn = "group", Bn = "push_mode", qn = "pop_mode", jn = "longer_alt", Vn = "line_breaks", Kn = "start_chars_hint";
  function zn(t3) {
    return go(t3);
  }
  H.createToken = zn;
  function go(t3) {
    var e = t3.pattern, r = {};
    if (r.name = t3.name, Te.isUndefined(e) || (r.PATTERN = e), Te.has(t3, _o)) throw `The parent property is no longer supported.
See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;
    return Te.has(t3, Un2) && (r.CATEGORIES = t3[Un2]), Pr.augmentTokenTypes([r]), Te.has(t3, Gn) && (r.LABEL = t3[Gn]), Te.has(t3, Wn) && (r.GROUP = t3[Wn]), Te.has(t3, qn) && (r.POP_MODE = t3[qn]), Te.has(t3, Bn) && (r.PUSH_MODE = t3[Bn]), Te.has(t3, jn) && (r.LONGER_ALT = t3[jn]), Te.has(t3, Vn) && (r.LINE_BREAKS = t3[Vn]), Te.has(t3, Kn) && (r.START_CHARS_HINT = t3[Kn]), r;
  }
  H.EOF = zn({ name: "EOF", pattern: Eo.Lexer.NA });
  Pr.augmentTokenTypes([H.EOF]);
  function Ao(t3, e, r, n2, i, a2, o, s) {
    return { image: e, startOffset: r, endOffset: n2, startLine: i, endLine: a2, startColumn: o, endColumn: s, tokenTypeIdx: t3.tokenTypeIdx, tokenType: t3 };
  }
  H.createTokenInstance = Ao;
  function Ro(t3, e) {
    return Pr.tokenStructuredMatcher(t3, e);
  }
  H.tokenMatcher = Ro;
});
var ne = R2((S) => {
  "use strict";
  var Le = S && S.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(S, "__esModule", { value: true });
  S.serializeProduction = S.serializeGrammar = S.Terminal = S.Alternation = S.RepetitionWithSeparator = S.Repetition = S.RepetitionMandatoryWithSeparator = S.RepetitionMandatory = S.Option = S.Alternative = S.Rule = S.NonTerminal = S.AbstractProduction = void 0;
  var G2 = k(), Oo = Ue(), Re = function() {
    function t3(e) {
      this._definition = e;
    }
    return Object.defineProperty(t3.prototype, "definition", { get: function() {
      return this._definition;
    }, set: function(e) {
      this._definition = e;
    }, enumerable: false, configurable: true }), t3.prototype.accept = function(e) {
      e.visit(this), G2.forEach(this.definition, function(r) {
        r.accept(e);
      });
    }, t3;
  }();
  S.AbstractProduction = Re;
  var Hn = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, []) || this;
      return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return Object.defineProperty(e.prototype, "definition", { get: function() {
      return this.referencedRule !== void 0 ? this.referencedRule.definition : [];
    }, set: function(r) {
    }, enumerable: false, configurable: true }), e.prototype.accept = function(r) {
      r.visit(this);
    }, e;
  }(Re);
  S.NonTerminal = Hn;
  var Yn = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, r.definition) || this;
      return n2.orgText = "", G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return e;
  }(Re);
  S.Rule = Yn;
  var Xn = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, r.definition) || this;
      return n2.ignoreAmbiguities = false, G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return e;
  }(Re);
  S.Alternative = Xn;
  var $n = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, r.definition) || this;
      return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return e;
  }(Re);
  S.Option = $n;
  var Zn = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, r.definition) || this;
      return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return e;
  }(Re);
  S.RepetitionMandatory = Zn;
  var Qn = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, r.definition) || this;
      return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return e;
  }(Re);
  S.RepetitionMandatoryWithSeparator = Qn;
  var Jn = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, r.definition) || this;
      return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return e;
  }(Re);
  S.Repetition = Jn;
  var ei = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, r.definition) || this;
      return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return e;
  }(Re);
  S.RepetitionWithSeparator = ei;
  var ti = function(t3) {
    Le(e, t3);
    function e(r) {
      var n2 = t3.call(this, r.definition) || this;
      return n2.idx = 1, n2.ignoreAmbiguities = false, n2.hasPredicates = false, G2.assign(n2, G2.pick(r, function(i) {
        return i !== void 0;
      })), n2;
    }
    return Object.defineProperty(e.prototype, "definition", { get: function() {
      return this._definition;
    }, set: function(r) {
      this._definition = r;
    }, enumerable: false, configurable: true }), e;
  }(Re);
  S.Alternation = ti;
  var Dt = function() {
    function t3(e) {
      this.idx = 1, G2.assign(this, G2.pick(e, function(r) {
        return r !== void 0;
      }));
    }
    return t3.prototype.accept = function(e) {
      e.visit(this);
    }, t3;
  }();
  S.Terminal = Dt;
  function No(t3) {
    return G2.map(t3, ht);
  }
  S.serializeGrammar = No;
  function ht(t3) {
    function e(i) {
      return G2.map(i, ht);
    }
    if (t3 instanceof Hn) return { type: "NonTerminal", name: t3.nonTerminalName, idx: t3.idx };
    if (t3 instanceof Xn) return { type: "Alternative", definition: e(t3.definition) };
    if (t3 instanceof $n) return { type: "Option", idx: t3.idx, definition: e(t3.definition) };
    if (t3 instanceof Zn) return { type: "RepetitionMandatory", idx: t3.idx, definition: e(t3.definition) };
    if (t3 instanceof Qn) return { type: "RepetitionMandatoryWithSeparator", idx: t3.idx, separator: ht(new Dt({ terminalType: t3.separator })), definition: e(t3.definition) };
    if (t3 instanceof ei) return { type: "RepetitionWithSeparator", idx: t3.idx, separator: ht(new Dt({ terminalType: t3.separator })), definition: e(t3.definition) };
    if (t3 instanceof Jn) return { type: "Repetition", idx: t3.idx, definition: e(t3.definition) };
    if (t3 instanceof ti) return { type: "Alternation", idx: t3.idx, definition: e(t3.definition) };
    if (t3 instanceof Dt) {
      var r = { type: "Terminal", name: t3.terminalType.name, label: Oo.tokenLabel(t3.terminalType), idx: t3.idx }, n2 = t3.terminalType.PATTERN;
      return t3.terminalType.PATTERN && (r.pattern = G2.isRegExp(n2) ? n2.source : n2), r;
    } else {
      if (t3 instanceof Yn) return { type: "Rule", name: t3.name, orgText: t3.orgText, definition: e(t3.definition) };
      throw Error("non exhaustive match");
    }
  }
  S.serializeProduction = ht;
});
var Gt = R2((Ut) => {
  "use strict";
  Object.defineProperty(Ut, "__esModule", { value: true });
  Ut.RestWalker = void 0;
  var Sr = k(), ie = ne(), Io = function() {
    function t3() {
    }
    return t3.prototype.walk = function(e, r) {
      var n2 = this;
      r === void 0 && (r = []), Sr.forEach(e.definition, function(i, a2) {
        var o = Sr.drop(e.definition, a2 + 1);
        if (i instanceof ie.NonTerminal) n2.walkProdRef(i, o, r);
        else if (i instanceof ie.Terminal) n2.walkTerminal(i, o, r);
        else if (i instanceof ie.Alternative) n2.walkFlat(i, o, r);
        else if (i instanceof ie.Option) n2.walkOption(i, o, r);
        else if (i instanceof ie.RepetitionMandatory) n2.walkAtLeastOne(i, o, r);
        else if (i instanceof ie.RepetitionMandatoryWithSeparator) n2.walkAtLeastOneSep(i, o, r);
        else if (i instanceof ie.RepetitionWithSeparator) n2.walkManySep(i, o, r);
        else if (i instanceof ie.Repetition) n2.walkMany(i, o, r);
        else if (i instanceof ie.Alternation) n2.walkOr(i, o, r);
        else throw Error("non exhaustive match");
      });
    }, t3.prototype.walkTerminal = function(e, r, n2) {
    }, t3.prototype.walkProdRef = function(e, r, n2) {
    }, t3.prototype.walkFlat = function(e, r, n2) {
      var i = r.concat(n2);
      this.walk(e, i);
    }, t3.prototype.walkOption = function(e, r, n2) {
      var i = r.concat(n2);
      this.walk(e, i);
    }, t3.prototype.walkAtLeastOne = function(e, r, n2) {
      var i = [new ie.Option({ definition: e.definition })].concat(r, n2);
      this.walk(e, i);
    }, t3.prototype.walkAtLeastOneSep = function(e, r, n2) {
      var i = ri(e, r, n2);
      this.walk(e, i);
    }, t3.prototype.walkMany = function(e, r, n2) {
      var i = [new ie.Option({ definition: e.definition })].concat(r, n2);
      this.walk(e, i);
    }, t3.prototype.walkManySep = function(e, r, n2) {
      var i = ri(e, r, n2);
      this.walk(e, i);
    }, t3.prototype.walkOr = function(e, r, n2) {
      var i = this, a2 = r.concat(n2);
      Sr.forEach(e.definition, function(o) {
        var s = new ie.Alternative({ definition: [o] });
        i.walk(s, a2);
      });
    }, t3;
  }();
  Ut.RestWalker = Io;
  function ri(t3, e, r) {
    var n2 = [new ie.Option({ definition: [new ie.Terminal({ terminalType: t3.separator })].concat(t3.definition) })], i = n2.concat(e, r);
    return i;
  }
});
var $e = R2((Wt) => {
  "use strict";
  Object.defineProperty(Wt, "__esModule", { value: true });
  Wt.GAstVisitor = void 0;
  var Oe = ne(), ko = function() {
    function t3() {
    }
    return t3.prototype.visit = function(e) {
      var r = e;
      switch (r.constructor) {
        case Oe.NonTerminal:
          return this.visitNonTerminal(r);
        case Oe.Alternative:
          return this.visitAlternative(r);
        case Oe.Option:
          return this.visitOption(r);
        case Oe.RepetitionMandatory:
          return this.visitRepetitionMandatory(r);
        case Oe.RepetitionMandatoryWithSeparator:
          return this.visitRepetitionMandatoryWithSeparator(r);
        case Oe.RepetitionWithSeparator:
          return this.visitRepetitionWithSeparator(r);
        case Oe.Repetition:
          return this.visitRepetition(r);
        case Oe.Alternation:
          return this.visitAlternation(r);
        case Oe.Terminal:
          return this.visitTerminal(r);
        case Oe.Rule:
          return this.visitRule(r);
        default:
          throw Error("non exhaustive match");
      }
    }, t3.prototype.visitNonTerminal = function(e) {
    }, t3.prototype.visitAlternative = function(e) {
    }, t3.prototype.visitOption = function(e) {
    }, t3.prototype.visitRepetition = function(e) {
    }, t3.prototype.visitRepetitionMandatory = function(e) {
    }, t3.prototype.visitRepetitionMandatoryWithSeparator = function(e) {
    }, t3.prototype.visitRepetitionWithSeparator = function(e) {
    }, t3.prototype.visitAlternation = function(e) {
    }, t3.prototype.visitTerminal = function(e) {
    }, t3.prototype.visitRule = function(e) {
    }, t3;
  }();
  Wt.GAstVisitor = ko;
});
var vt = R2((X) => {
  "use strict";
  var Po = X && X.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(X, "__esModule", { value: true });
  X.collectMethods = X.DslMethodsCollectorVisitor = X.getProductionDslName = X.isBranchingProd = X.isOptionalProd = X.isSequenceProd = void 0;
  var dt = k(), W = ne(), So = $e();
  function xo(t3) {
    return t3 instanceof W.Alternative || t3 instanceof W.Option || t3 instanceof W.Repetition || t3 instanceof W.RepetitionMandatory || t3 instanceof W.RepetitionMandatoryWithSeparator || t3 instanceof W.RepetitionWithSeparator || t3 instanceof W.Terminal || t3 instanceof W.Rule;
  }
  X.isSequenceProd = xo;
  function xr(t3, e) {
    e === void 0 && (e = []);
    var r = t3 instanceof W.Option || t3 instanceof W.Repetition || t3 instanceof W.RepetitionWithSeparator;
    return r ? true : t3 instanceof W.Alternation ? dt.some(t3.definition, function(n2) {
      return xr(n2, e);
    }) : t3 instanceof W.NonTerminal && dt.contains(e, t3) ? false : t3 instanceof W.AbstractProduction ? (t3 instanceof W.NonTerminal && e.push(t3), dt.every(t3.definition, function(n2) {
      return xr(n2, e);
    })) : false;
  }
  X.isOptionalProd = xr;
  function Co(t3) {
    return t3 instanceof W.Alternation;
  }
  X.isBranchingProd = Co;
  function Lo(t3) {
    if (t3 instanceof W.NonTerminal) return "SUBRULE";
    if (t3 instanceof W.Option) return "OPTION";
    if (t3 instanceof W.Alternation) return "OR";
    if (t3 instanceof W.RepetitionMandatory) return "AT_LEAST_ONE";
    if (t3 instanceof W.RepetitionMandatoryWithSeparator) return "AT_LEAST_ONE_SEP";
    if (t3 instanceof W.RepetitionWithSeparator) return "MANY_SEP";
    if (t3 instanceof W.Repetition) return "MANY";
    if (t3 instanceof W.Terminal) return "CONSUME";
    throw Error("non exhaustive match");
  }
  X.getProductionDslName = Lo;
  var ni = function(t3) {
    Po(e, t3);
    function e() {
      var r = t3 !== null && t3.apply(this, arguments) || this;
      return r.separator = "-", r.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }, r;
    }
    return e.prototype.reset = function() {
      this.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] };
    }, e.prototype.visitTerminal = function(r) {
      var n2 = r.terminalType.name + this.separator + "Terminal";
      dt.has(this.dslMethods, n2) || (this.dslMethods[n2] = []), this.dslMethods[n2].push(r);
    }, e.prototype.visitNonTerminal = function(r) {
      var n2 = r.nonTerminalName + this.separator + "Terminal";
      dt.has(this.dslMethods, n2) || (this.dslMethods[n2] = []), this.dslMethods[n2].push(r);
    }, e.prototype.visitOption = function(r) {
      this.dslMethods.option.push(r);
    }, e.prototype.visitRepetitionWithSeparator = function(r) {
      this.dslMethods.repetitionWithSeparator.push(r);
    }, e.prototype.visitRepetitionMandatory = function(r) {
      this.dslMethods.repetitionMandatory.push(r);
    }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) {
      this.dslMethods.repetitionMandatoryWithSeparator.push(r);
    }, e.prototype.visitRepetition = function(r) {
      this.dslMethods.repetition.push(r);
    }, e.prototype.visitAlternation = function(r) {
      this.dslMethods.alternation.push(r);
    }, e;
  }(So.GAstVisitor);
  X.DslMethodsCollectorVisitor = ni;
  var Bt = new ni();
  function Mo(t3) {
    Bt.reset(), t3.accept(Bt);
    var e = Bt.dslMethods;
    return Bt.reset(), e;
  }
  X.collectMethods = Mo;
});
var Lr = R2((Ne) => {
  "use strict";
  Object.defineProperty(Ne, "__esModule", { value: true });
  Ne.firstForTerminal = Ne.firstForBranching = Ne.firstForSequence = Ne.first = void 0;
  var qt = k(), ii = ne(), Cr = vt();
  function jt(t3) {
    if (t3 instanceof ii.NonTerminal) return jt(t3.referencedRule);
    if (t3 instanceof ii.Terminal) return si(t3);
    if (Cr.isSequenceProd(t3)) return ai(t3);
    if (Cr.isBranchingProd(t3)) return oi(t3);
    throw Error("non exhaustive match");
  }
  Ne.first = jt;
  function ai(t3) {
    for (var e = [], r = t3.definition, n2 = 0, i = r.length > n2, a2, o = true; i && o; ) a2 = r[n2], o = Cr.isOptionalProd(a2), e = e.concat(jt(a2)), n2 = n2 + 1, i = r.length > n2;
    return qt.uniq(e);
  }
  Ne.firstForSequence = ai;
  function oi(t3) {
    var e = qt.map(t3.definition, function(r) {
      return jt(r);
    });
    return qt.uniq(qt.flatten(e));
  }
  Ne.firstForBranching = oi;
  function si(t3) {
    return [t3.terminalType];
  }
  Ne.firstForTerminal = si;
});
var Mr = R2((Vt) => {
  "use strict";
  Object.defineProperty(Vt, "__esModule", { value: true });
  Vt.IN = void 0;
  Vt.IN = "_~IN~_";
});
var pi2 = R2((he) => {
  "use strict";
  var bo = he && he.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(he, "__esModule", { value: true });
  he.buildInProdFollowPrefix = he.buildBetweenProdsFollowPrefix = he.computeAllProdsFollows = he.ResyncFollowsWalker = void 0;
  var Fo = Gt(), wo = Lr(), ui = k(), ci = Mr(), Do = ne(), fi = function(t3) {
    bo(e, t3);
    function e(r) {
      var n2 = t3.call(this) || this;
      return n2.topProd = r, n2.follows = {}, n2;
    }
    return e.prototype.startWalking = function() {
      return this.walk(this.topProd), this.follows;
    }, e.prototype.walkTerminal = function(r, n2, i) {
    }, e.prototype.walkProdRef = function(r, n2, i) {
      var a2 = li(r.referencedRule, r.idx) + this.topProd.name, o = n2.concat(i), s = new Do.Alternative({ definition: o }), c2 = wo.first(s);
      this.follows[a2] = c2;
    }, e;
  }(Fo.RestWalker);
  he.ResyncFollowsWalker = fi;
  function Uo(t3) {
    var e = {};
    return ui.forEach(t3, function(r) {
      var n2 = new fi(r).startWalking();
      ui.assign(e, n2);
    }), e;
  }
  he.computeAllProdsFollows = Uo;
  function li(t3, e) {
    return t3.name + e + ci.IN;
  }
  he.buildBetweenProdsFollowPrefix = li;
  function Go(t3) {
    var e = t3.terminalType.name;
    return e + t3.idx + ci.IN;
  }
  he.buildInProdFollowPrefix = Go;
});
var mt = R2((Me) => {
  "use strict";
  Object.defineProperty(Me, "__esModule", { value: true });
  Me.defaultGrammarValidatorErrorProvider = Me.defaultGrammarResolverErrorProvider = Me.defaultParserErrorProvider = void 0;
  var Ze2 = Ue(), Wo = k(), ye = k(), br = ne(), hi = vt();
  Me.defaultParserErrorProvider = { buildMismatchTokenMessage: function(t3) {
    var e = t3.expected, r = t3.actual, n2 = t3.previous, i = t3.ruleName, a2 = Ze2.hasTokenLabel(e), o = a2 ? "--> " + Ze2.tokenLabel(e) + " <--" : "token of type --> " + e.name + " <--", s = "Expecting " + o + " but found --> '" + r.image + "' <--";
    return s;
  }, buildNotAllInputParsedMessage: function(t3) {
    var e = t3.firstRedundant, r = t3.ruleName;
    return "Redundant input, expecting EOF but found: " + e.image;
  }, buildNoViableAltMessage: function(t3) {
    var e = t3.expectedPathsPerAlt, r = t3.actual, n2 = t3.previous, i = t3.customUserDescription, a2 = t3.ruleName, o = "Expecting: ", s = ye.first(r).image, c2 = `
but found: '` + s + "'";
    if (i) return o + i + c2;
    var f = ye.reduce(e, function(v, u2) {
      return v.concat(u2);
    }, []), p = ye.map(f, function(v) {
      return "[" + ye.map(v, function(u2) {
        return Ze2.tokenLabel(u2);
      }).join(", ") + "]";
    }), l2 = ye.map(p, function(v, u2) {
      return "  " + (u2 + 1) + ". " + v;
    }), m = `one of these possible Token sequences:
` + l2.join(`
`);
    return o + m + c2;
  }, buildEarlyExitMessage: function(t3) {
    var e = t3.expectedIterationPaths, r = t3.actual, n2 = t3.customUserDescription, i = t3.ruleName, a2 = "Expecting: ", o = ye.first(r).image, s = `
but found: '` + o + "'";
    if (n2) return a2 + n2 + s;
    var c2 = ye.map(e, function(p) {
      return "[" + ye.map(p, function(l2) {
        return Ze2.tokenLabel(l2);
      }).join(",") + "]";
    }), f = `expecting at least one iteration which starts with one of these possible Token sequences::
  ` + ("<" + c2.join(" ,") + ">");
    return a2 + f + s;
  } };
  Object.freeze(Me.defaultParserErrorProvider);
  Me.defaultGrammarResolverErrorProvider = { buildRuleNotFoundError: function(t3, e) {
    var r = "Invalid grammar, reference to a rule which is not defined: ->" + e.nonTerminalName + `<-
inside top level rule: ->` + t3.name + "<-";
    return r;
  } };
  Me.defaultGrammarValidatorErrorProvider = { buildDuplicateFoundError: function(t3, e) {
    function r(p) {
      return p instanceof br.Terminal ? p.terminalType.name : p instanceof br.NonTerminal ? p.nonTerminalName : "";
    }
    var n2 = t3.name, i = ye.first(e), a2 = i.idx, o = hi.getProductionDslName(i), s = r(i), c2 = a2 > 0, f = "->" + o + (c2 ? a2 : "") + "<- " + (s ? "with argument: ->" + s + "<-" : "") + `
                  appears more than once (` + e.length + " times) in the top level rule: ->" + n2 + `<-.
                  For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES
                  `;
    return f = f.replace(/[ \t]+/g, " "), f = f.replace(/\s\s+/g, `
`), f;
  }, buildNamespaceConflictError: function(t3) {
    var e = `Namespace conflict found in grammar.
` + ("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <" + t3.name + `>.
`) + `To resolve this make sure each Terminal and Non-Terminal names are unique
This is easy to accomplish by using the convention that Terminal names start with an uppercase letter
and Non-Terminal names start with a lower case letter.`;
    return e;
  }, buildAlternationPrefixAmbiguityError: function(t3) {
    var e = ye.map(t3.prefixPath, function(i) {
      return Ze2.tokenLabel(i);
    }).join(", "), r = t3.alternation.idx === 0 ? "" : t3.alternation.idx, n2 = "Ambiguous alternatives: <" + t3.ambiguityIndices.join(" ,") + `> due to common lookahead prefix
` + ("in <OR" + r + "> inside <" + t3.topLevelRule.name + `> Rule,
`) + ("<" + e + `> may appears as a prefix path in all these alternatives.
`) + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX
For Further details.`;
    return n2;
  }, buildAlternationAmbiguityError: function(t3) {
    var e = ye.map(t3.prefixPath, function(i) {
      return Ze2.tokenLabel(i);
    }).join(", "), r = t3.alternation.idx === 0 ? "" : t3.alternation.idx, n2 = "Ambiguous Alternatives Detected: <" + t3.ambiguityIndices.join(" ,") + "> in <OR" + r + ">" + (" inside <" + t3.topLevelRule.name + `> Rule,
`) + ("<" + e + `> may appears as a prefix path in all these alternatives.
`);
    return n2 = n2 + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
For Further details.`, n2;
  }, buildEmptyRepetitionError: function(t3) {
    var e = hi.getProductionDslName(t3.repetition);
    t3.repetition.idx !== 0 && (e += t3.repetition.idx);
    var r = "The repetition <" + e + "> within Rule <" + t3.topLevelRule.name + `> can never consume any tokens.
This could lead to an infinite loop.`;
    return r;
  }, buildTokenNameError: function(t3) {
    return "deprecated";
  }, buildEmptyAlternationError: function(t3) {
    var e = "Ambiguous empty alternative: <" + (t3.emptyChoiceIdx + 1) + ">" + (" in <OR" + t3.alternation.idx + "> inside <" + t3.topLevelRule.name + `> Rule.
`) + "Only the last alternative may be an empty alternative.";
    return e;
  }, buildTooManyAlternativesError: function(t3) {
    var e = `An Alternation cannot have more than 256 alternatives:
` + ("<OR" + t3.alternation.idx + "> inside <" + t3.topLevelRule.name + `> Rule.
 has ` + (t3.alternation.definition.length + 1) + " alternatives.");
    return e;
  }, buildLeftRecursionError: function(t3) {
    var e = t3.topLevelRule.name, r = Wo.map(t3.leftRecursionPath, function(a2) {
      return a2.name;
    }), n2 = e + " --> " + r.concat([e]).join(" --> "), i = `Left Recursion found in grammar.
` + ("rule: <" + e + `> can be invoked from itself (directly or indirectly)
`) + (`without consuming any Tokens. The grammar path that causes this is:
 ` + n2 + `
`) + ` To fix this refactor your grammar to remove the left recursion.
see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`;
    return i;
  }, buildInvalidRuleNameError: function(t3) {
    return "deprecated";
  }, buildDuplicateRuleNameError: function(t3) {
    var e;
    t3.topLevelRule instanceof br.Rule ? e = t3.topLevelRule.name : e = t3.topLevelRule;
    var r = "Duplicate definition, rule: ->" + e + "<- is already defined in the grammar: ->" + t3.grammarName + "<-";
    return r;
  } };
});
var mi = R2((Ge2) => {
  "use strict";
  var Bo = Ge2 && Ge2.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(Ge2, "__esModule", { value: true });
  Ge2.GastRefResolverVisitor = Ge2.resolveGrammar = void 0;
  var qo = ce(), di = k(), jo = $e();
  function Vo(t3, e) {
    var r = new vi(t3, e);
    return r.resolveRefs(), r.errors;
  }
  Ge2.resolveGrammar = Vo;
  var vi = function(t3) {
    Bo(e, t3);
    function e(r, n2) {
      var i = t3.call(this) || this;
      return i.nameToTopRule = r, i.errMsgProvider = n2, i.errors = [], i;
    }
    return e.prototype.resolveRefs = function() {
      var r = this;
      di.forEach(di.values(this.nameToTopRule), function(n2) {
        r.currTopLevel = n2, n2.accept(r);
      });
    }, e.prototype.visitNonTerminal = function(r) {
      var n2 = this.nameToTopRule[r.nonTerminalName];
      if (n2) r.referencedRule = n2;
      else {
        var i = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, r);
        this.errors.push({ message: i, type: qo.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, ruleName: this.currTopLevel.name, unresolvedRefName: r.nonTerminalName });
      }
    }, e;
  }(jo.GAstVisitor);
  Ge2.GastRefResolverVisitor = vi;
});
var Tt = R2((j2) => {
  "use strict";
  var je = j2 && j2.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(j2, "__esModule", { value: true });
  j2.nextPossibleTokensAfter = j2.possiblePathsFrom = j2.NextTerminalAfterAtLeastOneSepWalker = j2.NextTerminalAfterAtLeastOneWalker = j2.NextTerminalAfterManySepWalker = j2.NextTerminalAfterManyWalker = j2.AbstractNextTerminalAfterProductionWalker = j2.NextAfterTokenWalker = j2.AbstractNextPossibleTokensWalker = void 0;
  var Ei2 = Gt(), I2 = k(), Ko = Lr(), O = ne(), Ti2 = function(t3) {
    je(e, t3);
    function e(r, n2) {
      var i = t3.call(this) || this;
      return i.topProd = r, i.path = n2, i.possibleTokTypes = [], i.nextProductionName = "", i.nextProductionOccurrence = 0, i.found = false, i.isAtEndOfPath = false, i;
    }
    return e.prototype.startWalking = function() {
      if (this.found = false, this.path.ruleStack[0] !== this.topProd.name) throw Error("The path does not start with the walker's top Rule!");
      return this.ruleStack = I2.cloneArr(this.path.ruleStack).reverse(), this.occurrenceStack = I2.cloneArr(this.path.occurrenceStack).reverse(), this.ruleStack.pop(), this.occurrenceStack.pop(), this.updateExpectedNext(), this.walk(this.topProd), this.possibleTokTypes;
    }, e.prototype.walk = function(r, n2) {
      n2 === void 0 && (n2 = []), this.found || t3.prototype.walk.call(this, r, n2);
    }, e.prototype.walkProdRef = function(r, n2, i) {
      if (r.referencedRule.name === this.nextProductionName && r.idx === this.nextProductionOccurrence) {
        var a2 = n2.concat(i);
        this.updateExpectedNext(), this.walk(r.referencedRule, a2);
      }
    }, e.prototype.updateExpectedNext = function() {
      I2.isEmpty(this.ruleStack) ? (this.nextProductionName = "", this.nextProductionOccurrence = 0, this.isAtEndOfPath = true) : (this.nextProductionName = this.ruleStack.pop(), this.nextProductionOccurrence = this.occurrenceStack.pop());
    }, e;
  }(Ei2.RestWalker);
  j2.AbstractNextPossibleTokensWalker = Ti2;
  var zo = function(t3) {
    je(e, t3);
    function e(r, n2) {
      var i = t3.call(this, r, n2) || this;
      return i.path = n2, i.nextTerminalName = "", i.nextTerminalOccurrence = 0, i.nextTerminalName = i.path.lastTok.name, i.nextTerminalOccurrence = i.path.lastTokOccurrence, i;
    }
    return e.prototype.walkTerminal = function(r, n2, i) {
      if (this.isAtEndOfPath && r.terminalType.name === this.nextTerminalName && r.idx === this.nextTerminalOccurrence && !this.found) {
        var a2 = n2.concat(i), o = new O.Alternative({ definition: a2 });
        this.possibleTokTypes = Ko.first(o), this.found = true;
      }
    }, e;
  }(Ti2);
  j2.NextAfterTokenWalker = zo;
  var Et = function(t3) {
    je(e, t3);
    function e(r, n2) {
      var i = t3.call(this) || this;
      return i.topRule = r, i.occurrence = n2, i.result = { token: void 0, occurrence: void 0, isEndOfRule: void 0 }, i;
    }
    return e.prototype.startWalking = function() {
      return this.walk(this.topRule), this.result;
    }, e;
  }(Ei2.RestWalker);
  j2.AbstractNextTerminalAfterProductionWalker = Et;
  var Ho = function(t3) {
    je(e, t3);
    function e() {
      return t3 !== null && t3.apply(this, arguments) || this;
    }
    return e.prototype.walkMany = function(r, n2, i) {
      if (r.idx === this.occurrence) {
        var a2 = I2.first(n2.concat(i));
        this.result.isEndOfRule = a2 === void 0, a2 instanceof O.Terminal && (this.result.token = a2.terminalType, this.result.occurrence = a2.idx);
      } else t3.prototype.walkMany.call(this, r, n2, i);
    }, e;
  }(Et);
  j2.NextTerminalAfterManyWalker = Ho;
  var Yo = function(t3) {
    je(e, t3);
    function e() {
      return t3 !== null && t3.apply(this, arguments) || this;
    }
    return e.prototype.walkManySep = function(r, n2, i) {
      if (r.idx === this.occurrence) {
        var a2 = I2.first(n2.concat(i));
        this.result.isEndOfRule = a2 === void 0, a2 instanceof O.Terminal && (this.result.token = a2.terminalType, this.result.occurrence = a2.idx);
      } else t3.prototype.walkManySep.call(this, r, n2, i);
    }, e;
  }(Et);
  j2.NextTerminalAfterManySepWalker = Yo;
  var Xo = function(t3) {
    je(e, t3);
    function e() {
      return t3 !== null && t3.apply(this, arguments) || this;
    }
    return e.prototype.walkAtLeastOne = function(r, n2, i) {
      if (r.idx === this.occurrence) {
        var a2 = I2.first(n2.concat(i));
        this.result.isEndOfRule = a2 === void 0, a2 instanceof O.Terminal && (this.result.token = a2.terminalType, this.result.occurrence = a2.idx);
      } else t3.prototype.walkAtLeastOne.call(this, r, n2, i);
    }, e;
  }(Et);
  j2.NextTerminalAfterAtLeastOneWalker = Xo;
  var $o = function(t3) {
    je(e, t3);
    function e() {
      return t3 !== null && t3.apply(this, arguments) || this;
    }
    return e.prototype.walkAtLeastOneSep = function(r, n2, i) {
      if (r.idx === this.occurrence) {
        var a2 = I2.first(n2.concat(i));
        this.result.isEndOfRule = a2 === void 0, a2 instanceof O.Terminal && (this.result.token = a2.terminalType, this.result.occurrence = a2.idx);
      } else t3.prototype.walkAtLeastOneSep.call(this, r, n2, i);
    }, e;
  }(Et);
  j2.NextTerminalAfterAtLeastOneSepWalker = $o;
  function yi(t3, e, r) {
    r === void 0 && (r = []), r = I2.cloneArr(r);
    var n2 = [], i = 0;
    function a2(f) {
      return f.concat(I2.drop(t3, i + 1));
    }
    function o(f) {
      var p = yi(a2(f), e, r);
      return n2.concat(p);
    }
    for (; r.length < e && i < t3.length; ) {
      var s = t3[i];
      if (s instanceof O.Alternative) return o(s.definition);
      if (s instanceof O.NonTerminal) return o(s.definition);
      if (s instanceof O.Option) n2 = o(s.definition);
      else if (s instanceof O.RepetitionMandatory) {
        var c2 = s.definition.concat([new O.Repetition({ definition: s.definition })]);
        return o(c2);
      } else if (s instanceof O.RepetitionMandatoryWithSeparator) {
        var c2 = [new O.Alternative({ definition: s.definition }), new O.Repetition({ definition: [new O.Terminal({ terminalType: s.separator })].concat(s.definition) })];
        return o(c2);
      } else if (s instanceof O.RepetitionWithSeparator) {
        var c2 = s.definition.concat([new O.Repetition({ definition: [new O.Terminal({ terminalType: s.separator })].concat(s.definition) })]);
        n2 = o(c2);
      } else if (s instanceof O.Repetition) {
        var c2 = s.definition.concat([new O.Repetition({ definition: s.definition })]);
        n2 = o(c2);
      } else {
        if (s instanceof O.Alternation) return I2.forEach(s.definition, function(f) {
          I2.isEmpty(f.definition) === false && (n2 = o(f.definition));
        }), n2;
        if (s instanceof O.Terminal) r.push(s.terminalType);
        else throw Error("non exhaustive match");
      }
      i++;
    }
    return n2.push({ partialPath: r, suffixDef: I2.drop(t3, i) }), n2;
  }
  j2.possiblePathsFrom = yi;
  function Qo(t3, e, r, n2) {
    var i = "EXIT_NONE_TERMINAL", a2 = [i], o = "EXIT_ALTERNATIVE", s = false, c2 = e.length, f = c2 - n2 - 1, p = [], l2 = [];
    for (l2.push({ idx: -1, def: t3, ruleStack: [], occurrenceStack: [] }); !I2.isEmpty(l2); ) {
      var m = l2.pop();
      if (m === o) {
        s && I2.last(l2).idx <= f && l2.pop();
        continue;
      }
      var v = m.def, u2 = m.idx, d = m.ruleStack, A2 = m.occurrenceStack;
      if (!I2.isEmpty(v)) {
        var _ = v[0];
        if (_ === i) {
          var g3 = { idx: u2, def: I2.drop(v), ruleStack: I2.dropRight(d), occurrenceStack: I2.dropRight(A2) };
          l2.push(g3);
        } else if (_ instanceof O.Terminal) if (u2 < c2 - 1) {
          var y = u2 + 1, b3 = e[y];
          if (r(b3, _.terminalType)) {
            var g3 = { idx: y, def: I2.drop(v), ruleStack: d, occurrenceStack: A2 };
            l2.push(g3);
          }
        } else if (u2 === c2 - 1) p.push({ nextTokenType: _.terminalType, nextTokenOccurrence: _.idx, ruleStack: d, occurrenceStack: A2 }), s = true;
        else throw Error("non exhaustive match");
        else if (_ instanceof O.NonTerminal) {
          var L = I2.cloneArr(d);
          L.push(_.nonTerminalName);
          var se = I2.cloneArr(A2);
          se.push(_.idx);
          var g3 = { idx: u2, def: _.definition.concat(a2, I2.drop(v)), ruleStack: L, occurrenceStack: se };
          l2.push(g3);
        } else if (_ instanceof O.Option) {
          var fe = { idx: u2, def: I2.drop(v), ruleStack: d, occurrenceStack: A2 };
          l2.push(fe), l2.push(o);
          var Z2 = { idx: u2, def: _.definition.concat(I2.drop(v)), ruleStack: d, occurrenceStack: A2 };
          l2.push(Z2);
        } else if (_ instanceof O.RepetitionMandatory) {
          var ue2 = new O.Repetition({ definition: _.definition, idx: _.idx }), Q2 = _.definition.concat([ue2], I2.drop(v)), g3 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 };
          l2.push(g3);
        } else if (_ instanceof O.RepetitionMandatoryWithSeparator) {
          var te3 = new O.Terminal({ terminalType: _.separator }), ue2 = new O.Repetition({ definition: [te3].concat(_.definition), idx: _.idx }), Q2 = _.definition.concat([ue2], I2.drop(v)), g3 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 };
          l2.push(g3);
        } else if (_ instanceof O.RepetitionWithSeparator) {
          var fe = { idx: u2, def: I2.drop(v), ruleStack: d, occurrenceStack: A2 };
          l2.push(fe), l2.push(o);
          var te3 = new O.Terminal({ terminalType: _.separator }), xe = new O.Repetition({ definition: [te3].concat(_.definition), idx: _.idx }), Q2 = _.definition.concat([xe], I2.drop(v)), Z2 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 };
          l2.push(Z2);
        } else if (_ instanceof O.Repetition) {
          var fe = { idx: u2, def: I2.drop(v), ruleStack: d, occurrenceStack: A2 };
          l2.push(fe), l2.push(o);
          var xe = new O.Repetition({ definition: _.definition, idx: _.idx }), Q2 = _.definition.concat([xe], I2.drop(v)), Z2 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 };
          l2.push(Z2);
        } else if (_ instanceof O.Alternation) for (var it2 = _.definition.length - 1; it2 >= 0; it2--) {
          var at = _.definition[it2], Ke = { idx: u2, def: at.definition.concat(I2.drop(v)), ruleStack: d, occurrenceStack: A2 };
          l2.push(Ke), l2.push(o);
        }
        else if (_ instanceof O.Alternative) l2.push({ idx: u2, def: _.definition.concat(I2.drop(v)), ruleStack: d, occurrenceStack: A2 });
        else if (_ instanceof O.Rule) l2.push(Zo(_, u2, d, A2));
        else throw Error("non exhaustive match");
      }
    }
    return p;
  }
  j2.nextPossibleTokensAfter = Qo;
  function Zo(t3, e, r, n2) {
    var i = I2.cloneArr(r);
    i.push(t3.name);
    var a2 = I2.cloneArr(n2);
    return a2.push(1), { idx: e, def: t3.definition, ruleStack: i, occurrenceStack: a2 };
  }
});
var yt2 = R2((C3) => {
  "use strict";
  var _i = C3 && C3.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(C3, "__esModule", { value: true });
  C3.areTokenCategoriesNotUsed = C3.isStrictPrefixOfPath = C3.containsPath = C3.getLookaheadPathsForOptionalProd = C3.getLookaheadPathsForOr = C3.lookAheadSequenceFromAlternatives = C3.buildSingleAlternativeLookaheadFunction = C3.buildAlternativesLookAheadFunc = C3.buildLookaheadFuncForOptionalProd = C3.buildLookaheadFuncForOr = C3.getProdType = C3.PROD_TYPE = void 0;
  var D = k(), gi = Tt(), Jo = Gt(), Kt = Xe(), We = ne(), es = $e(), z;
  (function(t3) {
    t3[t3.OPTION = 0] = "OPTION", t3[t3.REPETITION = 1] = "REPETITION", t3[t3.REPETITION_MANDATORY = 2] = "REPETITION_MANDATORY", t3[t3.REPETITION_MANDATORY_WITH_SEPARATOR = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR", t3[t3.REPETITION_WITH_SEPARATOR = 4] = "REPETITION_WITH_SEPARATOR", t3[t3.ALTERNATION = 5] = "ALTERNATION";
  })(z = C3.PROD_TYPE || (C3.PROD_TYPE = {}));
  function ts(t3) {
    if (t3 instanceof We.Option) return z.OPTION;
    if (t3 instanceof We.Repetition) return z.REPETITION;
    if (t3 instanceof We.RepetitionMandatory) return z.REPETITION_MANDATORY;
    if (t3 instanceof We.RepetitionMandatoryWithSeparator) return z.REPETITION_MANDATORY_WITH_SEPARATOR;
    if (t3 instanceof We.RepetitionWithSeparator) return z.REPETITION_WITH_SEPARATOR;
    if (t3 instanceof We.Alternation) return z.ALTERNATION;
    throw Error("non exhaustive match");
  }
  C3.getProdType = ts;
  function rs(t3, e, r, n2, i, a2) {
    var o = Ai(t3, e, r), s = Fr(o) ? Kt.tokenStructuredMatcherNoCategories : Kt.tokenStructuredMatcher;
    return a2(o, n2, s, i);
  }
  C3.buildLookaheadFuncForOr = rs;
  function ns(t3, e, r, n2, i, a2) {
    var o = Ri(t3, e, i, r), s = Fr(o) ? Kt.tokenStructuredMatcherNoCategories : Kt.tokenStructuredMatcher;
    return a2(o[0], s, n2);
  }
  C3.buildLookaheadFuncForOptionalProd = ns;
  function is(t3, e, r, n2) {
    var i = t3.length, a2 = D.every(t3, function(c2) {
      return D.every(c2, function(f) {
        return f.length === 1;
      });
    });
    if (e) return function(c2) {
      for (var f = D.map(c2, function(y) {
        return y.GATE;
      }), p = 0; p < i; p++) {
        var l2 = t3[p], m = l2.length, v = f[p];
        if (v !== void 0 && v.call(this) === false) continue;
        e: for (var u2 = 0; u2 < m; u2++) {
          for (var d = l2[u2], A2 = d.length, _ = 0; _ < A2; _++) {
            var g3 = this.LA(_ + 1);
            if (r(g3, d[_]) === false) continue e;
          }
          return p;
        }
      }
    };
    if (a2 && !n2) {
      var o = D.map(t3, function(c2) {
        return D.flatten(c2);
      }), s = D.reduce(o, function(c2, f, p) {
        return D.forEach(f, function(l2) {
          D.has(c2, l2.tokenTypeIdx) || (c2[l2.tokenTypeIdx] = p), D.forEach(l2.categoryMatches, function(m) {
            D.has(c2, m) || (c2[m] = p);
          });
        }), c2;
      }, []);
      return function() {
        var c2 = this.LA(1);
        return s[c2.tokenTypeIdx];
      };
    } else return function() {
      for (var c2 = 0; c2 < i; c2++) {
        var f = t3[c2], p = f.length;
        e: for (var l2 = 0; l2 < p; l2++) {
          for (var m = f[l2], v = m.length, u2 = 0; u2 < v; u2++) {
            var d = this.LA(u2 + 1);
            if (r(d, m[u2]) === false) continue e;
          }
          return c2;
        }
      }
    };
  }
  C3.buildAlternativesLookAheadFunc = is;
  function as(t3, e, r) {
    var n2 = D.every(t3, function(f) {
      return f.length === 1;
    }), i = t3.length;
    if (n2 && !r) {
      var a2 = D.flatten(t3);
      if (a2.length === 1 && D.isEmpty(a2[0].categoryMatches)) {
        var o = a2[0], s = o.tokenTypeIdx;
        return function() {
          return this.LA(1).tokenTypeIdx === s;
        };
      } else {
        var c2 = D.reduce(a2, function(f, p, l2) {
          return f[p.tokenTypeIdx] = true, D.forEach(p.categoryMatches, function(m) {
            f[m] = true;
          }), f;
        }, []);
        return function() {
          var f = this.LA(1);
          return c2[f.tokenTypeIdx] === true;
        };
      }
    } else return function() {
      e: for (var f = 0; f < i; f++) {
        for (var p = t3[f], l2 = p.length, m = 0; m < l2; m++) {
          var v = this.LA(m + 1);
          if (e(v, p[m]) === false) continue e;
        }
        return true;
      }
      return false;
    };
  }
  C3.buildSingleAlternativeLookaheadFunction = as;
  var os = function(t3) {
    _i(e, t3);
    function e(r, n2, i) {
      var a2 = t3.call(this) || this;
      return a2.topProd = r, a2.targetOccurrence = n2, a2.targetProdType = i, a2;
    }
    return e.prototype.startWalking = function() {
      return this.walk(this.topProd), this.restDef;
    }, e.prototype.checkIsTarget = function(r, n2, i, a2) {
      return r.idx === this.targetOccurrence && this.targetProdType === n2 ? (this.restDef = i.concat(a2), true) : false;
    }, e.prototype.walkOption = function(r, n2, i) {
      this.checkIsTarget(r, z.OPTION, n2, i) || t3.prototype.walkOption.call(this, r, n2, i);
    }, e.prototype.walkAtLeastOne = function(r, n2, i) {
      this.checkIsTarget(r, z.REPETITION_MANDATORY, n2, i) || t3.prototype.walkOption.call(this, r, n2, i);
    }, e.prototype.walkAtLeastOneSep = function(r, n2, i) {
      this.checkIsTarget(r, z.REPETITION_MANDATORY_WITH_SEPARATOR, n2, i) || t3.prototype.walkOption.call(this, r, n2, i);
    }, e.prototype.walkMany = function(r, n2, i) {
      this.checkIsTarget(r, z.REPETITION, n2, i) || t3.prototype.walkOption.call(this, r, n2, i);
    }, e.prototype.walkManySep = function(r, n2, i) {
      this.checkIsTarget(r, z.REPETITION_WITH_SEPARATOR, n2, i) || t3.prototype.walkOption.call(this, r, n2, i);
    }, e;
  }(Jo.RestWalker), Oi2 = function(t3) {
    _i(e, t3);
    function e(r, n2, i) {
      var a2 = t3.call(this) || this;
      return a2.targetOccurrence = r, a2.targetProdType = n2, a2.targetRef = i, a2.result = [], a2;
    }
    return e.prototype.checkIsTarget = function(r, n2) {
      r.idx === this.targetOccurrence && this.targetProdType === n2 && (this.targetRef === void 0 || r === this.targetRef) && (this.result = r.definition);
    }, e.prototype.visitOption = function(r) {
      this.checkIsTarget(r, z.OPTION);
    }, e.prototype.visitRepetition = function(r) {
      this.checkIsTarget(r, z.REPETITION);
    }, e.prototype.visitRepetitionMandatory = function(r) {
      this.checkIsTarget(r, z.REPETITION_MANDATORY);
    }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) {
      this.checkIsTarget(r, z.REPETITION_MANDATORY_WITH_SEPARATOR);
    }, e.prototype.visitRepetitionWithSeparator = function(r) {
      this.checkIsTarget(r, z.REPETITION_WITH_SEPARATOR);
    }, e.prototype.visitAlternation = function(r) {
      this.checkIsTarget(r, z.ALTERNATION);
    }, e;
  }(es.GAstVisitor);
  function Ni(t3) {
    for (var e = new Array(t3), r = 0; r < t3; r++) e[r] = [];
    return e;
  }
  function wr(t3) {
    for (var e = [""], r = 0; r < t3.length; r++) {
      for (var n2 = t3[r], i = [], a2 = 0; a2 < e.length; a2++) {
        var o = e[a2];
        i.push(o + "_" + n2.tokenTypeIdx);
        for (var s = 0; s < n2.categoryMatches.length; s++) {
          var c2 = "_" + n2.categoryMatches[s];
          i.push(o + c2);
        }
      }
      e = i;
    }
    return e;
  }
  function ss(t3, e, r) {
    for (var n2 = 0; n2 < t3.length; n2++) if (n2 !== r) for (var i = t3[n2], a2 = 0; a2 < e.length; a2++) {
      var o = e[a2];
      if (i[o] === true) return false;
    }
    return true;
  }
  function Dr(t3, e) {
    for (var r = D.map(t3, function(p) {
      return gi.possiblePathsFrom([p], 1);
    }), n2 = Ni(r.length), i = D.map(r, function(p) {
      var l2 = {};
      return D.forEach(p, function(m) {
        var v = wr(m.partialPath);
        D.forEach(v, function(u2) {
          l2[u2] = true;
        });
      }), l2;
    }), a2 = r, o = 1; o <= e; o++) {
      var s = a2;
      a2 = Ni(s.length);
      for (var c2 = function(p) {
        for (var l2 = s[p], m = 0; m < l2.length; m++) {
          var v = l2[m].partialPath, u2 = l2[m].suffixDef, d = wr(v), A2 = ss(i, d, p);
          if (A2 || D.isEmpty(u2) || v.length === e) {
            var _ = n2[p];
            if (Ii2(_, v) === false) {
              _.push(v);
              for (var g3 = 0; g3 < d.length; g3++) {
                var y = d[g3];
                i[p][y] = true;
              }
            }
          } else {
            var b3 = gi.possiblePathsFrom(u2, o + 1, v);
            a2[p] = a2[p].concat(b3), D.forEach(b3, function(L) {
              var se = wr(L.partialPath);
              D.forEach(se, function(fe) {
                i[p][fe] = true;
              });
            });
          }
        }
      }, f = 0; f < s.length; f++) c2(f);
    }
    return n2;
  }
  C3.lookAheadSequenceFromAlternatives = Dr;
  function Ai(t3, e, r, n2) {
    var i = new Oi2(t3, z.ALTERNATION, n2);
    return e.accept(i), Dr(i.result, r);
  }
  C3.getLookaheadPathsForOr = Ai;
  function Ri(t3, e, r, n2) {
    var i = new Oi2(t3, r);
    e.accept(i);
    var a2 = i.result, o = new os(e, t3, r), s = o.startWalking(), c2 = new We.Alternative({ definition: a2 }), f = new We.Alternative({ definition: s });
    return Dr([c2, f], n2);
  }
  C3.getLookaheadPathsForOptionalProd = Ri;
  function Ii2(t3, e) {
    e: for (var r = 0; r < t3.length; r++) {
      var n2 = t3[r];
      if (n2.length === e.length) {
        for (var i = 0; i < n2.length; i++) {
          var a2 = e[i], o = n2[i], s = a2 === o || o.categoryMatchesMap[a2.tokenTypeIdx] !== void 0;
          if (s === false) continue e;
        }
        return true;
      }
    }
    return false;
  }
  C3.containsPath = Ii2;
  function us(t3, e) {
    return t3.length < e.length && D.every(t3, function(r, n2) {
      var i = e[n2];
      return r === i || i.categoryMatchesMap[r.tokenTypeIdx];
    });
  }
  C3.isStrictPrefixOfPath = us;
  function Fr(t3) {
    return D.every(t3, function(e) {
      return D.every(e, function(r) {
        return D.every(r, function(n2) {
          return D.isEmpty(n2.categoryMatches);
        });
      });
    });
  }
  C3.areTokenCategoriesNotUsed = Fr;
});
var jr = R2((x2) => {
  "use strict";
  var Ur = x2 && x2.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(x2, "__esModule", { value: true });
  x2.checkPrefixAlternativesAmbiguities = x2.validateSomeNonEmptyLookaheadPath = x2.validateTooManyAlts = x2.RepetionCollector = x2.validateAmbiguousAlternationAlternatives = x2.validateEmptyOrAlternative = x2.getFirstNoneTerminal = x2.validateNoLeftRecursion = x2.validateRuleIsOverridden = x2.validateRuleDoesNotAlreadyExist = x2.OccurrenceValidationCollector = x2.identifyProductionForDuplicates = x2.validateGrammar = void 0;
  var M = k(), B2 = k(), Ie = ce(), Gr = vt(), Qe2 = yt2(), cs = Tt(), _e = ne(), Wr = $e();
  function ps(t3, e, r, n2, i) {
    var a2 = M.map(t3, function(v) {
      return ls(v, n2);
    }), o = M.map(t3, function(v) {
      return Br(v, v, n2);
    }), s = [], c2 = [], f = [];
    B2.every(o, B2.isEmpty) && (s = B2.map(t3, function(v) {
      return Pi2(v, n2);
    }), c2 = B2.map(t3, function(v) {
      return Si2(v, e, n2);
    }), f = Ci2(t3, e, n2));
    var p = fs(t3, r, n2), l2 = B2.map(t3, function(v) {
      return xi(v, n2);
    }), m = B2.map(t3, function(v) {
      return ki(v, t3, i, n2);
    });
    return M.flatten(a2.concat(f, o, s, c2, p, l2, m));
  }
  x2.validateGrammar = ps;
  function ls(t3, e) {
    var r = new bi();
    t3.accept(r);
    var n2 = r.allProductions, i = M.groupBy(n2, Li), a2 = M.pick(i, function(s) {
      return s.length > 1;
    }), o = M.map(M.values(a2), function(s) {
      var c2 = M.first(s), f = e.buildDuplicateFoundError(t3, s), p = Gr.getProductionDslName(c2), l2 = { message: f, type: Ie.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, ruleName: t3.name, dslName: p, occurrence: c2.idx }, m = Mi2(c2);
      return m && (l2.parameter = m), l2;
    });
    return o;
  }
  function Li(t3) {
    return Gr.getProductionDslName(t3) + "_#_" + t3.idx + "_#_" + Mi2(t3);
  }
  x2.identifyProductionForDuplicates = Li;
  function Mi2(t3) {
    return t3 instanceof _e.Terminal ? t3.terminalType.name : t3 instanceof _e.NonTerminal ? t3.nonTerminalName : "";
  }
  var bi = function(t3) {
    Ur(e, t3);
    function e() {
      var r = t3 !== null && t3.apply(this, arguments) || this;
      return r.allProductions = [], r;
    }
    return e.prototype.visitNonTerminal = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitOption = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitRepetitionWithSeparator = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitRepetitionMandatory = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitRepetition = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitAlternation = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitTerminal = function(r) {
      this.allProductions.push(r);
    }, e;
  }(Wr.GAstVisitor);
  x2.OccurrenceValidationCollector = bi;
  function ki(t3, e, r, n2) {
    var i = [], a2 = B2.reduce(e, function(s, c2) {
      return c2.name === t3.name ? s + 1 : s;
    }, 0);
    if (a2 > 1) {
      var o = n2.buildDuplicateRuleNameError({ topLevelRule: t3, grammarName: r });
      i.push({ message: o, type: Ie.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: t3.name });
    }
    return i;
  }
  x2.validateRuleDoesNotAlreadyExist = ki;
  function hs(t3, e, r) {
    var n2 = [], i;
    return M.contains(e, t3) || (i = "Invalid rule override, rule: ->" + t3 + "<- cannot be overridden in the grammar: ->" + r + "<-as it is not defined in any of the super grammars ", n2.push({ message: i, type: Ie.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, ruleName: t3 })), n2;
  }
  x2.validateRuleIsOverridden = hs;
  function Br(t3, e, r, n2) {
    n2 === void 0 && (n2 = []);
    var i = [], a2 = _t(e.definition);
    if (M.isEmpty(a2)) return [];
    var o = t3.name, s = M.contains(a2, t3);
    s && i.push({ message: r.buildLeftRecursionError({ topLevelRule: t3, leftRecursionPath: n2 }), type: Ie.ParserDefinitionErrorType.LEFT_RECURSION, ruleName: o });
    var c2 = M.difference(a2, n2.concat([t3])), f = M.map(c2, function(p) {
      var l2 = M.cloneArr(n2);
      return l2.push(p), Br(t3, p, r, l2);
    });
    return i.concat(M.flatten(f));
  }
  x2.validateNoLeftRecursion = Br;
  function _t(t3) {
    var e = [];
    if (M.isEmpty(t3)) return e;
    var r = M.first(t3);
    if (r instanceof _e.NonTerminal) e.push(r.referencedRule);
    else if (r instanceof _e.Alternative || r instanceof _e.Option || r instanceof _e.RepetitionMandatory || r instanceof _e.RepetitionMandatoryWithSeparator || r instanceof _e.RepetitionWithSeparator || r instanceof _e.Repetition) e = e.concat(_t(r.definition));
    else if (r instanceof _e.Alternation) e = M.flatten(M.map(r.definition, function(o) {
      return _t(o.definition);
    }));
    else if (!(r instanceof _e.Terminal)) throw Error("non exhaustive match");
    var n2 = Gr.isOptionalProd(r), i = t3.length > 1;
    if (n2 && i) {
      var a2 = M.drop(t3);
      return e.concat(_t(a2));
    } else return e;
  }
  x2.getFirstNoneTerminal = _t;
  var qr = function(t3) {
    Ur(e, t3);
    function e() {
      var r = t3 !== null && t3.apply(this, arguments) || this;
      return r.alternations = [], r;
    }
    return e.prototype.visitAlternation = function(r) {
      this.alternations.push(r);
    }, e;
  }(Wr.GAstVisitor);
  function Pi2(t3, e) {
    var r = new qr();
    t3.accept(r);
    var n2 = r.alternations, i = M.reduce(n2, function(a2, o) {
      var s = M.dropRight(o.definition), c2 = M.map(s, function(f, p) {
        var l2 = cs.nextPossibleTokensAfter([f], [], null, 1);
        return M.isEmpty(l2) ? { message: e.buildEmptyAlternationError({ topLevelRule: t3, alternation: o, emptyChoiceIdx: p }), type: Ie.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, ruleName: t3.name, occurrence: o.idx, alternative: p + 1 } : null;
      });
      return a2.concat(M.compact(c2));
    }, []);
    return i;
  }
  x2.validateEmptyOrAlternative = Pi2;
  function Si2(t3, e, r) {
    var n2 = new qr();
    t3.accept(n2);
    var i = n2.alternations;
    i = B2.reject(i, function(o) {
      return o.ignoreAmbiguities === true;
    });
    var a2 = M.reduce(i, function(o, s) {
      var c2 = s.idx, f = s.maxLookahead || e, p = Qe2.getLookaheadPathsForOr(c2, t3, f, s), l2 = ds(p, s, t3, r), m = Fi2(p, s, t3, r);
      return o.concat(l2, m);
    }, []);
    return a2;
  }
  x2.validateAmbiguousAlternationAlternatives = Si2;
  var wi = function(t3) {
    Ur(e, t3);
    function e() {
      var r = t3 !== null && t3.apply(this, arguments) || this;
      return r.allProductions = [], r;
    }
    return e.prototype.visitRepetitionWithSeparator = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitRepetitionMandatory = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) {
      this.allProductions.push(r);
    }, e.prototype.visitRepetition = function(r) {
      this.allProductions.push(r);
    }, e;
  }(Wr.GAstVisitor);
  x2.RepetionCollector = wi;
  function xi(t3, e) {
    var r = new qr();
    t3.accept(r);
    var n2 = r.alternations, i = M.reduce(n2, function(a2, o) {
      return o.definition.length > 255 && a2.push({ message: e.buildTooManyAlternativesError({ topLevelRule: t3, alternation: o }), type: Ie.ParserDefinitionErrorType.TOO_MANY_ALTS, ruleName: t3.name, occurrence: o.idx }), a2;
    }, []);
    return i;
  }
  x2.validateTooManyAlts = xi;
  function Ci2(t3, e, r) {
    var n2 = [];
    return B2.forEach(t3, function(i) {
      var a2 = new wi();
      i.accept(a2);
      var o = a2.allProductions;
      B2.forEach(o, function(s) {
        var c2 = Qe2.getProdType(s), f = s.maxLookahead || e, p = s.idx, l2 = Qe2.getLookaheadPathsForOptionalProd(p, i, c2, f), m = l2[0];
        if (B2.isEmpty(B2.flatten(m))) {
          var v = r.buildEmptyRepetitionError({ topLevelRule: i, repetition: s });
          n2.push({ message: v, type: Ie.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, ruleName: i.name });
        }
      });
    }), n2;
  }
  x2.validateSomeNonEmptyLookaheadPath = Ci2;
  function ds(t3, e, r, n2) {
    var i = [], a2 = B2.reduce(t3, function(s, c2, f) {
      return e.definition[f].ignoreAmbiguities === true || B2.forEach(c2, function(p) {
        var l2 = [f];
        B2.forEach(t3, function(m, v) {
          f !== v && Qe2.containsPath(m, p) && e.definition[v].ignoreAmbiguities !== true && l2.push(v);
        }), l2.length > 1 && !Qe2.containsPath(i, p) && (i.push(p), s.push({ alts: l2, path: p }));
      }), s;
    }, []), o = M.map(a2, function(s) {
      var c2 = B2.map(s.alts, function(p) {
        return p + 1;
      }), f = n2.buildAlternationAmbiguityError({ topLevelRule: r, alternation: e, ambiguityIndices: c2, prefixPath: s.path });
      return { message: f, type: Ie.ParserDefinitionErrorType.AMBIGUOUS_ALTS, ruleName: r.name, occurrence: e.idx, alternatives: [s.alts] };
    });
    return o;
  }
  function Fi2(t3, e, r, n2) {
    var i = [], a2 = B2.reduce(t3, function(o, s, c2) {
      var f = B2.map(s, function(p) {
        return { idx: c2, path: p };
      });
      return o.concat(f);
    }, []);
    return B2.forEach(a2, function(o) {
      var s = e.definition[o.idx];
      if (s.ignoreAmbiguities !== true) {
        var c2 = o.idx, f = o.path, p = B2.findAll(a2, function(m) {
          return e.definition[m.idx].ignoreAmbiguities !== true && m.idx < c2 && Qe2.isStrictPrefixOfPath(m.path, f);
        }), l2 = B2.map(p, function(m) {
          var v = [m.idx + 1, c2 + 1], u2 = e.idx === 0 ? "" : e.idx, d = n2.buildAlternationPrefixAmbiguityError({ topLevelRule: r, alternation: e, ambiguityIndices: v, prefixPath: m.path });
          return { message: d, type: Ie.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, ruleName: r.name, occurrence: u2, alternatives: v };
        });
        i = i.concat(l2);
      }
    }), i;
  }
  x2.checkPrefixAlternativesAmbiguities = Fi2;
  function fs(t3, e, r) {
    var n2 = [], i = B2.map(e, function(a2) {
      return a2.name;
    });
    return B2.forEach(t3, function(a2) {
      var o = a2.name;
      if (B2.contains(i, o)) {
        var s = r.buildNamespaceConflictError(a2);
        n2.push({ message: s, type: Ie.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, ruleName: o });
      }
    }), n2;
  }
});
var Ui = R2((Je2) => {
  "use strict";
  Object.defineProperty(Je2, "__esModule", { value: true });
  Je2.validateGrammar = Je2.resolveGrammar = void 0;
  var Vr = k(), vs = mi(), ms = jr(), Di = mt();
  function Es(t3) {
    t3 = Vr.defaults(t3, { errMsgProvider: Di.defaultGrammarResolverErrorProvider });
    var e = {};
    return Vr.forEach(t3.rules, function(r) {
      e[r.name] = r;
    }), vs.resolveGrammar(e, t3.errMsgProvider);
  }
  Je2.resolveGrammar = Es;
  function Ts(t3) {
    return t3 = Vr.defaults(t3, { errMsgProvider: Di.defaultGrammarValidatorErrorProvider }), ms.validateGrammar(t3.rules, t3.maxLookahead, t3.tokenTypes, t3.errMsgProvider, t3.grammarName);
  }
  Je2.validateGrammar = Ts;
});
var et2 = R2((ae2) => {
  "use strict";
  var gt = ae2 && ae2.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(ae2, "__esModule", { value: true });
  ae2.EarlyExitException = ae2.NotAllInputParsedException = ae2.NoViableAltException = ae2.MismatchedTokenException = ae2.isRecognitionException = void 0;
  var ys = k(), Gi = "MismatchedTokenException", Wi2 = "NoViableAltException", Bi = "EarlyExitException", qi = "NotAllInputParsedException", ji = [Gi, Wi2, Bi, qi];
  Object.freeze(ji);
  function _s(t3) {
    return ys.contains(ji, t3.name);
  }
  ae2.isRecognitionException = _s;
  var zt = function(t3) {
    gt(e, t3);
    function e(r, n2) {
      var i = this.constructor, a2 = t3.call(this, r) || this;
      return a2.token = n2, a2.resyncedTokens = [], Object.setPrototypeOf(a2, i.prototype), Error.captureStackTrace && Error.captureStackTrace(a2, a2.constructor), a2;
    }
    return e;
  }(Error), gs = function(t3) {
    gt(e, t3);
    function e(r, n2, i) {
      var a2 = t3.call(this, r, n2) || this;
      return a2.previousToken = i, a2.name = Gi, a2;
    }
    return e;
  }(zt);
  ae2.MismatchedTokenException = gs;
  var As = function(t3) {
    gt(e, t3);
    function e(r, n2, i) {
      var a2 = t3.call(this, r, n2) || this;
      return a2.previousToken = i, a2.name = Wi2, a2;
    }
    return e;
  }(zt);
  ae2.NoViableAltException = As;
  var Rs = function(t3) {
    gt(e, t3);
    function e(r, n2) {
      var i = t3.call(this, r, n2) || this;
      return i.name = qi, i;
    }
    return e;
  }(zt);
  ae2.NotAllInputParsedException = Rs;
  var Os = function(t3) {
    gt(e, t3);
    function e(r, n2, i) {
      var a2 = t3.call(this, r, n2) || this;
      return a2.previousToken = i, a2.name = Bi, a2;
    }
    return e;
  }(zt);
  ae2.EarlyExitException = Os;
});
var zr = R2(($2) => {
  "use strict";
  Object.defineProperty($2, "__esModule", { value: true });
  $2.attemptInRepetitionRecovery = $2.Recoverable = $2.InRuleRecoveryException = $2.IN_RULE_RECOVERY_EXCEPTION = $2.EOF_FOLLOW_KEY = void 0;
  var Ht = Ue(), de = k(), Ns = et2(), Is = Mr(), ks = ce();
  $2.EOF_FOLLOW_KEY = {};
  $2.IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException";
  function Kr(t3) {
    this.name = $2.IN_RULE_RECOVERY_EXCEPTION, this.message = t3;
  }
  $2.InRuleRecoveryException = Kr;
  Kr.prototype = Error.prototype;
  var Ps = function() {
    function t3() {
    }
    return t3.prototype.initRecoverable = function(e) {
      this.firstAfterRepMap = {}, this.resyncFollows = {}, this.recoveryEnabled = de.has(e, "recoveryEnabled") ? e.recoveryEnabled : ks.DEFAULT_PARSER_CONFIG.recoveryEnabled, this.recoveryEnabled && (this.attemptInRepetitionRecovery = Vi);
    }, t3.prototype.getTokenToInsert = function(e) {
      var r = Ht.createTokenInstance(e, "", NaN, NaN, NaN, NaN, NaN, NaN);
      return r.isInsertedInRecovery = true, r;
    }, t3.prototype.canTokenTypeBeInsertedInRecovery = function(e) {
      return true;
    }, t3.prototype.tryInRepetitionRecovery = function(e, r, n2, i) {
      for (var a2 = this, o = this.findReSyncTokenType(), s = this.exportLexerState(), c2 = [], f = false, p = this.LA(1), l2 = this.LA(1), m = function() {
        var v = a2.LA(0), u2 = a2.errorMessageProvider.buildMismatchTokenMessage({ expected: i, actual: p, previous: v, ruleName: a2.getCurrRuleFullName() }), d = new Ns.MismatchedTokenException(u2, p, a2.LA(0));
        d.resyncedTokens = de.dropRight(c2), a2.SAVE_ERROR(d);
      }; !f; ) if (this.tokenMatcher(l2, i)) {
        m();
        return;
      } else if (n2.call(this)) {
        m(), e.apply(this, r);
        return;
      } else this.tokenMatcher(l2, o) ? f = true : (l2 = this.SKIP_TOKEN(), this.addToResyncTokens(l2, c2));
      this.importLexerState(s);
    }, t3.prototype.shouldInRepetitionRecoveryBeTried = function(e, r, n2) {
      return !(n2 === false || e === void 0 || r === void 0 || this.tokenMatcher(this.LA(1), e) || this.isBackTracking() || this.canPerformInRuleRecovery(e, this.getFollowsForInRuleRecovery(e, r)));
    }, t3.prototype.getFollowsForInRuleRecovery = function(e, r) {
      var n2 = this.getCurrentGrammarPath(e, r), i = this.getNextPossibleTokenTypes(n2);
      return i;
    }, t3.prototype.tryInRuleRecovery = function(e, r) {
      if (this.canRecoverWithSingleTokenInsertion(e, r)) {
        var n2 = this.getTokenToInsert(e);
        return n2;
      }
      if (this.canRecoverWithSingleTokenDeletion(e)) {
        var i = this.SKIP_TOKEN();
        return this.consumeToken(), i;
      }
      throw new Kr("sad sad panda");
    }, t3.prototype.canPerformInRuleRecovery = function(e, r) {
      return this.canRecoverWithSingleTokenInsertion(e, r) || this.canRecoverWithSingleTokenDeletion(e);
    }, t3.prototype.canRecoverWithSingleTokenInsertion = function(e, r) {
      var n2 = this;
      if (!this.canTokenTypeBeInsertedInRecovery(e) || de.isEmpty(r)) return false;
      var i = this.LA(1), a2 = de.find(r, function(o) {
        return n2.tokenMatcher(i, o);
      }) !== void 0;
      return a2;
    }, t3.prototype.canRecoverWithSingleTokenDeletion = function(e) {
      var r = this.tokenMatcher(this.LA(2), e);
      return r;
    }, t3.prototype.isInCurrentRuleReSyncSet = function(e) {
      var r = this.getCurrFollowKey(), n2 = this.getFollowSetFromFollowKey(r);
      return de.contains(n2, e);
    }, t3.prototype.findReSyncTokenType = function() {
      for (var e = this.flattenFollowSet(), r = this.LA(1), n2 = 2; ; ) {
        var i = r.tokenType;
        if (de.contains(e, i)) return i;
        r = this.LA(n2), n2++;
      }
    }, t3.prototype.getCurrFollowKey = function() {
      if (this.RULE_STACK.length === 1) return $2.EOF_FOLLOW_KEY;
      var e = this.getLastExplicitRuleShortName(), r = this.getLastExplicitRuleOccurrenceIndex(), n2 = this.getPreviousExplicitRuleShortName();
      return { ruleName: this.shortRuleNameToFullName(e), idxInCallingRule: r, inRule: this.shortRuleNameToFullName(n2) };
    }, t3.prototype.buildFullFollowKeyStack = function() {
      var e = this, r = this.RULE_STACK, n2 = this.RULE_OCCURRENCE_STACK;
      return de.map(r, function(i, a2) {
        return a2 === 0 ? $2.EOF_FOLLOW_KEY : { ruleName: e.shortRuleNameToFullName(i), idxInCallingRule: n2[a2], inRule: e.shortRuleNameToFullName(r[a2 - 1]) };
      });
    }, t3.prototype.flattenFollowSet = function() {
      var e = this, r = de.map(this.buildFullFollowKeyStack(), function(n2) {
        return e.getFollowSetFromFollowKey(n2);
      });
      return de.flatten(r);
    }, t3.prototype.getFollowSetFromFollowKey = function(e) {
      if (e === $2.EOF_FOLLOW_KEY) return [Ht.EOF];
      var r = e.ruleName + e.idxInCallingRule + Is.IN + e.inRule;
      return this.resyncFollows[r];
    }, t3.prototype.addToResyncTokens = function(e, r) {
      return this.tokenMatcher(e, Ht.EOF) || r.push(e), r;
    }, t3.prototype.reSyncTo = function(e) {
      for (var r = [], n2 = this.LA(1); this.tokenMatcher(n2, e) === false; ) n2 = this.SKIP_TOKEN(), this.addToResyncTokens(n2, r);
      return de.dropRight(r);
    }, t3.prototype.attemptInRepetitionRecovery = function(e, r, n2, i, a2, o, s) {
    }, t3.prototype.getCurrentGrammarPath = function(e, r) {
      var n2 = this.getHumanReadableRuleStack(), i = de.cloneArr(this.RULE_OCCURRENCE_STACK), a2 = { ruleStack: n2, occurrenceStack: i, lastTok: e, lastTokOccurrence: r };
      return a2;
    }, t3.prototype.getHumanReadableRuleStack = function() {
      var e = this;
      return de.map(this.RULE_STACK, function(r) {
        return e.shortRuleNameToFullName(r);
      });
    }, t3;
  }();
  $2.Recoverable = Ps;
  function Vi(t3, e, r, n2, i, a2, o) {
    var s = this.getKeyForAutomaticLookahead(n2, i), c2 = this.firstAfterRepMap[s];
    if (c2 === void 0) {
      var f = this.getCurrRuleFullName(), p = this.getGAstProductions()[f], l2 = new a2(p, i);
      c2 = l2.startWalking(), this.firstAfterRepMap[s] = c2;
    }
    var m = c2.token, v = c2.occurrence, u2 = c2.isEndOfRule;
    this.RULE_STACK.length === 1 && u2 && m === void 0 && (m = Ht.EOF, v = 1), this.shouldInRepetitionRecoveryBeTried(m, v, o) && this.tryInRepetitionRecovery(t3, e, r, m);
  }
  $2.attemptInRepetitionRecovery = Vi;
});
var Yt = R2((P) => {
  "use strict";
  Object.defineProperty(P, "__esModule", { value: true });
  P.getKeyForAutomaticLookahead = P.AT_LEAST_ONE_SEP_IDX = P.MANY_SEP_IDX = P.AT_LEAST_ONE_IDX = P.MANY_IDX = P.OPTION_IDX = P.OR_IDX = P.BITS_FOR_ALT_IDX = P.BITS_FOR_RULE_IDX = P.BITS_FOR_OCCURRENCE_IDX = P.BITS_FOR_METHOD_TYPE = void 0;
  P.BITS_FOR_METHOD_TYPE = 4;
  P.BITS_FOR_OCCURRENCE_IDX = 8;
  P.BITS_FOR_RULE_IDX = 12;
  P.BITS_FOR_ALT_IDX = 8;
  P.OR_IDX = 1 << P.BITS_FOR_OCCURRENCE_IDX;
  P.OPTION_IDX = 2 << P.BITS_FOR_OCCURRENCE_IDX;
  P.MANY_IDX = 3 << P.BITS_FOR_OCCURRENCE_IDX;
  P.AT_LEAST_ONE_IDX = 4 << P.BITS_FOR_OCCURRENCE_IDX;
  P.MANY_SEP_IDX = 5 << P.BITS_FOR_OCCURRENCE_IDX;
  P.AT_LEAST_ONE_SEP_IDX = 6 << P.BITS_FOR_OCCURRENCE_IDX;
  function Ss(t3, e, r) {
    return r | e | t3;
  }
  P.getKeyForAutomaticLookahead = Ss;
  var ic = 32 - P.BITS_FOR_ALT_IDX;
});
var zi2 = R2((Xt) => {
  "use strict";
  Object.defineProperty(Xt, "__esModule", { value: true });
  Xt.LooksAhead = void 0;
  var be = yt2(), ge2 = k(), Ki = ce(), Fe = Yt(), Ve = vt(), xs = function() {
    function t3() {
    }
    return t3.prototype.initLooksAhead = function(e) {
      this.dynamicTokensEnabled = ge2.has(e, "dynamicTokensEnabled") ? e.dynamicTokensEnabled : Ki.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled, this.maxLookahead = ge2.has(e, "maxLookahead") ? e.maxLookahead : Ki.DEFAULT_PARSER_CONFIG.maxLookahead, this.lookAheadFuncsCache = ge2.isES2015MapSupported() ? /* @__PURE__ */ new Map() : [], ge2.isES2015MapSupported() ? (this.getLaFuncFromCache = this.getLaFuncFromMap, this.setLaFuncCache = this.setLaFuncCacheUsingMap) : (this.getLaFuncFromCache = this.getLaFuncFromObj, this.setLaFuncCache = this.setLaFuncUsingObj);
    }, t3.prototype.preComputeLookaheadFunctions = function(e) {
      var r = this;
      ge2.forEach(e, function(n2) {
        r.TRACE_INIT(n2.name + " Rule Lookahead", function() {
          var i = Ve.collectMethods(n2), a2 = i.alternation, o = i.repetition, s = i.option, c2 = i.repetitionMandatory, f = i.repetitionMandatoryWithSeparator, p = i.repetitionWithSeparator;
          ge2.forEach(a2, function(l2) {
            var m = l2.idx === 0 ? "" : l2.idx;
            r.TRACE_INIT("" + Ve.getProductionDslName(l2) + m, function() {
              var v = be.buildLookaheadFuncForOr(l2.idx, n2, l2.maxLookahead || r.maxLookahead, l2.hasPredicates, r.dynamicTokensEnabled, r.lookAheadBuilderForAlternatives), u2 = Fe.getKeyForAutomaticLookahead(r.fullRuleNameToShort[n2.name], Fe.OR_IDX, l2.idx);
              r.setLaFuncCache(u2, v);
            });
          }), ge2.forEach(o, function(l2) {
            r.computeLookaheadFunc(n2, l2.idx, Fe.MANY_IDX, be.PROD_TYPE.REPETITION, l2.maxLookahead, Ve.getProductionDslName(l2));
          }), ge2.forEach(s, function(l2) {
            r.computeLookaheadFunc(n2, l2.idx, Fe.OPTION_IDX, be.PROD_TYPE.OPTION, l2.maxLookahead, Ve.getProductionDslName(l2));
          }), ge2.forEach(c2, function(l2) {
            r.computeLookaheadFunc(n2, l2.idx, Fe.AT_LEAST_ONE_IDX, be.PROD_TYPE.REPETITION_MANDATORY, l2.maxLookahead, Ve.getProductionDslName(l2));
          }), ge2.forEach(f, function(l2) {
            r.computeLookaheadFunc(n2, l2.idx, Fe.AT_LEAST_ONE_SEP_IDX, be.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, l2.maxLookahead, Ve.getProductionDslName(l2));
          }), ge2.forEach(p, function(l2) {
            r.computeLookaheadFunc(n2, l2.idx, Fe.MANY_SEP_IDX, be.PROD_TYPE.REPETITION_WITH_SEPARATOR, l2.maxLookahead, Ve.getProductionDslName(l2));
          });
        });
      });
    }, t3.prototype.computeLookaheadFunc = function(e, r, n2, i, a2, o) {
      var s = this;
      this.TRACE_INIT("" + o + (r === 0 ? "" : r), function() {
        var c2 = be.buildLookaheadFuncForOptionalProd(r, e, a2 || s.maxLookahead, s.dynamicTokensEnabled, i, s.lookAheadBuilderForOptional), f = Fe.getKeyForAutomaticLookahead(s.fullRuleNameToShort[e.name], n2, r);
        s.setLaFuncCache(f, c2);
      });
    }, t3.prototype.lookAheadBuilderForOptional = function(e, r, n2) {
      return be.buildSingleAlternativeLookaheadFunction(e, r, n2);
    }, t3.prototype.lookAheadBuilderForAlternatives = function(e, r, n2, i) {
      return be.buildAlternativesLookAheadFunc(e, r, n2, i);
    }, t3.prototype.getKeyForAutomaticLookahead = function(e, r) {
      var n2 = this.getLastExplicitRuleShortName();
      return Fe.getKeyForAutomaticLookahead(n2, e, r);
    }, t3.prototype.getLaFuncFromCache = function(e) {
    }, t3.prototype.getLaFuncFromMap = function(e) {
      return this.lookAheadFuncsCache.get(e);
    }, t3.prototype.getLaFuncFromObj = function(e) {
      return this.lookAheadFuncsCache[e];
    }, t3.prototype.setLaFuncCache = function(e, r) {
    }, t3.prototype.setLaFuncCacheUsingMap = function(e, r) {
      this.lookAheadFuncsCache.set(e, r);
    }, t3.prototype.setLaFuncUsingObj = function(e, r) {
      this.lookAheadFuncsCache[e] = r;
    }, t3;
  }();
  Xt.LooksAhead = xs;
});
var Hi = R2((ke) => {
  "use strict";
  Object.defineProperty(ke, "__esModule", { value: true });
  ke.addNoneTerminalToCst = ke.addTerminalToCst = ke.setNodeLocationFull = ke.setNodeLocationOnlyOffset = void 0;
  function Cs(t3, e) {
    isNaN(t3.startOffset) === true ? (t3.startOffset = e.startOffset, t3.endOffset = e.endOffset) : t3.endOffset < e.endOffset && (t3.endOffset = e.endOffset);
  }
  ke.setNodeLocationOnlyOffset = Cs;
  function Ls(t3, e) {
    isNaN(t3.startOffset) === true ? (t3.startOffset = e.startOffset, t3.startColumn = e.startColumn, t3.startLine = e.startLine, t3.endOffset = e.endOffset, t3.endColumn = e.endColumn, t3.endLine = e.endLine) : t3.endOffset < e.endOffset && (t3.endOffset = e.endOffset, t3.endColumn = e.endColumn, t3.endLine = e.endLine);
  }
  ke.setNodeLocationFull = Ls;
  function Ms(t3, e, r) {
    t3.children[r] === void 0 ? t3.children[r] = [e] : t3.children[r].push(e);
  }
  ke.addTerminalToCst = Ms;
  function bs(t3, e, r) {
    t3.children[e] === void 0 ? t3.children[e] = [r] : t3.children[e].push(r);
  }
  ke.addNoneTerminalToCst = bs;
});
var Hr = R2((Be) => {
  "use strict";
  Object.defineProperty(Be, "__esModule", { value: true });
  Be.defineNameProp = Be.functionName = Be.classNameFromInstance = void 0;
  var Fs = k();
  function ws(t3) {
    return Yi(t3.constructor);
  }
  Be.classNameFromInstance = ws;
  var Xi = "name";
  function Yi(t3) {
    var e = t3.name;
    return e || "anonymous";
  }
  Be.functionName = Yi;
  function Ds(t3, e) {
    var r = Object.getOwnPropertyDescriptor(t3, Xi);
    return Fs.isUndefined(r) || r.configurable ? (Object.defineProperty(t3, Xi, { enumerable: false, configurable: true, writable: false, value: e }), true) : false;
  }
  Be.defineNameProp = Ds;
});
var ea = R2((Y) => {
  "use strict";
  Object.defineProperty(Y, "__esModule", { value: true });
  Y.validateRedundantMethods = Y.validateMissingCstMethods = Y.validateVisitor = Y.CstVisitorDefinitionError = Y.createBaseVisitorConstructorWithDefaults = Y.createBaseSemanticVisitorConstructor = Y.defaultVisit = void 0;
  var ve = k(), At = Hr();
  function $i(t3, e) {
    for (var r = ve.keys(t3), n2 = r.length, i = 0; i < n2; i++) for (var a2 = r[i], o = t3[a2], s = o.length, c2 = 0; c2 < s; c2++) {
      var f = o[c2];
      f.tokenTypeIdx === void 0 && this[f.name](f.children, e);
    }
  }
  Y.defaultVisit = $i;
  function Us(t3, e) {
    var r = function() {
    };
    At.defineNameProp(r, t3 + "BaseSemantics");
    var n2 = { visit: function(i, a2) {
      if (ve.isArray(i) && (i = i[0]), !ve.isUndefined(i)) return this[i.name](i.children, a2);
    }, validateVisitor: function() {
      var i = Zi(this, e);
      if (!ve.isEmpty(i)) {
        var a2 = ve.map(i, function(o) {
          return o.msg;
        });
        throw Error("Errors Detected in CST Visitor <" + At.functionName(this.constructor) + `>:
	` + ("" + a2.join(`

`).replace(/\n/g, `
	`)));
      }
    } };
    return r.prototype = n2, r.prototype.constructor = r, r._RULE_NAMES = e, r;
  }
  Y.createBaseSemanticVisitorConstructor = Us;
  function Gs(t3, e, r) {
    var n2 = function() {
    };
    At.defineNameProp(n2, t3 + "BaseSemanticsWithDefaults");
    var i = Object.create(r.prototype);
    return ve.forEach(e, function(a2) {
      i[a2] = $i;
    }), n2.prototype = i, n2.prototype.constructor = n2, n2;
  }
  Y.createBaseVisitorConstructorWithDefaults = Gs;
  var Yr;
  (function(t3) {
    t3[t3.REDUNDANT_METHOD = 0] = "REDUNDANT_METHOD", t3[t3.MISSING_METHOD = 1] = "MISSING_METHOD";
  })(Yr = Y.CstVisitorDefinitionError || (Y.CstVisitorDefinitionError = {}));
  function Zi(t3, e) {
    var r = Qi(t3, e), n2 = Ji(t3, e);
    return r.concat(n2);
  }
  Y.validateVisitor = Zi;
  function Qi(t3, e) {
    var r = ve.map(e, function(n2) {
      if (!ve.isFunction(t3[n2])) return { msg: "Missing visitor method: <" + n2 + "> on " + At.functionName(t3.constructor) + " CST Visitor.", type: Yr.MISSING_METHOD, methodName: n2 };
    });
    return ve.compact(r);
  }
  Y.validateMissingCstMethods = Qi;
  var Ws = ["constructor", "visit", "validateVisitor"];
  function Ji(t3, e) {
    var r = [];
    for (var n2 in t3) ve.isFunction(t3[n2]) && !ve.contains(Ws, n2) && !ve.contains(e, n2) && r.push({ msg: "Redundant visitor method: <" + n2 + "> on " + At.functionName(t3.constructor) + ` CST Visitor
There is no Grammar Rule corresponding to this method's name.
`, type: Yr.REDUNDANT_METHOD, methodName: n2 });
    return r;
  }
  Y.validateRedundantMethods = Ji;
});
var ra = R2(($t) => {
  "use strict";
  Object.defineProperty($t, "__esModule", { value: true });
  $t.TreeBuilder = void 0;
  var tt2 = Hi(), K = k(), ta = ea(), Bs = ce(), qs = function() {
    function t3() {
    }
    return t3.prototype.initTreeBuilder = function(e) {
      if (this.CST_STACK = [], this.outputCst = e.outputCst, this.nodeLocationTracking = K.has(e, "nodeLocationTracking") ? e.nodeLocationTracking : Bs.DEFAULT_PARSER_CONFIG.nodeLocationTracking, !this.outputCst) this.cstInvocationStateUpdate = K.NOOP, this.cstFinallyStateUpdate = K.NOOP, this.cstPostTerminal = K.NOOP, this.cstPostNonTerminal = K.NOOP, this.cstPostRule = K.NOOP;
      else if (/full/i.test(this.nodeLocationTracking)) this.recoveryEnabled ? (this.setNodeLocationFromToken = tt2.setNodeLocationFull, this.setNodeLocationFromNode = tt2.setNodeLocationFull, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery) : (this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = this.cstPostRuleFull, this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular);
      else if (/onlyOffset/i.test(this.nodeLocationTracking)) this.recoveryEnabled ? (this.setNodeLocationFromToken = tt2.setNodeLocationOnlyOffset, this.setNodeLocationFromNode = tt2.setNodeLocationOnlyOffset, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery) : (this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = this.cstPostRuleOnlyOffset, this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular);
      else if (/none/i.test(this.nodeLocationTracking)) this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = K.NOOP;
      else throw Error('Invalid <nodeLocationTracking> config option: "' + e.nodeLocationTracking + '"');
    }, t3.prototype.setInitialNodeLocationOnlyOffsetRecovery = function(e) {
      e.location = { startOffset: NaN, endOffset: NaN };
    }, t3.prototype.setInitialNodeLocationOnlyOffsetRegular = function(e) {
      e.location = { startOffset: this.LA(1).startOffset, endOffset: NaN };
    }, t3.prototype.setInitialNodeLocationFullRecovery = function(e) {
      e.location = { startOffset: NaN, startLine: NaN, startColumn: NaN, endOffset: NaN, endLine: NaN, endColumn: NaN };
    }, t3.prototype.setInitialNodeLocationFullRegular = function(e) {
      var r = this.LA(1);
      e.location = { startOffset: r.startOffset, startLine: r.startLine, startColumn: r.startColumn, endOffset: NaN, endLine: NaN, endColumn: NaN };
    }, t3.prototype.cstInvocationStateUpdate = function(e, r) {
      var n2 = { name: e, children: {} };
      this.setInitialNodeLocation(n2), this.CST_STACK.push(n2);
    }, t3.prototype.cstFinallyStateUpdate = function() {
      this.CST_STACK.pop();
    }, t3.prototype.cstPostRuleFull = function(e) {
      var r = this.LA(0), n2 = e.location;
      n2.startOffset <= r.startOffset ? (n2.endOffset = r.endOffset, n2.endLine = r.endLine, n2.endColumn = r.endColumn) : (n2.startOffset = NaN, n2.startLine = NaN, n2.startColumn = NaN);
    }, t3.prototype.cstPostRuleOnlyOffset = function(e) {
      var r = this.LA(0), n2 = e.location;
      n2.startOffset <= r.startOffset ? n2.endOffset = r.endOffset : n2.startOffset = NaN;
    }, t3.prototype.cstPostTerminal = function(e, r) {
      var n2 = this.CST_STACK[this.CST_STACK.length - 1];
      tt2.addTerminalToCst(n2, r, e), this.setNodeLocationFromToken(n2.location, r);
    }, t3.prototype.cstPostNonTerminal = function(e, r) {
      var n2 = this.CST_STACK[this.CST_STACK.length - 1];
      tt2.addNoneTerminalToCst(n2, r, e), this.setNodeLocationFromNode(n2.location, e.location);
    }, t3.prototype.getBaseCstVisitorConstructor = function() {
      if (K.isUndefined(this.baseCstVisitorConstructor)) {
        var e = ta.createBaseSemanticVisitorConstructor(this.className, K.keys(this.gastProductionsCache));
        return this.baseCstVisitorConstructor = e, e;
      }
      return this.baseCstVisitorConstructor;
    }, t3.prototype.getBaseCstVisitorConstructorWithDefaults = function() {
      if (K.isUndefined(this.baseCstVisitorWithDefaultsConstructor)) {
        var e = ta.createBaseVisitorConstructorWithDefaults(this.className, K.keys(this.gastProductionsCache), this.getBaseCstVisitorConstructor());
        return this.baseCstVisitorWithDefaultsConstructor = e, e;
      }
      return this.baseCstVisitorWithDefaultsConstructor;
    }, t3.prototype.getLastExplicitRuleShortName = function() {
      var e = this.RULE_STACK;
      return e[e.length - 1];
    }, t3.prototype.getPreviousExplicitRuleShortName = function() {
      var e = this.RULE_STACK;
      return e[e.length - 2];
    }, t3.prototype.getLastExplicitRuleOccurrenceIndex = function() {
      var e = this.RULE_OCCURRENCE_STACK;
      return e[e.length - 1];
    }, t3;
  }();
  $t.TreeBuilder = qs;
});
var ia = R2((Zt) => {
  "use strict";
  Object.defineProperty(Zt, "__esModule", { value: true });
  Zt.LexerAdapter = void 0;
  var na = ce(), js = function() {
    function t3() {
    }
    return t3.prototype.initLexerAdapter = function() {
      this.tokVector = [], this.tokVectorLength = 0, this.currIdx = -1;
    }, Object.defineProperty(t3.prototype, "input", { get: function() {
      return this.tokVector;
    }, set: function(e) {
      if (this.selfAnalysisDone !== true) throw Error("Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.");
      this.reset(), this.tokVector = e, this.tokVectorLength = e.length;
    }, enumerable: false, configurable: true }), t3.prototype.SKIP_TOKEN = function() {
      return this.currIdx <= this.tokVector.length - 2 ? (this.consumeToken(), this.LA(1)) : na.END_OF_FILE;
    }, t3.prototype.LA = function(e) {
      var r = this.currIdx + e;
      return r < 0 || this.tokVectorLength <= r ? na.END_OF_FILE : this.tokVector[r];
    }, t3.prototype.consumeToken = function() {
      this.currIdx++;
    }, t3.prototype.exportLexerState = function() {
      return this.currIdx;
    }, t3.prototype.importLexerState = function(e) {
      this.currIdx = e;
    }, t3.prototype.resetLexerState = function() {
      this.currIdx = -1;
    }, t3.prototype.moveToTerminatedState = function() {
      this.currIdx = this.tokVector.length - 1;
    }, t3.prototype.getLexerPosition = function() {
      return this.exportLexerState();
    }, t3;
  }();
  Zt.LexerAdapter = js;
});
var oa = R2((Qt) => {
  "use strict";
  Object.defineProperty(Qt, "__esModule", { value: true });
  Qt.RecognizerApi = void 0;
  var aa = k(), Vs = et2(), Xr = ce(), Ks = mt(), zs = jr(), Hs = ne(), Ys = function() {
    function t3() {
    }
    return t3.prototype.ACTION = function(e) {
      return e.call(this);
    }, t3.prototype.consume = function(e, r, n2) {
      return this.consumeInternal(r, e, n2);
    }, t3.prototype.subrule = function(e, r, n2) {
      return this.subruleInternal(r, e, n2);
    }, t3.prototype.option = function(e, r) {
      return this.optionInternal(r, e);
    }, t3.prototype.or = function(e, r) {
      return this.orInternal(r, e);
    }, t3.prototype.many = function(e, r) {
      return this.manyInternal(e, r);
    }, t3.prototype.atLeastOne = function(e, r) {
      return this.atLeastOneInternal(e, r);
    }, t3.prototype.CONSUME = function(e, r) {
      return this.consumeInternal(e, 0, r);
    }, t3.prototype.CONSUME1 = function(e, r) {
      return this.consumeInternal(e, 1, r);
    }, t3.prototype.CONSUME2 = function(e, r) {
      return this.consumeInternal(e, 2, r);
    }, t3.prototype.CONSUME3 = function(e, r) {
      return this.consumeInternal(e, 3, r);
    }, t3.prototype.CONSUME4 = function(e, r) {
      return this.consumeInternal(e, 4, r);
    }, t3.prototype.CONSUME5 = function(e, r) {
      return this.consumeInternal(e, 5, r);
    }, t3.prototype.CONSUME6 = function(e, r) {
      return this.consumeInternal(e, 6, r);
    }, t3.prototype.CONSUME7 = function(e, r) {
      return this.consumeInternal(e, 7, r);
    }, t3.prototype.CONSUME8 = function(e, r) {
      return this.consumeInternal(e, 8, r);
    }, t3.prototype.CONSUME9 = function(e, r) {
      return this.consumeInternal(e, 9, r);
    }, t3.prototype.SUBRULE = function(e, r) {
      return this.subruleInternal(e, 0, r);
    }, t3.prototype.SUBRULE1 = function(e, r) {
      return this.subruleInternal(e, 1, r);
    }, t3.prototype.SUBRULE2 = function(e, r) {
      return this.subruleInternal(e, 2, r);
    }, t3.prototype.SUBRULE3 = function(e, r) {
      return this.subruleInternal(e, 3, r);
    }, t3.prototype.SUBRULE4 = function(e, r) {
      return this.subruleInternal(e, 4, r);
    }, t3.prototype.SUBRULE5 = function(e, r) {
      return this.subruleInternal(e, 5, r);
    }, t3.prototype.SUBRULE6 = function(e, r) {
      return this.subruleInternal(e, 6, r);
    }, t3.prototype.SUBRULE7 = function(e, r) {
      return this.subruleInternal(e, 7, r);
    }, t3.prototype.SUBRULE8 = function(e, r) {
      return this.subruleInternal(e, 8, r);
    }, t3.prototype.SUBRULE9 = function(e, r) {
      return this.subruleInternal(e, 9, r);
    }, t3.prototype.OPTION = function(e) {
      return this.optionInternal(e, 0);
    }, t3.prototype.OPTION1 = function(e) {
      return this.optionInternal(e, 1);
    }, t3.prototype.OPTION2 = function(e) {
      return this.optionInternal(e, 2);
    }, t3.prototype.OPTION3 = function(e) {
      return this.optionInternal(e, 3);
    }, t3.prototype.OPTION4 = function(e) {
      return this.optionInternal(e, 4);
    }, t3.prototype.OPTION5 = function(e) {
      return this.optionInternal(e, 5);
    }, t3.prototype.OPTION6 = function(e) {
      return this.optionInternal(e, 6);
    }, t3.prototype.OPTION7 = function(e) {
      return this.optionInternal(e, 7);
    }, t3.prototype.OPTION8 = function(e) {
      return this.optionInternal(e, 8);
    }, t3.prototype.OPTION9 = function(e) {
      return this.optionInternal(e, 9);
    }, t3.prototype.OR = function(e) {
      return this.orInternal(e, 0);
    }, t3.prototype.OR1 = function(e) {
      return this.orInternal(e, 1);
    }, t3.prototype.OR2 = function(e) {
      return this.orInternal(e, 2);
    }, t3.prototype.OR3 = function(e) {
      return this.orInternal(e, 3);
    }, t3.prototype.OR4 = function(e) {
      return this.orInternal(e, 4);
    }, t3.prototype.OR5 = function(e) {
      return this.orInternal(e, 5);
    }, t3.prototype.OR6 = function(e) {
      return this.orInternal(e, 6);
    }, t3.prototype.OR7 = function(e) {
      return this.orInternal(e, 7);
    }, t3.prototype.OR8 = function(e) {
      return this.orInternal(e, 8);
    }, t3.prototype.OR9 = function(e) {
      return this.orInternal(e, 9);
    }, t3.prototype.MANY = function(e) {
      this.manyInternal(0, e);
    }, t3.prototype.MANY1 = function(e) {
      this.manyInternal(1, e);
    }, t3.prototype.MANY2 = function(e) {
      this.manyInternal(2, e);
    }, t3.prototype.MANY3 = function(e) {
      this.manyInternal(3, e);
    }, t3.prototype.MANY4 = function(e) {
      this.manyInternal(4, e);
    }, t3.prototype.MANY5 = function(e) {
      this.manyInternal(5, e);
    }, t3.prototype.MANY6 = function(e) {
      this.manyInternal(6, e);
    }, t3.prototype.MANY7 = function(e) {
      this.manyInternal(7, e);
    }, t3.prototype.MANY8 = function(e) {
      this.manyInternal(8, e);
    }, t3.prototype.MANY9 = function(e) {
      this.manyInternal(9, e);
    }, t3.prototype.MANY_SEP = function(e) {
      this.manySepFirstInternal(0, e);
    }, t3.prototype.MANY_SEP1 = function(e) {
      this.manySepFirstInternal(1, e);
    }, t3.prototype.MANY_SEP2 = function(e) {
      this.manySepFirstInternal(2, e);
    }, t3.prototype.MANY_SEP3 = function(e) {
      this.manySepFirstInternal(3, e);
    }, t3.prototype.MANY_SEP4 = function(e) {
      this.manySepFirstInternal(4, e);
    }, t3.prototype.MANY_SEP5 = function(e) {
      this.manySepFirstInternal(5, e);
    }, t3.prototype.MANY_SEP6 = function(e) {
      this.manySepFirstInternal(6, e);
    }, t3.prototype.MANY_SEP7 = function(e) {
      this.manySepFirstInternal(7, e);
    }, t3.prototype.MANY_SEP8 = function(e) {
      this.manySepFirstInternal(8, e);
    }, t3.prototype.MANY_SEP9 = function(e) {
      this.manySepFirstInternal(9, e);
    }, t3.prototype.AT_LEAST_ONE = function(e) {
      this.atLeastOneInternal(0, e);
    }, t3.prototype.AT_LEAST_ONE1 = function(e) {
      return this.atLeastOneInternal(1, e);
    }, t3.prototype.AT_LEAST_ONE2 = function(e) {
      this.atLeastOneInternal(2, e);
    }, t3.prototype.AT_LEAST_ONE3 = function(e) {
      this.atLeastOneInternal(3, e);
    }, t3.prototype.AT_LEAST_ONE4 = function(e) {
      this.atLeastOneInternal(4, e);
    }, t3.prototype.AT_LEAST_ONE5 = function(e) {
      this.atLeastOneInternal(5, e);
    }, t3.prototype.AT_LEAST_ONE6 = function(e) {
      this.atLeastOneInternal(6, e);
    }, t3.prototype.AT_LEAST_ONE7 = function(e) {
      this.atLeastOneInternal(7, e);
    }, t3.prototype.AT_LEAST_ONE8 = function(e) {
      this.atLeastOneInternal(8, e);
    }, t3.prototype.AT_LEAST_ONE9 = function(e) {
      this.atLeastOneInternal(9, e);
    }, t3.prototype.AT_LEAST_ONE_SEP = function(e) {
      this.atLeastOneSepFirstInternal(0, e);
    }, t3.prototype.AT_LEAST_ONE_SEP1 = function(e) {
      this.atLeastOneSepFirstInternal(1, e);
    }, t3.prototype.AT_LEAST_ONE_SEP2 = function(e) {
      this.atLeastOneSepFirstInternal(2, e);
    }, t3.prototype.AT_LEAST_ONE_SEP3 = function(e) {
      this.atLeastOneSepFirstInternal(3, e);
    }, t3.prototype.AT_LEAST_ONE_SEP4 = function(e) {
      this.atLeastOneSepFirstInternal(4, e);
    }, t3.prototype.AT_LEAST_ONE_SEP5 = function(e) {
      this.atLeastOneSepFirstInternal(5, e);
    }, t3.prototype.AT_LEAST_ONE_SEP6 = function(e) {
      this.atLeastOneSepFirstInternal(6, e);
    }, t3.prototype.AT_LEAST_ONE_SEP7 = function(e) {
      this.atLeastOneSepFirstInternal(7, e);
    }, t3.prototype.AT_LEAST_ONE_SEP8 = function(e) {
      this.atLeastOneSepFirstInternal(8, e);
    }, t3.prototype.AT_LEAST_ONE_SEP9 = function(e) {
      this.atLeastOneSepFirstInternal(9, e);
    }, t3.prototype.RULE = function(e, r, n2) {
      if (n2 === void 0 && (n2 = Xr.DEFAULT_RULE_CONFIG), aa.contains(this.definedRulesNames, e)) {
        var i = Ks.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ topLevelRule: e, grammarName: this.className }), a2 = { message: i, type: Xr.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: e };
        this.definitionErrors.push(a2);
      }
      this.definedRulesNames.push(e);
      var o = this.defineRule(e, r, n2);
      return this[e] = o, o;
    }, t3.prototype.OVERRIDE_RULE = function(e, r, n2) {
      n2 === void 0 && (n2 = Xr.DEFAULT_RULE_CONFIG);
      var i = [];
      i = i.concat(zs.validateRuleIsOverridden(e, this.definedRulesNames, this.className)), this.definitionErrors = this.definitionErrors.concat(i);
      var a2 = this.defineRule(e, r, n2);
      return this[e] = a2, a2;
    }, t3.prototype.BACKTRACK = function(e, r) {
      return function() {
        this.isBackTrackingStack.push(1);
        var n2 = this.saveRecogState();
        try {
          return e.apply(this, r), true;
        } catch (i) {
          if (Vs.isRecognitionException(i)) return false;
          throw i;
        } finally {
          this.reloadRecogState(n2), this.isBackTrackingStack.pop();
        }
      };
    }, t3.prototype.getGAstProductions = function() {
      return this.gastProductionsCache;
    }, t3.prototype.getSerializedGastProductions = function() {
      return Hs.serializeGrammar(aa.values(this.gastProductionsCache));
    }, t3;
  }();
  Qt.RecognizerApi = Ys;
});
var la = R2((Jt) => {
  "use strict";
  Object.defineProperty(Jt, "__esModule", { value: true });
  Jt.RecognizerEngine = void 0;
  var q2 = k(), le = Yt(), er = et2(), sa = yt2(), rt = Tt(), ua = ce(), Xs = zr(), ca = Ue(), Rt = Xe(), $s = Hr(), Zs = function() {
    function t3() {
    }
    return t3.prototype.initRecognizerEngine = function(e, r) {
      if (this.className = $s.classNameFromInstance(this), this.shortRuleNameToFull = {}, this.fullRuleNameToShort = {}, this.ruleShortNameIdx = 256, this.tokenMatcher = Rt.tokenStructuredMatcherNoCategories, this.definedRulesNames = [], this.tokensMap = {}, this.isBackTrackingStack = [], this.RULE_STACK = [], this.RULE_OCCURRENCE_STACK = [], this.gastProductionsCache = {}, q2.has(r, "serializedGrammar")) throw Error(`The Parser's configuration can no longer contain a <serializedGrammar> property.
	See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0
	For Further details.`);
      if (q2.isArray(e)) {
        if (q2.isEmpty(e)) throw Error(`A Token Vocabulary cannot be empty.
	Note that the first argument for the parser constructor
	is no longer a Token vector (since v4.0).`);
        if (typeof e[0].startOffset == "number") throw Error(`The Parser constructor no longer accepts a token vector as the first argument.
	See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0
	For Further details.`);
      }
      if (q2.isArray(e)) this.tokensMap = q2.reduce(e, function(o, s) {
        return o[s.name] = s, o;
      }, {});
      else if (q2.has(e, "modes") && q2.every(q2.flatten(q2.values(e.modes)), Rt.isTokenType)) {
        var n2 = q2.flatten(q2.values(e.modes)), i = q2.uniq(n2);
        this.tokensMap = q2.reduce(i, function(o, s) {
          return o[s.name] = s, o;
        }, {});
      } else if (q2.isObject(e)) this.tokensMap = q2.cloneObj(e);
      else throw new Error("<tokensDictionary> argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");
      this.tokensMap.EOF = ca.EOF;
      var a2 = q2.every(q2.values(e), function(o) {
        return q2.isEmpty(o.categoryMatches);
      });
      this.tokenMatcher = a2 ? Rt.tokenStructuredMatcherNoCategories : Rt.tokenStructuredMatcher, Rt.augmentTokenTypes(q2.values(this.tokensMap));
    }, t3.prototype.defineRule = function(e, r, n2) {
      if (this.selfAnalysisDone) throw Error("Grammar rule <" + e + `> may not be defined after the 'performSelfAnalysis' method has been called'
Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);
      var i = q2.has(n2, "resyncEnabled") ? n2.resyncEnabled : ua.DEFAULT_RULE_CONFIG.resyncEnabled, a2 = q2.has(n2, "recoveryValueFunc") ? n2.recoveryValueFunc : ua.DEFAULT_RULE_CONFIG.recoveryValueFunc, o = this.ruleShortNameIdx << le.BITS_FOR_METHOD_TYPE + le.BITS_FOR_OCCURRENCE_IDX;
      this.ruleShortNameIdx++, this.shortRuleNameToFull[o] = e, this.fullRuleNameToShort[e] = o;
      function s(p) {
        try {
          if (this.outputCst === true) {
            r.apply(this, p);
            var l2 = this.CST_STACK[this.CST_STACK.length - 1];
            return this.cstPostRule(l2), l2;
          } else return r.apply(this, p);
        } catch (m) {
          return this.invokeRuleCatch(m, i, a2);
        } finally {
          this.ruleFinallyStateUpdate();
        }
      }
      var c2 = function(p, l2) {
        return p === void 0 && (p = 0), this.ruleInvocationStateUpdate(o, e, p), s.call(this, l2);
      }, f = "ruleName";
      return c2[f] = e, c2.originalGrammarAction = r, c2;
    }, t3.prototype.invokeRuleCatch = function(e, r, n2) {
      var i = this.RULE_STACK.length === 1, a2 = r && !this.isBackTracking() && this.recoveryEnabled;
      if (er.isRecognitionException(e)) {
        var o = e;
        if (a2) {
          var s = this.findReSyncTokenType();
          if (this.isInCurrentRuleReSyncSet(s)) if (o.resyncedTokens = this.reSyncTo(s), this.outputCst) {
            var c2 = this.CST_STACK[this.CST_STACK.length - 1];
            return c2.recoveredNode = true, c2;
          } else return n2();
          else {
            if (this.outputCst) {
              var c2 = this.CST_STACK[this.CST_STACK.length - 1];
              c2.recoveredNode = true, o.partialCstResult = c2;
            }
            throw o;
          }
        } else {
          if (i) return this.moveToTerminatedState(), n2();
          throw o;
        }
      } else throw e;
    }, t3.prototype.optionInternal = function(e, r) {
      var n2 = this.getKeyForAutomaticLookahead(le.OPTION_IDX, r);
      return this.optionInternalLogic(e, r, n2);
    }, t3.prototype.optionInternalLogic = function(e, r, n2) {
      var i = this, a2 = this.getLaFuncFromCache(n2), o, s;
      if (e.DEF !== void 0) {
        if (o = e.DEF, s = e.GATE, s !== void 0) {
          var c2 = a2;
          a2 = function() {
            return s.call(i) && c2.call(i);
          };
        }
      } else o = e;
      if (a2.call(this) === true) return o.call(this);
    }, t3.prototype.atLeastOneInternal = function(e, r) {
      var n2 = this.getKeyForAutomaticLookahead(le.AT_LEAST_ONE_IDX, e);
      return this.atLeastOneInternalLogic(e, r, n2);
    }, t3.prototype.atLeastOneInternalLogic = function(e, r, n2) {
      var i = this, a2 = this.getLaFuncFromCache(n2), o, s;
      if (r.DEF !== void 0) {
        if (o = r.DEF, s = r.GATE, s !== void 0) {
          var c2 = a2;
          a2 = function() {
            return s.call(i) && c2.call(i);
          };
        }
      } else o = r;
      if (a2.call(this) === true) for (var f = this.doSingleRepetition(o); a2.call(this) === true && f === true; ) f = this.doSingleRepetition(o);
      else throw this.raiseEarlyExitException(e, sa.PROD_TYPE.REPETITION_MANDATORY, r.ERR_MSG);
      this.attemptInRepetitionRecovery(this.atLeastOneInternal, [e, r], a2, le.AT_LEAST_ONE_IDX, e, rt.NextTerminalAfterAtLeastOneWalker);
    }, t3.prototype.atLeastOneSepFirstInternal = function(e, r) {
      var n2 = this.getKeyForAutomaticLookahead(le.AT_LEAST_ONE_SEP_IDX, e);
      this.atLeastOneSepFirstInternalLogic(e, r, n2);
    }, t3.prototype.atLeastOneSepFirstInternalLogic = function(e, r, n2) {
      var i = this, a2 = r.DEF, o = r.SEP, s = this.getLaFuncFromCache(n2);
      if (s.call(this) === true) {
        a2.call(this);
        for (var c2 = function() {
          return i.tokenMatcher(i.LA(1), o);
        }; this.tokenMatcher(this.LA(1), o) === true; ) this.CONSUME(o), a2.call(this);
        this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, o, c2, a2, rt.NextTerminalAfterAtLeastOneSepWalker], c2, le.AT_LEAST_ONE_SEP_IDX, e, rt.NextTerminalAfterAtLeastOneSepWalker);
      } else throw this.raiseEarlyExitException(e, sa.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, r.ERR_MSG);
    }, t3.prototype.manyInternal = function(e, r) {
      var n2 = this.getKeyForAutomaticLookahead(le.MANY_IDX, e);
      return this.manyInternalLogic(e, r, n2);
    }, t3.prototype.manyInternalLogic = function(e, r, n2) {
      var i = this, a2 = this.getLaFuncFromCache(n2), o, s;
      if (r.DEF !== void 0) {
        if (o = r.DEF, s = r.GATE, s !== void 0) {
          var c2 = a2;
          a2 = function() {
            return s.call(i) && c2.call(i);
          };
        }
      } else o = r;
      for (var f = true; a2.call(this) === true && f === true; ) f = this.doSingleRepetition(o);
      this.attemptInRepetitionRecovery(this.manyInternal, [e, r], a2, le.MANY_IDX, e, rt.NextTerminalAfterManyWalker, f);
    }, t3.prototype.manySepFirstInternal = function(e, r) {
      var n2 = this.getKeyForAutomaticLookahead(le.MANY_SEP_IDX, e);
      this.manySepFirstInternalLogic(e, r, n2);
    }, t3.prototype.manySepFirstInternalLogic = function(e, r, n2) {
      var i = this, a2 = r.DEF, o = r.SEP, s = this.getLaFuncFromCache(n2);
      if (s.call(this) === true) {
        a2.call(this);
        for (var c2 = function() {
          return i.tokenMatcher(i.LA(1), o);
        }; this.tokenMatcher(this.LA(1), o) === true; ) this.CONSUME(o), a2.call(this);
        this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, o, c2, a2, rt.NextTerminalAfterManySepWalker], c2, le.MANY_SEP_IDX, e, rt.NextTerminalAfterManySepWalker);
      }
    }, t3.prototype.repetitionSepSecondInternal = function(e, r, n2, i, a2) {
      for (; n2(); ) this.CONSUME(r), i.call(this);
      this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, r, n2, i, a2], n2, le.AT_LEAST_ONE_SEP_IDX, e, a2);
    }, t3.prototype.doSingleRepetition = function(e) {
      var r = this.getLexerPosition();
      e.call(this);
      var n2 = this.getLexerPosition();
      return n2 > r;
    }, t3.prototype.orInternal = function(e, r) {
      var n2 = this.getKeyForAutomaticLookahead(le.OR_IDX, r), i = q2.isArray(e) ? e : e.DEF, a2 = this.getLaFuncFromCache(n2), o = a2.call(this, i);
      if (o !== void 0) {
        var s = i[o];
        return s.ALT.call(this);
      }
      this.raiseNoAltException(r, e.ERR_MSG);
    }, t3.prototype.ruleFinallyStateUpdate = function() {
      if (this.RULE_STACK.pop(), this.RULE_OCCURRENCE_STACK.pop(), this.cstFinallyStateUpdate(), this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) {
        var e = this.LA(1), r = this.errorMessageProvider.buildNotAllInputParsedMessage({ firstRedundant: e, ruleName: this.getCurrRuleFullName() });
        this.SAVE_ERROR(new er.NotAllInputParsedException(r, e));
      }
    }, t3.prototype.subruleInternal = function(e, r, n2) {
      var i;
      try {
        var a2 = n2 !== void 0 ? n2.ARGS : void 0;
        return i = e.call(this, r, a2), this.cstPostNonTerminal(i, n2 !== void 0 && n2.LABEL !== void 0 ? n2.LABEL : e.ruleName), i;
      } catch (o) {
        this.subruleInternalError(o, n2, e.ruleName);
      }
    }, t3.prototype.subruleInternalError = function(e, r, n2) {
      throw er.isRecognitionException(e) && e.partialCstResult !== void 0 && (this.cstPostNonTerminal(e.partialCstResult, r !== void 0 && r.LABEL !== void 0 ? r.LABEL : n2), delete e.partialCstResult), e;
    }, t3.prototype.consumeInternal = function(e, r, n2) {
      var i;
      try {
        var a2 = this.LA(1);
        this.tokenMatcher(a2, e) === true ? (this.consumeToken(), i = a2) : this.consumeInternalError(e, a2, n2);
      } catch (o) {
        i = this.consumeInternalRecovery(e, r, o);
      }
      return this.cstPostTerminal(n2 !== void 0 && n2.LABEL !== void 0 ? n2.LABEL : e.name, i), i;
    }, t3.prototype.consumeInternalError = function(e, r, n2) {
      var i, a2 = this.LA(0);
      throw n2 !== void 0 && n2.ERR_MSG ? i = n2.ERR_MSG : i = this.errorMessageProvider.buildMismatchTokenMessage({ expected: e, actual: r, previous: a2, ruleName: this.getCurrRuleFullName() }), this.SAVE_ERROR(new er.MismatchedTokenException(i, r, a2));
    }, t3.prototype.consumeInternalRecovery = function(e, r, n2) {
      if (this.recoveryEnabled && n2.name === "MismatchedTokenException" && !this.isBackTracking()) {
        var i = this.getFollowsForInRuleRecovery(e, r);
        try {
          return this.tryInRuleRecovery(e, i);
        } catch (a2) {
          throw a2.name === Xs.IN_RULE_RECOVERY_EXCEPTION ? n2 : a2;
        }
      } else throw n2;
    }, t3.prototype.saveRecogState = function() {
      var e = this.errors, r = q2.cloneArr(this.RULE_STACK);
      return { errors: e, lexerState: this.exportLexerState(), RULE_STACK: r, CST_STACK: this.CST_STACK };
    }, t3.prototype.reloadRecogState = function(e) {
      this.errors = e.errors, this.importLexerState(e.lexerState), this.RULE_STACK = e.RULE_STACK;
    }, t3.prototype.ruleInvocationStateUpdate = function(e, r, n2) {
      this.RULE_OCCURRENCE_STACK.push(n2), this.RULE_STACK.push(e), this.cstInvocationStateUpdate(r, e);
    }, t3.prototype.isBackTracking = function() {
      return this.isBackTrackingStack.length !== 0;
    }, t3.prototype.getCurrRuleFullName = function() {
      var e = this.getLastExplicitRuleShortName();
      return this.shortRuleNameToFull[e];
    }, t3.prototype.shortRuleNameToFullName = function(e) {
      return this.shortRuleNameToFull[e];
    }, t3.prototype.isAtEndOfInput = function() {
      return this.tokenMatcher(this.LA(1), ca.EOF);
    }, t3.prototype.reset = function() {
      this.resetLexerState(), this.isBackTrackingStack = [], this.errors = [], this.RULE_STACK = [], this.CST_STACK = [], this.RULE_OCCURRENCE_STACK = [];
    }, t3;
  }();
  Jt.RecognizerEngine = Zs;
});
var pa = R2((tr) => {
  "use strict";
  Object.defineProperty(tr, "__esModule", { value: true });
  tr.ErrorHandler = void 0;
  var $r = et2(), Zr = k(), fa = yt2(), Qs = ce(), Js = function() {
    function t3() {
    }
    return t3.prototype.initErrorHandler = function(e) {
      this._errors = [], this.errorMessageProvider = Zr.has(e, "errorMessageProvider") ? e.errorMessageProvider : Qs.DEFAULT_PARSER_CONFIG.errorMessageProvider;
    }, t3.prototype.SAVE_ERROR = function(e) {
      if ($r.isRecognitionException(e)) return e.context = { ruleStack: this.getHumanReadableRuleStack(), ruleOccurrenceStack: Zr.cloneArr(this.RULE_OCCURRENCE_STACK) }, this._errors.push(e), e;
      throw Error("Trying to save an Error which is not a RecognitionException");
    }, Object.defineProperty(t3.prototype, "errors", { get: function() {
      return Zr.cloneArr(this._errors);
    }, set: function(e) {
      this._errors = e;
    }, enumerable: false, configurable: true }), t3.prototype.raiseEarlyExitException = function(e, r, n2) {
      for (var i = this.getCurrRuleFullName(), a2 = this.getGAstProductions()[i], o = fa.getLookaheadPathsForOptionalProd(e, a2, r, this.maxLookahead), s = o[0], c2 = [], f = 1; f <= this.maxLookahead; f++) c2.push(this.LA(f));
      var p = this.errorMessageProvider.buildEarlyExitMessage({ expectedIterationPaths: s, actual: c2, previous: this.LA(0), customUserDescription: n2, ruleName: i });
      throw this.SAVE_ERROR(new $r.EarlyExitException(p, this.LA(1), this.LA(0)));
    }, t3.prototype.raiseNoAltException = function(e, r) {
      for (var n2 = this.getCurrRuleFullName(), i = this.getGAstProductions()[n2], a2 = fa.getLookaheadPathsForOr(e, i, this.maxLookahead), o = [], s = 1; s <= this.maxLookahead; s++) o.push(this.LA(s));
      var c2 = this.LA(0), f = this.errorMessageProvider.buildNoViableAltMessage({ expectedPathsPerAlt: a2, actual: o, previous: c2, customUserDescription: r, ruleName: this.getCurrRuleFullName() });
      throw this.SAVE_ERROR(new $r.NoViableAltException(f, this.LA(1), c2));
    }, t3;
  }();
  tr.ErrorHandler = Js;
});
var va = R2((rr) => {
  "use strict";
  Object.defineProperty(rr, "__esModule", { value: true });
  rr.ContentAssist = void 0;
  var ha = Tt(), da = k(), eu = function() {
    function t3() {
    }
    return t3.prototype.initContentAssist = function() {
    }, t3.prototype.computeContentAssist = function(e, r) {
      var n2 = this.gastProductionsCache[e];
      if (da.isUndefined(n2)) throw Error("Rule ->" + e + "<- does not exist in this grammar.");
      return ha.nextPossibleTokensAfter([n2], r, this.tokenMatcher, this.maxLookahead);
    }, t3.prototype.getNextPossibleTokenTypes = function(e) {
      var r = da.first(e.ruleStack), n2 = this.getGAstProductions(), i = n2[r], a2 = new ha.NextAfterTokenWalker(i, e).startWalking();
      return a2;
    }, t3;
  }();
  rr.ContentAssist = eu;
});
var Ra = R2((nr) => {
  "use strict";
  Object.defineProperty(nr, "__esModule", { value: true });
  nr.GastRecorder = void 0;
  var oe = k(), Pe = ne(), tu = ft(), ma = Xe(), Ea = Ue(), ru = ce(), nu = Yt(), ir = { description: "This Object indicates the Parser is during Recording Phase" };
  Object.freeze(ir);
  var Ta = true, ya = Math.pow(2, nu.BITS_FOR_OCCURRENCE_IDX) - 1, _a3 = Ea.createToken({ name: "RECORDING_PHASE_TOKEN", pattern: tu.Lexer.NA });
  ma.augmentTokenTypes([_a3]);
  var ga = Ea.createTokenInstance(_a3, `This IToken indicates the Parser is in Recording Phase
	See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`, -1, -1, -1, -1, -1, -1);
  Object.freeze(ga);
  var iu = { name: `This CSTNode indicates the Parser is in Recording Phase
	See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`, children: {} }, ou = function() {
    function t3() {
    }
    return t3.prototype.initGastRecorder = function(e) {
      this.recordingProdStack = [], this.RECORDING_PHASE = false;
    }, t3.prototype.enableRecording = function() {
      var e = this;
      this.RECORDING_PHASE = true, this.TRACE_INIT("Enable Recording", function() {
        for (var r = function(i) {
          var a2 = i > 0 ? i : "";
          e["CONSUME" + a2] = function(o, s) {
            return this.consumeInternalRecord(o, i, s);
          }, e["SUBRULE" + a2] = function(o, s) {
            return this.subruleInternalRecord(o, i, s);
          }, e["OPTION" + a2] = function(o) {
            return this.optionInternalRecord(o, i);
          }, e["OR" + a2] = function(o) {
            return this.orInternalRecord(o, i);
          }, e["MANY" + a2] = function(o) {
            this.manyInternalRecord(i, o);
          }, e["MANY_SEP" + a2] = function(o) {
            this.manySepFirstInternalRecord(i, o);
          }, e["AT_LEAST_ONE" + a2] = function(o) {
            this.atLeastOneInternalRecord(i, o);
          }, e["AT_LEAST_ONE_SEP" + a2] = function(o) {
            this.atLeastOneSepFirstInternalRecord(i, o);
          };
        }, n2 = 0; n2 < 10; n2++) r(n2);
        e.consume = function(i, a2, o) {
          return this.consumeInternalRecord(a2, i, o);
        }, e.subrule = function(i, a2, o) {
          return this.subruleInternalRecord(a2, i, o);
        }, e.option = function(i, a2) {
          return this.optionInternalRecord(a2, i);
        }, e.or = function(i, a2) {
          return this.orInternalRecord(a2, i);
        }, e.many = function(i, a2) {
          this.manyInternalRecord(i, a2);
        }, e.atLeastOne = function(i, a2) {
          this.atLeastOneInternalRecord(i, a2);
        }, e.ACTION = e.ACTION_RECORD, e.BACKTRACK = e.BACKTRACK_RECORD, e.LA = e.LA_RECORD;
      });
    }, t3.prototype.disableRecording = function() {
      var e = this;
      this.RECORDING_PHASE = false, this.TRACE_INIT("Deleting Recording methods", function() {
        for (var r = 0; r < 10; r++) {
          var n2 = r > 0 ? r : "";
          delete e["CONSUME" + n2], delete e["SUBRULE" + n2], delete e["OPTION" + n2], delete e["OR" + n2], delete e["MANY" + n2], delete e["MANY_SEP" + n2], delete e["AT_LEAST_ONE" + n2], delete e["AT_LEAST_ONE_SEP" + n2];
        }
        delete e.consume, delete e.subrule, delete e.option, delete e.or, delete e.many, delete e.atLeastOne, delete e.ACTION, delete e.BACKTRACK, delete e.LA;
      });
    }, t3.prototype.ACTION_RECORD = function(e) {
    }, t3.prototype.BACKTRACK_RECORD = function(e, r) {
      return function() {
        return true;
      };
    }, t3.prototype.LA_RECORD = function(e) {
      return ru.END_OF_FILE;
    }, t3.prototype.topLevelRuleRecord = function(e, r) {
      try {
        var n2 = new Pe.Rule({ definition: [], name: e });
        return n2.name = e, this.recordingProdStack.push(n2), r.call(this), this.recordingProdStack.pop(), n2;
      } catch (i) {
        if (i.KNOWN_RECORDER_ERROR !== true) try {
          i.message = i.message + `
	 This error was thrown during the "grammar recording phase" For more info see:
	https://chevrotain.io/docs/guide/internals.html#grammar-recording`;
        } catch (a2) {
          throw i;
        }
        throw i;
      }
    }, t3.prototype.optionInternalRecord = function(e, r) {
      return Ot.call(this, Pe.Option, e, r);
    }, t3.prototype.atLeastOneInternalRecord = function(e, r) {
      Ot.call(this, Pe.RepetitionMandatory, r, e);
    }, t3.prototype.atLeastOneSepFirstInternalRecord = function(e, r) {
      Ot.call(this, Pe.RepetitionMandatoryWithSeparator, r, e, Ta);
    }, t3.prototype.manyInternalRecord = function(e, r) {
      Ot.call(this, Pe.Repetition, r, e);
    }, t3.prototype.manySepFirstInternalRecord = function(e, r) {
      Ot.call(this, Pe.RepetitionWithSeparator, r, e, Ta);
    }, t3.prototype.orInternalRecord = function(e, r) {
      return au.call(this, e, r);
    }, t3.prototype.subruleInternalRecord = function(e, r, n2) {
      if (ar(r), !e || oe.has(e, "ruleName") === false) {
        var i = new Error("<SUBRULE" + Aa(r) + "> argument is invalid" + (" expecting a Parser method reference but got: <" + JSON.stringify(e) + ">") + (`
 inside top level rule: <` + this.recordingProdStack[0].name + ">"));
        throw i.KNOWN_RECORDER_ERROR = true, i;
      }
      var a2 = oe.peek(this.recordingProdStack), o = e.ruleName, s = new Pe.NonTerminal({ idx: r, nonTerminalName: o, referencedRule: void 0 });
      return a2.definition.push(s), this.outputCst ? iu : ir;
    }, t3.prototype.consumeInternalRecord = function(e, r, n2) {
      if (ar(r), !ma.hasShortKeyProperty(e)) {
        var i = new Error("<CONSUME" + Aa(r) + "> argument is invalid" + (" expecting a TokenType reference but got: <" + JSON.stringify(e) + ">") + (`
 inside top level rule: <` + this.recordingProdStack[0].name + ">"));
        throw i.KNOWN_RECORDER_ERROR = true, i;
      }
      var a2 = oe.peek(this.recordingProdStack), o = new Pe.Terminal({ idx: r, terminalType: e });
      return a2.definition.push(o), ga;
    }, t3;
  }();
  nr.GastRecorder = ou;
  function Ot(t3, e, r, n2) {
    n2 === void 0 && (n2 = false), ar(r);
    var i = oe.peek(this.recordingProdStack), a2 = oe.isFunction(e) ? e : e.DEF, o = new t3({ definition: [], idx: r });
    return n2 && (o.separator = e.SEP), oe.has(e, "MAX_LOOKAHEAD") && (o.maxLookahead = e.MAX_LOOKAHEAD), this.recordingProdStack.push(o), a2.call(this), i.definition.push(o), this.recordingProdStack.pop(), ir;
  }
  function au(t3, e) {
    var r = this;
    ar(e);
    var n2 = oe.peek(this.recordingProdStack), i = oe.isArray(t3) === false, a2 = i === false ? t3 : t3.DEF, o = new Pe.Alternation({ definition: [], idx: e, ignoreAmbiguities: i && t3.IGNORE_AMBIGUITIES === true });
    oe.has(t3, "MAX_LOOKAHEAD") && (o.maxLookahead = t3.MAX_LOOKAHEAD);
    var s = oe.some(a2, function(c2) {
      return oe.isFunction(c2.GATE);
    });
    return o.hasPredicates = s, n2.definition.push(o), oe.forEach(a2, function(c2) {
      var f = new Pe.Alternative({ definition: [] });
      o.definition.push(f), oe.has(c2, "IGNORE_AMBIGUITIES") ? f.ignoreAmbiguities = c2.IGNORE_AMBIGUITIES : oe.has(c2, "GATE") && (f.ignoreAmbiguities = true), r.recordingProdStack.push(f), c2.ALT.call(r), r.recordingProdStack.pop();
    }), ir;
  }
  function Aa(t3) {
    return t3 === 0 ? "" : "" + t3;
  }
  function ar(t3) {
    if (t3 < 0 || t3 > ya) {
      var e = new Error("Invalid DSL Method idx value: <" + t3 + `>
	` + ("Idx value must be a none negative value smaller than " + (ya + 1)));
      throw e.KNOWN_RECORDER_ERROR = true, e;
    }
  }
});
var Na = R2((or) => {
  "use strict";
  Object.defineProperty(or, "__esModule", { value: true });
  or.PerformanceTracer = void 0;
  var Oa = k(), su = ce(), uu = function() {
    function t3() {
    }
    return t3.prototype.initPerformanceTracer = function(e) {
      if (Oa.has(e, "traceInitPerf")) {
        var r = e.traceInitPerf, n2 = typeof r == "number";
        this.traceInitMaxIdent = n2 ? r : Infinity, this.traceInitPerf = n2 ? r > 0 : r;
      } else this.traceInitMaxIdent = 0, this.traceInitPerf = su.DEFAULT_PARSER_CONFIG.traceInitPerf;
      this.traceInitIndent = -1;
    }, t3.prototype.TRACE_INIT = function(e, r) {
      if (this.traceInitPerf === true) {
        this.traceInitIndent++;
        var n2 = new Array(this.traceInitIndent + 1).join("	");
        this.traceInitIndent < this.traceInitMaxIdent && console.log(n2 + "--> <" + e + ">");
        var i = Oa.timer(r), a2 = i.time, o = i.value, s = a2 > 10 ? console.warn : console.log;
        return this.traceInitIndent < this.traceInitMaxIdent && s(n2 + "<-- <" + e + "> time: " + a2 + "ms"), this.traceInitIndent--, o;
      } else return r();
    }, t3;
  }();
  or.PerformanceTracer = uu;
});
var Ia = R2((sr) => {
  "use strict";
  Object.defineProperty(sr, "__esModule", { value: true });
  sr.applyMixins = void 0;
  function cu(t3, e) {
    e.forEach(function(r) {
      var n2 = r.prototype;
      Object.getOwnPropertyNames(n2).forEach(function(i) {
        if (i !== "constructor") {
          var a2 = Object.getOwnPropertyDescriptor(n2, i);
          a2 && (a2.get || a2.set) ? Object.defineProperty(t3.prototype, i, a2) : t3.prototype[i] = r.prototype[i];
        }
      });
    });
  }
  sr.applyMixins = cu;
});
var ce = R2((U) => {
  "use strict";
  var ka = U && U.__extends || /* @__PURE__ */ function() {
    var t3 = function(e, r) {
      return t3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) {
        n2.__proto__ = i;
      } || function(n2, i) {
        for (var a2 in i) Object.prototype.hasOwnProperty.call(i, a2) && (n2[a2] = i[a2]);
      }, t3(e, r);
    };
    return function(e, r) {
      if (typeof r != "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null");
      t3(e, r);
      function n2() {
        this.constructor = e;
      }
      e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2());
    };
  }();
  Object.defineProperty(U, "__esModule", { value: true });
  U.EmbeddedActionsParser = U.CstParser = U.Parser = U.EMPTY_ALT = U.ParserDefinitionErrorType = U.DEFAULT_RULE_CONFIG = U.DEFAULT_PARSER_CONFIG = U.END_OF_FILE = void 0;
  var ee = k(), lu = pi2(), Pa = Ue(), Sa = mt(), xa = Ui(), fu = zr(), pu = zi2(), hu = ra(), du = ia(), vu = oa(), mu = la(), Eu = pa(), Tu = va(), yu = Ra(), _u = Na(), gu = Ia();
  U.END_OF_FILE = Pa.createTokenInstance(Pa.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN);
  Object.freeze(U.END_OF_FILE);
  U.DEFAULT_PARSER_CONFIG = Object.freeze({ recoveryEnabled: false, maxLookahead: 3, dynamicTokensEnabled: false, outputCst: true, errorMessageProvider: Sa.defaultParserErrorProvider, nodeLocationTracking: "none", traceInitPerf: false, skipValidations: false });
  U.DEFAULT_RULE_CONFIG = Object.freeze({ recoveryValueFunc: function() {
  }, resyncEnabled: true });
  var Au;
  (function(t3) {
    t3[t3.INVALID_RULE_NAME = 0] = "INVALID_RULE_NAME", t3[t3.DUPLICATE_RULE_NAME = 1] = "DUPLICATE_RULE_NAME", t3[t3.INVALID_RULE_OVERRIDE = 2] = "INVALID_RULE_OVERRIDE", t3[t3.DUPLICATE_PRODUCTIONS = 3] = "DUPLICATE_PRODUCTIONS", t3[t3.UNRESOLVED_SUBRULE_REF = 4] = "UNRESOLVED_SUBRULE_REF", t3[t3.LEFT_RECURSION = 5] = "LEFT_RECURSION", t3[t3.NONE_LAST_EMPTY_ALT = 6] = "NONE_LAST_EMPTY_ALT", t3[t3.AMBIGUOUS_ALTS = 7] = "AMBIGUOUS_ALTS", t3[t3.CONFLICT_TOKENS_RULES_NAMESPACE = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE", t3[t3.INVALID_TOKEN_NAME = 9] = "INVALID_TOKEN_NAME", t3[t3.NO_NON_EMPTY_LOOKAHEAD = 10] = "NO_NON_EMPTY_LOOKAHEAD", t3[t3.AMBIGUOUS_PREFIX_ALTS = 11] = "AMBIGUOUS_PREFIX_ALTS", t3[t3.TOO_MANY_ALTS = 12] = "TOO_MANY_ALTS";
  })(Au = U.ParserDefinitionErrorType || (U.ParserDefinitionErrorType = {}));
  function Ru(t3) {
    return t3 === void 0 && (t3 = void 0), function() {
      return t3;
    };
  }
  U.EMPTY_ALT = Ru;
  var ur = function() {
    function t3(e, r) {
      this.definitionErrors = [], this.selfAnalysisDone = false;
      var n2 = this;
      if (n2.initErrorHandler(r), n2.initLexerAdapter(), n2.initLooksAhead(r), n2.initRecognizerEngine(e, r), n2.initRecoverable(r), n2.initTreeBuilder(r), n2.initContentAssist(), n2.initGastRecorder(r), n2.initPerformanceTracer(r), ee.has(r, "ignoredIssues")) throw new Error(`The <ignoredIssues> IParserConfig property has been deprecated.
	Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.
	See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES
	For further details.`);
      this.skipValidations = ee.has(r, "skipValidations") ? r.skipValidations : U.DEFAULT_PARSER_CONFIG.skipValidations;
    }
    return t3.performSelfAnalysis = function(e) {
      throw Error("The **static** `performSelfAnalysis` method has been deprecated.	\nUse the **instance** method with the same name instead.");
    }, t3.prototype.performSelfAnalysis = function() {
      var e = this;
      this.TRACE_INIT("performSelfAnalysis", function() {
        var r;
        e.selfAnalysisDone = true;
        var n2 = e.className;
        e.TRACE_INIT("toFastProps", function() {
          ee.toFastProperties(e);
        }), e.TRACE_INIT("Grammar Recording", function() {
          try {
            e.enableRecording(), ee.forEach(e.definedRulesNames, function(a2) {
              var o = e[a2], s = o.originalGrammarAction, c2 = void 0;
              e.TRACE_INIT(a2 + " Rule", function() {
                c2 = e.topLevelRuleRecord(a2, s);
              }), e.gastProductionsCache[a2] = c2;
            });
          } finally {
            e.disableRecording();
          }
        });
        var i = [];
        if (e.TRACE_INIT("Grammar Resolving", function() {
          i = xa.resolveGrammar({ rules: ee.values(e.gastProductionsCache) }), e.definitionErrors = e.definitionErrors.concat(i);
        }), e.TRACE_INIT("Grammar Validations", function() {
          if (ee.isEmpty(i) && e.skipValidations === false) {
            var a2 = xa.validateGrammar({ rules: ee.values(e.gastProductionsCache), maxLookahead: e.maxLookahead, tokenTypes: ee.values(e.tokensMap), errMsgProvider: Sa.defaultGrammarValidatorErrorProvider, grammarName: n2 });
            e.definitionErrors = e.definitionErrors.concat(a2);
          }
        }), ee.isEmpty(e.definitionErrors) && (e.recoveryEnabled && e.TRACE_INIT("computeAllProdsFollows", function() {
          var a2 = lu.computeAllProdsFollows(ee.values(e.gastProductionsCache));
          e.resyncFollows = a2;
        }), e.TRACE_INIT("ComputeLookaheadFunctions", function() {
          e.preComputeLookaheadFunctions(ee.values(e.gastProductionsCache));
        })), !t3.DEFER_DEFINITION_ERRORS_HANDLING && !ee.isEmpty(e.definitionErrors)) throw r = ee.map(e.definitionErrors, function(a2) {
          return a2.message;
        }), new Error(`Parser Definition Errors detected:
 ` + r.join(`
-------------------------------
`));
      });
    }, t3.DEFER_DEFINITION_ERRORS_HANDLING = false, t3;
  }();
  U.Parser = ur;
  gu.applyMixins(ur, [fu.Recoverable, pu.LooksAhead, hu.TreeBuilder, du.LexerAdapter, mu.RecognizerEngine, vu.RecognizerApi, Eu.ErrorHandler, Tu.ContentAssist, yu.GastRecorder, _u.PerformanceTracer]);
  var Ou = function(t3) {
    ka(e, t3);
    function e(r, n2) {
      n2 === void 0 && (n2 = U.DEFAULT_PARSER_CONFIG);
      var i = this, a2 = ee.cloneObj(n2);
      return a2.outputCst = true, i = t3.call(this, r, a2) || this, i;
    }
    return e;
  }(ur);
  U.CstParser = Ou;
  var Nu = function(t3) {
    ka(e, t3);
    function e(r, n2) {
      n2 === void 0 && (n2 = U.DEFAULT_PARSER_CONFIG);
      var i = this, a2 = ee.cloneObj(n2);
      return a2.outputCst = false, i = t3.call(this, r, a2) || this, i;
    }
    return e;
  }(ur);
  U.EmbeddedActionsParser = Nu;
});
var La = R2((cr) => {
  "use strict";
  Object.defineProperty(cr, "__esModule", { value: true });
  cr.createSyntaxDiagramsCode = void 0;
  var Ca = Er();
  function Iu(t3, e) {
    var r = e === void 0 ? {} : e, n2 = r.resourceBase, i = n2 === void 0 ? "https://unpkg.com/chevrotain@" + Ca.VERSION + "/diagrams/" : n2, a2 = r.css, o = a2 === void 0 ? "https://unpkg.com/chevrotain@" + Ca.VERSION + "/diagrams/diagrams.css" : a2, s = `
<!-- This is a generated file -->
<!DOCTYPE html>
<meta charset="utf-8">
<style>
  body {
    background-color: hsl(30, 20%, 95%)
  }
</style>

`, c2 = `
<link rel='stylesheet' href='` + o + `'>
`, f = `
<script src='` + i + `vendor/railroad-diagrams.js'><\/script>
<script src='` + i + `src/diagrams_builder.js'><\/script>
<script src='` + i + `src/diagrams_behavior.js'><\/script>
<script src='` + i + `src/main.js'><\/script>
`, p = `
<div id="diagrams" align="center"></div>
`, l2 = `
<script>
    window.serializedGrammar = ` + JSON.stringify(t3, null, "  ") + `;
<\/script>
`, m = `
<script>
    var diagramsDiv = document.getElementById("diagrams");
    main.drawDiagramsFromSerializedGrammar(serializedGrammar, diagramsDiv);
<\/script>
`;
    return s + c2 + f + p + l2 + m;
  }
  cr.createSyntaxDiagramsCode = Iu;
});
var Fa = R2((E) => {
  "use strict";
  Object.defineProperty(E, "__esModule", { value: true });
  E.Parser = E.createSyntaxDiagramsCode = E.clearCache = E.GAstVisitor = E.serializeProduction = E.serializeGrammar = E.Terminal = E.Rule = E.RepetitionWithSeparator = E.RepetitionMandatoryWithSeparator = E.RepetitionMandatory = E.Repetition = E.Option = E.NonTerminal = E.Alternative = E.Alternation = E.defaultLexerErrorProvider = E.NoViableAltException = E.NotAllInputParsedException = E.MismatchedTokenException = E.isRecognitionException = E.EarlyExitException = E.defaultParserErrorProvider = E.tokenName = E.tokenMatcher = E.tokenLabel = E.EOF = E.createTokenInstance = E.createToken = E.LexerDefinitionErrorType = E.Lexer = E.EMPTY_ALT = E.ParserDefinitionErrorType = E.EmbeddedActionsParser = E.CstParser = E.VERSION = void 0;
  var ku = Er();
  Object.defineProperty(E, "VERSION", { enumerable: true, get: function() {
    return ku.VERSION;
  } });
  var lr = ce();
  Object.defineProperty(E, "CstParser", { enumerable: true, get: function() {
    return lr.CstParser;
  } });
  Object.defineProperty(E, "EmbeddedActionsParser", { enumerable: true, get: function() {
    return lr.EmbeddedActionsParser;
  } });
  Object.defineProperty(E, "ParserDefinitionErrorType", { enumerable: true, get: function() {
    return lr.ParserDefinitionErrorType;
  } });
  Object.defineProperty(E, "EMPTY_ALT", { enumerable: true, get: function() {
    return lr.EMPTY_ALT;
  } });
  var Ma = ft();
  Object.defineProperty(E, "Lexer", { enumerable: true, get: function() {
    return Ma.Lexer;
  } });
  Object.defineProperty(E, "LexerDefinitionErrorType", { enumerable: true, get: function() {
    return Ma.LexerDefinitionErrorType;
  } });
  var nt2 = Ue();
  Object.defineProperty(E, "createToken", { enumerable: true, get: function() {
    return nt2.createToken;
  } });
  Object.defineProperty(E, "createTokenInstance", { enumerable: true, get: function() {
    return nt2.createTokenInstance;
  } });
  Object.defineProperty(E, "EOF", { enumerable: true, get: function() {
    return nt2.EOF;
  } });
  Object.defineProperty(E, "tokenLabel", { enumerable: true, get: function() {
    return nt2.tokenLabel;
  } });
  Object.defineProperty(E, "tokenMatcher", { enumerable: true, get: function() {
    return nt2.tokenMatcher;
  } });
  Object.defineProperty(E, "tokenName", { enumerable: true, get: function() {
    return nt2.tokenName;
  } });
  var Pu = mt();
  Object.defineProperty(E, "defaultParserErrorProvider", { enumerable: true, get: function() {
    return Pu.defaultParserErrorProvider;
  } });
  var Nt = et2();
  Object.defineProperty(E, "EarlyExitException", { enumerable: true, get: function() {
    return Nt.EarlyExitException;
  } });
  Object.defineProperty(E, "isRecognitionException", { enumerable: true, get: function() {
    return Nt.isRecognitionException;
  } });
  Object.defineProperty(E, "MismatchedTokenException", { enumerable: true, get: function() {
    return Nt.MismatchedTokenException;
  } });
  Object.defineProperty(E, "NotAllInputParsedException", { enumerable: true, get: function() {
    return Nt.NotAllInputParsedException;
  } });
  Object.defineProperty(E, "NoViableAltException", { enumerable: true, get: function() {
    return Nt.NoViableAltException;
  } });
  var Su = kr();
  Object.defineProperty(E, "defaultLexerErrorProvider", { enumerable: true, get: function() {
    return Su.defaultLexerErrorProvider;
  } });
  var Se = ne();
  Object.defineProperty(E, "Alternation", { enumerable: true, get: function() {
    return Se.Alternation;
  } });
  Object.defineProperty(E, "Alternative", { enumerable: true, get: function() {
    return Se.Alternative;
  } });
  Object.defineProperty(E, "NonTerminal", { enumerable: true, get: function() {
    return Se.NonTerminal;
  } });
  Object.defineProperty(E, "Option", { enumerable: true, get: function() {
    return Se.Option;
  } });
  Object.defineProperty(E, "Repetition", { enumerable: true, get: function() {
    return Se.Repetition;
  } });
  Object.defineProperty(E, "RepetitionMandatory", { enumerable: true, get: function() {
    return Se.RepetitionMandatory;
  } });
  Object.defineProperty(E, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function() {
    return Se.RepetitionMandatoryWithSeparator;
  } });
  Object.defineProperty(E, "RepetitionWithSeparator", { enumerable: true, get: function() {
    return Se.RepetitionWithSeparator;
  } });
  Object.defineProperty(E, "Rule", { enumerable: true, get: function() {
    return Se.Rule;
  } });
  Object.defineProperty(E, "Terminal", { enumerable: true, get: function() {
    return Se.Terminal;
  } });
  var ba = ne();
  Object.defineProperty(E, "serializeGrammar", { enumerable: true, get: function() {
    return ba.serializeGrammar;
  } });
  Object.defineProperty(E, "serializeProduction", { enumerable: true, get: function() {
    return ba.serializeProduction;
  } });
  var xu = $e();
  Object.defineProperty(E, "GAstVisitor", { enumerable: true, get: function() {
    return xu.GAstVisitor;
  } });
  function Cu() {
    console.warn(`The clearCache function was 'soft' removed from the Chevrotain API.
	 It performs no action other than printing this message.
	 Please avoid using it as it will be completely removed in the future`);
  }
  E.clearCache = Cu;
  var Lu = La();
  Object.defineProperty(E, "createSyntaxDiagramsCode", { enumerable: true, get: function() {
    return Lu.createSyntaxDiagramsCode;
  } });
  var Mu = /* @__PURE__ */ function() {
    function t3() {
      throw new Error(`The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead.
See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0`);
    }
    return t3;
  }();
  E.Parser = Mu;
});
var chevrotain_module_min_default = Fa();

// node_modules/three/examples/jsm/loaders/VRMLLoader.js
var VRMLLoader = class extends Loader {
  /**
   * Constructs a new VRML loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded VRML asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(Scene)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const path = scope.path === "" ? LoaderUtils.extractUrlBase(url) : scope.path;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2, path));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given VRML data and returns the resulting scene.
   *
   * @param {string} data - The raw VRML data as a string.
   * @param {string} path - The URL base path.
   * @return {Scene} The parsed scene.
   */
  parse(data2, path) {
    const nodeMap = {};
    function generateVRMLTree(data3) {
      const tokenData = createTokens();
      const lexer = new VRMLLexer(tokenData.tokens);
      const parser = new VRMLParser(tokenData.tokenVocabulary);
      const visitor = createVisitor(parser.getBaseCstVisitorConstructor());
      const lexingResult = lexer.lex(data3);
      parser.input = lexingResult.tokens;
      const cstOutput = parser.vrml();
      if (parser.errors.length > 0) {
        console.error(parser.errors);
        throw Error("THREE.VRMLLoader: Parsing errors detected.");
      }
      const ast = visitor.visit(cstOutput);
      return ast;
    }
    function createTokens() {
      const createToken = chevrotain_module_min_default.createToken;
      const RouteIdentifier = createToken({ name: "RouteIdentifier", pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ });
      const Identifier = createToken({ name: "Identifier", pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]([^\0-\x20\x22\x27\x23\x2b\x2c\x2e\x5b\x5d\x5c\x7b\x7d])*/, longer_alt: RouteIdentifier });
      const nodeTypes = [
        "Anchor",
        "Billboard",
        "Collision",
        "Group",
        "Transform",
        // grouping nodes
        "Inline",
        "LOD",
        "Switch",
        // special groups
        "AudioClip",
        "DirectionalLight",
        "PointLight",
        "Script",
        "Shape",
        "Sound",
        "SpotLight",
        "WorldInfo",
        // common nodes
        "CylinderSensor",
        "PlaneSensor",
        "ProximitySensor",
        "SphereSensor",
        "TimeSensor",
        "TouchSensor",
        "VisibilitySensor",
        // sensors
        "Box",
        "Cone",
        "Cylinder",
        "ElevationGrid",
        "Extrusion",
        "IndexedFaceSet",
        "IndexedLineSet",
        "PointSet",
        "Sphere",
        // geometries
        "Color",
        "Coordinate",
        "Normal",
        "TextureCoordinate",
        // geometric properties
        "Appearance",
        "FontStyle",
        "ImageTexture",
        "Material",
        "MovieTexture",
        "PixelTexture",
        "TextureTransform",
        // appearance
        "ColorInterpolator",
        "CoordinateInterpolator",
        "NormalInterpolator",
        "OrientationInterpolator",
        "PositionInterpolator",
        "ScalarInterpolator",
        // interpolators
        "Background",
        "Fog",
        "NavigationInfo",
        "Viewpoint",
        // bindable nodes
        "Text"
        // Text must be placed at the end of the regex so there are no matches for TextureTransform and TextureCoordinate
      ];
      const Version = createToken({
        name: "Version",
        pattern: /#VRML.*/,
        longer_alt: Identifier
      });
      const NodeName = createToken({
        name: "NodeName",
        pattern: new RegExp(nodeTypes.join("|")),
        longer_alt: Identifier
      });
      const DEF = createToken({
        name: "DEF",
        pattern: /DEF/,
        longer_alt: Identifier
      });
      const USE = createToken({
        name: "USE",
        pattern: /USE/,
        longer_alt: Identifier
      });
      const ROUTE = createToken({
        name: "ROUTE",
        pattern: /ROUTE/,
        longer_alt: Identifier
      });
      const TO = createToken({
        name: "TO",
        pattern: /TO/,
        longer_alt: Identifier
      });
      const StringLiteral = createToken({ name: "StringLiteral", pattern: /"(?:[^\\"\n\r]|\\[bfnrtv"\\/]|\\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])*"/ });
      const HexLiteral = createToken({ name: "HexLiteral", pattern: /0[xX][0-9a-fA-F]+/ });
      const NumberLiteral = createToken({ name: "NumberLiteral", pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ });
      const TrueLiteral = createToken({ name: "TrueLiteral", pattern: /TRUE/ });
      const FalseLiteral = createToken({ name: "FalseLiteral", pattern: /FALSE/ });
      const NullLiteral = createToken({ name: "NullLiteral", pattern: /NULL/ });
      const LSquare = createToken({ name: "LSquare", pattern: /\[/ });
      const RSquare = createToken({ name: "RSquare", pattern: /]/ });
      const LCurly = createToken({ name: "LCurly", pattern: /{/ });
      const RCurly = createToken({ name: "RCurly", pattern: /}/ });
      const Comment = createToken({
        name: "Comment",
        pattern: /#.*/,
        group: chevrotain_module_min_default.Lexer.SKIPPED
      });
      const WhiteSpace = createToken({
        name: "WhiteSpace",
        pattern: /[ ,\s]/,
        group: chevrotain_module_min_default.Lexer.SKIPPED
      });
      const tokens = [
        WhiteSpace,
        // keywords appear before the Identifier
        NodeName,
        DEF,
        USE,
        ROUTE,
        TO,
        TrueLiteral,
        FalseLiteral,
        NullLiteral,
        // the Identifier must appear after the keywords because all keywords are valid identifiers
        Version,
        Identifier,
        RouteIdentifier,
        StringLiteral,
        HexLiteral,
        NumberLiteral,
        LSquare,
        RSquare,
        LCurly,
        RCurly,
        Comment
      ];
      const tokenVocabulary = {};
      for (let i = 0, l2 = tokens.length; i < l2; i++) {
        const token = tokens[i];
        tokenVocabulary[token.name] = token;
      }
      return { tokens, tokenVocabulary };
    }
    function createVisitor(BaseVRMLVisitor) {
      class VRMLToASTVisitor extends BaseVRMLVisitor {
        constructor() {
          super();
          this.validateVisitor();
        }
        vrml(ctx) {
          const data3 = {
            version: this.visit(ctx.version),
            nodes: [],
            routes: []
          };
          for (let i = 0, l2 = ctx.node.length; i < l2; i++) {
            const node = ctx.node[i];
            data3.nodes.push(this.visit(node));
          }
          if (ctx.route) {
            for (let i = 0, l2 = ctx.route.length; i < l2; i++) {
              const route = ctx.route[i];
              data3.routes.push(this.visit(route));
            }
          }
          return data3;
        }
        version(ctx) {
          return ctx.Version[0].image;
        }
        node(ctx) {
          const data3 = {
            name: ctx.NodeName[0].image,
            fields: []
          };
          if (ctx.field) {
            for (let i = 0, l2 = ctx.field.length; i < l2; i++) {
              const field = ctx.field[i];
              data3.fields.push(this.visit(field));
            }
          }
          if (ctx.def) {
            data3.DEF = this.visit(ctx.def[0]);
          }
          return data3;
        }
        field(ctx) {
          const data3 = {
            name: ctx.Identifier[0].image,
            type: null,
            values: null
          };
          let result;
          if (ctx.singleFieldValue) {
            result = this.visit(ctx.singleFieldValue[0]);
          }
          if (ctx.multiFieldValue) {
            result = this.visit(ctx.multiFieldValue[0]);
          }
          data3.type = result.type;
          data3.values = result.values;
          return data3;
        }
        def(ctx) {
          return (ctx.Identifier || ctx.NodeName)[0].image;
        }
        use(ctx) {
          return { USE: (ctx.Identifier || ctx.NodeName)[0].image };
        }
        singleFieldValue(ctx) {
          return processField(this, ctx);
        }
        multiFieldValue(ctx) {
          return processField(this, ctx);
        }
        route(ctx) {
          const data3 = {
            FROM: ctx.RouteIdentifier[0].image,
            TO: ctx.RouteIdentifier[1].image
          };
          return data3;
        }
      }
      function processField(scope, ctx) {
        const field = {
          type: null,
          values: []
        };
        if (ctx.node) {
          field.type = "node";
          for (let i = 0, l2 = ctx.node.length; i < l2; i++) {
            const node = ctx.node[i];
            field.values.push(scope.visit(node));
          }
        }
        if (ctx.use) {
          field.type = "use";
          for (let i = 0, l2 = ctx.use.length; i < l2; i++) {
            const use = ctx.use[i];
            field.values.push(scope.visit(use));
          }
        }
        if (ctx.StringLiteral) {
          field.type = "string";
          for (let i = 0, l2 = ctx.StringLiteral.length; i < l2; i++) {
            const stringLiteral = ctx.StringLiteral[i];
            field.values.push(stringLiteral.image.replace(/'|"/g, ""));
          }
        }
        if (ctx.NumberLiteral) {
          field.type = "number";
          for (let i = 0, l2 = ctx.NumberLiteral.length; i < l2; i++) {
            const numberLiteral = ctx.NumberLiteral[i];
            field.values.push(parseFloat(numberLiteral.image));
          }
        }
        if (ctx.HexLiteral) {
          field.type = "hex";
          for (let i = 0, l2 = ctx.HexLiteral.length; i < l2; i++) {
            const hexLiteral = ctx.HexLiteral[i];
            field.values.push(hexLiteral.image);
          }
        }
        if (ctx.TrueLiteral) {
          field.type = "boolean";
          for (let i = 0, l2 = ctx.TrueLiteral.length; i < l2; i++) {
            const trueLiteral = ctx.TrueLiteral[i];
            if (trueLiteral.image === "TRUE") field.values.push(true);
          }
        }
        if (ctx.FalseLiteral) {
          field.type = "boolean";
          for (let i = 0, l2 = ctx.FalseLiteral.length; i < l2; i++) {
            const falseLiteral = ctx.FalseLiteral[i];
            if (falseLiteral.image === "FALSE") field.values.push(false);
          }
        }
        if (ctx.NullLiteral) {
          field.type = "null";
          ctx.NullLiteral.forEach(function() {
            field.values.push(null);
          });
        }
        return field;
      }
      return new VRMLToASTVisitor();
    }
    function parseTree(tree2) {
      const nodes = tree2.nodes;
      const scene2 = new Scene();
      for (let i = 0, l2 = nodes.length; i < l2; i++) {
        const node = nodes[i];
        buildNodeMap(node);
      }
      for (let i = 0, l2 = nodes.length; i < l2; i++) {
        const node = nodes[i];
        const object = getNode(node);
        if (object instanceof Object3D) scene2.add(object);
        if (node.name === "WorldInfo") scene2.userData.worldInfo = object;
      }
      return scene2;
    }
    function buildNodeMap(node) {
      if (node.DEF) {
        nodeMap[node.DEF] = node;
      }
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        if (field.type === "node") {
          const fieldValues = field.values;
          for (let j2 = 0, jl = fieldValues.length; j2 < jl; j2++) {
            buildNodeMap(fieldValues[j2]);
          }
        }
      }
    }
    function getNode(node) {
      if (node.USE) {
        return resolveUSE(node.USE);
      }
      if (node.build !== void 0) return node.build;
      node.build = buildNode(node);
      return node.build;
    }
    function buildNode(node) {
      const nodeName = node.name;
      let build;
      switch (nodeName) {
        case "Anchor":
        case "Group":
        case "Transform":
        case "Collision":
          build = buildGroupingNode(node);
          break;
        case "Background":
          build = buildBackgroundNode(node);
          break;
        case "Shape":
          build = buildShapeNode(node);
          break;
        case "Appearance":
          build = buildAppearanceNode(node);
          break;
        case "Material":
          build = buildMaterialNode(node);
          break;
        case "ImageTexture":
          build = buildImageTextureNode(node);
          break;
        case "PixelTexture":
          build = buildPixelTextureNode(node);
          break;
        case "TextureTransform":
          build = buildTextureTransformNode(node);
          break;
        case "IndexedFaceSet":
          build = buildIndexedFaceSetNode(node);
          break;
        case "IndexedLineSet":
          build = buildIndexedLineSetNode(node);
          break;
        case "PointSet":
          build = buildPointSetNode(node);
          break;
        case "Box":
          build = buildBoxNode(node);
          break;
        case "Cone":
          build = buildConeNode(node);
          break;
        case "Cylinder":
          build = buildCylinderNode(node);
          break;
        case "Sphere":
          build = buildSphereNode(node);
          break;
        case "ElevationGrid":
          build = buildElevationGridNode(node);
          break;
        case "Extrusion":
          build = buildExtrusionNode(node);
          break;
        case "Color":
        case "Coordinate":
        case "Normal":
        case "TextureCoordinate":
          build = buildGeometricNode(node);
          break;
        case "WorldInfo":
          build = buildWorldInfoNode(node);
          break;
        case "Billboard":
        case "Inline":
        case "LOD":
        case "Switch":
        case "AudioClip":
        case "DirectionalLight":
        case "PointLight":
        case "Script":
        case "Sound":
        case "SpotLight":
        case "CylinderSensor":
        case "PlaneSensor":
        case "ProximitySensor":
        case "SphereSensor":
        case "TimeSensor":
        case "TouchSensor":
        case "VisibilitySensor":
        case "Text":
        case "FontStyle":
        case "MovieTexture":
        case "ColorInterpolator":
        case "CoordinateInterpolator":
        case "NormalInterpolator":
        case "OrientationInterpolator":
        case "PositionInterpolator":
        case "ScalarInterpolator":
        case "Fog":
        case "NavigationInfo":
        case "Viewpoint":
          break;
        default:
          console.warn("THREE.VRMLLoader: Unknown node:", nodeName);
          break;
      }
      if (build !== void 0 && node.DEF !== void 0 && build.hasOwnProperty("name") === true) {
        build.name = node.DEF;
      }
      return build;
    }
    function buildGroupingNode(node) {
      const object = new Group();
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "bboxCenter":
            break;
          case "bboxSize":
            break;
          case "center":
            break;
          case "children":
            parseFieldChildren(fieldValues, object);
            break;
          case "description":
            break;
          case "collide":
            break;
          case "parameter":
            break;
          case "rotation":
            const axis = new Vector3(fieldValues[0], fieldValues[1], fieldValues[2]).normalize();
            const angle = fieldValues[3];
            object.quaternion.setFromAxisAngle(axis, angle);
            break;
          case "scale":
            object.scale.set(fieldValues[0], fieldValues[1], fieldValues[2]);
            break;
          case "scaleOrientation":
            break;
          case "translation":
            object.position.set(fieldValues[0], fieldValues[1], fieldValues[2]);
            break;
          case "proxy":
            break;
          case "url":
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      return object;
    }
    function buildBackgroundNode(node) {
      const group = new Group();
      let groundAngle, groundColor;
      let skyAngle, skyColor;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "groundAngle":
            groundAngle = fieldValues;
            break;
          case "groundColor":
            groundColor = fieldValues;
            break;
          case "backUrl":
            break;
          case "bottomUrl":
            break;
          case "frontUrl":
            break;
          case "leftUrl":
            break;
          case "rightUrl":
            break;
          case "topUrl":
            break;
          case "skyAngle":
            skyAngle = fieldValues;
            break;
          case "skyColor":
            skyColor = fieldValues;
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      const radius = 1e4;
      if (skyColor) {
        const skyGeometry = new SphereGeometry(radius, 32, 16);
        const skyMaterial = new MeshBasicMaterial({ fog: false, side: BackSide, depthWrite: false, depthTest: false });
        if (skyColor.length > 3) {
          paintFaces(skyGeometry, radius, skyAngle, toColorArray(skyColor), true);
          skyMaterial.vertexColors = true;
        } else {
          skyMaterial.color.setRGB(skyColor[0], skyColor[1], skyColor[2], SRGBColorSpace);
        }
        const sky = new Mesh(skyGeometry, skyMaterial);
        group.add(sky);
      }
      if (groundColor) {
        if (groundColor.length > 0) {
          const groundGeometry = new SphereGeometry(radius, 32, 16, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI);
          const groundMaterial = new MeshBasicMaterial({ fog: false, side: BackSide, vertexColors: true, depthWrite: false, depthTest: false });
          paintFaces(groundGeometry, radius, groundAngle, toColorArray(groundColor), false);
          const ground = new Mesh(groundGeometry, groundMaterial);
          group.add(ground);
        }
      }
      group.renderOrder = -Infinity;
      return group;
    }
    function buildShapeNode(node) {
      const fields = node.fields;
      let material = new MeshBasicMaterial({
        name: Loader.DEFAULT_MATERIAL_NAME,
        color: 0
      });
      let geometry;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "appearance":
            if (fieldValues[0] !== null) {
              material = getNode(fieldValues[0]);
            }
            break;
          case "geometry":
            if (fieldValues[0] !== null) {
              geometry = getNode(fieldValues[0]);
            }
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      let object;
      if (geometry && geometry.attributes.position) {
        const type = geometry._type;
        if (type === "points") {
          const pointsMaterial = new PointsMaterial({
            name: Loader.DEFAULT_MATERIAL_NAME,
            color: 16777215,
            opacity: material.opacity,
            transparent: material.transparent
          });
          if (geometry.attributes.color !== void 0) {
            pointsMaterial.vertexColors = true;
          } else {
            if (material.isMeshPhongMaterial) {
              pointsMaterial.color.copy(material.emissive);
            }
          }
          object = new Points(geometry, pointsMaterial);
        } else if (type === "line") {
          const lineMaterial = new LineBasicMaterial({
            name: Loader.DEFAULT_MATERIAL_NAME,
            color: 16777215,
            opacity: material.opacity,
            transparent: material.transparent
          });
          if (geometry.attributes.color !== void 0) {
            lineMaterial.vertexColors = true;
          } else {
            if (material.isMeshPhongMaterial) {
              lineMaterial.color.copy(material.emissive);
            }
          }
          object = new LineSegments(geometry, lineMaterial);
        } else {
          if (geometry._solid !== void 0) {
            material.side = geometry._solid ? FrontSide : DoubleSide;
          }
          if (geometry.attributes.color !== void 0) {
            material.vertexColors = true;
          }
          object = new Mesh(geometry, material);
        }
      } else {
        object = new Object3D();
        object.visible = false;
      }
      return object;
    }
    function buildAppearanceNode(node) {
      let material = new MeshPhongMaterial();
      let transformData;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "material":
            if (fieldValues[0] !== null) {
              const materialData = getNode(fieldValues[0]);
              if (materialData.diffuseColor) material.color.copy(materialData.diffuseColor);
              if (materialData.emissiveColor) material.emissive.copy(materialData.emissiveColor);
              if (materialData.shininess) material.shininess = materialData.shininess;
              if (materialData.specularColor) material.specular.copy(materialData.specularColor);
              if (materialData.transparency) material.opacity = 1 - materialData.transparency;
              if (materialData.transparency > 0) material.transparent = true;
            } else {
              material = new MeshBasicMaterial({
                name: Loader.DEFAULT_MATERIAL_NAME,
                color: 0
              });
            }
            break;
          case "texture":
            const textureNode = fieldValues[0];
            if (textureNode !== null) {
              if (textureNode.name === "ImageTexture" || textureNode.name === "PixelTexture") {
                material.map = getNode(textureNode);
              } else {
              }
            }
            break;
          case "textureTransform":
            if (fieldValues[0] !== null) {
              transformData = getNode(fieldValues[0]);
            }
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      if (material.map) {
        if (material.map.__type) {
          switch (material.map.__type) {
            case TEXTURE_TYPE.INTENSITY_ALPHA:
              material.opacity = 1;
              break;
            case TEXTURE_TYPE.RGB:
              material.color.set(16777215);
              break;
            case TEXTURE_TYPE.RGBA:
              material.color.set(16777215);
              material.opacity = 1;
              break;
            default:
          }
          delete material.map.__type;
        }
        if (transformData) {
          material.map.center.copy(transformData.center);
          material.map.rotation = transformData.rotation;
          material.map.repeat.copy(transformData.scale);
          material.map.offset.copy(transformData.translation);
        }
      }
      return material;
    }
    function buildMaterialNode(node) {
      const materialData = {};
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "ambientIntensity":
            break;
          case "diffuseColor":
            materialData.diffuseColor = new Color().setRGB(fieldValues[0], fieldValues[1], fieldValues[2], SRGBColorSpace);
            break;
          case "emissiveColor":
            materialData.emissiveColor = new Color().setRGB(fieldValues[0], fieldValues[1], fieldValues[2], SRGBColorSpace);
            break;
          case "shininess":
            materialData.shininess = fieldValues[0];
            break;
          case "specularColor":
            materialData.specularColor = new Color().setRGB(fieldValues[0], fieldValues[1], fieldValues[2], SRGBColorSpace);
            break;
          case "transparency":
            materialData.transparency = fieldValues[0];
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      return materialData;
    }
    function parseHexColor(hex, textureType, color) {
      let value2;
      switch (textureType) {
        case TEXTURE_TYPE.INTENSITY:
          value2 = parseInt(hex);
          color.r = value2;
          color.g = value2;
          color.b = value2;
          color.a = 1;
          break;
        case TEXTURE_TYPE.INTENSITY_ALPHA:
          value2 = parseInt("0x" + hex.substring(2, 4));
          color.r = value2;
          color.g = value2;
          color.b = value2;
          color.a = parseInt("0x" + hex.substring(4, 6));
          break;
        case TEXTURE_TYPE.RGB:
          color.r = parseInt("0x" + hex.substring(2, 4));
          color.g = parseInt("0x" + hex.substring(4, 6));
          color.b = parseInt("0x" + hex.substring(6, 8));
          color.a = 1;
          break;
        case TEXTURE_TYPE.RGBA:
          color.r = parseInt("0x" + hex.substring(2, 4));
          color.g = parseInt("0x" + hex.substring(4, 6));
          color.b = parseInt("0x" + hex.substring(6, 8));
          color.a = parseInt("0x" + hex.substring(8, 10));
          break;
        default:
      }
    }
    function getTextureType(num_components) {
      let type;
      switch (num_components) {
        case 1:
          type = TEXTURE_TYPE.INTENSITY;
          break;
        case 2:
          type = TEXTURE_TYPE.INTENSITY_ALPHA;
          break;
        case 3:
          type = TEXTURE_TYPE.RGB;
          break;
        case 4:
          type = TEXTURE_TYPE.RGBA;
          break;
        default:
      }
      return type;
    }
    function buildPixelTextureNode(node) {
      let texture;
      let wrapS = RepeatWrapping;
      let wrapT = RepeatWrapping;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "image":
            const width2 = fieldValues[0];
            const height2 = fieldValues[1];
            const num_components = fieldValues[2];
            const textureType = getTextureType(num_components);
            const data3 = new Uint8Array(4 * width2 * height2);
            const color = { r: 0, g: 0, b: 0, a: 0 };
            for (let j2 = 3, k2 = 0, jl = fieldValues.length; j2 < jl; j2++, k2++) {
              parseHexColor(fieldValues[j2], textureType, color);
              const stride = k2 * 4;
              data3[stride + 0] = color.r;
              data3[stride + 1] = color.g;
              data3[stride + 2] = color.b;
              data3[stride + 3] = color.a;
            }
            texture = new DataTexture(data3, width2, height2);
            texture.colorSpace = SRGBColorSpace;
            texture.needsUpdate = true;
            texture.__type = textureType;
            break;
          case "repeatS":
            if (fieldValues[0] === false) wrapS = ClampToEdgeWrapping;
            break;
          case "repeatT":
            if (fieldValues[0] === false) wrapT = ClampToEdgeWrapping;
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      if (texture) {
        texture.wrapS = wrapS;
        texture.wrapT = wrapT;
      }
      return texture;
    }
    function buildImageTextureNode(node) {
      let texture;
      let wrapS = RepeatWrapping;
      let wrapT = RepeatWrapping;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "url":
            const url = fieldValues[0];
            if (url) texture = textureLoader.load(url);
            break;
          case "repeatS":
            if (fieldValues[0] === false) wrapS = ClampToEdgeWrapping;
            break;
          case "repeatT":
            if (fieldValues[0] === false) wrapT = ClampToEdgeWrapping;
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      if (texture) {
        texture.wrapS = wrapS;
        texture.wrapT = wrapT;
        texture.colorSpace = SRGBColorSpace;
      }
      return texture;
    }
    function buildTextureTransformNode(node) {
      const transformData = {
        center: new Vector2(),
        rotation: new Vector2(),
        scale: new Vector2(),
        translation: new Vector2()
      };
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "center":
            transformData.center.set(fieldValues[0], fieldValues[1]);
            break;
          case "rotation":
            transformData.rotation = fieldValues[0];
            break;
          case "scale":
            transformData.scale.set(fieldValues[0], fieldValues[1]);
            break;
          case "translation":
            transformData.translation.set(fieldValues[0], fieldValues[1]);
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      return transformData;
    }
    function buildGeometricNode(node) {
      return node.fields[0].values;
    }
    function buildWorldInfoNode(node) {
      const worldInfo = {};
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "title":
            worldInfo.title = fieldValues[0];
            break;
          case "info":
            worldInfo.info = fieldValues;
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      return worldInfo;
    }
    function buildIndexedFaceSetNode(node) {
      let color, coord, normal, texCoord;
      let ccw = true, solid = true, creaseAngle = 0;
      let colorIndex, coordIndex, normalIndex, texCoordIndex;
      let colorPerVertex = true, normalPerVertex = true;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "color":
            const colorNode = fieldValues[0];
            if (colorNode !== null) {
              color = getNode(colorNode);
            }
            break;
          case "coord":
            const coordNode = fieldValues[0];
            if (coordNode !== null) {
              coord = getNode(coordNode);
            }
            break;
          case "normal":
            const normalNode = fieldValues[0];
            if (normalNode !== null) {
              normal = getNode(normalNode);
            }
            break;
          case "texCoord":
            const texCoordNode = fieldValues[0];
            if (texCoordNode !== null) {
              texCoord = getNode(texCoordNode);
            }
            break;
          case "ccw":
            ccw = fieldValues[0];
            break;
          case "colorIndex":
            colorIndex = fieldValues;
            break;
          case "colorPerVertex":
            colorPerVertex = fieldValues[0];
            break;
          case "convex":
            break;
          case "coordIndex":
            coordIndex = fieldValues;
            break;
          case "creaseAngle":
            creaseAngle = fieldValues[0];
            break;
          case "normalIndex":
            normalIndex = fieldValues;
            break;
          case "normalPerVertex":
            normalPerVertex = fieldValues[0];
            break;
          case "solid":
            solid = fieldValues[0];
            break;
          case "texCoordIndex":
            texCoordIndex = fieldValues;
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      if (coordIndex === void 0) {
        console.warn("THREE.VRMLLoader: Missing coordIndex.");
        return new BufferGeometry();
      }
      const triangulatedCoordIndex = triangulateFaceIndex(coordIndex, ccw);
      let colorAttribute;
      let normalAttribute;
      let uvAttribute;
      if (color) {
        if (colorPerVertex === true) {
          if (colorIndex && colorIndex.length > 0) {
            const triangulatedColorIndex = triangulateFaceIndex(colorIndex, ccw);
            colorAttribute = computeAttributeFromIndexedData(triangulatedCoordIndex, triangulatedColorIndex, color, 3);
          } else {
            colorAttribute = toNonIndexedAttribute(triangulatedCoordIndex, new Float32BufferAttribute(color, 3));
          }
        } else {
          if (colorIndex && colorIndex.length > 0) {
            const flattenFaceColors = flattenData(color, colorIndex);
            const triangulatedFaceColors = triangulateFaceData(flattenFaceColors, coordIndex);
            colorAttribute = computeAttributeFromFaceData(triangulatedCoordIndex, triangulatedFaceColors);
          } else {
            const triangulatedFaceColors = triangulateFaceData(color, coordIndex);
            colorAttribute = computeAttributeFromFaceData(triangulatedCoordIndex, triangulatedFaceColors);
          }
        }
        convertColorsToLinearSRGB(colorAttribute);
      }
      if (normal) {
        if (normalPerVertex === true) {
          if (normalIndex && normalIndex.length > 0) {
            const triangulatedNormalIndex = triangulateFaceIndex(normalIndex, ccw);
            normalAttribute = computeAttributeFromIndexedData(triangulatedCoordIndex, triangulatedNormalIndex, normal, 3);
          } else {
            normalAttribute = toNonIndexedAttribute(triangulatedCoordIndex, new Float32BufferAttribute(normal, 3));
          }
        } else {
          if (normalIndex && normalIndex.length > 0) {
            const flattenFaceNormals = flattenData(normal, normalIndex);
            const triangulatedFaceNormals = triangulateFaceData(flattenFaceNormals, coordIndex);
            normalAttribute = computeAttributeFromFaceData(triangulatedCoordIndex, triangulatedFaceNormals);
          } else {
            const triangulatedFaceNormals = triangulateFaceData(normal, coordIndex);
            normalAttribute = computeAttributeFromFaceData(triangulatedCoordIndex, triangulatedFaceNormals);
          }
        }
      } else {
        normalAttribute = computeNormalAttribute(triangulatedCoordIndex, coord, creaseAngle);
      }
      if (texCoord) {
        if (texCoordIndex && texCoordIndex.length > 0) {
          const triangulatedTexCoordIndex = triangulateFaceIndex(texCoordIndex, ccw);
          uvAttribute = computeAttributeFromIndexedData(triangulatedCoordIndex, triangulatedTexCoordIndex, texCoord, 2);
        } else {
          uvAttribute = toNonIndexedAttribute(triangulatedCoordIndex, new Float32BufferAttribute(texCoord, 2));
        }
      }
      const geometry = new BufferGeometry();
      const positionAttribute = toNonIndexedAttribute(triangulatedCoordIndex, new Float32BufferAttribute(coord, 3));
      geometry.setAttribute("position", positionAttribute);
      geometry.setAttribute("normal", normalAttribute);
      if (colorAttribute) geometry.setAttribute("color", colorAttribute);
      if (uvAttribute) geometry.setAttribute("uv", uvAttribute);
      geometry._solid = solid;
      geometry._type = "mesh";
      return geometry;
    }
    function buildIndexedLineSetNode(node) {
      let color, coord;
      let colorIndex, coordIndex;
      let colorPerVertex = true;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "color":
            const colorNode = fieldValues[0];
            if (colorNode !== null) {
              color = getNode(colorNode);
            }
            break;
          case "coord":
            const coordNode = fieldValues[0];
            if (coordNode !== null) {
              coord = getNode(coordNode);
            }
            break;
          case "colorIndex":
            colorIndex = fieldValues;
            break;
          case "colorPerVertex":
            colorPerVertex = fieldValues[0];
            break;
          case "coordIndex":
            coordIndex = fieldValues;
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      let colorAttribute;
      const expandedLineIndex = expandLineIndex(coordIndex);
      if (color) {
        if (colorPerVertex === true) {
          if (colorIndex.length > 0) {
            const expandedColorIndex = expandLineIndex(colorIndex);
            colorAttribute = computeAttributeFromIndexedData(expandedLineIndex, expandedColorIndex, color, 3);
          } else {
            colorAttribute = toNonIndexedAttribute(expandedLineIndex, new Float32BufferAttribute(color, 3));
          }
        } else {
          if (colorIndex.length > 0) {
            const flattenLineColors = flattenData(color, colorIndex);
            const expandedLineColors = expandLineData(flattenLineColors, coordIndex);
            colorAttribute = computeAttributeFromLineData(expandedLineIndex, expandedLineColors);
          } else {
            const expandedLineColors = expandLineData(color, coordIndex);
            colorAttribute = computeAttributeFromLineData(expandedLineIndex, expandedLineColors);
          }
        }
        convertColorsToLinearSRGB(colorAttribute);
      }
      const geometry = new BufferGeometry();
      const positionAttribute = toNonIndexedAttribute(expandedLineIndex, new Float32BufferAttribute(coord, 3));
      geometry.setAttribute("position", positionAttribute);
      if (colorAttribute) geometry.setAttribute("color", colorAttribute);
      geometry._type = "line";
      return geometry;
    }
    function buildPointSetNode(node) {
      let color, coord;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "color":
            const colorNode = fieldValues[0];
            if (colorNode !== null) {
              color = getNode(colorNode);
            }
            break;
          case "coord":
            const coordNode = fieldValues[0];
            if (coordNode !== null) {
              coord = getNode(coordNode);
            }
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      const geometry = new BufferGeometry();
      geometry.setAttribute("position", new Float32BufferAttribute(coord, 3));
      if (color) {
        const colorAttribute = new Float32BufferAttribute(color, 3);
        convertColorsToLinearSRGB(colorAttribute);
        geometry.setAttribute("color", colorAttribute);
      }
      geometry._type = "points";
      return geometry;
    }
    function buildBoxNode(node) {
      const size2 = new Vector3(2, 2, 2);
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "size":
            size2.x = fieldValues[0];
            size2.y = fieldValues[1];
            size2.z = fieldValues[2];
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      const geometry = new BoxGeometry(size2.x, size2.y, size2.z);
      return geometry;
    }
    function buildConeNode(node) {
      let radius = 1, height2 = 2, openEnded = false;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "bottom":
            openEnded = !fieldValues[0];
            break;
          case "bottomRadius":
            radius = fieldValues[0];
            break;
          case "height":
            height2 = fieldValues[0];
            break;
          case "side":
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      const geometry = new ConeGeometry(radius, height2, 16, 1, openEnded);
      return geometry;
    }
    function buildCylinderNode(node) {
      let radius = 1, height2 = 2;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "bottom":
            break;
          case "radius":
            radius = fieldValues[0];
            break;
          case "height":
            height2 = fieldValues[0];
            break;
          case "side":
            break;
          case "top":
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      const geometry = new CylinderGeometry(radius, radius, height2, 16, 1);
      return geometry;
    }
    function buildSphereNode(node) {
      let radius = 1;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "radius":
            radius = fieldValues[0];
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      const geometry = new SphereGeometry(radius, 16, 16);
      return geometry;
    }
    function buildElevationGridNode(node) {
      let color;
      let normal;
      let texCoord;
      let height2;
      let colorPerVertex = true;
      let normalPerVertex = true;
      let solid = true;
      let ccw = true;
      let creaseAngle = 0;
      let xDimension = 2;
      let zDimension = 2;
      let xSpacing = 1;
      let zSpacing = 1;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "color":
            const colorNode = fieldValues[0];
            if (colorNode !== null) {
              color = getNode(colorNode);
            }
            break;
          case "normal":
            const normalNode = fieldValues[0];
            if (normalNode !== null) {
              normal = getNode(normalNode);
            }
            break;
          case "texCoord":
            const texCoordNode = fieldValues[0];
            if (texCoordNode !== null) {
              texCoord = getNode(texCoordNode);
            }
            break;
          case "height":
            height2 = fieldValues;
            break;
          case "ccw":
            ccw = fieldValues[0];
            break;
          case "colorPerVertex":
            colorPerVertex = fieldValues[0];
            break;
          case "creaseAngle":
            creaseAngle = fieldValues[0];
            break;
          case "normalPerVertex":
            normalPerVertex = fieldValues[0];
            break;
          case "solid":
            solid = fieldValues[0];
            break;
          case "xDimension":
            xDimension = fieldValues[0];
            break;
          case "xSpacing":
            xSpacing = fieldValues[0];
            break;
          case "zDimension":
            zDimension = fieldValues[0];
            break;
          case "zSpacing":
            zSpacing = fieldValues[0];
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      const vertices = [];
      const normals = [];
      const colors = [];
      const uvs = [];
      for (let i = 0; i < zDimension; i++) {
        for (let j2 = 0; j2 < xDimension; j2++) {
          const index2 = i * xDimension + j2;
          const x2 = xSpacing * i;
          const y = height2[index2];
          const z = zSpacing * j2;
          vertices.push(x2, y, z);
          if (color && colorPerVertex === true) {
            const r = color[index2 * 3 + 0];
            const g3 = color[index2 * 3 + 1];
            const b3 = color[index2 * 3 + 2];
            colors.push(r, g3, b3);
          }
          if (normal && normalPerVertex === true) {
            const xn2 = normal[index2 * 3 + 0];
            const yn = normal[index2 * 3 + 1];
            const zn = normal[index2 * 3 + 2];
            normals.push(xn2, yn, zn);
          }
          if (texCoord) {
            const s = texCoord[index2 * 2 + 0];
            const t3 = texCoord[index2 * 2 + 1];
            uvs.push(s, t3);
          } else {
            uvs.push(i / (xDimension - 1), j2 / (zDimension - 1));
          }
        }
      }
      const indices = [];
      for (let i = 0; i < xDimension - 1; i++) {
        for (let j2 = 0; j2 < zDimension - 1; j2++) {
          const a2 = i + j2 * xDimension;
          const b3 = i + (j2 + 1) * xDimension;
          const c2 = i + 1 + (j2 + 1) * xDimension;
          const d = i + 1 + j2 * xDimension;
          if (ccw === true) {
            indices.push(a2, c2, b3);
            indices.push(c2, a2, d);
          } else {
            indices.push(a2, b3, c2);
            indices.push(c2, d, a2);
          }
        }
      }
      const positionAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(vertices, 3));
      const uvAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(uvs, 2));
      let colorAttribute;
      let normalAttribute;
      if (color) {
        if (colorPerVertex === false) {
          for (let i = 0; i < xDimension - 1; i++) {
            for (let j2 = 0; j2 < zDimension - 1; j2++) {
              const index2 = i + j2 * (xDimension - 1);
              const r = color[index2 * 3 + 0];
              const g3 = color[index2 * 3 + 1];
              const b3 = color[index2 * 3 + 2];
              colors.push(r, g3, b3);
              colors.push(r, g3, b3);
              colors.push(r, g3, b3);
              colors.push(r, g3, b3);
              colors.push(r, g3, b3);
              colors.push(r, g3, b3);
            }
          }
          colorAttribute = new Float32BufferAttribute(colors, 3);
        } else {
          colorAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(colors, 3));
        }
        convertColorsToLinearSRGB(colorAttribute);
      }
      if (normal) {
        if (normalPerVertex === false) {
          for (let i = 0; i < xDimension - 1; i++) {
            for (let j2 = 0; j2 < zDimension - 1; j2++) {
              const index2 = i + j2 * (xDimension - 1);
              const xn2 = normal[index2 * 3 + 0];
              const yn = normal[index2 * 3 + 1];
              const zn = normal[index2 * 3 + 2];
              normals.push(xn2, yn, zn);
              normals.push(xn2, yn, zn);
              normals.push(xn2, yn, zn);
              normals.push(xn2, yn, zn);
              normals.push(xn2, yn, zn);
              normals.push(xn2, yn, zn);
            }
          }
          normalAttribute = new Float32BufferAttribute(normals, 3);
        } else {
          normalAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(normals, 3));
        }
      } else {
        normalAttribute = computeNormalAttribute(indices, vertices, creaseAngle);
      }
      const geometry = new BufferGeometry();
      geometry.setAttribute("position", positionAttribute);
      geometry.setAttribute("normal", normalAttribute);
      geometry.setAttribute("uv", uvAttribute);
      if (colorAttribute) geometry.setAttribute("color", colorAttribute);
      geometry._solid = solid;
      geometry._type = "mesh";
      return geometry;
    }
    function buildExtrusionNode(node) {
      let crossSection = [1, 1, 1, -1, -1, -1, -1, 1, 1, 1];
      let spine = [0, 0, 0, 0, 1, 0];
      let scale2;
      let orientation;
      let beginCap = true;
      let ccw = true;
      let creaseAngle = 0;
      let endCap = true;
      let solid = true;
      const fields = node.fields;
      for (let i = 0, l2 = fields.length; i < l2; i++) {
        const field = fields[i];
        const fieldName = field.name;
        const fieldValues = field.values;
        switch (fieldName) {
          case "beginCap":
            beginCap = fieldValues[0];
            break;
          case "ccw":
            ccw = fieldValues[0];
            break;
          case "convex":
            break;
          case "creaseAngle":
            creaseAngle = fieldValues[0];
            break;
          case "crossSection":
            crossSection = fieldValues;
            break;
          case "endCap":
            endCap = fieldValues[0];
            break;
          case "orientation":
            orientation = fieldValues;
            break;
          case "scale":
            scale2 = fieldValues;
            break;
          case "solid":
            solid = fieldValues[0];
            break;
          case "spine":
            spine = fieldValues;
            break;
          default:
            console.warn("THREE.VRMLLoader: Unknown field:", fieldName);
            break;
        }
      }
      const crossSectionClosed = crossSection[0] === crossSection[crossSection.length - 2] && crossSection[1] === crossSection[crossSection.length - 1];
      const vertices = [];
      const spineVector = new Vector3();
      const scaling = new Vector3();
      const axis = new Vector3();
      const vertex = new Vector3();
      const quaternion = new Quaternion();
      for (let i = 0, j2 = 0, o = 0, il = spine.length; i < il; i += 3, j2 += 2, o += 4) {
        spineVector.fromArray(spine, i);
        scaling.x = scale2 ? scale2[j2 + 0] : 1;
        scaling.y = 1;
        scaling.z = scale2 ? scale2[j2 + 1] : 1;
        axis.x = orientation ? orientation[o + 0] : 0;
        axis.y = orientation ? orientation[o + 1] : 0;
        axis.z = orientation ? orientation[o + 2] : 1;
        const angle = orientation ? orientation[o + 3] : 0;
        for (let k2 = 0, kl = crossSection.length; k2 < kl; k2 += 2) {
          vertex.x = crossSection[k2 + 0];
          vertex.y = 0;
          vertex.z = crossSection[k2 + 1];
          vertex.multiply(scaling);
          quaternion.setFromAxisAngle(axis, angle);
          vertex.applyQuaternion(quaternion);
          vertex.add(spineVector);
          vertices.push(vertex.x, vertex.y, vertex.z);
        }
      }
      const indices = [];
      const spineCount = spine.length / 3;
      const crossSectionCount = crossSection.length / 2;
      for (let i = 0; i < spineCount - 1; i++) {
        for (let j2 = 0; j2 < crossSectionCount - 1; j2++) {
          const a2 = j2 + i * crossSectionCount;
          let b3 = j2 + 1 + i * crossSectionCount;
          const c2 = j2 + (i + 1) * crossSectionCount;
          let d = j2 + 1 + (i + 1) * crossSectionCount;
          if (j2 === crossSectionCount - 2 && crossSectionClosed === true) {
            b3 = i * crossSectionCount;
            d = (i + 1) * crossSectionCount;
          }
          if (ccw === true) {
            indices.push(a2, b3, c2);
            indices.push(c2, b3, d);
          } else {
            indices.push(a2, c2, b3);
            indices.push(c2, d, b3);
          }
        }
      }
      if (beginCap === true || endCap === true) {
        const contour = [];
        for (let i = 0, l2 = crossSection.length; i < l2; i += 2) {
          contour.push(new Vector2(crossSection[i], crossSection[i + 1]));
        }
        const faces = ShapeUtils.triangulateShape(contour, []);
        const capIndices = [];
        for (let i = 0, l2 = faces.length; i < l2; i++) {
          const face = faces[i];
          capIndices.push(face[0], face[1], face[2]);
        }
        if (beginCap === true) {
          for (let i = 0, l2 = capIndices.length; i < l2; i += 3) {
            if (ccw === true) {
              indices.push(capIndices[i + 0], capIndices[i + 1], capIndices[i + 2]);
            } else {
              indices.push(capIndices[i + 0], capIndices[i + 2], capIndices[i + 1]);
            }
          }
        }
        if (endCap === true) {
          const indexOffset = crossSectionCount * (spineCount - 1);
          for (let i = 0, l2 = capIndices.length; i < l2; i += 3) {
            if (ccw === true) {
              indices.push(indexOffset + capIndices[i + 0], indexOffset + capIndices[i + 2], indexOffset + capIndices[i + 1]);
            } else {
              indices.push(indexOffset + capIndices[i + 0], indexOffset + capIndices[i + 1], indexOffset + capIndices[i + 2]);
            }
          }
        }
      }
      const positionAttribute = toNonIndexedAttribute(indices, new Float32BufferAttribute(vertices, 3));
      const normalAttribute = computeNormalAttribute(indices, vertices, creaseAngle);
      const geometry = new BufferGeometry();
      geometry.setAttribute("position", positionAttribute);
      geometry.setAttribute("normal", normalAttribute);
      geometry._solid = solid;
      geometry._type = "mesh";
      return geometry;
    }
    function resolveUSE(identifier) {
      const node = nodeMap[identifier];
      const build = getNode(node);
      return build.isObject3D || build.isMaterial ? build.clone() : build;
    }
    function parseFieldChildren(children, owner) {
      for (let i = 0, l2 = children.length; i < l2; i++) {
        const object = getNode(children[i]);
        if (object instanceof Object3D) owner.add(object);
      }
    }
    function triangulateFaceIndex(index2, ccw) {
      const indices = [];
      let start = 0;
      for (let i = 0, l2 = index2.length; i < l2; i++) {
        const i1 = index2[start];
        const i2 = index2[i + (ccw ? 1 : 2)];
        const i3 = index2[i + (ccw ? 2 : 1)];
        indices.push(i1, i2, i3);
        if (index2[i + 3] === -1 || i + 3 >= l2) {
          i += 3;
          start = i + 1;
        }
      }
      return indices;
    }
    function triangulateFaceData(data3, index2) {
      const triangulatedData = [];
      let start = 0;
      for (let i = 0, l2 = index2.length; i < l2; i++) {
        const stride = start * 3;
        const x2 = data3[stride];
        const y = data3[stride + 1];
        const z = data3[stride + 2];
        triangulatedData.push(x2, y, z);
        if (index2[i + 3] === -1 || i + 3 >= l2) {
          i += 3;
          start++;
        }
      }
      return triangulatedData;
    }
    function flattenData(data3, index2) {
      const flattenData2 = [];
      for (let i = 0, l2 = index2.length; i < l2; i++) {
        const i1 = index2[i];
        const stride = i1 * 3;
        const x2 = data3[stride];
        const y = data3[stride + 1];
        const z = data3[stride + 2];
        flattenData2.push(x2, y, z);
      }
      return flattenData2;
    }
    function expandLineIndex(index2) {
      const indices = [];
      for (let i = 0, l2 = index2.length; i < l2; i++) {
        const i1 = index2[i];
        const i2 = index2[i + 1];
        indices.push(i1, i2);
        if (index2[i + 2] === -1 || i + 2 >= l2) {
          i += 2;
        }
      }
      return indices;
    }
    function expandLineData(data3, index2) {
      const triangulatedData = [];
      let start = 0;
      for (let i = 0, l2 = index2.length; i < l2; i++) {
        const stride = start * 3;
        const x2 = data3[stride];
        const y = data3[stride + 1];
        const z = data3[stride + 2];
        triangulatedData.push(x2, y, z);
        if (index2[i + 2] === -1 || i + 2 >= l2) {
          i += 2;
          start++;
        }
      }
      return triangulatedData;
    }
    const vA = new Vector3();
    const vB = new Vector3();
    const vC = new Vector3();
    const uvA = new Vector2();
    const uvB = new Vector2();
    const uvC = new Vector2();
    function computeAttributeFromIndexedData(coordIndex, index2, data3, itemSize) {
      const array = [];
      for (let i = 0, l2 = coordIndex.length; i < l2; i += 3) {
        const a2 = index2[i];
        const b3 = index2[i + 1];
        const c2 = index2[i + 2];
        if (itemSize === 2) {
          uvA.fromArray(data3, a2 * itemSize);
          uvB.fromArray(data3, b3 * itemSize);
          uvC.fromArray(data3, c2 * itemSize);
          array.push(uvA.x, uvA.y);
          array.push(uvB.x, uvB.y);
          array.push(uvC.x, uvC.y);
        } else {
          vA.fromArray(data3, a2 * itemSize);
          vB.fromArray(data3, b3 * itemSize);
          vC.fromArray(data3, c2 * itemSize);
          array.push(vA.x, vA.y, vA.z);
          array.push(vB.x, vB.y, vB.z);
          array.push(vC.x, vC.y, vC.z);
        }
      }
      return new Float32BufferAttribute(array, itemSize);
    }
    function computeAttributeFromFaceData(index2, faceData) {
      const array = [];
      for (let i = 0, j2 = 0, l2 = index2.length; i < l2; i += 3, j2++) {
        vA.fromArray(faceData, j2 * 3);
        array.push(vA.x, vA.y, vA.z);
        array.push(vA.x, vA.y, vA.z);
        array.push(vA.x, vA.y, vA.z);
      }
      return new Float32BufferAttribute(array, 3);
    }
    function computeAttributeFromLineData(index2, lineData) {
      const array = [];
      for (let i = 0, j2 = 0, l2 = index2.length; i < l2; i += 2, j2++) {
        vA.fromArray(lineData, j2 * 3);
        array.push(vA.x, vA.y, vA.z);
        array.push(vA.x, vA.y, vA.z);
      }
      return new Float32BufferAttribute(array, 3);
    }
    function toNonIndexedAttribute(indices, attribute) {
      const array = attribute.array;
      const itemSize = attribute.itemSize;
      const array2 = new array.constructor(indices.length * itemSize);
      let index2 = 0, index22 = 0;
      for (let i = 0, l2 = indices.length; i < l2; i++) {
        index2 = indices[i] * itemSize;
        for (let j2 = 0; j2 < itemSize; j2++) {
          array2[index22++] = array[index2++];
        }
      }
      return new Float32BufferAttribute(array2, itemSize);
    }
    const ab = new Vector3();
    const cb = new Vector3();
    function computeNormalAttribute(index2, coord, creaseAngle) {
      const faces = [];
      const vertexNormals = {};
      for (let i = 0, l2 = index2.length; i < l2; i += 3) {
        const a2 = index2[i];
        const b3 = index2[i + 1];
        const c2 = index2[i + 2];
        const face = new Face2(a2, b3, c2);
        vA.fromArray(coord, a2 * 3);
        vB.fromArray(coord, b3 * 3);
        vC.fromArray(coord, c2 * 3);
        cb.subVectors(vC, vB);
        ab.subVectors(vA, vB);
        cb.cross(ab);
        cb.normalize();
        face.normal.copy(cb);
        if (vertexNormals[a2] === void 0) vertexNormals[a2] = [];
        if (vertexNormals[b3] === void 0) vertexNormals[b3] = [];
        if (vertexNormals[c2] === void 0) vertexNormals[c2] = [];
        vertexNormals[a2].push(face.normal);
        vertexNormals[b3].push(face.normal);
        vertexNormals[c2].push(face.normal);
        faces.push(face);
      }
      const normals = [];
      for (let i = 0, l2 = faces.length; i < l2; i++) {
        const face = faces[i];
        const nA = weightedNormal(vertexNormals[face.a], face.normal, creaseAngle);
        const nB = weightedNormal(vertexNormals[face.b], face.normal, creaseAngle);
        const nC = weightedNormal(vertexNormals[face.c], face.normal, creaseAngle);
        vA.fromArray(coord, face.a * 3);
        vB.fromArray(coord, face.b * 3);
        vC.fromArray(coord, face.c * 3);
        normals.push(nA.x, nA.y, nA.z);
        normals.push(nB.x, nB.y, nB.z);
        normals.push(nC.x, nC.y, nC.z);
      }
      return new Float32BufferAttribute(normals, 3);
    }
    function weightedNormal(normals, vector, creaseAngle) {
      const normal = new Vector3();
      if (creaseAngle === 0) {
        normal.copy(vector);
      } else {
        for (let i = 0, l2 = normals.length; i < l2; i++) {
          if (normals[i].angleTo(vector) < creaseAngle) {
            normal.add(normals[i]);
          }
        }
      }
      return normal.normalize();
    }
    function toColorArray(colors) {
      const array = [];
      for (let i = 0, l2 = colors.length; i < l2; i += 3) {
        array.push(new Color(colors[i], colors[i + 1], colors[i + 2]));
      }
      return array;
    }
    function convertColorsToLinearSRGB(attribute) {
      const color = new Color();
      for (let i = 0; i < attribute.count; i++) {
        color.fromBufferAttribute(attribute, i);
        ColorManagement.colorSpaceToWorking(color, SRGBColorSpace);
        attribute.setXYZ(i, color.r, color.g, color.b);
      }
    }
    function paintFaces(geometry, radius, angles, colors, topDown) {
      const thresholds = [];
      const startAngle = topDown === true ? 0 : Math.PI;
      for (let i = 0, l2 = colors.length; i < l2; i++) {
        let angle = i === 0 ? 0 : angles[i - 1];
        angle = topDown === true ? angle : startAngle - angle;
        const point = new Vector3();
        point.setFromSphericalCoords(radius, angle, 0);
        thresholds.push(point);
      }
      const indices = geometry.index;
      const positionAttribute = geometry.attributes.position;
      const colorAttribute = new BufferAttribute(new Float32Array(geometry.attributes.position.count * 3), 3);
      const position2 = new Vector3();
      const color = new Color();
      for (let i = 0; i < indices.count; i++) {
        const index2 = indices.getX(i);
        position2.fromBufferAttribute(positionAttribute, index2);
        let thresholdIndexA, thresholdIndexB;
        let t3 = 1;
        for (let j2 = 1; j2 < thresholds.length; j2++) {
          thresholdIndexA = j2 - 1;
          thresholdIndexB = j2;
          const thresholdA = thresholds[thresholdIndexA];
          const thresholdB = thresholds[thresholdIndexB];
          if (topDown === true) {
            if (position2.y <= thresholdA.y && position2.y > thresholdB.y) {
              t3 = Math.abs(thresholdA.y - position2.y) / Math.abs(thresholdA.y - thresholdB.y);
              break;
            }
          } else {
            if (position2.y >= thresholdA.y && position2.y < thresholdB.y) {
              t3 = Math.abs(thresholdA.y - position2.y) / Math.abs(thresholdA.y - thresholdB.y);
              break;
            }
          }
        }
        const colorA = colors[thresholdIndexA];
        const colorB = colors[thresholdIndexB];
        color.copy(colorA).lerp(colorB, t3);
        ColorManagement.colorSpaceToWorking(color, SRGBColorSpace);
        colorAttribute.setXYZ(index2, color.r, color.g, color.b);
      }
      geometry.setAttribute("color", colorAttribute);
    }
    const textureLoader = new TextureLoader(this.manager);
    textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
    if (data2.indexOf("#VRML V2.0") === -1) {
      throw Error("THREE.VRMLLexer: Version of VRML asset not supported.");
    }
    const tree = generateVRMLTree(data2);
    const scene = parseTree(tree);
    return scene;
  }
};
var VRMLLexer = class {
  constructor(tokens) {
    this.lexer = new chevrotain_module_min_default.Lexer(tokens);
  }
  lex(inputText) {
    const lexingResult = this.lexer.tokenize(inputText);
    if (lexingResult.errors.length > 0) {
      console.error(lexingResult.errors);
      throw Error("THREE.VRMLLexer: Lexing errors detected.");
    }
    return lexingResult;
  }
};
var CstParser = chevrotain_module_min_default.CstParser;
var VRMLParser = class extends CstParser {
  constructor(tokenVocabulary) {
    super(tokenVocabulary);
    const $2 = this;
    const Version = tokenVocabulary["Version"];
    const LCurly = tokenVocabulary["LCurly"];
    const RCurly = tokenVocabulary["RCurly"];
    const LSquare = tokenVocabulary["LSquare"];
    const RSquare = tokenVocabulary["RSquare"];
    const Identifier = tokenVocabulary["Identifier"];
    const RouteIdentifier = tokenVocabulary["RouteIdentifier"];
    const StringLiteral = tokenVocabulary["StringLiteral"];
    const HexLiteral = tokenVocabulary["HexLiteral"];
    const NumberLiteral = tokenVocabulary["NumberLiteral"];
    const TrueLiteral = tokenVocabulary["TrueLiteral"];
    const FalseLiteral = tokenVocabulary["FalseLiteral"];
    const NullLiteral = tokenVocabulary["NullLiteral"];
    const DEF = tokenVocabulary["DEF"];
    const USE = tokenVocabulary["USE"];
    const ROUTE = tokenVocabulary["ROUTE"];
    const TO = tokenVocabulary["TO"];
    const NodeName = tokenVocabulary["NodeName"];
    $2.RULE("vrml", function() {
      $2.SUBRULE($2.version);
      $2.AT_LEAST_ONE(function() {
        $2.SUBRULE($2.node);
      });
      $2.MANY(function() {
        $2.SUBRULE($2.route);
      });
    });
    $2.RULE("version", function() {
      $2.CONSUME(Version);
    });
    $2.RULE("node", function() {
      $2.OPTION(function() {
        $2.SUBRULE($2.def);
      });
      $2.CONSUME(NodeName);
      $2.CONSUME(LCurly);
      $2.MANY(function() {
        $2.SUBRULE($2.field);
      });
      $2.CONSUME(RCurly);
    });
    $2.RULE("field", function() {
      $2.CONSUME(Identifier);
      $2.OR2([
        { ALT: function() {
          $2.SUBRULE($2.singleFieldValue);
        } },
        { ALT: function() {
          $2.SUBRULE($2.multiFieldValue);
        } }
      ]);
    });
    $2.RULE("def", function() {
      $2.CONSUME(DEF);
      $2.OR([
        { ALT: function() {
          $2.CONSUME(Identifier);
        } },
        { ALT: function() {
          $2.CONSUME(NodeName);
        } }
      ]);
    });
    $2.RULE("use", function() {
      $2.CONSUME(USE);
      $2.OR([
        { ALT: function() {
          $2.CONSUME(Identifier);
        } },
        { ALT: function() {
          $2.CONSUME(NodeName);
        } }
      ]);
    });
    $2.RULE("singleFieldValue", function() {
      $2.AT_LEAST_ONE(function() {
        $2.OR([
          { ALT: function() {
            $2.SUBRULE($2.node);
          } },
          { ALT: function() {
            $2.SUBRULE($2.use);
          } },
          { ALT: function() {
            $2.CONSUME(StringLiteral);
          } },
          { ALT: function() {
            $2.CONSUME(HexLiteral);
          } },
          { ALT: function() {
            $2.CONSUME(NumberLiteral);
          } },
          { ALT: function() {
            $2.CONSUME(TrueLiteral);
          } },
          { ALT: function() {
            $2.CONSUME(FalseLiteral);
          } },
          { ALT: function() {
            $2.CONSUME(NullLiteral);
          } }
        ]);
      });
    });
    $2.RULE("multiFieldValue", function() {
      $2.CONSUME(LSquare);
      $2.MANY(function() {
        $2.OR([
          { ALT: function() {
            $2.SUBRULE($2.node);
          } },
          { ALT: function() {
            $2.SUBRULE($2.use);
          } },
          { ALT: function() {
            $2.CONSUME(StringLiteral);
          } },
          { ALT: function() {
            $2.CONSUME(HexLiteral);
          } },
          { ALT: function() {
            $2.CONSUME(NumberLiteral);
          } },
          { ALT: function() {
            $2.CONSUME(NullLiteral);
          } }
        ]);
      });
      $2.CONSUME(RSquare);
    });
    $2.RULE("route", function() {
      $2.CONSUME(ROUTE);
      $2.CONSUME(RouteIdentifier);
      $2.CONSUME(TO);
      $2.CONSUME2(RouteIdentifier);
    });
    this.performSelfAnalysis();
  }
};
var Face2 = class {
  constructor(a2, b3, c2) {
    this.a = a2;
    this.b = b3;
    this.c = c2;
    this.normal = new Vector3();
  }
};
var TEXTURE_TYPE = {
  INTENSITY: 1,
  INTENSITY_ALPHA: 2,
  RGB: 3,
  RGBA: 4
};

// node_modules/three/examples/jsm/loaders/VTKLoader.js
var VTKLoader = class extends Loader {
  /**
   * Constructs a new VTK loader.
   *
   * @param {LoadingManager} [manager] - The loading manager.
   */
  constructor(manager) {
    super(manager);
  }
  /**
   * Starts loading from the given URL and passes the loaded VRML asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(scope.manager);
    loader.setPath(scope.path);
    loader.setResponseType("arraybuffer");
    loader.setRequestHeader(scope.requestHeader);
    loader.setWithCredentials(scope.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given VTK data and returns the resulting geometry.
   *
   * @param {ArrayBuffer} data - The raw VTK data as an array buffer
   * @return {BufferGeometry} The parsed geometry.
   */
  parse(data2) {
    function parseASCII(data3) {
      const indices = [];
      const positions = [];
      const colors = [];
      const normals = [];
      let result;
      const patWord = /^[^\d.\s-]+/;
      const pat3Floats = /(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)/g;
      const patConnectivity = /^(\d+)\s+([\s\d]*)/;
      const patPOINTS = /^POINTS /;
      const patPOLYGONS = /^POLYGONS /;
      const patTRIANGLE_STRIPS = /^TRIANGLE_STRIPS /;
      const patPOINT_DATA = /^POINT_DATA[ ]+(\d+)/;
      const patCELL_DATA = /^CELL_DATA[ ]+(\d+)/;
      const patCOLOR_SCALARS = /^COLOR_SCALARS[ ]+(\w+)[ ]+3/;
      const patNORMALS = /^NORMALS[ ]+(\w+)[ ]+(\w+)/;
      let inPointsSection = false;
      let inPolygonsSection = false;
      let inTriangleStripSection = false;
      let inPointDataSection = false;
      let inCellDataSection = false;
      let inColorSection = false;
      let inNormalsSection = false;
      const color = new Color();
      const lines = data3.split("\n");
      for (const i in lines) {
        const line2 = lines[i].trim();
        if (line2.indexOf("DATASET") === 0) {
          const dataset = line2.split(" ")[1];
          if (dataset !== "POLYDATA") throw new Error("Unsupported DATASET type: " + dataset);
        } else if (inPointsSection) {
          while ((result = pat3Floats.exec(line2)) !== null) {
            if (patWord.exec(line2) !== null) break;
            const x2 = parseFloat(result[1]);
            const y = parseFloat(result[2]);
            const z = parseFloat(result[3]);
            positions.push(x2, y, z);
          }
        } else if (inPolygonsSection) {
          if ((result = patConnectivity.exec(line2)) !== null) {
            const numVertices = parseInt(result[1]);
            const inds = result[2].split(/\s+/);
            if (numVertices >= 3) {
              const i0 = parseInt(inds[0]);
              let k2 = 1;
              for (let j2 = 0; j2 < numVertices - 2; ++j2) {
                const i1 = parseInt(inds[k2]);
                const i2 = parseInt(inds[k2 + 1]);
                indices.push(i0, i1, i2);
                k2++;
              }
            }
          }
        } else if (inTriangleStripSection) {
          if ((result = patConnectivity.exec(line2)) !== null) {
            const numVertices = parseInt(result[1]);
            const inds = result[2].split(/\s+/);
            if (numVertices >= 3) {
              for (let j2 = 0; j2 < numVertices - 2; j2++) {
                if (j2 % 2 === 1) {
                  const i0 = parseInt(inds[j2]);
                  const i1 = parseInt(inds[j2 + 2]);
                  const i2 = parseInt(inds[j2 + 1]);
                  indices.push(i0, i1, i2);
                } else {
                  const i0 = parseInt(inds[j2]);
                  const i1 = parseInt(inds[j2 + 1]);
                  const i2 = parseInt(inds[j2 + 2]);
                  indices.push(i0, i1, i2);
                }
              }
            }
          }
        } else if (inPointDataSection || inCellDataSection) {
          if (inColorSection) {
            while ((result = pat3Floats.exec(line2)) !== null) {
              if (patWord.exec(line2) !== null) break;
              const r = parseFloat(result[1]);
              const g3 = parseFloat(result[2]);
              const b3 = parseFloat(result[3]);
              color.setRGB(r, g3, b3, SRGBColorSpace);
              colors.push(color.r, color.g, color.b);
            }
          } else if (inNormalsSection) {
            while ((result = pat3Floats.exec(line2)) !== null) {
              if (patWord.exec(line2) !== null) break;
              const nx = parseFloat(result[1]);
              const ny = parseFloat(result[2]);
              const nz = parseFloat(result[3]);
              normals.push(nx, ny, nz);
            }
          }
        }
        if (patPOLYGONS.exec(line2) !== null) {
          inPolygonsSection = true;
          inPointsSection = false;
          inTriangleStripSection = false;
        } else if (patPOINTS.exec(line2) !== null) {
          inPolygonsSection = false;
          inPointsSection = true;
          inTriangleStripSection = false;
        } else if (patTRIANGLE_STRIPS.exec(line2) !== null) {
          inPolygonsSection = false;
          inPointsSection = false;
          inTriangleStripSection = true;
        } else if (patPOINT_DATA.exec(line2) !== null) {
          inPointDataSection = true;
          inPointsSection = false;
          inPolygonsSection = false;
          inTriangleStripSection = false;
        } else if (patCELL_DATA.exec(line2) !== null) {
          inCellDataSection = true;
          inPointsSection = false;
          inPolygonsSection = false;
          inTriangleStripSection = false;
        } else if (patCOLOR_SCALARS.exec(line2) !== null) {
          inColorSection = true;
          inNormalsSection = false;
          inPointsSection = false;
          inPolygonsSection = false;
          inTriangleStripSection = false;
        } else if (patNORMALS.exec(line2) !== null) {
          inNormalsSection = true;
          inColorSection = false;
          inPointsSection = false;
          inPolygonsSection = false;
          inTriangleStripSection = false;
        }
      }
      let geometry = new BufferGeometry();
      geometry.setIndex(indices);
      geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
      if (normals.length === positions.length) {
        geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3));
      }
      if (colors.length !== indices.length) {
        if (colors.length === positions.length) {
          geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
        }
      } else {
        geometry = geometry.toNonIndexed();
        const numTriangles = geometry.attributes.position.count / 3;
        if (colors.length === numTriangles * 3) {
          const newColors = [];
          for (let i = 0; i < numTriangles; i++) {
            const r = colors[3 * i + 0];
            const g3 = colors[3 * i + 1];
            const b3 = colors[3 * i + 2];
            color.setRGB(r, g3, b3, SRGBColorSpace);
            newColors.push(color.r, color.g, color.b);
            newColors.push(color.r, color.g, color.b);
            newColors.push(color.r, color.g, color.b);
          }
          geometry.setAttribute("color", new Float32BufferAttribute(newColors, 3));
        }
      }
      return geometry;
    }
    function parseBinary(data3) {
      const buffer = new Uint8Array(data3);
      const dataView = new DataView(data3);
      let points = [];
      let normals = [];
      let indices = [];
      let index2 = 0;
      function findString(buffer2, start) {
        let index3 = start;
        let c2 = buffer2[index3];
        const s = [];
        while (c2 !== 10) {
          s.push(String.fromCharCode(c2));
          index3++;
          c2 = buffer2[index3];
        }
        return {
          start,
          end: index3,
          next: index3 + 1,
          parsedString: s.join("")
        };
      }
      let state, line2;
      while (true) {
        state = findString(buffer, index2);
        line2 = state.parsedString;
        if (line2.indexOf("DATASET") === 0) {
          const dataset = line2.split(" ")[1];
          if (dataset !== "POLYDATA") throw new Error("Unsupported DATASET type: " + dataset);
        } else if (line2.indexOf("POINTS") === 0) {
          const numberOfPoints = parseInt(line2.split(" ")[1], 10);
          const count = numberOfPoints * 4 * 3;
          points = new Float32Array(numberOfPoints * 3);
          let pointIndex = state.next;
          for (let i = 0; i < numberOfPoints; i++) {
            points[3 * i] = dataView.getFloat32(pointIndex, false);
            points[3 * i + 1] = dataView.getFloat32(pointIndex + 4, false);
            points[3 * i + 2] = dataView.getFloat32(pointIndex + 8, false);
            pointIndex = pointIndex + 12;
          }
          state.next = state.next + count + 1;
        } else if (line2.indexOf("TRIANGLE_STRIPS") === 0) {
          const numberOfStrips = parseInt(line2.split(" ")[1], 10);
          const size2 = parseInt(line2.split(" ")[2], 10);
          const count = size2 * 4;
          indices = new Uint32Array(3 * size2 - 9 * numberOfStrips);
          let indicesIndex = 0;
          let pointIndex = state.next;
          for (let i = 0; i < numberOfStrips; i++) {
            const indexCount = dataView.getInt32(pointIndex, false);
            const strip = [];
            pointIndex += 4;
            for (let s = 0; s < indexCount; s++) {
              strip.push(dataView.getInt32(pointIndex, false));
              pointIndex += 4;
            }
            for (let j2 = 0; j2 < indexCount - 2; j2++) {
              if (j2 % 2) {
                indices[indicesIndex++] = strip[j2];
                indices[indicesIndex++] = strip[j2 + 2];
                indices[indicesIndex++] = strip[j2 + 1];
              } else {
                indices[indicesIndex++] = strip[j2];
                indices[indicesIndex++] = strip[j2 + 1];
                indices[indicesIndex++] = strip[j2 + 2];
              }
            }
          }
          state.next = state.next + count + 1;
        } else if (line2.indexOf("POLYGONS") === 0) {
          const numberOfStrips = parseInt(line2.split(" ")[1], 10);
          const size2 = parseInt(line2.split(" ")[2], 10);
          const count = size2 * 4;
          indices = new Uint32Array(3 * size2 - 9 * numberOfStrips);
          let indicesIndex = 0;
          let pointIndex = state.next;
          for (let i = 0; i < numberOfStrips; i++) {
            const indexCount = dataView.getInt32(pointIndex, false);
            const strip = [];
            pointIndex += 4;
            for (let s = 0; s < indexCount; s++) {
              strip.push(dataView.getInt32(pointIndex, false));
              pointIndex += 4;
            }
            for (let j2 = 1; j2 < indexCount - 1; j2++) {
              indices[indicesIndex++] = strip[0];
              indices[indicesIndex++] = strip[j2];
              indices[indicesIndex++] = strip[j2 + 1];
            }
          }
          state.next = state.next + count + 1;
        } else if (line2.indexOf("POINT_DATA") === 0) {
          const numberOfPoints = parseInt(line2.split(" ")[1], 10);
          state = findString(buffer, state.next);
          const count = numberOfPoints * 4 * 3;
          normals = new Float32Array(numberOfPoints * 3);
          let pointIndex = state.next;
          for (let i = 0; i < numberOfPoints; i++) {
            normals[3 * i] = dataView.getFloat32(pointIndex, false);
            normals[3 * i + 1] = dataView.getFloat32(pointIndex + 4, false);
            normals[3 * i + 2] = dataView.getFloat32(pointIndex + 8, false);
            pointIndex += 12;
          }
          state.next = state.next + count;
        }
        index2 = state.next;
        if (index2 >= buffer.byteLength) {
          break;
        }
      }
      const geometry = new BufferGeometry();
      geometry.setIndex(new BufferAttribute(indices, 1));
      geometry.setAttribute("position", new BufferAttribute(points, 3));
      if (normals.length === points.length) {
        geometry.setAttribute("normal", new BufferAttribute(normals, 3));
      }
      return geometry;
    }
    function Float32Concat(first2, second) {
      const firstLength = first2.length, result = new Float32Array(firstLength + second.length);
      result.set(first2);
      result.set(second, firstLength);
      return result;
    }
    function Int32Concat(first2, second) {
      const firstLength = first2.length, result = new Int32Array(firstLength + second.length);
      result.set(first2);
      result.set(second, firstLength);
      return result;
    }
    function parseXML(stringFile) {
      function xmlToJson(xml) {
        let obj = {};
        if (xml.nodeType === 1) {
          if (xml.attributes) {
            if (xml.attributes.length > 0) {
              obj["attributes"] = {};
              for (let j2 = 0; j2 < xml.attributes.length; j2++) {
                const attribute = xml.attributes.item(j2);
                obj["attributes"][attribute.nodeName] = attribute.nodeValue.trim();
              }
            }
          }
        } else if (xml.nodeType === 3) {
          obj = xml.nodeValue.trim();
        }
        if (xml.hasChildNodes()) {
          for (let i = 0; i < xml.childNodes.length; i++) {
            const item = xml.childNodes.item(i);
            const nodeName = item.nodeName;
            if (typeof obj[nodeName] === "undefined") {
              const tmp = xmlToJson(item);
              if (tmp !== "") {
                if (Array.isArray(tmp["#text"])) {
                  tmp["#text"] = tmp["#text"][0];
                }
                obj[nodeName] = tmp;
              }
            } else {
              if (typeof obj[nodeName].push === "undefined") {
                const old = obj[nodeName];
                obj[nodeName] = [old];
              }
              const tmp = xmlToJson(item);
              if (tmp !== "") {
                if (Array.isArray(tmp["#text"])) {
                  tmp["#text"] = tmp["#text"][0];
                }
                obj[nodeName].push(tmp);
              }
            }
          }
        }
        return obj;
      }
      function Base64toByteArray(b64) {
        const Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
        const revLookup = [];
        const code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        for (let i2 = 0, l3 = code.length; i2 < l3; ++i2) {
          revLookup[code.charCodeAt(i2)] = i2;
        }
        revLookup["-".charCodeAt(0)] = 62;
        revLookup["_".charCodeAt(0)] = 63;
        const len = b64.length;
        if (len % 4 > 0) {
          throw new Error("Invalid string. Length must be a multiple of 4");
        }
        const placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0;
        const arr = new Arr(len * 3 / 4 - placeHolders);
        const l2 = placeHolders > 0 ? len - 4 : len;
        let L = 0;
        let i, j2;
        for (i = 0, j2 = 0; i < l2; i += 4, j2 += 3) {
          const tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
          arr[L++] = (tmp & 16711680) >> 16;
          arr[L++] = (tmp & 65280) >> 8;
          arr[L++] = tmp & 255;
        }
        if (placeHolders === 2) {
          const tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
          arr[L++] = tmp & 255;
        } else if (placeHolders === 1) {
          const tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
          arr[L++] = tmp >> 8 & 255;
          arr[L++] = tmp & 255;
        }
        return arr;
      }
      function parseDataArray(ele, compressed) {
        let numBytes = 0;
        if (json.attributes.header_type === "UInt64") {
          numBytes = 8;
        } else if (json.attributes.header_type === "UInt32") {
          numBytes = 4;
        }
        let txt, content2;
        if (ele.attributes.format === "binary" && compressed) {
          if (ele.attributes.type === "Float32") {
            txt = new Float32Array();
          } else if (ele.attributes.type === "Int32" || ele.attributes.type === "Int64") {
            txt = new Int32Array();
          }
          const textNode = ele["#text"];
          const rawData = Array.isArray(textNode) ? textNode[0] : textNode;
          const byteData = Base64toByteArray(rawData);
          const dataPointSize = 8;
          let blocks = byteData[0];
          for (let i = 1; i < numBytes - 1; i++) {
            blocks = blocks | byteData[i] << i * dataPointSize;
          }
          let headerSize = (blocks + 3) * numBytes;
          const padding = headerSize % 3 > 0 ? 3 - headerSize % 3 : 0;
          headerSize = headerSize + padding;
          const dataOffsets = [];
          let currentOffset = headerSize;
          dataOffsets.push(currentOffset);
          const cSizeStart = 3 * numBytes;
          for (let i = 0; i < blocks; i++) {
            let currentBlockSize = byteData[i * numBytes + cSizeStart];
            for (let j2 = 1; j2 < numBytes - 1; j2++) {
              currentBlockSize = currentBlockSize | byteData[i * numBytes + cSizeStart + j2] << j2 * dataPointSize;
            }
            currentOffset = currentOffset + currentBlockSize;
            dataOffsets.push(currentOffset);
          }
          for (let i = 0; i < dataOffsets.length - 1; i++) {
            const data3 = unzlibSync(byteData.slice(dataOffsets[i], dataOffsets[i + 1]));
            content2 = data3.buffer;
            if (ele.attributes.type === "Float32") {
              content2 = new Float32Array(content2);
              txt = Float32Concat(txt, content2);
            } else if (ele.attributes.type === "Int32" || ele.attributes.type === "Int64") {
              content2 = new Int32Array(content2);
              txt = Int32Concat(txt, content2);
            }
          }
          delete ele["#text"];
          if (ele.attributes.type === "Int64") {
            if (ele.attributes.format === "binary") {
              txt = txt.filter(function(el, idx) {
                if (idx % 2 !== 1) return true;
              });
            }
          }
        } else {
          if (ele.attributes.format === "binary" && !compressed) {
            content2 = Base64toByteArray(ele["#text"]);
            content2 = content2.slice(numBytes).buffer;
          } else {
            if (ele["#text"]) {
              content2 = ele["#text"].split(/\s+/).filter(function(el) {
                if (el !== "") return el;
              });
            } else {
              content2 = new Int32Array(0).buffer;
            }
          }
          delete ele["#text"];
          if (ele.attributes.type === "Float32") {
            txt = new Float32Array(content2);
          } else if (ele.attributes.type === "Int32") {
            txt = new Int32Array(content2);
          } else if (ele.attributes.type === "Int64") {
            txt = new Int32Array(content2);
            if (ele.attributes.format === "binary") {
              txt = txt.filter(function(el, idx) {
                if (idx % 2 !== 1) return true;
              });
            }
          }
        }
        return txt;
      }
      const dom = new DOMParser().parseFromString(stringFile, "application/xml");
      const doc = dom.documentElement;
      const json = xmlToJson(doc);
      let points = [];
      let normals = [];
      let indices = [];
      if (json.AppendedData) {
        const appendedData = json.AppendedData["#text"].slice(1);
        const piece = json.PolyData.Piece;
        const sections = ["PointData", "CellData", "Points", "Verts", "Lines", "Strips", "Polys"];
        let sectionIndex = 0;
        const offsets = sections.map((s) => {
          const sect = piece[s];
          if (sect && sect.DataArray) {
            const arr = Array.isArray(sect.DataArray) ? sect.DataArray : [sect.DataArray];
            return arr.map((a2) => a2.attributes.offset);
          }
          return [];
        }).flat();
        for (const sect of sections) {
          const section = piece[sect];
          if (section && section.DataArray) {
            if (Array.isArray(section.DataArray)) {
              for (const sectionEle of section.DataArray) {
                sectionEle["#text"] = appendedData.slice(offsets[sectionIndex], offsets[sectionIndex + 1]);
                sectionEle.attributes.format = "binary";
                sectionIndex++;
              }
            } else {
              section.DataArray["#text"] = appendedData.slice(offsets[sectionIndex], offsets[sectionIndex + 1]);
              section.DataArray.attributes.format = "binary";
              sectionIndex++;
            }
          }
        }
      }
      if (json.PolyData) {
        const piece = json.PolyData.Piece;
        const compressed = json.attributes.hasOwnProperty("compressor");
        const sections = ["PointData", "Points", "Strips", "Polys"];
        let sectionIndex = 0;
        const numberOfSections = sections.length;
        while (sectionIndex < numberOfSections) {
          const section = piece[sections[sectionIndex]];
          if (section && section.DataArray) {
            let arr;
            if (Array.isArray(section.DataArray)) {
              arr = section.DataArray;
            } else {
              arr = [section.DataArray];
            }
            let dataArrayIndex = 0;
            const numberOfDataArrays = arr.length;
            while (dataArrayIndex < numberOfDataArrays) {
              if ("#text" in arr[dataArrayIndex] && arr[dataArrayIndex]["#text"].length > 0) {
                arr[dataArrayIndex].text = parseDataArray(arr[dataArrayIndex], compressed);
              }
              dataArrayIndex++;
            }
            switch (sections[sectionIndex]) {
              // if iti is point data
              case "PointData":
                {
                  const numberOfPoints = parseInt(piece.attributes.NumberOfPoints);
                  const normalsName = section.attributes.Normals;
                  if (numberOfPoints > 0) {
                    for (let i = 0, len = arr.length; i < len; i++) {
                      if (normalsName === arr[i].attributes.Name) {
                        const components = arr[i].attributes.NumberOfComponents;
                        normals = new Float32Array(numberOfPoints * components);
                        normals.set(arr[i].text, 0);
                      }
                    }
                  }
                }
                break;
              // if it is points
              case "Points":
                {
                  const numberOfPoints = parseInt(piece.attributes.NumberOfPoints);
                  if (numberOfPoints > 0) {
                    const components = section.DataArray.attributes.NumberOfComponents;
                    points = new Float32Array(numberOfPoints * components);
                    points.set(section.DataArray.text, 0);
                  }
                }
                break;
              // if it is strips
              case "Strips":
                {
                  const numberOfStrips = parseInt(piece.attributes.NumberOfStrips);
                  if (numberOfStrips > 0) {
                    const connectivity = new Int32Array(section.DataArray[0].text.length);
                    const offset = new Int32Array(section.DataArray[1].text.length);
                    connectivity.set(section.DataArray[0].text, 0);
                    offset.set(section.DataArray[1].text, 0);
                    const size2 = numberOfStrips + connectivity.length;
                    indices = new Uint32Array(3 * size2 - 9 * numberOfStrips);
                    let indicesIndex = 0;
                    for (let i = 0, len = numberOfStrips; i < len; i++) {
                      const strip = [];
                      for (let s = 0, len1 = offset[i], len0 = 0; s < len1 - len0; s++) {
                        strip.push(connectivity[s]);
                        if (i > 0) len0 = offset[i - 1];
                      }
                      for (let j2 = 0, len1 = offset[i], len0 = 0; j2 < len1 - len0 - 2; j2++) {
                        if (j2 % 2) {
                          indices[indicesIndex++] = strip[j2];
                          indices[indicesIndex++] = strip[j2 + 2];
                          indices[indicesIndex++] = strip[j2 + 1];
                        } else {
                          indices[indicesIndex++] = strip[j2];
                          indices[indicesIndex++] = strip[j2 + 1];
                          indices[indicesIndex++] = strip[j2 + 2];
                        }
                        if (i > 0) len0 = offset[i - 1];
                      }
                    }
                  }
                }
                break;
              // if it is polys
              case "Polys":
                {
                  const numberOfPolys = parseInt(piece.attributes.NumberOfPolys);
                  if (numberOfPolys > 0) {
                    const connectivity = new Int32Array(section.DataArray[0].text.length);
                    const offset = new Int32Array(section.DataArray[1].text.length);
                    connectivity.set(section.DataArray[0].text, 0);
                    offset.set(section.DataArray[1].text, 0);
                    const size2 = numberOfPolys + connectivity.length;
                    indices = new Uint32Array(3 * size2 - 9 * numberOfPolys);
                    let indicesIndex = 0, connectivityIndex = 0;
                    let i = 0, len0 = 0;
                    const len = numberOfPolys;
                    while (i < len) {
                      const poly = [];
                      let s = 0;
                      const len1 = offset[i];
                      while (s < len1 - len0) {
                        poly.push(connectivity[connectivityIndex++]);
                        s++;
                      }
                      let j2 = 1;
                      while (j2 < len1 - len0 - 1) {
                        indices[indicesIndex++] = poly[0];
                        indices[indicesIndex++] = poly[j2];
                        indices[indicesIndex++] = poly[j2 + 1];
                        j2++;
                      }
                      i++;
                      len0 = offset[i - 1];
                    }
                  }
                }
                break;
              default:
                break;
            }
          }
          sectionIndex++;
        }
        const geometry = new BufferGeometry();
        geometry.setIndex(new BufferAttribute(indices, 1));
        geometry.setAttribute("position", new BufferAttribute(points, 3));
        if (normals.length === points.length) {
          geometry.setAttribute("normal", new BufferAttribute(normals, 3));
        }
        return geometry;
      } else {
        throw new Error("Unsupported DATASET type");
      }
    }
    const textDecoder = new TextDecoder();
    const meta2 = textDecoder.decode(new Uint8Array(data2, 0, 250)).split("\n");
    if (meta2[0].indexOf("xml") !== -1) {
      return parseXML(textDecoder.decode(data2));
    } else if (meta2[2].includes("ASCII")) {
      return parseASCII(textDecoder.decode(data2));
    } else {
      return parseBinary(data2);
    }
  }
};

// node_modules/three/examples/jsm/loaders/XYZLoader.js
var XYZLoader = class extends Loader {
  /**
   * Starts loading from the given URL and passes the loaded XYZ asset
   * to the `onLoad()` callback.
   *
   * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
   * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
   * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
   * @param {onErrorCallback} onError - Executed when errors occur.
   */
  load(url, onLoad, onProgress, onError) {
    const scope = this;
    const loader = new FileLoader(this.manager);
    loader.setPath(this.path);
    loader.setRequestHeader(this.requestHeader);
    loader.setWithCredentials(this.withCredentials);
    loader.load(url, function(text2) {
      try {
        onLoad(scope.parse(text2));
      } catch (e) {
        if (onError) {
          onError(e);
        } else {
          console.error(e);
        }
        scope.manager.itemError(url);
      }
    }, onProgress, onError);
  }
  /**
   * Parses the given XYZ data and returns the resulting geometry.
   *
   * @param {string} text - The raw XYZ data as a string.
   * @return {BufferGeometry} The geometry representing the point cloud.
   */
  parse(text2) {
    const lines = text2.split("\n");
    const vertices = [];
    const colors = [];
    const color = new Color();
    for (let line2 of lines) {
      line2 = line2.trim();
      if (line2.charAt(0) === "#") continue;
      const lineValues = line2.split(/\s+/);
      if (lineValues.length === 3) {
        vertices.push(parseFloat(lineValues[0]));
        vertices.push(parseFloat(lineValues[1]));
        vertices.push(parseFloat(lineValues[2]));
      }
      if (lineValues.length === 6) {
        vertices.push(parseFloat(lineValues[0]));
        vertices.push(parseFloat(lineValues[1]));
        vertices.push(parseFloat(lineValues[2]));
        const r = parseFloat(lineValues[3]) / 255;
        const g3 = parseFloat(lineValues[4]) / 255;
        const b3 = parseFloat(lineValues[5]) / 255;
        color.setRGB(r, g3, b3, SRGBColorSpace);
        colors.push(color.r, color.g, color.b);
      }
    }
    const geometry = new BufferGeometry();
    geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3));
    if (colors.length > 0) {
      geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));
    }
    return geometry;
  }
};

// node_modules/three/examples/jsm/materials/MeshGouraudMaterial.js
var GouraudShader = {
  name: "GouraudShader",
  uniforms: UniformsUtils.merge([
    UniformsLib.common,
    UniformsLib.specularmap,
    UniformsLib.envmap,
    UniformsLib.aomap,
    UniformsLib.lightmap,
    UniformsLib.emissivemap,
    UniformsLib.fog,
    UniformsLib.lights,
    {
      emissive: { value: new Color(0) }
    }
  ]),
  vertexShader: (
    /* glsl */
    `

		#define GOURAUD

		varying vec3 vLightFront;
		varying vec3 vIndirectFront;

		#ifdef DOUBLE_SIDED
			varying vec3 vLightBack;
			varying vec3 vIndirectBack;
		#endif

		#include <common>
		#include <uv_pars_vertex>
		#include <envmap_pars_vertex>
		#include <bsdfs>
		#include <lights_pars_begin>
		#include <color_pars_vertex>
		#include <fog_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 <beginnormal_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 <clipping_planes_vertex>

			#include <worldpos_vertex>
			#include <envmap_vertex>

			// inlining legacy <lights_lambert_vertex>

			vec3 diffuse = vec3( 1.0 );

			vec3 geometryPosition = mvPosition.xyz;
			vec3 geometryNormal = normalize( transformedNormal );
			vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );

			vec3 backGeometryNormal = - geometryNormal;

			vLightFront = vec3( 0.0 );
			vIndirectFront = vec3( 0.0 );
			#ifdef DOUBLE_SIDED
				vLightBack = vec3( 0.0 );
				vIndirectBack = vec3( 0.0 );
			#endif

			IncidentLight directLight;
			float dotNL;
			vec3 directLightColor_Diffuse;

			vIndirectFront += getAmbientLightIrradiance( ambientLightColor );

			#if defined( USE_LIGHT_PROBES )

				vIndirectFront += getLightProbeIrradiance( lightProbe, geometryNormal );

			#endif

			#ifdef DOUBLE_SIDED

				vIndirectBack += getAmbientLightIrradiance( ambientLightColor );

				#if defined( USE_LIGHT_PROBES )

					vIndirectBack += getLightProbeIrradiance( lightProbe, backGeometryNormal );

				#endif

			#endif

			#if NUM_POINT_LIGHTS > 0

				#pragma unroll_loop_start
				for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {

					getPointLightInfo( pointLights[ i ], geometryPosition, directLight );

					dotNL = dot( geometryNormal, directLight.direction );
					directLightColor_Diffuse = directLight.color;

					vLightFront += saturate( dotNL ) * directLightColor_Diffuse;

					#ifdef DOUBLE_SIDED

						vLightBack += saturate( - dotNL ) * directLightColor_Diffuse;

					#endif

				}
				#pragma unroll_loop_end

			#endif

			#if NUM_SPOT_LIGHTS > 0

				#pragma unroll_loop_start
				for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {

					getSpotLightInfo( spotLights[ i ], geometryPosition, directLight );

					dotNL = dot( geometryNormal, directLight.direction );
					directLightColor_Diffuse = directLight.color;

					vLightFront += saturate( dotNL ) * directLightColor_Diffuse;

					#ifdef DOUBLE_SIDED

						vLightBack += saturate( - dotNL ) * directLightColor_Diffuse;

					#endif
				}
				#pragma unroll_loop_end

			#endif

			#if NUM_DIR_LIGHTS > 0

				#pragma unroll_loop_start
				for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

					getDirectionalLightInfo( directionalLights[ i ], directLight );

					dotNL = dot( geometryNormal, directLight.direction );
					directLightColor_Diffuse = directLight.color;

					vLightFront += saturate( dotNL ) * directLightColor_Diffuse;

					#ifdef DOUBLE_SIDED

						vLightBack += saturate( - dotNL ) * directLightColor_Diffuse;

					#endif

				}
				#pragma unroll_loop_end

			#endif

			#if NUM_HEMI_LIGHTS > 0

				#pragma unroll_loop_start
				for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {

					vIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );

					#ifdef DOUBLE_SIDED

						vIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometryNormal );

					#endif

				}
				#pragma unroll_loop_end

			#endif

			#include <shadowmap_vertex>
			#include <fog_vertex>

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

		#define GOURAUD

		uniform vec3 diffuse;
		uniform vec3 emissive;
		uniform float opacity;

		varying vec3 vLightFront;
		varying vec3 vIndirectFront;

		#ifdef DOUBLE_SIDED
			varying vec3 vLightBack;
			varying vec3 vIndirectBack;
		#endif

		#include <common>
		#include <packing>
		#include <dithering_pars_fragment>
		#include <color_pars_fragment>
		#include <uv_pars_fragment>
		#include <map_pars_fragment>
		#include <alphamap_pars_fragment>
		#include <alphatest_pars_fragment>
		#include <aomap_pars_fragment>
		#include <lightmap_pars_fragment>
		#include <emissivemap_pars_fragment>
		#include <envmap_common_pars_fragment>
		#include <envmap_pars_fragment>
		#include <bsdfs>
		#include <lights_pars_begin>
		#include <fog_pars_fragment>
		#include <shadowmap_pars_fragment>
		#include <shadowmask_pars_fragment>
		#include <specularmap_pars_fragment>
		#include <logdepthbuf_pars_fragment>
		#include <clipping_planes_pars_fragment>

		void main() {

			#include <clipping_planes_fragment>

			vec4 diffuseColor = vec4( diffuse, opacity );
			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 <specularmap_fragment>
			#include <emissivemap_fragment>

			// accumulation

			#ifdef DOUBLE_SIDED

				reflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;

			#else

				reflectedLight.indirectDiffuse += vIndirectFront;

			#endif

			#ifdef USE_LIGHTMAP

				vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
				vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
				reflectedLight.indirectDiffuse += lightMapIrradiance;

			#endif

			reflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );

			#ifdef DOUBLE_SIDED

				reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;

			#else

				reflectedLight.directDiffuse = vLightFront;

			#endif

			reflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();

			// modulation

			#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>

		}`
  )
};
var MeshGouraudMaterial = class extends ShaderMaterial {
  constructor(parameters) {
    super();
    console.warn("THREE.MeshGouraudMaterial: MeshGouraudMaterial has been deprecated and will be removed with r183. Use THREE.MeshLambertMaterial instead.");
    this.isMeshGouraudMaterial = true;
    this.type = "MeshGouraudMaterial";
    this.combine = MultiplyOperation;
    this.fog = false;
    this.lights = true;
    this.clipping = false;
    const shader = GouraudShader;
    this.defines = Object.assign({}, shader.defines);
    this.uniforms = UniformsUtils.clone(shader.uniforms);
    this.vertexShader = shader.vertexShader;
    this.fragmentShader = shader.fragmentShader;
    const exposePropertyNames = [
      "map",
      "lightMap",
      "lightMapIntensity",
      "aoMap",
      "aoMapIntensity",
      "emissive",
      "emissiveIntensity",
      "emissiveMap",
      "specularMap",
      "alphaMap",
      "envMap",
      "reflectivity",
      "refractionRatio",
      "opacity",
      "diffuse"
    ];
    for (const propertyName of exposePropertyNames) {
      Object.defineProperty(this, propertyName, {
        get: function() {
          return this.uniforms[propertyName].value;
        },
        set: function(value2) {
          this.uniforms[propertyName].value = value2;
        }
      });
    }
    Object.defineProperty(this, "color", Object.getOwnPropertyDescriptor(this, "diffuse"));
    this.setValues(parameters);
  }
  copy(source) {
    super.copy(source);
    this.color.copy(source.color);
    this.map = source.map;
    this.lightMap = source.lightMap;
    this.lightMapIntensity = source.lightMapIntensity;
    this.aoMap = source.aoMap;
    this.aoMapIntensity = source.aoMapIntensity;
    this.emissive.copy(source.emissive);
    this.emissiveMap = source.emissiveMap;
    this.emissiveIntensity = source.emissiveIntensity;
    this.specularMap = source.specularMap;
    this.alphaMap = source.alphaMap;
    this.envMap = source.envMap;
    this.combine = source.combine;
    this.reflectivity = source.reflectivity;
    this.refractionRatio = source.refractionRatio;
    this.wireframe = source.wireframe;
    this.wireframeLinewidth = source.wireframeLinewidth;
    this.wireframeLinecap = source.wireframeLinecap;
    this.wireframeLinejoin = source.wireframeLinejoin;
    this.fog = source.fog;
    return this;
  }
};

// node_modules/three/examples/jsm/materials/LDrawConditionalLineMaterial.js
var LDrawConditionalLineMaterial = class extends ShaderMaterial {
  static get type() {
    return "LDrawConditionalLineMaterial";
  }
  /**
   * Constructs a new conditional line 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(parameters) {
    super({
      uniforms: UniformsUtils.merge([
        UniformsLib.fog,
        {
          diffuse: {
            value: new Color()
          },
          opacity: {
            value: 1
          }
        }
      ]),
      vertexShader: (
        /* glsl */
        `
				attribute vec3 control0;
				attribute vec3 control1;
				attribute vec3 direction;
				varying float discardFlag;

				#include <common>
				#include <color_pars_vertex>
				#include <fog_pars_vertex>
				#include <logdepthbuf_pars_vertex>
				#include <clipping_planes_pars_vertex>
				void main() {
					#include <color_vertex>

					vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
					gl_Position = projectionMatrix * mvPosition;

					// Transform the line segment ends and control points into camera clip space
					vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
					vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
					vec4 p0 = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
					vec4 p1 = projectionMatrix * modelViewMatrix * vec4( position + direction, 1.0 );

					c0.xy /= c0.w;
					c1.xy /= c1.w;
					p0.xy /= p0.w;
					p1.xy /= p1.w;

					// Get the direction of the segment and an orthogonal vector
					vec2 dir = p1.xy - p0.xy;
					vec2 norm = vec2( -dir.y, dir.x );

					// Get control point directions from the line
					vec2 c0dir = c0.xy - p1.xy;
					vec2 c1dir = c1.xy - p1.xy;

					// If the vectors to the controls points are pointed in different directions away
					// from the line segment then the line should not be drawn.
					float d0 = dot( normalize( norm ), normalize( c0dir ) );
					float d1 = dot( normalize( norm ), normalize( c1dir ) );
					discardFlag = float( sign( d0 ) != sign( d1 ) );

					#include <logdepthbuf_vertex>
					#include <clipping_planes_vertex>
					#include <fog_vertex>
				}
			`
      ),
      fragmentShader: (
        /* glsl */
        `
			uniform vec3 diffuse;
			uniform float opacity;
			varying float discardFlag;

			#include <common>
			#include <color_pars_fragment>
			#include <fog_pars_fragment>
			#include <logdepthbuf_pars_fragment>
			#include <clipping_planes_pars_fragment>
			void main() {

				if ( discardFlag > 0.5 ) discard;

				#include <clipping_planes_fragment>
				vec3 outgoingLight = vec3( 0.0 );
				vec4 diffuseColor = vec4( diffuse, opacity );
				#include <logdepthbuf_fragment>
				#include <color_fragment>
				outgoingLight = diffuseColor.rgb; // simple shader
				gl_FragColor = vec4( outgoingLight, diffuseColor.a );
				#include <tonemapping_fragment>
				#include <colorspace_fragment>
				#include <fog_fragment>
				#include <premultiplied_alpha_fragment>
			}
			`
      )
    });
    Object.defineProperties(this, {
      /**
       * The material's opacity.
       *
       * @name LDrawConditionalLineMaterial#opacity
       * @type {number}
       * @default 1
       */
      opacity: {
        get: function() {
          return this.uniforms.opacity.value;
        },
        set: function(value2) {
          this.uniforms.opacity.value = value2;
        }
      },
      /**
       * The material's color.
       *
       * @name LDrawConditionalLineMaterial#color
       * @type {Color}
       * @default (1,1,1)
       */
      color: {
        get: function() {
          return this.uniforms.diffuse.value;
        }
      }
    });
    this.setValues(parameters);
    this.isLDrawConditionalLineMaterial = true;
  }
};

// node_modules/three/examples/jsm/materials/MeshPostProcessingMaterial.js
var MeshPostProcessingMaterial = class extends MeshPhysicalMaterial {
  /**
   * Constructs a new conditional line 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(parameters) {
    const aoPassMap = parameters.aoPassMap;
    const aoPassMapScale = parameters.aoPassMapScale || 1;
    delete parameters.aoPassMap;
    delete parameters.aoPassMapScale;
    super(parameters);
    this.onBeforeCompile = this._onBeforeCompile;
    this.customProgramCacheKey = this._customProgramCacheKey;
    this._aoPassMap = aoPassMap;
    this.aoPassMapScale = aoPassMapScale;
    this._shader = null;
  }
  /**
   * A texture representing the AO pass.
   *
   * @type {Texture}
   */
  get aoPassMap() {
    return this._aoPassMap;
  }
  set aoPassMap(aoPassMap) {
    this._aoPassMap = aoPassMap;
    this.needsUpdate = true;
    this._setUniforms();
  }
  _customProgramCacheKey() {
    return this._aoPassMap !== void 0 && this._aoPassMap !== null ? "aoPassMap" : "";
  }
  _onBeforeCompile(shader) {
    this._shader = shader;
    if (this._aoPassMap !== void 0 && this._aoPassMap !== null) {
      shader.fragmentShader = shader.fragmentShader.replace(
        "#include <aomap_pars_fragment>",
        aomap_pars_fragment_replacement
      );
      shader.fragmentShader = shader.fragmentShader.replace(
        "#include <aomap_fragment>",
        aomap_fragment_replacement
      );
    }
    this._setUniforms();
  }
  _setUniforms() {
    if (this._shader) {
      this._shader.uniforms.tAoPassMap = { value: this._aoPassMap };
      this._shader.uniforms.aoPassMapScale = { value: this.aoPassMapScale };
    }
  }
};
var aomap_pars_fragment_replacement = (
  /* glsl */
  `
#ifdef USE_AOMAP

	uniform sampler2D aoMap;
	uniform float aoMapIntensity;

#endif

	uniform sampler2D tAoPassMap;
	uniform float aoPassMapScale;
`
);
var aomap_fragment_replacement = (
  /* glsl */
  `
#ifndef AOPASSMAP_SWIZZLE
	#define AOPASSMAP_SWIZZLE r
#endif
	float ambientOcclusion = texelFetch( tAoPassMap, ivec2( gl_FragCoord.xy * aoPassMapScale ), 0 ).AOPASSMAP_SWIZZLE;

#ifdef USE_AOMAP

	// reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture
	ambientOcclusion = min( ambientOcclusion, texture2D( aoMap, vAoMapUv ).r );
	ambientOcclusion *= ( ambientOcclusion - 1.0 ) * aoMapIntensity + 1.0;

#endif

	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
`
);

// node_modules/three/examples/jsm/math/Capsule.js
var Capsule = class {
  /**
   * Constructs a new capsule.
   *
   * @param {Vector3} [start] - The start vector.
   * @param {Vector3} [end] - The end vector.
   * @param {number} [radius=1] - The capsule's radius.
   */
  constructor(start = new Vector3(0, 0, 0), end = new Vector3(0, 1, 0), radius = 1) {
    this.start = start;
    this.end = end;
    this.radius = radius;
  }
  /**
   * Returns a new capsule with copied values from this instance.
   *
   * @return {Capsule} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Sets the capsule components to the given values.
   * Please note that this method only copies the values from the given objects.
   *
   * @param {Vector3} start - The start vector.
   * @param {Vector3} end - The end vector
   * @param {number} radius - The capsule's radius.
   * @return {Capsule} A reference to this capsule.
   */
  set(start, end, radius) {
    this.start.copy(start);
    this.end.copy(end);
    this.radius = radius;
    return this;
  }
  /**
   * Copies the values of the given capsule to this instance.
   *
   * @param {Capsule} capsule - The capsule to copy.
   * @return {Capsule} A reference to this capsule.
   */
  copy(capsule) {
    this.start.copy(capsule.start);
    this.end.copy(capsule.end);
    this.radius = capsule.radius;
    return this;
  }
  /**
   * Returns the center point of this capsule.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The center point.
   */
  getCenter(target) {
    return target.copy(this.end).add(this.start).multiplyScalar(0.5);
  }
  /**
   * Adds the given offset to this capsule, effectively moving it in 3D space.
   *
   * @param {Vector3} v - The offset that should be used to translate the capsule.
   * @return {Capsule} A reference to this capsule.
   */
  translate(v) {
    this.start.add(v);
    this.end.add(v);
    return this;
  }
  /**
   * Returns `true` if the given bounding box intersects with this capsule.
   *
   * @param {Box3} box - The bounding box to test.
   * @return {boolean} Whether the given bounding box intersects with this capsule.
   */
  intersectsBox(box) {
    return checkAABBAxis(
      this.start.x,
      this.start.y,
      this.end.x,
      this.end.y,
      box.min.x,
      box.max.x,
      box.min.y,
      box.max.y,
      this.radius
    ) && checkAABBAxis(
      this.start.x,
      this.start.z,
      this.end.x,
      this.end.z,
      box.min.x,
      box.max.x,
      box.min.z,
      box.max.z,
      this.radius
    ) && checkAABBAxis(
      this.start.y,
      this.start.z,
      this.end.y,
      this.end.z,
      box.min.y,
      box.max.y,
      box.min.z,
      box.max.z,
      this.radius
    );
  }
};
function checkAABBAxis(p1x, p1y, p2x, p2y, minx, maxx, miny, maxy, radius) {
  return (minx - p1x < radius || minx - p2x < radius) && (p1x - maxx < radius || p2x - maxx < radius) && (miny - p1y < radius || miny - p2y < radius) && (p1y - maxy < radius || p2y - maxy < radius);
}

// node_modules/three/examples/jsm/math/ColorConverter.js
var _hsl = {};
var ColorConverter = class {
  /**
   * Sets the given HSV color definition to the given color object.
   *
   * @param {Color} color - The color to set.
   * @param {number} h - The hue.
   * @param {number} s - The saturation.
   * @param {number} v - The value.
   * @return {Color} The update color.
   */
  static setHSV(color, h, s, v) {
    h = MathUtils.euclideanModulo(h, 1);
    s = MathUtils.clamp(s, 0, 1);
    v = MathUtils.clamp(v, 0, 1);
    return color.setHSL(h, s * v / ((h = (2 - s) * v) < 1 ? h : 2 - h), h * 0.5);
  }
  /**
   * Returns a HSV color representation of the given color object.
   *
   * @param {Color} color - The color to get HSV values from.
   * @param {{h:number,s:number,v:number}} target - The target object that is used to store the method's result.
   * @return {{h:number,s:number,v:number}} The HSV color.
   */
  static getHSV(color, target) {
    color.getHSL(_hsl);
    _hsl.s *= _hsl.l < 0.5 ? _hsl.l : 1 - _hsl.l;
    target.h = _hsl.h;
    target.s = 2 * _hsl.s / (_hsl.l + _hsl.s);
    target.v = _hsl.l + _hsl.s;
    return target;
  }
};

// node_modules/three/examples/jsm/math/ImprovedNoise.js
var { lerp } = MathUtils;
var _p = [
  151,
  160,
  137,
  91,
  90,
  15,
  131,
  13,
  201,
  95,
  96,
  53,
  194,
  233,
  7,
  225,
  140,
  36,
  103,
  30,
  69,
  142,
  8,
  99,
  37,
  240,
  21,
  10,
  23,
  190,
  6,
  148,
  247,
  120,
  234,
  75,
  0,
  26,
  197,
  62,
  94,
  252,
  219,
  203,
  117,
  35,
  11,
  32,
  57,
  177,
  33,
  88,
  237,
  149,
  56,
  87,
  174,
  20,
  125,
  136,
  171,
  168,
  68,
  175,
  74,
  165,
  71,
  134,
  139,
  48,
  27,
  166,
  77,
  146,
  158,
  231,
  83,
  111,
  229,
  122,
  60,
  211,
  133,
  230,
  220,
  105,
  92,
  41,
  55,
  46,
  245,
  40,
  244,
  102,
  143,
  54,
  65,
  25,
  63,
  161,
  1,
  216,
  80,
  73,
  209,
  76,
  132,
  187,
  208,
  89,
  18,
  169,
  200,
  196,
  135,
  130,
  116,
  188,
  159,
  86,
  164,
  100,
  109,
  198,
  173,
  186,
  3,
  64,
  52,
  217,
  226,
  250,
  124,
  123,
  5,
  202,
  38,
  147,
  118,
  126,
  255,
  82,
  85,
  212,
  207,
  206,
  59,
  227,
  47,
  16,
  58,
  17,
  182,
  189,
  28,
  42,
  223,
  183,
  170,
  213,
  119,
  248,
  152,
  2,
  44,
  154,
  163,
  70,
  221,
  153,
  101,
  155,
  167,
  43,
  172,
  9,
  129,
  22,
  39,
  253,
  19,
  98,
  108,
  110,
  79,
  113,
  224,
  232,
  178,
  185,
  112,
  104,
  218,
  246,
  97,
  228,
  251,
  34,
  242,
  193,
  238,
  210,
  144,
  12,
  191,
  179,
  162,
  241,
  81,
  51,
  145,
  235,
  249,
  14,
  239,
  107,
  49,
  192,
  214,
  31,
  181,
  199,
  106,
  157,
  184,
  84,
  204,
  176,
  115,
  121,
  50,
  45,
  127,
  4,
  150,
  254,
  138,
  236,
  205,
  93,
  222,
  114,
  67,
  29,
  24,
  72,
  243,
  141,
  128,
  195,
  78,
  66,
  215,
  61,
  156,
  180
];
for (let i = 0; i < 256; i++) {
  _p[256 + i] = _p[i];
}
function fade(t3) {
  return t3 * t3 * t3 * (t3 * (t3 * 6 - 15) + 10);
}
function grad(hash, x2, y, z) {
  const h = hash & 15;
  const u2 = h < 8 ? x2 : y, v = h < 4 ? y : h == 12 || h == 14 ? x2 : z;
  return ((h & 1) == 0 ? u2 : -u2) + ((h & 2) == 0 ? v : -v);
}
var ImprovedNoise = class {
  /**
   * Returns a noise value for the given parameters.
   *
   * @param {number} x - The x coordinate.
   * @param {number} y - The y coordinate.
   * @param {number} z - The z coordinate.
   * @return {number} The noise value.
   */
  noise(x2, y, z) {
    const floorX = Math.floor(x2), floorY = Math.floor(y), floorZ = Math.floor(z);
    const X = floorX & 255, Y = floorY & 255, Z2 = floorZ & 255;
    x2 -= floorX;
    y -= floorY;
    z -= floorZ;
    const xMinus1 = x2 - 1, yMinus1 = y - 1, zMinus1 = z - 1;
    const u2 = fade(x2), v = fade(y), w = fade(z);
    const A2 = _p[X] + Y, AA = _p[A2] + Z2, AB = _p[A2 + 1] + Z2, B2 = _p[X + 1] + Y, BA = _p[B2] + Z2, BB = _p[B2 + 1] + Z2;
    return lerp(
      lerp(
        lerp(grad(_p[AA], x2, y, z), grad(_p[BA], xMinus1, y, z), u2),
        lerp(grad(_p[AB], x2, yMinus1, z), grad(_p[BB], xMinus1, yMinus1, z), u2),
        v
      ),
      lerp(
        lerp(grad(_p[AA + 1], x2, y, zMinus1), grad(_p[BA + 1], xMinus1, y, zMinus1), u2),
        lerp(grad(_p[AB + 1], x2, yMinus1, zMinus1), grad(_p[BB + 1], xMinus1, yMinus1, zMinus1), u2),
        v
      ),
      w
    );
  }
};

// node_modules/three/examples/jsm/math/Lut.js
var Lut = class {
  /**
   * Constructs a new Lut.
   *
   * @param {('rainbow'|'cooltowarm'|'blackbody'|'grayscale')} [colormap='rainbow'] - Sets a colormap from predefined list of colormaps.
   * @param {number} [count=32] - Sets the number of colors used to represent the data array.
   */
  constructor(colormap, count = 32) {
    this.isLut = true;
    this.lut = [];
    this.map = [];
    this.n = 0;
    this.minV = 0;
    this.maxV = 1;
    this.setColorMap(colormap, count);
  }
  /**
   * Sets the given LUT.
   *
   * @param {Lut} value - The LUT to set.
   * @return {Lut} A reference to this LUT.
   */
  set(value2) {
    if (value2.isLut === true) {
      this.copy(value2);
    }
    return this;
  }
  /**
   * Sets the minimum value to be represented with this LUT.
   *
   * @param {number} min - The minimum value to be represented with the lookup table.
   * @return {Lut} A reference to this LUT.
   */
  setMin(min) {
    this.minV = min;
    return this;
  }
  /**
   * Sets the maximum value to be represented with this LUT.
   *
   * @param {number} max - The maximum value to be represented with the lookup table.
   * @return {Lut} A reference to this LUT.
   */
  setMax(max2) {
    this.maxV = max2;
    return this;
  }
  /**
   * Configure the lookup table for the given color map and number of colors.
   *
   * @param {string} colormap - The name of the color map.
   * @param {number} [count=32] - The number of colors.
   * @return {Lut} A reference to this LUT.
   */
  setColorMap(colormap, count = 32) {
    this.map = ColorMapKeywords[colormap] || ColorMapKeywords.rainbow;
    this.n = count;
    const step = 1 / this.n;
    const minColor = new Color();
    const maxColor = new Color();
    this.lut.length = 0;
    this.lut.push(new Color(this.map[0][1]));
    for (let i = 1; i < count; i++) {
      const alpha = i * step;
      for (let j2 = 0; j2 < this.map.length - 1; j2++) {
        if (alpha > this.map[j2][0] && alpha <= this.map[j2 + 1][0]) {
          const min = this.map[j2][0];
          const max2 = this.map[j2 + 1][0];
          minColor.setHex(this.map[j2][1], LinearSRGBColorSpace);
          maxColor.setHex(this.map[j2 + 1][1], LinearSRGBColorSpace);
          const color = new Color().lerpColors(minColor, maxColor, (alpha - min) / (max2 - min));
          this.lut.push(color);
        }
      }
    }
    this.lut.push(new Color(this.map[this.map.length - 1][1]));
    return this;
  }
  /**
   * Copies the given lut.
   *
   * @param {Lut} lut - The LUT to copy.
   * @return {Lut} A reference to this LUT.
   */
  copy(lut) {
    this.lut = lut.lut;
    this.map = lut.map;
    this.n = lut.n;
    this.minV = lut.minV;
    this.maxV = lut.maxV;
    return this;
  }
  /**
   * Returns an instance of Color for the given data value.
   *
   * @param {number} alpha - The value to lookup.
   * @return {Color} The color from the LUT.
   */
  getColor(alpha) {
    alpha = MathUtils.clamp(alpha, this.minV, this.maxV);
    alpha = (alpha - this.minV) / (this.maxV - this.minV);
    const colorPosition = Math.round(alpha * this.n);
    return this.lut[colorPosition];
  }
  /**
   * Adds a color map to this Lut instance.
   *
   * @param {string} name - The name of the color map.
   * @param {Array} arrayOfColors - An array of color values. Each value is an array
   * holding a threshold and the actual color value as a hexadecimal number.
   * @return {Lut} A reference to this LUT.
   */
  addColorMap(name2, arrayOfColors) {
    ColorMapKeywords[name2] = arrayOfColors;
    return this;
  }
  /**
   * Creates a canvas in order to visualize the lookup table as a texture.
   *
   * @return {HTMLCanvasElement} The created canvas.
   */
  createCanvas() {
    const canvas = document.createElement("canvas");
    canvas.width = 1;
    canvas.height = this.n;
    this.updateCanvas(canvas);
    return canvas;
  }
  /**
   * Updates the given canvas with the Lut's data.
   *
   * @param {HTMLCanvasElement} canvas - The canvas to update.
   * @return {HTMLCanvasElement} The updated canvas.
   */
  updateCanvas(canvas) {
    const ctx = canvas.getContext("2d", { alpha: false });
    const imageData = ctx.getImageData(0, 0, 1, this.n);
    const data2 = imageData.data;
    let k2 = 0;
    const step = 1 / this.n;
    const minColor = new Color();
    const maxColor = new Color();
    const finalColor = new Color();
    for (let i = 1; i >= 0; i -= step) {
      for (let j2 = this.map.length - 1; j2 >= 0; j2--) {
        if (i < this.map[j2][0] && i >= this.map[j2 - 1][0]) {
          const min = this.map[j2 - 1][0];
          const max2 = this.map[j2][0];
          minColor.setHex(this.map[j2 - 1][1], LinearSRGBColorSpace);
          maxColor.setHex(this.map[j2][1], LinearSRGBColorSpace);
          finalColor.lerpColors(minColor, maxColor, (i - min) / (max2 - min));
          data2[k2 * 4] = Math.round(finalColor.r * 255);
          data2[k2 * 4 + 1] = Math.round(finalColor.g * 255);
          data2[k2 * 4 + 2] = Math.round(finalColor.b * 255);
          data2[k2 * 4 + 3] = 255;
          k2 += 1;
        }
      }
    }
    ctx.putImageData(imageData, 0, 0);
    return canvas;
  }
};
var ColorMapKeywords = {
  "rainbow": [[0, 255], [0.2, 65535], [0.5, 65280], [0.8, 16776960], [1, 16711680]],
  "cooltowarm": [[0, 3952322], [0.2, 10206463], [0.5, 14474460], [0.8, 16163717], [1, 11797542]],
  "blackbody": [[0, 0], [0.2, 7864320], [0.5, 15086080], [0.8, 16776960], [1, 16777215]],
  "grayscale": [[0, 0], [0.2, 4210752], [0.5, 8355712], [0.8, 12566463], [1, 16777215]]
};

// node_modules/three/examples/jsm/math/MeshSurfaceSampler.js
var _face = new Triangle();
var _color3 = new Vector3();
var _uva = new Vector2();
var _uvb = new Vector2();
var _uvc = new Vector2();
var MeshSurfaceSampler = class {
  /**
   * Constructs a mesh surface sampler.
   *
   * @param {Mesh} mesh - Surface mesh from which to sample.
   */
  constructor(mesh) {
    this.geometry = mesh.geometry;
    this.randomFunction = Math.random;
    this.indexAttribute = this.geometry.index;
    this.positionAttribute = this.geometry.getAttribute("position");
    this.normalAttribute = this.geometry.getAttribute("normal");
    this.colorAttribute = this.geometry.getAttribute("color");
    this.uvAttribute = this.geometry.getAttribute("uv");
    this.weightAttribute = null;
    this.distribution = null;
  }
  /**
   * Specifies a vertex attribute to be used as a weight when sampling from the surface.
   * Faces with higher weights are more likely to be sampled, and those with weights of
   * zero will not be sampled at all. For vector attributes, only .x is used in sampling.
   *
   * If no weight attribute is selected, sampling is randomly distributed by area.
   *
   * @param {string} name - The attribute name.
   * @return {MeshSurfaceSampler} A reference to this sampler.
   */
  setWeightAttribute(name2) {
    this.weightAttribute = name2 ? this.geometry.getAttribute(name2) : null;
    return this;
  }
  /**
   * Processes the input geometry and prepares to return samples. Any configuration of the
   * geometry or sampler must occur before this method is called. Time complexity is O(n)
   * for a surface with n faces.
   *
   * @return {MeshSurfaceSampler} A reference to this sampler.
   */
  build() {
    const indexAttribute = this.indexAttribute;
    const positionAttribute = this.positionAttribute;
    const weightAttribute = this.weightAttribute;
    const totalFaces = indexAttribute ? indexAttribute.count / 3 : positionAttribute.count / 3;
    const faceWeights = new Float32Array(totalFaces);
    for (let i = 0; i < totalFaces; i++) {
      let faceWeight = 1;
      let i0 = 3 * i;
      let i1 = 3 * i + 1;
      let i2 = 3 * i + 2;
      if (indexAttribute) {
        i0 = indexAttribute.getX(i0);
        i1 = indexAttribute.getX(i1);
        i2 = indexAttribute.getX(i2);
      }
      if (weightAttribute) {
        faceWeight = weightAttribute.getX(i0) + weightAttribute.getX(i1) + weightAttribute.getX(i2);
      }
      _face.a.fromBufferAttribute(positionAttribute, i0);
      _face.b.fromBufferAttribute(positionAttribute, i1);
      _face.c.fromBufferAttribute(positionAttribute, i2);
      faceWeight *= _face.getArea();
      faceWeights[i] = faceWeight;
    }
    const distribution = new Float32Array(totalFaces);
    let cumulativeTotal = 0;
    for (let i = 0; i < totalFaces; i++) {
      cumulativeTotal += faceWeights[i];
      distribution[i] = cumulativeTotal;
    }
    this.distribution = distribution;
    return this;
  }
  /**
   * Allows to set a custom random number generator. Default is `Math.random()`.
   *
   * @param {Function} randomFunction - A random number generator.
   * @return {MeshSurfaceSampler} A reference to this sampler.
   */
  setRandomGenerator(randomFunction) {
    this.randomFunction = randomFunction;
    return this;
  }
  /**
   * Selects a random point on the surface of the input geometry, returning the
   * position and optionally the normal vector, color and UV Coordinate at that point.
   * Time complexity is O(log n) for a surface with n faces.
   *
   * @param {Vector3} targetPosition - The target object holding the sampled position.
   * @param {Vector3} targetNormal - The target object holding the sampled normal.
   * @param {Color} targetColor - The target object holding the sampled color.
   * @param {Vector2} targetUV -  The target object holding the sampled uv coordinates.
   * @return {MeshSurfaceSampler} A reference to this sampler.
   */
  sample(targetPosition, targetNormal, targetColor, targetUV) {
    const faceIndex = this._sampleFaceIndex();
    return this._sampleFace(faceIndex, targetPosition, targetNormal, targetColor, targetUV);
  }
  // private
  _sampleFaceIndex() {
    const cumulativeTotal = this.distribution[this.distribution.length - 1];
    return this._binarySearch(this.randomFunction() * cumulativeTotal);
  }
  _binarySearch(x2) {
    const dist = this.distribution;
    let start = 0;
    let end = dist.length - 1;
    let index2 = -1;
    while (start <= end) {
      const mid = Math.ceil((start + end) / 2);
      if (mid === 0 || dist[mid - 1] <= x2 && dist[mid] > x2) {
        index2 = mid;
        break;
      } else if (x2 < dist[mid]) {
        end = mid - 1;
      } else {
        start = mid + 1;
      }
    }
    return index2;
  }
  _sampleFace(faceIndex, targetPosition, targetNormal, targetColor, targetUV) {
    let u2 = this.randomFunction();
    let v = this.randomFunction();
    if (u2 + v > 1) {
      u2 = 1 - u2;
      v = 1 - v;
    }
    const indexAttribute = this.indexAttribute;
    let i0 = faceIndex * 3;
    let i1 = faceIndex * 3 + 1;
    let i2 = faceIndex * 3 + 2;
    if (indexAttribute) {
      i0 = indexAttribute.getX(i0);
      i1 = indexAttribute.getX(i1);
      i2 = indexAttribute.getX(i2);
    }
    _face.a.fromBufferAttribute(this.positionAttribute, i0);
    _face.b.fromBufferAttribute(this.positionAttribute, i1);
    _face.c.fromBufferAttribute(this.positionAttribute, i2);
    targetPosition.set(0, 0, 0).addScaledVector(_face.a, u2).addScaledVector(_face.b, v).addScaledVector(_face.c, 1 - (u2 + v));
    if (targetNormal !== void 0) {
      if (this.normalAttribute !== void 0) {
        _face.a.fromBufferAttribute(this.normalAttribute, i0);
        _face.b.fromBufferAttribute(this.normalAttribute, i1);
        _face.c.fromBufferAttribute(this.normalAttribute, i2);
        targetNormal.set(0, 0, 0).addScaledVector(_face.a, u2).addScaledVector(_face.b, v).addScaledVector(_face.c, 1 - (u2 + v)).normalize();
      } else {
        _face.getNormal(targetNormal);
      }
    }
    if (targetColor !== void 0 && this.colorAttribute !== void 0) {
      _face.a.fromBufferAttribute(this.colorAttribute, i0);
      _face.b.fromBufferAttribute(this.colorAttribute, i1);
      _face.c.fromBufferAttribute(this.colorAttribute, i2);
      _color3.set(0, 0, 0).addScaledVector(_face.a, u2).addScaledVector(_face.b, v).addScaledVector(_face.c, 1 - (u2 + v));
      targetColor.r = _color3.x;
      targetColor.g = _color3.y;
      targetColor.b = _color3.z;
    }
    if (targetUV !== void 0 && this.uvAttribute !== void 0) {
      _uva.fromBufferAttribute(this.uvAttribute, i0);
      _uvb.fromBufferAttribute(this.uvAttribute, i1);
      _uvc.fromBufferAttribute(this.uvAttribute, i2);
      targetUV.set(0, 0).addScaledVector(_uva, u2).addScaledVector(_uvb, v).addScaledVector(_uvc, 1 - (u2 + v));
    }
    return this;
  }
};

// node_modules/three/examples/jsm/math/OBB.js
var a = {
  c: null,
  // center
  u: [new Vector3(), new Vector3(), new Vector3()],
  // basis vectors
  e: []
  // half width
};
var b = {
  c: null,
  // center
  u: [new Vector3(), new Vector3(), new Vector3()],
  // basis vectors
  e: []
  // half width
};
var R3 = [[], [], []];
var AbsR = [[], [], []];
var t2 = [];
var xAxis = new Vector3();
var yAxis = new Vector3();
var zAxis = new Vector3();
var v1 = new Vector3();
var size = new Vector3();
var closestPoint = new Vector3();
var rotationMatrix = new Matrix3();
var aabb = new Box3();
var matrix = new Matrix4();
var inverse = new Matrix4();
var localRay = new Ray();
var OBB = class {
  /**
   * Constructs a new OBB.
   *
   * @param {Vector3} [center] - The center of the OBB.
   * @param {Vector3} [halfSize] - Positive halfwidth extents of the OBB along each axis.
   * @param {Matrix3} [rotation] - The rotation of the OBB.
   */
  constructor(center = new Vector3(), halfSize = new Vector3(), rotation2 = new Matrix3()) {
    this.center = center;
    this.halfSize = halfSize;
    this.rotation = rotation2;
  }
  /**
   * Sets the OBBs components to the given values.
   *
   * @param {Vector3} [center] - The center of the OBB.
   * @param {Vector3} [halfSize] - Positive halfwidth extents of the OBB along each axis.
   * @param {Matrix3} [rotation] - The rotation of the OBB.
   * @return {OBB} A reference to this OBB.
   */
  set(center, halfSize, rotation2) {
    this.center = center;
    this.halfSize = halfSize;
    this.rotation = rotation2;
    return this;
  }
  /**
   * Copies the values of the given OBB to this instance.
   *
   * @param {OBB} obb - The OBB to copy.
   * @return {OBB} A reference to this OBB.
   */
  copy(obb2) {
    this.center.copy(obb2.center);
    this.halfSize.copy(obb2.halfSize);
    this.rotation.copy(obb2.rotation);
    return this;
  }
  /**
   * Returns a new OBB with copied values from this instance.
   *
   * @return {OBB} A clone of this instance.
   */
  clone() {
    return new this.constructor().copy(this);
  }
  /**
   * Returns the size of this OBB.
   *
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {Vector3} The size.
   */
  getSize(target) {
    return target.copy(this.halfSize).multiplyScalar(2);
  }
  /**
   * Clamps the given point within the bounds of this OBB.
   *
   * @param {Vector3} point - The point that should be clamped within the bounds of this OBB.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @returns {Vector3} - The clamped point.
   */
  clampPoint(point, target) {
    const halfSize = this.halfSize;
    v1.subVectors(point, this.center);
    this.rotation.extractBasis(xAxis, yAxis, zAxis);
    target.copy(this.center);
    const x2 = MathUtils.clamp(v1.dot(xAxis), -halfSize.x, halfSize.x);
    target.add(xAxis.multiplyScalar(x2));
    const y = MathUtils.clamp(v1.dot(yAxis), -halfSize.y, halfSize.y);
    target.add(yAxis.multiplyScalar(y));
    const z = MathUtils.clamp(v1.dot(zAxis), -halfSize.z, halfSize.z);
    target.add(zAxis.multiplyScalar(z));
    return target;
  }
  /**
   * Returns `true` if the given point lies within this OBB.
   *
   * @param {Vector3} point - The point to test.
   * @returns {boolean} - Whether the given point lies within this OBB or not.
   */
  containsPoint(point) {
    v1.subVectors(point, this.center);
    this.rotation.extractBasis(xAxis, yAxis, zAxis);
    return Math.abs(v1.dot(xAxis)) <= this.halfSize.x && Math.abs(v1.dot(yAxis)) <= this.halfSize.y && Math.abs(v1.dot(zAxis)) <= this.halfSize.z;
  }
  /**
   * Returns `true` if the given AABB intersects this OBB.
   *
   * @param {Box3} box3 - The AABB to test.
   * @returns {boolean} - Whether the given AABB intersects this OBB or not.
   */
  intersectsBox3(box3) {
    return this.intersectsOBB(obb.fromBox3(box3));
  }
  /**
   * Returns `true` if the given bounding sphere intersects this OBB.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @returns {boolean} - Whether the given bounding sphere intersects this OBB or not.
   */
  intersectsSphere(sphere) {
    this.clampPoint(sphere.center, closestPoint);
    return closestPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  }
  /**
   * Returns `true` if the given OBB intersects this OBB.
   *
   * @param {OBB} obb - The OBB to test.
   * @param {number} [epsilon=Number.EPSILON] - A small value to prevent arithmetic errors.
   * @returns {boolean} - Whether the given OBB intersects this OBB or not.
   */
  intersectsOBB(obb2, epsilon = Number.EPSILON) {
    a.c = this.center;
    a.e[0] = this.halfSize.x;
    a.e[1] = this.halfSize.y;
    a.e[2] = this.halfSize.z;
    this.rotation.extractBasis(a.u[0], a.u[1], a.u[2]);
    b.c = obb2.center;
    b.e[0] = obb2.halfSize.x;
    b.e[1] = obb2.halfSize.y;
    b.e[2] = obb2.halfSize.z;
    obb2.rotation.extractBasis(b.u[0], b.u[1], b.u[2]);
    for (let i = 0; i < 3; i++) {
      for (let j2 = 0; j2 < 3; j2++) {
        R3[i][j2] = a.u[i].dot(b.u[j2]);
      }
    }
    v1.subVectors(b.c, a.c);
    t2[0] = v1.dot(a.u[0]);
    t2[1] = v1.dot(a.u[1]);
    t2[2] = v1.dot(a.u[2]);
    for (let i = 0; i < 3; i++) {
      for (let j2 = 0; j2 < 3; j2++) {
        AbsR[i][j2] = Math.abs(R3[i][j2]) + epsilon;
      }
    }
    let ra2, rb;
    for (let i = 0; i < 3; i++) {
      ra2 = a.e[i];
      rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2];
      if (Math.abs(t2[i]) > ra2 + rb) return false;
    }
    for (let i = 0; i < 3; i++) {
      ra2 = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i];
      rb = b.e[i];
      if (Math.abs(t2[0] * R3[0][i] + t2[1] * R3[1][i] + t2[2] * R3[2][i]) > ra2 + rb) return false;
    }
    ra2 = a.e[1] * AbsR[2][0] + a.e[2] * AbsR[1][0];
    rb = b.e[1] * AbsR[0][2] + b.e[2] * AbsR[0][1];
    if (Math.abs(t2[2] * R3[1][0] - t2[1] * R3[2][0]) > ra2 + rb) return false;
    ra2 = a.e[1] * AbsR[2][1] + a.e[2] * AbsR[1][1];
    rb = b.e[0] * AbsR[0][2] + b.e[2] * AbsR[0][0];
    if (Math.abs(t2[2] * R3[1][1] - t2[1] * R3[2][1]) > ra2 + rb) return false;
    ra2 = a.e[1] * AbsR[2][2] + a.e[2] * AbsR[1][2];
    rb = b.e[0] * AbsR[0][1] + b.e[1] * AbsR[0][0];
    if (Math.abs(t2[2] * R3[1][2] - t2[1] * R3[2][2]) > ra2 + rb) return false;
    ra2 = a.e[0] * AbsR[2][0] + a.e[2] * AbsR[0][0];
    rb = b.e[1] * AbsR[1][2] + b.e[2] * AbsR[1][1];
    if (Math.abs(t2[0] * R3[2][0] - t2[2] * R3[0][0]) > ra2 + rb) return false;
    ra2 = a.e[0] * AbsR[2][1] + a.e[2] * AbsR[0][1];
    rb = b.e[0] * AbsR[1][2] + b.e[2] * AbsR[1][0];
    if (Math.abs(t2[0] * R3[2][1] - t2[2] * R3[0][1]) > ra2 + rb) return false;
    ra2 = a.e[0] * AbsR[2][2] + a.e[2] * AbsR[0][2];
    rb = b.e[0] * AbsR[1][1] + b.e[1] * AbsR[1][0];
    if (Math.abs(t2[0] * R3[2][2] - t2[2] * R3[0][2]) > ra2 + rb) return false;
    ra2 = a.e[0] * AbsR[1][0] + a.e[1] * AbsR[0][0];
    rb = b.e[1] * AbsR[2][2] + b.e[2] * AbsR[2][1];
    if (Math.abs(t2[1] * R3[0][0] - t2[0] * R3[1][0]) > ra2 + rb) return false;
    ra2 = a.e[0] * AbsR[1][1] + a.e[1] * AbsR[0][1];
    rb = b.e[0] * AbsR[2][2] + b.e[2] * AbsR[2][0];
    if (Math.abs(t2[1] * R3[0][1] - t2[0] * R3[1][1]) > ra2 + rb) return false;
    ra2 = a.e[0] * AbsR[1][2] + a.e[1] * AbsR[0][2];
    rb = b.e[0] * AbsR[2][1] + b.e[1] * AbsR[2][0];
    if (Math.abs(t2[1] * R3[0][2] - t2[0] * R3[1][2]) > ra2 + rb) return false;
    return true;
  }
  /**
   * Returns `true` if the given plane intersects this OBB.
   *
   * @param {Plane} plane - The plane to test.
   * @returns {boolean} Whether the given plane intersects this OBB or not.
   */
  intersectsPlane(plane2) {
    this.rotation.extractBasis(xAxis, yAxis, zAxis);
    const r = this.halfSize.x * Math.abs(plane2.normal.dot(xAxis)) + this.halfSize.y * Math.abs(plane2.normal.dot(yAxis)) + this.halfSize.z * Math.abs(plane2.normal.dot(zAxis));
    const d = plane2.normal.dot(this.center) - plane2.constant;
    return Math.abs(d) <= r;
  }
  /**
   * Performs a ray/OBB intersection test and stores the intersection point
   * in the given 3D vector.
   *
   * @param {Ray} ray - The ray to test.
   * @param {Vector3} target - The target vector that is used to store the method's result.
   * @return {?Vector3} The intersection point. If no intersection is detected, `null` is returned.
   */
  intersectRay(ray, target) {
    this.getSize(size);
    aabb.setFromCenterAndSize(v1.set(0, 0, 0), size);
    matrix.setFromMatrix3(this.rotation);
    matrix.setPosition(this.center);
    inverse.copy(matrix).invert();
    localRay.copy(ray).applyMatrix4(inverse);
    if (localRay.intersectBox(aabb, target)) {
      return target.applyMatrix4(matrix);
    } else {
      return null;
    }
  }
  /**
   * Returns `true` if the given ray intersects this OBB.
   *
   * @param {Ray} ray - The ray to test.
   * @returns {boolean} Whether the given ray intersects this OBB or not.
   */
  intersectsRay(ray) {
    return this.intersectRay(ray, v1) !== null;
  }
  /**
   * Defines an OBB based on the given AABB.
   *
   * @param {Box3} box3 - The AABB to setup the OBB from.
   * @return {OBB} A reference of this OBB.
   */
  fromBox3(box3) {
    box3.getCenter(this.center);
    box3.getSize(this.halfSize).multiplyScalar(0.5);
    this.rotation.identity();
    return this;
  }
  /**
   * Returns `true` if the given OBB is equal to this OBB.
   *
   * @param {OBB} obb - The OBB to test.
   * @returns {boolean} Whether the given OBB is equal to this OBB or not.
   */
  equals(obb2) {
    return obb2.center.equals(this.center) && obb2.halfSize.equals(this.halfSize) && obb2.rotation.equals(this.rotation);
  }
  /**
   * Applies the given transformation matrix to this OBB. This method can be
   * used to transform the bounding volume with the world matrix of a 3D object
   * in order to keep both entities in sync.
   *
   * @param {Matrix4} matrix - The matrix to apply.
   * @return {OBB} A reference of this OBB.
   */
  applyMatrix4(matrix2) {
    const e = matrix2.elements;
    let sx = v1.set(e[0], e[1], e[2]).length();
    const sy = v1.set(e[4], e[5], e[6]).length();
    const sz = v1.set(e[8], e[9], e[10]).length();
    const det = matrix2.determinant();
    if (det < 0) sx = -sx;
    rotationMatrix.setFromMatrix4(matrix2);
    const invSX = 1 / sx;
    const invSY = 1 / sy;
    const invSZ = 1 / sz;
    rotationMatrix.elements[0] *= invSX;
    rotationMatrix.elements[1] *= invSX;
    rotationMatrix.elements[2] *= invSX;
    rotationMatrix.elements[3] *= invSY;
    rotationMatrix.elements[4] *= invSY;
    rotationMatrix.elements[5] *= invSY;
    rotationMatrix.elements[6] *= invSZ;
    rotationMatrix.elements[7] *= invSZ;
    rotationMatrix.elements[8] *= invSZ;
    this.rotation.multiply(rotationMatrix);
    this.halfSize.x *= sx;
    this.halfSize.y *= sy;
    this.halfSize.z *= sz;
    v1.setFromMatrixPosition(matrix2);
    this.center.add(v1);
    return this;
  }
};
var obb = new OBB();

// node_modules/three/examples/jsm/math/Octree.js
var _v15 = new Vector3();
var _v25 = new Vector3();
var _point1 = new Vector3();
var _point2 = new Vector3();
var _plane4 = new Plane();
var _line1 = new Line3();
var _line2 = new Line3();
var _sphere2 = new Sphere();
var _capsule = new Capsule();
var _temp1 = new Vector3();
var _temp2 = new Vector3();
var _temp3 = new Vector3();
var EPS = 1e-10;
function lineToLineClosestPoints(line1, line2, target1 = null, target2 = null) {
  const r = _temp1.copy(line1.end).sub(line1.start);
  const s = _temp2.copy(line2.end).sub(line2.start);
  const w = _temp3.copy(line2.start).sub(line1.start);
  const a2 = r.dot(s), b3 = r.dot(r), c2 = s.dot(s), d = s.dot(w), e = r.dot(w);
  let t1, t22;
  const divisor = b3 * c2 - a2 * a2;
  if (Math.abs(divisor) < EPS) {
    const d1 = -d / c2;
    const d2 = (a2 - d) / c2;
    if (Math.abs(d1 - 0.5) < Math.abs(d2 - 0.5)) {
      t1 = 0;
      t22 = d1;
    } else {
      t1 = 1;
      t22 = d2;
    }
  } else {
    t1 = (d * a2 + e * c2) / divisor;
    t22 = (t1 * a2 - d) / c2;
  }
  t22 = Math.max(0, Math.min(1, t22));
  t1 = Math.max(0, Math.min(1, t1));
  if (target1) {
    target1.copy(r).multiplyScalar(t1).add(line1.start);
  }
  if (target2) {
    target2.copy(s).multiplyScalar(t22).add(line2.start);
  }
}
var Octree = class _Octree {
  /**
   * Constructs a new Octree.
   *
   * @param {Box3} [box] - The base box with enclose the entire Octree.
   */
  constructor(box) {
    this.box = box;
    this.bounds = new Box3();
    this.layers = new Layers();
    this.trianglesPerLeaf = 8;
    this.maxLevel = 16;
    this.subTrees = [];
    this.triangles = [];
  }
  /**
   * Adds the given triangle to the Octree. The triangle vertices are clamped if they exceed
   * the bounds of the Octree.
   *
   * @param {Triangle} triangle - The triangle to add.
   * @return {Octree} A reference to this Octree.
   */
  addTriangle(triangle) {
    this.bounds.min.x = Math.min(this.bounds.min.x, triangle.a.x, triangle.b.x, triangle.c.x);
    this.bounds.min.y = Math.min(this.bounds.min.y, triangle.a.y, triangle.b.y, triangle.c.y);
    this.bounds.min.z = Math.min(this.bounds.min.z, triangle.a.z, triangle.b.z, triangle.c.z);
    this.bounds.max.x = Math.max(this.bounds.max.x, triangle.a.x, triangle.b.x, triangle.c.x);
    this.bounds.max.y = Math.max(this.bounds.max.y, triangle.a.y, triangle.b.y, triangle.c.y);
    this.bounds.max.z = Math.max(this.bounds.max.z, triangle.a.z, triangle.b.z, triangle.c.z);
    this.triangles.push(triangle);
    return this;
  }
  /**
   * Prepares {@link Octree#box} for the build.
   *
   * @return {Octree} A reference to this Octree.
   */
  calcBox() {
    this.box = this.bounds.clone();
    this.box.min.x -= 0.01;
    this.box.min.y -= 0.01;
    this.box.min.z -= 0.01;
    return this;
  }
  /**
   * Splits the Octree. This method is used recursively when
   * building the Octree.
   *
   * @param {number} level - The current level.
   * @return {Octree} A reference to this Octree.
   */
  split(level) {
    if (!this.box) return;
    const subTrees = [];
    const halfsize = _v25.copy(this.box.max).sub(this.box.min).multiplyScalar(0.5);
    for (let x2 = 0; x2 < 2; x2++) {
      for (let y = 0; y < 2; y++) {
        for (let z = 0; z < 2; z++) {
          const box = new Box3();
          const v = _v15.set(x2, y, z);
          box.min.copy(this.box.min).add(v.multiply(halfsize));
          box.max.copy(box.min).add(halfsize);
          subTrees.push(new _Octree(box));
        }
      }
    }
    let triangle;
    while (triangle = this.triangles.pop()) {
      for (let i = 0; i < subTrees.length; i++) {
        if (subTrees[i].box.intersectsTriangle(triangle)) {
          subTrees[i].triangles.push(triangle);
        }
      }
    }
    for (let i = 0; i < subTrees.length; i++) {
      const len = subTrees[i].triangles.length;
      if (len > this.trianglesPerLeaf && level < this.maxLevel) {
        subTrees[i].split(level + 1);
      }
      if (len !== 0) {
        this.subTrees.push(subTrees[i]);
      }
    }
    return this;
  }
  /**
   * Builds the Octree.
   *
   * @return {Octree} A reference to this Octree.
   */
  build() {
    this.calcBox();
    this.split(0);
    return this;
  }
  /**
   * Computes the triangles that potentially intersect with the given ray.
   *
   * @param {Ray} ray - The ray to test.
   * @param {Array<Triangle>} triangles - The target array that holds the triangles.
   */
  getRayTriangles(ray, triangles) {
    for (let i = 0; i < this.subTrees.length; i++) {
      const subTree = this.subTrees[i];
      if (!ray.intersectsBox(subTree.box)) continue;
      if (subTree.triangles.length > 0) {
        for (let j2 = 0; j2 < subTree.triangles.length; j2++) {
          if (triangles.indexOf(subTree.triangles[j2]) === -1) triangles.push(subTree.triangles[j2]);
        }
      } else {
        subTree.getRayTriangles(ray, triangles);
      }
    }
  }
  /**
   * Computes the intersection between the given capsule and triangle.
   *
   * @param {Capsule} capsule - The capsule to test.
   * @param {Triangle} triangle - The triangle to test.
   * @return {Object|false} The intersection object. If no intersection
   * is detected, the method returns `false`.
   */
  triangleCapsuleIntersect(capsule, triangle) {
    triangle.getPlane(_plane4);
    const d1 = _plane4.distanceToPoint(capsule.start) - capsule.radius;
    const d2 = _plane4.distanceToPoint(capsule.end) - capsule.radius;
    if (d1 > 0 && d2 > 0 || d1 < -capsule.radius && d2 < -capsule.radius) {
      return false;
    }
    const delta = Math.abs(d1 / (Math.abs(d1) + Math.abs(d2)));
    const intersectPoint = _v15.copy(capsule.start).lerp(capsule.end, delta);
    if (triangle.containsPoint(intersectPoint)) {
      return { normal: _plane4.normal.clone(), point: intersectPoint.clone(), depth: Math.abs(Math.min(d1, d2)) };
    }
    const r2 = capsule.radius * capsule.radius;
    const line1 = _line1.set(capsule.start, capsule.end);
    const lines = [
      [triangle.a, triangle.b],
      [triangle.b, triangle.c],
      [triangle.c, triangle.a]
    ];
    for (let i = 0; i < lines.length; i++) {
      const line2 = _line2.set(lines[i][0], lines[i][1]);
      lineToLineClosestPoints(line1, line2, _point1, _point2);
      if (_point1.distanceToSquared(_point2) < r2) {
        return {
          normal: _point1.clone().sub(_point2).normalize(),
          point: _point2.clone(),
          depth: capsule.radius - _point1.distanceTo(_point2)
        };
      }
    }
    return false;
  }
  /**
   * Computes the intersection between the given sphere and triangle.
   *
   * @param {Sphere} sphere - The sphere to test.
   * @param {Triangle} triangle - The triangle to test.
   * @return {Object|false} The intersection object. If no intersection
   * is detected, the method returns `false`.
   */
  triangleSphereIntersect(sphere, triangle) {
    triangle.getPlane(_plane4);
    if (!sphere.intersectsPlane(_plane4)) return false;
    const depth = Math.abs(_plane4.distanceToSphere(sphere));
    const r2 = sphere.radius * sphere.radius - depth * depth;
    const plainPoint = _plane4.projectPoint(sphere.center, _v15);
    if (triangle.containsPoint(sphere.center)) {
      return { normal: _plane4.normal.clone(), point: plainPoint.clone(), depth: Math.abs(_plane4.distanceToSphere(sphere)) };
    }
    const lines = [
      [triangle.a, triangle.b],
      [triangle.b, triangle.c],
      [triangle.c, triangle.a]
    ];
    for (let i = 0; i < lines.length; i++) {
      _line1.set(lines[i][0], lines[i][1]);
      _line1.closestPointToPoint(plainPoint, true, _v25);
      const d = _v25.distanceToSquared(sphere.center);
      if (d < r2) {
        return { normal: sphere.center.clone().sub(_v25).normalize(), point: _v25.clone(), depth: sphere.radius - Math.sqrt(d) };
      }
    }
    return false;
  }
  /**
   * Computes the triangles that potentially intersect with the given bounding sphere.
   *
   * @param {Sphere} sphere - The sphere to test.
   * @param {Array<Triangle>} triangles - The target array that holds the triangles.
   */
  getSphereTriangles(sphere, triangles) {
    for (let i = 0; i < this.subTrees.length; i++) {
      const subTree = this.subTrees[i];
      if (!sphere.intersectsBox(subTree.box)) continue;
      if (subTree.triangles.length > 0) {
        for (let j2 = 0; j2 < subTree.triangles.length; j2++) {
          if (triangles.indexOf(subTree.triangles[j2]) === -1) triangles.push(subTree.triangles[j2]);
        }
      } else {
        subTree.getSphereTriangles(sphere, triangles);
      }
    }
  }
  /**
   * Computes the triangles that potentially intersect with the given capsule.
   *
   * @param {Capsule} capsule - The capsule to test.
   * @param {Array<Triangle>} triangles - The target array that holds the triangles.
   */
  getCapsuleTriangles(capsule, triangles) {
    for (let i = 0; i < this.subTrees.length; i++) {
      const subTree = this.subTrees[i];
      if (!capsule.intersectsBox(subTree.box)) continue;
      if (subTree.triangles.length > 0) {
        for (let j2 = 0; j2 < subTree.triangles.length; j2++) {
          if (triangles.indexOf(subTree.triangles[j2]) === -1) triangles.push(subTree.triangles[j2]);
        }
      } else {
        subTree.getCapsuleTriangles(capsule, triangles);
      }
    }
  }
  /**
   * Performs a bounding sphere intersection test with this Octree.
   *
   * @param {Sphere} sphere - The bounding sphere to test.
   * @return {Object|boolean} The intersection object. If no intersection
   * is detected, the method returns `false`.
   */
  sphereIntersect(sphere) {
    _sphere2.copy(sphere);
    const triangles = [];
    let result, hit = false;
    this.getSphereTriangles(sphere, triangles);
    for (let i = 0; i < triangles.length; i++) {
      if (result = this.triangleSphereIntersect(_sphere2, triangles[i])) {
        hit = true;
        _sphere2.center.add(result.normal.multiplyScalar(result.depth));
      }
    }
    if (hit) {
      const collisionVector = _sphere2.center.clone().sub(sphere.center);
      const depth = collisionVector.length();
      return { normal: collisionVector.normalize(), depth };
    }
    return false;
  }
  /**
   * Performs a capsule intersection test with this Octree.
   *
   * @param {Capsule} capsule - The capsule to test.
   * @return {Object|boolean} The intersection object. If no intersection
   * is detected, the method returns `false`.
   */
  capsuleIntersect(capsule) {
    _capsule.copy(capsule);
    const triangles = [];
    let result, hit = false;
    this.getCapsuleTriangles(_capsule, triangles);
    for (let i = 0; i < triangles.length; i++) {
      if (result = this.triangleCapsuleIntersect(_capsule, triangles[i])) {
        hit = true;
        _capsule.translate(result.normal.multiplyScalar(result.depth));
      }
    }
    if (hit) {
      const collisionVector = _capsule.getCenter(new Vector3()).sub(capsule.getCenter(_v15));
      const depth = collisionVector.length();
      return { normal: collisionVector.normalize(), depth };
    }
    return false;
  }
  /**
   * Performs a ray intersection test with this Octree.
   *
   * @param {Ray} ray - The ray to test.
   * @return {Object|boolean} The nearest intersection object. If no intersection
   * is detected, the method returns `false`.
   */
  rayIntersect(ray) {
    const triangles = [];
    let triangle, position2, distance = 1e100;
    this.getRayTriangles(ray, triangles);
    for (let i = 0; i < triangles.length; i++) {
      const result = ray.intersectTriangle(triangles[i].a, triangles[i].b, triangles[i].c, true, _v15);
      if (result) {
        const newdistance = result.sub(ray.origin).length();
        if (distance > newdistance) {
          position2 = result.clone().add(ray.origin);
          distance = newdistance;
          triangle = triangles[i];
        }
      }
    }
    return distance < 1e100 ? { distance, triangle, position: position2 } : false;
  }
  /**
   * Constructs the Octree from the given 3D object.
   *
   * @param {Object3D} group - The scene graph node.
   * @return {Octree} A reference to this Octree.
   */
  fromGraphNode(group) {
    group.updateWorldMatrix(true, true);
    group.traverse((obj) => {
      if (obj.isMesh === true) {
        if (this.layers.test(obj.layers)) {
          let geometry, isTemp = false;
          if (obj.geometry.index !== null) {
            isTemp = true;
            geometry = obj.geometry.toNonIndexed();
          } else {
            geometry = obj.geometry;
          }
          const positionAttribute = geometry.getAttribute("position");
          for (let i = 0; i < positionAttribute.count; i += 3) {
            const v12 = new Vector3().fromBufferAttribute(positionAttribute, i);
            const v2 = new Vector3().fromBufferAttribute(positionAttribute, i + 1);
            const v3 = new Vector3().fromBufferAttribute(positionAttribute, i + 2);
            v12.applyMatrix4(obj.matrixWorld);
            v2.applyMatrix4(obj.matrixWorld);
            v3.applyMatrix4(obj.matrixWorld);
            this.addTriangle(new Triangle(v12, v2, v3));
          }
          if (isTemp) {
            geometry.dispose();
          }
        }
      }
    });
    this.build();
    return this;
  }
  /**
   * Clears the Octree by making it empty.
   *
   * @return {Octree} A reference to this Octree.
   */
  clear() {
    this.box = null;
    this.bounds.makeEmpty();
    this.subTrees.length = 0;
    this.triangles.length = 0;
    return this;
  }
};

// node_modules/three/examples/jsm/math/SimplexNoise.js
var SimplexNoise = class {
  /**
   * Constructs a new simplex noise object.
   *
   * @param {Object} [r=Math] - A math utility class that holds a `random()` method. This makes it
   * possible to pass in custom random number generator.
   */
  constructor(r = Math) {
    this.grad3 = [
      [1, 1, 0],
      [-1, 1, 0],
      [1, -1, 0],
      [-1, -1, 0],
      [1, 0, 1],
      [-1, 0, 1],
      [1, 0, -1],
      [-1, 0, -1],
      [0, 1, 1],
      [0, -1, 1],
      [0, 1, -1],
      [0, -1, -1]
    ];
    this.grad4 = [
      [0, 1, 1, 1],
      [0, 1, 1, -1],
      [0, 1, -1, 1],
      [0, 1, -1, -1],
      [0, -1, 1, 1],
      [0, -1, 1, -1],
      [0, -1, -1, 1],
      [0, -1, -1, -1],
      [1, 0, 1, 1],
      [1, 0, 1, -1],
      [1, 0, -1, 1],
      [1, 0, -1, -1],
      [-1, 0, 1, 1],
      [-1, 0, 1, -1],
      [-1, 0, -1, 1],
      [-1, 0, -1, -1],
      [1, 1, 0, 1],
      [1, 1, 0, -1],
      [1, -1, 0, 1],
      [1, -1, 0, -1],
      [-1, 1, 0, 1],
      [-1, 1, 0, -1],
      [-1, -1, 0, 1],
      [-1, -1, 0, -1],
      [1, 1, 1, 0],
      [1, 1, -1, 0],
      [1, -1, 1, 0],
      [1, -1, -1, 0],
      [-1, 1, 1, 0],
      [-1, 1, -1, 0],
      [-1, -1, 1, 0],
      [-1, -1, -1, 0]
    ];
    this.p = [];
    for (let i = 0; i < 256; i++) {
      this.p[i] = Math.floor(r.random() * 256);
    }
    this.perm = [];
    for (let i = 0; i < 512; i++) {
      this.perm[i] = this.p[i & 255];
    }
    this.simplex = [
      [0, 1, 2, 3],
      [0, 1, 3, 2],
      [0, 0, 0, 0],
      [0, 2, 3, 1],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [1, 2, 3, 0],
      [0, 2, 1, 3],
      [0, 0, 0, 0],
      [0, 3, 1, 2],
      [0, 3, 2, 1],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [1, 3, 2, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [1, 2, 0, 3],
      [0, 0, 0, 0],
      [1, 3, 0, 2],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [2, 3, 0, 1],
      [2, 3, 1, 0],
      [1, 0, 2, 3],
      [1, 0, 3, 2],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [2, 0, 3, 1],
      [0, 0, 0, 0],
      [2, 1, 3, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [2, 0, 1, 3],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [3, 0, 1, 2],
      [3, 0, 2, 1],
      [0, 0, 0, 0],
      [3, 1, 2, 0],
      [2, 1, 0, 3],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [3, 1, 0, 2],
      [0, 0, 0, 0],
      [3, 2, 0, 1],
      [3, 2, 1, 0]
    ];
  }
  /**
   * A 2D simplex noise method.
   *
   * @param {number} xin - The x coordinate.
   * @param {number} yin - The y coordinate.
   * @return {number} The noise value.
   */
  noise(xin, yin) {
    let n0;
    let n1;
    let n2;
    const F2 = 0.5 * (Math.sqrt(3) - 1);
    const s = (xin + yin) * F2;
    const i = Math.floor(xin + s);
    const j2 = Math.floor(yin + s);
    const G2 = (3 - Math.sqrt(3)) / 6;
    const t3 = (i + j2) * G2;
    const X0 = i - t3;
    const Y0 = j2 - t3;
    const x0 = xin - X0;
    const y0 = yin - Y0;
    let i1;
    let j1;
    if (x0 > y0) {
      i1 = 1;
      j1 = 0;
    } else {
      i1 = 0;
      j1 = 1;
    }
    const x1 = x0 - i1 + G2;
    const y1 = y0 - j1 + G2;
    const x2 = x0 - 1 + 2 * G2;
    const y2 = y0 - 1 + 2 * G2;
    const ii = i & 255;
    const jj = j2 & 255;
    const gi0 = this.perm[ii + this.perm[jj]] % 12;
    const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12;
    const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12;
    let t0 = 0.5 - x0 * x0 - y0 * y0;
    if (t0 < 0) n0 = 0;
    else {
      t0 *= t0;
      n0 = t0 * t0 * this._dot(this.grad3[gi0], x0, y0);
    }
    let t1 = 0.5 - x1 * x1 - y1 * y1;
    if (t1 < 0) n1 = 0;
    else {
      t1 *= t1;
      n1 = t1 * t1 * this._dot(this.grad3[gi1], x1, y1);
    }
    let t22 = 0.5 - x2 * x2 - y2 * y2;
    if (t22 < 0) n2 = 0;
    else {
      t22 *= t22;
      n2 = t22 * t22 * this._dot(this.grad3[gi2], x2, y2);
    }
    return 70 * (n0 + n1 + n2);
  }
  /**
   * A 3D simplex noise method.
   *
   * @param {number} xin - The x coordinate.
   * @param {number} yin - The y coordinate.
   * @param {number} zin - The z coordinate.
   * @return {number} The noise value.
   */
  noise3d(xin, yin, zin) {
    let n0;
    let n1;
    let n2;
    let n3;
    const F3 = 1 / 3;
    const s = (xin + yin + zin) * F3;
    const i = Math.floor(xin + s);
    const j2 = Math.floor(yin + s);
    const k2 = Math.floor(zin + s);
    const G3 = 1 / 6;
    const t3 = (i + j2 + k2) * G3;
    const X0 = i - t3;
    const Y0 = j2 - t3;
    const Z0 = k2 - t3;
    const x0 = xin - X0;
    const y0 = yin - Y0;
    const z0 = zin - Z0;
    let i1;
    let j1;
    let k1;
    let i2;
    let j22;
    let k22;
    if (x0 >= y0) {
      if (y0 >= z0) {
        i1 = 1;
        j1 = 0;
        k1 = 0;
        i2 = 1;
        j22 = 1;
        k22 = 0;
      } else if (x0 >= z0) {
        i1 = 1;
        j1 = 0;
        k1 = 0;
        i2 = 1;
        j22 = 0;
        k22 = 1;
      } else {
        i1 = 0;
        j1 = 0;
        k1 = 1;
        i2 = 1;
        j22 = 0;
        k22 = 1;
      }
    } else {
      if (y0 < z0) {
        i1 = 0;
        j1 = 0;
        k1 = 1;
        i2 = 0;
        j22 = 1;
        k22 = 1;
      } else if (x0 < z0) {
        i1 = 0;
        j1 = 1;
        k1 = 0;
        i2 = 0;
        j22 = 1;
        k22 = 1;
      } else {
        i1 = 0;
        j1 = 1;
        k1 = 0;
        i2 = 1;
        j22 = 1;
        k22 = 0;
      }
    }
    const x1 = x0 - i1 + G3;
    const y1 = y0 - j1 + G3;
    const z1 = z0 - k1 + G3;
    const x2 = x0 - i2 + 2 * G3;
    const y2 = y0 - j22 + 2 * G3;
    const z2 = z0 - k22 + 2 * G3;
    const x3 = x0 - 1 + 3 * G3;
    const y3 = y0 - 1 + 3 * G3;
    const z3 = z0 - 1 + 3 * G3;
    const ii = i & 255;
    const jj = j2 & 255;
    const kk = k2 & 255;
    const gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12;
    const gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12;
    const gi2 = this.perm[ii + i2 + this.perm[jj + j22 + this.perm[kk + k22]]] % 12;
    const gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12;
    let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
    if (t0 < 0) n0 = 0;
    else {
      t0 *= t0;
      n0 = t0 * t0 * this._dot3(this.grad3[gi0], x0, y0, z0);
    }
    let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
    if (t1 < 0) n1 = 0;
    else {
      t1 *= t1;
      n1 = t1 * t1 * this._dot3(this.grad3[gi1], x1, y1, z1);
    }
    let t22 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
    if (t22 < 0) n2 = 0;
    else {
      t22 *= t22;
      n2 = t22 * t22 * this._dot3(this.grad3[gi2], x2, y2, z2);
    }
    let t32 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
    if (t32 < 0) n3 = 0;
    else {
      t32 *= t32;
      n3 = t32 * t32 * this._dot3(this.grad3[gi3], x3, y3, z3);
    }
    return 32 * (n0 + n1 + n2 + n3);
  }
  /**
   * A 4D simplex noise method.
   *
   * @param {number} x - The x coordinate.
   * @param {number} y - The y coordinate.
   * @param {number} z - The z coordinate.
   * @param {number} w - The w coordinate.
   * @return {number} The noise value.
   */
  noise4d(x2, y, z, w) {
    const grad4 = this.grad4;
    const simplex = this.simplex;
    const perm = this.perm;
    const F4 = (Math.sqrt(5) - 1) / 4;
    const G4 = (5 - Math.sqrt(5)) / 20;
    let n0;
    let n1;
    let n2;
    let n3;
    let n4;
    const s = (x2 + y + z + w) * F4;
    const i = Math.floor(x2 + s);
    const j2 = Math.floor(y + s);
    const k2 = Math.floor(z + s);
    const l2 = Math.floor(w + s);
    const t3 = (i + j2 + k2 + l2) * G4;
    const X0 = i - t3;
    const Y0 = j2 - t3;
    const Z0 = k2 - t3;
    const W0 = l2 - t3;
    const x0 = x2 - X0;
    const y0 = y - Y0;
    const z0 = z - Z0;
    const w0 = w - W0;
    const c1 = x0 > y0 ? 32 : 0;
    const c2 = x0 > z0 ? 16 : 0;
    const c3 = y0 > z0 ? 8 : 0;
    const c4 = x0 > w0 ? 4 : 0;
    const c5 = y0 > w0 ? 2 : 0;
    const c6 = z0 > w0 ? 1 : 0;
    const c7 = c1 + c2 + c3 + c4 + c5 + c6;
    const i1 = simplex[c7][0] >= 3 ? 1 : 0;
    const j1 = simplex[c7][1] >= 3 ? 1 : 0;
    const k1 = simplex[c7][2] >= 3 ? 1 : 0;
    const l1 = simplex[c7][3] >= 3 ? 1 : 0;
    const i2 = simplex[c7][0] >= 2 ? 1 : 0;
    const j22 = simplex[c7][1] >= 2 ? 1 : 0;
    const k22 = simplex[c7][2] >= 2 ? 1 : 0;
    const l22 = simplex[c7][3] >= 2 ? 1 : 0;
    const i3 = simplex[c7][0] >= 1 ? 1 : 0;
    const j3 = simplex[c7][1] >= 1 ? 1 : 0;
    const k3 = simplex[c7][2] >= 1 ? 1 : 0;
    const l3 = simplex[c7][3] >= 1 ? 1 : 0;
    const x1 = x0 - i1 + G4;
    const y1 = y0 - j1 + G4;
    const z1 = z0 - k1 + G4;
    const w1 = w0 - l1 + G4;
    const x22 = x0 - i2 + 2 * G4;
    const y2 = y0 - j22 + 2 * G4;
    const z2 = z0 - k22 + 2 * G4;
    const w2 = w0 - l22 + 2 * G4;
    const x3 = x0 - i3 + 3 * G4;
    const y3 = y0 - j3 + 3 * G4;
    const z3 = z0 - k3 + 3 * G4;
    const w3 = w0 - l3 + 3 * G4;
    const x4 = x0 - 1 + 4 * G4;
    const y4 = y0 - 1 + 4 * G4;
    const z4 = z0 - 1 + 4 * G4;
    const w4 = w0 - 1 + 4 * G4;
    const ii = i & 255;
    const jj = j2 & 255;
    const kk = k2 & 255;
    const ll = l2 & 255;
    const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32;
    const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32;
    const gi2 = perm[ii + i2 + perm[jj + j22 + perm[kk + k22 + perm[ll + l22]]]] % 32;
    const gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32;
    const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32;
    let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
    if (t0 < 0) n0 = 0;
    else {
      t0 *= t0;
      n0 = t0 * t0 * this._dot4(grad4[gi0], x0, y0, z0, w0);
    }
    let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
    if (t1 < 0) n1 = 0;
    else {
      t1 *= t1;
      n1 = t1 * t1 * this._dot4(grad4[gi1], x1, y1, z1, w1);
    }
    let t22 = 0.6 - x22 * x22 - y2 * y2 - z2 * z2 - w2 * w2;
    if (t22 < 0) n2 = 0;
    else {
      t22 *= t22;
      n2 = t22 * t22 * this._dot4(grad4[gi2], x22, y2, z2, w2);
    }
    let t32 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
    if (t32 < 0) n3 = 0;
    else {
      t32 *= t32;
      n3 = t32 * t32 * this._dot4(grad4[gi3], x3, y3, z3, w3);
    }
    let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
    if (t4 < 0) n4 = 0;
    else {
      t4 *= t4;
      n4 = t4 * t4 * this._dot4(grad4[gi4], x4, y4, z4, w4);
    }
    return 27 * (n0 + n1 + n2 + n3 + n4);
  }
  // private
  _dot(g3, x2, y) {
    return g3[0] * x2 + g3[1] * y;
  }
  _dot3(g3, x2, y, z) {
    return g3[0] * x2 + g3[1] * y + g3[2] * z;
  }
  _dot4(g3, x2, y, z, w) {
    return g3[0] * x2 + g3[1] * y + g3[2] * z + g3[3] * w;
  }
};

// node_modules/three/examples/jsm/misc/ConvexObjectBreaker.js
var _v16 = new Vector3();
var ConvexObjectBreaker = class _ConvexObjectBreaker {
  /**
   * Constructs a new convex object breaker.
   *
   * @param {number} [minSizeForBreak=1.4] - Min size a debris can have to break.
  	 * @param {number} [smallDelta=0.0001] - Max distance to consider that a point belongs to a plane.
   */
  constructor(minSizeForBreak = 1.4, smallDelta = 1e-4) {
    this.minSizeForBreak = minSizeForBreak;
    this.smallDelta = smallDelta;
    this.tempLine1 = new Line3();
    this.tempPlane1 = new Plane();
    this.tempPlane2 = new Plane();
    this.tempPlane_Cut = new Plane();
    this.tempCM1 = new Vector3();
    this.tempCM2 = new Vector3();
    this.tempVector3 = new Vector3();
    this.tempVector3_2 = new Vector3();
    this.tempVector3_3 = new Vector3();
    this.tempVector3_P0 = new Vector3();
    this.tempVector3_P1 = new Vector3();
    this.tempVector3_P2 = new Vector3();
    this.tempVector3_N0 = new Vector3();
    this.tempVector3_N1 = new Vector3();
    this.tempVector3_AB = new Vector3();
    this.tempVector3_CB = new Vector3();
    this.tempResultObjects = { object1: null, object2: null };
    this.segments = [];
    const n2 = 30 * 30;
    for (let i = 0; i < n2; i++) this.segments[i] = false;
  }
  /**
   * Must be called for all 3D objects that should be breakable.
   *
   * @param {Object3D} object - The 3D object. It must have a convex geometry.
   * @param {number} mass - The 3D object's mass in kg. Must be greater than `0`.
   * @param {Vector3} velocity - The 3D object's velocity.
   * @param {Vector3} angularVelocity - The 3D object's angular velocity.
   * @param {boolean} breakable - Whether the 3D object is breakable or not.
   */
  prepareBreakableObject(object, mass, velocity2, angularVelocity, breakable) {
    const userData = object.userData;
    userData.mass = mass;
    userData.velocity = velocity2.clone();
    userData.angularVelocity = angularVelocity.clone();
    userData.breakable = breakable;
  }
  /**
   * Subdivides the given 3D object into pieces by an impact (meaning another object hits
   * the given 3D object at a certain surface point).
   *
   * @param {Object3D} object - The 3D object to subdivide.
   * @param {Vector3} pointOfImpact - The point of impact.
   * @param {Vector3} normal - The impact normal.
   * @param {number} maxRadialIterations - Iterations for radial cuts.
   * @param {number} maxRandomIterations - Max random iterations for not-radial cuts.
   * @return {Array<Object3D>} The array of pieces.
   */
  subdivideByImpact(object, pointOfImpact, normal, maxRadialIterations, maxRandomIterations) {
    const debris = [];
    const tempPlane1 = this.tempPlane1;
    const tempPlane2 = this.tempPlane2;
    this.tempVector3.addVectors(pointOfImpact, normal);
    tempPlane1.setFromCoplanarPoints(pointOfImpact, object.position, this.tempVector3);
    const maxTotalIterations = maxRandomIterations + maxRadialIterations;
    const scope = this;
    function subdivideRadial(subObject, startAngle, endAngle, numIterations) {
      if (Math.random() < numIterations * 0.05 || numIterations > maxTotalIterations) {
        debris.push(subObject);
        return;
      }
      let angle = Math.PI;
      if (numIterations === 0) {
        tempPlane2.normal.copy(tempPlane1.normal);
        tempPlane2.constant = tempPlane1.constant;
      } else {
        if (numIterations <= maxRadialIterations) {
          angle = (endAngle - startAngle) * (0.2 + 0.6 * Math.random()) + startAngle;
          scope.tempVector3_2.copy(object.position).sub(pointOfImpact).applyAxisAngle(normal, angle).add(pointOfImpact);
          tempPlane2.setFromCoplanarPoints(pointOfImpact, scope.tempVector3, scope.tempVector3_2);
        } else {
          angle = (0.5 * (numIterations & 1) + 0.2 * (2 - Math.random())) * Math.PI;
          scope.tempVector3_2.copy(pointOfImpact).sub(subObject.position).applyAxisAngle(normal, angle).add(subObject.position);
          scope.tempVector3_3.copy(normal).add(subObject.position);
          tempPlane2.setFromCoplanarPoints(subObject.position, scope.tempVector3_3, scope.tempVector3_2);
        }
      }
      scope.cutByPlane(subObject, tempPlane2, scope.tempResultObjects);
      const obj1 = scope.tempResultObjects.object1;
      const obj2 = scope.tempResultObjects.object2;
      if (obj1) {
        subdivideRadial(obj1, startAngle, angle, numIterations + 1);
      }
      if (obj2) {
        subdivideRadial(obj2, angle, endAngle, numIterations + 1);
      }
    }
    subdivideRadial(object, 0, 2 * Math.PI, 0);
    return debris;
  }
  /**
   * Subdivides the given 3D object into pieces by a plane.
   *
   * @param {Object3D} object - The 3D object to subdivide.
   * @param {Plane} plane - The plane to cut the 3D object.
   * @param {{object1:?Mesh,object2:?Mesh}} output - An object that stores the pieces.
   * @return {number} The number of pieces.
   */
  cutByPlane(object, plane2, output) {
    const geometry = object.geometry;
    const coords = geometry.attributes.position.array;
    const normals = geometry.attributes.normal.array;
    const numPoints = coords.length / 3;
    let numFaces = numPoints / 3;
    let indices = geometry.getIndex();
    if (indices) {
      indices = indices.array;
      numFaces = indices.length / 3;
    }
    function getVertexIndex(faceIdx, vert) {
      const idx = faceIdx * 3 + vert;
      return indices ? indices[idx] : idx;
    }
    const points1 = [];
    const points2 = [];
    const delta = this.smallDelta;
    const numPointPairs = numPoints * numPoints;
    for (let i = 0; i < numPointPairs; i++) this.segments[i] = false;
    const p0 = this.tempVector3_P0;
    const p1 = this.tempVector3_P1;
    const n0 = this.tempVector3_N0;
    const n1 = this.tempVector3_N1;
    for (let i = 0; i < numFaces - 1; i++) {
      const a1 = getVertexIndex(i, 0);
      const b1 = getVertexIndex(i, 1);
      const c1 = getVertexIndex(i, 2);
      n0.set(normals[a1], normals[a1] + 1, normals[a1] + 2);
      for (let j2 = i + 1; j2 < numFaces; j2++) {
        const a2 = getVertexIndex(j2, 0);
        const b22 = getVertexIndex(j2, 1);
        const c2 = getVertexIndex(j2, 2);
        n1.set(normals[a2], normals[a2] + 1, normals[a2] + 2);
        const coplanar = 1 - n0.dot(n1) < delta;
        if (coplanar) {
          if (a1 === a2 || a1 === b22 || a1 === c2) {
            if (b1 === a2 || b1 === b22 || b1 === c2) {
              this.segments[a1 * numPoints + b1] = true;
              this.segments[b1 * numPoints + a1] = true;
            } else {
              this.segments[c1 * numPoints + a1] = true;
              this.segments[a1 * numPoints + c1] = true;
            }
          } else if (b1 === a2 || b1 === b22 || b1 === c2) {
            this.segments[c1 * numPoints + b1] = true;
            this.segments[b1 * numPoints + c1] = true;
          }
        }
      }
    }
    const localPlane = this.tempPlane_Cut;
    object.updateMatrix();
    _ConvexObjectBreaker.transformPlaneToLocalSpace(plane2, object.matrix, localPlane);
    for (let i = 0; i < numFaces; i++) {
      const va2 = getVertexIndex(i, 0);
      const vb = getVertexIndex(i, 1);
      const vc = getVertexIndex(i, 2);
      for (let segment = 0; segment < 3; segment++) {
        const i0 = segment === 0 ? va2 : segment === 1 ? vb : vc;
        const i1 = segment === 0 ? vb : segment === 1 ? vc : va2;
        const segmentState = this.segments[i0 * numPoints + i1];
        if (segmentState) continue;
        this.segments[i0 * numPoints + i1] = true;
        this.segments[i1 * numPoints + i0] = true;
        p0.set(coords[3 * i0], coords[3 * i0 + 1], coords[3 * i0 + 2]);
        p1.set(coords[3 * i1], coords[3 * i1 + 1], coords[3 * i1 + 2]);
        let mark0 = 0;
        let d = localPlane.distanceToPoint(p0);
        if (d > delta) {
          mark0 = 2;
          points2.push(p0.clone());
        } else if (d < -delta) {
          mark0 = 1;
          points1.push(p0.clone());
        } else {
          mark0 = 3;
          points1.push(p0.clone());
          points2.push(p0.clone());
        }
        let mark1 = 0;
        d = localPlane.distanceToPoint(p1);
        if (d > delta) {
          mark1 = 2;
          points2.push(p1.clone());
        } else if (d < -delta) {
          mark1 = 1;
          points1.push(p1.clone());
        } else {
          mark1 = 3;
          points1.push(p1.clone());
          points2.push(p1.clone());
        }
        if (mark0 === 1 && mark1 === 2 || mark0 === 2 && mark1 === 1) {
          this.tempLine1.start.copy(p0);
          this.tempLine1.end.copy(p1);
          let intersection = new Vector3();
          intersection = localPlane.intersectLine(this.tempLine1, intersection);
          if (intersection === null) {
            console.error("Internal error: segment does not intersect plane.");
            output.segmentedObject1 = null;
            output.segmentedObject2 = null;
            return 0;
          }
          points1.push(intersection);
          points2.push(intersection.clone());
        }
      }
    }
    const newMass = object.userData.mass * 0.5;
    this.tempCM1.set(0, 0, 0);
    let radius1 = 0;
    const numPoints1 = points1.length;
    if (numPoints1 > 0) {
      for (let i = 0; i < numPoints1; i++) this.tempCM1.add(points1[i]);
      this.tempCM1.divideScalar(numPoints1);
      for (let i = 0; i < numPoints1; i++) {
        const p = points1[i];
        p.sub(this.tempCM1);
        radius1 = Math.max(radius1, p.x, p.y, p.z);
      }
      this.tempCM1.add(object.position);
    }
    this.tempCM2.set(0, 0, 0);
    let radius2 = 0;
    const numPoints2 = points2.length;
    if (numPoints2 > 0) {
      for (let i = 0; i < numPoints2; i++) this.tempCM2.add(points2[i]);
      this.tempCM2.divideScalar(numPoints2);
      for (let i = 0; i < numPoints2; i++) {
        const p = points2[i];
        p.sub(this.tempCM2);
        radius2 = Math.max(radius2, p.x, p.y, p.z);
      }
      this.tempCM2.add(object.position);
    }
    let object1 = null;
    let object2 = null;
    let numObjects = 0;
    if (numPoints1 > 4) {
      object1 = new Mesh(new ConvexGeometry(points1), object.material);
      object1.position.copy(this.tempCM1);
      object1.quaternion.copy(object.quaternion);
      this.prepareBreakableObject(object1, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius1 > this.minSizeForBreak);
      numObjects++;
    }
    if (numPoints2 > 4) {
      object2 = new Mesh(new ConvexGeometry(points2), object.material);
      object2.position.copy(this.tempCM2);
      object2.quaternion.copy(object.quaternion);
      this.prepareBreakableObject(object2, newMass, object.userData.velocity, object.userData.angularVelocity, 2 * radius2 > this.minSizeForBreak);
      numObjects++;
    }
    output.object1 = object1;
    output.object2 = object2;
    return numObjects;
  }
  // internal helpers
  static transformFreeVector(v, m) {
    const x2 = v.x, y = v.y, z = v.z;
    const e = m.elements;
    v.x = e[0] * x2 + e[4] * y + e[8] * z;
    v.y = e[1] * x2 + e[5] * y + e[9] * z;
    v.z = e[2] * x2 + e[6] * y + e[10] * z;
    return v;
  }
  static transformFreeVectorInverse(v, m) {
    const x2 = v.x, y = v.y, z = v.z;
    const e = m.elements;
    v.x = e[0] * x2 + e[1] * y + e[2] * z;
    v.y = e[4] * x2 + e[5] * y + e[6] * z;
    v.z = e[8] * x2 + e[9] * y + e[10] * z;
    return v;
  }
  static transformTiedVectorInverse(v, m) {
    const x2 = v.x, y = v.y, z = v.z;
    const e = m.elements;
    v.x = e[0] * x2 + e[1] * y + e[2] * z - e[12];
    v.y = e[4] * x2 + e[5] * y + e[6] * z - e[13];
    v.z = e[8] * x2 + e[9] * y + e[10] * z - e[14];
    return v;
  }
  static transformPlaneToLocalSpace(plane2, m, resultPlane) {
    resultPlane.normal.copy(plane2.normal);
    resultPlane.constant = plane2.constant;
    const referencePoint = _ConvexObjectBreaker.transformTiedVectorInverse(plane2.coplanarPoint(_v16), m);
    _ConvexObjectBreaker.transformFreeVectorInverse(resultPlane.normal, m);
    resultPlane.constant = -referencePoint.dot(resultPlane.normal);
  }
};

// node_modules/three/examples/jsm/misc/GPUComputationRenderer.js
var GPUComputationRenderer = class {
  /**
   * Constructs a new GPU computation renderer.
   *
   * @param {number} sizeX - Computation problem size is always 2d: sizeX * sizeY elements.
  	 * @param {number} sizeY - Computation problem size is always 2d: sizeX * sizeY elements.
  	 * @param {WebGLRenderer} renderer - The renderer.
   */
  constructor(sizeX, sizeY, renderer2) {
    this.variables = [];
    this.currentTextureIndex = 0;
    let dataType = FloatType;
    const passThruUniforms = {
      passThruTexture: { value: null }
    };
    const passThruShader = createShaderMaterial(getPassThroughFragmentShader(), passThruUniforms);
    const quad = new FullScreenQuad(passThruShader);
    this.setDataType = function(type) {
      dataType = type;
      return this;
    };
    this.addVariable = function(variableName, computeFragmentShader, initialValueTexture) {
      const material = this.createShaderMaterial(computeFragmentShader);
      const variable = {
        name: variableName,
        initialValueTexture,
        material,
        dependencies: null,
        renderTargets: [],
        wrapS: null,
        wrapT: null,
        minFilter: NearestFilter,
        magFilter: NearestFilter
      };
      this.variables.push(variable);
      return variable;
    };
    this.setVariableDependencies = function(variable, dependencies) {
      variable.dependencies = dependencies;
    };
    this.init = function() {
      if (renderer2.capabilities.maxVertexTextures === 0) {
        return "No support for vertex shader textures.";
      }
      for (let i = 0; i < this.variables.length; i++) {
        const variable = this.variables[i];
        variable.renderTargets[0] = this.createRenderTarget(sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter);
        variable.renderTargets[1] = this.createRenderTarget(sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter);
        this.renderTexture(variable.initialValueTexture, variable.renderTargets[0]);
        this.renderTexture(variable.initialValueTexture, variable.renderTargets[1]);
        const material = variable.material;
        const uniforms = material.uniforms;
        if (variable.dependencies !== null) {
          for (let d = 0; d < variable.dependencies.length; d++) {
            const depVar = variable.dependencies[d];
            if (depVar.name !== variable.name) {
              let found = false;
              for (let j2 = 0; j2 < this.variables.length; j2++) {
                if (depVar.name === this.variables[j2].name) {
                  found = true;
                  break;
                }
              }
              if (!found) {
                return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
              }
            }
            uniforms[depVar.name] = { value: null };
            material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
          }
        }
      }
      this.currentTextureIndex = 0;
      return null;
    };
    this.compute = function() {
      const currentTextureIndex = this.currentTextureIndex;
      const nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
      for (let i = 0, il = this.variables.length; i < il; i++) {
        const variable = this.variables[i];
        if (variable.dependencies !== null) {
          const uniforms = variable.material.uniforms;
          for (let d = 0, dl = variable.dependencies.length; d < dl; d++) {
            const depVar = variable.dependencies[d];
            uniforms[depVar.name].value = depVar.renderTargets[currentTextureIndex].texture;
          }
        }
        this.doRenderTarget(variable.material, variable.renderTargets[nextTextureIndex]);
      }
      this.currentTextureIndex = nextTextureIndex;
    };
    this.getCurrentRenderTarget = function(variable) {
      return variable.renderTargets[this.currentTextureIndex];
    };
    this.getAlternateRenderTarget = function(variable) {
      return variable.renderTargets[this.currentTextureIndex === 0 ? 1 : 0];
    };
    this.dispose = function() {
      quad.dispose();
      const variables = this.variables;
      for (let i = 0; i < variables.length; i++) {
        const variable = variables[i];
        if (variable.initialValueTexture) variable.initialValueTexture.dispose();
        const renderTargets = variable.renderTargets;
        for (let j2 = 0; j2 < renderTargets.length; j2++) {
          const renderTarget = renderTargets[j2];
          renderTarget.dispose();
        }
      }
    };
    function addResolutionDefine(materialShader) {
      materialShader.defines.resolution = "vec2( " + sizeX.toFixed(1) + ", " + sizeY.toFixed(1) + " )";
    }
    this.addResolutionDefine = addResolutionDefine;
    function createShaderMaterial(computeFragmentShader, uniforms) {
      uniforms = uniforms || {};
      const material = new ShaderMaterial({
        name: "GPUComputationShader",
        uniforms,
        vertexShader: getPassThroughVertexShader(),
        fragmentShader: computeFragmentShader
      });
      addResolutionDefine(material);
      return material;
    }
    this.createShaderMaterial = createShaderMaterial;
    this.createRenderTarget = function(sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter) {
      sizeXTexture = sizeXTexture || sizeX;
      sizeYTexture = sizeYTexture || sizeY;
      wrapS = wrapS || ClampToEdgeWrapping;
      wrapT = wrapT || ClampToEdgeWrapping;
      minFilter = minFilter || NearestFilter;
      magFilter = magFilter || NearestFilter;
      const renderTarget = new WebGLRenderTarget(sizeXTexture, sizeYTexture, {
        wrapS,
        wrapT,
        minFilter,
        magFilter,
        format: RGBAFormat,
        type: dataType,
        depthBuffer: false
      });
      return renderTarget;
    };
    this.createTexture = function() {
      const data2 = new Float32Array(sizeX * sizeY * 4);
      const texture = new DataTexture(data2, sizeX, sizeY, RGBAFormat, FloatType);
      texture.needsUpdate = true;
      return texture;
    };
    this.renderTexture = function(input, output) {
      passThruUniforms.passThruTexture.value = input;
      this.doRenderTarget(passThruShader, output);
      passThruUniforms.passThruTexture.value = null;
    };
    this.doRenderTarget = function(material, output) {
      const currentRenderTarget = renderer2.getRenderTarget();
      const currentXrEnabled = renderer2.xr.enabled;
      const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate;
      renderer2.xr.enabled = false;
      renderer2.shadowMap.autoUpdate = false;
      quad.material = material;
      renderer2.setRenderTarget(output);
      quad.render(renderer2);
      quad.material = passThruShader;
      renderer2.xr.enabled = currentXrEnabled;
      renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate;
      renderer2.setRenderTarget(currentRenderTarget);
    };
    function getPassThroughVertexShader() {
      return "void main()	{\n\n	gl_Position = vec4( position, 1.0 );\n\n}\n";
    }
    function getPassThroughFragmentShader() {
      return "uniform sampler2D passThruTexture;\n\nvoid main() {\n\n	vec2 uv = gl_FragCoord.xy / resolution.xy;\n\n	gl_FragColor = texture2D( passThruTexture, uv );\n\n}\n";
    }
  }
};

// node_modules/three/examples/jsm/misc/Gyroscope.js
var _translationObject = new Vector3();
var _quaternionObject = new Quaternion();
var _scaleObject = new Vector3();
var _translationWorld = new Vector3();
var _quaternionWorld = new Quaternion();
var _scaleWorld = new Vector3();
var Gyroscope = class extends Object3D {
  /**
   * Constructs a new gyroscope.
   */
  constructor() {
    super();
  }
  updateMatrixWorld(force) {
    this.matrixAutoUpdate && this.updateMatrix();
    if (this.matrixWorldNeedsUpdate || force) {
      if (this.parent !== null) {
        this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
        this.matrixWorld.decompose(_translationWorld, _quaternionWorld, _scaleWorld);
        this.matrix.decompose(_translationObject, _quaternionObject, _scaleObject);
        this.matrixWorld.compose(_translationWorld, _quaternionObject, _scaleWorld);
      } else {
        this.matrixWorld.copy(this.matrix);
      }
      this.matrixWorldNeedsUpdate = false;
      force = true;
    }
    for (let i = 0, l2 = this.children.length; i < l2; i++) {
      this.children[i].updateMatrixWorld(force);
    }
  }
};

// node_modules/three/examples/jsm/misc/MD2Character.js
var MD2Character = class {
  /**
   * Constructs a new MD2 character.
   */
  constructor() {
    this.scale = 1;
    this.animationFPS = 6;
    this.root = new Object3D();
    this.meshBody = null;
    this.meshWeapon = null;
    this.skinsBody = [];
    this.skinsWeapon = [];
    this.weapons = [];
    this.activeAnimationClipName = null;
    this.mixer = null;
    this.onLoadComplete = function() {
    };
    this.loadCounter = 0;
  }
  /**
   * Loads the character model for the given config.
   *
   * @param {Object} config - The config which defines the model and textures paths.
   */
  loadParts(config) {
    const scope = this;
    function createPart(geometry, skinMap) {
      const materialWireframe = new MeshLambertMaterial({ color: 16755200, wireframe: true });
      const materialTexture = new MeshLambertMaterial({ color: 16777215, wireframe: false, map: skinMap });
      const mesh = new Mesh(geometry, materialTexture);
      mesh.rotation.y = -Math.PI / 2;
      mesh.castShadow = true;
      mesh.receiveShadow = true;
      mesh.materialTexture = materialTexture;
      mesh.materialWireframe = materialWireframe;
      return mesh;
    }
    function loadTextures(baseUrl, textureUrls) {
      const textureLoader = new TextureLoader();
      const textures = [];
      for (let i = 0; i < textureUrls.length; i++) {
        textures[i] = textureLoader.load(baseUrl + textureUrls[i], checkLoadingComplete);
        textures[i].mapping = UVMapping;
        textures[i].name = textureUrls[i];
        textures[i].colorSpace = SRGBColorSpace;
      }
      return textures;
    }
    function checkLoadingComplete() {
      scope.loadCounter -= 1;
      if (scope.loadCounter === 0) scope.onLoadComplete();
    }
    this.loadCounter = config.weapons.length * 2 + config.skins.length + 1;
    const weaponsTextures = [];
    for (let i = 0; i < config.weapons.length; i++) weaponsTextures[i] = config.weapons[i][1];
    this.skinsBody = loadTextures(config.baseUrl + "skins/", config.skins);
    this.skinsWeapon = loadTextures(config.baseUrl + "skins/", weaponsTextures);
    const loader = new MD2Loader();
    loader.load(config.baseUrl + config.body, function(geo) {
      const boundingBox = new Box3();
      boundingBox.setFromBufferAttribute(geo.attributes.position);
      scope.root.position.y = -scope.scale * boundingBox.min.y;
      const mesh = createPart(geo, scope.skinsBody[0]);
      mesh.scale.set(scope.scale, scope.scale, scope.scale);
      scope.root.add(mesh);
      scope.meshBody = mesh;
      scope.meshBody.clipOffset = 0;
      scope.activeAnimationClipName = mesh.geometry.animations[0].name;
      scope.mixer = new AnimationMixer(mesh);
      checkLoadingComplete();
    });
    const generateCallback = function(index2, name2) {
      return function(geo) {
        const mesh = createPart(geo, scope.skinsWeapon[index2]);
        mesh.scale.set(scope.scale, scope.scale, scope.scale);
        mesh.visible = false;
        mesh.name = name2;
        scope.root.add(mesh);
        scope.weapons[index2] = mesh;
        scope.meshWeapon = mesh;
        checkLoadingComplete();
      };
    };
    for (let i = 0; i < config.weapons.length; i++) {
      loader.load(config.baseUrl + config.weapons[i][0], generateCallback(i, config.weapons[i][0]));
    }
  }
  /**
   * Sets the animation playback rate.
   *
   * @param {number} rate - The playback rate to set.
   */
  setPlaybackRate(rate) {
    if (rate !== 0) {
      this.mixer.timeScale = 1 / rate;
    } else {
      this.mixer.timeScale = 0;
    }
  }
  /**
   * Sets the wireframe material flag.
   *
   * @param {boolean} wireframeEnabled - Whether to enable wireframe rendering or not.
   */
  setWireframe(wireframeEnabled) {
    if (wireframeEnabled) {
      if (this.meshBody) this.meshBody.material = this.meshBody.materialWireframe;
      if (this.meshWeapon) this.meshWeapon.material = this.meshWeapon.materialWireframe;
    } else {
      if (this.meshBody) this.meshBody.material = this.meshBody.materialTexture;
      if (this.meshWeapon) this.meshWeapon.material = this.meshWeapon.materialTexture;
    }
  }
  /**
   * Sets the skin defined by the given skin index. This will result in a different texture
   * for the body mesh.
   *
   * @param {number} index - The skin index.
   */
  setSkin(index2) {
    if (this.meshBody && this.meshBody.material.wireframe === false) {
      this.meshBody.material.map = this.skinsBody[index2];
    }
  }
  /**
   * Sets the weapon defined by the given weapon index. This will result in a different weapon
   * hold by the character.
   *
   * @param {number} index - The weapon index.
   */
  setWeapon(index2) {
    for (let i = 0; i < this.weapons.length; i++) this.weapons[i].visible = false;
    const activeWeapon = this.weapons[index2];
    if (activeWeapon) {
      activeWeapon.visible = true;
      this.meshWeapon = activeWeapon;
      this.syncWeaponAnimation();
    }
  }
  /**
   * Sets the defined animation clip as the active animation.
   *
   * @param {string} clipName - The name of the animation clip.
   */
  setAnimation(clipName) {
    if (this.meshBody) {
      if (this.meshBody.activeAction) {
        this.meshBody.activeAction.stop();
        this.meshBody.activeAction = null;
      }
      const action = this.mixer.clipAction(clipName, this.meshBody);
      if (action) {
        this.meshBody.activeAction = action.play();
      }
    }
    this.activeClipName = clipName;
    this.syncWeaponAnimation();
  }
  /**
   * Synchronizes the weapon with the body animation.
   */
  syncWeaponAnimation() {
    const clipName = this.activeClipName;
    if (this.meshWeapon) {
      if (this.meshWeapon.activeAction) {
        this.meshWeapon.activeAction.stop();
        this.meshWeapon.activeAction = null;
      }
      const action = this.mixer.clipAction(clipName, this.meshWeapon);
      if (action) {
        this.meshWeapon.activeAction = action.syncWith(this.meshBody.activeAction).play();
      }
    }
  }
  /**
   * Updates the animations of the mesh. Must be called inside the animation loop.
   *
   * @param {number} delta - The delta time in seconds.
   */
  update(delta) {
    if (this.mixer) this.mixer.update(delta);
  }
};

// node_modules/three/examples/jsm/misc/MorphBlendMesh.js
var MorphBlendMesh = class extends Mesh {
  /**
   * Constructs a new morph blend mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(geometry, material) {
    super(geometry, material);
    this.animationsMap = {};
    this.animationsList = [];
    const numFrames = Object.keys(this.morphTargetDictionary).length;
    const name2 = "__default";
    const startFrame = 0;
    const endFrame = numFrames - 1;
    const fps = numFrames / 1;
    this.createAnimation(name2, startFrame, endFrame, fps);
    this.setAnimationWeight(name2, 1);
  }
  /**
   * Creates a new animation.
   *
   * @param {string} name - The animation name.
   * @param {number} start - The start time.
   * @param {number} end - The end time.
   * @param {number} fps - The FPS.
   */
  createAnimation(name2, start, end, fps) {
    const animation = {
      start,
      end,
      length: end - start + 1,
      fps,
      duration: (end - start) / fps,
      lastFrame: 0,
      currentFrame: 0,
      active: false,
      time: 0,
      direction: 1,
      weight: 1,
      directionBackwards: false,
      mirroredLoop: false
    };
    this.animationsMap[name2] = animation;
    this.animationsList.push(animation);
  }
  /**
   * Automatically creates animations based on the values in
   * {@link Mesh#morphTargetDictionary}.
   *
   * @param {number} fps - The FPS of all animations.
   */
  autoCreateAnimations(fps) {
    const pattern = /([a-z]+)_?(\d+)/i;
    let firstAnimation;
    const frameRanges = {};
    let i = 0;
    for (const key2 in this.morphTargetDictionary) {
      const chunks = key2.match(pattern);
      if (chunks && chunks.length > 1) {
        const name2 = chunks[1];
        if (!frameRanges[name2]) frameRanges[name2] = { start: Infinity, end: -Infinity };
        const range = frameRanges[name2];
        if (i < range.start) range.start = i;
        if (i > range.end) range.end = i;
        if (!firstAnimation) firstAnimation = name2;
      }
      i++;
    }
    for (const name2 in frameRanges) {
      const range = frameRanges[name2];
      this.createAnimation(name2, range.start, range.end, fps);
    }
    this.firstAnimation = firstAnimation;
  }
  /**
   * Sets the animation playback direction to "forward" for the
   * defined animation.
   *
   * @param {string} name - The animation name.
   */
  setAnimationDirectionForward(name2) {
    const animation = this.animationsMap[name2];
    if (animation) {
      animation.direction = 1;
      animation.directionBackwards = false;
    }
  }
  /**
   * Sets the animation playback direction to "backward" for the
   * defined animation.
   *
   * @param {string} name - The animation name.
   */
  setAnimationDirectionBackward(name2) {
    const animation = this.animationsMap[name2];
    if (animation) {
      animation.direction = -1;
      animation.directionBackwards = true;
    }
  }
  /**
   * Sets the FPS to the given value for the defined animation.
   *
   * @param {string} name - The animation name.
   * @param {number} fps - The FPS to set.
   */
  setAnimationFPS(name2, fps) {
    const animation = this.animationsMap[name2];
    if (animation) {
      animation.fps = fps;
      animation.duration = (animation.end - animation.start) / animation.fps;
    }
  }
  /**
   * Sets the duration to the given value for the defined animation.
   *
   * @param {string} name - The animation name.
   * @param {number} duration - The duration to set.
   */
  setAnimationDuration(name2, duration) {
    const animation = this.animationsMap[name2];
    if (animation) {
      animation.duration = duration;
      animation.fps = (animation.end - animation.start) / animation.duration;
    }
  }
  /**
   * Sets the weight to the given value for the defined animation.
   *
   * @param {string} name - The animation name.
   * @param {number} weight - The weight to set.
   */
  setAnimationWeight(name2, weight) {
    const animation = this.animationsMap[name2];
    if (animation) {
      animation.weight = weight;
    }
  }
  /**
   * Sets the time to the given value for the defined animation.
   *
   * @param {string} name - The animation name.
   * @param {number} time - The time to set.
   */
  setAnimationTime(name2, time2) {
    const animation = this.animationsMap[name2];
    if (animation) {
      animation.time = time2;
    }
  }
  /**
   * Returns the time for the defined animation.
   *
   * @param {string} name - The animation name.
   * @return {number} The time.
   */
  getAnimationTime(name2) {
    let time2 = 0;
    const animation = this.animationsMap[name2];
    if (animation) {
      time2 = animation.time;
    }
    return time2;
  }
  /**
   * Returns the duration for the defined animation.
   *
   * @param {string} name - The animation name.
   * @return {number} The duration.
   */
  getAnimationDuration(name2) {
    let duration = -1;
    const animation = this.animationsMap[name2];
    if (animation) {
      duration = animation.duration;
    }
    return duration;
  }
  /**
   * Plays the defined animation.
   *
   * @param {string} name - The animation name.
   */
  playAnimation(name2) {
    const animation = this.animationsMap[name2];
    if (animation) {
      animation.time = 0;
      animation.active = true;
    } else {
      console.warn("THREE.MorphBlendMesh: animation[" + name2 + "] undefined in .playAnimation()");
    }
  }
  /**
   * Stops the defined animation.
   *
   * @param {string} name - The animation name.
   */
  stopAnimation(name2) {
    const animation = this.animationsMap[name2];
    if (animation) {
      animation.active = false;
    }
  }
  /**
   * Updates the animations of the mesh.
   *
   * @param {number} delta - The delta time in seconds.
   */
  update(delta) {
    for (let i = 0, il = this.animationsList.length; i < il; i++) {
      const animation = this.animationsList[i];
      if (!animation.active) continue;
      const frameTime = animation.duration / animation.length;
      animation.time += animation.direction * delta;
      if (animation.mirroredLoop) {
        if (animation.time > animation.duration || animation.time < 0) {
          animation.direction *= -1;
          if (animation.time > animation.duration) {
            animation.time = animation.duration;
            animation.directionBackwards = true;
          }
          if (animation.time < 0) {
            animation.time = 0;
            animation.directionBackwards = false;
          }
        }
      } else {
        animation.time = animation.time % animation.duration;
        if (animation.time < 0) animation.time += animation.duration;
      }
      const keyframe = animation.start + MathUtils.clamp(Math.floor(animation.time / frameTime), 0, animation.length - 1);
      const weight = animation.weight;
      if (keyframe !== animation.currentFrame) {
        this.morphTargetInfluences[animation.lastFrame] = 0;
        this.morphTargetInfluences[animation.currentFrame] = 1 * weight;
        this.morphTargetInfluences[keyframe] = 0;
        animation.lastFrame = animation.currentFrame;
        animation.currentFrame = keyframe;
      }
      let mix = animation.time % frameTime / frameTime;
      if (animation.directionBackwards) mix = 1 - mix;
      if (animation.currentFrame !== animation.lastFrame) {
        this.morphTargetInfluences[animation.currentFrame] = mix * weight;
        this.morphTargetInfluences[animation.lastFrame] = (1 - mix) * weight;
      } else {
        this.morphTargetInfluences[animation.currentFrame] = weight;
      }
    }
  }
};

// node_modules/three/examples/jsm/misc/MD2CharacterComplex.js
var MD2CharacterComplex = class {
  /**
   * Constructs a new MD2 character.
   */
  constructor() {
    this.scale = 1;
    this.animationFPS = 6;
    this.transitionFrames = 15;
    this.maxSpeed = 275;
    this.maxReverseSpeed = -275;
    this.frontAcceleration = 600;
    this.backAcceleration = 600;
    this.frontDeceleration = 600;
    this.angularSpeed = 2.5;
    this.root = new Object3D();
    this.meshBody = null;
    this.meshWeapon = null;
    this.controls = null;
    this.skinsBody = [];
    this.skinsWeapon = [];
    this.weapons = [];
    this.currentSkin = void 0;
    this.onLoadComplete = function() {
    };
    this.meshes = [];
    this.animations = {};
    this.loadCounter = 0;
    this.speed = 0;
    this.bodyOrientation = 0;
    this.walkSpeed = this.maxSpeed;
    this.crouchSpeed = this.maxSpeed * 0.5;
    this.activeAnimation = null;
    this.oldAnimation = null;
  }
  /**
   * Toggles shadow casting and receiving on the character's meshes.
   *
   * @param {boolean} enable - Whether to enable shadows or not.
   */
  enableShadows(enable) {
    for (let i = 0; i < this.meshes.length; i++) {
      this.meshes[i].castShadow = enable;
      this.meshes[i].receiveShadow = enable;
    }
  }
  /**
   * Toggles visibility on the character's meshes.
   *
   * @param {boolean} enable - Whether the character is visible or not.
   */
  setVisible(enable) {
    for (let i = 0; i < this.meshes.length; i++) {
      this.meshes[i].visible = enable;
      this.meshes[i].visible = enable;
    }
  }
  /**
   * Shares certain resources from a different character model.
   *
   * @param {MD2CharacterComplex} original - The original MD2 character.
   */
  shareParts(original) {
    this.animations = original.animations;
    this.walkSpeed = original.walkSpeed;
    this.crouchSpeed = original.crouchSpeed;
    this.skinsBody = original.skinsBody;
    this.skinsWeapon = original.skinsWeapon;
    const mesh = this._createPart(original.meshBody.geometry, this.skinsBody[0]);
    mesh.scale.set(this.scale, this.scale, this.scale);
    this.root.position.y = original.root.position.y;
    this.root.add(mesh);
    this.meshBody = mesh;
    this.meshes.push(mesh);
    for (let i = 0; i < original.weapons.length; i++) {
      const meshWeapon = this._createPart(original.weapons[i].geometry, this.skinsWeapon[i]);
      meshWeapon.scale.set(this.scale, this.scale, this.scale);
      meshWeapon.visible = false;
      meshWeapon.name = original.weapons[i].name;
      this.root.add(meshWeapon);
      this.weapons[i] = meshWeapon;
      this.meshWeapon = meshWeapon;
      this.meshes.push(meshWeapon);
    }
  }
  /**
   * Loads the character model for the given config.
   *
   * @param {Object} config - The config which defines the model and textures paths.
   */
  loadParts(config) {
    const scope = this;
    function loadTextures(baseUrl, textureUrls) {
      const textureLoader = new TextureLoader();
      const textures = [];
      for (let i = 0; i < textureUrls.length; i++) {
        textures[i] = textureLoader.load(baseUrl + textureUrls[i], checkLoadingComplete);
        textures[i].mapping = UVMapping;
        textures[i].name = textureUrls[i];
        textures[i].colorSpace = SRGBColorSpace;
      }
      return textures;
    }
    function checkLoadingComplete() {
      scope.loadCounter -= 1;
      if (scope.loadCounter === 0) scope.onLoadComplete();
    }
    this.animations = config.animations;
    this.walkSpeed = config.walkSpeed;
    this.crouchSpeed = config.crouchSpeed;
    this.loadCounter = config.weapons.length * 2 + config.skins.length + 1;
    const weaponsTextures = [];
    for (let i = 0; i < config.weapons.length; i++) weaponsTextures[i] = config.weapons[i][1];
    this.skinsBody = loadTextures(config.baseUrl + "skins/", config.skins);
    this.skinsWeapon = loadTextures(config.baseUrl + "skins/", weaponsTextures);
    const loader = new MD2Loader();
    loader.load(config.baseUrl + config.body, function(geo) {
      const boundingBox = new Box3();
      boundingBox.setFromBufferAttribute(geo.attributes.position);
      scope.root.position.y = -scope.scale * boundingBox.min.y;
      const mesh = scope._createPart(geo, scope.skinsBody[0]);
      mesh.scale.set(scope.scale, scope.scale, scope.scale);
      scope.root.add(mesh);
      scope.meshBody = mesh;
      scope.meshes.push(mesh);
      checkLoadingComplete();
    });
    const generateCallback = function(index2, name2) {
      return function(geo) {
        const mesh = scope._createPart(geo, scope.skinsWeapon[index2]);
        mesh.scale.set(scope.scale, scope.scale, scope.scale);
        mesh.visible = false;
        mesh.name = name2;
        scope.root.add(mesh);
        scope.weapons[index2] = mesh;
        scope.meshWeapon = mesh;
        scope.meshes.push(mesh);
        checkLoadingComplete();
      };
    };
    for (let i = 0; i < config.weapons.length; i++) {
      loader.load(config.baseUrl + config.weapons[i][0], generateCallback(i, config.weapons[i][0]));
    }
  }
  /**
   * Sets the animation playback rate.
   *
   * @param {number} rate - The playback rate to set.
   */
  setPlaybackRate(rate) {
    if (this.meshBody) this.meshBody.duration = this.meshBody.baseDuration / rate;
    if (this.meshWeapon) this.meshWeapon.duration = this.meshWeapon.baseDuration / rate;
  }
  /**
   * Sets the wireframe material flag.
   *
   * @param {boolean} wireframeEnabled - Whether to enable wireframe rendering or not.
   */
  setWireframe(wireframeEnabled) {
    if (wireframeEnabled) {
      if (this.meshBody) this.meshBody.material = this.meshBody.materialWireframe;
      if (this.meshWeapon) this.meshWeapon.material = this.meshWeapon.materialWireframe;
    } else {
      if (this.meshBody) this.meshBody.material = this.meshBody.materialTexture;
      if (this.meshWeapon) this.meshWeapon.material = this.meshWeapon.materialTexture;
    }
  }
  /**
   * Sets the skin defined by the given skin index. This will result in a different texture
   * for the body mesh.
   *
   * @param {number} index - The skin index.
   */
  setSkin(index2) {
    if (this.meshBody && this.meshBody.material.wireframe === false) {
      this.meshBody.material.map = this.skinsBody[index2];
      this.currentSkin = index2;
    }
  }
  /**
   * Sets the weapon defined by the given weapon index. This will result in a different weapon
   * hold by the character.
   *
   * @param {number} index - The weapon index.
   */
  setWeapon(index2) {
    for (let i = 0; i < this.weapons.length; i++) this.weapons[i].visible = false;
    const activeWeapon = this.weapons[index2];
    if (activeWeapon) {
      activeWeapon.visible = true;
      this.meshWeapon = activeWeapon;
      if (this.activeAnimation) {
        activeWeapon.playAnimation(this.activeAnimation);
        this.meshWeapon.setAnimationTime(this.activeAnimation, this.meshBody.getAnimationTime(this.activeAnimation));
      }
    }
  }
  /**
   * Sets the defined animation clip as the active animation.
   *
   * @param {string} animationName - The name of the animation clip.
   */
  setAnimation(animationName) {
    if (animationName === this.activeAnimation || !animationName) return;
    if (this.meshBody) {
      this.meshBody.setAnimationWeight(animationName, 0);
      this.meshBody.playAnimation(animationName);
      this.oldAnimation = this.activeAnimation;
      this.activeAnimation = animationName;
      this.blendCounter = this.transitionFrames;
    }
    if (this.meshWeapon) {
      this.meshWeapon.setAnimationWeight(animationName, 0);
      this.meshWeapon.playAnimation(animationName);
    }
  }
  update(delta) {
    if (this.controls) this.updateMovementModel(delta);
    if (this.animations) {
      this.updateBehaviors();
      this.updateAnimations(delta);
    }
  }
  /**
   * Updates the animations of the mesh. Must be called inside the animation loop.
   *
   * @param {number} delta - The delta time in seconds.
   */
  updateAnimations(delta) {
    let mix = 1;
    if (this.blendCounter > 0) {
      mix = (this.transitionFrames - this.blendCounter) / this.transitionFrames;
      this.blendCounter -= 1;
    }
    if (this.meshBody) {
      this.meshBody.update(delta);
      this.meshBody.setAnimationWeight(this.activeAnimation, mix);
      this.meshBody.setAnimationWeight(this.oldAnimation, 1 - mix);
    }
    if (this.meshWeapon) {
      this.meshWeapon.update(delta);
      this.meshWeapon.setAnimationWeight(this.activeAnimation, mix);
      this.meshWeapon.setAnimationWeight(this.oldAnimation, 1 - mix);
    }
  }
  /**
   * Updates the animation state based on the control inputs.
   */
  updateBehaviors() {
    const controls = this.controls;
    const animations = this.animations;
    let moveAnimation, idleAnimation;
    if (controls.crouch) {
      moveAnimation = animations["crouchMove"];
      idleAnimation = animations["crouchIdle"];
    } else {
      moveAnimation = animations["move"];
      idleAnimation = animations["idle"];
    }
    if (controls.jump) {
      moveAnimation = animations["jump"];
      idleAnimation = animations["jump"];
    }
    if (controls.attack) {
      if (controls.crouch) {
        moveAnimation = animations["crouchAttack"];
        idleAnimation = animations["crouchAttack"];
      } else {
        moveAnimation = animations["attack"];
        idleAnimation = animations["attack"];
      }
    }
    if (controls.moveForward || controls.moveBackward || controls.moveLeft || controls.moveRight) {
      if (this.activeAnimation !== moveAnimation) {
        this.setAnimation(moveAnimation);
      }
    }
    if (Math.abs(this.speed) < 0.2 * this.maxSpeed && !(controls.moveLeft || controls.moveRight || controls.moveForward || controls.moveBackward)) {
      if (this.activeAnimation !== idleAnimation) {
        this.setAnimation(idleAnimation);
      }
    }
    if (controls.moveForward) {
      if (this.meshBody) {
        this.meshBody.setAnimationDirectionForward(this.activeAnimation);
        this.meshBody.setAnimationDirectionForward(this.oldAnimation);
      }
      if (this.meshWeapon) {
        this.meshWeapon.setAnimationDirectionForward(this.activeAnimation);
        this.meshWeapon.setAnimationDirectionForward(this.oldAnimation);
      }
    }
    if (controls.moveBackward) {
      if (this.meshBody) {
        this.meshBody.setAnimationDirectionBackward(this.activeAnimation);
        this.meshBody.setAnimationDirectionBackward(this.oldAnimation);
      }
      if (this.meshWeapon) {
        this.meshWeapon.setAnimationDirectionBackward(this.activeAnimation);
        this.meshWeapon.setAnimationDirectionBackward(this.oldAnimation);
      }
    }
  }
  /**
   * Transforms the character model based on the control input.
   *
   * @param {number} delta - The delta time in seconds.
   */
  updateMovementModel(delta) {
    function exponentialEaseOut(k2) {
      return k2 === 1 ? 1 : -Math.pow(2, -10 * k2) + 1;
    }
    const controls = this.controls;
    if (controls.crouch) this.maxSpeed = this.crouchSpeed;
    else this.maxSpeed = this.walkSpeed;
    this.maxReverseSpeed = -this.maxSpeed;
    if (controls.moveForward) this.speed = MathUtils.clamp(this.speed + delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed);
    if (controls.moveBackward) this.speed = MathUtils.clamp(this.speed - delta * this.backAcceleration, this.maxReverseSpeed, this.maxSpeed);
    const dir = 1;
    if (controls.moveLeft) {
      this.bodyOrientation += delta * this.angularSpeed;
      this.speed = MathUtils.clamp(this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed);
    }
    if (controls.moveRight) {
      this.bodyOrientation -= delta * this.angularSpeed;
      this.speed = MathUtils.clamp(this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed);
    }
    if (!(controls.moveForward || controls.moveBackward)) {
      if (this.speed > 0) {
        const k2 = exponentialEaseOut(this.speed / this.maxSpeed);
        this.speed = MathUtils.clamp(this.speed - k2 * delta * this.frontDeceleration, 0, this.maxSpeed);
      } else {
        const k2 = exponentialEaseOut(this.speed / this.maxReverseSpeed);
        this.speed = MathUtils.clamp(this.speed + k2 * delta * this.backAcceleration, this.maxReverseSpeed, 0);
      }
    }
    const forwardDelta = this.speed * delta;
    this.root.position.x += Math.sin(this.bodyOrientation) * forwardDelta;
    this.root.position.z += Math.cos(this.bodyOrientation) * forwardDelta;
    this.root.rotation.y = this.bodyOrientation;
  }
  // internal
  _createPart(geometry, skinMap) {
    const materialWireframe = new MeshLambertMaterial({ color: 16755200, wireframe: true });
    const materialTexture = new MeshLambertMaterial({ color: 16777215, wireframe: false, map: skinMap });
    const mesh = new MorphBlendMesh(geometry, materialTexture);
    mesh.rotation.y = -Math.PI / 2;
    mesh.materialTexture = materialTexture;
    mesh.materialWireframe = materialWireframe;
    mesh.autoCreateAnimations(this.animationFPS);
    return mesh;
  }
};

// node_modules/three/examples/jsm/misc/MorphAnimMesh.js
var MorphAnimMesh = class extends Mesh {
  /**
   * Constructs a new morph anim mesh.
   *
   * @param {BufferGeometry} [geometry] - The mesh geometry.
   * @param {Material|Array<Material>} [material] - The mesh material.
   */
  constructor(geometry, material) {
    super(geometry, material);
    this.type = "MorphAnimMesh";
    this.mixer = new AnimationMixer(this);
    this.activeAction = null;
  }
  /**
   * Sets the animation playback direction to "forward".
   */
  setDirectionForward() {
    this.mixer.timeScale = 1;
  }
  /**
   * Sets the animation playback direction to "backward".
   */
  setDirectionBackward() {
    this.mixer.timeScale = -1;
  }
  /**
   * Plays the defined animation clip. The implementation assumes the animation
   * clips are stored in {@link Object3D#animations} or the geometry.
   *
   * @param {string} label - The name of the animation clip.
   * @param {number} fps - The FPS of the animation clip.
   */
  playAnimation(label, fps) {
    if (this.activeAction) {
      this.activeAction.stop();
      this.activeAction = null;
    }
    const clip = AnimationClip.findByName(this, label);
    if (clip) {
      const action = this.mixer.clipAction(clip);
      action.timeScale = clip.tracks.length * fps / clip.duration;
      this.activeAction = action.play();
    } else {
      throw new Error("THREE.MorphAnimMesh: animations[" + label + "] undefined in .playAnimation()");
    }
  }
  /**
   * Updates the animations of the mesh. Must be called inside the animation loop.
   *
   * @param {number} delta - The delta time in seconds.
   */
  updateAnimation(delta) {
    this.mixer.update(delta);
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.mixer = new AnimationMixer(this);
    return this;
  }
};

// node_modules/three/examples/jsm/libs/potpack.module.js
function potpack(boxes) {
  let area = 0;
  let maxWidth = 0;
  for (const box of boxes) {
    area += box.w * box.h;
    maxWidth = Math.max(maxWidth, box.w);
  }
  boxes.sort((a2, b3) => b3.h - a2.h);
  const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth);
  const spaces = [{ x: 0, y: 0, w: startWidth, h: Infinity }];
  let width2 = 0;
  let height2 = 0;
  for (const box of boxes) {
    for (let i = spaces.length - 1; i >= 0; i--) {
      const space = spaces[i];
      if (box.w > space.w || box.h > space.h) continue;
      box.x = space.x;
      box.y = space.y;
      height2 = Math.max(height2, box.y + box.h);
      width2 = Math.max(width2, box.x + box.w);
      if (box.w === space.w && box.h === space.h) {
        const last2 = spaces.pop();
        if (i < spaces.length) spaces[i] = last2;
      } else if (box.h === space.h) {
        space.x += box.w;
        space.w -= box.w;
      } else if (box.w === space.w) {
        space.y += box.h;
        space.h -= box.h;
      } else {
        spaces.push({
          x: space.x + box.w,
          y: space.y,
          w: space.w - box.w,
          h: box.h
        });
        space.y += box.h;
        space.h -= box.h;
      }
      break;
    }
  }
  return {
    w: width2,
    // container width
    h: height2,
    // container height
    fill: area / (width2 * height2) || 0
    // space utilization
  };
}

// node_modules/three/examples/jsm/misc/ProgressiveLightMap.js
var ProgressiveLightMap = class {
  /**
   * Constructs a new progressive light map.
   *
   * @param {WebGLRenderer} renderer - The renderer.
  	 * @param {number} [res=1024] - The side-long dimension of the total lightmap.
   */
  constructor(renderer2, res = 1024) {
    this.renderer = renderer2;
    this.res = res;
    this.lightMapContainers = [];
    this.scene = new Scene();
    this.buffer1Active = false;
    this.firstUpdate = true;
    this.labelMesh = null;
    this.blurringPlane = null;
    const format = /(Android|iPad|iPhone|iPod)/g.test(navigator.userAgent) ? HalfFloatType : FloatType;
    this.progressiveLightMap1 = new WebGLRenderTarget(this.res, this.res, { type: format });
    this.progressiveLightMap2 = new WebGLRenderTarget(this.res, this.res, { type: format });
    this.progressiveLightMap2.texture.channel = 1;
    this.uvMat = new MeshPhongMaterial();
    this.uvMat.uniforms = {};
    this.uvMat.onBeforeCompile = (shader) => {
      shader.vertexShader = "attribute vec2 uv1;\n#define USE_LIGHTMAP\n#define LIGHTMAP_UV uv1\n" + shader.vertexShader.slice(0, -1) + "	gl_Position = vec4((LIGHTMAP_UV - 0.5) * 2.0, 1.0, 1.0); }";
      const bodyStart = shader.fragmentShader.indexOf("void main() {");
      shader.fragmentShader = "#define USE_LIGHTMAP\n" + shader.fragmentShader.slice(0, bodyStart) + "	uniform sampler2D previousShadowMap;\n	uniform float averagingWindow;\n" + shader.fragmentShader.slice(bodyStart - 1, -1) + `
vec3 texelOld = texture2D(previousShadowMap, vLightMapUv).rgb;
				gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/averagingWindow);
			}`;
      shader.uniforms.previousShadowMap = { value: this.progressiveLightMap1.texture };
      shader.uniforms.averagingWindow = { value: 100 };
      this.uvMat.uniforms = shader.uniforms;
      this.uvMat.userData.shader = shader;
    };
  }
  /**
   * Sets these objects' materials' lightmaps and modifies their uv1's.
   *
   * @param {Array<Object3D>} objects - An array of objects and lights to set up your lightmap.
   */
  addObjectsToLightMap(objects) {
    this.uv_boxes = [];
    const padding = 3 / this.res;
    for (let ob2 = 0; ob2 < objects.length; ob2++) {
      const object = objects[ob2];
      if (object.isLight) {
        this.scene.attach(object);
        continue;
      }
      if (object.geometry.hasAttribute("uv") === false) {
        console.warn("THREE.ProgressiveLightMap: All lightmap objects need uvs.");
        continue;
      }
      if (this.blurringPlane === null) {
        this._initializeBlurPlane(this.res, this.progressiveLightMap1);
      }
      object.material.lightMap = this.progressiveLightMap2.texture;
      object.material.dithering = true;
      object.castShadow = true;
      object.receiveShadow = true;
      object.renderOrder = 1e3 + ob2;
      this.uv_boxes.push({
        w: 1 + padding * 2,
        h: 1 + padding * 2,
        index: ob2
      });
      this.lightMapContainers.push({ basicMat: object.material, object });
    }
    const dimensions = potpack(this.uv_boxes);
    this.uv_boxes.forEach((box) => {
      const uv1 = objects[box.index].geometry.getAttribute("uv").clone();
      for (let i = 0; i < uv1.array.length; i += uv1.itemSize) {
        uv1.array[i] = (uv1.array[i] + box.x + padding) / dimensions.w;
        uv1.array[i + 1] = (uv1.array[i + 1] + box.y + padding) / dimensions.h;
      }
      objects[box.index].geometry.setAttribute("uv1", uv1);
      objects[box.index].geometry.getAttribute("uv1").needsUpdate = true;
    });
  }
  /**
   * This function renders each mesh one at a time into their respective surface maps.
   *
   * @param {Camera} camera - The camera the scene is rendered with.
   * @param {number} [blendWindow=100] - When >1, samples will accumulate over time.
   * @param {boolean} [blurEdges=true] - Whether to fix UV Edges via blurring.
   */
  update(camera, blendWindow = 100, blurEdges = true) {
    if (this.blurringPlane === null) {
      return;
    }
    const oldTarget = this.renderer.getRenderTarget();
    this.blurringPlane.visible = blurEdges;
    for (let l2 = 0; l2 < this.lightMapContainers.length; l2++) {
      this.lightMapContainers[l2].object.oldScene = this.lightMapContainers[l2].object.parent;
      this.scene.attach(this.lightMapContainers[l2].object);
    }
    if (this.firstUpdate === true) {
      this.renderer.compile(this.scene, camera);
      this.firstUpdate = false;
    }
    for (let l2 = 0; l2 < this.lightMapContainers.length; l2++) {
      this.uvMat.uniforms.averagingWindow = { value: blendWindow };
      this.lightMapContainers[l2].object.material = this.uvMat;
      this.lightMapContainers[l2].object.oldFrustumCulled = this.lightMapContainers[l2].object.frustumCulled;
      this.lightMapContainers[l2].object.frustumCulled = false;
    }
    const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2;
    const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1;
    this.renderer.setRenderTarget(activeMap);
    this.uvMat.uniforms.previousShadowMap = { value: inactiveMap.texture };
    this.blurringPlane.material.uniforms.previousShadowMap = { value: inactiveMap.texture };
    this.buffer1Active = !this.buffer1Active;
    this.renderer.render(this.scene, camera);
    for (let l2 = 0; l2 < this.lightMapContainers.length; l2++) {
      this.lightMapContainers[l2].object.frustumCulled = this.lightMapContainers[l2].object.oldFrustumCulled;
      this.lightMapContainers[l2].object.material = this.lightMapContainers[l2].basicMat;
      this.lightMapContainers[l2].object.oldScene.attach(this.lightMapContainers[l2].object);
    }
    this.renderer.setRenderTarget(oldTarget);
  }
  /**
   * Draws the lightmap in the main scene. Call this after adding the objects to it.
   *
   * @param {boolean} visible - Whether the debug plane should be visible
   * @param {Vector3} [position] - Where the debug plane should be drawn
  */
  showDebugLightmap(visible, position2 = void 0) {
    if (this.lightMapContainers.length === 0) {
      console.warn("THREE.ProgressiveLightMap: Call .showDebugLightmap() after adding the objects.");
      return;
    }
    if (this.labelMesh === null) {
      const labelMaterial = new MeshBasicMaterial({ map: this.progressiveLightMap1.texture, side: DoubleSide });
      const labelGeometry = new PlaneGeometry(100, 100);
      this.labelMesh = new Mesh(labelGeometry, labelMaterial);
      this.labelMesh.position.y = 250;
      this.lightMapContainers[0].object.parent.add(this.labelMesh);
    }
    if (position2 !== void 0) {
      this.labelMesh.position.copy(position2);
    }
    this.labelMesh.visible = visible;
  }
  /**
   * Creates the Blurring Plane.
   *
   * @private
   * @param {number} res - The square resolution of this object's lightMap.
   * @param {WebGLRenderTarget} [lightMap] - The lightmap to initialize the plane with.
   */
  _initializeBlurPlane(res, lightMap = null) {
    const blurMaterial = new MeshBasicMaterial();
    blurMaterial.uniforms = {
      previousShadowMap: { value: null },
      pixelOffset: { value: 1 / res },
      polygonOffset: true,
      polygonOffsetFactor: -1,
      polygonOffsetUnits: 3
    };
    blurMaterial.onBeforeCompile = (shader) => {
      shader.vertexShader = "#define USE_UV\n" + shader.vertexShader.slice(0, -1) + "	gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }";
      const bodyStart = shader.fragmentShader.indexOf("void main() {");
      shader.fragmentShader = "#define USE_UV\n" + shader.fragmentShader.slice(0, bodyStart) + "	uniform sampler2D previousShadowMap;\n	uniform float pixelOffset;\n" + shader.fragmentShader.slice(bodyStart - 1, -1) + `	gl_FragColor.rgb = (
									texture2D(previousShadowMap, vUv + vec2( pixelOffset,  0.0        )).rgb +
									texture2D(previousShadowMap, vUv + vec2( 0.0        ,  pixelOffset)).rgb +
									texture2D(previousShadowMap, vUv + vec2( 0.0        , -pixelOffset)).rgb +
									texture2D(previousShadowMap, vUv + vec2(-pixelOffset,  0.0        )).rgb +
									texture2D(previousShadowMap, vUv + vec2( pixelOffset,  pixelOffset)).rgb +
									texture2D(previousShadowMap, vUv + vec2(-pixelOffset,  pixelOffset)).rgb +
									texture2D(previousShadowMap, vUv + vec2( pixelOffset, -pixelOffset)).rgb +
									texture2D(previousShadowMap, vUv + vec2(-pixelOffset, -pixelOffset)).rgb)/8.0;
				}`;
      shader.uniforms.previousShadowMap = { value: lightMap.texture };
      shader.uniforms.pixelOffset = { value: 0.5 / res };
      blurMaterial.uniforms = shader.uniforms;
      blurMaterial.userData.shader = shader;
    };
    this.blurringPlane = new Mesh(new PlaneGeometry(1, 1), blurMaterial);
    this.blurringPlane.name = "Blurring Plane";
    this.blurringPlane.frustumCulled = false;
    this.blurringPlane.renderOrder = 0;
    this.blurringPlane.material.depthWrite = false;
    this.scene.add(this.blurringPlane);
  }
  /**
   * Frees all internal resources.
   */
  dispose() {
    this.progressiveLightMap1.dispose();
    this.progressiveLightMap2.dispose();
    this.uvMat.dispose();
    if (this.blurringPlane !== null) {
      this.blurringPlane.geometry.dispose();
      this.blurringPlane.material.dispose();
    }
    if (this.labelMesh !== null) {
      this.labelMesh.geometry.dispose();
      this.labelMesh.material.dispose();
    }
  }
};

// node_modules/three/examples/jsm/misc/RollerCoaster.js
var RollerCoasterGeometry = class extends BufferGeometry {
  /**
   * Constructs a new geometry.
   *
   * @param {Curve} curve - The curve to generate the geometry along.
  	 * @param {number} divisions - The number of divisions which defines the detail of the geometry.
   */
  constructor(curve, divisions) {
    super();
    const vertices = [];
    const normals = [];
    const colors = [];
    const color1 = [1, 1, 1];
    const color2 = [1, 1, 0];
    const up = new Vector3(0, 1, 0);
    const forward = new Vector3();
    const right = new Vector3();
    const quaternion = new Quaternion();
    const prevQuaternion = new Quaternion();
    prevQuaternion.setFromAxisAngle(up, Math.PI / 2);
    const point = new Vector3();
    const prevPoint = new Vector3();
    prevPoint.copy(curve.getPointAt(0));
    const step = [
      new Vector3(-0.225, 0, 0),
      new Vector3(0, -0.05, 0),
      new Vector3(0, -0.175, 0),
      new Vector3(0, -0.05, 0),
      new Vector3(0.225, 0, 0),
      new Vector3(0, -0.175, 0)
    ];
    const PI2 = Math.PI * 2;
    let sides = 5;
    const tube1 = [];
    for (let i = 0; i < sides; i++) {
      const angle = i / sides * PI2;
      tube1.push(new Vector3(Math.sin(angle) * 0.06, Math.cos(angle) * 0.06, 0));
    }
    sides = 6;
    const tube2 = [];
    for (let i = 0; i < sides; i++) {
      const angle = i / sides * PI2;
      tube2.push(new Vector3(Math.sin(angle) * 0.025, Math.cos(angle) * 0.025, 0));
    }
    const vector = new Vector3();
    const normal = new Vector3();
    function drawShape(shape, color) {
      normal.set(0, 0, -1).applyQuaternion(quaternion);
      for (let j2 = 0; j2 < shape.length; j2++) {
        vector.copy(shape[j2]);
        vector.applyQuaternion(quaternion);
        vector.add(point);
        vertices.push(vector.x, vector.y, vector.z);
        normals.push(normal.x, normal.y, normal.z);
        colors.push(color[0], color[1], color[2]);
      }
      normal.set(0, 0, 1).applyQuaternion(quaternion);
      for (let j2 = shape.length - 1; j2 >= 0; j2--) {
        vector.copy(shape[j2]);
        vector.applyQuaternion(quaternion);
        vector.add(point);
        vertices.push(vector.x, vector.y, vector.z);
        normals.push(normal.x, normal.y, normal.z);
        colors.push(color[0], color[1], color[2]);
      }
    }
    const vector1 = new Vector3();
    const vector2 = new Vector3();
    const vector3 = new Vector3();
    const vector4 = new Vector3();
    const normal1 = new Vector3();
    const normal2 = new Vector3();
    const normal3 = new Vector3();
    const normal4 = new Vector3();
    function extrudeShape(shape, offset2, color) {
      for (let j2 = 0, jl = shape.length; j2 < jl; j2++) {
        const point1 = shape[j2];
        const point2 = shape[(j2 + 1) % jl];
        vector1.copy(point1).add(offset2);
        vector1.applyQuaternion(quaternion);
        vector1.add(point);
        vector2.copy(point2).add(offset2);
        vector2.applyQuaternion(quaternion);
        vector2.add(point);
        vector3.copy(point2).add(offset2);
        vector3.applyQuaternion(prevQuaternion);
        vector3.add(prevPoint);
        vector4.copy(point1).add(offset2);
        vector4.applyQuaternion(prevQuaternion);
        vector4.add(prevPoint);
        vertices.push(vector1.x, vector1.y, vector1.z);
        vertices.push(vector2.x, vector2.y, vector2.z);
        vertices.push(vector4.x, vector4.y, vector4.z);
        vertices.push(vector2.x, vector2.y, vector2.z);
        vertices.push(vector3.x, vector3.y, vector3.z);
        vertices.push(vector4.x, vector4.y, vector4.z);
        normal1.copy(point1);
        normal1.applyQuaternion(quaternion);
        normal1.normalize();
        normal2.copy(point2);
        normal2.applyQuaternion(quaternion);
        normal2.normalize();
        normal3.copy(point2);
        normal3.applyQuaternion(prevQuaternion);
        normal3.normalize();
        normal4.copy(point1);
        normal4.applyQuaternion(prevQuaternion);
        normal4.normalize();
        normals.push(normal1.x, normal1.y, normal1.z);
        normals.push(normal2.x, normal2.y, normal2.z);
        normals.push(normal4.x, normal4.y, normal4.z);
        normals.push(normal2.x, normal2.y, normal2.z);
        normals.push(normal3.x, normal3.y, normal3.z);
        normals.push(normal4.x, normal4.y, normal4.z);
        colors.push(color[0], color[1], color[2]);
        colors.push(color[0], color[1], color[2]);
        colors.push(color[0], color[1], color[2]);
        colors.push(color[0], color[1], color[2]);
        colors.push(color[0], color[1], color[2]);
        colors.push(color[0], color[1], color[2]);
      }
    }
    const offset = new Vector3();
    for (let i = 1; i <= divisions; i++) {
      point.copy(curve.getPointAt(i / divisions));
      up.set(0, 1, 0);
      forward.subVectors(point, prevPoint).normalize();
      right.crossVectors(up, forward).normalize();
      up.crossVectors(forward, right);
      const angle = Math.atan2(forward.x, forward.z);
      quaternion.setFromAxisAngle(up, angle);
      if (i % 2 === 0) {
        drawShape(step, color2);
      }
      extrudeShape(tube1, offset.set(0, -0.125, 0), color2);
      extrudeShape(tube2, offset.set(0.2, 0, 0), color1);
      extrudeShape(tube2, offset.set(-0.2, 0, 0), color1);
      prevPoint.copy(point);
      prevQuaternion.copy(quaternion);
    }
    this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3));
    this.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3));
    this.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3));
  }
};
var RollerCoasterLiftersGeometry = class extends BufferGeometry {
  /**
   * Constructs a new geometry.
   *
   * @param {Curve} curve - The curve to generate the geometry along.
  	 * @param {number} divisions - The number of divisions which defines the detail of the geometry.
   */
  constructor(curve, divisions) {
    super();
    const vertices = [];
    const normals = [];
    const quaternion = new Quaternion();
    const up = new Vector3(0, 1, 0);
    const point = new Vector3();
    const tangent = new Vector3();
    const tube1 = [
      new Vector3(0, 0.05, -0.05),
      new Vector3(0, 0.05, 0.05),
      new Vector3(0, -0.05, 0)
    ];
    const tube2 = [
      new Vector3(-0.05, 0, 0.05),
      new Vector3(-0.05, 0, -0.05),
      new Vector3(0.05, 0, 0)
    ];
    const tube3 = [
      new Vector3(0.05, 0, -0.05),
      new Vector3(0.05, 0, 0.05),
      new Vector3(-0.05, 0, 0)
    ];
    const vector1 = new Vector3();
    const vector2 = new Vector3();
    const vector3 = new Vector3();
    const vector4 = new Vector3();
    const normal1 = new Vector3();
    const normal2 = new Vector3();
    const normal3 = new Vector3();
    const normal4 = new Vector3();
    function extrudeShape(shape, fromPoint2, toPoint2) {
      for (let j2 = 0, jl = shape.length; j2 < jl; j2++) {
        const point1 = shape[j2];
        const point2 = shape[(j2 + 1) % jl];
        vector1.copy(point1);
        vector1.applyQuaternion(quaternion);
        vector1.add(fromPoint2);
        vector2.copy(point2);
        vector2.applyQuaternion(quaternion);
        vector2.add(fromPoint2);
        vector3.copy(point2);
        vector3.applyQuaternion(quaternion);
        vector3.add(toPoint2);
        vector4.copy(point1);
        vector4.applyQuaternion(quaternion);
        vector4.add(toPoint2);
        vertices.push(vector1.x, vector1.y, vector1.z);
        vertices.push(vector2.x, vector2.y, vector2.z);
        vertices.push(vector4.x, vector4.y, vector4.z);
        vertices.push(vector2.x, vector2.y, vector2.z);
        vertices.push(vector3.x, vector3.y, vector3.z);
        vertices.push(vector4.x, vector4.y, vector4.z);
        normal1.copy(point1);
        normal1.applyQuaternion(quaternion);
        normal1.normalize();
        normal2.copy(point2);
        normal2.applyQuaternion(quaternion);
        normal2.normalize();
        normal3.copy(point2);
        normal3.applyQuaternion(quaternion);
        normal3.normalize();
        normal4.copy(point1);
        normal4.applyQuaternion(quaternion);
        normal4.normalize();
        normals.push(normal1.x, normal1.y, normal1.z);
        normals.push(normal2.x, normal2.y, normal2.z);
        normals.push(normal4.x, normal4.y, normal4.z);
        normals.push(normal2.x, normal2.y, normal2.z);
        normals.push(normal3.x, normal3.y, normal3.z);
        normals.push(normal4.x, normal4.y, normal4.z);
      }
    }
    const fromPoint = new Vector3();
    const toPoint = new Vector3();
    for (let i = 1; i <= divisions; i++) {
      point.copy(curve.getPointAt(i / divisions));
      tangent.copy(curve.getTangentAt(i / divisions));
      const angle = Math.atan2(tangent.x, tangent.z);
      quaternion.setFromAxisAngle(up, angle);
      if (point.y > 10) {
        fromPoint.set(-0.75, -0.35, 0);
        fromPoint.applyQuaternion(quaternion);
        fromPoint.add(point);
        toPoint.set(0.75, -0.35, 0);
        toPoint.applyQuaternion(quaternion);
        toPoint.add(point);
        extrudeShape(tube1, fromPoint, toPoint);
        fromPoint.set(-0.7, -0.3, 0);
        fromPoint.applyQuaternion(quaternion);
        fromPoint.add(point);
        toPoint.set(-0.7, -point.y, 0);
        toPoint.applyQuaternion(quaternion);
        toPoint.add(point);
        extrudeShape(tube2, fromPoint, toPoint);
        fromPoint.set(0.7, -0.3, 0);
        fromPoint.applyQuaternion(quaternion);
        fromPoint.add(point);
        toPoint.set(0.7, -point.y, 0);
        toPoint.applyQuaternion(quaternion);
        toPoint.add(point);
        extrudeShape(tube3, fromPoint, toPoint);
      } else {
        fromPoint.set(0, -0.2, 0);
        fromPoint.applyQuaternion(quaternion);
        fromPoint.add(point);
        toPoint.set(0, -point.y, 0);
        toPoint.applyQuaternion(quaternion);
        toPoint.add(point);
        extrudeShape(tube3, fromPoint, toPoint);
      }
    }
    this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3));
    this.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3));
  }
};
var RollerCoasterShadowGeometry = class extends BufferGeometry {
  /**
   * Constructs a new geometry.
   *
   * @param {Curve} curve - The curve to generate the geometry along.
  	 * @param {number} divisions - The number of divisions which defines the detail of the geometry.
   */
  constructor(curve, divisions) {
    super();
    const vertices = [];
    const up = new Vector3(0, 1, 0);
    const forward = new Vector3();
    const quaternion = new Quaternion();
    const prevQuaternion = new Quaternion();
    prevQuaternion.setFromAxisAngle(up, Math.PI / 2);
    const point = new Vector3();
    const prevPoint = new Vector3();
    prevPoint.copy(curve.getPointAt(0));
    prevPoint.y = 0;
    const vector1 = new Vector3();
    const vector2 = new Vector3();
    const vector3 = new Vector3();
    const vector4 = new Vector3();
    for (let i = 1; i <= divisions; i++) {
      point.copy(curve.getPointAt(i / divisions));
      point.y = 0;
      forward.subVectors(point, prevPoint);
      const angle = Math.atan2(forward.x, forward.z);
      quaternion.setFromAxisAngle(up, angle);
      vector1.set(-0.3, 0, 0);
      vector1.applyQuaternion(quaternion);
      vector1.add(point);
      vector2.set(0.3, 0, 0);
      vector2.applyQuaternion(quaternion);
      vector2.add(point);
      vector3.set(0.3, 0, 0);
      vector3.applyQuaternion(prevQuaternion);
      vector3.add(prevPoint);
      vector4.set(-0.3, 0, 0);
      vector4.applyQuaternion(prevQuaternion);
      vector4.add(prevPoint);
      vertices.push(vector1.x, vector1.y, vector1.z);
      vertices.push(vector2.x, vector2.y, vector2.z);
      vertices.push(vector4.x, vector4.y, vector4.z);
      vertices.push(vector2.x, vector2.y, vector2.z);
      vertices.push(vector3.x, vector3.y, vector3.z);
      vertices.push(vector4.x, vector4.y, vector4.z);
      prevPoint.copy(point);
      prevQuaternion.copy(quaternion);
    }
    this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3));
  }
};
var SkyGeometry = class extends BufferGeometry {
  /**
   * Constructs a new geometry.
   */
  constructor() {
    super();
    const vertices = [];
    for (let i = 0; i < 100; i++) {
      const x2 = Math.random() * 800 - 400;
      const y = Math.random() * 50 + 50;
      const z = Math.random() * 800 - 400;
      const size2 = Math.random() * 40 + 20;
      vertices.push(x2 - size2, y, z - size2);
      vertices.push(x2 + size2, y, z - size2);
      vertices.push(x2 - size2, y, z + size2);
      vertices.push(x2 + size2, y, z - size2);
      vertices.push(x2 + size2, y, z + size2);
      vertices.push(x2 - size2, y, z + size2);
    }
    this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3));
  }
};
var TreesGeometry = class extends BufferGeometry {
  /**
   * Constructs a new geometry.
   *
   * @param {Mesh} landscape - A mesh representing the landscape. Trees will be positioned
   * randomly on the landscape's surface.
   */
  constructor(landscape) {
    super();
    const vertices = [];
    const colors = [];
    const raycaster = new Raycaster();
    raycaster.ray.direction.set(0, -1, 0);
    const _color5 = new Color();
    for (let i = 0; i < 2e3; i++) {
      const x2 = Math.random() * 500 - 250;
      const z = Math.random() * 500 - 250;
      raycaster.ray.origin.set(x2, 50, z);
      const intersections = raycaster.intersectObject(landscape);
      if (intersections.length === 0) continue;
      const y = intersections[0].point.y;
      const height2 = Math.random() * 5 + 0.5;
      let angle = Math.random() * Math.PI * 2;
      vertices.push(x2 + Math.sin(angle), y, z + Math.cos(angle));
      vertices.push(x2, y + height2, z);
      vertices.push(x2 + Math.sin(angle + Math.PI), y, z + Math.cos(angle + Math.PI));
      angle += Math.PI / 2;
      vertices.push(x2 + Math.sin(angle), y, z + Math.cos(angle));
      vertices.push(x2, y + height2, z);
      vertices.push(x2 + Math.sin(angle + Math.PI), y, z + Math.cos(angle + Math.PI));
      const random2 = Math.random() * 0.1;
      for (let j2 = 0; j2 < 6; j2++) {
        _color5.setRGB(0.2 + random2, 0.4 + random2, 0, SRGBColorSpace);
        colors.push(_color5.r, _color5.g, _color5.b);
      }
    }
    this.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3));
    this.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3));
  }
};

// node_modules/three/examples/jsm/misc/Timer.js
var Timer = class {
  /**
   * Constructs a new timer.
   */
  constructor() {
    this._previousTime = 0;
    this._currentTime = 0;
    this._startTime = now();
    this._delta = 0;
    this._elapsed = 0;
    this._timescale = 1;
    this._document = null;
    this._pageVisibilityHandler = null;
  }
  /**
   * Connect the timer to the given document.Calling this method is not mandatory to
   * use the timer but enables the usage of the Page Visibility API to avoid large time
   * delta values.
   *
   * @param {Document} document - The document.
   */
  connect(document2) {
    this._document = document2;
    if (document2.hidden !== void 0) {
      this._pageVisibilityHandler = handleVisibilityChange.bind(this);
      document2.addEventListener("visibilitychange", this._pageVisibilityHandler, false);
    }
  }
  /**
   * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
   */
  disconnect() {
    if (this._pageVisibilityHandler !== null) {
      this._document.removeEventListener("visibilitychange", this._pageVisibilityHandler);
      this._pageVisibilityHandler = null;
    }
    this._document = null;
  }
  /**
   * Returns the time delta in seconds.
   *
   * @return {number} The time delta in second.
   */
  getDelta() {
    return this._delta / 1e3;
  }
  /**
   * Returns the elapsed time in seconds.
   *
   * @return {number} The elapsed time in second.
   */
  getElapsed() {
    return this._elapsed / 1e3;
  }
  /**
   * Returns the timescale.
   *
   * @return {number} The timescale.
   */
  getTimescale() {
    return this._timescale;
  }
  /**
   * Sets the given timescale which scale the time delta computation
   * in `update()`.
   *
   * @param {number} timescale - The timescale to set.
   * @return {Timer} A reference to this timer.
   */
  setTimescale(timescale) {
    this._timescale = timescale;
    return this;
  }
  /**
   * Resets the time computation for the current simulation step.
   *
   * @return {Timer} A reference to this timer.
   */
  reset() {
    this._currentTime = now() - this._startTime;
    return this;
  }
  /**
   * Can be used to free all internal resources. Usually called when
   * the timer instance isn't required anymore.
   */
  dispose() {
    this.disconnect();
  }
  /**
   * Updates the internal state of the timer. This method should be called
   * once per simulation step and before you perform queries against the timer
   * (e.g. via `getDelta()`).
   *
   * @param {number} timestamp - The current time in milliseconds. Can be obtained
   * from the `requestAnimationFrame` callback argument. If not provided, the current
   * time will be determined with `performance.now`.
   * @return {Timer} A reference to this timer.
   */
  update(timestamp) {
    if (this._pageVisibilityHandler !== null && this._document.hidden === true) {
      this._delta = 0;
    } else {
      this._previousTime = this._currentTime;
      this._currentTime = (timestamp !== void 0 ? timestamp : now()) - this._startTime;
      this._delta = (this._currentTime - this._previousTime) * this._timescale;
      this._elapsed += this._delta;
    }
    return this;
  }
};
var FixedTimer = class extends Timer {
  /**
   * Constructs a new timer.
   *
   * @param {number} [fps=60] - The fixed FPS of this timer.
   */
  constructor(fps = 60) {
    super();
    this._delta = 1 / fps * 1e3;
  }
  update() {
    this._elapsed += this._delta * this._timescale;
    return this;
  }
};
function now() {
  return performance.now();
}
function handleVisibilityChange() {
  if (this._document.hidden === false) this.reset();
}

// node_modules/three/examples/jsm/misc/TubePainter.js
function TubePainter() {
  const BUFFER_SIZE = 1e6 * 3;
  const positions = new BufferAttribute(new Float32Array(BUFFER_SIZE), 3);
  positions.usage = DynamicDrawUsage;
  const normals = new BufferAttribute(new Float32Array(BUFFER_SIZE), 3);
  normals.usage = DynamicDrawUsage;
  const colors = new BufferAttribute(new Float32Array(BUFFER_SIZE), 3);
  colors.usage = DynamicDrawUsage;
  const geometry = new BufferGeometry();
  geometry.setAttribute("position", positions);
  geometry.setAttribute("normal", normals);
  geometry.setAttribute("color", colors);
  geometry.drawRange.count = 0;
  const material = new MeshStandardMaterial({
    vertexColors: true
  });
  const mesh = new Mesh(geometry, material);
  mesh.frustumCulled = false;
  function getPoints(size3) {
    const PI2 = Math.PI * 2;
    const sides = 10;
    const array = [];
    const radius = 0.01 * size3;
    for (let i = 0; i < sides; i++) {
      const angle = i / sides * PI2;
      array.push(new Vector3(Math.sin(angle) * radius, Math.cos(angle) * radius, 0));
    }
    return array;
  }
  const vector1 = new Vector3();
  const vector2 = new Vector3();
  const vector3 = new Vector3();
  const vector4 = new Vector3();
  const color = new Color(16777215);
  let size2 = 1;
  function stroke(position1, position2, matrix12, matrix22) {
    if (position1.distanceToSquared(position2) === 0) return;
    let count2 = geometry.drawRange.count;
    const points = getPoints(size2);
    for (let i = 0, il = points.length; i < il; i++) {
      const vertex1 = points[i];
      const vertex2 = points[(i + 1) % il];
      vector1.copy(vertex1).applyMatrix4(matrix22).add(position2);
      vector2.copy(vertex2).applyMatrix4(matrix22).add(position2);
      vector3.copy(vertex2).applyMatrix4(matrix12).add(position1);
      vector4.copy(vertex1).applyMatrix4(matrix12).add(position1);
      vector1.toArray(positions.array, (count2 + 0) * 3);
      vector2.toArray(positions.array, (count2 + 1) * 3);
      vector4.toArray(positions.array, (count2 + 2) * 3);
      vector2.toArray(positions.array, (count2 + 3) * 3);
      vector3.toArray(positions.array, (count2 + 4) * 3);
      vector4.toArray(positions.array, (count2 + 5) * 3);
      vector1.copy(vertex1).applyMatrix4(matrix22).normalize();
      vector2.copy(vertex2).applyMatrix4(matrix22).normalize();
      vector3.copy(vertex2).applyMatrix4(matrix12).normalize();
      vector4.copy(vertex1).applyMatrix4(matrix12).normalize();
      vector1.toArray(normals.array, (count2 + 0) * 3);
      vector2.toArray(normals.array, (count2 + 1) * 3);
      vector4.toArray(normals.array, (count2 + 2) * 3);
      vector2.toArray(normals.array, (count2 + 3) * 3);
      vector3.toArray(normals.array, (count2 + 4) * 3);
      vector4.toArray(normals.array, (count2 + 5) * 3);
      color.toArray(colors.array, (count2 + 0) * 3);
      color.toArray(colors.array, (count2 + 1) * 3);
      color.toArray(colors.array, (count2 + 2) * 3);
      color.toArray(colors.array, (count2 + 3) * 3);
      color.toArray(colors.array, (count2 + 4) * 3);
      color.toArray(colors.array, (count2 + 5) * 3);
      count2 += 6;
    }
    geometry.drawRange.count = count2;
  }
  const up = new Vector3(0, 1, 0);
  const point1 = new Vector3();
  const point2 = new Vector3();
  const matrix1 = new Matrix4();
  const matrix2 = new Matrix4();
  function moveTo(position2) {
    point1.copy(position2);
    matrix1.lookAt(point2, point1, up);
    point2.copy(position2);
    matrix2.copy(matrix1);
  }
  function lineTo(position2) {
    point1.copy(position2);
    matrix1.lookAt(point2, point1, up);
    stroke(point1, point2, matrix1, matrix2);
    point2.copy(point1);
    matrix2.copy(matrix1);
  }
  function setSize(value2) {
    size2 = value2;
  }
  let count = 0;
  function update() {
    const start = count;
    const end = geometry.drawRange.count;
    if (start === end) return;
    positions.addUpdateRange(start * 3, (end - start) * 3);
    positions.needsUpdate = true;
    normals.addUpdateRange(start * 3, (end - start) * 3);
    normals.needsUpdate = true;
    colors.addUpdateRange(start * 3, (end - start) * 3);
    colors.needsUpdate = true;
    count = geometry.drawRange.count;
  }
  return {
    /**
     * The "painted" tube mesh. Must be added to the scene.
     *
     * @name TubePainter#mesh
     * @type {Mesh}
     */
    mesh,
    /**
     * Moves the current painting position to the given value.
     *
     * @method
     * @name TubePainter#moveTo
     * @param {Vector3} position The new painting position.
     */
    moveTo,
    /**
     * Draw a stroke from the current position to the given one.
     * This method extends the tube while drawing with the XR
     * controllers.
     *
     * @method
     * @name TubePainter#lineTo
     * @param {Vector3} position The destination position.
     */
    lineTo,
    /**
     * Sets the size of newly rendered tube segments.
     *
     * @method
     * @name TubePainter#setSize
     * @param {number} size The size.
     */
    setSize,
    /**
     * Updates the internal geometry buffers so the new painted
     * segments are rendered.
     *
     * @method
     * @name TubePainter#update
     */
    update
  };
}

// node_modules/three/examples/jsm/modifiers/CurveModifier.js
var CHANNELS = 4;
var TEXTURE_WIDTH = 1024;
var TEXTURE_HEIGHT = 4;
function initSplineTexture(numberOfCurves = 1) {
  const dataArray2 = new Uint16Array(TEXTURE_WIDTH * TEXTURE_HEIGHT * numberOfCurves * CHANNELS);
  const dataTexture = new DataTexture(
    dataArray2,
    TEXTURE_WIDTH,
    TEXTURE_HEIGHT * numberOfCurves,
    RGBAFormat,
    HalfFloatType
  );
  dataTexture.wrapS = RepeatWrapping;
  dataTexture.wrapY = RepeatWrapping;
  dataTexture.magFilter = LinearFilter;
  dataTexture.minFilter = LinearFilter;
  dataTexture.needsUpdate = true;
  return dataTexture;
}
function updateSplineTexture(texture, splineCurve, offset = 0) {
  const numberOfPoints = Math.floor(TEXTURE_WIDTH * (TEXTURE_HEIGHT / 4));
  splineCurve.arcLengthDivisions = numberOfPoints / 2;
  splineCurve.updateArcLengths();
  const points = splineCurve.getSpacedPoints(numberOfPoints);
  const frenetFrames = splineCurve.computeFrenetFrames(numberOfPoints, true);
  for (let i = 0; i < numberOfPoints; i++) {
    const rowOffset = Math.floor(i / TEXTURE_WIDTH);
    const rowIndex = i % TEXTURE_WIDTH;
    let pt = points[i];
    setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 0 + rowOffset + TEXTURE_HEIGHT * offset);
    pt = frenetFrames.tangents[i];
    setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 1 + rowOffset + TEXTURE_HEIGHT * offset);
    pt = frenetFrames.normals[i];
    setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 2 + rowOffset + TEXTURE_HEIGHT * offset);
    pt = frenetFrames.binormals[i];
    setTextureValue(texture, rowIndex, pt.x, pt.y, pt.z, 3 + rowOffset + TEXTURE_HEIGHT * offset);
  }
  texture.needsUpdate = true;
}
function setTextureValue(texture, index2, x2, y, z, o) {
  const image = texture.image;
  const { data: data2 } = image;
  const i = CHANNELS * TEXTURE_WIDTH * o;
  data2[index2 * CHANNELS + i + 0] = DataUtils.toHalfFloat(x2);
  data2[index2 * CHANNELS + i + 1] = DataUtils.toHalfFloat(y);
  data2[index2 * CHANNELS + i + 2] = DataUtils.toHalfFloat(z);
  data2[index2 * CHANNELS + i + 3] = DataUtils.toHalfFloat(1);
}
function getUniforms(splineTexture) {
  const uniforms = {
    spineTexture: { value: splineTexture },
    pathOffset: { type: "f", value: 0 },
    // time of path curve
    pathSegment: { type: "f", value: 1 },
    // fractional length of path
    spineOffset: { type: "f", value: 161 },
    spineLength: { type: "f", value: 400 },
    flow: { type: "i", value: 1 }
  };
  return uniforms;
}
function modifyShader(material, uniforms, numberOfCurves = 1) {
  if (material.__ok) return;
  material.__ok = true;
  material.onBeforeCompile = (shader) => {
    if (shader.__modified) return;
    shader.__modified = true;
    Object.assign(shader.uniforms, uniforms);
    const vertexShader = `
		uniform sampler2D spineTexture;
		uniform float pathOffset;
		uniform float pathSegment;
		uniform float spineOffset;
		uniform float spineLength;
		uniform int flow;

		float textureLayers = ${TEXTURE_HEIGHT * numberOfCurves}.;
		float textureStacks = ${TEXTURE_HEIGHT / 4}.;

		${shader.vertexShader}
		`.replace("#include <beginnormal_vertex>", "").replace("#include <defaultnormal_vertex>", "").replace("#include <begin_vertex>", "").replace(
      /void\s*main\s*\(\)\s*\{/,
      `
void main() {
#include <beginnormal_vertex>

vec4 worldPos = modelMatrix * vec4(position, 1.);

bool bend = flow > 0;
float xWeight = bend ? 0. : 1.;

#ifdef USE_INSTANCING
float pathOffsetFromInstanceMatrix = instanceMatrix[3][2];
float spineLengthFromInstanceMatrix = instanceMatrix[3][0];
float spinePortion = bend ? (worldPos.x + spineOffset) / spineLengthFromInstanceMatrix : 0.;
float mt = (spinePortion * pathSegment + pathOffset + pathOffsetFromInstanceMatrix)*textureStacks;
#else
float spinePortion = bend ? (worldPos.x + spineOffset) / spineLength : 0.;
float mt = (spinePortion * pathSegment + pathOffset)*textureStacks;
#endif

mt = mod(mt, textureStacks);
float rowOffset = floor(mt);

#ifdef USE_INSTANCING
rowOffset += instanceMatrix[3][1] * ${TEXTURE_HEIGHT}.;
#endif

vec3 spinePos = texture2D(spineTexture, vec2(mt, (0. + rowOffset + 0.5) / textureLayers)).xyz;
vec3 a =        texture2D(spineTexture, vec2(mt, (1. + rowOffset + 0.5) / textureLayers)).xyz;
vec3 b =        texture2D(spineTexture, vec2(mt, (2. + rowOffset + 0.5) / textureLayers)).xyz;
vec3 c =        texture2D(spineTexture, vec2(mt, (3. + rowOffset + 0.5) / textureLayers)).xyz;
mat3 basis = mat3(a, b, c);

vec3 transformed = basis
	* vec3(worldPos.x * xWeight, worldPos.y * 1., worldPos.z * 1.)
	+ spinePos;

vec3 transformedNormal = normalMatrix * (basis * objectNormal);
			`
    ).replace(
      "#include <project_vertex>",
      `vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );
				gl_Position = projectionMatrix * mvPosition;`
    );
    shader.vertexShader = vertexShader;
  };
}
var Flow = class {
  /**
   * Constructs a new Flow instance.
   *
   * @param {Mesh} mesh - The mesh to clone and modify to bend around the curve.
   * @param {number} numberOfCurves - The amount of space that should preallocated for additional curves.
   */
  constructor(mesh, numberOfCurves = 1) {
    const obj3D = mesh.clone();
    const splineTexture = initSplineTexture(numberOfCurves);
    const uniforms = getUniforms(splineTexture);
    obj3D.traverse(function(child) {
      if (child instanceof Mesh || child instanceof InstancedMesh) {
        if (Array.isArray(child.material)) {
          const materials = [];
          for (const material of child.material) {
            const newMaterial = material.clone();
            modifyShader(newMaterial, uniforms, numberOfCurves);
            materials.push(newMaterial);
          }
          child.material = materials;
        } else {
          child.material = child.material.clone();
          modifyShader(child.material, uniforms, numberOfCurves);
        }
      }
    });
    this.curveArray = new Array(numberOfCurves);
    this.curveLengthArray = new Array(numberOfCurves);
    this.object3D = obj3D;
    this.splineTexture = splineTexture;
    this.uniforms = uniforms;
  }
  /**
   * Updates the curve for the given curve index.
   *
   * @param {number} index - The curve index.
   * @param {Curve} curve - The curve that should be used to bend the mesh.
   */
  updateCurve(index2, curve) {
    if (index2 >= this.curveArray.length) throw Error("Flow: Index out of range.");
    const curveLength = curve.getLength();
    this.uniforms.spineLength.value = curveLength;
    this.curveLengthArray[index2] = curveLength;
    this.curveArray[index2] = curve;
    updateSplineTexture(this.splineTexture, curve, index2);
  }
  /**
   * Moves the mesh along the curve.
   *
   * @param {number} amount - The offset.
   */
  moveAlongCurve(amount) {
    this.uniforms.pathOffset.value += amount;
  }
};
var _matrix3 = new Matrix4();
var InstancedFlow = class extends Flow {
  /**
   * Constructs a new InstancedFlow instance.
   *
   * @param {number} count - The number of instanced elements.
   * @param {number} curveCount - The number of curves to preallocate for.
   * @param {Geometry} geometry - The geometry to use for the instanced mesh.
   * @param {Material} material - The material to use for the instanced mesh.
   */
  constructor(count, curveCount, geometry, material) {
    const mesh = new InstancedMesh(
      geometry,
      material,
      count
    );
    mesh.instanceMatrix.setUsage(DynamicDrawUsage);
    mesh.frustumCulled = false;
    super(mesh, curveCount);
    this.offsets = new Array(count).fill(0);
    this.whichCurve = new Array(count).fill(0);
  }
  /**
   * The extra information about which curve and curve position is stored in the translation components of the matrix for the instanced objects
   * This writes that information to the matrix and marks it as needing update.
   *
   * @param {number} index - The index of tge instanced element to update.
   */
  writeChanges(index2) {
    _matrix3.makeTranslation(
      this.curveLengthArray[this.whichCurve[index2]],
      this.whichCurve[index2],
      this.offsets[index2]
    );
    this.object3D.setMatrixAt(index2, _matrix3);
    this.object3D.instanceMatrix.needsUpdate = true;
  }
  /**
   * Move an individual element along the curve by a specific amount.
   *
   * @param {number} index - Which element to update.
   * @param {number} offset - The offset.
   */
  moveIndividualAlongCurve(index2, offset) {
    this.offsets[index2] += offset;
    this.writeChanges(index2);
  }
  /**
   * Select which curve to use for an element.
   *
   * @param {number} index - The index of the instanced element to update.
   * @param {number} curveNo - The index of the curve it should use.
   */
  setCurve(index2, curveNo) {
    if (isNaN(curveNo)) throw Error("InstancedFlow: Curve index being set is Not a Number (NaN).");
    this.whichCurve[index2] = curveNo;
    this.writeChanges(index2);
  }
};

// node_modules/three/examples/jsm/modifiers/EdgeSplitModifier.js
var _A = new Vector3();
var _B = new Vector3();
var _C = new Vector3();
var EdgeSplitModifier = class {
  /**
   * Returns a new, modified version of the given geometry by applying an edge-split operation.
   * Please note that the resulting geometry is always indexed.
   *
   * @param {BufferGeometry} geometry - The geometry to modify.
   * @param {number} cutOffAngle - The cut off angle in radians.
   * @param {boolean} [tryKeepNormals=true] - Whether to try to keep normals or not.
   * @return {BufferGeometry} A new, modified geometry.
   */
  modify(geometry, cutOffAngle, tryKeepNormals = true) {
    function computeNormals() {
      normals = new Float32Array(indexes.length * 3);
      for (let i = 0; i < indexes.length; i += 3) {
        let index2 = indexes[i];
        _A.set(
          positions[3 * index2],
          positions[3 * index2 + 1],
          positions[3 * index2 + 2]
        );
        index2 = indexes[i + 1];
        _B.set(
          positions[3 * index2],
          positions[3 * index2 + 1],
          positions[3 * index2 + 2]
        );
        index2 = indexes[i + 2];
        _C.set(
          positions[3 * index2],
          positions[3 * index2 + 1],
          positions[3 * index2 + 2]
        );
        _C.sub(_B);
        _A.sub(_B);
        const normal = _C.cross(_A).normalize();
        for (let j2 = 0; j2 < 3; j2++) {
          normals[3 * (i + j2)] = normal.x;
          normals[3 * (i + j2) + 1] = normal.y;
          normals[3 * (i + j2) + 2] = normal.z;
        }
      }
    }
    function mapPositionsToIndexes() {
      pointToIndexMap = Array(positions.length / 3);
      for (let i = 0; i < indexes.length; i++) {
        const index2 = indexes[i];
        if (pointToIndexMap[index2] == null) {
          pointToIndexMap[index2] = [];
        }
        pointToIndexMap[index2].push(i);
      }
    }
    function edgeSplitToGroups(indexes2, cutOff, firstIndex) {
      _A.set(normals[3 * firstIndex], normals[3 * firstIndex + 1], normals[3 * firstIndex + 2]).normalize();
      const result = {
        splitGroup: [],
        currentGroup: [firstIndex]
      };
      for (const j2 of indexes2) {
        if (j2 !== firstIndex) {
          _B.set(normals[3 * j2], normals[3 * j2 + 1], normals[3 * j2 + 2]).normalize();
          if (_B.dot(_A) < cutOff) {
            result.splitGroup.push(j2);
          } else {
            result.currentGroup.push(j2);
          }
        }
      }
      return result;
    }
    function edgeSplit(indexes2, cutOff, original = null) {
      if (indexes2.length === 0) return;
      const groupResults = [];
      for (const index2 of indexes2) {
        groupResults.push(edgeSplitToGroups(indexes2, cutOff, index2));
      }
      let result = groupResults[0];
      for (const groupResult of groupResults) {
        if (groupResult.currentGroup.length > result.currentGroup.length) {
          result = groupResult;
        }
      }
      if (original != null) {
        splitIndexes.push({
          original,
          indexes: result.currentGroup
        });
      }
      if (result.splitGroup.length) {
        edgeSplit(result.splitGroup, cutOff, original || result.currentGroup[0]);
      }
    }
    let hadNormals = false;
    let oldNormals = null;
    if (geometry.attributes.normal) {
      hadNormals = true;
      geometry = geometry.clone();
      if (tryKeepNormals === true && geometry.index !== null) {
        oldNormals = geometry.attributes.normal.array;
      }
      geometry.deleteAttribute("normal");
    }
    if (geometry.index == null) {
      geometry = mergeVertices(geometry);
    }
    const indexes = geometry.index.array;
    const positions = geometry.getAttribute("position").array;
    let normals;
    let pointToIndexMap;
    computeNormals();
    mapPositionsToIndexes();
    const splitIndexes = [];
    for (const vertexIndexes of pointToIndexMap) {
      edgeSplit(vertexIndexes, Math.cos(cutOffAngle) - 1e-3);
    }
    const newAttributes = {};
    for (const name2 of Object.keys(geometry.attributes)) {
      const oldAttribute = geometry.attributes[name2];
      const newArray = new oldAttribute.array.constructor((indexes.length + splitIndexes.length) * oldAttribute.itemSize);
      newArray.set(oldAttribute.array);
      newAttributes[name2] = new BufferAttribute(newArray, oldAttribute.itemSize, oldAttribute.normalized);
    }
    const newIndexes = new Uint32Array(indexes.length);
    newIndexes.set(indexes);
    for (let i = 0; i < splitIndexes.length; i++) {
      const split = splitIndexes[i];
      const index2 = indexes[split.original];
      for (const attribute of Object.values(newAttributes)) {
        for (let j2 = 0; j2 < attribute.itemSize; j2++) {
          attribute.array[(indexes.length + i) * attribute.itemSize + j2] = attribute.array[index2 * attribute.itemSize + j2];
        }
      }
      for (const j2 of split.indexes) {
        newIndexes[j2] = indexes.length + i;
      }
    }
    geometry = new BufferGeometry();
    geometry.setIndex(new BufferAttribute(newIndexes, 1));
    for (const name2 of Object.keys(newAttributes)) {
      geometry.setAttribute(name2, newAttributes[name2]);
    }
    if (hadNormals) {
      geometry.computeVertexNormals();
      if (oldNormals !== null) {
        const changedNormals = new Array(oldNormals.length / 3).fill(false);
        for (const splitData of splitIndexes)
          changedNormals[splitData.original] = true;
        for (let i = 0; i < changedNormals.length; i++) {
          if (changedNormals[i] === false) {
            for (let j2 = 0; j2 < 3; j2++)
              geometry.attributes.normal.array[3 * i + j2] = oldNormals[3 * i + j2];
          }
        }
      }
    }
    return geometry;
  }
};

// node_modules/three/examples/jsm/modifiers/SimplifyModifier.js
var _cb2 = new Vector3();
var _ab2 = new Vector3();
var SimplifyModifier = class {
  /**
   * Returns a new, modified version of the given geometry by applying a simplification.
   * Please note that the resulting geometry is always non-indexed.
   *
   * @param {BufferGeometry} geometry - The geometry to modify.
   * @param {number} count - The number of vertices to remove.
   * @return {BufferGeometry} A new, modified geometry.
   */
  modify(geometry, count) {
    geometry = geometry.clone();
    delete geometry.morphAttributes.position;
    delete geometry.morphAttributes.normal;
    const attributes = geometry.attributes;
    for (const name2 in attributes) {
      if (name2 !== "position" && name2 !== "uv" && name2 !== "normal" && name2 !== "tangent" && name2 !== "color") geometry.deleteAttribute(name2);
    }
    geometry = mergeVertices(geometry);
    const vertices = [];
    const faces = [];
    const positionAttribute = geometry.getAttribute("position");
    const uvAttribute = geometry.getAttribute("uv");
    const normalAttribute = geometry.getAttribute("normal");
    const tangentAttribute = geometry.getAttribute("tangent");
    const colorAttribute = geometry.getAttribute("color");
    let t3 = null;
    let v2 = null;
    let nor = null;
    let col = null;
    for (let i = 0; i < positionAttribute.count; i++) {
      const v = new Vector3().fromBufferAttribute(positionAttribute, i);
      if (uvAttribute) {
        v2 = new Vector2().fromBufferAttribute(uvAttribute, i);
      }
      if (normalAttribute) {
        nor = new Vector3().fromBufferAttribute(normalAttribute, i);
      }
      if (tangentAttribute) {
        t3 = new Vector4().fromBufferAttribute(tangentAttribute, i);
      }
      if (colorAttribute) {
        col = new Color().fromBufferAttribute(colorAttribute, i);
      }
      const vertex = new Vertex(v, v2, nor, t3, col);
      vertices.push(vertex);
    }
    let index2 = geometry.getIndex();
    if (index2 !== null) {
      for (let i = 0; i < index2.count; i += 3) {
        const a2 = index2.getX(i);
        const b3 = index2.getX(i + 1);
        const c2 = index2.getX(i + 2);
        const triangle = new Triangle2(vertices[a2], vertices[b3], vertices[c2], a2, b3, c2);
        faces.push(triangle);
      }
    } else {
      for (let i = 0; i < positionAttribute.count; i += 3) {
        const a2 = i;
        const b3 = i + 1;
        const c2 = i + 2;
        const triangle = new Triangle2(vertices[a2], vertices[b3], vertices[c2], a2, b3, c2);
        faces.push(triangle);
      }
    }
    for (let i = 0, il = vertices.length; i < il; i++) {
      computeEdgeCostAtVertex(vertices[i]);
    }
    let nextVertex;
    let z = count;
    while (z--) {
      nextVertex = minimumCostEdge(vertices);
      if (!nextVertex) {
        console.log("THREE.SimplifyModifier: No next vertex");
        break;
      }
      collapse(vertices, faces, nextVertex, nextVertex.collapseNeighbor);
    }
    const simplifiedGeometry = new BufferGeometry();
    const position2 = [];
    const uv = [];
    const normal = [];
    const tangent = [];
    const color = [];
    index2 = [];
    for (let i = 0; i < vertices.length; i++) {
      const vertex = vertices[i];
      position2.push(vertex.position.x, vertex.position.y, vertex.position.z);
      if (vertex.uv) {
        uv.push(vertex.uv.x, vertex.uv.y);
      }
      if (vertex.normal) {
        normal.push(vertex.normal.x, vertex.normal.y, vertex.normal.z);
      }
      if (vertex.tangent) {
        tangent.push(vertex.tangent.x, vertex.tangent.y, vertex.tangent.z, vertex.tangent.w);
      }
      if (vertex.color) {
        color.push(vertex.color.r, vertex.color.g, vertex.color.b);
      }
      vertex.id = i;
    }
    for (let i = 0; i < faces.length; i++) {
      const face = faces[i];
      index2.push(face.v1.id, face.v2.id, face.v3.id);
    }
    simplifiedGeometry.setAttribute("position", new Float32BufferAttribute(position2, 3));
    if (uv.length > 0) simplifiedGeometry.setAttribute("uv", new Float32BufferAttribute(uv, 2));
    if (normal.length > 0) simplifiedGeometry.setAttribute("normal", new Float32BufferAttribute(normal, 3));
    if (tangent.length > 0) simplifiedGeometry.setAttribute("tangent", new Float32BufferAttribute(tangent, 4));
    if (color.length > 0) simplifiedGeometry.setAttribute("color", new Float32BufferAttribute(color, 3));
    simplifiedGeometry.setIndex(index2);
    return simplifiedGeometry;
  }
};
function pushIfUnique(array, object) {
  if (array.indexOf(object) === -1) array.push(object);
}
function removeFromArray(array, object) {
  const k2 = array.indexOf(object);
  if (k2 > -1) array.splice(k2, 1);
}
function computeEdgeCollapseCost(u2, v) {
  const edgelength = v.position.distanceTo(u2.position);
  let curvature = 0;
  const sideFaces = [];
  for (let i = 0, il = u2.faces.length; i < il; i++) {
    const face = u2.faces[i];
    if (face.hasVertex(v)) {
      sideFaces.push(face);
    }
  }
  for (let i = 0, il = u2.faces.length; i < il; i++) {
    let minCurvature = 1;
    const face = u2.faces[i];
    for (let j2 = 0; j2 < sideFaces.length; j2++) {
      const sideFace = sideFaces[j2];
      const dotProd = face.normal.dot(sideFace.normal);
      minCurvature = Math.min(minCurvature, (1.001 - dotProd) / 2);
    }
    curvature = Math.max(curvature, minCurvature);
  }
  const borders = 0;
  if (sideFaces.length < 2) {
    curvature = 1;
  }
  const amt = edgelength * curvature + borders;
  return amt;
}
function computeEdgeCostAtVertex(v) {
  if (v.neighbors.length === 0) {
    v.collapseNeighbor = null;
    v.collapseCost = -0.01;
    return;
  }
  v.collapseCost = 1e5;
  v.collapseNeighbor = null;
  for (let i = 0; i < v.neighbors.length; i++) {
    const collapseCost = computeEdgeCollapseCost(v, v.neighbors[i]);
    if (!v.collapseNeighbor) {
      v.collapseNeighbor = v.neighbors[i];
      v.collapseCost = collapseCost;
      v.minCost = collapseCost;
      v.totalCost = 0;
      v.costCount = 0;
    }
    v.costCount++;
    v.totalCost += collapseCost;
    if (collapseCost < v.minCost) {
      v.collapseNeighbor = v.neighbors[i];
      v.minCost = collapseCost;
    }
  }
  v.collapseCost = v.totalCost / v.costCount;
}
function removeVertex(v, vertices) {
  console.assert(v.faces.length === 0);
  while (v.neighbors.length) {
    const n2 = v.neighbors.pop();
    removeFromArray(n2.neighbors, v);
  }
  removeFromArray(vertices, v);
}
function removeFace(f, faces) {
  removeFromArray(faces, f);
  if (f.v1) removeFromArray(f.v1.faces, f);
  if (f.v2) removeFromArray(f.v2.faces, f);
  if (f.v3) removeFromArray(f.v3.faces, f);
  const vs = [f.v1, f.v2, f.v3];
  for (let i = 0; i < 3; i++) {
    const v12 = vs[i];
    const v2 = vs[(i + 1) % 3];
    if (!v12 || !v2) continue;
    v12.removeIfNonNeighbor(v2);
    v2.removeIfNonNeighbor(v12);
  }
}
function collapse(vertices, faces, u2, v) {
  if (!v) {
    removeVertex(u2, vertices);
    return;
  }
  if (v.uv) {
    u2.uv.copy(v.uv);
  }
  if (v.normal) {
    v.normal.add(u2.normal).normalize();
  }
  if (v.tangent) {
    v.tangent.add(u2.tangent).normalize();
  }
  const tmpVertices = [];
  for (let i = 0; i < u2.neighbors.length; i++) {
    tmpVertices.push(u2.neighbors[i]);
  }
  for (let i = u2.faces.length - 1; i >= 0; i--) {
    if (u2.faces[i] && u2.faces[i].hasVertex(v)) {
      removeFace(u2.faces[i], faces);
    }
  }
  for (let i = u2.faces.length - 1; i >= 0; i--) {
    u2.faces[i].replaceVertex(u2, v);
  }
  removeVertex(u2, vertices);
  for (let i = 0; i < tmpVertices.length; i++) {
    computeEdgeCostAtVertex(tmpVertices[i]);
  }
}
function minimumCostEdge(vertices) {
  let least = vertices[0];
  for (let i = 0; i < vertices.length; i++) {
    if (vertices[i].collapseCost < least.collapseCost) {
      least = vertices[i];
    }
  }
  return least;
}
var Triangle2 = class {
  constructor(v12, v2, v3, a2, b3, c2) {
    this.a = a2;
    this.b = b3;
    this.c = c2;
    this.v1 = v12;
    this.v2 = v2;
    this.v3 = v3;
    this.normal = new Vector3();
    this.computeNormal();
    v12.faces.push(this);
    v12.addUniqueNeighbor(v2);
    v12.addUniqueNeighbor(v3);
    v2.faces.push(this);
    v2.addUniqueNeighbor(v12);
    v2.addUniqueNeighbor(v3);
    v3.faces.push(this);
    v3.addUniqueNeighbor(v12);
    v3.addUniqueNeighbor(v2);
  }
  computeNormal() {
    const vA = this.v1.position;
    const vB = this.v2.position;
    const vC = this.v3.position;
    _cb2.subVectors(vC, vB);
    _ab2.subVectors(vA, vB);
    _cb2.cross(_ab2).normalize();
    this.normal.copy(_cb2);
  }
  hasVertex(v) {
    return v === this.v1 || v === this.v2 || v === this.v3;
  }
  replaceVertex(oldv, newv) {
    if (oldv === this.v1) this.v1 = newv;
    else if (oldv === this.v2) this.v2 = newv;
    else if (oldv === this.v3) this.v3 = newv;
    removeFromArray(oldv.faces, this);
    newv.faces.push(this);
    oldv.removeIfNonNeighbor(this.v1);
    this.v1.removeIfNonNeighbor(oldv);
    oldv.removeIfNonNeighbor(this.v2);
    this.v2.removeIfNonNeighbor(oldv);
    oldv.removeIfNonNeighbor(this.v3);
    this.v3.removeIfNonNeighbor(oldv);
    this.v1.addUniqueNeighbor(this.v2);
    this.v1.addUniqueNeighbor(this.v3);
    this.v2.addUniqueNeighbor(this.v1);
    this.v2.addUniqueNeighbor(this.v3);
    this.v3.addUniqueNeighbor(this.v1);
    this.v3.addUniqueNeighbor(this.v2);
    this.computeNormal();
  }
};
var Vertex = class {
  constructor(v, uv, normal, tangent, color) {
    this.position = v;
    this.uv = uv;
    this.normal = normal;
    this.tangent = tangent;
    this.color = color;
    this.id = -1;
    this.faces = [];
    this.neighbors = [];
    this.collapseCost = 0;
    this.collapseNeighbor = null;
  }
  addUniqueNeighbor(vertex) {
    pushIfUnique(this.neighbors, vertex);
  }
  removeIfNonNeighbor(n2) {
    const neighbors = this.neighbors;
    const faces = this.faces;
    const offset = neighbors.indexOf(n2);
    if (offset === -1) return;
    for (let i = 0; i < faces.length; i++) {
      if (faces[i].hasVertex(n2)) return;
    }
    neighbors.splice(offset, 1);
  }
};

// node_modules/three/examples/jsm/modifiers/TessellateModifier.js
var TessellateModifier = class {
  /**
   * Constructs a new Tessellate modifier.
   *
   * @param {number} [maxEdgeLength=0.1] - The maximum edge length.
   * @param {number} [maxIterations=6] - The number of iterations.
   */
  constructor(maxEdgeLength = 0.1, maxIterations = 6) {
    this.maxEdgeLength = maxEdgeLength;
    this.maxIterations = maxIterations;
  }
  /**
   * Returns a new, modified version of the given geometry by applying a tesselation.
   * Please note that the resulting geometry is always non-indexed.
   *
   * @param {BufferGeometry} geometry - The geometry to modify.
   * @return {BufferGeometry} A new, modified geometry.
   */
  modify(geometry) {
    if (geometry.index !== null) {
      geometry = geometry.toNonIndexed();
    }
    const maxIterations = this.maxIterations;
    const maxEdgeLengthSquared = this.maxEdgeLength * this.maxEdgeLength;
    const va2 = new Vector3();
    const vb = new Vector3();
    const vc = new Vector3();
    const vm = new Vector3();
    const vs = [va2, vb, vc, vm];
    const na = new Vector3();
    const nb = new Vector3();
    const nc = new Vector3();
    const nm = new Vector3();
    const ns = [na, nb, nc, nm];
    const ca = new Color();
    const cb = new Color();
    const cc = new Color();
    const cm = new Color();
    const cs = [ca, cb, cc, cm];
    const ua = new Vector2();
    const ub = new Vector2();
    const uc = new Vector2();
    const um = new Vector2();
    const us = [ua, ub, uc, um];
    const u2a = new Vector2();
    const u2b = new Vector2();
    const u2c = new Vector2();
    const u2m = new Vector2();
    const u2s = [u2a, u2b, u2c, u2m];
    const attributes = geometry.attributes;
    const hasNormals = attributes.normal !== void 0;
    const hasColors = attributes.color !== void 0;
    const hasUVs = attributes.uv !== void 0;
    const hasUV1s = attributes.uv1 !== void 0;
    let positions = attributes.position.array;
    let normals = hasNormals ? attributes.normal.array : null;
    let colors = hasColors ? attributes.color.array : null;
    let uvs = hasUVs ? attributes.uv.array : null;
    let uv1s = hasUV1s ? attributes.uv1.array : null;
    let positions2 = positions;
    let normals2 = normals;
    let colors2 = colors;
    let uvs2 = uvs;
    let uv1s2 = uv1s;
    let iteration = 0;
    let tessellating = true;
    function addTriangle(a2, b3, c2) {
      const v12 = vs[a2];
      const v2 = vs[b3];
      const v3 = vs[c2];
      positions2.push(v12.x, v12.y, v12.z);
      positions2.push(v2.x, v2.y, v2.z);
      positions2.push(v3.x, v3.y, v3.z);
      if (hasNormals) {
        const n1 = ns[a2];
        const n2 = ns[b3];
        const n3 = ns[c2];
        normals2.push(n1.x, n1.y, n1.z);
        normals2.push(n2.x, n2.y, n2.z);
        normals2.push(n3.x, n3.y, n3.z);
      }
      if (hasColors) {
        const c1 = cs[a2];
        const c22 = cs[b3];
        const c3 = cs[c2];
        colors2.push(c1.r, c1.g, c1.b);
        colors2.push(c22.r, c22.g, c22.b);
        colors2.push(c3.r, c3.g, c3.b);
      }
      if (hasUVs) {
        const u1 = us[a2];
        const u2 = us[b3];
        const u3 = us[c2];
        uvs2.push(u1.x, u1.y);
        uvs2.push(u2.x, u2.y);
        uvs2.push(u3.x, u3.y);
      }
      if (hasUV1s) {
        const u21 = u2s[a2];
        const u22 = u2s[b3];
        const u23 = u2s[c2];
        uv1s2.push(u21.x, u21.y);
        uv1s2.push(u22.x, u22.y);
        uv1s2.push(u23.x, u23.y);
      }
    }
    while (tessellating && iteration < maxIterations) {
      iteration++;
      tessellating = false;
      positions = positions2;
      positions2 = [];
      if (hasNormals) {
        normals = normals2;
        normals2 = [];
      }
      if (hasColors) {
        colors = colors2;
        colors2 = [];
      }
      if (hasUVs) {
        uvs = uvs2;
        uvs2 = [];
      }
      if (hasUV1s) {
        uv1s = uv1s2;
        uv1s2 = [];
      }
      for (let i = 0, i2 = 0, il = positions.length; i < il; i += 9, i2 += 6) {
        va2.fromArray(positions, i + 0);
        vb.fromArray(positions, i + 3);
        vc.fromArray(positions, i + 6);
        if (hasNormals) {
          na.fromArray(normals, i + 0);
          nb.fromArray(normals, i + 3);
          nc.fromArray(normals, i + 6);
        }
        if (hasColors) {
          ca.fromArray(colors, i + 0);
          cb.fromArray(colors, i + 3);
          cc.fromArray(colors, i + 6);
        }
        if (hasUVs) {
          ua.fromArray(uvs, i2 + 0);
          ub.fromArray(uvs, i2 + 2);
          uc.fromArray(uvs, i2 + 4);
        }
        if (hasUV1s) {
          u2a.fromArray(uv1s, i2 + 0);
          u2b.fromArray(uv1s, i2 + 2);
          u2c.fromArray(uv1s, i2 + 4);
        }
        const dab = va2.distanceToSquared(vb);
        const dbc = vb.distanceToSquared(vc);
        const dac = va2.distanceToSquared(vc);
        if (dab > maxEdgeLengthSquared || dbc > maxEdgeLengthSquared || dac > maxEdgeLengthSquared) {
          tessellating = true;
          if (dab >= dbc && dab >= dac) {
            vm.lerpVectors(va2, vb, 0.5);
            if (hasNormals) nm.lerpVectors(na, nb, 0.5);
            if (hasColors) cm.lerpColors(ca, cb, 0.5);
            if (hasUVs) um.lerpVectors(ua, ub, 0.5);
            if (hasUV1s) u2m.lerpVectors(u2a, u2b, 0.5);
            addTriangle(0, 3, 2);
            addTriangle(3, 1, 2);
          } else if (dbc >= dab && dbc >= dac) {
            vm.lerpVectors(vb, vc, 0.5);
            if (hasNormals) nm.lerpVectors(nb, nc, 0.5);
            if (hasColors) cm.lerpColors(cb, cc, 0.5);
            if (hasUVs) um.lerpVectors(ub, uc, 0.5);
            if (hasUV1s) u2m.lerpVectors(u2b, u2c, 0.5);
            addTriangle(0, 1, 3);
            addTriangle(3, 2, 0);
          } else {
            vm.lerpVectors(va2, vc, 0.5);
            if (hasNormals) nm.lerpVectors(na, nc, 0.5);
            if (hasColors) cm.lerpColors(ca, cc, 0.5);
            if (hasUVs) um.lerpVectors(ua, uc, 0.5);
            if (hasUV1s) u2m.lerpVectors(u2a, u2c, 0.5);
            addTriangle(0, 1, 3);
            addTriangle(3, 1, 2);
          }
        } else {
          addTriangle(0, 1, 2);
        }
      }
    }
    const geometry2 = new BufferGeometry();
    geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3));
    if (hasNormals) {
      geometry2.setAttribute("normal", new Float32BufferAttribute(normals2, 3));
    }
    if (hasColors) {
      geometry2.setAttribute("color", new Float32BufferAttribute(colors2, 3));
    }
    if (hasUVs) {
      geometry2.setAttribute("uv", new Float32BufferAttribute(uvs2, 2));
    }
    if (hasUV1s) {
      geometry2.setAttribute("uv1", new Float32BufferAttribute(uv1s2, 2));
    }
    return geometry2;
  }
};

// node_modules/three/examples/jsm/objects/GroundedSkybox.js
var GroundedSkybox = class extends Mesh {
  /**
   * Constructs a new ground-projected skybox.
   *
   * @param {Texture} map - The environment map to use.
   * @param {number} height - The height is how far the camera that took the photo was above the ground.
   * A larger value will magnify the downward part of the image.
   * @param {number} radius - The radius of the skybox. Must be large enough to ensure the scene's camera stays inside.
   * @param {number} [resolution=128] - The geometry resolution of the skybox.
   */
  constructor(map2, height2, radius, resolution = 128) {
    if (height2 <= 0 || radius <= 0 || resolution <= 0) {
      throw new Error("GroundedSkybox height, radius, and resolution must be positive.");
    }
    const geometry = new SphereGeometry(radius, 2 * resolution, resolution);
    geometry.scale(1, 1, -1);
    const pos = geometry.getAttribute("position");
    const tmp = new Vector3();
    for (let i = 0; i < pos.count; ++i) {
      tmp.fromBufferAttribute(pos, i);
      if (tmp.y < 0) {
        const y1 = -height2 * 3 / 2;
        const f = tmp.y < y1 ? -height2 / tmp.y : 1 - tmp.y * tmp.y / (3 * y1 * y1);
        tmp.multiplyScalar(f);
        tmp.toArray(pos.array, 3 * i);
      }
    }
    pos.needsUpdate = true;
    super(geometry, new MeshBasicMaterial({ map: map2, depthWrite: false }));
  }
};

// node_modules/three/examples/jsm/objects/Lensflare.js
var Lensflare = class _Lensflare extends Mesh {
  /**
   * Constructs a new lensflare.
   */
  constructor() {
    super(_Lensflare.Geometry, new MeshBasicMaterial({ opacity: 0, transparent: true }));
    this.isLensflare = true;
    this.type = "Lensflare";
    this.frustumCulled = false;
    this.renderOrder = Infinity;
    const positionScreen = new Vector3();
    const positionView = new Vector3();
    const tempMap = new FramebufferTexture(16, 16);
    const occlusionMap = new FramebufferTexture(16, 16);
    let currentType = UnsignedByteType;
    const geometry = _Lensflare.Geometry;
    const material1a = new RawShaderMaterial({
      uniforms: {
        "scale": { value: null },
        "screenPosition": { value: null }
      },
      vertexShader: (
        /* glsl */
        `

				precision highp float;

				uniform vec3 screenPosition;
				uniform vec2 scale;

				attribute vec3 position;

				void main() {

					gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );

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

				precision highp float;

				void main() {

					gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 );

				}`
      ),
      depthTest: true,
      depthWrite: false,
      transparent: false
    });
    const material1b = new RawShaderMaterial({
      uniforms: {
        "map": { value: tempMap },
        "scale": { value: null },
        "screenPosition": { value: null }
      },
      vertexShader: (
        /* glsl */
        `

				precision highp float;

				uniform vec3 screenPosition;
				uniform vec2 scale;

				attribute vec3 position;
				attribute vec2 uv;

				varying vec2 vUV;

				void main() {

					vUV = uv;

					gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 );

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

				precision highp float;

				uniform sampler2D map;

				varying vec2 vUV;

				void main() {

					gl_FragColor = texture2D( map, vUV );

				}`
      ),
      depthTest: false,
      depthWrite: false,
      transparent: false
    });
    const mesh1 = new Mesh(geometry, material1a);
    const elements = [];
    const shader = LensflareElement.Shader;
    const material2 = new RawShaderMaterial({
      name: shader.name,
      uniforms: {
        "map": { value: null },
        "occlusionMap": { value: occlusionMap },
        "color": { value: new Color(16777215) },
        "scale": { value: new Vector2() },
        "screenPosition": { value: new Vector3() }
      },
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader,
      blending: AdditiveBlending,
      transparent: true,
      depthWrite: false
    });
    const mesh2 = new Mesh(geometry, material2);
    this.addElement = function(element) {
      elements.push(element);
    };
    const scale2 = new Vector2();
    const screenPositionPixels = new Vector2();
    const validArea = new Box2();
    const viewport = new Vector4();
    this.onBeforeRender = function(renderer2, scene, camera) {
      renderer2.getCurrentViewport(viewport);
      const renderTarget = renderer2.getRenderTarget();
      const type = renderTarget !== null ? renderTarget.texture.type : UnsignedByteType;
      if (currentType !== type) {
        tempMap.dispose();
        occlusionMap.dispose();
        tempMap.type = occlusionMap.type = type;
        currentType = type;
      }
      const invAspect = viewport.w / viewport.z;
      const halfViewportWidth = viewport.z / 2;
      const halfViewportHeight = viewport.w / 2;
      let size2 = 16 / viewport.w;
      scale2.set(size2 * invAspect, size2);
      validArea.min.set(viewport.x, viewport.y);
      validArea.max.set(viewport.x + (viewport.z - 16), viewport.y + (viewport.w - 16));
      positionView.setFromMatrixPosition(this.matrixWorld);
      positionView.applyMatrix4(camera.matrixWorldInverse);
      if (positionView.z > 0) return;
      positionScreen.copy(positionView).applyMatrix4(camera.projectionMatrix);
      screenPositionPixels.x = viewport.x + positionScreen.x * halfViewportWidth + halfViewportWidth - 8;
      screenPositionPixels.y = viewport.y + positionScreen.y * halfViewportHeight + halfViewportHeight - 8;
      if (validArea.containsPoint(screenPositionPixels)) {
        renderer2.copyFramebufferToTexture(tempMap, screenPositionPixels);
        let uniforms = material1a.uniforms;
        uniforms["scale"].value = scale2;
        uniforms["screenPosition"].value = positionScreen;
        renderer2.renderBufferDirect(camera, null, geometry, material1a, mesh1, null);
        renderer2.copyFramebufferToTexture(occlusionMap, screenPositionPixels);
        uniforms = material1b.uniforms;
        uniforms["scale"].value = scale2;
        uniforms["screenPosition"].value = positionScreen;
        renderer2.renderBufferDirect(camera, null, geometry, material1b, mesh1, null);
        const vecX = -positionScreen.x * 2;
        const vecY = -positionScreen.y * 2;
        for (let i = 0, l2 = elements.length; i < l2; i++) {
          const element = elements[i];
          const uniforms2 = material2.uniforms;
          uniforms2["color"].value.copy(element.color);
          uniforms2["map"].value = element.texture;
          uniforms2["screenPosition"].value.x = positionScreen.x + vecX * element.distance;
          uniforms2["screenPosition"].value.y = positionScreen.y + vecY * element.distance;
          size2 = element.size / viewport.w;
          const invAspect2 = viewport.w / viewport.z;
          uniforms2["scale"].value.set(size2 * invAspect2, size2);
          material2.uniformsNeedUpdate = true;
          renderer2.renderBufferDirect(camera, null, geometry, material2, mesh2, null);
        }
      }
    };
    this.dispose = function() {
      material1a.dispose();
      material1b.dispose();
      material2.dispose();
      tempMap.dispose();
      occlusionMap.dispose();
      for (let i = 0, l2 = elements.length; i < l2; i++) {
        elements[i].texture.dispose();
      }
    };
  }
};
var LensflareElement = class {
  /**
   * Constructs a new lensflare element.
   *
   * @param {Texture} texture - The flare's texture.
   * @param {number} [size=1] - The size in pixels.
   * @param {number} [distance=0] - The normalized distance (`[0,1]`) from the light source.
   * A value of `0` means the flare is located at light source.
   * @param {Color} [color] - The flare's color
   */
  constructor(texture, size2 = 1, distance = 0, color = new Color(16777215)) {
    this.texture = texture;
    this.size = size2;
    this.distance = distance;
    this.color = color;
  }
};
LensflareElement.Shader = {
  name: "LensflareElementShader",
  uniforms: {
    "map": { value: null },
    "occlusionMap": { value: null },
    "color": { value: null },
    "scale": { value: null },
    "screenPosition": { value: null }
  },
  vertexShader: (
    /* glsl */
    `

		precision highp float;

		uniform vec3 screenPosition;
		uniform vec2 scale;

		uniform sampler2D occlusionMap;

		attribute vec3 position;
		attribute vec2 uv;

		varying vec2 vUV;
		varying float vVisibility;

		void main() {

			vUV = uv;

			vec2 pos = position.xy;

			vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );
			visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );
			visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );
			visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );
			visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );
			visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );
			visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );
			visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );
			visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );

			vVisibility =        visibility.r / 9.0;
			vVisibility *= 1.0 - visibility.g / 9.0;
			vVisibility *=       visibility.b / 9.0;

			gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );

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

		precision highp float;

		uniform sampler2D map;
		uniform vec3 color;

		varying vec2 vUV;
		varying float vVisibility;

		void main() {

			vec4 texture = texture2D( map, vUV );
			texture.a *= vVisibility;
			gl_FragColor = texture;
			gl_FragColor.rgb *= color;

		}`
  )
};
Lensflare.Geometry = function() {
  const geometry = new BufferGeometry();
  const float32Array = new Float32Array([
    -1,
    -1,
    0,
    0,
    0,
    1,
    -1,
    0,
    1,
    0,
    1,
    1,
    0,
    1,
    1,
    -1,
    1,
    0,
    0,
    1
  ]);
  const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  geometry.setIndex([0, 1, 2, 0, 2, 3]);
  geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  return geometry;
}();

// node_modules/three/examples/jsm/objects/MarchingCubes.js
var MarchingCubes = class extends Mesh {
  /**
   * Constructs a new marching cubes instance.
   *
   * @param {number} resolution - The effect's resolution.
   * @param {Material} material - The cube's material.
   * @param {boolean} [enableUvs=false] - Whether texture coordinates should be animated or not.
   * @param {boolean} [enableColors=false] - Whether colors should be animated or not.
   * @param {number} [maxPolyCount=10000] - The maximum size of the geometry buffers.
   */
  constructor(resolution, material, enableUvs = false, enableColors = false, maxPolyCount = 1e4) {
    const geometry = new BufferGeometry();
    super(geometry, material);
    this.isMarchingCubes = true;
    const scope = this;
    const vlist = new Float32Array(12 * 3);
    const nlist = new Float32Array(12 * 3);
    const clist = new Float32Array(12 * 3);
    this.enableUvs = enableUvs;
    this.enableColors = enableColors;
    this.init = function(resolution2) {
      this.resolution = resolution2;
      this.isolation = 80;
      this.size = resolution2;
      this.size2 = this.size * this.size;
      this.size3 = this.size2 * this.size;
      this.halfsize = this.size / 2;
      this.delta = 2 / this.size;
      this.yd = this.size;
      this.zd = this.size2;
      this.field = new Float32Array(this.size3);
      this.normal_cache = new Float32Array(this.size3 * 3);
      this.palette = new Float32Array(this.size3 * 3);
      this.count = 0;
      const maxVertexCount = maxPolyCount * 3;
      this.positionArray = new Float32Array(maxVertexCount * 3);
      const positionAttribute = new BufferAttribute(this.positionArray, 3);
      positionAttribute.setUsage(DynamicDrawUsage);
      geometry.setAttribute("position", positionAttribute);
      this.normalArray = new Float32Array(maxVertexCount * 3);
      const normalAttribute = new BufferAttribute(this.normalArray, 3);
      normalAttribute.setUsage(DynamicDrawUsage);
      geometry.setAttribute("normal", normalAttribute);
      if (this.enableUvs) {
        this.uvArray = new Float32Array(maxVertexCount * 2);
        const uvAttribute = new BufferAttribute(this.uvArray, 2);
        uvAttribute.setUsage(DynamicDrawUsage);
        geometry.setAttribute("uv", uvAttribute);
      }
      if (this.enableColors) {
        this.colorArray = new Float32Array(maxVertexCount * 3);
        const colorAttribute = new BufferAttribute(this.colorArray, 3);
        colorAttribute.setUsage(DynamicDrawUsage);
        geometry.setAttribute("color", colorAttribute);
      }
      geometry.boundingSphere = new Sphere(new Vector3(), 1);
    };
    function lerp2(a2, b3, t3) {
      return a2 + (b3 - a2) * t3;
    }
    function VIntX(q2, offset, isol, x2, y, z, valp1, valp2, c_offset1, c_offset2) {
      const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache;
      vlist[offset + 0] = x2 + mu * scope.delta;
      vlist[offset + 1] = y;
      vlist[offset + 2] = z;
      nlist[offset + 0] = lerp2(nc[q2 + 0], nc[q2 + 3], mu);
      nlist[offset + 1] = lerp2(nc[q2 + 1], nc[q2 + 4], mu);
      nlist[offset + 2] = lerp2(nc[q2 + 2], nc[q2 + 5], mu);
      clist[offset + 0] = lerp2(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu);
      clist[offset + 1] = lerp2(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu);
      clist[offset + 2] = lerp2(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu);
    }
    function VIntY(q2, offset, isol, x2, y, z, valp1, valp2, c_offset1, c_offset2) {
      const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache;
      vlist[offset + 0] = x2;
      vlist[offset + 1] = y + mu * scope.delta;
      vlist[offset + 2] = z;
      const q22 = q2 + scope.yd * 3;
      nlist[offset + 0] = lerp2(nc[q2 + 0], nc[q22 + 0], mu);
      nlist[offset + 1] = lerp2(nc[q2 + 1], nc[q22 + 1], mu);
      nlist[offset + 2] = lerp2(nc[q2 + 2], nc[q22 + 2], mu);
      clist[offset + 0] = lerp2(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu);
      clist[offset + 1] = lerp2(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu);
      clist[offset + 2] = lerp2(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu);
    }
    function VIntZ(q2, offset, isol, x2, y, z, valp1, valp2, c_offset1, c_offset2) {
      const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache;
      vlist[offset + 0] = x2;
      vlist[offset + 1] = y;
      vlist[offset + 2] = z + mu * scope.delta;
      const q22 = q2 + scope.zd * 3;
      nlist[offset + 0] = lerp2(nc[q2 + 0], nc[q22 + 0], mu);
      nlist[offset + 1] = lerp2(nc[q2 + 1], nc[q22 + 1], mu);
      nlist[offset + 2] = lerp2(nc[q2 + 2], nc[q22 + 2], mu);
      clist[offset + 0] = lerp2(scope.palette[c_offset1 * 3 + 0], scope.palette[c_offset2 * 3 + 0], mu);
      clist[offset + 1] = lerp2(scope.palette[c_offset1 * 3 + 1], scope.palette[c_offset2 * 3 + 1], mu);
      clist[offset + 2] = lerp2(scope.palette[c_offset1 * 3 + 2], scope.palette[c_offset2 * 3 + 2], mu);
    }
    function compNorm(q2) {
      const q3 = q2 * 3;
      if (scope.normal_cache[q3] === 0) {
        scope.normal_cache[q3 + 0] = scope.field[q2 - 1] - scope.field[q2 + 1];
        scope.normal_cache[q3 + 1] = scope.field[q2 - scope.yd] - scope.field[q2 + scope.yd];
        scope.normal_cache[q3 + 2] = scope.field[q2 - scope.zd] - scope.field[q2 + scope.zd];
      }
    }
    function polygonize(fx, fy, fz, q2, isol) {
      const q1 = q2 + 1, qy = q2 + scope.yd, qz = q2 + scope.zd, q1y = q1 + scope.yd, q1z = q1 + scope.zd, qyz = q2 + scope.yd + scope.zd, q1yz = q1 + scope.yd + scope.zd;
      let cubeindex = 0;
      const field0 = scope.field[q2], field1 = scope.field[q1], field2 = scope.field[qy], field3 = scope.field[q1y], field4 = scope.field[qz], field5 = scope.field[q1z], field6 = scope.field[qyz], field7 = scope.field[q1yz];
      if (field0 < isol) cubeindex |= 1;
      if (field1 < isol) cubeindex |= 2;
      if (field2 < isol) cubeindex |= 8;
      if (field3 < isol) cubeindex |= 4;
      if (field4 < isol) cubeindex |= 16;
      if (field5 < isol) cubeindex |= 32;
      if (field6 < isol) cubeindex |= 128;
      if (field7 < isol) cubeindex |= 64;
      const bits2 = edgeTable[cubeindex];
      if (bits2 === 0) return 0;
      const d = scope.delta, fx2 = fx + d, fy2 = fy + d, fz2 = fz + d;
      if (bits2 & 1) {
        compNorm(q2);
        compNorm(q1);
        VIntX(q2 * 3, 0, isol, fx, fy, fz, field0, field1, q2, q1);
      }
      if (bits2 & 2) {
        compNorm(q1);
        compNorm(q1y);
        VIntY(q1 * 3, 3, isol, fx2, fy, fz, field1, field3, q1, q1y);
      }
      if (bits2 & 4) {
        compNorm(qy);
        compNorm(q1y);
        VIntX(qy * 3, 6, isol, fx, fy2, fz, field2, field3, qy, q1y);
      }
      if (bits2 & 8) {
        compNorm(q2);
        compNorm(qy);
        VIntY(q2 * 3, 9, isol, fx, fy, fz, field0, field2, q2, qy);
      }
      if (bits2 & 16) {
        compNorm(qz);
        compNorm(q1z);
        VIntX(qz * 3, 12, isol, fx, fy, fz2, field4, field5, qz, q1z);
      }
      if (bits2 & 32) {
        compNorm(q1z);
        compNorm(q1yz);
        VIntY(
          q1z * 3,
          15,
          isol,
          fx2,
          fy,
          fz2,
          field5,
          field7,
          q1z,
          q1yz
        );
      }
      if (bits2 & 64) {
        compNorm(qyz);
        compNorm(q1yz);
        VIntX(
          qyz * 3,
          18,
          isol,
          fx,
          fy2,
          fz2,
          field6,
          field7,
          qyz,
          q1yz
        );
      }
      if (bits2 & 128) {
        compNorm(qz);
        compNorm(qyz);
        VIntY(qz * 3, 21, isol, fx, fy, fz2, field4, field6, qz, qyz);
      }
      if (bits2 & 256) {
        compNorm(q2);
        compNorm(qz);
        VIntZ(q2 * 3, 24, isol, fx, fy, fz, field0, field4, q2, qz);
      }
      if (bits2 & 512) {
        compNorm(q1);
        compNorm(q1z);
        VIntZ(q1 * 3, 27, isol, fx2, fy, fz, field1, field5, q1, q1z);
      }
      if (bits2 & 1024) {
        compNorm(q1y);
        compNorm(q1yz);
        VIntZ(
          q1y * 3,
          30,
          isol,
          fx2,
          fy2,
          fz,
          field3,
          field7,
          q1y,
          q1yz
        );
      }
      if (bits2 & 2048) {
        compNorm(qy);
        compNorm(qyz);
        VIntZ(qy * 3, 33, isol, fx, fy2, fz, field2, field6, qy, qyz);
      }
      cubeindex <<= 4;
      let o1, o2, o3, numtris = 0, i = 0;
      while (triTable[cubeindex + i] != -1) {
        o1 = cubeindex + i;
        o2 = o1 + 1;
        o3 = o1 + 2;
        posnormtriv(
          vlist,
          nlist,
          clist,
          3 * triTable[o1],
          3 * triTable[o2],
          3 * triTable[o3]
        );
        i += 3;
        numtris++;
      }
      return numtris;
    }
    function posnormtriv(pos, norm, colors, o1, o2, o3) {
      const c2 = scope.count * 3;
      scope.positionArray[c2 + 0] = pos[o1];
      scope.positionArray[c2 + 1] = pos[o1 + 1];
      scope.positionArray[c2 + 2] = pos[o1 + 2];
      scope.positionArray[c2 + 3] = pos[o2];
      scope.positionArray[c2 + 4] = pos[o2 + 1];
      scope.positionArray[c2 + 5] = pos[o2 + 2];
      scope.positionArray[c2 + 6] = pos[o3];
      scope.positionArray[c2 + 7] = pos[o3 + 1];
      scope.positionArray[c2 + 8] = pos[o3 + 2];
      if (scope.material.flatShading === true) {
        const nx = (norm[o1 + 0] + norm[o2 + 0] + norm[o3 + 0]) / 3;
        const ny = (norm[o1 + 1] + norm[o2 + 1] + norm[o3 + 1]) / 3;
        const nz = (norm[o1 + 2] + norm[o2 + 2] + norm[o3 + 2]) / 3;
        scope.normalArray[c2 + 0] = nx;
        scope.normalArray[c2 + 1] = ny;
        scope.normalArray[c2 + 2] = nz;
        scope.normalArray[c2 + 3] = nx;
        scope.normalArray[c2 + 4] = ny;
        scope.normalArray[c2 + 5] = nz;
        scope.normalArray[c2 + 6] = nx;
        scope.normalArray[c2 + 7] = ny;
        scope.normalArray[c2 + 8] = nz;
      } else {
        scope.normalArray[c2 + 0] = norm[o1 + 0];
        scope.normalArray[c2 + 1] = norm[o1 + 1];
        scope.normalArray[c2 + 2] = norm[o1 + 2];
        scope.normalArray[c2 + 3] = norm[o2 + 0];
        scope.normalArray[c2 + 4] = norm[o2 + 1];
        scope.normalArray[c2 + 5] = norm[o2 + 2];
        scope.normalArray[c2 + 6] = norm[o3 + 0];
        scope.normalArray[c2 + 7] = norm[o3 + 1];
        scope.normalArray[c2 + 8] = norm[o3 + 2];
      }
      if (scope.enableUvs) {
        const d = scope.count * 2;
        scope.uvArray[d + 0] = pos[o1 + 0];
        scope.uvArray[d + 1] = pos[o1 + 2];
        scope.uvArray[d + 2] = pos[o2 + 0];
        scope.uvArray[d + 3] = pos[o2 + 2];
        scope.uvArray[d + 4] = pos[o3 + 0];
        scope.uvArray[d + 5] = pos[o3 + 2];
      }
      if (scope.enableColors) {
        scope.colorArray[c2 + 0] = colors[o1 + 0];
        scope.colorArray[c2 + 1] = colors[o1 + 1];
        scope.colorArray[c2 + 2] = colors[o1 + 2];
        scope.colorArray[c2 + 3] = colors[o2 + 0];
        scope.colorArray[c2 + 4] = colors[o2 + 1];
        scope.colorArray[c2 + 5] = colors[o2 + 2];
        scope.colorArray[c2 + 6] = colors[o3 + 0];
        scope.colorArray[c2 + 7] = colors[o3 + 1];
        scope.colorArray[c2 + 8] = colors[o3 + 2];
      }
      scope.count += 3;
    }
    this.addBall = function(ballx, bally, ballz, strength, subtract, colors) {
      const sign = Math.sign(strength);
      strength = Math.abs(strength);
      const userDefineColor = !(colors === void 0 || colors === null);
      let ballColor = new Color(ballx, bally, ballz);
      if (userDefineColor) {
        try {
          ballColor = colors instanceof Color ? colors : Array.isArray(colors) ? new Color(
            Math.min(Math.abs(colors[0]), 1),
            Math.min(Math.abs(colors[1]), 1),
            Math.min(Math.abs(colors[2]), 1)
          ) : new Color(colors);
        } catch (err2) {
          ballColor = new Color(ballx, bally, ballz);
        }
      }
      const radius = this.size * Math.sqrt(strength / subtract), zs = ballz * this.size, ys = bally * this.size, xs = ballx * this.size;
      let min_z = Math.floor(zs - radius);
      if (min_z < 1) min_z = 1;
      let max_z = Math.floor(zs + radius);
      if (max_z > this.size - 1) max_z = this.size - 1;
      let min_y = Math.floor(ys - radius);
      if (min_y < 1) min_y = 1;
      let max_y = Math.floor(ys + radius);
      if (max_y > this.size - 1) max_y = this.size - 1;
      let min_x = Math.floor(xs - radius);
      if (min_x < 1) min_x = 1;
      let max_x = Math.floor(xs + radius);
      if (max_x > this.size - 1) max_x = this.size - 1;
      let x2, y, z, y_offset, z_offset, fx, fy, fz, fz2, fy2, val2;
      for (z = min_z; z < max_z; z++) {
        z_offset = this.size2 * z;
        fz = z / this.size - ballz;
        fz2 = fz * fz;
        for (y = min_y; y < max_y; y++) {
          y_offset = z_offset + this.size * y;
          fy = y / this.size - bally;
          fy2 = fy * fy;
          for (x2 = min_x; x2 < max_x; x2++) {
            fx = x2 / this.size - ballx;
            val2 = strength / (1e-6 + fx * fx + fy2 + fz2) - subtract;
            if (val2 > 0) {
              this.field[y_offset + x2] += val2 * sign;
              const ratio = Math.sqrt((x2 - xs) * (x2 - xs) + (y - ys) * (y - ys) + (z - zs) * (z - zs)) / radius;
              const contrib = 1 - ratio * ratio * ratio * (ratio * (ratio * 6 - 15) + 10);
              this.palette[(y_offset + x2) * 3 + 0] += ballColor.r * contrib;
              this.palette[(y_offset + x2) * 3 + 1] += ballColor.g * contrib;
              this.palette[(y_offset + x2) * 3 + 2] += ballColor.b * contrib;
            }
          }
        }
      }
    };
    this.addPlaneX = function(strength, subtract) {
      const size2 = this.size, yd = this.yd, zd = this.zd, field = this.field;
      let x2, y, z, xx, val2, xdiv, cxy, dist = size2 * Math.sqrt(strength / subtract);
      if (dist > size2) dist = size2;
      for (x2 = 0; x2 < dist; x2++) {
        xdiv = x2 / size2;
        xx = xdiv * xdiv;
        val2 = strength / (1e-4 + xx) - subtract;
        if (val2 > 0) {
          for (y = 0; y < size2; y++) {
            cxy = x2 + y * yd;
            for (z = 0; z < size2; z++) {
              field[zd * z + cxy] += val2;
            }
          }
        }
      }
    };
    this.addPlaneY = function(strength, subtract) {
      const size2 = this.size, yd = this.yd, zd = this.zd, field = this.field;
      let x2, y, z, yy, val2, ydiv, cy, cxy, dist = size2 * Math.sqrt(strength / subtract);
      if (dist > size2) dist = size2;
      for (y = 0; y < dist; y++) {
        ydiv = y / size2;
        yy = ydiv * ydiv;
        val2 = strength / (1e-4 + yy) - subtract;
        if (val2 > 0) {
          cy = y * yd;
          for (x2 = 0; x2 < size2; x2++) {
            cxy = cy + x2;
            for (z = 0; z < size2; z++) field[zd * z + cxy] += val2;
          }
        }
      }
    };
    this.addPlaneZ = function(strength, subtract) {
      const size2 = this.size, yd = this.yd, zd = this.zd, field = this.field;
      let x2, y, z, zz, val2, zdiv, cz, cyz, dist = size2 * Math.sqrt(strength / subtract);
      if (dist > size2) dist = size2;
      for (z = 0; z < dist; z++) {
        zdiv = z / size2;
        zz = zdiv * zdiv;
        val2 = strength / (1e-4 + zz) - subtract;
        if (val2 > 0) {
          cz = zd * z;
          for (y = 0; y < size2; y++) {
            cyz = cz + y * yd;
            for (x2 = 0; x2 < size2; x2++) field[cyz + x2] += val2;
          }
        }
      }
    };
    this.setCell = function(x2, y, z, value2) {
      const index2 = this.size2 * z + this.size * y + x2;
      this.field[index2] = value2;
    };
    this.getCell = function(x2, y, z) {
      const index2 = this.size2 * z + this.size * y + x2;
      return this.field[index2];
    };
    this.blur = function(intensity = 1) {
      const field = this.field;
      const fieldCopy = field.slice();
      const size2 = this.size;
      const size22 = this.size2;
      for (let x2 = 0; x2 < size2; x2++) {
        for (let y = 0; y < size2; y++) {
          for (let z = 0; z < size2; z++) {
            const index2 = size22 * z + size2 * y + x2;
            let val2 = fieldCopy[index2];
            let count = 1;
            for (let x22 = -1; x22 <= 1; x22 += 2) {
              const x3 = x22 + x2;
              if (x3 < 0 || x3 >= size2) continue;
              for (let y2 = -1; y2 <= 1; y2 += 2) {
                const y3 = y2 + y;
                if (y3 < 0 || y3 >= size2) continue;
                for (let z2 = -1; z2 <= 1; z2 += 2) {
                  const z3 = z2 + z;
                  if (z3 < 0 || z3 >= size2) continue;
                  const index22 = size22 * z3 + size2 * y3 + x3;
                  const val22 = fieldCopy[index22];
                  count++;
                  val2 += intensity * (val22 - val2) / count;
                }
              }
            }
            field[index2] = val2;
          }
        }
      }
    };
    this.reset = function() {
      for (let i = 0; i < this.size3; i++) {
        this.normal_cache[i * 3] = 0;
        this.field[i] = 0;
        this.palette[i * 3] = this.palette[i * 3 + 1] = this.palette[i * 3 + 2] = 0;
      }
    };
    this.update = function() {
      this.count = 0;
      const smin2 = this.size - 2;
      for (let z = 1; z < smin2; z++) {
        const z_offset = this.size2 * z;
        const fz = (z - this.halfsize) / this.halfsize;
        for (let y = 1; y < smin2; y++) {
          const y_offset = z_offset + this.size * y;
          const fy = (y - this.halfsize) / this.halfsize;
          for (let x2 = 1; x2 < smin2; x2++) {
            const fx = (x2 - this.halfsize) / this.halfsize;
            const q2 = y_offset + x2;
            polygonize(fx, fy, fz, q2, this.isolation);
          }
        }
      }
      this.geometry.setDrawRange(0, this.count);
      geometry.getAttribute("position").needsUpdate = true;
      geometry.getAttribute("normal").needsUpdate = true;
      if (this.enableUvs) geometry.getAttribute("uv").needsUpdate = true;
      if (this.enableColors) geometry.getAttribute("color").needsUpdate = true;
      if (this.count / 3 > maxPolyCount) console.warn("THREE.MarchingCubes: Geometry buffers too small for rendering. Please create an instance with a higher poly count.");
    };
    this.init(resolution);
  }
};
var edgeTable = new Int32Array([
  0,
  265,
  515,
  778,
  1030,
  1295,
  1541,
  1804,
  2060,
  2309,
  2575,
  2822,
  3082,
  3331,
  3593,
  3840,
  400,
  153,
  915,
  666,
  1430,
  1183,
  1941,
  1692,
  2460,
  2197,
  2975,
  2710,
  3482,
  3219,
  3993,
  3728,
  560,
  825,
  51,
  314,
  1590,
  1855,
  1077,
  1340,
  2620,
  2869,
  2111,
  2358,
  3642,
  3891,
  3129,
  3376,
  928,
  681,
  419,
  170,
  1958,
  1711,
  1445,
  1196,
  2988,
  2725,
  2479,
  2214,
  4010,
  3747,
  3497,
  3232,
  1120,
  1385,
  1635,
  1898,
  102,
  367,
  613,
  876,
  3180,
  3429,
  3695,
  3942,
  2154,
  2403,
  2665,
  2912,
  1520,
  1273,
  2035,
  1786,
  502,
  255,
  1013,
  764,
  3580,
  3317,
  4095,
  3830,
  2554,
  2291,
  3065,
  2800,
  1616,
  1881,
  1107,
  1370,
  598,
  863,
  85,
  348,
  3676,
  3925,
  3167,
  3414,
  2650,
  2899,
  2137,
  2384,
  1984,
  1737,
  1475,
  1226,
  966,
  719,
  453,
  204,
  4044,
  3781,
  3535,
  3270,
  3018,
  2755,
  2505,
  2240,
  2240,
  2505,
  2755,
  3018,
  3270,
  3535,
  3781,
  4044,
  204,
  453,
  719,
  966,
  1226,
  1475,
  1737,
  1984,
  2384,
  2137,
  2899,
  2650,
  3414,
  3167,
  3925,
  3676,
  348,
  85,
  863,
  598,
  1370,
  1107,
  1881,
  1616,
  2800,
  3065,
  2291,
  2554,
  3830,
  4095,
  3317,
  3580,
  764,
  1013,
  255,
  502,
  1786,
  2035,
  1273,
  1520,
  2912,
  2665,
  2403,
  2154,
  3942,
  3695,
  3429,
  3180,
  876,
  613,
  367,
  102,
  1898,
  1635,
  1385,
  1120,
  3232,
  3497,
  3747,
  4010,
  2214,
  2479,
  2725,
  2988,
  1196,
  1445,
  1711,
  1958,
  170,
  419,
  681,
  928,
  3376,
  3129,
  3891,
  3642,
  2358,
  2111,
  2869,
  2620,
  1340,
  1077,
  1855,
  1590,
  314,
  51,
  825,
  560,
  3728,
  3993,
  3219,
  3482,
  2710,
  2975,
  2197,
  2460,
  1692,
  1941,
  1183,
  1430,
  666,
  915,
  153,
  400,
  3840,
  3593,
  3331,
  3082,
  2822,
  2575,
  2309,
  2060,
  1804,
  1541,
  1295,
  1030,
  778,
  515,
  265,
  0
]);
var triTable = new Int32Array([
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  1,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  8,
  3,
  9,
  8,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  3,
  1,
  2,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  2,
  10,
  0,
  2,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  8,
  3,
  2,
  10,
  8,
  10,
  9,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  11,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  11,
  2,
  8,
  11,
  0,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  9,
  0,
  2,
  3,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  11,
  2,
  1,
  9,
  11,
  9,
  8,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  10,
  1,
  11,
  10,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  10,
  1,
  0,
  8,
  10,
  8,
  11,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  9,
  0,
  3,
  11,
  9,
  11,
  10,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  8,
  10,
  10,
  8,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  7,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  3,
  0,
  7,
  3,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  1,
  9,
  8,
  4,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  1,
  9,
  4,
  7,
  1,
  7,
  3,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  10,
  8,
  4,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  4,
  7,
  3,
  0,
  4,
  1,
  2,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  2,
  10,
  9,
  0,
  2,
  8,
  4,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  10,
  9,
  2,
  9,
  7,
  2,
  7,
  3,
  7,
  9,
  4,
  -1,
  -1,
  -1,
  -1,
  8,
  4,
  7,
  3,
  11,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  11,
  4,
  7,
  11,
  2,
  4,
  2,
  0,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  0,
  1,
  8,
  4,
  7,
  2,
  3,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  7,
  11,
  9,
  4,
  11,
  9,
  11,
  2,
  9,
  2,
  1,
  -1,
  -1,
  -1,
  -1,
  3,
  10,
  1,
  3,
  11,
  10,
  7,
  8,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  11,
  10,
  1,
  4,
  11,
  1,
  0,
  4,
  7,
  11,
  4,
  -1,
  -1,
  -1,
  -1,
  4,
  7,
  8,
  9,
  0,
  11,
  9,
  11,
  10,
  11,
  0,
  3,
  -1,
  -1,
  -1,
  -1,
  4,
  7,
  11,
  4,
  11,
  9,
  9,
  11,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  5,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  5,
  4,
  0,
  8,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  5,
  4,
  1,
  5,
  0,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8,
  5,
  4,
  8,
  3,
  5,
  3,
  1,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  10,
  9,
  5,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  0,
  8,
  1,
  2,
  10,
  4,
  9,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  2,
  10,
  5,
  4,
  2,
  4,
  0,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  10,
  5,
  3,
  2,
  5,
  3,
  5,
  4,
  3,
  4,
  8,
  -1,
  -1,
  -1,
  -1,
  9,
  5,
  4,
  2,
  3,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  11,
  2,
  0,
  8,
  11,
  4,
  9,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  5,
  4,
  0,
  1,
  5,
  2,
  3,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  1,
  5,
  2,
  5,
  8,
  2,
  8,
  11,
  4,
  8,
  5,
  -1,
  -1,
  -1,
  -1,
  10,
  3,
  11,
  10,
  1,
  3,
  9,
  5,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  9,
  5,
  0,
  8,
  1,
  8,
  10,
  1,
  8,
  11,
  10,
  -1,
  -1,
  -1,
  -1,
  5,
  4,
  0,
  5,
  0,
  11,
  5,
  11,
  10,
  11,
  0,
  3,
  -1,
  -1,
  -1,
  -1,
  5,
  4,
  8,
  5,
  8,
  10,
  10,
  8,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  7,
  8,
  5,
  7,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  3,
  0,
  9,
  5,
  3,
  5,
  7,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  7,
  8,
  0,
  1,
  7,
  1,
  5,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  5,
  3,
  3,
  5,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  7,
  8,
  9,
  5,
  7,
  10,
  1,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  1,
  2,
  9,
  5,
  0,
  5,
  3,
  0,
  5,
  7,
  3,
  -1,
  -1,
  -1,
  -1,
  8,
  0,
  2,
  8,
  2,
  5,
  8,
  5,
  7,
  10,
  5,
  2,
  -1,
  -1,
  -1,
  -1,
  2,
  10,
  5,
  2,
  5,
  3,
  3,
  5,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7,
  9,
  5,
  7,
  8,
  9,
  3,
  11,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  5,
  7,
  9,
  7,
  2,
  9,
  2,
  0,
  2,
  7,
  11,
  -1,
  -1,
  -1,
  -1,
  2,
  3,
  11,
  0,
  1,
  8,
  1,
  7,
  8,
  1,
  5,
  7,
  -1,
  -1,
  -1,
  -1,
  11,
  2,
  1,
  11,
  1,
  7,
  7,
  1,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  5,
  8,
  8,
  5,
  7,
  10,
  1,
  3,
  10,
  3,
  11,
  -1,
  -1,
  -1,
  -1,
  5,
  7,
  0,
  5,
  0,
  9,
  7,
  11,
  0,
  1,
  0,
  10,
  11,
  10,
  0,
  -1,
  11,
  10,
  0,
  11,
  0,
  3,
  10,
  5,
  0,
  8,
  0,
  7,
  5,
  7,
  0,
  -1,
  11,
  10,
  5,
  7,
  11,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  6,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  3,
  5,
  10,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  0,
  1,
  5,
  10,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  8,
  3,
  1,
  9,
  8,
  5,
  10,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  6,
  5,
  2,
  6,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  6,
  5,
  1,
  2,
  6,
  3,
  0,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  6,
  5,
  9,
  0,
  6,
  0,
  2,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  9,
  8,
  5,
  8,
  2,
  5,
  2,
  6,
  3,
  2,
  8,
  -1,
  -1,
  -1,
  -1,
  2,
  3,
  11,
  10,
  6,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  11,
  0,
  8,
  11,
  2,
  0,
  10,
  6,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  1,
  9,
  2,
  3,
  11,
  5,
  10,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  10,
  6,
  1,
  9,
  2,
  9,
  11,
  2,
  9,
  8,
  11,
  -1,
  -1,
  -1,
  -1,
  6,
  3,
  11,
  6,
  5,
  3,
  5,
  1,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  11,
  0,
  11,
  5,
  0,
  5,
  1,
  5,
  11,
  6,
  -1,
  -1,
  -1,
  -1,
  3,
  11,
  6,
  0,
  3,
  6,
  0,
  6,
  5,
  0,
  5,
  9,
  -1,
  -1,
  -1,
  -1,
  6,
  5,
  9,
  6,
  9,
  11,
  11,
  9,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  10,
  6,
  4,
  7,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  3,
  0,
  4,
  7,
  3,
  6,
  5,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  9,
  0,
  5,
  10,
  6,
  8,
  4,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  6,
  5,
  1,
  9,
  7,
  1,
  7,
  3,
  7,
  9,
  4,
  -1,
  -1,
  -1,
  -1,
  6,
  1,
  2,
  6,
  5,
  1,
  4,
  7,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  5,
  5,
  2,
  6,
  3,
  0,
  4,
  3,
  4,
  7,
  -1,
  -1,
  -1,
  -1,
  8,
  4,
  7,
  9,
  0,
  5,
  0,
  6,
  5,
  0,
  2,
  6,
  -1,
  -1,
  -1,
  -1,
  7,
  3,
  9,
  7,
  9,
  4,
  3,
  2,
  9,
  5,
  9,
  6,
  2,
  6,
  9,
  -1,
  3,
  11,
  2,
  7,
  8,
  4,
  10,
  6,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  10,
  6,
  4,
  7,
  2,
  4,
  2,
  0,
  2,
  7,
  11,
  -1,
  -1,
  -1,
  -1,
  0,
  1,
  9,
  4,
  7,
  8,
  2,
  3,
  11,
  5,
  10,
  6,
  -1,
  -1,
  -1,
  -1,
  9,
  2,
  1,
  9,
  11,
  2,
  9,
  4,
  11,
  7,
  11,
  4,
  5,
  10,
  6,
  -1,
  8,
  4,
  7,
  3,
  11,
  5,
  3,
  5,
  1,
  5,
  11,
  6,
  -1,
  -1,
  -1,
  -1,
  5,
  1,
  11,
  5,
  11,
  6,
  1,
  0,
  11,
  7,
  11,
  4,
  0,
  4,
  11,
  -1,
  0,
  5,
  9,
  0,
  6,
  5,
  0,
  3,
  6,
  11,
  6,
  3,
  8,
  4,
  7,
  -1,
  6,
  5,
  9,
  6,
  9,
  11,
  4,
  7,
  9,
  7,
  11,
  9,
  -1,
  -1,
  -1,
  -1,
  10,
  4,
  9,
  6,
  4,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  10,
  6,
  4,
  9,
  10,
  0,
  8,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  0,
  1,
  10,
  6,
  0,
  6,
  4,
  0,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8,
  3,
  1,
  8,
  1,
  6,
  8,
  6,
  4,
  6,
  1,
  10,
  -1,
  -1,
  -1,
  -1,
  1,
  4,
  9,
  1,
  2,
  4,
  2,
  6,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  0,
  8,
  1,
  2,
  9,
  2,
  4,
  9,
  2,
  6,
  4,
  -1,
  -1,
  -1,
  -1,
  0,
  2,
  4,
  4,
  2,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8,
  3,
  2,
  8,
  2,
  4,
  4,
  2,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  4,
  9,
  10,
  6,
  4,
  11,
  2,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  2,
  2,
  8,
  11,
  4,
  9,
  10,
  4,
  10,
  6,
  -1,
  -1,
  -1,
  -1,
  3,
  11,
  2,
  0,
  1,
  6,
  0,
  6,
  4,
  6,
  1,
  10,
  -1,
  -1,
  -1,
  -1,
  6,
  4,
  1,
  6,
  1,
  10,
  4,
  8,
  1,
  2,
  1,
  11,
  8,
  11,
  1,
  -1,
  9,
  6,
  4,
  9,
  3,
  6,
  9,
  1,
  3,
  11,
  6,
  3,
  -1,
  -1,
  -1,
  -1,
  8,
  11,
  1,
  8,
  1,
  0,
  11,
  6,
  1,
  9,
  1,
  4,
  6,
  4,
  1,
  -1,
  3,
  11,
  6,
  3,
  6,
  0,
  0,
  6,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6,
  4,
  8,
  11,
  6,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7,
  10,
  6,
  7,
  8,
  10,
  8,
  9,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  7,
  3,
  0,
  10,
  7,
  0,
  9,
  10,
  6,
  7,
  10,
  -1,
  -1,
  -1,
  -1,
  10,
  6,
  7,
  1,
  10,
  7,
  1,
  7,
  8,
  1,
  8,
  0,
  -1,
  -1,
  -1,
  -1,
  10,
  6,
  7,
  10,
  7,
  1,
  1,
  7,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  6,
  1,
  6,
  8,
  1,
  8,
  9,
  8,
  6,
  7,
  -1,
  -1,
  -1,
  -1,
  2,
  6,
  9,
  2,
  9,
  1,
  6,
  7,
  9,
  0,
  9,
  3,
  7,
  3,
  9,
  -1,
  7,
  8,
  0,
  7,
  0,
  6,
  6,
  0,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7,
  3,
  2,
  6,
  7,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  3,
  11,
  10,
  6,
  8,
  10,
  8,
  9,
  8,
  6,
  7,
  -1,
  -1,
  -1,
  -1,
  2,
  0,
  7,
  2,
  7,
  11,
  0,
  9,
  7,
  6,
  7,
  10,
  9,
  10,
  7,
  -1,
  1,
  8,
  0,
  1,
  7,
  8,
  1,
  10,
  7,
  6,
  7,
  10,
  2,
  3,
  11,
  -1,
  11,
  2,
  1,
  11,
  1,
  7,
  10,
  6,
  1,
  6,
  7,
  1,
  -1,
  -1,
  -1,
  -1,
  8,
  9,
  6,
  8,
  6,
  7,
  9,
  1,
  6,
  11,
  6,
  3,
  1,
  3,
  6,
  -1,
  0,
  9,
  1,
  11,
  6,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7,
  8,
  0,
  7,
  0,
  6,
  3,
  11,
  0,
  11,
  6,
  0,
  -1,
  -1,
  -1,
  -1,
  7,
  11,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7,
  6,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  0,
  8,
  11,
  7,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  1,
  9,
  11,
  7,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8,
  1,
  9,
  8,
  3,
  1,
  11,
  7,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  1,
  2,
  6,
  11,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  10,
  3,
  0,
  8,
  6,
  11,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  9,
  0,
  2,
  10,
  9,
  6,
  11,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6,
  11,
  7,
  2,
  10,
  3,
  10,
  8,
  3,
  10,
  9,
  8,
  -1,
  -1,
  -1,
  -1,
  7,
  2,
  3,
  6,
  2,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  7,
  0,
  8,
  7,
  6,
  0,
  6,
  2,
  0,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  7,
  6,
  2,
  3,
  7,
  0,
  1,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  6,
  2,
  1,
  8,
  6,
  1,
  9,
  8,
  8,
  7,
  6,
  -1,
  -1,
  -1,
  -1,
  10,
  7,
  6,
  10,
  1,
  7,
  1,
  3,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  7,
  6,
  1,
  7,
  10,
  1,
  8,
  7,
  1,
  0,
  8,
  -1,
  -1,
  -1,
  -1,
  0,
  3,
  7,
  0,
  7,
  10,
  0,
  10,
  9,
  6,
  10,
  7,
  -1,
  -1,
  -1,
  -1,
  7,
  6,
  10,
  7,
  10,
  8,
  8,
  10,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6,
  8,
  4,
  11,
  8,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  6,
  11,
  3,
  0,
  6,
  0,
  4,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8,
  6,
  11,
  8,
  4,
  6,
  9,
  0,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  4,
  6,
  9,
  6,
  3,
  9,
  3,
  1,
  11,
  3,
  6,
  -1,
  -1,
  -1,
  -1,
  6,
  8,
  4,
  6,
  11,
  8,
  2,
  10,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  10,
  3,
  0,
  11,
  0,
  6,
  11,
  0,
  4,
  6,
  -1,
  -1,
  -1,
  -1,
  4,
  11,
  8,
  4,
  6,
  11,
  0,
  2,
  9,
  2,
  10,
  9,
  -1,
  -1,
  -1,
  -1,
  10,
  9,
  3,
  10,
  3,
  2,
  9,
  4,
  3,
  11,
  3,
  6,
  4,
  6,
  3,
  -1,
  8,
  2,
  3,
  8,
  4,
  2,
  4,
  6,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  4,
  2,
  4,
  6,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  9,
  0,
  2,
  3,
  4,
  2,
  4,
  6,
  4,
  3,
  8,
  -1,
  -1,
  -1,
  -1,
  1,
  9,
  4,
  1,
  4,
  2,
  2,
  4,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8,
  1,
  3,
  8,
  6,
  1,
  8,
  4,
  6,
  6,
  10,
  1,
  -1,
  -1,
  -1,
  -1,
  10,
  1,
  0,
  10,
  0,
  6,
  6,
  0,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  6,
  3,
  4,
  3,
  8,
  6,
  10,
  3,
  0,
  3,
  9,
  10,
  9,
  3,
  -1,
  10,
  9,
  4,
  6,
  10,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  9,
  5,
  7,
  6,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  3,
  4,
  9,
  5,
  11,
  7,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  0,
  1,
  5,
  4,
  0,
  7,
  6,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  11,
  7,
  6,
  8,
  3,
  4,
  3,
  5,
  4,
  3,
  1,
  5,
  -1,
  -1,
  -1,
  -1,
  9,
  5,
  4,
  10,
  1,
  2,
  7,
  6,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  6,
  11,
  7,
  1,
  2,
  10,
  0,
  8,
  3,
  4,
  9,
  5,
  -1,
  -1,
  -1,
  -1,
  7,
  6,
  11,
  5,
  4,
  10,
  4,
  2,
  10,
  4,
  0,
  2,
  -1,
  -1,
  -1,
  -1,
  3,
  4,
  8,
  3,
  5,
  4,
  3,
  2,
  5,
  10,
  5,
  2,
  11,
  7,
  6,
  -1,
  7,
  2,
  3,
  7,
  6,
  2,
  5,
  4,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  5,
  4,
  0,
  8,
  6,
  0,
  6,
  2,
  6,
  8,
  7,
  -1,
  -1,
  -1,
  -1,
  3,
  6,
  2,
  3,
  7,
  6,
  1,
  5,
  0,
  5,
  4,
  0,
  -1,
  -1,
  -1,
  -1,
  6,
  2,
  8,
  6,
  8,
  7,
  2,
  1,
  8,
  4,
  8,
  5,
  1,
  5,
  8,
  -1,
  9,
  5,
  4,
  10,
  1,
  6,
  1,
  7,
  6,
  1,
  3,
  7,
  -1,
  -1,
  -1,
  -1,
  1,
  6,
  10,
  1,
  7,
  6,
  1,
  0,
  7,
  8,
  7,
  0,
  9,
  5,
  4,
  -1,
  4,
  0,
  10,
  4,
  10,
  5,
  0,
  3,
  10,
  6,
  10,
  7,
  3,
  7,
  10,
  -1,
  7,
  6,
  10,
  7,
  10,
  8,
  5,
  4,
  10,
  4,
  8,
  10,
  -1,
  -1,
  -1,
  -1,
  6,
  9,
  5,
  6,
  11,
  9,
  11,
  8,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  6,
  11,
  0,
  6,
  3,
  0,
  5,
  6,
  0,
  9,
  5,
  -1,
  -1,
  -1,
  -1,
  0,
  11,
  8,
  0,
  5,
  11,
  0,
  1,
  5,
  5,
  6,
  11,
  -1,
  -1,
  -1,
  -1,
  6,
  11,
  3,
  6,
  3,
  5,
  5,
  3,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  10,
  9,
  5,
  11,
  9,
  11,
  8,
  11,
  5,
  6,
  -1,
  -1,
  -1,
  -1,
  0,
  11,
  3,
  0,
  6,
  11,
  0,
  9,
  6,
  5,
  6,
  9,
  1,
  2,
  10,
  -1,
  11,
  8,
  5,
  11,
  5,
  6,
  8,
  0,
  5,
  10,
  5,
  2,
  0,
  2,
  5,
  -1,
  6,
  11,
  3,
  6,
  3,
  5,
  2,
  10,
  3,
  10,
  5,
  3,
  -1,
  -1,
  -1,
  -1,
  5,
  8,
  9,
  5,
  2,
  8,
  5,
  6,
  2,
  3,
  8,
  2,
  -1,
  -1,
  -1,
  -1,
  9,
  5,
  6,
  9,
  6,
  0,
  0,
  6,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  5,
  8,
  1,
  8,
  0,
  5,
  6,
  8,
  3,
  8,
  2,
  6,
  2,
  8,
  -1,
  1,
  5,
  6,
  2,
  1,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  3,
  6,
  1,
  6,
  10,
  3,
  8,
  6,
  5,
  6,
  9,
  8,
  9,
  6,
  -1,
  10,
  1,
  0,
  10,
  0,
  6,
  9,
  5,
  0,
  5,
  6,
  0,
  -1,
  -1,
  -1,
  -1,
  0,
  3,
  8,
  5,
  6,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  5,
  6,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  11,
  5,
  10,
  7,
  5,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  11,
  5,
  10,
  11,
  7,
  5,
  8,
  3,
  0,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  11,
  7,
  5,
  10,
  11,
  1,
  9,
  0,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  10,
  7,
  5,
  10,
  11,
  7,
  9,
  8,
  1,
  8,
  3,
  1,
  -1,
  -1,
  -1,
  -1,
  11,
  1,
  2,
  11,
  7,
  1,
  7,
  5,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  3,
  1,
  2,
  7,
  1,
  7,
  5,
  7,
  2,
  11,
  -1,
  -1,
  -1,
  -1,
  9,
  7,
  5,
  9,
  2,
  7,
  9,
  0,
  2,
  2,
  11,
  7,
  -1,
  -1,
  -1,
  -1,
  7,
  5,
  2,
  7,
  2,
  11,
  5,
  9,
  2,
  3,
  2,
  8,
  9,
  8,
  2,
  -1,
  2,
  5,
  10,
  2,
  3,
  5,
  3,
  7,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8,
  2,
  0,
  8,
  5,
  2,
  8,
  7,
  5,
  10,
  2,
  5,
  -1,
  -1,
  -1,
  -1,
  9,
  0,
  1,
  5,
  10,
  3,
  5,
  3,
  7,
  3,
  10,
  2,
  -1,
  -1,
  -1,
  -1,
  9,
  8,
  2,
  9,
  2,
  1,
  8,
  7,
  2,
  10,
  2,
  5,
  7,
  5,
  2,
  -1,
  1,
  3,
  5,
  3,
  7,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  7,
  0,
  7,
  1,
  1,
  7,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  0,
  3,
  9,
  3,
  5,
  5,
  3,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  8,
  7,
  5,
  9,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  8,
  4,
  5,
  10,
  8,
  10,
  11,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  5,
  0,
  4,
  5,
  11,
  0,
  5,
  10,
  11,
  11,
  3,
  0,
  -1,
  -1,
  -1,
  -1,
  0,
  1,
  9,
  8,
  4,
  10,
  8,
  10,
  11,
  10,
  4,
  5,
  -1,
  -1,
  -1,
  -1,
  10,
  11,
  4,
  10,
  4,
  5,
  11,
  3,
  4,
  9,
  4,
  1,
  3,
  1,
  4,
  -1,
  2,
  5,
  1,
  2,
  8,
  5,
  2,
  11,
  8,
  4,
  5,
  8,
  -1,
  -1,
  -1,
  -1,
  0,
  4,
  11,
  0,
  11,
  3,
  4,
  5,
  11,
  2,
  11,
  1,
  5,
  1,
  11,
  -1,
  0,
  2,
  5,
  0,
  5,
  9,
  2,
  11,
  5,
  4,
  5,
  8,
  11,
  8,
  5,
  -1,
  9,
  4,
  5,
  2,
  11,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  5,
  10,
  3,
  5,
  2,
  3,
  4,
  5,
  3,
  8,
  4,
  -1,
  -1,
  -1,
  -1,
  5,
  10,
  2,
  5,
  2,
  4,
  4,
  2,
  0,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  10,
  2,
  3,
  5,
  10,
  3,
  8,
  5,
  4,
  5,
  8,
  0,
  1,
  9,
  -1,
  5,
  10,
  2,
  5,
  2,
  4,
  1,
  9,
  2,
  9,
  4,
  2,
  -1,
  -1,
  -1,
  -1,
  8,
  4,
  5,
  8,
  5,
  3,
  3,
  5,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  4,
  5,
  1,
  0,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  8,
  4,
  5,
  8,
  5,
  3,
  9,
  0,
  5,
  0,
  3,
  5,
  -1,
  -1,
  -1,
  -1,
  9,
  4,
  5,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  11,
  7,
  4,
  9,
  11,
  9,
  10,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  8,
  3,
  4,
  9,
  7,
  9,
  11,
  7,
  9,
  10,
  11,
  -1,
  -1,
  -1,
  -1,
  1,
  10,
  11,
  1,
  11,
  4,
  1,
  4,
  0,
  7,
  4,
  11,
  -1,
  -1,
  -1,
  -1,
  3,
  1,
  4,
  3,
  4,
  8,
  1,
  10,
  4,
  7,
  4,
  11,
  10,
  11,
  4,
  -1,
  4,
  11,
  7,
  9,
  11,
  4,
  9,
  2,
  11,
  9,
  1,
  2,
  -1,
  -1,
  -1,
  -1,
  9,
  7,
  4,
  9,
  11,
  7,
  9,
  1,
  11,
  2,
  11,
  1,
  0,
  8,
  3,
  -1,
  11,
  7,
  4,
  11,
  4,
  2,
  2,
  4,
  0,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  11,
  7,
  4,
  11,
  4,
  2,
  8,
  3,
  4,
  3,
  2,
  4,
  -1,
  -1,
  -1,
  -1,
  2,
  9,
  10,
  2,
  7,
  9,
  2,
  3,
  7,
  7,
  4,
  9,
  -1,
  -1,
  -1,
  -1,
  9,
  10,
  7,
  9,
  7,
  4,
  10,
  2,
  7,
  8,
  7,
  0,
  2,
  0,
  7,
  -1,
  3,
  7,
  10,
  3,
  10,
  2,
  7,
  4,
  10,
  1,
  10,
  0,
  4,
  0,
  10,
  -1,
  1,
  10,
  2,
  8,
  7,
  4,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  9,
  1,
  4,
  1,
  7,
  7,
  1,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  9,
  1,
  4,
  1,
  7,
  0,
  8,
  1,
  8,
  7,
  1,
  -1,
  -1,
  -1,
  -1,
  4,
  0,
  3,
  7,
  4,
  3,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  4,
  8,
  7,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  10,
  8,
  10,
  11,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  0,
  9,
  3,
  9,
  11,
  11,
  9,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  1,
  10,
  0,
  10,
  8,
  8,
  10,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  1,
  10,
  11,
  3,
  10,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  2,
  11,
  1,
  11,
  9,
  9,
  11,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  0,
  9,
  3,
  9,
  11,
  1,
  2,
  9,
  2,
  11,
  9,
  -1,
  -1,
  -1,
  -1,
  0,
  2,
  11,
  8,
  0,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  3,
  2,
  11,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  3,
  8,
  2,
  8,
  10,
  10,
  8,
  9,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  9,
  10,
  2,
  0,
  9,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  2,
  3,
  8,
  2,
  8,
  10,
  0,
  1,
  8,
  1,
  10,
  8,
  -1,
  -1,
  -1,
  -1,
  1,
  10,
  2,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  1,
  3,
  8,
  9,
  1,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  9,
  1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  0,
  3,
  8,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1,
  -1
]);

// node_modules/three/examples/jsm/objects/Reflector.js
var Reflector = class _Reflector extends Mesh {
  /**
   * Constructs a new reflector.
   *
   * @param {BufferGeometry} geometry - The reflector's geometry.
   * @param {Reflector~Options} [options] - The configuration options.
   */
  constructor(geometry, options = {}) {
    super(geometry);
    this.isReflector = true;
    this.type = "Reflector";
    this.forceUpdate = false;
    this.camera = new PerspectiveCamera();
    const scope = this;
    const color = options.color !== void 0 ? new Color(options.color) : new Color(8355711);
    const textureWidth = options.textureWidth || 512;
    const textureHeight = options.textureHeight || 512;
    const clipBias = options.clipBias || 0;
    const shader = options.shader || _Reflector.ReflectorShader;
    const multisample = options.multisample !== void 0 ? options.multisample : 4;
    const reflectorPlane = new Plane();
    const normal = new Vector3();
    const reflectorWorldPosition = new Vector3();
    const cameraWorldPosition = new Vector3();
    const rotationMatrix2 = new Matrix4();
    const lookAtPosition = new Vector3(0, 0, -1);
    const clipPlane = new Vector4();
    const view = new Vector3();
    const target = new Vector3();
    const q2 = new Vector4();
    const textureMatrix = new Matrix4();
    const virtualCamera = this.camera;
    const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType });
    const material = new ShaderMaterial({
      name: shader.name !== void 0 ? shader.name : "unspecified",
      uniforms: UniformsUtils.clone(shader.uniforms),
      fragmentShader: shader.fragmentShader,
      vertexShader: shader.vertexShader
    });
    material.uniforms["tDiffuse"].value = renderTarget.texture;
    material.uniforms["color"].value = color;
    material.uniforms["textureMatrix"].value = textureMatrix;
    this.material = material;
    this.onBeforeRender = function(renderer2, scene, camera) {
      reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld);
      cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
      rotationMatrix2.extractRotation(scope.matrixWorld);
      normal.set(0, 0, 1);
      normal.applyMatrix4(rotationMatrix2);
      view.subVectors(reflectorWorldPosition, cameraWorldPosition);
      const isFacingAway = view.dot(normal) > 0;
      if (isFacingAway === true && this.forceUpdate === false) return;
      view.reflect(normal).negate();
      view.add(reflectorWorldPosition);
      rotationMatrix2.extractRotation(camera.matrixWorld);
      lookAtPosition.set(0, 0, -1);
      lookAtPosition.applyMatrix4(rotationMatrix2);
      lookAtPosition.add(cameraWorldPosition);
      target.subVectors(reflectorWorldPosition, lookAtPosition);
      target.reflect(normal).negate();
      target.add(reflectorWorldPosition);
      virtualCamera.position.copy(view);
      virtualCamera.up.set(0, 1, 0);
      virtualCamera.up.applyMatrix4(rotationMatrix2);
      virtualCamera.up.reflect(normal);
      virtualCamera.lookAt(target);
      virtualCamera.far = camera.far;
      virtualCamera.updateMatrixWorld();
      virtualCamera.projectionMatrix.copy(camera.projectionMatrix);
      textureMatrix.set(
        0.5,
        0,
        0,
        0.5,
        0,
        0.5,
        0,
        0.5,
        0,
        0,
        0.5,
        0.5,
        0,
        0,
        0,
        1
      );
      textureMatrix.multiply(virtualCamera.projectionMatrix);
      textureMatrix.multiply(virtualCamera.matrixWorldInverse);
      textureMatrix.multiply(scope.matrixWorld);
      reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition);
      reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse);
      clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant);
      const projectionMatrix = virtualCamera.projectionMatrix;
      q2.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0];
      q2.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5];
      q2.z = -1;
      q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14];
      clipPlane.multiplyScalar(2 / clipPlane.dot(q2));
      projectionMatrix.elements[2] = clipPlane.x;
      projectionMatrix.elements[6] = clipPlane.y;
      projectionMatrix.elements[10] = clipPlane.z + 1 - clipBias;
      projectionMatrix.elements[14] = clipPlane.w;
      scope.visible = false;
      const currentRenderTarget = renderer2.getRenderTarget();
      const currentXrEnabled = renderer2.xr.enabled;
      const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate;
      renderer2.xr.enabled = false;
      renderer2.shadowMap.autoUpdate = false;
      renderer2.setRenderTarget(renderTarget);
      renderer2.state.buffers.depth.setMask(true);
      if (renderer2.autoClear === false) renderer2.clear();
      renderer2.render(scene, virtualCamera);
      renderer2.xr.enabled = currentXrEnabled;
      renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate;
      renderer2.setRenderTarget(currentRenderTarget);
      const viewport = camera.viewport;
      if (viewport !== void 0) {
        renderer2.state.viewport(viewport);
      }
      scope.visible = true;
      this.forceUpdate = false;
    };
    this.getRenderTarget = function() {
      return renderTarget;
    };
    this.dispose = function() {
      renderTarget.dispose();
      scope.material.dispose();
    };
  }
};
Reflector.ReflectorShader = {
  name: "ReflectorShader",
  uniforms: {
    "color": {
      value: null
    },
    "tDiffuse": {
      value: null
    },
    "textureMatrix": {
      value: null
    }
  },
  vertexShader: (
    /* glsl */
    `
		uniform mat4 textureMatrix;
		varying vec4 vUv;

		#include <common>
		#include <logdepthbuf_pars_vertex>

		void main() {

			vUv = textureMatrix * vec4( position, 1.0 );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

			#include <logdepthbuf_vertex>

		}`
  ),
  fragmentShader: (
    /* glsl */
    `
		uniform vec3 color;
		uniform sampler2D tDiffuse;
		varying vec4 vUv;

		#include <logdepthbuf_pars_fragment>

		float blendOverlay( float base, float blend ) {

			return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );

		}

		vec3 blendOverlay( vec3 base, vec3 blend ) {

			return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );

		}

		void main() {

			#include <logdepthbuf_fragment>

			vec4 base = texture2DProj( tDiffuse, vUv );
			gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>

		}`
  )
};

// node_modules/three/examples/jsm/objects/ReflectorForSSRPass.js
var ReflectorForSSRPass = class _ReflectorForSSRPass extends Mesh {
  /**
   * Constructs a new reflector.
   *
   * @param {BufferGeometry} geometry - The reflector's geometry.
   * @param {ReflectorForSSRPass~Options} [options] - The configuration options.
   */
  constructor(geometry, options = {}) {
    super(geometry);
    this.isReflectorForSSRPass = true;
    this.type = "ReflectorForSSRPass";
    const scope = this;
    const color = options.color !== void 0 ? new Color(options.color) : new Color(8355711);
    const textureWidth = options.textureWidth || 512;
    const textureHeight = options.textureHeight || 512;
    const clipBias = options.clipBias || 0;
    const shader = options.shader || _ReflectorForSSRPass.ReflectorShader;
    const useDepthTexture = options.useDepthTexture === true;
    const yAxis2 = new Vector3(0, 1, 0);
    const vecTemp0 = new Vector3();
    const vecTemp1 = new Vector3();
    scope.needsUpdate = false;
    scope.maxDistance = _ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value;
    scope.opacity = _ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value;
    scope.color = color;
    scope.resolution = options.resolution || new Vector2(window.innerWidth, window.innerHeight);
    scope._distanceAttenuation = _ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION;
    Object.defineProperty(scope, "distanceAttenuation", {
      get() {
        return scope._distanceAttenuation;
      },
      set(val2) {
        if (scope._distanceAttenuation === val2) return;
        scope._distanceAttenuation = val2;
        scope.material.defines.DISTANCE_ATTENUATION = val2;
        scope.material.needsUpdate = true;
      }
    });
    scope._fresnel = _ReflectorForSSRPass.ReflectorShader.defines.FRESNEL;
    Object.defineProperty(scope, "fresnel", {
      get() {
        return scope._fresnel;
      },
      set(val2) {
        if (scope._fresnel === val2) return;
        scope._fresnel = val2;
        scope.material.defines.FRESNEL = val2;
        scope.material.needsUpdate = true;
      }
    });
    const normal = new Vector3();
    const reflectorWorldPosition = new Vector3();
    const cameraWorldPosition = new Vector3();
    const rotationMatrix2 = new Matrix4();
    const lookAtPosition = new Vector3(0, 0, -1);
    const view = new Vector3();
    const target = new Vector3();
    const textureMatrix = new Matrix4();
    const virtualCamera = new PerspectiveCamera();
    let depthTexture;
    if (useDepthTexture) {
      depthTexture = new DepthTexture();
      depthTexture.type = UnsignedShortType;
      depthTexture.minFilter = NearestFilter;
      depthTexture.magFilter = NearestFilter;
    }
    const parameters = {
      depthTexture: useDepthTexture ? depthTexture : null,
      type: HalfFloatType
    };
    const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, parameters);
    const material = new ShaderMaterial({
      name: shader.name !== void 0 ? shader.name : "unspecified",
      transparent: useDepthTexture,
      defines: Object.assign({}, _ReflectorForSSRPass.ReflectorShader.defines, {
        useDepthTexture
      }),
      uniforms: UniformsUtils.clone(shader.uniforms),
      fragmentShader: shader.fragmentShader,
      vertexShader: shader.vertexShader
    });
    material.uniforms["tDiffuse"].value = renderTarget.texture;
    material.uniforms["color"].value = scope.color;
    material.uniforms["textureMatrix"].value = textureMatrix;
    if (useDepthTexture) {
      material.uniforms["tDepth"].value = renderTarget.depthTexture;
    }
    this.material = material;
    const globalPlane = new Plane(new Vector3(0, 1, 0), clipBias);
    const globalPlanes = [globalPlane];
    this.doRender = function(renderer2, scene, camera) {
      material.uniforms["maxDistance"].value = scope.maxDistance;
      material.uniforms["color"].value = scope.color;
      material.uniforms["opacity"].value = scope.opacity;
      vecTemp0.copy(camera.position).normalize();
      vecTemp1.copy(vecTemp0).reflect(yAxis2);
      material.uniforms["fresnelCoe"].value = (vecTemp0.dot(vecTemp1) + 1) / 2;
      reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld);
      cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
      rotationMatrix2.extractRotation(scope.matrixWorld);
      normal.set(0, 0, 1);
      normal.applyMatrix4(rotationMatrix2);
      view.subVectors(reflectorWorldPosition, cameraWorldPosition);
      if (view.dot(normal) > 0) return;
      view.reflect(normal).negate();
      view.add(reflectorWorldPosition);
      rotationMatrix2.extractRotation(camera.matrixWorld);
      lookAtPosition.set(0, 0, -1);
      lookAtPosition.applyMatrix4(rotationMatrix2);
      lookAtPosition.add(cameraWorldPosition);
      target.subVectors(reflectorWorldPosition, lookAtPosition);
      target.reflect(normal).negate();
      target.add(reflectorWorldPosition);
      virtualCamera.position.copy(view);
      virtualCamera.up.set(0, 1, 0);
      virtualCamera.up.applyMatrix4(rotationMatrix2);
      virtualCamera.up.reflect(normal);
      virtualCamera.lookAt(target);
      virtualCamera.far = camera.far;
      virtualCamera.updateMatrixWorld();
      virtualCamera.projectionMatrix.copy(camera.projectionMatrix);
      material.uniforms["virtualCameraNear"].value = camera.near;
      material.uniforms["virtualCameraFar"].value = camera.far;
      material.uniforms["virtualCameraMatrixWorld"].value = virtualCamera.matrixWorld;
      material.uniforms["virtualCameraProjectionMatrix"].value = camera.projectionMatrix;
      material.uniforms["virtualCameraProjectionMatrixInverse"].value = camera.projectionMatrixInverse;
      material.uniforms["resolution"].value = scope.resolution;
      textureMatrix.set(
        0.5,
        0,
        0,
        0.5,
        0,
        0.5,
        0,
        0.5,
        0,
        0,
        0.5,
        0.5,
        0,
        0,
        0,
        1
      );
      textureMatrix.multiply(virtualCamera.projectionMatrix);
      textureMatrix.multiply(virtualCamera.matrixWorldInverse);
      textureMatrix.multiply(scope.matrixWorld);
      const currentRenderTarget = renderer2.getRenderTarget();
      const currentXrEnabled = renderer2.xr.enabled;
      const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate;
      const currentClippingPlanes = renderer2.clippingPlanes;
      renderer2.xr.enabled = false;
      renderer2.shadowMap.autoUpdate = false;
      renderer2.clippingPlanes = globalPlanes;
      renderer2.setRenderTarget(renderTarget);
      renderer2.state.buffers.depth.setMask(true);
      if (renderer2.autoClear === false) renderer2.clear();
      renderer2.render(scene, virtualCamera);
      renderer2.xr.enabled = currentXrEnabled;
      renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate;
      renderer2.clippingPlanes = currentClippingPlanes;
      renderer2.setRenderTarget(currentRenderTarget);
      const viewport = camera.viewport;
      if (viewport !== void 0) {
        renderer2.state.viewport(viewport);
      }
    };
    this.getRenderTarget = function() {
      return renderTarget;
    };
    this.dispose = function() {
      renderTarget.dispose();
      scope.material.dispose();
    };
  }
};
ReflectorForSSRPass.ReflectorShader = {
  name: "ReflectorShader",
  defines: {
    DISTANCE_ATTENUATION: true,
    FRESNEL: true
  },
  uniforms: {
    color: { value: null },
    tDiffuse: { value: null },
    tDepth: { value: null },
    textureMatrix: { value: new Matrix4() },
    maxDistance: { value: 180 },
    opacity: { value: 0.5 },
    fresnelCoe: { value: null },
    virtualCameraNear: { value: null },
    virtualCameraFar: { value: null },
    virtualCameraProjectionMatrix: { value: new Matrix4() },
    virtualCameraMatrixWorld: { value: new Matrix4() },
    virtualCameraProjectionMatrixInverse: { value: new Matrix4() },
    resolution: { value: new Vector2() }
  },
  vertexShader: (
    /* glsl */
    `
		uniform mat4 textureMatrix;
		varying vec4 vUv;

		void main() {

			vUv = textureMatrix * vec4( position, 1.0 );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`
  ),
  fragmentShader: (
    /* glsl */
    `
		uniform vec3 color;
		uniform sampler2D tDiffuse;
		uniform sampler2D tDepth;
		uniform float maxDistance;
		uniform float opacity;
		uniform float fresnelCoe;
		uniform float virtualCameraNear;
		uniform float virtualCameraFar;
		uniform mat4 virtualCameraProjectionMatrix;
		uniform mat4 virtualCameraProjectionMatrixInverse;
		uniform mat4 virtualCameraMatrixWorld;
		uniform vec2 resolution;
		varying vec4 vUv;
		#include <packing>
		float blendOverlay( float base, float blend ) {
			return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
		}
		vec3 blendOverlay( vec3 base, vec3 blend ) {
			return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
		}
		float getDepth( const in vec2 uv ) {
			return texture2D( tDepth, uv ).x;
		}
		float getViewZ( const in float depth ) {
			return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar );
		}
		vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
			vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
			clipPosition *= clipW; //clip
			return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view
		}
		void main() {
			vec4 base = texture2DProj( tDiffuse, vUv );
			#ifdef useDepthTexture
				vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy;
				uv.x=1.-uv.x;
				float depth = texture2DProj( tDepth, vUv ).r;
				float viewZ = getViewZ( depth );
				float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3];
				vec3 viewPosition=getViewPosition( uv, depth, clipW );
				vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz;
				if(worldPosition.y>maxDistance) discard;
				float op=opacity;
				#ifdef DISTANCE_ATTENUATION
					float ratio=1.-(worldPosition.y/maxDistance);
					float attenuation=ratio*ratio;
					op=opacity*attenuation;
				#endif
				#ifdef FRESNEL
					op*=fresnelCoe;
				#endif
				gl_FragColor = vec4( blendOverlay( base.rgb, color ), op );
			#else
				gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
			#endif
		}
	`
  )
};

// node_modules/three/examples/jsm/objects/Refractor.js
var Refractor = class _Refractor extends Mesh {
  /**
   * Constructs a new refractor.
   *
   * @param {BufferGeometry} geometry - The refractor's geometry.
   * @param {Refractor~Options} [options] - The configuration options.
   */
  constructor(geometry, options = {}) {
    super(geometry);
    this.isRefractor = true;
    this.type = "Refractor";
    this.camera = new PerspectiveCamera();
    const scope = this;
    const color = options.color !== void 0 ? new Color(options.color) : new Color(8355711);
    const textureWidth = options.textureWidth || 512;
    const textureHeight = options.textureHeight || 512;
    const clipBias = options.clipBias || 0;
    const shader = options.shader || _Refractor.RefractorShader;
    const multisample = options.multisample !== void 0 ? options.multisample : 4;
    const virtualCamera = this.camera;
    virtualCamera.matrixAutoUpdate = false;
    virtualCamera.userData.refractor = true;
    const refractorPlane = new Plane();
    const textureMatrix = new Matrix4();
    const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType });
    this.material = new ShaderMaterial({
      name: shader.name !== void 0 ? shader.name : "unspecified",
      uniforms: UniformsUtils.clone(shader.uniforms),
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader,
      transparent: true
      // ensures, refractors are drawn from farthest to closest
    });
    this.material.uniforms["color"].value = color;
    this.material.uniforms["tDiffuse"].value = renderTarget.texture;
    this.material.uniforms["textureMatrix"].value = textureMatrix;
    const visible = function() {
      const refractorWorldPosition = new Vector3();
      const cameraWorldPosition = new Vector3();
      const rotationMatrix2 = new Matrix4();
      const view = new Vector3();
      const normal = new Vector3();
      return function visible2(camera) {
        refractorWorldPosition.setFromMatrixPosition(scope.matrixWorld);
        cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
        view.subVectors(refractorWorldPosition, cameraWorldPosition);
        rotationMatrix2.extractRotation(scope.matrixWorld);
        normal.set(0, 0, 1);
        normal.applyMatrix4(rotationMatrix2);
        return view.dot(normal) < 0;
      };
    }();
    const updateRefractorPlane = function() {
      const normal = new Vector3();
      const position2 = new Vector3();
      const quaternion = new Quaternion();
      const scale2 = new Vector3();
      return function updateRefractorPlane2() {
        scope.matrixWorld.decompose(position2, quaternion, scale2);
        normal.set(0, 0, 1).applyQuaternion(quaternion).normalize();
        normal.negate();
        refractorPlane.setFromNormalAndCoplanarPoint(normal, position2);
      };
    }();
    const updateVirtualCamera = function() {
      const clipPlane = new Plane();
      const clipVector = new Vector4();
      const q2 = new Vector4();
      return function updateVirtualCamera2(camera) {
        virtualCamera.matrixWorld.copy(camera.matrixWorld);
        virtualCamera.matrixWorldInverse.copy(virtualCamera.matrixWorld).invert();
        virtualCamera.projectionMatrix.copy(camera.projectionMatrix);
        virtualCamera.far = camera.far;
        clipPlane.copy(refractorPlane);
        clipPlane.applyMatrix4(virtualCamera.matrixWorldInverse);
        clipVector.set(clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant);
        const projectionMatrix = virtualCamera.projectionMatrix;
        q2.x = (Math.sign(clipVector.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0];
        q2.y = (Math.sign(clipVector.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5];
        q2.z = -1;
        q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14];
        clipVector.multiplyScalar(2 / clipVector.dot(q2));
        projectionMatrix.elements[2] = clipVector.x;
        projectionMatrix.elements[6] = clipVector.y;
        projectionMatrix.elements[10] = clipVector.z + 1 - clipBias;
        projectionMatrix.elements[14] = clipVector.w;
      };
    }();
    function updateTextureMatrix(camera) {
      textureMatrix.set(
        0.5,
        0,
        0,
        0.5,
        0,
        0.5,
        0,
        0.5,
        0,
        0,
        0.5,
        0.5,
        0,
        0,
        0,
        1
      );
      textureMatrix.multiply(camera.projectionMatrix);
      textureMatrix.multiply(camera.matrixWorldInverse);
      textureMatrix.multiply(scope.matrixWorld);
    }
    function render(renderer2, scene, camera) {
      scope.visible = false;
      const currentRenderTarget = renderer2.getRenderTarget();
      const currentXrEnabled = renderer2.xr.enabled;
      const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate;
      renderer2.xr.enabled = false;
      renderer2.shadowMap.autoUpdate = false;
      renderer2.setRenderTarget(renderTarget);
      if (renderer2.autoClear === false) renderer2.clear();
      renderer2.render(scene, virtualCamera);
      renderer2.xr.enabled = currentXrEnabled;
      renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate;
      renderer2.setRenderTarget(currentRenderTarget);
      const viewport = camera.viewport;
      if (viewport !== void 0) {
        renderer2.state.viewport(viewport);
      }
      scope.visible = true;
    }
    this.onBeforeRender = function(renderer2, scene, camera) {
      if (camera.userData.refractor === true) return;
      if (!visible(camera) === true) return;
      updateRefractorPlane();
      updateTextureMatrix(camera);
      updateVirtualCamera(camera);
      render(renderer2, scene, camera);
    };
    this.getRenderTarget = function() {
      return renderTarget;
    };
    this.dispose = function() {
      renderTarget.dispose();
      scope.material.dispose();
    };
  }
};
Refractor.RefractorShader = {
  name: "RefractorShader",
  uniforms: {
    "color": {
      value: null
    },
    "tDiffuse": {
      value: null
    },
    "textureMatrix": {
      value: null
    }
  },
  vertexShader: (
    /* glsl */
    `

		uniform mat4 textureMatrix;

		varying vec4 vUv;

		void main() {

			vUv = textureMatrix * vec4( position, 1.0 );
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform vec3 color;
		uniform sampler2D tDiffuse;

		varying vec4 vUv;

		float blendOverlay( float base, float blend ) {

			return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );

		}

		vec3 blendOverlay( vec3 base, vec3 blend ) {

			return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );

		}

		void main() {

			vec4 base = texture2DProj( tDiffuse, vUv );
			gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>

		}`
  )
};

// node_modules/three/examples/jsm/objects/ShadowMesh.js
var _shadowMatrix = new Matrix4();
var ShadowMesh = class extends Mesh {
  /**
   * Constructs a new shadow mesh.
   *
   * @param {Mesh} mesh - The shadow-casting reference mesh.
   */
  constructor(mesh) {
    const shadowMaterial = new MeshBasicMaterial({
      color: 0,
      transparent: true,
      opacity: 0.6,
      depthWrite: false,
      stencilWrite: true,
      stencilFunc: EqualStencilFunc,
      stencilRef: 0,
      stencilZPass: IncrementStencilOp
    });
    super(mesh.geometry, shadowMaterial);
    this.isShadowMesh = true;
    this.meshMatrix = mesh.matrixWorld;
    this.frustumCulled = false;
    this.matrixAutoUpdate = false;
  }
  /**
   * Updates the shadow mesh so it follows its shadow-casting reference mesh.
   *
   * @param {Plane} plane - The plane onto the shadow mesh is projected.
   * @param {Vector4} lightPosition4D - The light position.
   */
  update(plane2, lightPosition4D) {
    const dot = plane2.normal.x * lightPosition4D.x + plane2.normal.y * lightPosition4D.y + plane2.normal.z * lightPosition4D.z + -plane2.constant * lightPosition4D.w;
    const sme = _shadowMatrix.elements;
    sme[0] = dot - lightPosition4D.x * plane2.normal.x;
    sme[4] = -lightPosition4D.x * plane2.normal.y;
    sme[8] = -lightPosition4D.x * plane2.normal.z;
    sme[12] = -lightPosition4D.x * -plane2.constant;
    sme[1] = -lightPosition4D.y * plane2.normal.x;
    sme[5] = dot - lightPosition4D.y * plane2.normal.y;
    sme[9] = -lightPosition4D.y * plane2.normal.z;
    sme[13] = -lightPosition4D.y * -plane2.constant;
    sme[2] = -lightPosition4D.z * plane2.normal.x;
    sme[6] = -lightPosition4D.z * plane2.normal.y;
    sme[10] = dot - lightPosition4D.z * plane2.normal.z;
    sme[14] = -lightPosition4D.z * -plane2.constant;
    sme[3] = -lightPosition4D.w * plane2.normal.x;
    sme[7] = -lightPosition4D.w * plane2.normal.y;
    sme[11] = -lightPosition4D.w * plane2.normal.z;
    sme[15] = dot - lightPosition4D.w * -plane2.constant;
    this.matrix.multiplyMatrices(_shadowMatrix, this.meshMatrix);
  }
};

// node_modules/three/examples/jsm/objects/Sky.js
var Sky = class _Sky extends Mesh {
  /**
   * Constructs a new skydome.
   */
  constructor() {
    const shader = _Sky.SkyShader;
    const material = new ShaderMaterial({
      name: shader.name,
      uniforms: UniformsUtils.clone(shader.uniforms),
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader,
      side: BackSide,
      depthWrite: false
    });
    super(new BoxGeometry(1, 1, 1), material);
    this.isSky = true;
  }
};
Sky.SkyShader = {
  name: "SkyShader",
  uniforms: {
    "turbidity": { value: 2 },
    "rayleigh": { value: 1 },
    "mieCoefficient": { value: 5e-3 },
    "mieDirectionalG": { value: 0.8 },
    "sunPosition": { value: new Vector3() },
    "up": { value: new Vector3(0, 1, 0) }
  },
  vertexShader: (
    /* glsl */
    `
		uniform vec3 sunPosition;
		uniform float rayleigh;
		uniform float turbidity;
		uniform float mieCoefficient;
		uniform vec3 up;

		varying vec3 vWorldPosition;
		varying vec3 vSunDirection;
		varying float vSunfade;
		varying vec3 vBetaR;
		varying vec3 vBetaM;
		varying float vSunE;

		// constants for atmospheric scattering
		const float e = 2.71828182845904523536028747135266249775724709369995957;
		const float pi = 3.141592653589793238462643383279502884197169;

		// wavelength of used primaries, according to preetham
		const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 );
		// this pre-calculation replaces older TotalRayleigh(vec3 lambda) function:
		// (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn))
		const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 );

		// mie stuff
		// K coefficient for the primaries
		const float v = 4.0;
		const vec3 K = vec3( 0.686, 0.678, 0.666 );
		// MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K
		const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 );

		// earth shadow hack
		// cutoffAngle = pi / 1.95;
		const float cutoffAngle = 1.6110731556870734;
		const float steepness = 1.5;
		const float EE = 1000.0;

		float sunIntensity( float zenithAngleCos ) {
			zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 );
			return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) );
		}

		vec3 totalMie( float T ) {
			float c = ( 0.2 * T ) * 10E-18;
			return 0.434 * c * MieConst;
		}

		void main() {

			vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
			vWorldPosition = worldPosition.xyz;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
			gl_Position.z = gl_Position.w; // set z to camera.far

			vSunDirection = normalize( sunPosition );

			vSunE = sunIntensity( dot( vSunDirection, up ) );

			vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 );

			float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) );

			// extinction (absorption + out scattering)
			// rayleigh coefficients
			vBetaR = totalRayleigh * rayleighCoefficient;

			// mie coefficients
			vBetaM = totalMie( turbidity ) * mieCoefficient;

		}`
  ),
  fragmentShader: (
    /* glsl */
    `
		varying vec3 vWorldPosition;
		varying vec3 vSunDirection;
		varying float vSunfade;
		varying vec3 vBetaR;
		varying vec3 vBetaM;
		varying float vSunE;

		uniform float mieDirectionalG;
		uniform vec3 up;

		// constants for atmospheric scattering
		const float pi = 3.141592653589793238462643383279502884197169;

		const float n = 1.0003; // refractive index of air
		const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius)

		// optical length at zenith for molecules
		const float rayleighZenithLength = 8.4E3;
		const float mieZenithLength = 1.25E3;
		// 66 arc seconds -> degrees, and the cosine of that
		const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324;

		// 3.0 / ( 16.0 * pi )
		const float THREE_OVER_SIXTEENPI = 0.05968310365946075;
		// 1.0 / ( 4.0 * pi )
		const float ONE_OVER_FOURPI = 0.07957747154594767;

		float rayleighPhase( float cosTheta ) {
			return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) );
		}

		float hgPhase( float cosTheta, float g ) {
			float g2 = pow( g, 2.0 );
			float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 );
			return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse );
		}

		void main() {

			vec3 direction = normalize( vWorldPosition - cameraPosition );

			// optical length
			// cutoff angle at 90 to avoid singularity in next formula.
			float zenithAngle = acos( max( 0.0, dot( up, direction ) ) );
			float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) );
			float sR = rayleighZenithLength * inverse;
			float sM = mieZenithLength * inverse;

			// combined extinction factor
			vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) );

			// in scattering
			float cosTheta = dot( direction, vSunDirection );

			float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 );
			vec3 betaRTheta = vBetaR * rPhase;

			float mPhase = hgPhase( cosTheta, mieDirectionalG );
			vec3 betaMTheta = vBetaM * mPhase;

			vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) );
			Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) );

			// nightsky
			float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2]
			float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2]
			vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 );
			vec3 L0 = vec3( 0.1 ) * Fex;

			// composition + solar disc
			float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta );
			L0 += ( vSunE * 19000.0 * Fex ) * sundisk;

			vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 );

			vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) );

			gl_FragColor = vec4( retColor, 1.0 );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>

		}`
  )
};

// node_modules/three/examples/jsm/objects/Water.js
var Water = class extends Mesh {
  /**
   * Constructs a new water instance.
   *
   * @param {BufferGeometry} geometry - The water's geometry.
   * @param {Water~Options} [options] - The configuration options.
   */
  constructor(geometry, options = {}) {
    super(geometry);
    this.isWater = true;
    const scope = this;
    const textureWidth = options.textureWidth !== void 0 ? options.textureWidth : 512;
    const textureHeight = options.textureHeight !== void 0 ? options.textureHeight : 512;
    const clipBias = options.clipBias !== void 0 ? options.clipBias : 0;
    const alpha = options.alpha !== void 0 ? options.alpha : 1;
    const time2 = options.time !== void 0 ? options.time : 0;
    const normalSampler = options.waterNormals !== void 0 ? options.waterNormals : null;
    const sunDirection = options.sunDirection !== void 0 ? options.sunDirection : new Vector3(0.70707, 0.70707, 0);
    const sunColor = new Color(options.sunColor !== void 0 ? options.sunColor : 16777215);
    const waterColor = new Color(options.waterColor !== void 0 ? options.waterColor : 8355711);
    const eye = options.eye !== void 0 ? options.eye : new Vector3(0, 0, 0);
    const distortionScale = options.distortionScale !== void 0 ? options.distortionScale : 20;
    const side = options.side !== void 0 ? options.side : FrontSide;
    const fog = options.fog !== void 0 ? options.fog : false;
    const mirrorPlane = new Plane();
    const normal = new Vector3();
    const mirrorWorldPosition = new Vector3();
    const cameraWorldPosition = new Vector3();
    const rotationMatrix2 = new Matrix4();
    const lookAtPosition = new Vector3(0, 0, -1);
    const clipPlane = new Vector4();
    const view = new Vector3();
    const target = new Vector3();
    const q2 = new Vector4();
    const textureMatrix = new Matrix4();
    const mirrorCamera = new PerspectiveCamera();
    const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight);
    const mirrorShader = {
      name: "MirrorShader",
      uniforms: UniformsUtils.merge([
        UniformsLib["fog"],
        UniformsLib["lights"],
        {
          "normalSampler": { value: null },
          "mirrorSampler": { value: null },
          "alpha": { value: 1 },
          "time": { value: 0 },
          "size": { value: 1 },
          "distortionScale": { value: 20 },
          "textureMatrix": { value: new Matrix4() },
          "sunColor": { value: new Color(8355711) },
          "sunDirection": { value: new Vector3(0.70707, 0.70707, 0) },
          "eye": { value: new Vector3() },
          "waterColor": { value: new Color(5592405) }
        }
      ]),
      vertexShader: (
        /* glsl */
        `
				uniform mat4 textureMatrix;
				uniform float time;

				varying vec4 mirrorCoord;
				varying vec4 worldPosition;

				#include <common>
				#include <fog_pars_vertex>
				#include <shadowmap_pars_vertex>
				#include <logdepthbuf_pars_vertex>

				void main() {
					mirrorCoord = modelMatrix * vec4( position, 1.0 );
					worldPosition = mirrorCoord.xyzw;
					mirrorCoord = textureMatrix * mirrorCoord;
					vec4 mvPosition =  modelViewMatrix * vec4( position, 1.0 );
					gl_Position = projectionMatrix * mvPosition;

				#include <beginnormal_vertex>
				#include <defaultnormal_vertex>
				#include <logdepthbuf_vertex>
				#include <fog_vertex>
				#include <shadowmap_vertex>
			}`
      ),
      fragmentShader: (
        /* glsl */
        `
				uniform sampler2D mirrorSampler;
				uniform float alpha;
				uniform float time;
				uniform float size;
				uniform float distortionScale;
				uniform sampler2D normalSampler;
				uniform vec3 sunColor;
				uniform vec3 sunDirection;
				uniform vec3 eye;
				uniform vec3 waterColor;

				varying vec4 mirrorCoord;
				varying vec4 worldPosition;

				vec4 getNoise( vec2 uv ) {
					vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);
					vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );
					vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );
					vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );
					vec4 noise = texture2D( normalSampler, uv0 ) +
						texture2D( normalSampler, uv1 ) +
						texture2D( normalSampler, uv2 ) +
						texture2D( normalSampler, uv3 );
					return noise * 0.5 - 1.0;
				}

				void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) {
					vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );
					float direction = max( 0.0, dot( eyeDirection, reflection ) );
					specularColor += pow( direction, shiny ) * sunColor * spec;
					diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;
				}

				#include <common>
				#include <packing>
				#include <bsdfs>
				#include <fog_pars_fragment>
				#include <logdepthbuf_pars_fragment>
				#include <lights_pars_begin>
				#include <shadowmap_pars_fragment>
				#include <shadowmask_pars_fragment>

				void main() {

					#include <logdepthbuf_fragment>
					vec4 noise = getNoise( worldPosition.xz * size );
					vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );

					vec3 diffuseLight = vec3(0.0);
					vec3 specularLight = vec3(0.0);

					vec3 worldToEye = eye-worldPosition.xyz;
					vec3 eyeDirection = normalize( worldToEye );
					sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );

					float distance = length(worldToEye);

					vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;
					vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) );

					float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );
					float rf0 = 0.3;
					float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );
					vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;
					vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance);
					vec3 outgoingLight = albedo;
					gl_FragColor = vec4( outgoingLight, alpha );

					#include <tonemapping_fragment>
					#include <colorspace_fragment>
					#include <fog_fragment>	
				}`
      )
    };
    const material = new ShaderMaterial({
      name: mirrorShader.name,
      uniforms: UniformsUtils.clone(mirrorShader.uniforms),
      vertexShader: mirrorShader.vertexShader,
      fragmentShader: mirrorShader.fragmentShader,
      lights: true,
      side,
      fog
    });
    material.uniforms["mirrorSampler"].value = renderTarget.texture;
    material.uniforms["textureMatrix"].value = textureMatrix;
    material.uniforms["alpha"].value = alpha;
    material.uniforms["time"].value = time2;
    material.uniforms["normalSampler"].value = normalSampler;
    material.uniforms["sunColor"].value = sunColor;
    material.uniforms["waterColor"].value = waterColor;
    material.uniforms["sunDirection"].value = sunDirection;
    material.uniforms["distortionScale"].value = distortionScale;
    material.uniforms["eye"].value = eye;
    scope.material = material;
    scope.onBeforeRender = function(renderer2, scene, camera) {
      mirrorWorldPosition.setFromMatrixPosition(scope.matrixWorld);
      cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
      rotationMatrix2.extractRotation(scope.matrixWorld);
      normal.set(0, 0, 1);
      normal.applyMatrix4(rotationMatrix2);
      view.subVectors(mirrorWorldPosition, cameraWorldPosition);
      if (view.dot(normal) > 0) return;
      view.reflect(normal).negate();
      view.add(mirrorWorldPosition);
      rotationMatrix2.extractRotation(camera.matrixWorld);
      lookAtPosition.set(0, 0, -1);
      lookAtPosition.applyMatrix4(rotationMatrix2);
      lookAtPosition.add(cameraWorldPosition);
      target.subVectors(mirrorWorldPosition, lookAtPosition);
      target.reflect(normal).negate();
      target.add(mirrorWorldPosition);
      mirrorCamera.position.copy(view);
      mirrorCamera.up.set(0, 1, 0);
      mirrorCamera.up.applyMatrix4(rotationMatrix2);
      mirrorCamera.up.reflect(normal);
      mirrorCamera.lookAt(target);
      mirrorCamera.far = camera.far;
      mirrorCamera.updateMatrixWorld();
      mirrorCamera.projectionMatrix.copy(camera.projectionMatrix);
      textureMatrix.set(
        0.5,
        0,
        0,
        0.5,
        0,
        0.5,
        0,
        0.5,
        0,
        0,
        0.5,
        0.5,
        0,
        0,
        0,
        1
      );
      textureMatrix.multiply(mirrorCamera.projectionMatrix);
      textureMatrix.multiply(mirrorCamera.matrixWorldInverse);
      mirrorPlane.setFromNormalAndCoplanarPoint(normal, mirrorWorldPosition);
      mirrorPlane.applyMatrix4(mirrorCamera.matrixWorldInverse);
      clipPlane.set(mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant);
      const projectionMatrix = mirrorCamera.projectionMatrix;
      q2.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0];
      q2.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5];
      q2.z = -1;
      q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14];
      clipPlane.multiplyScalar(2 / clipPlane.dot(q2));
      projectionMatrix.elements[2] = clipPlane.x;
      projectionMatrix.elements[6] = clipPlane.y;
      projectionMatrix.elements[10] = clipPlane.z + 1 - clipBias;
      projectionMatrix.elements[14] = clipPlane.w;
      eye.setFromMatrixPosition(camera.matrixWorld);
      const currentRenderTarget = renderer2.getRenderTarget();
      const currentXrEnabled = renderer2.xr.enabled;
      const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate;
      scope.visible = false;
      renderer2.xr.enabled = false;
      renderer2.shadowMap.autoUpdate = false;
      renderer2.setRenderTarget(renderTarget);
      renderer2.state.buffers.depth.setMask(true);
      if (renderer2.autoClear === false) renderer2.clear();
      renderer2.render(scene, mirrorCamera);
      scope.visible = true;
      renderer2.xr.enabled = currentXrEnabled;
      renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate;
      renderer2.setRenderTarget(currentRenderTarget);
      const viewport = camera.viewport;
      if (viewport !== void 0) {
        renderer2.state.viewport(viewport);
      }
    };
  }
};

// node_modules/three/examples/jsm/objects/Water2.js
var Water2 = class _Water extends Mesh {
  /**
   * Constructs a new water instance.
   *
   * @param {BufferGeometry} geometry - The water's geometry.
   * @param {module:Water2~Options} [options] - The configuration options.
   */
  constructor(geometry, options = {}) {
    super(geometry);
    this.isWater = true;
    this.type = "Water";
    const scope = this;
    const color = options.color !== void 0 ? new Color(options.color) : new Color(16777215);
    const textureWidth = options.textureWidth !== void 0 ? options.textureWidth : 512;
    const textureHeight = options.textureHeight !== void 0 ? options.textureHeight : 512;
    const clipBias = options.clipBias !== void 0 ? options.clipBias : 0;
    const flowDirection = options.flowDirection !== void 0 ? options.flowDirection : new Vector2(1, 0);
    const flowSpeed = options.flowSpeed !== void 0 ? options.flowSpeed : 0.03;
    const reflectivity = options.reflectivity !== void 0 ? options.reflectivity : 0.02;
    const scale2 = options.scale !== void 0 ? options.scale : 1;
    const shader = options.shader !== void 0 ? options.shader : _Water.WaterShader;
    const textureLoader = new TextureLoader();
    const flowMap = options.flowMap || void 0;
    const normalMap0 = options.normalMap0 || textureLoader.load("textures/water/Water_1_M_Normal.jpg");
    const normalMap1 = options.normalMap1 || textureLoader.load("textures/water/Water_2_M_Normal.jpg");
    const cycle = 0.15;
    const halfCycle = cycle * 0.5;
    const textureMatrix = new Matrix4();
    const clock = new Clock();
    if (Reflector === void 0) {
      console.error("THREE.Water: Required component Reflector not found.");
      return;
    }
    if (Refractor === void 0) {
      console.error("THREE.Water: Required component Refractor not found.");
      return;
    }
    const reflector = new Reflector(geometry, {
      textureWidth,
      textureHeight,
      clipBias
    });
    const refractor = new Refractor(geometry, {
      textureWidth,
      textureHeight,
      clipBias
    });
    reflector.matrixAutoUpdate = false;
    refractor.matrixAutoUpdate = false;
    this.material = new ShaderMaterial({
      name: shader.name,
      uniforms: UniformsUtils.merge([
        UniformsLib["fog"],
        shader.uniforms
      ]),
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader,
      transparent: true,
      fog: true
    });
    if (flowMap !== void 0) {
      this.material.defines.USE_FLOWMAP = "";
      this.material.uniforms["tFlowMap"] = {
        type: "t",
        value: flowMap
      };
    } else {
      this.material.uniforms["flowDirection"] = {
        type: "v2",
        value: flowDirection
      };
    }
    normalMap0.wrapS = normalMap0.wrapT = RepeatWrapping;
    normalMap1.wrapS = normalMap1.wrapT = RepeatWrapping;
    this.material.uniforms["tReflectionMap"].value = reflector.getRenderTarget().texture;
    this.material.uniforms["tRefractionMap"].value = refractor.getRenderTarget().texture;
    this.material.uniforms["tNormalMap0"].value = normalMap0;
    this.material.uniforms["tNormalMap1"].value = normalMap1;
    this.material.uniforms["color"].value = color;
    this.material.uniforms["reflectivity"].value = reflectivity;
    this.material.uniforms["textureMatrix"].value = textureMatrix;
    this.material.uniforms["config"].value.x = 0;
    this.material.uniforms["config"].value.y = halfCycle;
    this.material.uniforms["config"].value.z = halfCycle;
    this.material.uniforms["config"].value.w = scale2;
    function updateTextureMatrix(camera) {
      textureMatrix.set(
        0.5,
        0,
        0,
        0.5,
        0,
        0.5,
        0,
        0.5,
        0,
        0,
        0.5,
        0.5,
        0,
        0,
        0,
        1
      );
      textureMatrix.multiply(camera.projectionMatrix);
      textureMatrix.multiply(camera.matrixWorldInverse);
      textureMatrix.multiply(scope.matrixWorld);
    }
    function updateFlow() {
      const delta = clock.getDelta();
      const config = scope.material.uniforms["config"];
      config.value.x += flowSpeed * delta;
      config.value.y = config.value.x + halfCycle;
      if (config.value.x >= cycle) {
        config.value.x = 0;
        config.value.y = halfCycle;
      } else if (config.value.y >= cycle) {
        config.value.y = config.value.y - cycle;
      }
    }
    this.onBeforeRender = function(renderer2, scene, camera) {
      updateTextureMatrix(camera);
      updateFlow();
      scope.visible = false;
      reflector.matrixWorld.copy(scope.matrixWorld);
      refractor.matrixWorld.copy(scope.matrixWorld);
      reflector.onBeforeRender(renderer2, scene, camera);
      refractor.onBeforeRender(renderer2, scene, camera);
      scope.visible = true;
    };
  }
};
Water2.WaterShader = {
  name: "WaterShader",
  uniforms: {
    "color": {
      type: "c",
      value: null
    },
    "reflectivity": {
      type: "f",
      value: 0
    },
    "tReflectionMap": {
      type: "t",
      value: null
    },
    "tRefractionMap": {
      type: "t",
      value: null
    },
    "tNormalMap0": {
      type: "t",
      value: null
    },
    "tNormalMap1": {
      type: "t",
      value: null
    },
    "textureMatrix": {
      type: "m4",
      value: null
    },
    "config": {
      type: "v4",
      value: new Vector4()
    }
  },
  vertexShader: (
    /* glsl */
    `

		#include <common>
		#include <fog_pars_vertex>
		#include <logdepthbuf_pars_vertex>

		uniform mat4 textureMatrix;

		varying vec4 vCoord;
		varying vec2 vUv;
		varying vec3 vToEye;

		void main() {

			vUv = uv;
			vCoord = textureMatrix * vec4( position, 1.0 );

			vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
			vToEye = cameraPosition - worldPosition.xyz;

			vec4 mvPosition =  viewMatrix * worldPosition; // used in fog_vertex
			gl_Position = projectionMatrix * mvPosition;

			#include <logdepthbuf_vertex>
			#include <fog_vertex>

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

		#include <common>
		#include <fog_pars_fragment>
		#include <logdepthbuf_pars_fragment>

		uniform sampler2D tReflectionMap;
		uniform sampler2D tRefractionMap;
		uniform sampler2D tNormalMap0;
		uniform sampler2D tNormalMap1;

		#ifdef USE_FLOWMAP
			uniform sampler2D tFlowMap;
		#else
			uniform vec2 flowDirection;
		#endif

		uniform vec3 color;
		uniform float reflectivity;
		uniform vec4 config;

		varying vec4 vCoord;
		varying vec2 vUv;
		varying vec3 vToEye;

		void main() {

			#include <logdepthbuf_fragment>

			float flowMapOffset0 = config.x;
			float flowMapOffset1 = config.y;
			float halfCycle = config.z;
			float scale = config.w;

			vec3 toEye = normalize( vToEye );

			// determine flow direction
			vec2 flow;
			#ifdef USE_FLOWMAP
				flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0;
			#else
				flow = flowDirection;
			#endif
			flow.x *= - 1.0;

			// sample normal maps (distort uvs with flowdata)
			vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 );
			vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 );

			// linear interpolate to get the final normal color
			float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle;
			vec4 normalColor = mix( normalColor0, normalColor1, flowLerp );

			// calculate normal vector
			vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b,  normalColor.g * 2.0 - 1.0 ) );

			// calculate the fresnel term to blend reflection and refraction maps
			float theta = max( dot( toEye, normal ), 0.0 );
			float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 );

			// calculate final uv coords
			vec3 coord = vCoord.xyz / vCoord.w;
			vec2 uv = coord.xy + coord.z * normal.xz * 0.05;

			vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) );
			vec4 refractColor = texture2D( tRefractionMap, uv );

			// multiply water color with the mix of both textures
			gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance );

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

		}`
  )
};

// node_modules/three/examples/jsm/physics/AmmoPhysics.js
async function AmmoPhysics() {
  if ("Ammo" in window === false) {
    console.error("AmmoPhysics: Couldn't find Ammo.js");
    return;
  }
  const AmmoLib = await Ammo();
  const frameRate2 = 60;
  const collisionConfiguration = new AmmoLib.btDefaultCollisionConfiguration();
  const dispatcher = new AmmoLib.btCollisionDispatcher(collisionConfiguration);
  const broadphase = new AmmoLib.btDbvtBroadphase();
  const solver = new AmmoLib.btSequentialImpulseConstraintSolver();
  const world = new AmmoLib.btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
  world.setGravity(new AmmoLib.btVector3(0, -9.8, 0));
  const worldTransform = new AmmoLib.btTransform();
  function getShape2(geometry) {
    const parameters = geometry.parameters;
    if (geometry.type === "BoxGeometry") {
      const sx = parameters.width !== void 0 ? parameters.width / 2 : 0.5;
      const sy = parameters.height !== void 0 ? parameters.height / 2 : 0.5;
      const sz = parameters.depth !== void 0 ? parameters.depth / 2 : 0.5;
      const shape = new AmmoLib.btBoxShape(new AmmoLib.btVector3(sx, sy, sz));
      shape.setMargin(0.05);
      return shape;
    } else if (geometry.type === "SphereGeometry" || geometry.type === "IcosahedronGeometry") {
      const radius = parameters.radius !== void 0 ? parameters.radius : 1;
      const shape = new AmmoLib.btSphereShape(radius);
      shape.setMargin(0.05);
      return shape;
    }
    return null;
  }
  const meshes = [];
  const meshMap = /* @__PURE__ */ new WeakMap();
  function addScene(scene) {
    scene.traverse(function(child) {
      if (child.isMesh) {
        const physics = child.userData.physics;
        if (physics) {
          addMesh(child, physics.mass);
        }
      }
    });
  }
  function addMesh(mesh, mass = 0) {
    const shape = getShape2(mesh.geometry);
    if (shape !== null) {
      if (mesh.isInstancedMesh) {
        handleInstancedMesh(mesh, mass, shape);
      } else if (mesh.isMesh) {
        handleMesh(mesh, mass, shape);
      }
    }
  }
  function handleMesh(mesh, mass, shape) {
    const position2 = mesh.position;
    const quaternion = mesh.quaternion;
    const transform2 = new AmmoLib.btTransform();
    transform2.setIdentity();
    transform2.setOrigin(new AmmoLib.btVector3(position2.x, position2.y, position2.z));
    transform2.setRotation(new AmmoLib.btQuaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w));
    const motionState = new AmmoLib.btDefaultMotionState(transform2);
    const localInertia = new AmmoLib.btVector3(0, 0, 0);
    shape.calculateLocalInertia(mass, localInertia);
    const rbInfo = new AmmoLib.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia);
    const body = new AmmoLib.btRigidBody(rbInfo);
    world.addRigidBody(body);
    if (mass > 0) {
      meshes.push(mesh);
      meshMap.set(mesh, body);
    }
  }
  function handleInstancedMesh(mesh, mass, shape) {
    const array = mesh.instanceMatrix.array;
    const bodies = [];
    for (let i = 0; i < mesh.count; i++) {
      const index2 = i * 16;
      const transform2 = new AmmoLib.btTransform();
      transform2.setFromOpenGLMatrix(array.slice(index2, index2 + 16));
      const motionState = new AmmoLib.btDefaultMotionState(transform2);
      const localInertia = new AmmoLib.btVector3(0, 0, 0);
      shape.calculateLocalInertia(mass, localInertia);
      const rbInfo = new AmmoLib.btRigidBodyConstructionInfo(mass, motionState, shape, localInertia);
      const body = new AmmoLib.btRigidBody(rbInfo);
      world.addRigidBody(body);
      bodies.push(body);
    }
    if (mass > 0) {
      meshes.push(mesh);
      meshMap.set(mesh, bodies);
    }
  }
  function setMeshPosition(mesh, position2, index2 = 0) {
    if (mesh.isInstancedMesh) {
      const bodies = meshMap.get(mesh);
      const body = bodies[index2];
      body.setAngularVelocity(new AmmoLib.btVector3(0, 0, 0));
      body.setLinearVelocity(new AmmoLib.btVector3(0, 0, 0));
      worldTransform.setIdentity();
      worldTransform.setOrigin(new AmmoLib.btVector3(position2.x, position2.y, position2.z));
      body.setWorldTransform(worldTransform);
    } else if (mesh.isMesh) {
      const body = meshMap.get(mesh);
      body.setAngularVelocity(new AmmoLib.btVector3(0, 0, 0));
      body.setLinearVelocity(new AmmoLib.btVector3(0, 0, 0));
      worldTransform.setIdentity();
      worldTransform.setOrigin(new AmmoLib.btVector3(position2.x, position2.y, position2.z));
      body.setWorldTransform(worldTransform);
    }
  }
  let lastTime = 0;
  function step() {
    const time2 = performance.now();
    if (lastTime > 0) {
      const delta = (time2 - lastTime) / 1e3;
      world.stepSimulation(delta, 10);
      for (let i = 0, l2 = meshes.length; i < l2; i++) {
        const mesh = meshes[i];
        if (mesh.isInstancedMesh) {
          const array = mesh.instanceMatrix.array;
          const bodies = meshMap.get(mesh);
          for (let j2 = 0; j2 < bodies.length; j2++) {
            const body = bodies[j2];
            const motionState = body.getMotionState();
            motionState.getWorldTransform(worldTransform);
            const position2 = worldTransform.getOrigin();
            const quaternion = worldTransform.getRotation();
            compose(position2, quaternion, array, j2 * 16);
          }
          mesh.instanceMatrix.needsUpdate = true;
          mesh.computeBoundingSphere();
        } else if (mesh.isMesh) {
          const body = meshMap.get(mesh);
          const motionState = body.getMotionState();
          motionState.getWorldTransform(worldTransform);
          const position2 = worldTransform.getOrigin();
          const quaternion = worldTransform.getRotation();
          mesh.position.set(position2.x(), position2.y(), position2.z());
          mesh.quaternion.set(quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w());
        }
      }
    }
    lastTime = time2;
  }
  setInterval(step, 1e3 / frameRate2);
  return {
    /**
     * Adds the given scene to this physics simulation. Only meshes with a
     * `physics` object in their {@link Object3D#userData} field will be honored.
     * The object can be used to store the mass of the mesh. E.g.:
     * ```js
     * box.userData.physics = { mass: 1 };
     * ```
     *
     * @method
     * @name AmmoPhysics#addScene
     * @param {Object3D} scene The scene or any type of 3D object to add.
     */
    addScene,
    /**
     * Adds the given mesh to this physics simulation.
     *
     * @method
     * @name AmmoPhysics#addMesh
     * @param {Mesh} mesh The mesh to add.
     * @param {number} [mass=0] The mass in kg of the mesh.
     */
    addMesh,
    /**
     * Set the position of the given mesh which is part of the physics simulation. Calling this
     * method will reset the current simulated velocity of the mesh.
     *
     * @method
     * @name AmmoPhysics#setMeshPosition
     * @param {Mesh} mesh The mesh to update the position for.
     * @param {Vector3} position - The new position.
     * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
     */
    setMeshPosition
    // addCompoundMesh
  };
}
function compose(position2, quaternion, array, index2) {
  const x2 = quaternion.x(), y = quaternion.y(), z = quaternion.z(), w = quaternion.w();
  const x22 = x2 + x2, y2 = y + y, z2 = z + z;
  const xx = x2 * x22, xy = x2 * y2, xz = x2 * z2;
  const yy = y * y2, yz = y * z2, zz = z * z2;
  const wx = w * x22, wy = w * y2, wz = w * z2;
  array[index2 + 0] = 1 - (yy + zz);
  array[index2 + 1] = xy + wz;
  array[index2 + 2] = xz - wy;
  array[index2 + 3] = 0;
  array[index2 + 4] = xy - wz;
  array[index2 + 5] = 1 - (xx + zz);
  array[index2 + 6] = yz + wx;
  array[index2 + 7] = 0;
  array[index2 + 8] = xz + wy;
  array[index2 + 9] = yz - wx;
  array[index2 + 10] = 1 - (xx + yy);
  array[index2 + 11] = 0;
  array[index2 + 12] = position2.x();
  array[index2 + 13] = position2.y();
  array[index2 + 14] = position2.z();
  array[index2 + 15] = 1;
}

// node_modules/three/examples/jsm/physics/RapierPhysics.js
var RAPIER_PATH = "https://cdn.skypack.dev/@dimforge/rapier3d-compat@0.17.3";
var frameRate = 60;
var _scale2 = new Vector3(1, 1, 1);
var ZERO = new Vector3();
var RAPIER = null;
function getShape(geometry) {
  const parameters = geometry.parameters;
  if (geometry.type === "BoxGeometry") {
    const sx = parameters.width !== void 0 ? parameters.width / 2 : 0.5;
    const sy = parameters.height !== void 0 ? parameters.height / 2 : 0.5;
    const sz = parameters.depth !== void 0 ? parameters.depth / 2 : 0.5;
    return RAPIER.ColliderDesc.cuboid(sx, sy, sz);
  } else if (geometry.type === "SphereGeometry" || geometry.type === "IcosahedronGeometry") {
    const radius = parameters.radius !== void 0 ? parameters.radius : 1;
    return RAPIER.ColliderDesc.ball(radius);
  } else if (geometry.type === "CylinderGeometry") {
    const radius = parameters.radiusBottom !== void 0 ? parameters.radiusBottom : 0.5;
    const length2 = parameters.height !== void 0 ? parameters.height : 0.5;
    return RAPIER.ColliderDesc.cylinder(length2 / 2, radius);
  } else if (geometry.type === "CapsuleGeometry") {
    const radius = parameters.radius !== void 0 ? parameters.radius : 0.5;
    const length2 = parameters.height !== void 0 ? parameters.height : 0.5;
    return RAPIER.ColliderDesc.capsule(length2 / 2, radius);
  } else if (geometry.type === "BufferGeometry") {
    const vertices = [];
    const vertex = new Vector3();
    const position2 = geometry.getAttribute("position");
    for (let i = 0; i < position2.count; i++) {
      vertex.fromBufferAttribute(position2, i);
      vertices.push(vertex.x, vertex.y, vertex.z);
    }
    const indices = geometry.getIndex() === null ? Uint32Array.from(Array(parseInt(vertices.length / 3)).keys()) : geometry.getIndex().array;
    return RAPIER.ColliderDesc.trimesh(vertices, indices);
  }
  return null;
}
async function RapierPhysics() {
  if (RAPIER === null) {
    RAPIER = await import(`${RAPIER_PATH}`);
    await RAPIER.init();
  }
  const gravity = new Vector3(0, -9.81, 0);
  const world = new RAPIER.World(gravity);
  const meshes = [];
  const meshMap = /* @__PURE__ */ new WeakMap();
  const _vector6 = new Vector3();
  const _quaternion6 = new Quaternion();
  const _matrix7 = new Matrix4();
  function addScene(scene) {
    scene.traverse(function(child) {
      if (child.isMesh) {
        const physics = child.userData.physics;
        if (physics) {
          addMesh(child, physics.mass, physics.restitution);
        }
      }
    });
  }
  function addMesh(mesh, mass = 0, restitution = 0) {
    const shape = getShape(mesh.geometry);
    if (shape === null) return;
    shape.setMass(mass);
    shape.setRestitution(restitution);
    const { body, collider } = mesh.isInstancedMesh ? createInstancedBody(mesh, mass, shape) : createBody(mesh.position, mesh.quaternion, mass, shape);
    if (!mesh.userData.physics) mesh.userData.physics = {};
    mesh.userData.physics.body = body;
    mesh.userData.physics.collider = collider;
    if (mass > 0) {
      meshes.push(mesh);
      meshMap.set(mesh, { body, collider });
    }
  }
  function removeMesh(mesh) {
    const index2 = meshes.indexOf(mesh);
    if (index2 !== -1) {
      meshes.splice(index2, 1);
      meshMap.delete(mesh);
      if (!mesh.userData.physics) return;
      const body = mesh.userData.physics.body;
      const collider = mesh.userData.physics.collider;
      if (body) removeBody(body);
      if (collider) removeCollider(collider);
    }
  }
  function createInstancedBody(mesh, mass, shape) {
    const array = mesh.instanceMatrix.array;
    const bodies = [];
    const colliders = [];
    for (let i = 0; i < mesh.count; i++) {
      const position2 = _vector6.fromArray(array, i * 16 + 12);
      const { body, collider } = createBody(position2, null, mass, shape);
      bodies.push(body);
      colliders.push(collider);
    }
    return { body: bodies, collider: colliders };
  }
  function createBody(position2, quaternion, mass, shape) {
    const desc = mass > 0 ? RAPIER.RigidBodyDesc.dynamic() : RAPIER.RigidBodyDesc.fixed();
    desc.setTranslation(...position2);
    if (quaternion !== null) desc.setRotation(quaternion);
    const body = world.createRigidBody(desc);
    const collider = world.createCollider(shape, body);
    return { body, collider };
  }
  function removeBody(body) {
    if (Array.isArray(body)) {
      for (let i = 0; i < body.length; i++) {
        world.removeRigidBody(body[i]);
      }
    } else {
      world.removeRigidBody(body);
    }
  }
  function removeCollider(collider) {
    if (Array.isArray(collider)) {
      for (let i = 0; i < collider.length; i++) {
        world.removeCollider(collider[i]);
      }
    } else {
      world.removeCollider(collider);
    }
  }
  function setMeshPosition(mesh, position2, index2 = 0) {
    let { body } = meshMap.get(mesh);
    if (mesh.isInstancedMesh) {
      body = body[index2];
    }
    body.setAngvel(ZERO);
    body.setLinvel(ZERO);
    body.setTranslation(position2);
  }
  function setMeshVelocity(mesh, velocity2, index2 = 0) {
    let { body } = meshMap.get(mesh);
    if (mesh.isInstancedMesh) {
      body = body[index2];
    }
    body.setLinvel(velocity2);
  }
  function addHeightfield(mesh, width2, depth, heights, scale2) {
    const shape = RAPIER.ColliderDesc.heightfield(width2, depth, heights, scale2);
    const bodyDesc = RAPIER.RigidBodyDesc.fixed();
    bodyDesc.setTranslation(mesh.position.x, mesh.position.y, mesh.position.z);
    bodyDesc.setRotation(mesh.quaternion);
    const body = world.createRigidBody(bodyDesc);
    world.createCollider(shape, body);
    if (!mesh.userData.physics) mesh.userData.physics = {};
    mesh.userData.physics.body = body;
    return body;
  }
  const clock = new Clock();
  function step() {
    world.timestep = clock.getDelta();
    world.step();
    for (let i = 0, l2 = meshes.length; i < l2; i++) {
      const mesh = meshes[i];
      if (mesh.isInstancedMesh) {
        const array = mesh.instanceMatrix.array;
        const { body: bodies } = meshMap.get(mesh);
        for (let j2 = 0; j2 < bodies.length; j2++) {
          const body = bodies[j2];
          const position2 = body.translation();
          _quaternion6.copy(body.rotation());
          _matrix7.compose(position2, _quaternion6, _scale2).toArray(array, j2 * 16);
        }
        mesh.instanceMatrix.needsUpdate = true;
        mesh.computeBoundingSphere();
      } else {
        const { body } = meshMap.get(mesh);
        mesh.position.copy(body.translation());
        mesh.quaternion.copy(body.rotation());
      }
    }
  }
  setInterval(step, 1e3 / frameRate);
  return {
    RAPIER,
    world,
    /**
     * Adds the given scene to this physics simulation. Only meshes with a
     * `physics` object in their {@link Object3D#userData} field will be honored.
     * The object can be used to store the mass and restitution of the mesh. E.g.:
     * ```js
     * box.userData.physics = { mass: 1, restitution: 0 };
     * ```
     *
     * @method
     * @name RapierPhysics#addScene
     * @param {Object3D} scene The scene or any type of 3D object to add.
     */
    addScene,
    /**
     * Adds the given mesh to this physics simulation.
     *
     * @method
     * @name RapierPhysics#addMesh
     * @param {Mesh} mesh The mesh to add.
     * @param {number} [mass=0] The mass in kg of the mesh.
     * @param {number} [restitution=0] The restitution/friction of the mesh.
     */
    addMesh,
    /**
     * Removes the given mesh from this physics simulation.
     *
     * @method
     * @name RapierPhysics#removeMesh
     * @param {Mesh} mesh The mesh to remove.
     */
    removeMesh,
    /**
     * Set the position of the given mesh which is part of the physics simulation. Calling this
     * method will reset the current simulated velocity of the mesh.
     *
     * @method
     * @name RapierPhysics#setMeshPosition
     * @param {Mesh} mesh The mesh to update the position for.
     * @param {Vector3} position - The new position.
     * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
     */
    setMeshPosition,
    /**
     * Set the velocity of the given mesh which is part of the physics simulation.
     *
     * @method
     * @name RapierPhysics#setMeshVelocity
     * @param {Mesh} mesh The mesh to update the velocity for.
     * @param {Vector3} velocity - The new velocity.
     * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
     */
    setMeshVelocity,
    /**
     * Adds a heightfield terrain to the physics simulation.
     * 
     * @method
     * @name RapierPhysics#addHeightfield
     * @param {Mesh} mesh - The Three.js mesh representing the terrain.
     * @param {number} width - The number of vertices along the width (x-axis) of the heightfield.
     * @param {number} depth - The number of vertices along the depth (z-axis) of the heightfield.
     * @param {Float32Array} heights - Array of height values for each vertex in the heightfield.
     * @param {Object} scale - Scale factors for the heightfield dimensions.
     * @param {number} scale.x - Scale factor for width.
     * @param {number} scale.y - Scale factor for height.
     * @param {number} scale.z - Scale factor for depth.
     * @returns {RigidBody} The created Rapier rigid body for the heightfield.
     */
    addHeightfield
  };
}

// node_modules/three/examples/jsm/shaders/CopyShader.js
var CopyShader = {
  name: "CopyShader",
  uniforms: {
    "tDiffuse": { value: null },
    "opacity": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float opacity;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );
			gl_FragColor = opacity * texel;


		}`
  )
};

// node_modules/three/examples/jsm/shaders/AfterimageShader.js
var AfterimageShader = {
  name: "AfterimageShader",
  uniforms: {
    "damp": { value: 0.96 },
    "tOld": { value: null },
    "tNew": { value: null }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float damp;

		uniform sampler2D tOld;
		uniform sampler2D tNew;

		varying vec2 vUv;

		vec4 when_gt( vec4 x, float y ) {

			return max( sign( x - y ), 0.0 );

		}

		void main() {

			vec4 texelOld = texture2D( tOld, vUv );
			vec4 texelNew = texture2D( tNew, vUv );

			texelOld *= damp * when_gt( texelOld, 0.1 );

			gl_FragColor = max(texelNew, texelOld);

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/AfterimagePass.js
var AfterimagePass = class extends Pass {
  /**
   * Constructs a new after image pass.
   *
   * @param {number} [damp=0.96] - The damping intensity. A higher value means a stronger after image effect.
   */
  constructor(damp = 0.96) {
    super();
    this.uniforms = UniformsUtils.clone(AfterimageShader.uniforms);
    this.damp = damp;
    this.compFsMaterial = new ShaderMaterial({
      uniforms: this.uniforms,
      vertexShader: AfterimageShader.vertexShader,
      fragmentShader: AfterimageShader.fragmentShader
    });
    this.copyFsMaterial = new ShaderMaterial({
      uniforms: UniformsUtils.clone(CopyShader.uniforms),
      vertexShader: CopyShader.vertexShader,
      fragmentShader: CopyShader.fragmentShader,
      blending: NoBlending,
      depthTest: false,
      depthWrite: false
    });
    this._textureComp = new WebGLRenderTarget(window.innerWidth, window.innerHeight, {
      magFilter: NearestFilter,
      type: HalfFloatType
    });
    this._textureOld = new WebGLRenderTarget(window.innerWidth, window.innerHeight, {
      magFilter: NearestFilter,
      type: HalfFloatType
    });
    this._compFsQuad = new FullScreenQuad(this.compFsMaterial);
    this._copyFsQuad = new FullScreenQuad(this.copyFsMaterial);
  }
  /**
   * The damping intensity, from 0.0 to 1.0. A higher value means a stronger after image effect.
   *
   * @type {number}
   */
  get damp() {
    return this.uniforms["damp"].value;
  }
  set damp(value2) {
    this.uniforms["damp"].value = value2;
  }
  /**
   * Performs the after image pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this.uniforms["tOld"].value = this._textureOld.texture;
    this.uniforms["tNew"].value = readBuffer.texture;
    renderer2.setRenderTarget(this._textureComp);
    this._compFsQuad.render(renderer2);
    this._copyFsQuad.material.uniforms.tDiffuse.value = this._textureComp.texture;
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._copyFsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear();
      this._copyFsQuad.render(renderer2);
    }
    const temp = this._textureOld;
    this._textureOld = this._textureComp;
    this._textureComp = temp;
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this._textureComp.setSize(width2, height2);
    this._textureOld.setSize(width2, height2);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this._textureComp.dispose();
    this._textureOld.dispose();
    this.compFsMaterial.dispose();
    this.copyFsMaterial.dispose();
    this._compFsQuad.dispose();
    this._copyFsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/shaders/ConvolutionShader.js
var ConvolutionShader = {
  name: "ConvolutionShader",
  defines: {
    "KERNEL_SIZE_FLOAT": "25.0",
    "KERNEL_SIZE_INT": "25"
  },
  uniforms: {
    "tDiffuse": { value: null },
    "uImageIncrement": { value: new Vector2(1953125e-9, 0) },
    "cKernel": { value: [] }
  },
  vertexShader: (
    /* glsl */
    `

		uniform vec2 uImageIncrement;

		varying vec2 vUv;

		void main() {

			vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float cKernel[ KERNEL_SIZE_INT ];

		uniform sampler2D tDiffuse;
		uniform vec2 uImageIncrement;

		varying vec2 vUv;

		void main() {

			vec2 imageCoord = vUv;
			vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );

			for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {

				sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];
				imageCoord += uImageIncrement;

			}

			gl_FragColor = sum;

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/BloomPass.js
var BloomPass = class _BloomPass extends Pass {
  /**
   * Constructs a new Bloom pass.
   *
   * @param {number} [strength=1] - The Bloom strength.
   * @param {number} [kernelSize=25] - The kernel size.
   * @param {number} [sigma=4] - The sigma.
   */
  constructor(strength = 1, kernelSize = 25, sigma = 4) {
    super();
    this.combineUniforms = UniformsUtils.clone(CombineShader.uniforms);
    this.combineUniforms["strength"].value = strength;
    this.materialCombine = new ShaderMaterial({
      name: CombineShader.name,
      uniforms: this.combineUniforms,
      vertexShader: CombineShader.vertexShader,
      fragmentShader: CombineShader.fragmentShader,
      blending: AdditiveBlending,
      transparent: true
    });
    const convolutionShader = ConvolutionShader;
    this.convolutionUniforms = UniformsUtils.clone(convolutionShader.uniforms);
    this.convolutionUniforms["uImageIncrement"].value = _BloomPass.blurX;
    this.convolutionUniforms["cKernel"].value = buildKernel(sigma);
    this.materialConvolution = new ShaderMaterial({
      name: convolutionShader.name,
      uniforms: this.convolutionUniforms,
      vertexShader: convolutionShader.vertexShader,
      fragmentShader: convolutionShader.fragmentShader,
      defines: {
        "KERNEL_SIZE_FLOAT": kernelSize.toFixed(1),
        "KERNEL_SIZE_INT": kernelSize.toFixed(0)
      }
    });
    this.needsSwap = false;
    this._renderTargetX = new WebGLRenderTarget(1, 1, { type: HalfFloatType });
    this._renderTargetX.texture.name = "BloomPass.x";
    this._renderTargetY = new WebGLRenderTarget(1, 1, { type: HalfFloatType });
    this._renderTargetY.texture.name = "BloomPass.y";
    this._fsQuad = new FullScreenQuad(null);
  }
  /**
   * Performs the Bloom pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) {
    if (maskActive) renderer2.state.buffers.stencil.setTest(false);
    this._fsQuad.material = this.materialConvolution;
    this.convolutionUniforms["tDiffuse"].value = readBuffer.texture;
    this.convolutionUniforms["uImageIncrement"].value = _BloomPass.blurX;
    renderer2.setRenderTarget(this._renderTargetX);
    renderer2.clear();
    this._fsQuad.render(renderer2);
    this.convolutionUniforms["tDiffuse"].value = this._renderTargetX.texture;
    this.convolutionUniforms["uImageIncrement"].value = _BloomPass.blurY;
    renderer2.setRenderTarget(this._renderTargetY);
    renderer2.clear();
    this._fsQuad.render(renderer2);
    this._fsQuad.material = this.materialCombine;
    this.combineUniforms["tDiffuse"].value = this._renderTargetY.texture;
    if (maskActive) renderer2.state.buffers.stencil.setTest(true);
    renderer2.setRenderTarget(readBuffer);
    if (this.clear) renderer2.clear();
    this._fsQuad.render(renderer2);
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this._renderTargetX.setSize(width2, height2);
    this._renderTargetY.setSize(width2, height2);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this._renderTargetX.dispose();
    this._renderTargetY.dispose();
    this.materialCombine.dispose();
    this.materialConvolution.dispose();
    this._fsQuad.dispose();
  }
};
var CombineShader = {
  name: "CombineShader",
  uniforms: {
    "tDiffuse": { value: null },
    "strength": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float strength;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );
			gl_FragColor = strength * texel;

		}`
  )
};
BloomPass.blurX = new Vector2(1953125e-9, 0);
BloomPass.blurY = new Vector2(0, 1953125e-9);
function gauss(x2, sigma) {
  return Math.exp(-(x2 * x2) / (2 * sigma * sigma));
}
function buildKernel(sigma) {
  const kMaxKernelSize = 25;
  let kernelSize = 2 * Math.ceil(sigma * 3) + 1;
  if (kernelSize > kMaxKernelSize) kernelSize = kMaxKernelSize;
  const halfWidth = (kernelSize - 1) * 0.5;
  const values2 = new Array(kernelSize);
  let sum2 = 0;
  for (let i = 0; i < kernelSize; ++i) {
    values2[i] = gauss(i - halfWidth, sigma);
    sum2 += values2[i];
  }
  for (let i = 0; i < kernelSize; ++i) values2[i] /= sum2;
  return values2;
}

// node_modules/three/examples/jsm/shaders/BokehShader.js
var BokehShader = {
  name: "BokehShader",
  defines: {
    "DEPTH_PACKING": 1,
    "PERSPECTIVE_CAMERA": 1
  },
  uniforms: {
    "tColor": { value: null },
    "tDepth": { value: null },
    "focus": { value: 1 },
    "aspect": { value: 1 },
    "aperture": { value: 0.025 },
    "maxblur": { value: 0.01 },
    "nearClip": { value: 1 },
    "farClip": { value: 1e3 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		#include <common>

		varying vec2 vUv;

		uniform sampler2D tColor;
		uniform sampler2D tDepth;

		uniform float maxblur; // max blur amount
		uniform float aperture; // aperture - bigger values for shallower depth of field

		uniform float nearClip;
		uniform float farClip;

		uniform float focus;
		uniform float aspect;

		#include <packing>

		float getDepth( const in vec2 screenPosition ) {
			#if DEPTH_PACKING == 1
			return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );
			#else
			return texture2D( tDepth, screenPosition ).x;
			#endif
		}

		float getViewZ( const in float depth ) {
			#if PERSPECTIVE_CAMERA == 1
			return perspectiveDepthToViewZ( depth, nearClip, farClip );
			#else
			return orthographicDepthToViewZ( depth, nearClip, farClip );
			#endif
		}


		void main() {

			vec2 aspectcorrect = vec2( 1.0, aspect );

			float viewZ = getViewZ( getDepth( vUv ) );

			float factor = ( focus + viewZ ); // viewZ is <= 0, so this is a difference equation

			vec2 dofblur = vec2 ( clamp( factor * aperture, -maxblur, maxblur ) );

			vec2 dofblur9 = dofblur * 0.9;
			vec2 dofblur7 = dofblur * 0.7;
			vec2 dofblur4 = dofblur * 0.4;

			vec4 col = vec4( 0.0 );

			col += texture2D( tColor, vUv.xy );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.0,   0.4  ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.15,  0.37 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.29,  0.29 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.37,  0.15 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.40,  0.0  ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.37, -0.15 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.29, -0.29 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.0,  -0.4  ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.15,  0.37 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.29,  0.29 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.37,  0.15 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.4,   0.0  ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.15, -0.37 ) * aspectcorrect ) * dofblur );

			col += texture2D( tColor, vUv.xy + ( vec2(  0.15,  0.37 ) * aspectcorrect ) * dofblur9 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.37,  0.15 ) * aspectcorrect ) * dofblur9 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.37, -0.15 ) * aspectcorrect ) * dofblur9 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.15, -0.37 ) * aspectcorrect ) * dofblur9 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.15,  0.37 ) * aspectcorrect ) * dofblur9 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.37,  0.15 ) * aspectcorrect ) * dofblur9 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.37, -0.15 ) * aspectcorrect ) * dofblur9 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.15, -0.37 ) * aspectcorrect ) * dofblur9 );

			col += texture2D( tColor, vUv.xy + ( vec2(  0.29,  0.29 ) * aspectcorrect ) * dofblur7 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.40,  0.0  ) * aspectcorrect ) * dofblur7 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.29, -0.29 ) * aspectcorrect ) * dofblur7 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.0,  -0.4  ) * aspectcorrect ) * dofblur7 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.29,  0.29 ) * aspectcorrect ) * dofblur7 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.4,   0.0  ) * aspectcorrect ) * dofblur7 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur7 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.0,   0.4  ) * aspectcorrect ) * dofblur7 );

			col += texture2D( tColor, vUv.xy + ( vec2(  0.29,  0.29 ) * aspectcorrect ) * dofblur4 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.4,   0.0  ) * aspectcorrect ) * dofblur4 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.29, -0.29 ) * aspectcorrect ) * dofblur4 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.0,  -0.4  ) * aspectcorrect ) * dofblur4 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.29,  0.29 ) * aspectcorrect ) * dofblur4 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.4,   0.0  ) * aspectcorrect ) * dofblur4 );
			col += texture2D( tColor, vUv.xy + ( vec2( -0.29, -0.29 ) * aspectcorrect ) * dofblur4 );
			col += texture2D( tColor, vUv.xy + ( vec2(  0.0,   0.4  ) * aspectcorrect ) * dofblur4 );

			gl_FragColor = col / 41.0;
			gl_FragColor.a = 1.0;

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/BokehPass.js
var BokehPass = class extends Pass {
  /**
   * Constructs a new Bokeh pass.
   *
   * @param {Scene} scene - The scene to render the DOF for.
   * @param {Camera} camera - The camera.
   * @param {BokehPass~Options} params - The pass options.
   */
  constructor(scene, camera, params) {
    super();
    this.scene = scene;
    this.camera = camera;
    const focus = params.focus !== void 0 ? params.focus : 1;
    const aperture = params.aperture !== void 0 ? params.aperture : 0.025;
    const maxblur = params.maxblur !== void 0 ? params.maxblur : 1;
    this._renderTargetDepth = new WebGLRenderTarget(1, 1, {
      // will be resized later
      minFilter: NearestFilter,
      magFilter: NearestFilter,
      type: HalfFloatType
    });
    this._renderTargetDepth.texture.name = "BokehPass.depth";
    this._materialDepth = new MeshDepthMaterial();
    this._materialDepth.depthPacking = RGBADepthPacking;
    this._materialDepth.blending = NoBlending;
    const bokehUniforms = UniformsUtils.clone(BokehShader.uniforms);
    bokehUniforms["tDepth"].value = this._renderTargetDepth.texture;
    bokehUniforms["focus"].value = focus;
    bokehUniforms["aspect"].value = camera.aspect;
    bokehUniforms["aperture"].value = aperture;
    bokehUniforms["maxblur"].value = maxblur;
    bokehUniforms["nearClip"].value = camera.near;
    bokehUniforms["farClip"].value = camera.far;
    this.materialBokeh = new ShaderMaterial({
      defines: Object.assign({}, BokehShader.defines),
      uniforms: bokehUniforms,
      vertexShader: BokehShader.vertexShader,
      fragmentShader: BokehShader.fragmentShader
    });
    this.uniforms = bokehUniforms;
    this._fsQuad = new FullScreenQuad(this.materialBokeh);
    this._oldClearColor = new Color();
  }
  /**
   * Performs the Bokeh pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this.scene.overrideMaterial = this._materialDepth;
    renderer2.getClearColor(this._oldClearColor);
    const oldClearAlpha = renderer2.getClearAlpha();
    const oldAutoClear = renderer2.autoClear;
    renderer2.autoClear = false;
    renderer2.setClearColor(16777215);
    renderer2.setClearAlpha(1);
    renderer2.setRenderTarget(this._renderTargetDepth);
    renderer2.clear();
    renderer2.render(this.scene, this.camera);
    this.uniforms["tColor"].value = readBuffer.texture;
    this.uniforms["nearClip"].value = this.camera.near;
    this.uniforms["farClip"].value = this.camera.far;
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      renderer2.clear();
      this._fsQuad.render(renderer2);
    }
    this.scene.overrideMaterial = null;
    renderer2.setClearColor(this._oldClearColor);
    renderer2.setClearAlpha(oldClearAlpha);
    renderer2.autoClear = oldAutoClear;
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this.materialBokeh.uniforms["aspect"].value = width2 / height2;
    this._renderTargetDepth.setSize(width2, height2);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this._renderTargetDepth.dispose();
    this._materialDepth.dispose();
    this.materialBokeh.dispose();
    this._fsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/postprocessing/ClearPass.js
var ClearPass = class extends Pass {
  /**
   * Constructs a new clear pass.
   *
   * @param {(number|Color|string)} [clearColor=0x000000] - The clear color.
   * @param {number} [clearAlpha=0] - The clear alpha.
   */
  constructor(clearColor = 0, clearAlpha = 0) {
    super();
    this.needsSwap = false;
    this.clearColor = clearColor;
    this.clearAlpha = clearAlpha;
    this._oldClearColor = new Color();
  }
  /**
   * Performs the clear operation. This affects the current read or the default framebuffer.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    let oldClearAlpha;
    if (this.clearColor) {
      renderer2.getClearColor(this._oldClearColor);
      oldClearAlpha = renderer2.getClearAlpha();
      renderer2.setClearColor(this.clearColor, this.clearAlpha);
    }
    renderer2.setRenderTarget(this.renderToScreen ? null : readBuffer);
    renderer2.clear();
    if (this.clearColor) {
      renderer2.setClearColor(this._oldClearColor, oldClearAlpha);
    }
  }
};

// node_modules/three/examples/jsm/postprocessing/CubeTexturePass.js
var CubeTexturePass = class extends Pass {
  /**
   * Constructs a new cube texture pass.
   *
   * @param {PerspectiveCamera} camera - The camera.
   * @param {CubeTexture} tCube - The cube texture to render.
   * @param {number} [opacity=1] - The opacity.
   */
  constructor(camera, tCube, opacity = 1) {
    super();
    this.camera = camera;
    this.tCube = tCube;
    this.opacity = opacity;
    this.needsSwap = false;
    const cubeShader = ShaderLib["cube"];
    this._cubeMesh = new Mesh(
      new BoxGeometry(10, 10, 10),
      new ShaderMaterial({
        uniforms: UniformsUtils.clone(cubeShader.uniforms),
        vertexShader: cubeShader.vertexShader,
        fragmentShader: cubeShader.fragmentShader,
        depthTest: false,
        depthWrite: false,
        side: BackSide
      })
    );
    Object.defineProperty(this._cubeMesh.material, "envMap", {
      get: function() {
        return this.uniforms.tCube.value;
      }
    });
    this._cubeScene = new Scene();
    this._cubeCamera = new PerspectiveCamera();
    this._cubeScene.add(this._cubeMesh);
  }
  /**
   * Performs the cube texture pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    const oldAutoClear = renderer2.autoClear;
    renderer2.autoClear = false;
    this._cubeCamera.projectionMatrix.copy(this.camera.projectionMatrix);
    this._cubeCamera.quaternion.setFromRotationMatrix(this.camera.matrixWorld);
    this._cubeMesh.material.uniforms.tCube.value = this.tCube;
    this._cubeMesh.material.uniforms.tFlip.value = this.tCube.isCubeTexture && this.tCube.isRenderTargetTexture === false ? -1 : 1;
    this._cubeMesh.material.uniforms.opacity.value = this.opacity;
    this._cubeMesh.material.transparent = this.opacity < 1;
    renderer2.setRenderTarget(this.renderToScreen ? null : readBuffer);
    if (this.clear) renderer2.clear();
    renderer2.render(this._cubeScene, this._cubeCamera);
    renderer2.autoClear = oldAutoClear;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this._cubeMesh.geometry.dispose();
    this._cubeMesh.material.dispose();
  }
};

// node_modules/three/examples/jsm/shaders/DotScreenShader.js
var DotScreenShader = {
  name: "DotScreenShader",
  uniforms: {
    "tDiffuse": { value: null },
    "tSize": { value: new Vector2(256, 256) },
    "center": { value: new Vector2(0.5, 0.5) },
    "angle": { value: 1.57 },
    "scale": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform vec2 center;
		uniform float angle;
		uniform float scale;
		uniform vec2 tSize;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		float pattern() {

			float s = sin( angle ), c = cos( angle );

			vec2 tex = vUv * tSize - center;
			vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale;

			return ( sin( point.x ) * sin( point.y ) ) * 4.0;

		}

		void main() {

			vec4 color = texture2D( tDiffuse, vUv );

			float average = ( color.r + color.g + color.b ) / 3.0;

			gl_FragColor = vec4( vec3( average * 10.0 - 5.0 + pattern() ), color.a );

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/DotScreenPass.js
var DotScreenPass = class extends Pass {
  /**
   * Constructs a new dot screen pass.
   *
   * @param {Vector2} center - The center point.
   * @param {number} angle - The rotation of the effect in radians.
   * @param {number} scale - The scale of the effect. A higher value means smaller dots.
   */
  constructor(center, angle, scale2) {
    super();
    this.uniforms = UniformsUtils.clone(DotScreenShader.uniforms);
    if (center !== void 0) this.uniforms["center"].value.copy(center);
    if (angle !== void 0) this.uniforms["angle"].value = angle;
    if (scale2 !== void 0) this.uniforms["scale"].value = scale2;
    this.material = new ShaderMaterial({
      name: DotScreenShader.name,
      uniforms: this.uniforms,
      vertexShader: DotScreenShader.vertexShader,
      fragmentShader: DotScreenShader.fragmentShader
    });
    this._fsQuad = new FullScreenQuad(this.material);
  }
  /**
   * Performs the dot screen pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this.uniforms["tDiffuse"].value = readBuffer.texture;
    this.uniforms["tSize"].value.set(readBuffer.width, readBuffer.height);
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear();
      this._fsQuad.render(renderer2);
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.material.dispose();
    this._fsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/postprocessing/ShaderPass.js
var ShaderPass = class extends Pass {
  /**
   * Constructs a new shader pass.
   *
   * @param {Object|ShaderMaterial} [shader] - A shader object holding vertex and fragment shader as well as
   * defines and uniforms. It's also valid to pass a custom shader material.
   * @param {string} [textureID='tDiffuse'] - The name of the texture uniform that should sample
   * the read buffer.
   */
  constructor(shader, textureID = "tDiffuse") {
    super();
    this.textureID = textureID;
    this.uniforms = null;
    this.material = null;
    if (shader instanceof ShaderMaterial) {
      this.uniforms = shader.uniforms;
      this.material = shader;
    } else if (shader) {
      this.uniforms = UniformsUtils.clone(shader.uniforms);
      this.material = new ShaderMaterial({
        name: shader.name !== void 0 ? shader.name : "unspecified",
        defines: Object.assign({}, shader.defines),
        uniforms: this.uniforms,
        vertexShader: shader.vertexShader,
        fragmentShader: shader.fragmentShader
      });
    }
    this._fsQuad = new FullScreenQuad(this.material);
  }
  /**
   * Performs the shader pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    if (this.uniforms[this.textureID]) {
      this.uniforms[this.textureID].value = readBuffer.texture;
    }
    this._fsQuad.material = this.material;
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil);
      this._fsQuad.render(renderer2);
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.material.dispose();
    this._fsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/postprocessing/MaskPass.js
var MaskPass = class extends Pass {
  /**
   * Constructs a new mask pass.
   *
   * @param {Scene} scene - The 3D objects in this scene will define the mask.
   * @param {Camera} camera - The camera.
   */
  constructor(scene, camera) {
    super();
    this.scene = scene;
    this.camera = camera;
    this.clear = true;
    this.needsSwap = false;
    this.inverse = false;
  }
  /**
   * Performs a mask pass with the configured scene and camera.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    const context = renderer2.getContext();
    const state = renderer2.state;
    state.buffers.color.setMask(false);
    state.buffers.depth.setMask(false);
    state.buffers.color.setLocked(true);
    state.buffers.depth.setLocked(true);
    let writeValue, clearValue;
    if (this.inverse) {
      writeValue = 0;
      clearValue = 1;
    } else {
      writeValue = 1;
      clearValue = 0;
    }
    state.buffers.stencil.setTest(true);
    state.buffers.stencil.setOp(context.REPLACE, context.REPLACE, context.REPLACE);
    state.buffers.stencil.setFunc(context.ALWAYS, writeValue, 4294967295);
    state.buffers.stencil.setClear(clearValue);
    state.buffers.stencil.setLocked(true);
    renderer2.setRenderTarget(readBuffer);
    if (this.clear) renderer2.clear();
    renderer2.render(this.scene, this.camera);
    renderer2.setRenderTarget(writeBuffer);
    if (this.clear) renderer2.clear();
    renderer2.render(this.scene, this.camera);
    state.buffers.color.setLocked(false);
    state.buffers.depth.setLocked(false);
    state.buffers.color.setMask(true);
    state.buffers.depth.setMask(true);
    state.buffers.stencil.setLocked(false);
    state.buffers.stencil.setFunc(context.EQUAL, 1, 4294967295);
    state.buffers.stencil.setOp(context.KEEP, context.KEEP, context.KEEP);
    state.buffers.stencil.setLocked(true);
  }
};
var ClearMaskPass = class extends Pass {
  /**
   * Constructs a new clear mask pass.
   */
  constructor() {
    super();
    this.needsSwap = false;
  }
  /**
   * Performs the clear of the currently defined mask.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2) {
    renderer2.state.buffers.stencil.setLocked(false);
    renderer2.state.buffers.stencil.setTest(false);
  }
};

// node_modules/three/examples/jsm/postprocessing/EffectComposer.js
var EffectComposer = class {
  /**
   * Constructs a new effect composer.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} [renderTarget] - This render target and a clone will
   * be used as the internal read and write buffers. If not given, the composer creates
   * the buffers automatically.
   */
  constructor(renderer2, renderTarget) {
    this.renderer = renderer2;
    this._pixelRatio = renderer2.getPixelRatio();
    if (renderTarget === void 0) {
      const size2 = renderer2.getSize(new Vector2());
      this._width = size2.width;
      this._height = size2.height;
      renderTarget = new WebGLRenderTarget(this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType });
      renderTarget.texture.name = "EffectComposer.rt1";
    } else {
      this._width = renderTarget.width;
      this._height = renderTarget.height;
    }
    this.renderTarget1 = renderTarget;
    this.renderTarget2 = renderTarget.clone();
    this.renderTarget2.texture.name = "EffectComposer.rt2";
    this.writeBuffer = this.renderTarget1;
    this.readBuffer = this.renderTarget2;
    this.renderToScreen = true;
    this.passes = [];
    this.copyPass = new ShaderPass(CopyShader);
    this.copyPass.material.blending = NoBlending;
    this.clock = new Clock();
  }
  /**
   * Swaps the internal read/write buffers.
   */
  swapBuffers() {
    const tmp = this.readBuffer;
    this.readBuffer = this.writeBuffer;
    this.writeBuffer = tmp;
  }
  /**
   * Adds the given pass to the pass chain.
   *
   * @param {Pass} pass - The pass to add.
   */
  addPass(pass) {
    this.passes.push(pass);
    pass.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio);
  }
  /**
   * Inserts the given pass at a given index.
   *
   * @param {Pass} pass - The pass to insert.
   * @param {number} index - The index into the pass chain.
   */
  insertPass(pass, index2) {
    this.passes.splice(index2, 0, pass);
    pass.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio);
  }
  /**
   * Removes the given pass from the pass chain.
   *
   * @param {Pass} pass - The pass to remove.
   */
  removePass(pass) {
    const index2 = this.passes.indexOf(pass);
    if (index2 !== -1) {
      this.passes.splice(index2, 1);
    }
  }
  /**
   * Returns `true` if the pass for the given index is the last enabled pass in the pass chain.
   *
   * @param {number} passIndex - The pass index.
   * @return {boolean} Whether the pass for the given index is the last pass in the pass chain.
   */
  isLastEnabledPass(passIndex) {
    for (let i = passIndex + 1; i < this.passes.length; i++) {
      if (this.passes[i].enabled) {
        return false;
      }
    }
    return true;
  }
  /**
   * Executes all enabled post-processing passes in order to produce the final frame.
   *
   * @param {number} deltaTime - The delta time in seconds. If not given, the composer computes
   * its own time delta value.
   */
  render(deltaTime) {
    if (deltaTime === void 0) {
      deltaTime = this.clock.getDelta();
    }
    const currentRenderTarget = this.renderer.getRenderTarget();
    let maskActive = false;
    for (let i = 0, il = this.passes.length; i < il; i++) {
      const pass = this.passes[i];
      if (pass.enabled === false) continue;
      pass.renderToScreen = this.renderToScreen && this.isLastEnabledPass(i);
      pass.render(this.renderer, this.writeBuffer, this.readBuffer, deltaTime, maskActive);
      if (pass.needsSwap) {
        if (maskActive) {
          const context = this.renderer.getContext();
          const stencil = this.renderer.state.buffers.stencil;
          stencil.setFunc(context.NOTEQUAL, 1, 4294967295);
          this.copyPass.render(this.renderer, this.writeBuffer, this.readBuffer, deltaTime);
          stencil.setFunc(context.EQUAL, 1, 4294967295);
        }
        this.swapBuffers();
      }
      if (MaskPass !== void 0) {
        if (pass instanceof MaskPass) {
          maskActive = true;
        } else if (pass instanceof ClearMaskPass) {
          maskActive = false;
        }
      }
    }
    this.renderer.setRenderTarget(currentRenderTarget);
  }
  /**
   * Resets the internal state of the EffectComposer.
   *
   * @param {WebGLRenderTarget} [renderTarget] - This render target has the same purpose like
   * the one from the constructor. If set, it is used to setup the read and write buffers.
   */
  reset(renderTarget) {
    if (renderTarget === void 0) {
      const size2 = this.renderer.getSize(new Vector2());
      this._pixelRatio = this.renderer.getPixelRatio();
      this._width = size2.width;
      this._height = size2.height;
      renderTarget = this.renderTarget1.clone();
      renderTarget.setSize(this._width * this._pixelRatio, this._height * this._pixelRatio);
    }
    this.renderTarget1.dispose();
    this.renderTarget2.dispose();
    this.renderTarget1 = renderTarget;
    this.renderTarget2 = renderTarget.clone();
    this.writeBuffer = this.renderTarget1;
    this.readBuffer = this.renderTarget2;
  }
  /**
   * Resizes the internal read and write buffers as well as all passes. Similar to {@link WebGLRenderer#setSize},
   * this method honors the current pixel ration.
   *
   * @param {number} width - The width in logical pixels.
   * @param {number} height - The height in logical pixels.
   */
  setSize(width2, height2) {
    this._width = width2;
    this._height = height2;
    const effectiveWidth = this._width * this._pixelRatio;
    const effectiveHeight = this._height * this._pixelRatio;
    this.renderTarget1.setSize(effectiveWidth, effectiveHeight);
    this.renderTarget2.setSize(effectiveWidth, effectiveHeight);
    for (let i = 0; i < this.passes.length; i++) {
      this.passes[i].setSize(effectiveWidth, effectiveHeight);
    }
  }
  /**
   * Sets device pixel ratio. This is usually used for HiDPI device to prevent blurring output.
   * Setting the pixel ratio will automatically resize the composer.
   *
   * @param {number} pixelRatio - The pixel ratio to set.
   */
  setPixelRatio(pixelRatio) {
    this._pixelRatio = pixelRatio;
    this.setSize(this._width, this._height);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the composer is no longer used in your app.
   */
  dispose() {
    this.renderTarget1.dispose();
    this.renderTarget2.dispose();
    this.copyPass.dispose();
  }
};

// node_modules/three/examples/jsm/shaders/FilmShader.js
var FilmShader = {
  name: "FilmShader",
  uniforms: {
    "tDiffuse": { value: null },
    "time": { value: 0 },
    "intensity": { value: 0.5 },
    "grayscale": { value: false }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		#include <common>

		uniform float intensity;
		uniform bool grayscale;
		uniform float time;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 base = texture2D( tDiffuse, vUv );

			float noise = rand( fract( vUv + time ) );

			vec3 color = base.rgb + base.rgb * clamp( 0.1 + noise, 0.0, 1.0 );

			color = mix( base.rgb, color, intensity );

			if ( grayscale ) {

				color = vec3( luminance( color ) ); // assuming linear-srgb

			}

			gl_FragColor = vec4( color, base.a );

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/FilmPass.js
var FilmPass = class extends Pass {
  /**
   * Constructs a new film pass.
   *
   * @param {number} [intensity=0.5] - The grain intensity in the range `[0,1]` (0 = no effect, 1 = full effect).
   * @param {boolean} [grayscale=false] - Whether to apply a grayscale effect or not.
   */
  constructor(intensity = 0.5, grayscale = false) {
    super();
    const shader = FilmShader;
    this.uniforms = UniformsUtils.clone(shader.uniforms);
    this.material = new ShaderMaterial({
      name: shader.name,
      uniforms: this.uniforms,
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader
    });
    this.uniforms.intensity.value = intensity;
    this.uniforms.grayscale.value = grayscale;
    this._fsQuad = new FullScreenQuad(this.material);
  }
  /**
   * Performs the film pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer, deltaTime) {
    this.uniforms["tDiffuse"].value = readBuffer.texture;
    this.uniforms["time"].value += deltaTime;
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear();
      this._fsQuad.render(renderer2);
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.material.dispose();
    this._fsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/shaders/DigitalGlitch.js
var DigitalGlitch = {
  name: "DigitalGlitch",
  uniforms: {
    "tDiffuse": { value: null },
    //diffuse texture
    "tDisp": { value: null },
    //displacement texture for digital glitch squares
    "byp": { value: 0 },
    //apply the glitch ?
    "amount": { value: 0.08 },
    "angle": { value: 0.02 },
    "seed": { value: 0.02 },
    "seed_x": { value: 0.02 },
    //-1,1
    "seed_y": { value: 0.02 },
    //-1,1
    "distortion_x": { value: 0.5 },
    "distortion_y": { value: 0.6 },
    "col_s": { value: 0.05 }
  },
  vertexShader: (
    /* glsl */
    `

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

		uniform int byp; //should we apply the glitch ?

		uniform sampler2D tDiffuse;
		uniform sampler2D tDisp;

		uniform float amount;
		uniform float angle;
		uniform float seed;
		uniform float seed_x;
		uniform float seed_y;
		uniform float distortion_x;
		uniform float distortion_y;
		uniform float col_s;

		varying vec2 vUv;


		float rand(vec2 co){
			return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
		}

		void main() {
			if(byp<1) {
				vec2 p = vUv;
				float xs = floor(gl_FragCoord.x / 0.5);
				float ys = floor(gl_FragCoord.y / 0.5);
				//based on staffantans glitch shader for unity https://github.com/staffantan/unityglitch
				float disp = texture2D(tDisp, p*seed*seed).r;
				if(p.y<distortion_x+col_s && p.y>distortion_x-col_s*seed) {
					if(seed_x>0.){
						p.y = 1. - (p.y + distortion_y);
					}
					else {
						p.y = distortion_y;
					}
				}
				if(p.x<distortion_y+col_s && p.x>distortion_y-col_s*seed) {
					if(seed_y>0.){
						p.x=distortion_x;
					}
					else {
						p.x = 1. - (p.x + distortion_x);
					}
				}
				p.x+=disp*seed_x*(seed/5.);
				p.y+=disp*seed_y*(seed/5.);
				//base from RGB shift shader
				vec2 offset = amount * vec2( cos(angle), sin(angle));
				vec4 cr = texture2D(tDiffuse, p + offset);
				vec4 cga = texture2D(tDiffuse, p);
				vec4 cb = texture2D(tDiffuse, p - offset);
				gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a);
				//add noise
				vec4 snow = 200.*amount*vec4(rand(vec2(xs * seed,ys * seed*50.))*0.2);
				gl_FragColor = gl_FragColor+ snow;
			}
			else {
				gl_FragColor=texture2D (tDiffuse, vUv);
			}
		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/GlitchPass.js
var GlitchPass = class extends Pass {
  /**
   * Constructs a new glitch pass.
   *
   * @param {number} [dt_size=64] - The size of the displacement texture
   * for digital glitch squares.
   */
  constructor(dt_size = 64) {
    super();
    this.uniforms = UniformsUtils.clone(DigitalGlitch.uniforms);
    this.material = new ShaderMaterial({
      uniforms: this.uniforms,
      vertexShader: DigitalGlitch.vertexShader,
      fragmentShader: DigitalGlitch.fragmentShader
    });
    this.goWild = false;
    this._heightMap = this._generateHeightmap(dt_size);
    this.uniforms["tDisp"].value = this.heightMap;
    this._fsQuad = new FullScreenQuad(this.material);
    this._curF = 0;
    this._randX = 0;
    this._generateTrigger();
  }
  /**
   * Performs the glitch pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this.uniforms["tDiffuse"].value = readBuffer.texture;
    this.uniforms["seed"].value = Math.random();
    this.uniforms["byp"].value = 0;
    if (this._curF % this._randX == 0 || this.goWild == true) {
      this.uniforms["amount"].value = Math.random() / 30;
      this.uniforms["angle"].value = MathUtils.randFloat(-Math.PI, Math.PI);
      this.uniforms["seed_x"].value = MathUtils.randFloat(-1, 1);
      this.uniforms["seed_y"].value = MathUtils.randFloat(-1, 1);
      this.uniforms["distortion_x"].value = MathUtils.randFloat(0, 1);
      this.uniforms["distortion_y"].value = MathUtils.randFloat(0, 1);
      this._curF = 0;
      this._generateTrigger();
    } else if (this._curF % this._randX < this._randX / 5) {
      this.uniforms["amount"].value = Math.random() / 90;
      this.uniforms["angle"].value = MathUtils.randFloat(-Math.PI, Math.PI);
      this.uniforms["distortion_x"].value = MathUtils.randFloat(0, 1);
      this.uniforms["distortion_y"].value = MathUtils.randFloat(0, 1);
      this.uniforms["seed_x"].value = MathUtils.randFloat(-0.3, 0.3);
      this.uniforms["seed_y"].value = MathUtils.randFloat(-0.3, 0.3);
    } else if (this.goWild == false) {
      this.uniforms["byp"].value = 1;
    }
    this._curF++;
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear();
      this._fsQuad.render(renderer2);
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.material.dispose();
    this.heightMap.dispose();
    this._fsQuad.dispose();
  }
  // internals
  _generateTrigger() {
    this._randX = MathUtils.randInt(120, 240);
  }
  _generateHeightmap(dt_size) {
    const data_arr = new Float32Array(dt_size * dt_size);
    const length2 = dt_size * dt_size;
    for (let i = 0; i < length2; i++) {
      const val2 = MathUtils.randFloat(0, 1);
      data_arr[i] = val2;
    }
    const texture = new DataTexture(data_arr, dt_size, dt_size, RedFormat, FloatType);
    texture.needsUpdate = true;
    return texture;
  }
};

// node_modules/three/examples/jsm/shaders/GTAOShader.js
var GTAOShader = {
  name: "GTAOShader",
  defines: {
    PERSPECTIVE_CAMERA: 1,
    SAMPLES: 16,
    NORMAL_VECTOR_TYPE: 1,
    DEPTH_SWIZZLING: "x",
    SCREEN_SPACE_RADIUS: 0,
    SCREEN_SPACE_RADIUS_SCALE: 100,
    SCENE_CLIP_BOX: 0
  },
  uniforms: {
    tNormal: { value: null },
    tDepth: { value: null },
    tNoise: { value: null },
    resolution: { value: new Vector2() },
    cameraNear: { value: null },
    cameraFar: { value: null },
    cameraProjectionMatrix: { value: new Matrix4() },
    cameraProjectionMatrixInverse: { value: new Matrix4() },
    cameraWorldMatrix: { value: new Matrix4() },
    radius: { value: 0.25 },
    distanceExponent: { value: 1 },
    thickness: { value: 1 },
    distanceFallOff: { value: 1 },
    scale: { value: 1 },
    sceneBoxMin: { value: new Vector3(-1, -1, -1) },
    sceneBoxMax: { value: new Vector3(1, 1, 1) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {
			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`
  ),
  fragmentShader: (
    /* glsl */
    `
		varying vec2 vUv;
		uniform highp sampler2D tNormal;
		uniform highp sampler2D tDepth;
		uniform sampler2D tNoise;
		uniform vec2 resolution;
		uniform float cameraNear;
		uniform float cameraFar;
		uniform mat4 cameraProjectionMatrix;
		uniform mat4 cameraProjectionMatrixInverse;
		uniform mat4 cameraWorldMatrix;
		uniform float radius;
		uniform float distanceExponent;
		uniform float thickness;
		uniform float distanceFallOff;
		uniform float scale;
		#if SCENE_CLIP_BOX == 1
			uniform vec3 sceneBoxMin;
			uniform vec3 sceneBoxMax;
		#endif

		#include <common>
		#include <packing>

		#ifndef FRAGMENT_OUTPUT
		#define FRAGMENT_OUTPUT vec4(vec3(ao), 1.)
		#endif

		vec3 getViewPosition(const in vec2 screenPosition, const in float depth) {
			vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0);
			vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
			return viewSpacePosition.xyz / viewSpacePosition.w;
		}

		float getDepth(const vec2 uv) {
			return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING;
		}

		float fetchDepth(const ivec2 uv) {
			return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING;
		}

		float getViewZ(const in float depth) {
			#if PERSPECTIVE_CAMERA == 1
				return perspectiveDepthToViewZ(depth, cameraNear, cameraFar);
			#else
				return orthographicDepthToViewZ(depth, cameraNear, cameraFar);
			#endif
		}

		vec3 computeNormalFromDepth(const vec2 uv) {
			vec2 size = vec2(textureSize(tDepth, 0));
			ivec2 p = ivec2(uv * size);
			float c0 = fetchDepth(p);
			float l2 = fetchDepth(p - ivec2(2, 0));
			float l1 = fetchDepth(p - ivec2(1, 0));
			float r1 = fetchDepth(p + ivec2(1, 0));
			float r2 = fetchDepth(p + ivec2(2, 0));
			float b2 = fetchDepth(p - ivec2(0, 2));
			float b1 = fetchDepth(p - ivec2(0, 1));
			float t1 = fetchDepth(p + ivec2(0, 1));
			float t2 = fetchDepth(p + ivec2(0, 2));
			float dl = abs((2.0 * l1 - l2) - c0);
			float dr = abs((2.0 * r1 - r2) - c0);
			float db = abs((2.0 * b1 - b2) - c0);
			float dt = abs((2.0 * t1 - t2) - c0);
			vec3 ce = getViewPosition(uv, c0).xyz;
			vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
			vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
			return normalize(cross(dpdx, dpdy));
		}

		vec3 getViewNormal(const vec2 uv) {
			#if NORMAL_VECTOR_TYPE == 2
				return normalize(textureLod(tNormal, uv, 0.).rgb);
			#elif NORMAL_VECTOR_TYPE == 1
				return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
			#else
				return computeNormalFromDepth(uv);
			#endif
		}

		vec3 getSceneUvAndDepth(vec3 sampleViewPos) {
			vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.);
			vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5;
			float sampleSceneDepth = getDepth(sampleUv);
			return vec3(sampleUv, sampleSceneDepth);
		}

		void main() {
			float depth = getDepth(vUv.xy);
			if (depth >= 1.0) {
				discard;
				return;
			}
			vec3 viewPos = getViewPosition(vUv, depth);
			vec3 viewNormal = getViewNormal(vUv);

			float radiusToUse = radius;
			float distanceFalloffToUse = thickness;
			#if SCREEN_SPACE_RADIUS == 1
				float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x;
				radiusToUse *= radiusScale;
				distanceFalloffToUse *= radiusScale;
			#endif

			#if SCENE_CLIP_BOX == 1
				vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz;
				float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax)));
				if (boxDistance > radiusToUse) {
					discard;
					return;
				}
			#endif

			vec2 noiseResolution = vec2(textureSize(tNoise, 0));
			vec2 noiseUv = vUv * resolution / noiseResolution;
			vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
			vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0;
			vec3 tangent = normalize(vec3(randomVec.xy, 0.));
			vec3 bitangent = vec3(-tangent.y, tangent.x, 0.);
			mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.));

			const int DIRECTIONS = SAMPLES < 30 ? 3 : 5;
			const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS;
			float ao = 0.0;
			for (int i = 0; i < DIRECTIONS; ++i) {

				float angle = float(i) / float(DIRECTIONS) * PI;
				vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w);
				sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz);

				vec3 viewDir = normalize(-viewPos.xyz);
				vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir));
				vec3 sliceTangent = cross(sliceBitangent, viewDir);
				vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent));

				vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent);
				vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice));

				for (int j = 0; j < STEPS; ++j) {
					vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent);

					vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset);
					vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
					vec3 viewDelta = sampleSceneViewPos - viewPos;
					if (abs(viewDelta.z) < thickness) {
						float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
						cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff));
					}

					sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset);
					sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
					viewDelta = sampleSceneViewPos - viewPos;
					if (abs(viewDelta.z) < thickness) {
						float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
						cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff));
					}
				}

				vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons);
				float nx = dot(normalInSlice, sliceTangent);
				float ny = dot(normalInSlice, viewDir);
				float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y);
				float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y);
				float occlusion = nx * nxb + ny * nyb;
				ao += occlusion;
			}

			ao = clamp(ao / float(DIRECTIONS), 0., 1.);
		#if SCENE_CLIP_BOX == 1
			ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance));
		#endif
			ao = pow(ao, scale);

			gl_FragColor = FRAGMENT_OUTPUT;
		}`
  )
};
var GTAODepthShader = {
  name: "GTAODepthShader",
  defines: {
    PERSPECTIVE_CAMERA: 1
  },
  uniforms: {
    tDepth: { value: null },
    cameraNear: { value: null },
    cameraFar: { value: null }
  },
  vertexShader: (
    /* glsl */
    `
		varying vec2 vUv;

		void main() {
			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`
  ),
  fragmentShader: (
    /* glsl */
    `
		uniform sampler2D tDepth;
		uniform float cameraNear;
		uniform float cameraFar;
		varying vec2 vUv;

		#include <packing>

		float getLinearDepth( const in vec2 screenPosition ) {
			#if PERSPECTIVE_CAMERA == 1
				float fragCoordZ = texture2D( tDepth, screenPosition ).x;
				float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
				return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
			#else
				return texture2D( tDepth, screenPosition ).x;
			#endif
		}

		void main() {
			float depth = getLinearDepth( vUv );
			gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );

		}`
  )
};
var GTAOBlendShader = {
  name: "GTAOBlendShader",
  uniforms: {
    tDiffuse: { value: null },
    intensity: { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `
		varying vec2 vUv;

		void main() {
			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`
  ),
  fragmentShader: (
    /* glsl */
    `
		uniform float intensity;
		uniform sampler2D tDiffuse;
		varying vec2 vUv;

		void main() {
			vec4 texel = texture2D( tDiffuse, vUv );
			gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a);
		}`
  )
};
function generateMagicSquareNoise(size2 = 5) {
  const noiseSize = Math.floor(size2) % 2 === 0 ? Math.floor(size2) + 1 : Math.floor(size2);
  const magicSquare = generateMagicSquare(noiseSize);
  const noiseSquareSize = magicSquare.length;
  const data2 = new Uint8Array(noiseSquareSize * 4);
  for (let inx = 0; inx < noiseSquareSize; ++inx) {
    const iAng = magicSquare[inx];
    const angle = 2 * Math.PI * iAng / noiseSquareSize;
    const randomVec = new Vector3(
      Math.cos(angle),
      Math.sin(angle),
      0
    ).normalize();
    data2[inx * 4] = (randomVec.x * 0.5 + 0.5) * 255;
    data2[inx * 4 + 1] = (randomVec.y * 0.5 + 0.5) * 255;
    data2[inx * 4 + 2] = 127;
    data2[inx * 4 + 3] = 255;
  }
  const noiseTexture = new DataTexture(data2, noiseSize, noiseSize);
  noiseTexture.wrapS = RepeatWrapping;
  noiseTexture.wrapT = RepeatWrapping;
  noiseTexture.needsUpdate = true;
  return noiseTexture;
}
function generateMagicSquare(size2) {
  const noiseSize = Math.floor(size2) % 2 === 0 ? Math.floor(size2) + 1 : Math.floor(size2);
  const noiseSquareSize = noiseSize * noiseSize;
  const magicSquare = Array(noiseSquareSize).fill(0);
  let i = Math.floor(noiseSize / 2);
  let j2 = noiseSize - 1;
  for (let num = 1; num <= noiseSquareSize; ) {
    if (i === -1 && j2 === noiseSize) {
      j2 = noiseSize - 2;
      i = 0;
    } else {
      if (j2 === noiseSize) {
        j2 = 0;
      }
      if (i < 0) {
        i = noiseSize - 1;
      }
    }
    if (magicSquare[i * noiseSize + j2] !== 0) {
      j2 -= 2;
      i++;
      continue;
    } else {
      magicSquare[i * noiseSize + j2] = num++;
    }
    j2++;
    i--;
  }
  return magicSquare;
}

// node_modules/three/examples/jsm/shaders/PoissonDenoiseShader.js
var PoissonDenoiseShader = {
  name: "PoissonDenoiseShader",
  defines: {
    "SAMPLES": 16,
    "SAMPLE_VECTORS": generatePdSamplePointInitializer(16, 2, 1),
    "NORMAL_VECTOR_TYPE": 1,
    "DEPTH_VALUE_SOURCE": 0
  },
  uniforms: {
    "tDiffuse": { value: null },
    "tNormal": { value: null },
    "tDepth": { value: null },
    "tNoise": { value: null },
    "resolution": { value: new Vector2() },
    "cameraProjectionMatrixInverse": { value: new Matrix4() },
    "lumaPhi": { value: 5 },
    "depthPhi": { value: 5 },
    "normalPhi": { value: 5 },
    "radius": { value: 4 },
    "index": { value: 0 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

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

		varying vec2 vUv;

		uniform sampler2D tDiffuse;
		uniform sampler2D tNormal;
		uniform sampler2D tDepth;
		uniform sampler2D tNoise;
		uniform vec2 resolution;
		uniform mat4 cameraProjectionMatrixInverse;
		uniform float lumaPhi;
		uniform float depthPhi;
		uniform float normalPhi;
		uniform float radius;
		uniform int index;

		#include <common>
		#include <packing>

		#ifndef SAMPLE_LUMINANCE
		#define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a)
		#endif

		#ifndef FRAGMENT_OUTPUT
		#define FRAGMENT_OUTPUT vec4(denoised, 1.)
		#endif

		float getLuminance(const in vec3 a) {
			return SAMPLE_LUMINANCE;
		}

		const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS;

		vec3 getViewPosition(const in vec2 screenPosition, const in float depth) {
			vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0);
			vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
			return viewSpacePosition.xyz / viewSpacePosition.w;
		}

		float getDepth(const vec2 uv) {
		#if DEPTH_VALUE_SOURCE == 1
			return textureLod(tDepth, uv.xy, 0.0).a;
		#else
			return textureLod(tDepth, uv.xy, 0.0).r;
		#endif
		}

		float fetchDepth(const ivec2 uv) {
			#if DEPTH_VALUE_SOURCE == 1
				return texelFetch(tDepth, uv.xy, 0).a;
			#else
				return texelFetch(tDepth, uv.xy, 0).r;
			#endif
		}

		vec3 computeNormalFromDepth(const vec2 uv) {
			vec2 size = vec2(textureSize(tDepth, 0));
			ivec2 p = ivec2(uv * size);
			float c0 = fetchDepth(p);
			float l2 = fetchDepth(p - ivec2(2, 0));
			float l1 = fetchDepth(p - ivec2(1, 0));
			float r1 = fetchDepth(p + ivec2(1, 0));
			float r2 = fetchDepth(p + ivec2(2, 0));
			float b2 = fetchDepth(p - ivec2(0, 2));
			float b1 = fetchDepth(p - ivec2(0, 1));
			float t1 = fetchDepth(p + ivec2(0, 1));
			float t2 = fetchDepth(p + ivec2(0, 2));
			float dl = abs((2.0 * l1 - l2) - c0);
			float dr = abs((2.0 * r1 - r2) - c0);
			float db = abs((2.0 * b1 - b2) - c0);
			float dt = abs((2.0 * t1 - t2) - c0);
			vec3 ce = getViewPosition(uv, c0).xyz;
			vec3 dpdx = (dl < dr) ?  ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz
									: -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
			vec3 dpdy = (db < dt) ?  ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz
									: -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
			return normalize(cross(dpdx, dpdy));
		}

		vec3 getViewNormal(const vec2 uv) {
		#if NORMAL_VECTOR_TYPE == 2
			return normalize(textureLod(tNormal, uv, 0.).rgb);
		#elif NORMAL_VECTOR_TYPE == 1
			return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
		#else
			return computeNormalFromDepth(uv);
		#endif
		}

		void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) {
			vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0);
			float sampleDepth = getDepth(sampleUv);
			vec3 sampleNormal = getViewNormal(sampleUv);
			vec3 neighborColor = sampleTexel.rgb;
			vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth);

			float normalDiff = dot(viewNormal, sampleNormal);
			float normalSimilarity = pow(max(normalDiff, 0.), normalPhi);
			float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center));
			float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0);
			float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal));
			float depthSimilarity = max(1. - depthDiff / depthPhi, 0.);
			float w = lumaSimilarity * depthSimilarity * normalSimilarity;

			denoised += w * neighborColor;
			totalWeight += w;
		}

		void main() {
			float depth = getDepth(vUv.xy);
			vec3 viewNormal = getViewNormal(vUv);
			if (depth == 1. || dot(viewNormal, viewNormal) == 0.) {
				discard;
				return;
			}
			vec4 texel = textureLod(tDiffuse, vUv, 0.0);
			vec3 center = texel.rgb;
			vec3 viewPos = getViewPosition(vUv, depth);

			vec2 noiseResolution = vec2(textureSize(tNoise, 0));
			vec2 noiseUv = vUv * resolution / noiseResolution;
			vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
      		vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI));
    		mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y);

			float totalWeight = 1.0;
			vec3 denoised = texel.rgb;
			for (int i = 0; i < SAMPLES; i++) {
				vec3 sampleDir = poissonDisk[i];
				vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution);
				vec2 sampleUv = vUv + offset;
				denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight);
			}

			if (totalWeight > 0.) {
				denoised /= totalWeight;
			}
			gl_FragColor = FRAGMENT_OUTPUT;
		}`
  )
};
function generatePdSamplePointInitializer(samples, rings, radiusExponent) {
  const poissonDisk = generateDenoiseSamples(
    samples,
    rings,
    radiusExponent
  );
  let glslCode = "vec3[SAMPLES](";
  for (let i = 0; i < samples; i++) {
    const sample = poissonDisk[i];
    glslCode += `vec3(${sample.x}, ${sample.y}, ${sample.z})${i < samples - 1 ? "," : ")"}`;
  }
  return glslCode;
}
function generateDenoiseSamples(numSamples, numRings, radiusExponent) {
  const samples = [];
  for (let i = 0; i < numSamples; i++) {
    const angle = 2 * Math.PI * numRings * i / numSamples;
    const radius = Math.pow(i / (numSamples - 1), radiusExponent);
    samples.push(new Vector3(Math.cos(angle), Math.sin(angle), radius));
  }
  return samples;
}

// node_modules/three/examples/jsm/postprocessing/GTAOPass.js
var GTAOPass = class _GTAOPass extends Pass {
  /**
   * Constructs a new GTAO pass.
   *
   * @param {Scene} scene - The scene to compute the AO for.
   * @param {Camera} camera - The camera.
   * @param {number} [width=512] - The width of the effect.
   * @param {number} [height=512] - The height of the effect.
   * @param {Object} [parameters] - The pass parameters.
   * @param {Object} [aoParameters] - The AO parameters.
   * @param {Object} [pdParameters] - The denoise parameters.
   */
  constructor(scene, camera, width2 = 512, height2 = 512, parameters, aoParameters, pdParameters) {
    super();
    this.width = width2;
    this.height = height2;
    this.clear = true;
    this.camera = camera;
    this.scene = scene;
    this.output = 0;
    this._renderGBuffer = true;
    this._visibilityCache = /* @__PURE__ */ new Map();
    this.blendIntensity = 1;
    this.pdRings = 2;
    this.pdRadiusExponent = 2;
    this.pdSamples = 16;
    this.gtaoNoiseTexture = generateMagicSquareNoise();
    this.pdNoiseTexture = this._generateNoise();
    this.gtaoRenderTarget = new WebGLRenderTarget(this.width, this.height, { type: HalfFloatType });
    this.pdRenderTarget = this.gtaoRenderTarget.clone();
    this.gtaoMaterial = new ShaderMaterial({
      defines: Object.assign({}, GTAOShader.defines),
      uniforms: UniformsUtils.clone(GTAOShader.uniforms),
      vertexShader: GTAOShader.vertexShader,
      fragmentShader: GTAOShader.fragmentShader,
      blending: NoBlending,
      depthTest: false,
      depthWrite: false
    });
    this.gtaoMaterial.defines.PERSPECTIVE_CAMERA = this.camera.isPerspectiveCamera ? 1 : 0;
    this.gtaoMaterial.uniforms.tNoise.value = this.gtaoNoiseTexture;
    this.gtaoMaterial.uniforms.resolution.value.set(this.width, this.height);
    this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near;
    this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far;
    this.normalMaterial = new MeshNormalMaterial();
    this.normalMaterial.blending = NoBlending;
    this.pdMaterial = new ShaderMaterial({
      defines: Object.assign({}, PoissonDenoiseShader.defines),
      uniforms: UniformsUtils.clone(PoissonDenoiseShader.uniforms),
      vertexShader: PoissonDenoiseShader.vertexShader,
      fragmentShader: PoissonDenoiseShader.fragmentShader,
      depthTest: false,
      depthWrite: false
    });
    this.pdMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture;
    this.pdMaterial.uniforms.tNoise.value = this.pdNoiseTexture;
    this.pdMaterial.uniforms.resolution.value.set(this.width, this.height);
    this.pdMaterial.uniforms.lumaPhi.value = 10;
    this.pdMaterial.uniforms.depthPhi.value = 2;
    this.pdMaterial.uniforms.normalPhi.value = 3;
    this.pdMaterial.uniforms.radius.value = 8;
    this.depthRenderMaterial = new ShaderMaterial({
      defines: Object.assign({}, GTAODepthShader.defines),
      uniforms: UniformsUtils.clone(GTAODepthShader.uniforms),
      vertexShader: GTAODepthShader.vertexShader,
      fragmentShader: GTAODepthShader.fragmentShader,
      blending: NoBlending
    });
    this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near;
    this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far;
    this.copyMaterial = new ShaderMaterial({
      uniforms: UniformsUtils.clone(CopyShader.uniforms),
      vertexShader: CopyShader.vertexShader,
      fragmentShader: CopyShader.fragmentShader,
      transparent: true,
      depthTest: false,
      depthWrite: false,
      blendSrc: DstColorFactor,
      blendDst: ZeroFactor,
      blendEquation: AddEquation,
      blendSrcAlpha: DstAlphaFactor,
      blendDstAlpha: ZeroFactor,
      blendEquationAlpha: AddEquation
    });
    this.blendMaterial = new ShaderMaterial({
      uniforms: UniformsUtils.clone(GTAOBlendShader.uniforms),
      vertexShader: GTAOBlendShader.vertexShader,
      fragmentShader: GTAOBlendShader.fragmentShader,
      transparent: true,
      depthTest: false,
      depthWrite: false,
      blending: CustomBlending,
      blendSrc: DstColorFactor,
      blendDst: ZeroFactor,
      blendEquation: AddEquation,
      blendSrcAlpha: DstAlphaFactor,
      blendDstAlpha: ZeroFactor,
      blendEquationAlpha: AddEquation
    });
    this._fsQuad = new FullScreenQuad(null);
    this._originalClearColor = new Color();
    this.setGBuffer(parameters ? parameters.depthTexture : void 0, parameters ? parameters.normalTexture : void 0);
    if (aoParameters !== void 0) {
      this.updateGtaoMaterial(aoParameters);
    }
    if (pdParameters !== void 0) {
      this.updatePdMaterial(pdParameters);
    }
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this.width = width2;
    this.height = height2;
    this.gtaoRenderTarget.setSize(width2, height2);
    this.normalRenderTarget.setSize(width2, height2);
    this.pdRenderTarget.setSize(width2, height2);
    this.gtaoMaterial.uniforms.resolution.value.set(width2, height2);
    this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix);
    this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse);
    this.pdMaterial.uniforms.resolution.value.set(width2, height2);
    this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.gtaoNoiseTexture.dispose();
    this.pdNoiseTexture.dispose();
    this.normalRenderTarget.dispose();
    this.gtaoRenderTarget.dispose();
    this.pdRenderTarget.dispose();
    this.normalMaterial.dispose();
    this.pdMaterial.dispose();
    this.copyMaterial.dispose();
    this.depthRenderMaterial.dispose();
    this._fsQuad.dispose();
  }
  /**
   * A texture holding the computed AO.
   *
   * @type {Texture}
   * @readonly
   */
  get gtaoMap() {
    return this.pdRenderTarget.texture;
  }
  /**
   * Configures the GBuffer of this pass. If no arguments are passed,
   * the pass creates an internal render target for holding depth
   * and normal data.
   *
   * @param {DepthTexture} [depthTexture] - The depth texture.
   * @param {DepthTexture} [normalTexture] - The normal texture.
   */
  setGBuffer(depthTexture, normalTexture) {
    if (depthTexture !== void 0) {
      this.depthTexture = depthTexture;
      this.normalTexture = normalTexture;
      this._renderGBuffer = false;
    } else {
      this.depthTexture = new DepthTexture();
      this.depthTexture.format = DepthStencilFormat;
      this.depthTexture.type = UnsignedInt248Type;
      this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, {
        minFilter: NearestFilter,
        magFilter: NearestFilter,
        type: HalfFloatType,
        depthTexture: this.depthTexture
      });
      this.normalTexture = this.normalRenderTarget.texture;
      this._renderGBuffer = true;
    }
    const normalVectorType = this.normalTexture ? 1 : 0;
    const depthValueSource = this.depthTexture === this.normalTexture ? "w" : "x";
    this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType;
    this.gtaoMaterial.defines.DEPTH_SWIZZLING = depthValueSource;
    this.gtaoMaterial.uniforms.tNormal.value = this.normalTexture;
    this.gtaoMaterial.uniforms.tDepth.value = this.depthTexture;
    this.pdMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType;
    this.pdMaterial.defines.DEPTH_SWIZZLING = depthValueSource;
    this.pdMaterial.uniforms.tNormal.value = this.normalTexture;
    this.pdMaterial.uniforms.tDepth.value = this.depthTexture;
    this.depthRenderMaterial.uniforms.tDepth.value = this.normalRenderTarget.depthTexture;
  }
  /**
   * Configures the clip box of the GTAO shader with the given AABB.
   *
   * @param {?Box3} box - The AABB enclosing the scene that should receive AO. When passing
   * `null`, to clip box is used.
   */
  setSceneClipBox(box) {
    if (box) {
      this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX !== 1;
      this.gtaoMaterial.defines.SCENE_CLIP_BOX = 1;
      this.gtaoMaterial.uniforms.sceneBoxMin.value.copy(box.min);
      this.gtaoMaterial.uniforms.sceneBoxMax.value.copy(box.max);
    } else {
      this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX === 0;
      this.gtaoMaterial.defines.SCENE_CLIP_BOX = 0;
    }
  }
  /**
   * Updates the GTAO material from the given parameter object.
   *
   * @param {Object} parameters - The GTAO material parameters.
   */
  updateGtaoMaterial(parameters) {
    if (parameters.radius !== void 0) {
      this.gtaoMaterial.uniforms.radius.value = parameters.radius;
    }
    if (parameters.distanceExponent !== void 0) {
      this.gtaoMaterial.uniforms.distanceExponent.value = parameters.distanceExponent;
    }
    if (parameters.thickness !== void 0) {
      this.gtaoMaterial.uniforms.thickness.value = parameters.thickness;
    }
    if (parameters.distanceFallOff !== void 0) {
      this.gtaoMaterial.uniforms.distanceFallOff.value = parameters.distanceFallOff;
      this.gtaoMaterial.needsUpdate = true;
    }
    if (parameters.scale !== void 0) {
      this.gtaoMaterial.uniforms.scale.value = parameters.scale;
    }
    if (parameters.samples !== void 0 && parameters.samples !== this.gtaoMaterial.defines.SAMPLES) {
      this.gtaoMaterial.defines.SAMPLES = parameters.samples;
      this.gtaoMaterial.needsUpdate = true;
    }
    if (parameters.screenSpaceRadius !== void 0 && (parameters.screenSpaceRadius ? 1 : 0) !== this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS) {
      this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS = parameters.screenSpaceRadius ? 1 : 0;
      this.gtaoMaterial.needsUpdate = true;
    }
  }
  /**
   * Updates the Denoise material from the given parameter object.
   *
   * @param {Object} parameters - The denoise parameters.
   */
  updatePdMaterial(parameters) {
    let updateShader = false;
    if (parameters.lumaPhi !== void 0) {
      this.pdMaterial.uniforms.lumaPhi.value = parameters.lumaPhi;
    }
    if (parameters.depthPhi !== void 0) {
      this.pdMaterial.uniforms.depthPhi.value = parameters.depthPhi;
    }
    if (parameters.normalPhi !== void 0) {
      this.pdMaterial.uniforms.normalPhi.value = parameters.normalPhi;
    }
    if (parameters.radius !== void 0 && parameters.radius !== this.radius) {
      this.pdMaterial.uniforms.radius.value = parameters.radius;
    }
    if (parameters.radiusExponent !== void 0 && parameters.radiusExponent !== this.pdRadiusExponent) {
      this.pdRadiusExponent = parameters.radiusExponent;
      updateShader = true;
    }
    if (parameters.rings !== void 0 && parameters.rings !== this.pdRings) {
      this.pdRings = parameters.rings;
      updateShader = true;
    }
    if (parameters.samples !== void 0 && parameters.samples !== this.pdSamples) {
      this.pdSamples = parameters.samples;
      updateShader = true;
    }
    if (updateShader) {
      this.pdMaterial.defines.SAMPLES = this.pdSamples;
      this.pdMaterial.defines.SAMPLE_VECTORS = generatePdSamplePointInitializer(this.pdSamples, this.pdRings, this.pdRadiusExponent);
      this.pdMaterial.needsUpdate = true;
    }
  }
  /**
   * Performs the GTAO pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    if (this._renderGBuffer) {
      this._overrideVisibility();
      this._renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1);
      this._restoreVisibility();
    }
    this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near;
    this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far;
    this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix);
    this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse);
    this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy(this.camera.matrixWorld);
    this._renderPass(renderer2, this.gtaoMaterial, this.gtaoRenderTarget, 16777215, 1);
    this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse);
    this._renderPass(renderer2, this.pdMaterial, this.pdRenderTarget, 16777215, 1);
    switch (this.output) {
      case _GTAOPass.OUTPUT.Off:
        break;
      case _GTAOPass.OUTPUT.Diffuse:
        this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      case _GTAOPass.OUTPUT.AO:
        this.copyMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      case _GTAOPass.OUTPUT.Denoise:
        this.copyMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      case _GTAOPass.OUTPUT.Depth:
        this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near;
        this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far;
        this._renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      case _GTAOPass.OUTPUT.Normal:
        this.copyMaterial.uniforms.tDiffuse.value = this.normalRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      case _GTAOPass.OUTPUT.Default:
        this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        this.blendMaterial.uniforms.intensity.value = this.blendIntensity;
        this.blendMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture;
        this._renderPass(renderer2, this.blendMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      default:
        console.warn("THREE.GTAOPass: Unknown output type.");
    }
  }
  // internals
  _renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) {
    renderer2.getClearColor(this._originalClearColor);
    const originalClearAlpha = renderer2.getClearAlpha();
    const originalAutoClear = renderer2.autoClear;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this._fsQuad.material = passMaterial;
    this._fsQuad.render(renderer2);
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this._originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
  }
  _renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) {
    renderer2.getClearColor(this._originalClearColor);
    const originalClearAlpha = renderer2.getClearAlpha();
    const originalAutoClear = renderer2.autoClear;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    clearColor = overrideMaterial.clearColor || clearColor;
    clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this.scene.overrideMaterial = overrideMaterial;
    renderer2.render(this.scene, this.camera);
    this.scene.overrideMaterial = null;
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this._originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
  }
  _overrideVisibility() {
    const scene = this.scene;
    const cache = this._visibilityCache;
    scene.traverse(function(object) {
      cache.set(object, object.visible);
      if (object.isPoints || object.isLine) object.visible = false;
    });
  }
  _restoreVisibility() {
    const scene = this.scene;
    const cache = this._visibilityCache;
    scene.traverse(function(object) {
      const visible = cache.get(object);
      object.visible = visible;
    });
    cache.clear();
  }
  _generateNoise(size2 = 64) {
    const simplex = new SimplexNoise();
    const arraySize = size2 * size2 * 4;
    const data2 = new Uint8Array(arraySize);
    for (let i = 0; i < size2; i++) {
      for (let j2 = 0; j2 < size2; j2++) {
        const x2 = i;
        const y = j2;
        data2[(i * size2 + j2) * 4] = (simplex.noise(x2, y) * 0.5 + 0.5) * 255;
        data2[(i * size2 + j2) * 4 + 1] = (simplex.noise(x2 + size2, y) * 0.5 + 0.5) * 255;
        data2[(i * size2 + j2) * 4 + 2] = (simplex.noise(x2, y + size2) * 0.5 + 0.5) * 255;
        data2[(i * size2 + j2) * 4 + 3] = (simplex.noise(x2 + size2, y + size2) * 0.5 + 0.5) * 255;
      }
    }
    const noiseTexture = new DataTexture(data2, size2, size2, RGBAFormat, UnsignedByteType);
    noiseTexture.wrapS = RepeatWrapping;
    noiseTexture.wrapT = RepeatWrapping;
    noiseTexture.needsUpdate = true;
    return noiseTexture;
  }
};
GTAOPass.OUTPUT = {
  "Off": -1,
  "Default": 0,
  "Diffuse": 1,
  "Depth": 2,
  "Normal": 3,
  "AO": 4,
  "Denoise": 5
};

// node_modules/three/examples/jsm/shaders/HalftoneShader.js
var HalftoneShader = {
  name: "HalftoneShader",
  uniforms: {
    "tDiffuse": { value: null },
    "shape": { value: 1 },
    "radius": { value: 4 },
    "rotateR": { value: Math.PI / 12 * 1 },
    "rotateG": { value: Math.PI / 12 * 2 },
    "rotateB": { value: Math.PI / 12 * 3 },
    "scatter": { value: 0 },
    "width": { value: 1 },
    "height": { value: 1 },
    "blending": { value: 1 },
    "blendingMode": { value: 1 },
    "greyscale": { value: false },
    "disable": { value: false }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUV;

		void main() {

			vUV = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

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

		#define SQRT2_MINUS_ONE 0.41421356
		#define SQRT2_HALF_MINUS_ONE 0.20710678
		#define PI2 6.28318531
		#define SHAPE_DOT 1
		#define SHAPE_ELLIPSE 2
		#define SHAPE_LINE 3
		#define SHAPE_SQUARE 4
		#define BLENDING_LINEAR 1
		#define BLENDING_MULTIPLY 2
		#define BLENDING_ADD 3
		#define BLENDING_LIGHTER 4
		#define BLENDING_DARKER 5
		uniform sampler2D tDiffuse;
		uniform float radius;
		uniform float rotateR;
		uniform float rotateG;
		uniform float rotateB;
		uniform float scatter;
		uniform float width;
		uniform float height;
		uniform int shape;
		uniform bool disable;
		uniform float blending;
		uniform int blendingMode;
		varying vec2 vUV;
		uniform bool greyscale;
		const int samples = 8;

		float blend( float a, float b, float t ) {

		// linear blend
			return a * ( 1.0 - t ) + b * t;

		}

		float hypot( float x, float y ) {

		// vector magnitude
			return sqrt( x * x + y * y );

		}

		float rand( vec2 seed ){

		// get pseudo-random number
			return fract( sin( dot( seed.xy, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );

		}

		float distanceToDotRadius( float channel, vec2 coord, vec2 normal, vec2 p, float angle, float rad_max ) {

		// apply shape-specific transforms
			float dist = hypot( coord.x - p.x, coord.y - p.y );
			float rad = channel;

			if ( shape == SHAPE_DOT ) {

				rad = pow( abs( rad ), 1.125 ) * rad_max;

			} else if ( shape == SHAPE_ELLIPSE ) {

				rad = pow( abs( rad ), 1.125 ) * rad_max;

				if ( dist != 0.0 ) {
					float dot_p = abs( ( p.x - coord.x ) / dist * normal.x + ( p.y - coord.y ) / dist * normal.y );
					dist = ( dist * ( 1.0 - SQRT2_HALF_MINUS_ONE ) ) + dot_p * dist * SQRT2_MINUS_ONE;
				}

			} else if ( shape == SHAPE_LINE ) {

				rad = pow( abs( rad ), 1.5) * rad_max;
				float dot_p = ( p.x - coord.x ) * normal.x + ( p.y - coord.y ) * normal.y;
				dist = hypot( normal.x * dot_p, normal.y * dot_p );

			} else if ( shape == SHAPE_SQUARE ) {

				float theta = atan( p.y - coord.y, p.x - coord.x ) - angle;
				float sin_t = abs( sin( theta ) );
				float cos_t = abs( cos( theta ) );
				rad = pow( abs( rad ), 1.4 );
				rad = rad_max * ( rad + ( ( sin_t > cos_t ) ? rad - sin_t * rad : rad - cos_t * rad ) );

			}

			return rad - dist;

		}

		struct Cell {

		// grid sample positions
			vec2 normal;
			vec2 p1;
			vec2 p2;
			vec2 p3;
			vec2 p4;
			float samp2;
			float samp1;
			float samp3;
			float samp4;

		};

		vec4 getSample( vec2 point ) {

		// multi-sampled point
			vec4 tex = texture2D( tDiffuse, vec2( point.x / width, point.y / height ) );
			float base = rand( vec2( floor( point.x ), floor( point.y ) ) ) * PI2;
			float step = PI2 / float( samples );
			float dist = radius * 0.66;

			for ( int i = 0; i < samples; ++i ) {

				float r = base + step * float( i );
				vec2 coord = point + vec2( cos( r ) * dist, sin( r ) * dist );
				tex += texture2D( tDiffuse, vec2( coord.x / width, coord.y / height ) );

			}

			tex /= float( samples ) + 1.0;
			return tex;

		}

		float getDotColour( Cell c, vec2 p, int channel, float angle, float aa ) {

		// get colour for given point
			float dist_c_1, dist_c_2, dist_c_3, dist_c_4, res;

			if ( channel == 0 ) {

				c.samp1 = getSample( c.p1 ).r;
				c.samp2 = getSample( c.p2 ).r;
				c.samp3 = getSample( c.p3 ).r;
				c.samp4 = getSample( c.p4 ).r;

			} else if (channel == 1) {

				c.samp1 = getSample( c.p1 ).g;
				c.samp2 = getSample( c.p2 ).g;
				c.samp3 = getSample( c.p3 ).g;
				c.samp4 = getSample( c.p4 ).g;

			} else {

				c.samp1 = getSample( c.p1 ).b;
				c.samp3 = getSample( c.p3 ).b;
				c.samp2 = getSample( c.p2 ).b;
				c.samp4 = getSample( c.p4 ).b;

			}

			dist_c_1 = distanceToDotRadius( c.samp1, c.p1, c.normal, p, angle, radius );
			dist_c_2 = distanceToDotRadius( c.samp2, c.p2, c.normal, p, angle, radius );
			dist_c_3 = distanceToDotRadius( c.samp3, c.p3, c.normal, p, angle, radius );
			dist_c_4 = distanceToDotRadius( c.samp4, c.p4, c.normal, p, angle, radius );
			res = ( dist_c_1 > 0.0 ) ? clamp( dist_c_1 / aa, 0.0, 1.0 ) : 0.0;
			res += ( dist_c_2 > 0.0 ) ? clamp( dist_c_2 / aa, 0.0, 1.0 ) : 0.0;
			res += ( dist_c_3 > 0.0 ) ? clamp( dist_c_3 / aa, 0.0, 1.0 ) : 0.0;
			res += ( dist_c_4 > 0.0 ) ? clamp( dist_c_4 / aa, 0.0, 1.0 ) : 0.0;
			res = clamp( res, 0.0, 1.0 );

			return res;

		}

		Cell getReferenceCell( vec2 p, vec2 origin, float grid_angle, float step ) {

		// get containing cell
			Cell c;

		// calc grid
			vec2 n = vec2( cos( grid_angle ), sin( grid_angle ) );
			float threshold = step * 0.5;
			float dot_normal = n.x * ( p.x - origin.x ) + n.y * ( p.y - origin.y );
			float dot_line = -n.y * ( p.x - origin.x ) + n.x * ( p.y - origin.y );
			vec2 offset = vec2( n.x * dot_normal, n.y * dot_normal );
			float offset_normal = mod( hypot( offset.x, offset.y ), step );
			float normal_dir = ( dot_normal < 0.0 ) ? 1.0 : -1.0;
			float normal_scale = ( ( offset_normal < threshold ) ? -offset_normal : step - offset_normal ) * normal_dir;
			float offset_line = mod( hypot( ( p.x - offset.x ) - origin.x, ( p.y - offset.y ) - origin.y ), step );
			float line_dir = ( dot_line < 0.0 ) ? 1.0 : -1.0;
			float line_scale = ( ( offset_line < threshold ) ? -offset_line : step - offset_line ) * line_dir;

		// get closest corner
			c.normal = n;
			c.p1.x = p.x - n.x * normal_scale + n.y * line_scale;
			c.p1.y = p.y - n.y * normal_scale - n.x * line_scale;

		// scatter
			if ( scatter != 0.0 ) {

				float off_mag = scatter * threshold * 0.5;
				float off_angle = rand( vec2( floor( c.p1.x ), floor( c.p1.y ) ) ) * PI2;
				c.p1.x += cos( off_angle ) * off_mag;
				c.p1.y += sin( off_angle ) * off_mag;

			}

		// find corners
			float normal_step = normal_dir * ( ( offset_normal < threshold ) ? step : -step );
			float line_step = line_dir * ( ( offset_line < threshold ) ? step : -step );
			c.p2.x = c.p1.x - n.x * normal_step;
			c.p2.y = c.p1.y - n.y * normal_step;
			c.p3.x = c.p1.x + n.y * line_step;
			c.p3.y = c.p1.y - n.x * line_step;
			c.p4.x = c.p1.x - n.x * normal_step + n.y * line_step;
			c.p4.y = c.p1.y - n.y * normal_step - n.x * line_step;

			return c;

		}

		float blendColour( float a, float b, float t ) {

		// blend colours
			if ( blendingMode == BLENDING_LINEAR ) {
				return blend( a, b, 1.0 - t );
			} else if ( blendingMode == BLENDING_ADD ) {
				return blend( a, min( 1.0, a + b ), t );
			} else if ( blendingMode == BLENDING_MULTIPLY ) {
				return blend( a, max( 0.0, a * b ), t );
			} else if ( blendingMode == BLENDING_LIGHTER ) {
				return blend( a, max( a, b ), t );
			} else if ( blendingMode == BLENDING_DARKER ) {
				return blend( a, min( a, b ), t );
			} else {
				return blend( a, b, 1.0 - t );
			}

		}

		void main() {

			if ( ! disable ) {

		// setup
				vec2 p = vec2( vUV.x * width, vUV.y * height );
				vec2 origin = vec2( 0, 0 );
				float aa = ( radius < 2.5 ) ? radius * 0.5 : 1.25;

		// get channel samples
				Cell cell_r = getReferenceCell( p, origin, rotateR, radius );
				Cell cell_g = getReferenceCell( p, origin, rotateG, radius );
				Cell cell_b = getReferenceCell( p, origin, rotateB, radius );
				float r = getDotColour( cell_r, p, 0, rotateR, aa );
				float g = getDotColour( cell_g, p, 1, rotateG, aa );
				float b = getDotColour( cell_b, p, 2, rotateB, aa );

		// blend with original
				vec4 colour = texture2D( tDiffuse, vUV );
				r = blendColour( r, colour.r, blending );
				g = blendColour( g, colour.g, blending );
				b = blendColour( b, colour.b, blending );

				if ( greyscale ) {
					r = g = b = (r + b + g) / 3.0;
				}

				gl_FragColor = vec4( r, g, b, 1.0 );

			} else {

				gl_FragColor = texture2D( tDiffuse, vUV );

			}

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/HalftonePass.js
var HalftonePass = class extends Pass {
  /**
   * Constructs a new halftone pass.
   *
   * @param {Object} params - The halftone shader parameter.
   */
  constructor(params) {
    super();
    this.uniforms = UniformsUtils.clone(HalftoneShader.uniforms);
    this.material = new ShaderMaterial({
      uniforms: this.uniforms,
      fragmentShader: HalftoneShader.fragmentShader,
      vertexShader: HalftoneShader.vertexShader
    });
    for (const key2 in params) {
      if (params.hasOwnProperty(key2) && this.uniforms.hasOwnProperty(key2)) {
        this.uniforms[key2].value = params[key2];
      }
    }
    this._fsQuad = new FullScreenQuad(this.material);
  }
  /**
   * Performs the halftone pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this.material.uniforms["tDiffuse"].value = readBuffer.texture;
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear();
      this._fsQuad.render(renderer2);
    }
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this.uniforms.width.value = width2;
    this.uniforms.height.value = height2;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.material.dispose();
    this._fsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/postprocessing/LUTPass.js
var LUTShader = {
  name: "LUTShader",
  uniforms: {
    lut: { value: null },
    lutSize: { value: 0 },
    tDiffuse: { value: null },
    intensity: { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}

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

		uniform float lutSize;
		uniform sampler3D lut;

		varying vec2 vUv;
		uniform float intensity;
		uniform sampler2D tDiffuse;
		void main() {

			vec4 val = texture2D( tDiffuse, vUv );
			vec4 lutVal;

			// pull the sample in by half a pixel so the sample begins
			// at the center of the edge pixels.
			float pixelWidth = 1.0 / lutSize;
			float halfPixelWidth = 0.5 / lutSize;
			vec3 uvw = vec3( halfPixelWidth ) + val.rgb * ( 1.0 - pixelWidth );


			lutVal = vec4( texture( lut, uvw ).rgb, val.a );

			gl_FragColor = vec4( mix( val, lutVal, intensity ) );

		}

	`
  )
};
var LUTPass = class extends ShaderPass {
  /**
   * Constructs a LUT pass.
   *
   * @param {{lut:Data3DTexture,intensity:number}} [options={}] - The pass options.
   */
  constructor(options = {}) {
    super(LUTShader);
    this.lut = options.lut || null;
    this.intensity = "intensity" in options ? options.intensity : 1;
  }
  set lut(v) {
    const material = this.material;
    if (v !== this.lut) {
      material.uniforms.lut.value = null;
      if (v) {
        material.uniforms.lutSize.value = v.image.width;
        material.uniforms.lut.value = v;
      }
    }
  }
  get lut() {
    return this.material.uniforms.lut.value;
  }
  set intensity(v) {
    this.material.uniforms.intensity.value = v;
  }
  get intensity() {
    return this.material.uniforms.intensity.value;
  }
};

// node_modules/three/examples/jsm/postprocessing/OutlinePass.js
var OutlinePass = class _OutlinePass extends Pass {
  /**
   * Constructs a new outline pass.
   *
   * @param {Vector2} [resolution] - The effect's resolution.
   * @param {Scene} scene - The scene to render.
   * @param {Camera} camera - The camera.
   * @param {Array<Object3D>} [selectedObjects] - The selected 3D objects that should receive an outline.
   *
   */
  constructor(resolution, scene, camera, selectedObjects) {
    super();
    this.renderScene = scene;
    this.renderCamera = camera;
    this.selectedObjects = selectedObjects !== void 0 ? selectedObjects : [];
    this.visibleEdgeColor = new Color(1, 1, 1);
    this.hiddenEdgeColor = new Color(0.1, 0.04, 0.02);
    this.edgeGlow = 0;
    this.usePatternTexture = false;
    this.patternTexture = null;
    this.edgeThickness = 1;
    this.edgeStrength = 3;
    this.downSampleRatio = 2;
    this.pulsePeriod = 0;
    this._visibilityCache = /* @__PURE__ */ new Map();
    this._selectionCache = /* @__PURE__ */ new Set();
    this.resolution = resolution !== void 0 ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256);
    const resx = Math.round(this.resolution.x / this.downSampleRatio);
    const resy = Math.round(this.resolution.y / this.downSampleRatio);
    this.renderTargetMaskBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y);
    this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask";
    this.renderTargetMaskBuffer.texture.generateMipmaps = false;
    this.depthMaterial = new MeshDepthMaterial();
    this.depthMaterial.side = DoubleSide;
    this.depthMaterial.depthPacking = RGBADepthPacking;
    this.depthMaterial.blending = NoBlending;
    this.prepareMaskMaterial = this._getPrepareMaskMaterial();
    this.prepareMaskMaterial.side = DoubleSide;
    this.prepareMaskMaterial.fragmentShader = replaceDepthToViewZ(this.prepareMaskMaterial.fragmentShader, this.renderCamera);
    this.renderTargetDepthBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { type: HalfFloatType });
    this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth";
    this.renderTargetDepthBuffer.texture.generateMipmaps = false;
    this.renderTargetMaskDownSampleBuffer = new WebGLRenderTarget(resx, resy, { type: HalfFloatType });
    this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample";
    this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false;
    this.renderTargetBlurBuffer1 = new WebGLRenderTarget(resx, resy, { type: HalfFloatType });
    this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1";
    this.renderTargetBlurBuffer1.texture.generateMipmaps = false;
    this.renderTargetBlurBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2), { type: HalfFloatType });
    this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2";
    this.renderTargetBlurBuffer2.texture.generateMipmaps = false;
    this.edgeDetectionMaterial = this._getEdgeDetectionMaterial();
    this.renderTargetEdgeBuffer1 = new WebGLRenderTarget(resx, resy, { type: HalfFloatType });
    this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1";
    this.renderTargetEdgeBuffer1.texture.generateMipmaps = false;
    this.renderTargetEdgeBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2), { type: HalfFloatType });
    this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2";
    this.renderTargetEdgeBuffer2.texture.generateMipmaps = false;
    const MAX_EDGE_THICKNESS = 4;
    const MAX_EDGE_GLOW = 4;
    this.separableBlurMaterial1 = this._getSeparableBlurMaterial(MAX_EDGE_THICKNESS);
    this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy);
    this.separableBlurMaterial1.uniforms["kernelRadius"].value = 1;
    this.separableBlurMaterial2 = this._getSeparableBlurMaterial(MAX_EDGE_GLOW);
    this.separableBlurMaterial2.uniforms["texSize"].value.set(Math.round(resx / 2), Math.round(resy / 2));
    this.separableBlurMaterial2.uniforms["kernelRadius"].value = MAX_EDGE_GLOW;
    this.overlayMaterial = this._getOverlayMaterial();
    const copyShader = CopyShader;
    this.copyUniforms = UniformsUtils.clone(copyShader.uniforms);
    this.materialCopy = new ShaderMaterial({
      uniforms: this.copyUniforms,
      vertexShader: copyShader.vertexShader,
      fragmentShader: copyShader.fragmentShader,
      blending: NoBlending,
      depthTest: false,
      depthWrite: false
    });
    this.enabled = true;
    this.needsSwap = false;
    this._oldClearColor = new Color();
    this.oldClearAlpha = 1;
    this._fsQuad = new FullScreenQuad(null);
    this.tempPulseColor1 = new Color();
    this.tempPulseColor2 = new Color();
    this.textureMatrix = new Matrix4();
    function replaceDepthToViewZ(string, camera2) {
      const type = camera2.isPerspectiveCamera ? "perspective" : "orthographic";
      return string.replace(/DEPTH_TO_VIEW_Z/g, type + "DepthToViewZ");
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.renderTargetMaskBuffer.dispose();
    this.renderTargetDepthBuffer.dispose();
    this.renderTargetMaskDownSampleBuffer.dispose();
    this.renderTargetBlurBuffer1.dispose();
    this.renderTargetBlurBuffer2.dispose();
    this.renderTargetEdgeBuffer1.dispose();
    this.renderTargetEdgeBuffer2.dispose();
    this.depthMaterial.dispose();
    this.prepareMaskMaterial.dispose();
    this.edgeDetectionMaterial.dispose();
    this.separableBlurMaterial1.dispose();
    this.separableBlurMaterial2.dispose();
    this.overlayMaterial.dispose();
    this.materialCopy.dispose();
    this._fsQuad.dispose();
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this.renderTargetMaskBuffer.setSize(width2, height2);
    this.renderTargetDepthBuffer.setSize(width2, height2);
    let resx = Math.round(width2 / this.downSampleRatio);
    let resy = Math.round(height2 / this.downSampleRatio);
    this.renderTargetMaskDownSampleBuffer.setSize(resx, resy);
    this.renderTargetBlurBuffer1.setSize(resx, resy);
    this.renderTargetEdgeBuffer1.setSize(resx, resy);
    this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy);
    resx = Math.round(resx / 2);
    resy = Math.round(resy / 2);
    this.renderTargetBlurBuffer2.setSize(resx, resy);
    this.renderTargetEdgeBuffer2.setSize(resx, resy);
    this.separableBlurMaterial2.uniforms["texSize"].value.set(resx, resy);
  }
  /**
   * Performs the Outline pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) {
    if (this.selectedObjects.length > 0) {
      renderer2.getClearColor(this._oldClearColor);
      this.oldClearAlpha = renderer2.getClearAlpha();
      const oldAutoClear = renderer2.autoClear;
      renderer2.autoClear = false;
      if (maskActive) renderer2.state.buffers.stencil.setTest(false);
      renderer2.setClearColor(16777215, 1);
      this._updateSelectionCache();
      this._changeVisibilityOfSelectedObjects(false);
      const currentBackground = this.renderScene.background;
      const currentOverrideMaterial = this.renderScene.overrideMaterial;
      this.renderScene.background = null;
      this.renderScene.overrideMaterial = this.depthMaterial;
      renderer2.setRenderTarget(this.renderTargetDepthBuffer);
      renderer2.clear();
      renderer2.render(this.renderScene, this.renderCamera);
      this._changeVisibilityOfSelectedObjects(true);
      this._visibilityCache.clear();
      this._updateTextureMatrix();
      this._changeVisibilityOfNonSelectedObjects(false);
      this.renderScene.overrideMaterial = this.prepareMaskMaterial;
      this.prepareMaskMaterial.uniforms["cameraNearFar"].value.set(this.renderCamera.near, this.renderCamera.far);
      this.prepareMaskMaterial.uniforms["depthTexture"].value = this.renderTargetDepthBuffer.texture;
      this.prepareMaskMaterial.uniforms["textureMatrix"].value = this.textureMatrix;
      renderer2.setRenderTarget(this.renderTargetMaskBuffer);
      renderer2.clear();
      renderer2.render(this.renderScene, this.renderCamera);
      this._changeVisibilityOfNonSelectedObjects(true);
      this._visibilityCache.clear();
      this._selectionCache.clear();
      this.renderScene.background = currentBackground;
      this.renderScene.overrideMaterial = currentOverrideMaterial;
      this._fsQuad.material = this.materialCopy;
      this.copyUniforms["tDiffuse"].value = this.renderTargetMaskBuffer.texture;
      renderer2.setRenderTarget(this.renderTargetMaskDownSampleBuffer);
      renderer2.clear();
      this._fsQuad.render(renderer2);
      this.tempPulseColor1.copy(this.visibleEdgeColor);
      this.tempPulseColor2.copy(this.hiddenEdgeColor);
      if (this.pulsePeriod > 0) {
        const scalar = (1 + 0.25) / 2 + Math.cos(performance.now() * 0.01 / this.pulsePeriod) * (1 - 0.25) / 2;
        this.tempPulseColor1.multiplyScalar(scalar);
        this.tempPulseColor2.multiplyScalar(scalar);
      }
      this._fsQuad.material = this.edgeDetectionMaterial;
      this.edgeDetectionMaterial.uniforms["maskTexture"].value = this.renderTargetMaskDownSampleBuffer.texture;
      this.edgeDetectionMaterial.uniforms["texSize"].value.set(this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height);
      this.edgeDetectionMaterial.uniforms["visibleEdgeColor"].value = this.tempPulseColor1;
      this.edgeDetectionMaterial.uniforms["hiddenEdgeColor"].value = this.tempPulseColor2;
      renderer2.setRenderTarget(this.renderTargetEdgeBuffer1);
      renderer2.clear();
      this._fsQuad.render(renderer2);
      this._fsQuad.material = this.separableBlurMaterial1;
      this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture;
      this.separableBlurMaterial1.uniforms["direction"].value = _OutlinePass.BlurDirectionX;
      this.separableBlurMaterial1.uniforms["kernelRadius"].value = this.edgeThickness;
      renderer2.setRenderTarget(this.renderTargetBlurBuffer1);
      renderer2.clear();
      this._fsQuad.render(renderer2);
      this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetBlurBuffer1.texture;
      this.separableBlurMaterial1.uniforms["direction"].value = _OutlinePass.BlurDirectionY;
      renderer2.setRenderTarget(this.renderTargetEdgeBuffer1);
      renderer2.clear();
      this._fsQuad.render(renderer2);
      this._fsQuad.material = this.separableBlurMaterial2;
      this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture;
      this.separableBlurMaterial2.uniforms["direction"].value = _OutlinePass.BlurDirectionX;
      renderer2.setRenderTarget(this.renderTargetBlurBuffer2);
      renderer2.clear();
      this._fsQuad.render(renderer2);
      this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetBlurBuffer2.texture;
      this.separableBlurMaterial2.uniforms["direction"].value = _OutlinePass.BlurDirectionY;
      renderer2.setRenderTarget(this.renderTargetEdgeBuffer2);
      renderer2.clear();
      this._fsQuad.render(renderer2);
      this._fsQuad.material = this.overlayMaterial;
      this.overlayMaterial.uniforms["maskTexture"].value = this.renderTargetMaskBuffer.texture;
      this.overlayMaterial.uniforms["edgeTexture1"].value = this.renderTargetEdgeBuffer1.texture;
      this.overlayMaterial.uniforms["edgeTexture2"].value = this.renderTargetEdgeBuffer2.texture;
      this.overlayMaterial.uniforms["patternTexture"].value = this.patternTexture;
      this.overlayMaterial.uniforms["edgeStrength"].value = this.edgeStrength;
      this.overlayMaterial.uniforms["edgeGlow"].value = this.edgeGlow;
      this.overlayMaterial.uniforms["usePatternTexture"].value = this.usePatternTexture;
      if (maskActive) renderer2.state.buffers.stencil.setTest(true);
      renderer2.setRenderTarget(readBuffer);
      this._fsQuad.render(renderer2);
      renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha);
      renderer2.autoClear = oldAutoClear;
    }
    if (this.renderToScreen) {
      this._fsQuad.material = this.materialCopy;
      this.copyUniforms["tDiffuse"].value = readBuffer.texture;
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    }
  }
  // internals
  _updateSelectionCache() {
    const cache = this._selectionCache;
    function gatherSelectedMeshesCallBack(object) {
      if (object.isMesh) cache.add(object);
    }
    cache.clear();
    for (let i = 0; i < this.selectedObjects.length; i++) {
      const selectedObject = this.selectedObjects[i];
      selectedObject.traverse(gatherSelectedMeshesCallBack);
    }
  }
  _changeVisibilityOfSelectedObjects(bVisible) {
    const cache = this._visibilityCache;
    for (const mesh of this._selectionCache) {
      if (bVisible === true) {
        mesh.visible = cache.get(mesh);
      } else {
        cache.set(mesh, mesh.visible);
        mesh.visible = bVisible;
      }
    }
  }
  _changeVisibilityOfNonSelectedObjects(bVisible) {
    const visibilityCache = this._visibilityCache;
    const selectionCache = this._selectionCache;
    function VisibilityChangeCallBack(object) {
      if (object.isMesh || object.isSprite) {
        if (!selectionCache.has(object)) {
          const visibility = object.visible;
          if (bVisible === false || visibilityCache.get(object) === true) {
            object.visible = bVisible;
          }
          visibilityCache.set(object, visibility);
        }
      } else if (object.isPoints || object.isLine) {
        if (bVisible === true) {
          object.visible = visibilityCache.get(object);
        } else {
          visibilityCache.set(object, object.visible);
          object.visible = bVisible;
        }
      }
    }
    this.renderScene.traverse(VisibilityChangeCallBack);
  }
  _updateTextureMatrix() {
    this.textureMatrix.set(
      0.5,
      0,
      0,
      0.5,
      0,
      0.5,
      0,
      0.5,
      0,
      0,
      0.5,
      0.5,
      0,
      0,
      0,
      1
    );
    this.textureMatrix.multiply(this.renderCamera.projectionMatrix);
    this.textureMatrix.multiply(this.renderCamera.matrixWorldInverse);
  }
  _getPrepareMaskMaterial() {
    return new ShaderMaterial({
      uniforms: {
        "depthTexture": { value: null },
        "cameraNearFar": { value: new Vector2(0.5, 0.5) },
        "textureMatrix": { value: null }
      },
      vertexShader: `#include <batching_pars_vertex>
				#include <morphtarget_pars_vertex>
				#include <skinning_pars_vertex>

				varying vec4 projTexCoord;
				varying vec4 vPosition;
				uniform mat4 textureMatrix;

				void main() {

					#include <batching_vertex>
					#include <skinbase_vertex>
					#include <begin_vertex>
					#include <morphtarget_vertex>
					#include <skinning_vertex>
					#include <project_vertex>

					vPosition = mvPosition;

					vec4 worldPosition = vec4( transformed, 1.0 );

					#ifdef USE_INSTANCING

						worldPosition = instanceMatrix * worldPosition;

					#endif

					worldPosition = modelMatrix * worldPosition;

					projTexCoord = textureMatrix * worldPosition;

				}`,
      fragmentShader: `#include <packing>
				varying vec4 vPosition;
				varying vec4 projTexCoord;
				uniform sampler2D depthTexture;
				uniform vec2 cameraNearFar;

				void main() {

					float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord ));
					float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y );
					float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0;
					gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0);

				}`
    });
  }
  _getEdgeDetectionMaterial() {
    return new ShaderMaterial({
      uniforms: {
        "maskTexture": { value: null },
        "texSize": { value: new Vector2(0.5, 0.5) },
        "visibleEdgeColor": { value: new Vector3(1, 1, 1) },
        "hiddenEdgeColor": { value: new Vector3(1, 1, 1) }
      },
      vertexShader: `varying vec2 vUv;

				void main() {
					vUv = uv;
					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
				}`,
      fragmentShader: `varying vec2 vUv;

				uniform sampler2D maskTexture;
				uniform vec2 texSize;
				uniform vec3 visibleEdgeColor;
				uniform vec3 hiddenEdgeColor;

				void main() {
					vec2 invSize = 1.0 / texSize;
					vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);
					vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);
					vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);
					vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);
					vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);
					float diff1 = (c1.r - c2.r)*0.5;
					float diff2 = (c3.r - c4.r)*0.5;
					float d = length( vec2(diff1, diff2) );
					float a1 = min(c1.g, c2.g);
					float a2 = min(c3.g, c4.g);
					float visibilityFactor = min(a1, a2);
					vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;
					gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);
				}`
    });
  }
  _getSeparableBlurMaterial(maxRadius) {
    return new ShaderMaterial({
      defines: {
        "MAX_RADIUS": maxRadius
      },
      uniforms: {
        "colorTexture": { value: null },
        "texSize": { value: new Vector2(0.5, 0.5) },
        "direction": { value: new Vector2(0.5, 0.5) },
        "kernelRadius": { value: 1 }
      },
      vertexShader: `varying vec2 vUv;

				void main() {
					vUv = uv;
					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
				}`,
      fragmentShader: `#include <common>
				varying vec2 vUv;
				uniform sampler2D colorTexture;
				uniform vec2 texSize;
				uniform vec2 direction;
				uniform float kernelRadius;

				float gaussianPdf(in float x, in float sigma) {
					return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;
				}

				void main() {
					vec2 invSize = 1.0 / texSize;
					float sigma = kernelRadius/2.0;
					float weightSum = gaussianPdf(0.0, sigma);
					vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum;
					vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS);
					vec2 uvOffset = delta;
					for( int i = 1; i <= MAX_RADIUS; i ++ ) {
						float x = kernelRadius * float(i) / float(MAX_RADIUS);
						float w = gaussianPdf(x, sigma);
						vec4 sample1 = texture2D( colorTexture, vUv + uvOffset);
						vec4 sample2 = texture2D( colorTexture, vUv - uvOffset);
						diffuseSum += ((sample1 + sample2) * w);
						weightSum += (2.0 * w);
						uvOffset += delta;
					}
					gl_FragColor = diffuseSum/weightSum;
				}`
    });
  }
  _getOverlayMaterial() {
    return new ShaderMaterial({
      uniforms: {
        "maskTexture": { value: null },
        "edgeTexture1": { value: null },
        "edgeTexture2": { value: null },
        "patternTexture": { value: null },
        "edgeStrength": { value: 1 },
        "edgeGlow": { value: 1 },
        "usePatternTexture": { value: 0 }
      },
      vertexShader: `varying vec2 vUv;

				void main() {
					vUv = uv;
					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
				}`,
      fragmentShader: `varying vec2 vUv;

				uniform sampler2D maskTexture;
				uniform sampler2D edgeTexture1;
				uniform sampler2D edgeTexture2;
				uniform sampler2D patternTexture;
				uniform float edgeStrength;
				uniform float edgeGlow;
				uniform bool usePatternTexture;

				void main() {
					vec4 edgeValue1 = texture2D(edgeTexture1, vUv);
					vec4 edgeValue2 = texture2D(edgeTexture2, vUv);
					vec4 maskColor = texture2D(maskTexture, vUv);
					vec4 patternColor = texture2D(patternTexture, 6.0 * vUv);
					float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;
					vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow;
					vec4 finalColor = edgeStrength * maskColor.r * edgeValue;
					if(usePatternTexture)
						finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r);
					gl_FragColor = finalColor;
				}`,
      blending: AdditiveBlending,
      depthTest: false,
      depthWrite: false,
      transparent: true
    });
  }
};
OutlinePass.BlurDirectionX = new Vector2(1, 0);
OutlinePass.BlurDirectionY = new Vector2(0, 1);

// node_modules/three/examples/jsm/shaders/OutputShader.js
var OutputShader = {
  name: "OutputShader",
  uniforms: {
    "tDiffuse": { value: null },
    "toneMappingExposure": { value: 1 }
  },
  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;

		#include <tonemapping_pars_fragment>
		#include <colorspace_pars_fragment>

		varying vec2 vUv;

		void main() {

			gl_FragColor = texture2D( tDiffuse, vUv );

			// tone mapping

			#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

			// color space

			#ifdef SRGB_TRANSFER

				gl_FragColor = sRGBTransferOETF( gl_FragColor );

			#endif

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/OutputPass.js
var OutputPass = class extends Pass {
  /**
   * Constructs a new output pass.
   */
  constructor() {
    super();
    this.uniforms = UniformsUtils.clone(OutputShader.uniforms);
    this.material = new RawShaderMaterial({
      name: OutputShader.name,
      uniforms: this.uniforms,
      vertexShader: OutputShader.vertexShader,
      fragmentShader: OutputShader.fragmentShader
    });
    this._fsQuad = new FullScreenQuad(this.material);
    this._outputColorSpace = null;
    this._toneMapping = null;
  }
  /**
   * Performs the output pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this.uniforms["tDiffuse"].value = readBuffer.texture;
    this.uniforms["toneMappingExposure"].value = renderer2.toneMappingExposure;
    if (this._outputColorSpace !== renderer2.outputColorSpace || this._toneMapping !== renderer2.toneMapping) {
      this._outputColorSpace = renderer2.outputColorSpace;
      this._toneMapping = renderer2.toneMapping;
      this.material.defines = {};
      if (ColorManagement.getTransfer(this._outputColorSpace) === SRGBTransfer) this.material.defines.SRGB_TRANSFER = "";
      if (this._toneMapping === LinearToneMapping) this.material.defines.LINEAR_TONE_MAPPING = "";
      else if (this._toneMapping === ReinhardToneMapping) this.material.defines.REINHARD_TONE_MAPPING = "";
      else if (this._toneMapping === CineonToneMapping) this.material.defines.CINEON_TONE_MAPPING = "";
      else if (this._toneMapping === ACESFilmicToneMapping) this.material.defines.ACES_FILMIC_TONE_MAPPING = "";
      else if (this._toneMapping === AgXToneMapping) this.material.defines.AGX_TONE_MAPPING = "";
      else if (this._toneMapping === NeutralToneMapping) this.material.defines.NEUTRAL_TONE_MAPPING = "";
      else if (this._toneMapping === CustomToneMapping) this.material.defines.CUSTOM_TONE_MAPPING = "";
      this.material.needsUpdate = true;
    }
    if (this.renderToScreen === true) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil);
      this._fsQuad.render(renderer2);
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.material.dispose();
    this._fsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/postprocessing/RenderPass.js
var RenderPass = class extends Pass {
  /**
   * Constructs a new render pass.
   *
   * @param {Scene} scene - The scene to render.
   * @param {Camera} camera - The camera.
   * @param {?Material} [overrideMaterial=null] - The override material. If set, this material is used
   * for all objects in the scene.
   * @param {?(number|Color|string)} [clearColor=null] - The clear color of the render pass.
   * @param {?number} [clearAlpha=null] - The clear alpha of the render pass.
   */
  constructor(scene, camera, overrideMaterial = null, clearColor = null, clearAlpha = null) {
    super();
    this.scene = scene;
    this.camera = camera;
    this.overrideMaterial = overrideMaterial;
    this.clearColor = clearColor;
    this.clearAlpha = clearAlpha;
    this.clear = true;
    this.clearDepth = false;
    this.needsSwap = false;
    this._oldClearColor = new Color();
  }
  /**
   * Performs a beauty pass with the configured scene and camera.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    const oldAutoClear = renderer2.autoClear;
    renderer2.autoClear = false;
    let oldClearAlpha, oldOverrideMaterial;
    if (this.overrideMaterial !== null) {
      oldOverrideMaterial = this.scene.overrideMaterial;
      this.scene.overrideMaterial = this.overrideMaterial;
    }
    if (this.clearColor !== null) {
      renderer2.getClearColor(this._oldClearColor);
      renderer2.setClearColor(this.clearColor, renderer2.getClearAlpha());
    }
    if (this.clearAlpha !== null) {
      oldClearAlpha = renderer2.getClearAlpha();
      renderer2.setClearAlpha(this.clearAlpha);
    }
    if (this.clearDepth == true) {
      renderer2.clearDepth();
    }
    renderer2.setRenderTarget(this.renderToScreen ? null : readBuffer);
    if (this.clear === true) {
      renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil);
    }
    renderer2.render(this.scene, this.camera);
    if (this.clearColor !== null) {
      renderer2.setClearColor(this._oldClearColor);
    }
    if (this.clearAlpha !== null) {
      renderer2.setClearAlpha(oldClearAlpha);
    }
    if (this.overrideMaterial !== null) {
      this.scene.overrideMaterial = oldOverrideMaterial;
    }
    renderer2.autoClear = oldAutoClear;
  }
};

// node_modules/three/examples/jsm/postprocessing/RenderPixelatedPass.js
var RenderPixelatedPass = class extends Pass {
  /**
   * Constructs a new render pixelated pass.
   *
   * @param {number} pixelSize - The effect's pixel size.
   * @param {Scene} scene - The scene to render.
   * @param {Camera} camera - The camera.
   * @param {{normalEdgeStrength:number,depthEdgeStrength:number}} options - The pass options.
   */
  constructor(pixelSize, scene, camera, options = {}) {
    super();
    this.pixelSize = pixelSize;
    this.scene = scene;
    this.camera = camera;
    this.normalEdgeStrength = options.normalEdgeStrength || 0.3;
    this.depthEdgeStrength = options.depthEdgeStrength || 0.4;
    this.pixelatedMaterial = this._createPixelatedMaterial();
    this._resolution = new Vector2();
    this._renderResolution = new Vector2();
    this._normalMaterial = new MeshNormalMaterial();
    this._beautyRenderTarget = new WebGLRenderTarget();
    this._beautyRenderTarget.texture.minFilter = NearestFilter;
    this._beautyRenderTarget.texture.magFilter = NearestFilter;
    this._beautyRenderTarget.texture.type = HalfFloatType;
    this._beautyRenderTarget.depthTexture = new DepthTexture();
    this._normalRenderTarget = new WebGLRenderTarget();
    this._normalRenderTarget.texture.minFilter = NearestFilter;
    this._normalRenderTarget.texture.magFilter = NearestFilter;
    this._normalRenderTarget.texture.type = HalfFloatType;
    this._fsQuad = new FullScreenQuad(this.pixelatedMaterial);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this._beautyRenderTarget.dispose();
    this._normalRenderTarget.dispose();
    this.pixelatedMaterial.dispose();
    this._normalMaterial.dispose();
    this._fsQuad.dispose();
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this._resolution.set(width2, height2);
    this._renderResolution.set(width2 / this.pixelSize | 0, height2 / this.pixelSize | 0);
    const { x: x2, y } = this._renderResolution;
    this._beautyRenderTarget.setSize(x2, y);
    this._normalRenderTarget.setSize(x2, y);
    this._fsQuad.material.uniforms.resolution.value.set(x2, y, 1 / x2, 1 / y);
  }
  /**
   * Sets the effect's pixel size.
   *
   * @param {number} pixelSize - The pixel size to set.
   */
  setPixelSize(pixelSize) {
    this.pixelSize = pixelSize;
    this.setSize(this._resolution.x, this._resolution.y);
  }
  /**
   * Performs the pixelation pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer) {
    const uniforms = this._fsQuad.material.uniforms;
    uniforms.normalEdgeStrength.value = this.normalEdgeStrength;
    uniforms.depthEdgeStrength.value = this.depthEdgeStrength;
    renderer2.setRenderTarget(this._beautyRenderTarget);
    renderer2.render(this.scene, this.camera);
    const overrideMaterial_old = this.scene.overrideMaterial;
    renderer2.setRenderTarget(this._normalRenderTarget);
    this.scene.overrideMaterial = this._normalMaterial;
    renderer2.render(this.scene, this.camera);
    this.scene.overrideMaterial = overrideMaterial_old;
    uniforms.tDiffuse.value = this._beautyRenderTarget.texture;
    uniforms.tDepth.value = this._beautyRenderTarget.depthTexture;
    uniforms.tNormal.value = this._normalRenderTarget.texture;
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear();
    }
    this._fsQuad.render(renderer2);
  }
  // internals
  _createPixelatedMaterial() {
    return new ShaderMaterial({
      uniforms: {
        tDiffuse: { value: null },
        tDepth: { value: null },
        tNormal: { value: null },
        resolution: { value: new Vector4() },
        normalEdgeStrength: { value: 0 },
        depthEdgeStrength: { value: 0 }
      },
      vertexShader: (
        /* glsl */
        `
				varying vec2 vUv;

				void main() {

					vUv = uv;
					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

				}
			`
      ),
      fragmentShader: (
        /* glsl */
        `
				uniform sampler2D tDiffuse;
				uniform sampler2D tDepth;
				uniform sampler2D tNormal;
				uniform vec4 resolution;
				uniform float normalEdgeStrength;
				uniform float depthEdgeStrength;
				varying vec2 vUv;

				float getDepth(int x, int y) {

					return texture2D( tDepth, vUv + vec2(x, y) * resolution.zw ).r;

				}

				vec3 getNormal(int x, int y) {

					return texture2D( tNormal, vUv + vec2(x, y) * resolution.zw ).rgb * 2.0 - 1.0;

				}

				float depthEdgeIndicator(float depth, vec3 normal) {

					float diff = 0.0;
					diff += clamp(getDepth(1, 0) - depth, 0.0, 1.0);
					diff += clamp(getDepth(-1, 0) - depth, 0.0, 1.0);
					diff += clamp(getDepth(0, 1) - depth, 0.0, 1.0);
					diff += clamp(getDepth(0, -1) - depth, 0.0, 1.0);
					return floor(smoothstep(0.01, 0.02, diff) * 2.) / 2.;

				}

				float neighborNormalEdgeIndicator(int x, int y, float depth, vec3 normal) {

					float depthDiff = getDepth(x, y) - depth;
					vec3 neighborNormal = getNormal(x, y);

					// Edge pixels should yield to faces who's normals are closer to the bias normal.
					vec3 normalEdgeBias = vec3(1., 1., 1.); // This should probably be a parameter.
					float normalDiff = dot(normal - neighborNormal, normalEdgeBias);
					float normalIndicator = clamp(smoothstep(-.01, .01, normalDiff), 0.0, 1.0);

					// Only the shallower pixel should detect the normal edge.
					float depthIndicator = clamp(sign(depthDiff * .25 + .0025), 0.0, 1.0);

					return (1.0 - dot(normal, neighborNormal)) * depthIndicator * normalIndicator;

				}

				float normalEdgeIndicator(float depth, vec3 normal) {

					float indicator = 0.0;

					indicator += neighborNormalEdgeIndicator(0, -1, depth, normal);
					indicator += neighborNormalEdgeIndicator(0, 1, depth, normal);
					indicator += neighborNormalEdgeIndicator(-1, 0, depth, normal);
					indicator += neighborNormalEdgeIndicator(1, 0, depth, normal);

					return step(0.1, indicator);

				}

				void main() {

					vec4 texel = texture2D( tDiffuse, vUv );

					float depth = 0.0;
					vec3 normal = vec3(0.0);

					if (depthEdgeStrength > 0.0 || normalEdgeStrength > 0.0) {

						depth = getDepth(0, 0);
						normal = getNormal(0, 0);

					}

					float dei = 0.0;
					if (depthEdgeStrength > 0.0)
						dei = depthEdgeIndicator(depth, normal);

					float nei = 0.0;
					if (normalEdgeStrength > 0.0)
						nei = normalEdgeIndicator(depth, normal);

					float Strength = dei > 0.0 ? (1.0 - depthEdgeStrength * dei) : (1.0 + normalEdgeStrength * nei);

					gl_FragColor = texel * Strength;

				}
			`
      )
    });
  }
};

// node_modules/three/examples/jsm/shaders/SAOShader.js
var SAOShader = {
  name: "SAOShader",
  defines: {
    "NUM_SAMPLES": 7,
    "NUM_RINGS": 4,
    "DIFFUSE_TEXTURE": 0,
    "PERSPECTIVE_CAMERA": 1
  },
  uniforms: {
    "tDepth": { value: null },
    "tDiffuse": { value: null },
    "tNormal": { value: null },
    "size": { value: new Vector2(512, 512) },
    "cameraNear": { value: 1 },
    "cameraFar": { value: 100 },
    "cameraProjectionMatrix": { value: new Matrix4() },
    "cameraInverseProjectionMatrix": { value: new Matrix4() },
    "scale": { value: 1 },
    "intensity": { value: 0.1 },
    "bias": { value: 0.5 },
    "minResolution": { value: 0 },
    "kernelRadius": { value: 100 },
    "randomSeed": { value: 0 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {
			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`
  ),
  fragmentShader: (
    /* glsl */
    `
		#include <common>

		varying vec2 vUv;

		#if DIFFUSE_TEXTURE == 1
		uniform sampler2D tDiffuse;
		#endif

		uniform highp sampler2D tDepth;
		uniform highp sampler2D tNormal;

		uniform float cameraNear;
		uniform float cameraFar;
		uniform mat4 cameraProjectionMatrix;
		uniform mat4 cameraInverseProjectionMatrix;

		uniform float scale;
		uniform float intensity;
		uniform float bias;
		uniform float kernelRadius;
		uniform float minResolution;
		uniform vec2 size;
		uniform float randomSeed;

		// RGBA depth

		#include <packing>

		vec4 getDefaultColor( const in vec2 screenPosition ) {
			#if DIFFUSE_TEXTURE == 1
			return texture2D( tDiffuse, vUv );
			#else
			return vec4( 1.0 );
			#endif
		}

		float getDepth( const in vec2 screenPosition ) {
			return texture2D( tDepth, screenPosition ).x;
		}

		float getViewZ( const in float depth ) {
			#if PERSPECTIVE_CAMERA == 1
			return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
			#else
			return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
			#endif
		}

		vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {
			float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];
			vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );
			clipPosition *= clipW; // unprojection.

			return ( cameraInverseProjectionMatrix * clipPosition ).xyz;
		}

		vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) {
			return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );
		}

		float scaleDividedByCameraFar;
		float minResolutionMultipliedByCameraFar;

		float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {
			vec3 viewDelta = sampleViewPosition - centerViewPosition;
			float viewDistance = length( viewDelta );
			float scaledScreenDistance = scaleDividedByCameraFar * viewDistance;

			return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) );
		}

		// moving costly divides into consts
		const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );
		const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );

		float getAmbientOcclusion( const in vec3 centerViewPosition ) {
			// precompute some variables require in getOcclusion.
			scaleDividedByCameraFar = scale / cameraFar;
			minResolutionMultipliedByCameraFar = minResolution * cameraFar;
			vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv );

			// jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/
			float angle = rand( vUv + randomSeed ) * PI2;
			vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size;
			vec2 radiusStep = radius;

			float occlusionSum = 0.0;
			float weightSum = 0.0;

			for( int i = 0; i < NUM_SAMPLES; i ++ ) {
				vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius;
				radius += radiusStep;
				angle += ANGLE_STEP;

				float sampleDepth = getDepth( sampleUv );
				if( sampleDepth >= ( 1.0 - EPSILON ) ) {
					continue;
				}

				float sampleViewZ = getViewZ( sampleDepth );
				vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ );
				occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );
				weightSum += 1.0;
			}

			if( weightSum == 0.0 ) discard;

			return occlusionSum * ( intensity / weightSum );
		}

		void main() {
			float centerDepth = getDepth( vUv );
			if( centerDepth >= ( 1.0 - EPSILON ) ) {
				discard;
			}

			float centerViewZ = getViewZ( centerDepth );
			vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ );

			float ambientOcclusion = getAmbientOcclusion( viewPosition );

			gl_FragColor = getDefaultColor( vUv );
			gl_FragColor.xyz *=  1.0 - ambientOcclusion;
		}`
  )
};

// node_modules/three/examples/jsm/shaders/DepthLimitedBlurShader.js
var DepthLimitedBlurShader = {
  name: "DepthLimitedBlurShader",
  defines: {
    "KERNEL_RADIUS": 4,
    "DEPTH_PACKING": 1,
    "PERSPECTIVE_CAMERA": 1
  },
  uniforms: {
    "tDiffuse": { value: null },
    "size": { value: new Vector2(512, 512) },
    "sampleUvOffsets": { value: [new Vector2(0, 0)] },
    "sampleWeights": { value: [1] },
    "tDepth": { value: null },
    "cameraNear": { value: 10 },
    "cameraFar": { value: 1e3 },
    "depthCutoff": { value: 10 }
  },
  vertexShader: (
    /* glsl */
    `

		#include <common>

		uniform vec2 size;

		varying vec2 vUv;
		varying vec2 vInvSize;

		void main() {
			vUv = uv;
			vInvSize = 1.0 / size;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`
  ),
  fragmentShader: (
    /* glsl */
    `

		#include <common>
		#include <packing>

		uniform sampler2D tDiffuse;
		uniform sampler2D tDepth;

		uniform float cameraNear;
		uniform float cameraFar;
		uniform float depthCutoff;

		uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ];
		uniform float sampleWeights[ KERNEL_RADIUS + 1 ];

		varying vec2 vUv;
		varying vec2 vInvSize;

		float getDepth( const in vec2 screenPosition ) {
			#if DEPTH_PACKING == 1
			return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) );
			#else
			return texture2D( tDepth, screenPosition ).x;
			#endif
		}

		float getViewZ( const in float depth ) {
			#if PERSPECTIVE_CAMERA == 1
			return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
			#else
			return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
			#endif
		}

		void main() {
			float depth = getDepth( vUv );
			if( depth >= ( 1.0 - EPSILON ) ) {
				discard;
			}

			float centerViewZ = -getViewZ( depth );
			bool rBreak = false, lBreak = false;

			float weightSum = sampleWeights[0];
			vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum;

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

				float sampleWeight = sampleWeights[i];
				vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize;

				vec2 sampleUv = vUv + sampleUvOffset;
				float viewZ = -getViewZ( getDepth( sampleUv ) );

				if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true;

				if( ! rBreak ) {
					diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;
					weightSum += sampleWeight;
				}

				sampleUv = vUv - sampleUvOffset;
				viewZ = -getViewZ( getDepth( sampleUv ) );

				if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true;

				if( ! lBreak ) {
					diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight;
					weightSum += sampleWeight;
				}

			}

			gl_FragColor = diffuseSum / weightSum;
		}`
  )
};
var BlurShaderUtils = {
  createSampleWeights: function(kernelRadius, stdDev) {
    const weights = [];
    for (let i = 0; i <= kernelRadius; i++) {
      weights.push(gaussian(i, stdDev));
    }
    return weights;
  },
  createSampleOffsets: function(kernelRadius, uvIncrement) {
    const offsets = [];
    for (let i = 0; i <= kernelRadius; i++) {
      offsets.push(uvIncrement.clone().multiplyScalar(i));
    }
    return offsets;
  },
  configure: function(material, kernelRadius, stdDev, uvIncrement) {
    material.defines["KERNEL_RADIUS"] = kernelRadius;
    material.uniforms["sampleUvOffsets"].value = BlurShaderUtils.createSampleOffsets(kernelRadius, uvIncrement);
    material.uniforms["sampleWeights"].value = BlurShaderUtils.createSampleWeights(kernelRadius, stdDev);
    material.needsUpdate = true;
  }
};
function gaussian(x2, stdDev) {
  return Math.exp(-(x2 * x2) / (2 * (stdDev * stdDev))) / (Math.sqrt(2 * Math.PI) * stdDev);
}

// node_modules/three/examples/jsm/postprocessing/SAOPass.js
var SAOPass = class _SAOPass extends Pass {
  /**
   * Constructs a new SAO pass.
   *
   * @param {Scene} scene - The scene to compute the AO for.
   * @param {Camera} camera - The camera.
   * @param {Vector2} [resolution] - The effect's resolution.
   */
  constructor(scene, camera, resolution = new Vector2(256, 256)) {
    super();
    this.scene = scene;
    this.camera = camera;
    this.clear = true;
    this.needsSwap = false;
    this._originalClearColor = new Color();
    this._oldClearColor = new Color();
    this._oldClearAlpha = 1;
    this.params = {
      output: 0,
      saoBias: 0.5,
      saoIntensity: 0.18,
      saoScale: 1,
      saoKernelRadius: 100,
      saoMinResolution: 0,
      saoBlur: true,
      saoBlurRadius: 8,
      saoBlurStdDev: 4,
      saoBlurDepthCutoff: 0.01
    };
    this.resolution = new Vector2(resolution.x, resolution.y);
    this.saoRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { type: HalfFloatType });
    this.blurIntermediateRenderTarget = this.saoRenderTarget.clone();
    const depthTexture = new DepthTexture();
    depthTexture.format = DepthStencilFormat;
    depthTexture.type = UnsignedInt248Type;
    this.normalRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, {
      minFilter: NearestFilter,
      magFilter: NearestFilter,
      type: HalfFloatType,
      depthTexture
    });
    this.normalMaterial = new MeshNormalMaterial();
    this.normalMaterial.blending = NoBlending;
    this.saoMaterial = new ShaderMaterial({
      defines: Object.assign({}, SAOShader.defines),
      fragmentShader: SAOShader.fragmentShader,
      vertexShader: SAOShader.vertexShader,
      uniforms: UniformsUtils.clone(SAOShader.uniforms)
    });
    this.saoMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0;
    this.saoMaterial.uniforms["tDepth"].value = depthTexture;
    this.saoMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture;
    this.saoMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y);
    this.saoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse);
    this.saoMaterial.uniforms["cameraProjectionMatrix"].value = this.camera.projectionMatrix;
    this.saoMaterial.blending = NoBlending;
    this.vBlurMaterial = new ShaderMaterial({
      uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms),
      defines: Object.assign({}, DepthLimitedBlurShader.defines),
      vertexShader: DepthLimitedBlurShader.vertexShader,
      fragmentShader: DepthLimitedBlurShader.fragmentShader
    });
    this.vBlurMaterial.defines["DEPTH_PACKING"] = 0;
    this.vBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0;
    this.vBlurMaterial.uniforms["tDiffuse"].value = this.saoRenderTarget.texture;
    this.vBlurMaterial.uniforms["tDepth"].value = depthTexture;
    this.vBlurMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y);
    this.vBlurMaterial.blending = NoBlending;
    this.hBlurMaterial = new ShaderMaterial({
      uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms),
      defines: Object.assign({}, DepthLimitedBlurShader.defines),
      vertexShader: DepthLimitedBlurShader.vertexShader,
      fragmentShader: DepthLimitedBlurShader.fragmentShader
    });
    this.hBlurMaterial.defines["DEPTH_PACKING"] = 0;
    this.hBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0;
    this.hBlurMaterial.uniforms["tDiffuse"].value = this.blurIntermediateRenderTarget.texture;
    this.hBlurMaterial.uniforms["tDepth"].value = depthTexture;
    this.hBlurMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y);
    this.hBlurMaterial.blending = NoBlending;
    this.materialCopy = new ShaderMaterial({
      uniforms: UniformsUtils.clone(CopyShader.uniforms),
      vertexShader: CopyShader.vertexShader,
      fragmentShader: CopyShader.fragmentShader,
      blending: NoBlending
    });
    this.materialCopy.transparent = true;
    this.materialCopy.depthTest = false;
    this.materialCopy.depthWrite = false;
    this.materialCopy.blending = CustomBlending;
    this.materialCopy.blendSrc = DstColorFactor;
    this.materialCopy.blendDst = ZeroFactor;
    this.materialCopy.blendEquation = AddEquation;
    this.materialCopy.blendSrcAlpha = DstAlphaFactor;
    this.materialCopy.blendDstAlpha = ZeroFactor;
    this.materialCopy.blendEquationAlpha = AddEquation;
    this.fsQuad = new FullScreenQuad(null);
  }
  /**
   * Performs the SAO pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    if (this.renderToScreen) {
      this.materialCopy.blending = NoBlending;
      this.materialCopy.uniforms["tDiffuse"].value = readBuffer.texture;
      this.materialCopy.needsUpdate = true;
      this._renderPass(renderer2, this.materialCopy, null);
    }
    renderer2.getClearColor(this._oldClearColor);
    this._oldClearAlpha = renderer2.getClearAlpha();
    const oldAutoClear = renderer2.autoClear;
    renderer2.autoClear = false;
    this.saoMaterial.uniforms["bias"].value = this.params.saoBias;
    this.saoMaterial.uniforms["intensity"].value = this.params.saoIntensity;
    this.saoMaterial.uniforms["scale"].value = this.params.saoScale;
    this.saoMaterial.uniforms["kernelRadius"].value = this.params.saoKernelRadius;
    this.saoMaterial.uniforms["minResolution"].value = this.params.saoMinResolution;
    this.saoMaterial.uniforms["cameraNear"].value = this.camera.near;
    this.saoMaterial.uniforms["cameraFar"].value = this.camera.far;
    const depthCutoff = this.params.saoBlurDepthCutoff * (this.camera.far - this.camera.near);
    this.vBlurMaterial.uniforms["depthCutoff"].value = depthCutoff;
    this.hBlurMaterial.uniforms["depthCutoff"].value = depthCutoff;
    this.vBlurMaterial.uniforms["cameraNear"].value = this.camera.near;
    this.vBlurMaterial.uniforms["cameraFar"].value = this.camera.far;
    this.hBlurMaterial.uniforms["cameraNear"].value = this.camera.near;
    this.hBlurMaterial.uniforms["cameraFar"].value = this.camera.far;
    this.params.saoBlurRadius = Math.floor(this.params.saoBlurRadius);
    if (this.prevStdDev !== this.params.saoBlurStdDev || this.prevNumSamples !== this.params.saoBlurRadius) {
      BlurShaderUtils.configure(this.vBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(0, 1));
      BlurShaderUtils.configure(this.hBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(1, 0));
      this.prevStdDev = this.params.saoBlurStdDev;
      this.prevNumSamples = this.params.saoBlurRadius;
    }
    this._renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1);
    this._renderPass(renderer2, this.saoMaterial, this.saoRenderTarget, 16777215, 1);
    if (this.params.saoBlur) {
      this._renderPass(renderer2, this.vBlurMaterial, this.blurIntermediateRenderTarget, 16777215, 1);
      this._renderPass(renderer2, this.hBlurMaterial, this.saoRenderTarget, 16777215, 1);
    }
    const outputMaterial = this.materialCopy;
    if (this.params.output === _SAOPass.OUTPUT.Normal) {
      this.materialCopy.uniforms["tDiffuse"].value = this.normalRenderTarget.texture;
      this.materialCopy.needsUpdate = true;
    } else {
      this.materialCopy.uniforms["tDiffuse"].value = this.saoRenderTarget.texture;
      this.materialCopy.needsUpdate = true;
    }
    if (this.params.output === _SAOPass.OUTPUT.Default) {
      outputMaterial.blending = CustomBlending;
    } else {
      outputMaterial.blending = NoBlending;
    }
    this._renderPass(renderer2, outputMaterial, this.renderToScreen ? null : readBuffer);
    renderer2.setClearColor(this._oldClearColor, this._oldClearAlpha);
    renderer2.autoClear = oldAutoClear;
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this.saoRenderTarget.setSize(width2, height2);
    this.blurIntermediateRenderTarget.setSize(width2, height2);
    this.normalRenderTarget.setSize(width2, height2);
    this.saoMaterial.uniforms["size"].value.set(width2, height2);
    this.saoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse);
    this.saoMaterial.uniforms["cameraProjectionMatrix"].value = this.camera.projectionMatrix;
    this.saoMaterial.needsUpdate = true;
    this.vBlurMaterial.uniforms["size"].value.set(width2, height2);
    this.vBlurMaterial.needsUpdate = true;
    this.hBlurMaterial.uniforms["size"].value.set(width2, height2);
    this.hBlurMaterial.needsUpdate = true;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.saoRenderTarget.dispose();
    this.blurIntermediateRenderTarget.dispose();
    this.normalRenderTarget.dispose();
    this.normalMaterial.dispose();
    this.saoMaterial.dispose();
    this.vBlurMaterial.dispose();
    this.hBlurMaterial.dispose();
    this.materialCopy.dispose();
    this.fsQuad.dispose();
  }
  // internal
  _renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) {
    renderer2.getClearColor(this._originalClearColor);
    const originalClearAlpha = renderer2.getClearAlpha();
    const originalAutoClear = renderer2.autoClear;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this.fsQuad.material = passMaterial;
    this.fsQuad.render(renderer2);
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this._originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
  }
  _renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) {
    renderer2.getClearColor(this._originalClearColor);
    const originalClearAlpha = renderer2.getClearAlpha();
    const originalAutoClear = renderer2.autoClear;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    clearColor = overrideMaterial.clearColor || clearColor;
    clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this.scene.overrideMaterial = overrideMaterial;
    renderer2.render(this.scene, this.camera);
    this.scene.overrideMaterial = null;
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this._originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
  }
};
SAOPass.OUTPUT = {
  "Default": 0,
  "SAO": 1,
  "Normal": 2
};

// node_modules/three/examples/jsm/shaders/SMAAShader.js
var SMAAEdgesShader = {
  name: "SMAAEdgesShader",
  defines: {
    "SMAA_THRESHOLD": "0.1"
  },
  uniforms: {
    "tDiffuse": { value: null },
    "resolution": { value: new Vector2(1 / 1024, 1 / 512) }
  },
  vertexShader: (
    /* glsl */
    `

		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[ 3 ];

		void SMAAEdgeDetectionVS( vec2 texcoord ) {
			vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0,  1.0 ); // WebGL port note: Changed sign in W component
			vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4(  1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
			vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0,  2.0 ); // WebGL port note: Changed sign in W component
		}

		void main() {

			vUv = uv;

			SMAAEdgeDetectionVS( vUv );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;

		varying vec2 vUv;
		varying vec4 vOffset[ 3 ];

		vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) {
			vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD );

			// Calculate color deltas:
			vec4 delta;
			vec3 C = texture2D( colorTex, texcoord ).rgb;

			vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb;
			vec3 t = abs( C - Cleft );
			delta.x = max( max( t.r, t.g ), t.b );

			vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb;
			t = abs( C - Ctop );
			delta.y = max( max( t.r, t.g ), t.b );

			// We do the usual threshold:
			vec2 edges = step( threshold, delta.xy );

			// Then discard if there is no edge:
			if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 )
				discard;

			// Calculate right and bottom deltas:
			vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb;
			t = abs( C - Cright );
			delta.z = max( max( t.r, t.g ), t.b );

			vec3 Cbottom  = texture2D( colorTex, offset[1].zw ).rgb;
			t = abs( C - Cbottom );
			delta.w = max( max( t.r, t.g ), t.b );

			// Calculate the maximum delta in the direct neighborhood:
			float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w );

			// Calculate left-left and top-top deltas:
			vec3 Cleftleft  = texture2D( colorTex, offset[2].xy ).rgb;
			t = abs( C - Cleftleft );
			delta.z = max( max( t.r, t.g ), t.b );

			vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb;
			t = abs( C - Ctoptop );
			delta.w = max( max( t.r, t.g ), t.b );

			// Calculate the final maximum delta:
			maxDelta = max( max( maxDelta, delta.z ), delta.w );

			// Local contrast adaptation in action:
			edges.xy *= step( 0.5 * maxDelta, delta.xy );

			return vec4( edges, 0.0, 0.0 );
		}

		void main() {

			gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse );

		}`
  )
};
var SMAAWeightsShader = {
  name: "SMAAWeightsShader",
  defines: {
    "SMAA_MAX_SEARCH_STEPS": "8",
    "SMAA_AREATEX_MAX_DISTANCE": "16",
    "SMAA_AREATEX_PIXEL_SIZE": "( 1.0 / vec2( 160.0, 560.0 ) )",
    "SMAA_AREATEX_SUBTEX_SIZE": "( 1.0 / 7.0 )"
  },
  uniforms: {
    "tDiffuse": { value: null },
    "tArea": { value: null },
    "tSearch": { value: null },
    "resolution": { value: new Vector2(1 / 1024, 1 / 512) }
  },
  vertexShader: (
    /* glsl */
    `

		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[ 3 ];
		varying vec2 vPixcoord;

		void SMAABlendingWeightCalculationVS( vec2 texcoord ) {
			vPixcoord = texcoord / resolution;

			// We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
			vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components
			vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components

			// And these for the searches, they indicate the ends of the loops:
			vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS );

		}

		void main() {

			vUv = uv;

			SMAABlendingWeightCalculationVS( vUv );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		#define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 )

		uniform sampler2D tDiffuse;
		uniform sampler2D tArea;
		uniform sampler2D tSearch;
		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[3];
		varying vec2 vPixcoord;

		#if __VERSION__ == 100
		vec2 round( vec2 x ) {
			return sign( x ) * floor( abs( x ) + 0.5 );
		}
		#endif

		float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) {
			// Not required if searchTex accesses are set to point:
			// float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0);
			// e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE +
			//     e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE;
			e.r = bias + e.r * scale;
			return 255.0 * texture2D( searchTex, e, 0.0 ).r;
		}

		float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
			/**
				* @PSEUDO_GATHER4
				* This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
				* sample between edge, thus fetching four edges in a row.
				* Sampling with different offsets in each direction allows to disambiguate
				* which edges are active from the four fetched ones.
				*/
			vec2 e = vec2( 0.0, 1.0 );

			for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
				e = texture2D( edgesTex, texcoord, 0.0 ).rg;
				texcoord -= vec2( 2.0, 0.0 ) * resolution;
				if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break;
			}

			// We correct the previous (-0.25, -0.125) offset we applied:
			texcoord.x += 0.25 * resolution.x;

			// The searches are bias by 1, so adjust the coords accordingly:
			texcoord.x += resolution.x;

			// Disambiguate the length added by the last step:
			texcoord.x += 2.0 * resolution.x; // Undo last step
			texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5);

			return texcoord.x;
		}

		float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
			vec2 e = vec2( 0.0, 1.0 );

			for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
				e = texture2D( edgesTex, texcoord, 0.0 ).rg;
				texcoord += vec2( 2.0, 0.0 ) * resolution;
				if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break;
			}

			texcoord.x -= 0.25 * resolution.x;
			texcoord.x -= resolution.x;
			texcoord.x -= 2.0 * resolution.x;
			texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 );

			return texcoord.x;
		}

		float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
			vec2 e = vec2( 1.0, 0.0 );

			for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
				e = texture2D( edgesTex, texcoord, 0.0 ).rg;
				texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
				if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break;
			}

			texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign
			texcoord.y -= resolution.y; // WebGL port note: Changed sign
			texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign
			texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign

			return texcoord.y;
		}

		float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
			vec2 e = vec2( 1.0, 0.0 );

			for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
				e = texture2D( edgesTex, texcoord, 0.0 ).rg;
				texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
				if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break;
			}

			texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign
			texcoord.y += resolution.y; // WebGL port note: Changed sign
			texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign
			texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign

			return texcoord.y;
		}

		vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) {
			// Rounding prevents precision errors of bilinear filtering:
			vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist;

			// We do a scale and bias for mapping to texel space:
			texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE );

			// Move to proper place, according to the subpixel offset:
			texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;

			return texture2D( areaTex, texcoord, 0.0 ).rg;
		}

		vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) {
			vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 );

			vec2 e = texture2D( edgesTex, texcoord ).rg;

			if ( e.g > 0.0 ) { // Edge at north
				vec2 d;

				// Find the distance to the left:
				vec2 coords;
				coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x );
				coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET)
				d.x = coords.x;

				// Now fetch the left crossing edges, two at a time using bilinear
				// filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
				// discern what value each edge has:
				float e1 = texture2D( edgesTex, coords, 0.0 ).r;

				// Find the distance to the right:
				coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y );
				d.y = coords.x;

				// We want the distances to be in pixel units (doing this here allow to
				// better interleave arithmetic and memory accesses):
				d = d / resolution.x - pixcoord.x;

				// SMAAArea below needs a sqrt, as the areas texture is compressed
				// quadratically:
				vec2 sqrt_d = sqrt( abs( d ) );

				// Fetch the right crossing edges:
				coords.y -= 1.0 * resolution.y; // WebGL port note: Added
				float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r;

				// Ok, we know how this pattern looks like, now it is time for getting
				// the actual area:
				weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) );
			}

			if ( e.r > 0.0 ) { // Edge at west
				vec2 d;

				// Find the distance to the top:
				vec2 coords;

				coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z );
				coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x;
				d.x = coords.y;

				// Fetch the top crossing edges:
				float e1 = texture2D( edgesTex, coords, 0.0 ).g;

				// Find the distance to the bottom:
				coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w );
				d.y = coords.y;

				// We want the distances to be in pixel units:
				d = d / resolution.y - pixcoord.y;

				// SMAAArea below needs a sqrt, as the areas texture is compressed
				// quadratically:
				vec2 sqrt_d = sqrt( abs( d ) );

				// Fetch the bottom crossing edges:
				coords.y -= 1.0 * resolution.y; // WebGL port note: Added
				float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g;

				// Get the area for this direction:
				weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) );
			}

			return weights;
		}

		void main() {

			gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) );

		}`
  )
};
var SMAABlendShader = {
  name: "SMAABlendShader",
  uniforms: {
    "tDiffuse": { value: null },
    "tColor": { value: null },
    "resolution": { value: new Vector2(1 / 1024, 1 / 512) }
  },
  vertexShader: (
    /* glsl */
    `

		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[ 2 ];

		void SMAANeighborhoodBlendingVS( vec2 texcoord ) {
			vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component
			vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
		}

		void main() {

			vUv = uv;

			SMAANeighborhoodBlendingVS( vUv );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform sampler2D tColor;
		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[ 2 ];

		vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {
			// Fetch the blending weights for current pixel:
			vec4 a;
			a.xz = texture2D( blendTex, texcoord ).xz;
			a.y = texture2D( blendTex, offset[ 1 ].zw ).g;
			a.w = texture2D( blendTex, offset[ 1 ].xy ).a;

			// Is there any blending weight with a value greater than 0.0?
			if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {
				return texture2D( colorTex, texcoord, 0.0 );
			} else {
				// Up to 4 lines can be crossing a pixel (one through each edge). We
				// favor blending by choosing the line with the maximum weight for each
				// direction:
				vec2 offset;
				offset.x = a.a > a.b ? a.a : -a.b; // left vs. right
				offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs

				// Then we go in the direction that has the maximum weight:
				if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical
					offset.y = 0.0;
				} else {
					offset.x = 0.0;
				}

				// Fetch the opposite color and lerp by hand:
				vec4 C = texture2D( colorTex, texcoord, 0.0 );
				texcoord += sign( offset ) * resolution;
				vec4 Cop = texture2D( colorTex, texcoord, 0.0 );
				float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );

				// WebGL port note: Added gamma correction
				C.xyz = pow(C.xyz, vec3(2.2));
				Cop.xyz = pow(Cop.xyz, vec3(2.2));
				vec4 mixed = mix(C, Cop, s);
				mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));

				return mixed;
			}
		}

		void main() {

			gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse );

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/SMAAPass.js
var SMAAPass = class extends Pass {
  /**
   * Constructs a new SMAA pass.
   */
  constructor() {
    super();
    this._edgesRT = new WebGLRenderTarget(1, 1, {
      depthBuffer: false,
      type: HalfFloatType
    });
    this._edgesRT.texture.name = "SMAAPass.edges";
    this._weightsRT = new WebGLRenderTarget(1, 1, {
      depthBuffer: false,
      type: HalfFloatType
    });
    this._weightsRT.texture.name = "SMAAPass.weights";
    const scope = this;
    const areaTextureImage = new Image();
    areaTextureImage.src = this._getAreaTexture();
    areaTextureImage.onload = function() {
      scope._areaTexture.needsUpdate = true;
    };
    this._areaTexture = new Texture();
    this._areaTexture.name = "SMAAPass.area";
    this._areaTexture.image = areaTextureImage;
    this._areaTexture.minFilter = LinearFilter;
    this._areaTexture.generateMipmaps = false;
    this._areaTexture.flipY = false;
    const searchTextureImage = new Image();
    searchTextureImage.src = this._getSearchTexture();
    searchTextureImage.onload = function() {
      scope._searchTexture.needsUpdate = true;
    };
    this._searchTexture = new Texture();
    this._searchTexture.name = "SMAAPass.search";
    this._searchTexture.image = searchTextureImage;
    this._searchTexture.magFilter = NearestFilter;
    this._searchTexture.minFilter = NearestFilter;
    this._searchTexture.generateMipmaps = false;
    this._searchTexture.flipY = false;
    this._uniformsEdges = UniformsUtils.clone(SMAAEdgesShader.uniforms);
    this._materialEdges = new ShaderMaterial({
      defines: Object.assign({}, SMAAEdgesShader.defines),
      uniforms: this._uniformsEdges,
      vertexShader: SMAAEdgesShader.vertexShader,
      fragmentShader: SMAAEdgesShader.fragmentShader
    });
    this._uniformsWeights = UniformsUtils.clone(SMAAWeightsShader.uniforms);
    this._uniformsWeights["tDiffuse"].value = this._edgesRT.texture;
    this._uniformsWeights["tArea"].value = this._areaTexture;
    this._uniformsWeights["tSearch"].value = this._searchTexture;
    this._materialWeights = new ShaderMaterial({
      defines: Object.assign({}, SMAAWeightsShader.defines),
      uniforms: this._uniformsWeights,
      vertexShader: SMAAWeightsShader.vertexShader,
      fragmentShader: SMAAWeightsShader.fragmentShader
    });
    this._uniformsBlend = UniformsUtils.clone(SMAABlendShader.uniforms);
    this._uniformsBlend["tDiffuse"].value = this._weightsRT.texture;
    this._materialBlend = new ShaderMaterial({
      uniforms: this._uniformsBlend,
      vertexShader: SMAABlendShader.vertexShader,
      fragmentShader: SMAABlendShader.fragmentShader
    });
    this._fsQuad = new FullScreenQuad(null);
  }
  /**
   * Performs the SMAA pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this._uniformsEdges["tDiffuse"].value = readBuffer.texture;
    this._fsQuad.material = this._materialEdges;
    renderer2.setRenderTarget(this._edgesRT);
    if (this.clear) renderer2.clear();
    this._fsQuad.render(renderer2);
    this._fsQuad.material = this._materialWeights;
    renderer2.setRenderTarget(this._weightsRT);
    if (this.clear) renderer2.clear();
    this._fsQuad.render(renderer2);
    this._uniformsBlend["tColor"].value = readBuffer.texture;
    this._fsQuad.material = this._materialBlend;
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(writeBuffer);
      if (this.clear) renderer2.clear();
      this._fsQuad.render(renderer2);
    }
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this._edgesRT.setSize(width2, height2);
    this._weightsRT.setSize(width2, height2);
    this._materialEdges.uniforms["resolution"].value.set(1 / width2, 1 / height2);
    this._materialWeights.uniforms["resolution"].value.set(1 / width2, 1 / height2);
    this._materialBlend.uniforms["resolution"].value.set(1 / width2, 1 / height2);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this._edgesRT.dispose();
    this._weightsRT.dispose();
    this._areaTexture.dispose();
    this._searchTexture.dispose();
    this._materialEdges.dispose();
    this._materialWeights.dispose();
    this._materialBlend.dispose();
    this._fsQuad.dispose();
  }
  // internals
  _getAreaTexture() {
    return "data:image/png;base64,[encoded data, 44272 characters]";
  }
  _getSearchTexture() {
    return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAhCAAAAABIXyLAAAAAOElEQVRIx2NgGAWjYBSMglEwEICREYRgFBZBqDCSLA2MGPUIVQETE9iNUAqLR5gIeoQKRgwXjwAAGn4AtaFeYLEAAAAASUVORK5CYII=";
  }
};

// node_modules/three/examples/jsm/postprocessing/SSAARenderPass.js
var SSAARenderPass = class extends Pass {
  /**
   * Constructs a new SSAA render pass.
   *
   * @param {Scene} scene - The scene to render.
   * @param {Camera} camera - The camera.
   * @param {?(number|Color|string)} [clearColor=0x000000] - The clear color of the render pass.
   * @param {?number} [clearAlpha=0] - The clear alpha of the render pass.
   */
  constructor(scene, camera, clearColor = 0, clearAlpha = 0) {
    super();
    this.scene = scene;
    this.camera = camera;
    this.sampleLevel = 4;
    this.unbiased = true;
    this.stencilBuffer = false;
    this.clearColor = clearColor;
    this.clearAlpha = clearAlpha;
    this._sampleRenderTarget = null;
    this._oldClearColor = new Color();
    this._copyUniforms = UniformsUtils.clone(CopyShader.uniforms);
    this._copyMaterial = new ShaderMaterial({
      uniforms: this._copyUniforms,
      vertexShader: CopyShader.vertexShader,
      fragmentShader: CopyShader.fragmentShader,
      transparent: true,
      depthTest: false,
      depthWrite: false,
      premultipliedAlpha: true,
      blending: AdditiveBlending
    });
    this._fsQuad = new FullScreenQuad(this._copyMaterial);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    if (this._sampleRenderTarget) {
      this._sampleRenderTarget.dispose();
      this._sampleRenderTarget = null;
    }
    this._copyMaterial.dispose();
    this._fsQuad.dispose();
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    if (this._sampleRenderTarget) this._sampleRenderTarget.setSize(width2, height2);
  }
  /**
   * Performs the SSAA render pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    if (!this._sampleRenderTarget) {
      this._sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { type: HalfFloatType, stencilBuffer: this.stencilBuffer });
      this._sampleRenderTarget.texture.name = "SSAARenderPass.sample";
    }
    const jitterOffsets = _JitterVectors[Math.max(0, Math.min(this.sampleLevel, 5))];
    const autoClear = renderer2.autoClear;
    renderer2.autoClear = false;
    renderer2.getClearColor(this._oldClearColor);
    const oldClearAlpha = renderer2.getClearAlpha();
    const baseSampleWeight = 1 / jitterOffsets.length;
    const roundingRange = 1 / 32;
    this._copyUniforms["tDiffuse"].value = this._sampleRenderTarget.texture;
    const viewOffset = {
      fullWidth: readBuffer.width,
      fullHeight: readBuffer.height,
      offsetX: 0,
      offsetY: 0,
      width: readBuffer.width,
      height: readBuffer.height
    };
    const originalViewOffset = Object.assign({}, this.camera.view);
    if (originalViewOffset.enabled) Object.assign(viewOffset, originalViewOffset);
    for (let i = 0; i < jitterOffsets.length; i++) {
      const jitterOffset = jitterOffsets[i];
      if (this.camera.setViewOffset) {
        this.camera.setViewOffset(
          viewOffset.fullWidth,
          viewOffset.fullHeight,
          viewOffset.offsetX + jitterOffset[0] * 0.0625,
          viewOffset.offsetY + jitterOffset[1] * 0.0625,
          // 0.0625 = 1 / 16
          viewOffset.width,
          viewOffset.height
        );
      }
      let sampleWeight = baseSampleWeight;
      if (this.unbiased) {
        const uniformCenteredDistribution = -0.5 + (i + 0.5) / jitterOffsets.length;
        sampleWeight += roundingRange * uniformCenteredDistribution;
      }
      this._copyUniforms["opacity"].value = sampleWeight;
      renderer2.setClearColor(this.clearColor, this.clearAlpha);
      renderer2.setRenderTarget(this._sampleRenderTarget);
      renderer2.clear();
      renderer2.render(this.scene, this.camera);
      renderer2.setRenderTarget(this.renderToScreen ? null : writeBuffer);
      if (i === 0) {
        renderer2.setClearColor(0, 0);
        renderer2.clear();
      }
      this._fsQuad.render(renderer2);
    }
    if (this.camera.setViewOffset && originalViewOffset.enabled) {
      this.camera.setViewOffset(
        originalViewOffset.fullWidth,
        originalViewOffset.fullHeight,
        originalViewOffset.offsetX,
        originalViewOffset.offsetY,
        originalViewOffset.width,
        originalViewOffset.height
      );
    } else if (this.camera.clearViewOffset) {
      this.camera.clearViewOffset();
    }
    renderer2.autoClear = autoClear;
    renderer2.setClearColor(this._oldClearColor, oldClearAlpha);
  }
};
var _JitterVectors = [
  [
    [0, 0]
  ],
  [
    [4, 4],
    [-4, -4]
  ],
  [
    [-2, -6],
    [6, -2],
    [-6, 2],
    [2, 6]
  ],
  [
    [1, -3],
    [-1, 3],
    [5, 1],
    [-3, -5],
    [-5, 5],
    [-7, -1],
    [3, 7],
    [7, -7]
  ],
  [
    [1, 1],
    [-1, -3],
    [-3, 2],
    [4, -1],
    [-5, -2],
    [2, 5],
    [5, 3],
    [3, -5],
    [-2, 6],
    [0, -7],
    [-4, -6],
    [-6, 4],
    [-8, 0],
    [7, -4],
    [6, 7],
    [-7, -8]
  ],
  [
    [-4, -7],
    [-7, -5],
    [-3, -5],
    [-5, -4],
    [-1, -4],
    [-2, -2],
    [-6, -1],
    [-4, 0],
    [-7, 1],
    [-1, 2],
    [-6, 3],
    [-3, 3],
    [-7, 6],
    [-3, 6],
    [-5, 7],
    [-1, 7],
    [5, -7],
    [1, -6],
    [6, -5],
    [4, -4],
    [2, -3],
    [7, -2],
    [1, -1],
    [4, -1],
    [2, 1],
    [6, 2],
    [0, 4],
    [4, 4],
    [2, 5],
    [7, 5],
    [5, 6],
    [3, 7]
  ]
];

// node_modules/three/examples/jsm/shaders/SSAOShader.js
var SSAOShader = {
  name: "SSAOShader",
  defines: {
    "PERSPECTIVE_CAMERA": 1,
    "KERNEL_SIZE": 32
  },
  uniforms: {
    "tNormal": { value: null },
    "tDepth": { value: null },
    "tNoise": { value: null },
    "kernel": { value: null },
    "cameraNear": { value: null },
    "cameraFar": { value: null },
    "resolution": { value: new Vector2() },
    "cameraProjectionMatrix": { value: new Matrix4() },
    "cameraInverseProjectionMatrix": { value: new Matrix4() },
    "kernelRadius": { value: 8 },
    "minDistance": { value: 5e-3 },
    "maxDistance": { value: 0.05 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`
  ),
  fragmentShader: (
    /* glsl */
    `
		uniform highp sampler2D tNormal;
		uniform highp sampler2D tDepth;
		uniform sampler2D tNoise;

		uniform vec3 kernel[ KERNEL_SIZE ];

		uniform vec2 resolution;

		uniform float cameraNear;
		uniform float cameraFar;
		uniform mat4 cameraProjectionMatrix;
		uniform mat4 cameraInverseProjectionMatrix;

		uniform float kernelRadius;
		uniform float minDistance; // avoid artifacts caused by neighbour fragments with minimal depth difference
		uniform float maxDistance; // avoid the influence of fragments which are too far away

		varying vec2 vUv;

		#include <packing>

		float getDepth( const in vec2 screenPosition ) {

			return texture2D( tDepth, screenPosition ).x;

		}

		float getLinearDepth( const in vec2 screenPosition ) {

			#if PERSPECTIVE_CAMERA == 1

				float fragCoordZ = texture2D( tDepth, screenPosition ).x;
				float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
				return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );

			#else

				return texture2D( tDepth, screenPosition ).x;

			#endif

		}

		float getViewZ( const in float depth ) {

			#if PERSPECTIVE_CAMERA == 1

				return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );

			#else

				return orthographicDepthToViewZ( depth, cameraNear, cameraFar );

			#endif

		}

		vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) {

			float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3];

			vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 );

			clipPosition *= clipW; // unprojection.

			return ( cameraInverseProjectionMatrix * clipPosition ).xyz;

		}

		vec3 getViewNormal( const in vec2 screenPosition ) {

			return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz );

		}

		void main() {

			float depth = getDepth( vUv );

			if ( depth == 1.0 ) {

				gl_FragColor = vec4( 1.0 ); // don't influence background

			} else {

				float viewZ = getViewZ( depth );

				vec3 viewPosition = getViewPosition( vUv, depth, viewZ );
				vec3 viewNormal = getViewNormal( vUv );

				vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 );
				vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r );

				// compute matrix used to reorient a kernel vector

				vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) );
				vec3 bitangent = cross( viewNormal, tangent );
				mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal );

				float occlusion = 0.0;

				for ( int i = 0; i < KERNEL_SIZE; i ++ ) {

					vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space
					vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point

					vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC
					samplePointNDC /= samplePointNDC.w;

					vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates

					float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture
					float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value
					float delta = sampleDepth - realDepth;

					if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion

						occlusion += 1.0;

					}

				}

				occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 );

				gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 );

			}

		}`
  )
};
var SSAODepthShader = {
  name: "SSAODepthShader",
  defines: {
    "PERSPECTIVE_CAMERA": 1
  },
  uniforms: {
    "tDepth": { value: null },
    "cameraNear": { value: null },
    "cameraFar": { value: null }
  },
  vertexShader: `varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,
  fragmentShader: `uniform sampler2D tDepth;

		uniform float cameraNear;
		uniform float cameraFar;

		varying vec2 vUv;

		#include <packing>

		float getLinearDepth( const in vec2 screenPosition ) {

			#if PERSPECTIVE_CAMERA == 1

				float fragCoordZ = texture2D( tDepth, screenPosition ).x;
				float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
				return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );

			#else

				return texture2D( tDepth, screenPosition ).x;

			#endif

		}

		void main() {

			float depth = getLinearDepth( vUv );
			gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );

		}`
};
var SSAOBlurShader = {
  name: "SSAOBlurShader",
  uniforms: {
    "tDiffuse": { value: null },
    "resolution": { value: new Vector2() }
  },
  vertexShader: `varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,
  fragmentShader: `uniform sampler2D tDiffuse;

		uniform vec2 resolution;

		varying vec2 vUv;

		void main() {

			vec2 texelSize = ( 1.0 / resolution );
			float result = 0.0;

			for ( int i = - 2; i <= 2; i ++ ) {

				for ( int j = - 2; j <= 2; j ++ ) {

					vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize;
					result += texture2D( tDiffuse, vUv + offset ).r;

				}

			}

			gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 );

		}`
};

// node_modules/three/examples/jsm/postprocessing/SSAOPass.js
var SSAOPass = class _SSAOPass extends Pass {
  /**
   * Constructs a new SSAO pass.
   *
   * @param {Scene} scene - The scene to compute the AO for.
   * @param {Camera} camera - The camera.
   * @param {number} [width=512] - The width of the effect.
   * @param {number} [height=512] - The height of the effect.
   * @param {number} [kernelSize=32] - The kernel size.
   */
  constructor(scene, camera, width2 = 512, height2 = 512, kernelSize = 32) {
    super();
    this.width = width2;
    this.height = height2;
    this.clear = true;
    this.needsSwap = false;
    this.camera = camera;
    this.scene = scene;
    this.kernelRadius = 8;
    this.kernel = [];
    this.noiseTexture = null;
    this.output = 0;
    this.minDistance = 5e-3;
    this.maxDistance = 0.1;
    this._visibilityCache = /* @__PURE__ */ new Map();
    this._generateSampleKernel(kernelSize);
    this._generateRandomKernelRotations();
    const depthTexture = new DepthTexture();
    depthTexture.format = DepthStencilFormat;
    depthTexture.type = UnsignedInt248Type;
    this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, {
      minFilter: NearestFilter,
      magFilter: NearestFilter,
      type: HalfFloatType,
      depthTexture
    });
    this.ssaoRenderTarget = new WebGLRenderTarget(this.width, this.height, { type: HalfFloatType });
    this.blurRenderTarget = this.ssaoRenderTarget.clone();
    this.ssaoMaterial = new ShaderMaterial({
      defines: Object.assign({}, SSAOShader.defines),
      uniforms: UniformsUtils.clone(SSAOShader.uniforms),
      vertexShader: SSAOShader.vertexShader,
      fragmentShader: SSAOShader.fragmentShader,
      blending: NoBlending
    });
    this.ssaoMaterial.defines["KERNEL_SIZE"] = kernelSize;
    this.ssaoMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture;
    this.ssaoMaterial.uniforms["tDepth"].value = this.normalRenderTarget.depthTexture;
    this.ssaoMaterial.uniforms["tNoise"].value = this.noiseTexture;
    this.ssaoMaterial.uniforms["kernel"].value = this.kernel;
    this.ssaoMaterial.uniforms["cameraNear"].value = this.camera.near;
    this.ssaoMaterial.uniforms["cameraFar"].value = this.camera.far;
    this.ssaoMaterial.uniforms["resolution"].value.set(this.width, this.height);
    this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix);
    this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse);
    this.normalMaterial = new MeshNormalMaterial();
    this.normalMaterial.blending = NoBlending;
    this.blurMaterial = new ShaderMaterial({
      defines: Object.assign({}, SSAOBlurShader.defines),
      uniforms: UniformsUtils.clone(SSAOBlurShader.uniforms),
      vertexShader: SSAOBlurShader.vertexShader,
      fragmentShader: SSAOBlurShader.fragmentShader
    });
    this.blurMaterial.uniforms["tDiffuse"].value = this.ssaoRenderTarget.texture;
    this.blurMaterial.uniforms["resolution"].value.set(this.width, this.height);
    this.depthRenderMaterial = new ShaderMaterial({
      defines: Object.assign({}, SSAODepthShader.defines),
      uniforms: UniformsUtils.clone(SSAODepthShader.uniforms),
      vertexShader: SSAODepthShader.vertexShader,
      fragmentShader: SSAODepthShader.fragmentShader,
      blending: NoBlending
    });
    this.depthRenderMaterial.uniforms["tDepth"].value = this.normalRenderTarget.depthTexture;
    this.depthRenderMaterial.uniforms["cameraNear"].value = this.camera.near;
    this.depthRenderMaterial.uniforms["cameraFar"].value = this.camera.far;
    this.copyMaterial = new ShaderMaterial({
      uniforms: UniformsUtils.clone(CopyShader.uniforms),
      vertexShader: CopyShader.vertexShader,
      fragmentShader: CopyShader.fragmentShader,
      transparent: true,
      depthTest: false,
      depthWrite: false,
      blendSrc: DstColorFactor,
      blendDst: ZeroFactor,
      blendEquation: AddEquation,
      blendSrcAlpha: DstAlphaFactor,
      blendDstAlpha: ZeroFactor,
      blendEquationAlpha: AddEquation
    });
    this._fsQuad = new FullScreenQuad(null);
    this._originalClearColor = new Color();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.normalRenderTarget.dispose();
    this.ssaoRenderTarget.dispose();
    this.blurRenderTarget.dispose();
    this.normalMaterial.dispose();
    this.blurMaterial.dispose();
    this.copyMaterial.dispose();
    this.depthRenderMaterial.dispose();
    this._fsQuad.dispose();
  }
  /**
   * Performs the SSAO pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this._overrideVisibility();
    this._renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1);
    this._restoreVisibility();
    this.ssaoMaterial.uniforms["kernelRadius"].value = this.kernelRadius;
    this.ssaoMaterial.uniforms["minDistance"].value = this.minDistance;
    this.ssaoMaterial.uniforms["maxDistance"].value = this.maxDistance;
    this._renderPass(renderer2, this.ssaoMaterial, this.ssaoRenderTarget);
    this._renderPass(renderer2, this.blurMaterial, this.blurRenderTarget);
    switch (this.output) {
      case _SSAOPass.OUTPUT.SSAO:
        this.copyMaterial.uniforms["tDiffuse"].value = this.ssaoRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer);
        break;
      case _SSAOPass.OUTPUT.Blur:
        this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer);
        break;
      case _SSAOPass.OUTPUT.Depth:
        this._renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : readBuffer);
        break;
      case _SSAOPass.OUTPUT.Normal:
        this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer);
        break;
      case _SSAOPass.OUTPUT.Default:
        this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture;
        this.copyMaterial.blending = CustomBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer);
        break;
      default:
        console.warn("THREE.SSAOPass: Unknown output type.");
    }
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this.width = width2;
    this.height = height2;
    this.ssaoRenderTarget.setSize(width2, height2);
    this.normalRenderTarget.setSize(width2, height2);
    this.blurRenderTarget.setSize(width2, height2);
    this.ssaoMaterial.uniforms["resolution"].value.set(width2, height2);
    this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix);
    this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse);
    this.blurMaterial.uniforms["resolution"].value.set(width2, height2);
  }
  // internals
  _renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) {
    renderer2.getClearColor(this._originalClearColor);
    const originalClearAlpha = renderer2.getClearAlpha();
    const originalAutoClear = renderer2.autoClear;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this._fsQuad.material = passMaterial;
    this._fsQuad.render(renderer2);
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this._originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
  }
  _renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) {
    renderer2.getClearColor(this._originalClearColor);
    const originalClearAlpha = renderer2.getClearAlpha();
    const originalAutoClear = renderer2.autoClear;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    clearColor = overrideMaterial.clearColor || clearColor;
    clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this.scene.overrideMaterial = overrideMaterial;
    renderer2.render(this.scene, this.camera);
    this.scene.overrideMaterial = null;
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this._originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
  }
  _generateSampleKernel(kernelSize) {
    const kernel = this.kernel;
    for (let i = 0; i < kernelSize; i++) {
      const sample = new Vector3();
      sample.x = Math.random() * 2 - 1;
      sample.y = Math.random() * 2 - 1;
      sample.z = Math.random();
      sample.normalize();
      let scale2 = i / kernelSize;
      scale2 = MathUtils.lerp(0.1, 1, scale2 * scale2);
      sample.multiplyScalar(scale2);
      kernel.push(sample);
    }
  }
  _generateRandomKernelRotations() {
    const width2 = 4, height2 = 4;
    const simplex = new SimplexNoise();
    const size2 = width2 * height2;
    const data2 = new Float32Array(size2);
    for (let i = 0; i < size2; i++) {
      const x2 = Math.random() * 2 - 1;
      const y = Math.random() * 2 - 1;
      const z = 0;
      data2[i] = simplex.noise3d(x2, y, z);
    }
    this.noiseTexture = new DataTexture(data2, width2, height2, RedFormat, FloatType);
    this.noiseTexture.wrapS = RepeatWrapping;
    this.noiseTexture.wrapT = RepeatWrapping;
    this.noiseTexture.needsUpdate = true;
  }
  _overrideVisibility() {
    const scene = this.scene;
    const cache = this._visibilityCache;
    scene.traverse(function(object) {
      cache.set(object, object.visible);
      if (object.isPoints || object.isLine) object.visible = false;
    });
  }
  _restoreVisibility() {
    const scene = this.scene;
    const cache = this._visibilityCache;
    scene.traverse(function(object) {
      const visible = cache.get(object);
      object.visible = visible;
    });
    cache.clear();
  }
};
SSAOPass.OUTPUT = {
  "Default": 0,
  "SSAO": 1,
  "Blur": 2,
  "Depth": 3,
  "Normal": 4
};

// node_modules/three/examples/jsm/shaders/SSRShader.js
var SSRShader = {
  name: "SSRShader",
  defines: {
    MAX_STEP: 0,
    PERSPECTIVE_CAMERA: true,
    DISTANCE_ATTENUATION: true,
    FRESNEL: true,
    INFINITE_THICK: false,
    SELECTIVE: false
  },
  uniforms: {
    "tDiffuse": { value: null },
    "tNormal": { value: null },
    "tMetalness": { value: null },
    "tDepth": { value: null },
    "cameraNear": { value: null },
    "cameraFar": { value: null },
    "resolution": { value: new Vector2() },
    "cameraProjectionMatrix": { value: new Matrix4() },
    "cameraInverseProjectionMatrix": { value: new Matrix4() },
    "opacity": { value: 0.5 },
    "maxDistance": { value: 180 },
    "cameraRange": { value: 0 },
    "thickness": { value: 0.018 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}

	`
  ),
  fragmentShader: (
    /* glsl */
    `
		// precision highp float;
		precision highp sampler2D;
		varying vec2 vUv;
		uniform sampler2D tDepth;
		uniform sampler2D tNormal;
		uniform sampler2D tMetalness;
		uniform sampler2D tDiffuse;
		uniform float cameraRange;
		uniform vec2 resolution;
		uniform float opacity;
		uniform float cameraNear;
		uniform float cameraFar;
		uniform float maxDistance;
		uniform float thickness;
		uniform mat4 cameraProjectionMatrix;
		uniform mat4 cameraInverseProjectionMatrix;
		#include <packing>
		float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) {
			//x0: point, x1: linePointA, x2: linePointB
			//https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
			return length(cross(x0-x1,x0-x2))/length(x2-x1);
		}
		float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){
			// https://mathworld.wolfram.com/Point-PlaneDistance.html
			//// https://en.wikipedia.org/wiki/Plane_(geometry)
			//// http://paulbourke.net/geometry/pointlineplane/
			float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z;
			float x0=point.x,y0=point.y,z0=point.z;
			float x=planePoint.x,y=planePoint.y,z=planePoint.z;
			float d=-(a*x+b*y+c*z);
			float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c);
			return distance;
		}
		float getDepth( const in vec2 uv ) {
			return texture2D( tDepth, uv ).x;
		}
		float getViewZ( const in float depth ) {
			#ifdef PERSPECTIVE_CAMERA
				return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
			#else
				return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
			#endif
		}
		vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
			vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
			clipPosition *= clipW; //clip
			return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view
		}
		vec3 getViewNormal( const in vec2 uv ) {
			return unpackRGBToNormal( texture2D( tNormal, uv ).xyz );
		}
		vec2 viewPositionToXY(vec3 viewPosition){
			vec2 xy;
			vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1);
			xy=clip.xy;//clip
			float clipW=clip.w;
			xy/=clipW;//NDC
			xy=(xy+1.)/2.;//uv
			xy*=resolution;//screen
			return xy;
		}
		void main(){
			#ifdef SELECTIVE
				float metalness=texture2D(tMetalness,vUv).r;
				if(metalness==0.) return;
			#endif

			float depth = getDepth( vUv );
			float viewZ = getViewZ( depth );
			if(-viewZ>=cameraFar) return;

			float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3];
			vec3 viewPosition=getViewPosition( vUv, depth, clipW );

			vec2 d0=gl_FragCoord.xy;
			vec2 d1;

			vec3 viewNormal=getViewNormal( vUv );

			#ifdef PERSPECTIVE_CAMERA
				vec3 viewIncidentDir=normalize(viewPosition);
				vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal);
			#else
				vec3 viewIncidentDir=vec3(0,0,-1);
				vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal);
			#endif

			float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal);
			// dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html
			// if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta)
			// maxDistance/maxReflectRayLen=cos(theta)
			// maxDistance/maxReflectRayLen==dot(a,b)
			// maxReflectRayLen==maxDistance/dot(a,b)

			vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen;
			#ifdef PERSPECTIVE_CAMERA
				if(d1viewPosition.z>-cameraNear){
					//https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx
					float t=(-cameraNear-viewPosition.z)/viewReflectDir.z;
					d1viewPosition=viewPosition+viewReflectDir*t;
				}
			#endif
			d1=viewPositionToXY(d1viewPosition);

			float totalLen=length(d1-d0);
			float xLen=d1.x-d0.x;
			float yLen=d1.y-d0.y;
			float totalStep=max(abs(xLen),abs(yLen));
			float xSpan=xLen/totalStep;
			float ySpan=yLen/totalStep;
			for(float i=0.;i<float(MAX_STEP);i++){
				if(i>=totalStep) break;
				vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan);
				if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break;
				float s=length(xy-d0)/totalLen;
				vec2 uv=xy/resolution;

				float d = getDepth(uv);
				float vZ = getViewZ( d );
				if(-vZ>=cameraFar) continue;
				float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3];
				vec3 vP=getViewPosition( uv, d, cW );

				#ifdef PERSPECTIVE_CAMERA
					// https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf
					float recipVPZ=1./viewPosition.z;
					float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ));
				#else
					float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z);
				#endif

				// if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang.
				// https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164
				if(viewReflectRayZ<=vZ){

					bool hit;
					#ifdef INFINITE_THICK
						hit=true;
					#else
						float away=pointToLineDistance(vP,viewPosition,d1viewPosition);

						float minThickness;
						vec2 xyNeighbor=xy;
						xyNeighbor.x+=1.;
						vec2 uvNeighbor=xyNeighbor/resolution;
						vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW);
						minThickness=vPNeighbor.x-vP.x;
						minThickness*=3.;
						float tk=max(minThickness,thickness);

						hit=away<=tk;
					#endif

					if(hit){
						vec3 vN=getViewNormal( uv );
						if(dot(viewReflectDir,vN)>=0.) continue;
						float distance=pointPlaneDistance(vP,viewPosition,viewNormal);
						if(distance>maxDistance) break;
						float op=opacity;
						#ifdef DISTANCE_ATTENUATION
							float ratio=1.-(distance/maxDistance);
							float attenuation=ratio*ratio;
							op=opacity*attenuation;
						#endif
						#ifdef FRESNEL
							float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.;
							op*=fresnelCoe;
						#endif
						vec4 reflectColor=texture2D(tDiffuse,uv);
						gl_FragColor.xyz=reflectColor.xyz;
						gl_FragColor.a=op;
						break;
					}
				}
			}
		}
	`
  )
};
var SSRDepthShader = {
  name: "SSRDepthShader",
  defines: {
    "PERSPECTIVE_CAMERA": 1
  },
  uniforms: {
    "tDepth": { value: null },
    "cameraNear": { value: null },
    "cameraFar": { value: null }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}

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

		uniform sampler2D tDepth;

		uniform float cameraNear;
		uniform float cameraFar;

		varying vec2 vUv;

		#include <packing>

		float getLinearDepth( const in vec2 uv ) {

			#if PERSPECTIVE_CAMERA == 1

				float fragCoordZ = texture2D( tDepth, uv ).x;
				float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
				return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );

			#else

				return texture2D( tDepth, uv ).x;

			#endif

		}

		void main() {

			float depth = getLinearDepth( vUv );
			float d = 1.0 - depth;
			// d=(d-.999)*1000.;
			gl_FragColor = vec4( vec3( d ), 1.0 );

		}

	`
  )
};
var SSRBlurShader = {
  name: "SSRBlurShader",
  uniforms: {
    "tDiffuse": { value: null },
    "resolution": { value: new Vector2() },
    "opacity": { value: 0.5 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}

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

		uniform sampler2D tDiffuse;
		uniform vec2 resolution;
		varying vec2 vUv;
		void main() {
			//reverse engineering from PhotoShop blur filter, then change coefficient

			vec2 texelSize = ( 1.0 / resolution );

			vec4 c=texture2D(tDiffuse,vUv);

			vec2 offset;

			offset=(vec2(-1,0))*texelSize;
			vec4 cl=texture2D(tDiffuse,vUv+offset);

			offset=(vec2(1,0))*texelSize;
			vec4 cr=texture2D(tDiffuse,vUv+offset);

			offset=(vec2(0,-1))*texelSize;
			vec4 cb=texture2D(tDiffuse,vUv+offset);

			offset=(vec2(0,1))*texelSize;
			vec4 ct=texture2D(tDiffuse,vUv+offset);

			// float coeCenter=.5;
			// float coeSide=.125;
			float coeCenter=.2;
			float coeSide=.2;
			float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide;
			vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a;
			gl_FragColor=vec4(rgb,a);

		}
	`
  )
};

// node_modules/three/examples/jsm/postprocessing/SSRPass.js
var SSRPass = class _SSRPass extends Pass {
  /**
   * Constructs a new SSR pass.
   *
   * @param {SSRPass~Options} options - The pass options.
   */
  constructor({ renderer: renderer2, scene, camera, width: width2 = 512, height: height2 = 512, selects = null, bouncing = false, groundReflector = null }) {
    super();
    this.width = width2;
    this.height = height2;
    this.clear = true;
    this.renderer = renderer2;
    this.scene = scene;
    this.camera = camera;
    this.groundReflector = groundReflector;
    this.opacity = SSRShader.uniforms.opacity.value;
    this.output = 0;
    this.maxDistance = SSRShader.uniforms.maxDistance.value;
    this.thickness = SSRShader.uniforms.thickness.value;
    this.tempColor = new Color();
    this._selects = selects;
    this.selective = Array.isArray(this._selects);
    Object.defineProperty(this, "selects", {
      get() {
        return this._selects;
      },
      set(val2) {
        if (this._selects === val2) return;
        this._selects = val2;
        if (Array.isArray(val2)) {
          this.selective = true;
          this.ssrMaterial.defines.SELECTIVE = true;
          this.ssrMaterial.needsUpdate = true;
        } else {
          this.selective = false;
          this.ssrMaterial.defines.SELECTIVE = false;
          this.ssrMaterial.needsUpdate = true;
        }
      }
    });
    this._bouncing = bouncing;
    Object.defineProperty(this, "bouncing", {
      get() {
        return this._bouncing;
      },
      set(val2) {
        if (this._bouncing === val2) return;
        this._bouncing = val2;
        if (val2) {
          this.ssrMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture;
        } else {
          this.ssrMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture;
        }
      }
    });
    this.blur = true;
    this._distanceAttenuation = SSRShader.defines.DISTANCE_ATTENUATION;
    Object.defineProperty(this, "distanceAttenuation", {
      get() {
        return this._distanceAttenuation;
      },
      set(val2) {
        if (this._distanceAttenuation === val2) return;
        this._distanceAttenuation = val2;
        this.ssrMaterial.defines.DISTANCE_ATTENUATION = val2;
        this.ssrMaterial.needsUpdate = true;
      }
    });
    this._fresnel = SSRShader.defines.FRESNEL;
    Object.defineProperty(this, "fresnel", {
      get() {
        return this._fresnel;
      },
      set(val2) {
        if (this._fresnel === val2) return;
        this._fresnel = val2;
        this.ssrMaterial.defines.FRESNEL = val2;
        this.ssrMaterial.needsUpdate = true;
      }
    });
    this._infiniteThick = SSRShader.defines.INFINITE_THICK;
    Object.defineProperty(this, "infiniteThick", {
      get() {
        return this._infiniteThick;
      },
      set(val2) {
        if (this._infiniteThick === val2) return;
        this._infiniteThick = val2;
        this.ssrMaterial.defines.INFINITE_THICK = val2;
        this.ssrMaterial.needsUpdate = true;
      }
    });
    const depthTexture = new DepthTexture();
    depthTexture.type = UnsignedShortType;
    depthTexture.minFilter = NearestFilter;
    depthTexture.magFilter = NearestFilter;
    this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height, {
      minFilter: NearestFilter,
      magFilter: NearestFilter,
      type: HalfFloatType,
      depthTexture,
      depthBuffer: true
    });
    this.prevRenderTarget = new WebGLRenderTarget(this.width, this.height, {
      minFilter: NearestFilter,
      magFilter: NearestFilter
    });
    this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, {
      minFilter: NearestFilter,
      magFilter: NearestFilter,
      type: HalfFloatType
    });
    this.metalnessRenderTarget = new WebGLRenderTarget(this.width, this.height, {
      minFilter: NearestFilter,
      magFilter: NearestFilter,
      type: HalfFloatType
    });
    this.ssrRenderTarget = new WebGLRenderTarget(this.width, this.height, {
      minFilter: NearestFilter,
      magFilter: NearestFilter
    });
    this.blurRenderTarget = this.ssrRenderTarget.clone();
    this.blurRenderTarget2 = this.ssrRenderTarget.clone();
    this.ssrMaterial = new ShaderMaterial({
      defines: Object.assign({}, SSRShader.defines, {
        MAX_STEP: Math.sqrt(this.width * this.width + this.height * this.height)
      }),
      uniforms: UniformsUtils.clone(SSRShader.uniforms),
      vertexShader: SSRShader.vertexShader,
      fragmentShader: SSRShader.fragmentShader,
      blending: NoBlending
    });
    this.ssrMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture;
    this.ssrMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture;
    this.ssrMaterial.defines.SELECTIVE = this.selective;
    this.ssrMaterial.needsUpdate = true;
    this.ssrMaterial.uniforms["tMetalness"].value = this.metalnessRenderTarget.texture;
    this.ssrMaterial.uniforms["tDepth"].value = this.beautyRenderTarget.depthTexture;
    this.ssrMaterial.uniforms["cameraNear"].value = this.camera.near;
    this.ssrMaterial.uniforms["cameraFar"].value = this.camera.far;
    this.ssrMaterial.uniforms["thickness"].value = this.thickness;
    this.ssrMaterial.uniforms["resolution"].value.set(this.width, this.height);
    this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix);
    this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse);
    this.normalMaterial = new MeshNormalMaterial();
    this.normalMaterial.blending = NoBlending;
    this.metalnessOnMaterial = new MeshBasicMaterial({
      color: "white"
    });
    this.metalnessOffMaterial = new MeshBasicMaterial({
      color: "black"
    });
    this.blurMaterial = new ShaderMaterial({
      defines: Object.assign({}, SSRBlurShader.defines),
      uniforms: UniformsUtils.clone(SSRBlurShader.uniforms),
      vertexShader: SSRBlurShader.vertexShader,
      fragmentShader: SSRBlurShader.fragmentShader
    });
    this.blurMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture;
    this.blurMaterial.uniforms["resolution"].value.set(this.width, this.height);
    this.blurMaterial2 = new ShaderMaterial({
      defines: Object.assign({}, SSRBlurShader.defines),
      uniforms: UniformsUtils.clone(SSRBlurShader.uniforms),
      vertexShader: SSRBlurShader.vertexShader,
      fragmentShader: SSRBlurShader.fragmentShader
    });
    this.blurMaterial2.uniforms["tDiffuse"].value = this.blurRenderTarget.texture;
    this.blurMaterial2.uniforms["resolution"].value.set(this.width, this.height);
    this.depthRenderMaterial = new ShaderMaterial({
      defines: Object.assign({}, SSRDepthShader.defines),
      uniforms: UniformsUtils.clone(SSRDepthShader.uniforms),
      vertexShader: SSRDepthShader.vertexShader,
      fragmentShader: SSRDepthShader.fragmentShader,
      blending: NoBlending
    });
    this.depthRenderMaterial.uniforms["tDepth"].value = this.beautyRenderTarget.depthTexture;
    this.depthRenderMaterial.uniforms["cameraNear"].value = this.camera.near;
    this.depthRenderMaterial.uniforms["cameraFar"].value = this.camera.far;
    this.copyMaterial = new ShaderMaterial({
      uniforms: UniformsUtils.clone(CopyShader.uniforms),
      vertexShader: CopyShader.vertexShader,
      fragmentShader: CopyShader.fragmentShader,
      transparent: true,
      depthTest: false,
      depthWrite: false,
      blendSrc: SrcAlphaFactor,
      blendDst: OneMinusSrcAlphaFactor,
      blendEquation: AddEquation,
      blendSrcAlpha: SrcAlphaFactor,
      blendDstAlpha: OneMinusSrcAlphaFactor,
      blendEquationAlpha: AddEquation
      // premultipliedAlpha:true,
    });
    this.fsQuad = new FullScreenQuad(null);
    this.originalClearColor = new Color();
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.beautyRenderTarget.dispose();
    this.prevRenderTarget.dispose();
    this.normalRenderTarget.dispose();
    this.metalnessRenderTarget.dispose();
    this.ssrRenderTarget.dispose();
    this.blurRenderTarget.dispose();
    this.blurRenderTarget2.dispose();
    this.normalMaterial.dispose();
    this.metalnessOnMaterial.dispose();
    this.metalnessOffMaterial.dispose();
    this.blurMaterial.dispose();
    this.blurMaterial2.dispose();
    this.copyMaterial.dispose();
    this.depthRenderMaterial.dispose();
    this.fsQuad.dispose();
  }
  /**
   * Performs the SSR pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer) {
    renderer2.setRenderTarget(this.beautyRenderTarget);
    renderer2.clear();
    if (this.groundReflector) {
      this.groundReflector.visible = false;
      this.groundReflector.doRender(this.renderer, this.scene, this.camera);
      this.groundReflector.visible = true;
    }
    renderer2.render(this.scene, this.camera);
    if (this.groundReflector) this.groundReflector.visible = false;
    this._renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 0, 0);
    if (this.selective) {
      this._renderMetalness(renderer2, this.metalnessOnMaterial, this.metalnessRenderTarget, 0, 0);
    }
    this.ssrMaterial.uniforms["opacity"].value = this.opacity;
    this.ssrMaterial.uniforms["maxDistance"].value = this.maxDistance;
    this.ssrMaterial.uniforms["thickness"].value = this.thickness;
    this._renderPass(renderer2, this.ssrMaterial, this.ssrRenderTarget);
    if (this.blur) {
      this._renderPass(renderer2, this.blurMaterial, this.blurRenderTarget);
      this._renderPass(renderer2, this.blurMaterial2, this.blurRenderTarget2);
    }
    switch (this.output) {
      case _SSRPass.OUTPUT.Default:
        if (this.bouncing) {
          this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture;
          this.copyMaterial.blending = NoBlending;
          this._renderPass(renderer2, this.copyMaterial, this.prevRenderTarget);
          if (this.blur)
            this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture;
          else
            this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture;
          this.copyMaterial.blending = NormalBlending;
          this._renderPass(renderer2, this.copyMaterial, this.prevRenderTarget);
          this.copyMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture;
          this.copyMaterial.blending = NoBlending;
          this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        } else {
          this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture;
          this.copyMaterial.blending = NoBlending;
          this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
          if (this.blur)
            this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture;
          else
            this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture;
          this.copyMaterial.blending = NormalBlending;
          this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        }
        break;
      case _SSRPass.OUTPUT.SSR:
        if (this.blur)
          this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture;
        else
          this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        if (this.bouncing) {
          if (this.blur)
            this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture;
          else
            this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture;
          this.copyMaterial.blending = NoBlending;
          this._renderPass(renderer2, this.copyMaterial, this.prevRenderTarget);
          this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture;
          this.copyMaterial.blending = NormalBlending;
          this._renderPass(renderer2, this.copyMaterial, this.prevRenderTarget);
        }
        break;
      case _SSRPass.OUTPUT.Beauty:
        this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      case _SSRPass.OUTPUT.Depth:
        this._renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      case _SSRPass.OUTPUT.Normal:
        this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      case _SSRPass.OUTPUT.Metalness:
        this.copyMaterial.uniforms["tDiffuse"].value = this.metalnessRenderTarget.texture;
        this.copyMaterial.blending = NoBlending;
        this._renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer);
        break;
      default:
        console.warn("THREE.SSRPass: Unknown output type.");
    }
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this.width = width2;
    this.height = height2;
    this.ssrMaterial.defines.MAX_STEP = Math.sqrt(width2 * width2 + height2 * height2);
    this.ssrMaterial.needsUpdate = true;
    this.beautyRenderTarget.setSize(width2, height2);
    this.prevRenderTarget.setSize(width2, height2);
    this.ssrRenderTarget.setSize(width2, height2);
    this.normalRenderTarget.setSize(width2, height2);
    this.metalnessRenderTarget.setSize(width2, height2);
    this.blurRenderTarget.setSize(width2, height2);
    this.blurRenderTarget2.setSize(width2, height2);
    this.ssrMaterial.uniforms["resolution"].value.set(width2, height2);
    this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix);
    this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse);
    this.blurMaterial.uniforms["resolution"].value.set(width2, height2);
    this.blurMaterial2.uniforms["resolution"].value.set(width2, height2);
  }
  // internals
  _renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) {
    this.originalClearColor.copy(renderer2.getClearColor(this.tempColor));
    const originalClearAlpha = renderer2.getClearAlpha(this.tempColor);
    const originalAutoClear = renderer2.autoClear;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this.fsQuad.material = passMaterial;
    this.fsQuad.render(renderer2);
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this.originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
  }
  _renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) {
    this.originalClearColor.copy(renderer2.getClearColor(this.tempColor));
    const originalClearAlpha = renderer2.getClearAlpha(this.tempColor);
    const originalAutoClear = renderer2.autoClear;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    clearColor = overrideMaterial.clearColor || clearColor;
    clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this.scene.overrideMaterial = overrideMaterial;
    renderer2.render(this.scene, this.camera);
    this.scene.overrideMaterial = null;
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this.originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
  }
  _renderMetalness(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) {
    this.originalClearColor.copy(renderer2.getClearColor(this.tempColor));
    const originalClearAlpha = renderer2.getClearAlpha(this.tempColor);
    const originalAutoClear = renderer2.autoClear;
    const originalBackground = this.scene.background;
    const originalFog = this.scene.fog;
    renderer2.setRenderTarget(renderTarget);
    renderer2.autoClear = false;
    this.scene.background = null;
    this.scene.fog = null;
    clearColor = overrideMaterial.clearColor || clearColor;
    clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
    if (clearColor !== void 0 && clearColor !== null) {
      renderer2.setClearColor(clearColor);
      renderer2.setClearAlpha(clearAlpha || 0);
      renderer2.clear();
    }
    this.scene.traverseVisible((child) => {
      child._SSRPassBackupMaterial = child.material;
      if (this._selects.includes(child)) {
        child.material = this.metalnessOnMaterial;
      } else {
        child.material = this.metalnessOffMaterial;
      }
    });
    renderer2.render(this.scene, this.camera);
    this.scene.traverseVisible((child) => {
      child.material = child._SSRPassBackupMaterial;
    });
    renderer2.autoClear = originalAutoClear;
    renderer2.setClearColor(this.originalClearColor);
    renderer2.setClearAlpha(originalClearAlpha);
    this.scene.background = originalBackground;
    this.scene.fog = originalFog;
  }
};
SSRPass.OUTPUT = {
  "Default": 0,
  "SSR": 1,
  "Beauty": 3,
  "Depth": 4,
  "Normal": 5,
  "Metalness": 7
};

// node_modules/three/examples/jsm/postprocessing/SavePass.js
var SavePass = class extends Pass {
  /**
   * Constructs a new save pass.
   *
   * @param {WebGLRenderTarget} [renderTarget] - The render target for saving the read buffer.
   * If not provided, the pass automatically creates a render target.
   */
  constructor(renderTarget) {
    super();
    this.uniforms = UniformsUtils.clone(CopyShader.uniforms);
    this.material = new ShaderMaterial({
      uniforms: this.uniforms,
      vertexShader: CopyShader.vertexShader,
      fragmentShader: CopyShader.fragmentShader,
      blending: NoBlending
    });
    this.renderTarget = renderTarget;
    if (this.renderTarget === void 0) {
      this.renderTarget = new WebGLRenderTarget(1, 1, { type: HalfFloatType });
      this.renderTarget.texture.name = "SavePass.rt";
    }
    this.needsSwap = false;
    this._fsQuad = new FullScreenQuad(this.material);
  }
  /**
   * Performs the save pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    this.uniforms["tDiffuse"].value = readBuffer.texture;
    renderer2.setRenderTarget(this.renderTarget);
    if (this.clear) renderer2.clear();
    this._fsQuad.render(renderer2);
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    this.renderTarget.setSize(width2, height2);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.renderTarget.dispose();
    this.material.dispose();
    this._fsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/postprocessing/TAARenderPass.js
var TAARenderPass = class extends SSAARenderPass {
  /**
   * Constructs a new TAA render pass.
   *
   * @param {Scene} scene - The scene to render.
   * @param {Camera} camera - The camera.
   * @param {?(number|Color|string)} [clearColor=0x000000] - The clear color of the render pass.
   * @param {?number} [clearAlpha=0] - The clear alpha of the render pass.
   */
  constructor(scene, camera, clearColor, clearAlpha) {
    super(scene, camera, clearColor, clearAlpha);
    this.sampleLevel = 0;
    this.accumulate = false;
    this.accumulateIndex = -1;
    this._sampleRenderTarget = null;
    this._holdRenderTarget = null;
  }
  /**
   * Performs the TAA render pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer, deltaTime) {
    if (this.accumulate === false) {
      super.render(renderer2, writeBuffer, readBuffer, deltaTime);
      this.accumulateIndex = -1;
      return;
    }
    const jitterOffsets = _JitterVectors2[5];
    if (this._sampleRenderTarget === null) {
      this._sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { type: HalfFloatType });
      this._sampleRenderTarget.texture.name = "TAARenderPass.sample";
    }
    if (this._holdRenderTarget === null) {
      this._holdRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, { type: HalfFloatType });
      this._holdRenderTarget.texture.name = "TAARenderPass.hold";
    }
    if (this.accumulateIndex === -1) {
      super.render(renderer2, this._holdRenderTarget, readBuffer, deltaTime);
      this.accumulateIndex = 0;
    }
    const autoClear = renderer2.autoClear;
    renderer2.autoClear = false;
    renderer2.getClearColor(this._oldClearColor);
    const oldClearAlpha = renderer2.getClearAlpha();
    const sampleWeight = 1 / jitterOffsets.length;
    if (this.accumulateIndex >= 0 && this.accumulateIndex < jitterOffsets.length) {
      this._copyUniforms["opacity"].value = sampleWeight;
      this._copyUniforms["tDiffuse"].value = writeBuffer.texture;
      const numSamplesPerFrame = Math.pow(2, this.sampleLevel);
      for (let i = 0; i < numSamplesPerFrame; i++) {
        const j2 = this.accumulateIndex;
        const jitterOffset = jitterOffsets[j2];
        if (this.camera.setViewOffset) {
          this.camera.setViewOffset(
            readBuffer.width,
            readBuffer.height,
            jitterOffset[0] * 0.0625,
            jitterOffset[1] * 0.0625,
            // 0.0625 = 1 / 16
            readBuffer.width,
            readBuffer.height
          );
        }
        renderer2.setRenderTarget(writeBuffer);
        renderer2.setClearColor(this.clearColor, this.clearAlpha);
        renderer2.clear();
        renderer2.render(this.scene, this.camera);
        renderer2.setRenderTarget(this._sampleRenderTarget);
        if (this.accumulateIndex === 0) {
          renderer2.setClearColor(0, 0);
          renderer2.clear();
        }
        this._fsQuad.render(renderer2);
        this.accumulateIndex++;
        if (this.accumulateIndex >= jitterOffsets.length) break;
      }
      if (this.camera.clearViewOffset) this.camera.clearViewOffset();
    }
    renderer2.setClearColor(this.clearColor, this.clearAlpha);
    const accumulationWeight = this.accumulateIndex * sampleWeight;
    if (accumulationWeight > 0) {
      this._copyUniforms["opacity"].value = 1;
      this._copyUniforms["tDiffuse"].value = this._sampleRenderTarget.texture;
      renderer2.setRenderTarget(writeBuffer);
      renderer2.clear();
      this._fsQuad.render(renderer2);
    }
    if (accumulationWeight < 1) {
      this._copyUniforms["opacity"].value = 1 - accumulationWeight;
      this._copyUniforms["tDiffuse"].value = this._holdRenderTarget.texture;
      renderer2.setRenderTarget(writeBuffer);
      this._fsQuad.render(renderer2);
    }
    renderer2.autoClear = autoClear;
    renderer2.setClearColor(this._oldClearColor, oldClearAlpha);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    super.dispose();
    if (this._holdRenderTarget) this._holdRenderTarget.dispose();
  }
};
var _JitterVectors2 = [
  [
    [0, 0]
  ],
  [
    [4, 4],
    [-4, -4]
  ],
  [
    [-2, -6],
    [6, -2],
    [-6, 2],
    [2, 6]
  ],
  [
    [1, -3],
    [-1, 3],
    [5, 1],
    [-3, -5],
    [-5, 5],
    [-7, -1],
    [3, 7],
    [7, -7]
  ],
  [
    [1, 1],
    [-1, -3],
    [-3, 2],
    [4, -1],
    [-5, -2],
    [2, 5],
    [5, 3],
    [3, -5],
    [-2, 6],
    [0, -7],
    [-4, -6],
    [-6, 4],
    [-8, 0],
    [7, -4],
    [6, 7],
    [-7, -8]
  ],
  [
    [-4, -7],
    [-7, -5],
    [-3, -5],
    [-5, -4],
    [-1, -4],
    [-2, -2],
    [-6, -1],
    [-4, 0],
    [-7, 1],
    [-1, 2],
    [-6, 3],
    [-3, 3],
    [-7, 6],
    [-3, 6],
    [-5, 7],
    [-1, 7],
    [5, -7],
    [1, -6],
    [6, -5],
    [4, -4],
    [2, -3],
    [7, -2],
    [1, -1],
    [4, -1],
    [2, 1],
    [6, 2],
    [0, 4],
    [4, 4],
    [2, 5],
    [7, 5],
    [5, 6],
    [3, 7]
  ]
];

// node_modules/three/examples/jsm/postprocessing/TexturePass.js
var TexturePass = class extends Pass {
  /**
   * Constructs a new texture pass.
   *
   * @param {Texture} map - The texture to render.
   * @param {number} [opacity=1] - The opacity.
   */
  constructor(map2, opacity = 1) {
    super();
    const shader = CopyShader;
    this.map = map2;
    this.opacity = opacity;
    this.needsSwap = false;
    this.uniforms = UniformsUtils.clone(shader.uniforms);
    this.material = new ShaderMaterial({
      uniforms: this.uniforms,
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader,
      depthTest: false,
      depthWrite: false,
      premultipliedAlpha: true
    });
    this._fsQuad = new FullScreenQuad(null);
  }
  /**
   * Performs the texture pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer) {
    const oldAutoClear = renderer2.autoClear;
    renderer2.autoClear = false;
    this._fsQuad.material = this.material;
    this.uniforms["opacity"].value = this.opacity;
    this.uniforms["tDiffuse"].value = this.map;
    this.material.transparent = this.opacity < 1;
    renderer2.setRenderTarget(this.renderToScreen ? null : readBuffer);
    if (this.clear) renderer2.clear();
    this._fsQuad.render(renderer2);
    renderer2.autoClear = oldAutoClear;
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    this.material.dispose();
    this._fsQuad.dispose();
  }
};

// node_modules/three/examples/jsm/shaders/LuminosityHighPassShader.js
var LuminosityHighPassShader = {
  name: "LuminosityHighPassShader",
  uniforms: {
    "tDiffuse": { value: null },
    "luminosityThreshold": { value: 1 },
    "smoothWidth": { value: 1 },
    "defaultColor": { value: new Color(0) },
    "defaultOpacity": { value: 0 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform vec3 defaultColor;
		uniform float defaultOpacity;
		uniform float luminosityThreshold;
		uniform float smoothWidth;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );

			float v = luminance( texel.xyz );

			vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity );

			float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v );

			gl_FragColor = mix( outputColor, texel, alpha );

		}`
  )
};

// node_modules/three/examples/jsm/postprocessing/UnrealBloomPass.js
var UnrealBloomPass = class _UnrealBloomPass extends Pass {
  /**
   * Constructs a new Unreal Bloom pass.
   *
   * @param {Vector2} [resolution] - The effect's resolution.
   * @param {number} [strength=1] - The Bloom strength.
   * @param {number} radius - The Bloom radius.
   * @param {number} threshold - The luminance threshold limits which bright areas contribute to the Bloom effect.
   */
  constructor(resolution, strength = 1, radius, threshold) {
    super();
    this.strength = strength;
    this.radius = radius;
    this.threshold = threshold;
    this.resolution = resolution !== void 0 ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256);
    this.clearColor = new Color(0, 0, 0);
    this.needsSwap = false;
    this.renderTargetsHorizontal = [];
    this.renderTargetsVertical = [];
    this.nMips = 5;
    let resx = Math.round(this.resolution.x / 2);
    let resy = Math.round(this.resolution.y / 2);
    this.renderTargetBright = new WebGLRenderTarget(resx, resy, { type: HalfFloatType });
    this.renderTargetBright.texture.name = "UnrealBloomPass.bright";
    this.renderTargetBright.texture.generateMipmaps = false;
    for (let i = 0; i < this.nMips; i++) {
      const renderTargetHorizontal = new WebGLRenderTarget(resx, resy, { type: HalfFloatType });
      renderTargetHorizontal.texture.name = "UnrealBloomPass.h" + i;
      renderTargetHorizontal.texture.generateMipmaps = false;
      this.renderTargetsHorizontal.push(renderTargetHorizontal);
      const renderTargetVertical = new WebGLRenderTarget(resx, resy, { type: HalfFloatType });
      renderTargetVertical.texture.name = "UnrealBloomPass.v" + i;
      renderTargetVertical.texture.generateMipmaps = false;
      this.renderTargetsVertical.push(renderTargetVertical);
      resx = Math.round(resx / 2);
      resy = Math.round(resy / 2);
    }
    const highPassShader = LuminosityHighPassShader;
    this.highPassUniforms = UniformsUtils.clone(highPassShader.uniforms);
    this.highPassUniforms["luminosityThreshold"].value = threshold;
    this.highPassUniforms["smoothWidth"].value = 0.01;
    this.materialHighPassFilter = new ShaderMaterial({
      uniforms: this.highPassUniforms,
      vertexShader: highPassShader.vertexShader,
      fragmentShader: highPassShader.fragmentShader
    });
    this.separableBlurMaterials = [];
    const kernelSizeArray = [3, 5, 7, 9, 11];
    resx = Math.round(this.resolution.x / 2);
    resy = Math.round(this.resolution.y / 2);
    for (let i = 0; i < this.nMips; i++) {
      this.separableBlurMaterials.push(this._getSeparableBlurMaterial(kernelSizeArray[i]));
      this.separableBlurMaterials[i].uniforms["invSize"].value = new Vector2(1 / resx, 1 / resy);
      resx = Math.round(resx / 2);
      resy = Math.round(resy / 2);
    }
    this.compositeMaterial = this._getCompositeMaterial(this.nMips);
    this.compositeMaterial.uniforms["blurTexture1"].value = this.renderTargetsVertical[0].texture;
    this.compositeMaterial.uniforms["blurTexture2"].value = this.renderTargetsVertical[1].texture;
    this.compositeMaterial.uniforms["blurTexture3"].value = this.renderTargetsVertical[2].texture;
    this.compositeMaterial.uniforms["blurTexture4"].value = this.renderTargetsVertical[3].texture;
    this.compositeMaterial.uniforms["blurTexture5"].value = this.renderTargetsVertical[4].texture;
    this.compositeMaterial.uniforms["bloomStrength"].value = strength;
    this.compositeMaterial.uniforms["bloomRadius"].value = 0.1;
    const bloomFactors = [1, 0.8, 0.6, 0.4, 0.2];
    this.compositeMaterial.uniforms["bloomFactors"].value = bloomFactors;
    this.bloomTintColors = [new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1)];
    this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors;
    this.copyUniforms = UniformsUtils.clone(CopyShader.uniforms);
    this.blendMaterial = new ShaderMaterial({
      uniforms: this.copyUniforms,
      vertexShader: CopyShader.vertexShader,
      fragmentShader: CopyShader.fragmentShader,
      blending: AdditiveBlending,
      depthTest: false,
      depthWrite: false,
      transparent: true
    });
    this._oldClearColor = new Color();
    this._oldClearAlpha = 1;
    this._basic = new MeshBasicMaterial();
    this._fsQuad = new FullScreenQuad(null);
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever the pass is no longer used in your app.
   */
  dispose() {
    for (let i = 0; i < this.renderTargetsHorizontal.length; i++) {
      this.renderTargetsHorizontal[i].dispose();
    }
    for (let i = 0; i < this.renderTargetsVertical.length; i++) {
      this.renderTargetsVertical[i].dispose();
    }
    this.renderTargetBright.dispose();
    for (let i = 0; i < this.separableBlurMaterials.length; i++) {
      this.separableBlurMaterials[i].dispose();
    }
    this.compositeMaterial.dispose();
    this.blendMaterial.dispose();
    this._basic.dispose();
    this._fsQuad.dispose();
  }
  /**
   * Sets the size of the pass.
   *
   * @param {number} width - The width to set.
   * @param {number} height - The height to set.
   */
  setSize(width2, height2) {
    let resx = Math.round(width2 / 2);
    let resy = Math.round(height2 / 2);
    this.renderTargetBright.setSize(resx, resy);
    for (let i = 0; i < this.nMips; i++) {
      this.renderTargetsHorizontal[i].setSize(resx, resy);
      this.renderTargetsVertical[i].setSize(resx, resy);
      this.separableBlurMaterials[i].uniforms["invSize"].value = new Vector2(1 / resx, 1 / resy);
      resx = Math.round(resx / 2);
      resy = Math.round(resy / 2);
    }
  }
  /**
   * Performs the Bloom pass.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
   * destination for the pass.
   * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
   * previous pass from this buffer.
   * @param {number} deltaTime - The delta time in seconds.
   * @param {boolean} maskActive - Whether masking is active or not.
   */
  render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) {
    renderer2.getClearColor(this._oldClearColor);
    this._oldClearAlpha = renderer2.getClearAlpha();
    const oldAutoClear = renderer2.autoClear;
    renderer2.autoClear = false;
    renderer2.setClearColor(this.clearColor, 0);
    if (maskActive) renderer2.state.buffers.stencil.setTest(false);
    if (this.renderToScreen) {
      this._fsQuad.material = this._basic;
      this._basic.map = readBuffer.texture;
      renderer2.setRenderTarget(null);
      renderer2.clear();
      this._fsQuad.render(renderer2);
    }
    this.highPassUniforms["tDiffuse"].value = readBuffer.texture;
    this.highPassUniforms["luminosityThreshold"].value = this.threshold;
    this._fsQuad.material = this.materialHighPassFilter;
    renderer2.setRenderTarget(this.renderTargetBright);
    renderer2.clear();
    this._fsQuad.render(renderer2);
    let inputRenderTarget = this.renderTargetBright;
    for (let i = 0; i < this.nMips; i++) {
      this._fsQuad.material = this.separableBlurMaterials[i];
      this.separableBlurMaterials[i].uniforms["colorTexture"].value = inputRenderTarget.texture;
      this.separableBlurMaterials[i].uniforms["direction"].value = _UnrealBloomPass.BlurDirectionX;
      renderer2.setRenderTarget(this.renderTargetsHorizontal[i]);
      renderer2.clear();
      this._fsQuad.render(renderer2);
      this.separableBlurMaterials[i].uniforms["colorTexture"].value = this.renderTargetsHorizontal[i].texture;
      this.separableBlurMaterials[i].uniforms["direction"].value = _UnrealBloomPass.BlurDirectionY;
      renderer2.setRenderTarget(this.renderTargetsVertical[i]);
      renderer2.clear();
      this._fsQuad.render(renderer2);
      inputRenderTarget = this.renderTargetsVertical[i];
    }
    this._fsQuad.material = this.compositeMaterial;
    this.compositeMaterial.uniforms["bloomStrength"].value = this.strength;
    this.compositeMaterial.uniforms["bloomRadius"].value = this.radius;
    this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors;
    renderer2.setRenderTarget(this.renderTargetsHorizontal[0]);
    renderer2.clear();
    this._fsQuad.render(renderer2);
    this._fsQuad.material = this.blendMaterial;
    this.copyUniforms["tDiffuse"].value = this.renderTargetsHorizontal[0].texture;
    if (maskActive) renderer2.state.buffers.stencil.setTest(true);
    if (this.renderToScreen) {
      renderer2.setRenderTarget(null);
      this._fsQuad.render(renderer2);
    } else {
      renderer2.setRenderTarget(readBuffer);
      this._fsQuad.render(renderer2);
    }
    renderer2.setClearColor(this._oldClearColor, this._oldClearAlpha);
    renderer2.autoClear = oldAutoClear;
  }
  // internals
  _getSeparableBlurMaterial(kernelRadius) {
    const coefficients = [];
    for (let i = 0; i < kernelRadius; i++) {
      coefficients.push(0.39894 * Math.exp(-0.5 * i * i / (kernelRadius * kernelRadius)) / kernelRadius);
    }
    return new ShaderMaterial({
      defines: {
        "KERNEL_RADIUS": kernelRadius
      },
      uniforms: {
        "colorTexture": { value: null },
        "invSize": { value: new Vector2(0.5, 0.5) },
        // inverse texture size
        "direction": { value: new Vector2(0.5, 0.5) },
        "gaussianCoefficients": { value: coefficients }
        // precomputed Gaussian coefficients
      },
      vertexShader: `varying vec2 vUv;
				void main() {
					vUv = uv;
					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
				}`,
      fragmentShader: `#include <common>
				varying vec2 vUv;
				uniform sampler2D colorTexture;
				uniform vec2 invSize;
				uniform vec2 direction;
				uniform float gaussianCoefficients[KERNEL_RADIUS];

				void main() {
					float weightSum = gaussianCoefficients[0];
					vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum;
					for( int i = 1; i < KERNEL_RADIUS; i ++ ) {
						float x = float(i);
						float w = gaussianCoefficients[i];
						vec2 uvOffset = direction * invSize * x;
						vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb;
						vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb;
						diffuseSum += (sample1 + sample2) * w;
						weightSum += 2.0 * w;
					}
					gl_FragColor = vec4(diffuseSum/weightSum, 1.0);
				}`
    });
  }
  _getCompositeMaterial(nMips) {
    return new ShaderMaterial({
      defines: {
        "NUM_MIPS": nMips
      },
      uniforms: {
        "blurTexture1": { value: null },
        "blurTexture2": { value: null },
        "blurTexture3": { value: null },
        "blurTexture4": { value: null },
        "blurTexture5": { value: null },
        "bloomStrength": { value: 1 },
        "bloomFactors": { value: null },
        "bloomTintColors": { value: null },
        "bloomRadius": { value: 0 }
      },
      vertexShader: `varying vec2 vUv;
				void main() {
					vUv = uv;
					gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
				}`,
      fragmentShader: `varying vec2 vUv;
				uniform sampler2D blurTexture1;
				uniform sampler2D blurTexture2;
				uniform sampler2D blurTexture3;
				uniform sampler2D blurTexture4;
				uniform sampler2D blurTexture5;
				uniform float bloomStrength;
				uniform float bloomRadius;
				uniform float bloomFactors[NUM_MIPS];
				uniform vec3 bloomTintColors[NUM_MIPS];

				float lerpBloomFactor(const in float factor) {
					float mirrorFactor = 1.2 - factor;
					return mix(factor, mirrorFactor, bloomRadius);
				}

				void main() {
					gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) +
						lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) +
						lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) +
						lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) +
						lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );
				}`
    });
  }
};
UnrealBloomPass.BlurDirectionX = new Vector2(1, 0);
UnrealBloomPass.BlurDirectionY = new Vector2(0, 1);

// node_modules/three/examples/jsm/renderers/CSS2DRenderer.js
var CSS2DObject = class extends Object3D {
  /**
   * Constructs a new CSS2D object.
   *
   * @param {DOMElement} [element] - The DOM element.
   */
  constructor(element = document.createElement("div")) {
    super();
    this.isCSS2DObject = true;
    this.element = element;
    this.element.style.position = "absolute";
    this.element.style.userSelect = "none";
    this.element.setAttribute("draggable", false);
    this.center = new Vector2(0.5, 0.5);
    this.addEventListener("removed", function() {
      this.traverse(function(object) {
        if (object.element instanceof object.element.ownerDocument.defaultView.Element && object.element.parentNode !== null) {
          object.element.remove();
        }
      });
    });
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.element = source.element.cloneNode(true);
    this.center = source.center;
    return this;
  }
};
var _vector4 = new Vector3();
var _viewMatrix = new Matrix4();
var _viewProjectionMatrix = new Matrix4();
var _a2 = new Vector3();
var _b2 = new Vector3();
var CSS2DRenderer = class {
  /**
   * Constructs a new CSS2D renderer.
   *
   * @param {CSS2DRenderer~Parameters} [parameters] - The parameters.
   */
  constructor(parameters = {}) {
    const _this = this;
    let _width, _height;
    let _widthHalf, _heightHalf;
    const cache = {
      objects: /* @__PURE__ */ new WeakMap()
    };
    const domElement = parameters.element !== void 0 ? parameters.element : document.createElement("div");
    domElement.style.overflow = "hidden";
    this.domElement = domElement;
    this.getSize = function() {
      return {
        width: _width,
        height: _height
      };
    };
    this.render = function(scene, camera) {
      if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
      if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
      _viewMatrix.copy(camera.matrixWorldInverse);
      _viewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, _viewMatrix);
      renderObject(scene, scene, camera);
      zOrder(scene);
    };
    this.setSize = function(width2, height2) {
      _width = width2;
      _height = height2;
      _widthHalf = _width / 2;
      _heightHalf = _height / 2;
      domElement.style.width = width2 + "px";
      domElement.style.height = height2 + "px";
    };
    function hideObject(object) {
      if (object.isCSS2DObject) object.element.style.display = "none";
      for (let i = 0, l2 = object.children.length; i < l2; i++) {
        hideObject(object.children[i]);
      }
    }
    function renderObject(object, scene, camera) {
      if (object.visible === false) {
        hideObject(object);
        return;
      }
      if (object.isCSS2DObject) {
        _vector4.setFromMatrixPosition(object.matrixWorld);
        _vector4.applyMatrix4(_viewProjectionMatrix);
        const visible = _vector4.z >= -1 && _vector4.z <= 1 && object.layers.test(camera.layers) === true;
        const element = object.element;
        element.style.display = visible === true ? "" : "none";
        if (visible === true) {
          object.onBeforeRender(_this, scene, camera);
          element.style.transform = "translate(" + -100 * object.center.x + "%," + -100 * object.center.y + "%)translate(" + (_vector4.x * _widthHalf + _widthHalf) + "px," + (-_vector4.y * _heightHalf + _heightHalf) + "px)";
          if (element.parentNode !== domElement) {
            domElement.appendChild(element);
          }
          object.onAfterRender(_this, scene, camera);
        }
        const objectData = {
          distanceToCameraSquared: getDistanceToSquared(camera, object)
        };
        cache.objects.set(object, objectData);
      }
      for (let i = 0, l2 = object.children.length; i < l2; i++) {
        renderObject(object.children[i], scene, camera);
      }
    }
    function getDistanceToSquared(object1, object2) {
      _a2.setFromMatrixPosition(object1.matrixWorld);
      _b2.setFromMatrixPosition(object2.matrixWorld);
      return _a2.distanceToSquared(_b2);
    }
    function filterAndFlatten(scene) {
      const result = [];
      scene.traverseVisible(function(object) {
        if (object.isCSS2DObject) result.push(object);
      });
      return result;
    }
    function zOrder(scene) {
      const sorted = filterAndFlatten(scene).sort(function(a2, b3) {
        if (a2.renderOrder !== b3.renderOrder) {
          return b3.renderOrder - a2.renderOrder;
        }
        const distanceA = cache.objects.get(a2).distanceToCameraSquared;
        const distanceB = cache.objects.get(b3).distanceToCameraSquared;
        return distanceA - distanceB;
      });
      const zMax = sorted.length;
      for (let i = 0, l2 = sorted.length; i < l2; i++) {
        sorted[i].element.style.zIndex = zMax - i;
      }
    }
  }
};

// node_modules/three/examples/jsm/renderers/CSS3DRenderer.js
var _position = new Vector3();
var _quaternion5 = new Quaternion();
var _scale3 = new Vector3();
var CSS3DObject = class extends Object3D {
  /**
   * Constructs a new CSS3D object.
   *
   * @param {DOMElement} [element] - The DOM element.
   */
  constructor(element = document.createElement("div")) {
    super();
    this.isCSS3DObject = true;
    this.element = element;
    this.element.style.position = "absolute";
    this.element.style.pointerEvents = "auto";
    this.element.style.userSelect = "none";
    this.element.setAttribute("draggable", false);
    this.addEventListener("removed", function() {
      this.traverse(function(object) {
        if (object.element instanceof object.element.ownerDocument.defaultView.Element && object.element.parentNode !== null) {
          object.element.remove();
        }
      });
    });
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.element = source.element.cloneNode(true);
    return this;
  }
};
var CSS3DSprite = class extends CSS3DObject {
  /**
   * Constructs a new CSS3D sprite object.
   *
   * @param {DOMElement} [element] - The DOM element.
   */
  constructor(element) {
    super(element);
    this.isCSS3DSprite = true;
    this.rotation2D = 0;
  }
  copy(source, recursive) {
    super.copy(source, recursive);
    this.rotation2D = source.rotation2D;
    return this;
  }
};
var _matrix4 = new Matrix4();
var _matrix22 = new Matrix4();
var CSS3DRenderer = class {
  /**
   * Constructs a new CSS3D renderer.
   *
   * @param {CSS3DRenderer~Parameters} [parameters] - The parameters.
   */
  constructor(parameters = {}) {
    const _this = this;
    let _width, _height;
    let _widthHalf, _heightHalf;
    const cache = {
      camera: { style: "" },
      objects: /* @__PURE__ */ new WeakMap()
    };
    const domElement = parameters.element !== void 0 ? parameters.element : document.createElement("div");
    domElement.style.overflow = "hidden";
    this.domElement = domElement;
    const viewElement = document.createElement("div");
    viewElement.style.transformOrigin = "0 0";
    viewElement.style.pointerEvents = "none";
    domElement.appendChild(viewElement);
    const cameraElement = document.createElement("div");
    cameraElement.style.transformStyle = "preserve-3d";
    viewElement.appendChild(cameraElement);
    this.getSize = function() {
      return {
        width: _width,
        height: _height
      };
    };
    this.render = function(scene, camera) {
      const fov = camera.projectionMatrix.elements[5] * _heightHalf;
      if (camera.view && camera.view.enabled) {
        viewElement.style.transform = `translate( ${-camera.view.offsetX * (_width / camera.view.width)}px, ${-camera.view.offsetY * (_height / camera.view.height)}px )`;
        viewElement.style.transform += `scale( ${camera.view.fullWidth / camera.view.width}, ${camera.view.fullHeight / camera.view.height} )`;
      } else {
        viewElement.style.transform = "";
      }
      if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
      if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
      let tx, ty;
      if (camera.isOrthographicCamera) {
        tx = -(camera.right + camera.left) / 2;
        ty = (camera.top + camera.bottom) / 2;
      }
      const scaleByViewOffset = camera.view && camera.view.enabled ? camera.view.height / camera.view.fullHeight : 1;
      const cameraCSSMatrix = camera.isOrthographicCamera ? `scale( ${scaleByViewOffset} )scale(` + fov + ")translate(" + epsilon(tx) + "px," + epsilon(ty) + "px)" + getCameraCSSMatrix(camera.matrixWorldInverse) : `scale( ${scaleByViewOffset} )translateZ(` + fov + "px)" + getCameraCSSMatrix(camera.matrixWorldInverse);
      const perspective = camera.isPerspectiveCamera ? "perspective(" + fov + "px) " : "";
      const style = perspective + cameraCSSMatrix + "translate(" + _widthHalf + "px," + _heightHalf + "px)";
      if (cache.camera.style !== style) {
        cameraElement.style.transform = style;
        cache.camera.style = style;
      }
      renderObject(scene, scene, camera, cameraCSSMatrix);
    };
    this.setSize = function(width2, height2) {
      _width = width2;
      _height = height2;
      _widthHalf = _width / 2;
      _heightHalf = _height / 2;
      domElement.style.width = width2 + "px";
      domElement.style.height = height2 + "px";
      viewElement.style.width = width2 + "px";
      viewElement.style.height = height2 + "px";
      cameraElement.style.width = width2 + "px";
      cameraElement.style.height = height2 + "px";
    };
    function epsilon(value2) {
      return Math.abs(value2) < 1e-10 ? 0 : value2;
    }
    function getCameraCSSMatrix(matrix2) {
      const elements = matrix2.elements;
      return "matrix3d(" + epsilon(elements[0]) + "," + epsilon(-elements[1]) + "," + epsilon(elements[2]) + "," + epsilon(elements[3]) + "," + epsilon(elements[4]) + "," + epsilon(-elements[5]) + "," + epsilon(elements[6]) + "," + epsilon(elements[7]) + "," + epsilon(elements[8]) + "," + epsilon(-elements[9]) + "," + epsilon(elements[10]) + "," + epsilon(elements[11]) + "," + epsilon(elements[12]) + "," + epsilon(-elements[13]) + "," + epsilon(elements[14]) + "," + epsilon(elements[15]) + ")";
    }
    function getObjectCSSMatrix(matrix2) {
      const elements = matrix2.elements;
      const matrix3d = "matrix3d(" + epsilon(elements[0]) + "," + epsilon(elements[1]) + "," + epsilon(elements[2]) + "," + epsilon(elements[3]) + "," + epsilon(-elements[4]) + "," + epsilon(-elements[5]) + "," + epsilon(-elements[6]) + "," + epsilon(-elements[7]) + "," + epsilon(elements[8]) + "," + epsilon(elements[9]) + "," + epsilon(elements[10]) + "," + epsilon(elements[11]) + "," + epsilon(elements[12]) + "," + epsilon(elements[13]) + "," + epsilon(elements[14]) + "," + epsilon(elements[15]) + ")";
      return "translate(-50%,-50%)" + matrix3d;
    }
    function hideObject(object) {
      if (object.isCSS3DObject) object.element.style.display = "none";
      for (let i = 0, l2 = object.children.length; i < l2; i++) {
        hideObject(object.children[i]);
      }
    }
    function renderObject(object, scene, camera, cameraCSSMatrix) {
      if (object.visible === false) {
        hideObject(object);
        return;
      }
      if (object.isCSS3DObject) {
        const visible = object.layers.test(camera.layers) === true;
        const element = object.element;
        element.style.display = visible === true ? "" : "none";
        if (visible === true) {
          object.onBeforeRender(_this, scene, camera);
          let style;
          if (object.isCSS3DSprite) {
            _matrix4.copy(camera.matrixWorldInverse);
            _matrix4.transpose();
            if (object.rotation2D !== 0) _matrix4.multiply(_matrix22.makeRotationZ(object.rotation2D));
            object.matrixWorld.decompose(_position, _quaternion5, _scale3);
            _matrix4.setPosition(_position);
            _matrix4.scale(_scale3);
            _matrix4.elements[3] = 0;
            _matrix4.elements[7] = 0;
            _matrix4.elements[11] = 0;
            _matrix4.elements[15] = 1;
            style = getObjectCSSMatrix(_matrix4);
          } else {
            style = getObjectCSSMatrix(object.matrixWorld);
          }
          const cachedObject = cache.objects.get(object);
          if (cachedObject === void 0 || cachedObject.style !== style) {
            element.style.transform = style;
            const objectData = { style };
            cache.objects.set(object, objectData);
          }
          if (element.parentNode !== cameraElement) {
            cameraElement.appendChild(element);
          }
          object.onAfterRender(_this, scene, camera);
        }
      }
      for (let i = 0, l2 = object.children.length; i < l2; i++) {
        renderObject(object.children[i], scene, camera, cameraCSSMatrix);
      }
    }
  }
};

// node_modules/three/examples/jsm/renderers/Projector.js
var RenderableObject = class {
  constructor() {
    this.id = 0;
    this.object = null;
    this.z = 0;
    this.renderOrder = 0;
  }
};
var RenderableFace = class {
  constructor() {
    this.id = 0;
    this.v1 = new RenderableVertex();
    this.v2 = new RenderableVertex();
    this.v3 = new RenderableVertex();
    this.normalModel = new Vector3();
    this.vertexNormalsModel = [new Vector3(), new Vector3(), new Vector3()];
    this.vertexNormalsLength = 0;
    this.color = new Color();
    this.material = null;
    this.uvs = [new Vector2(), new Vector2(), new Vector2()];
    this.z = 0;
    this.renderOrder = 0;
  }
};
var RenderableVertex = class {
  constructor() {
    this.position = new Vector3();
    this.positionWorld = new Vector3();
    this.positionScreen = new Vector4();
    this.visible = true;
  }
  copy(vertex) {
    this.positionWorld.copy(vertex.positionWorld);
    this.positionScreen.copy(vertex.positionScreen);
  }
};
var RenderableLine = class {
  constructor() {
    this.id = 0;
    this.v1 = new RenderableVertex();
    this.v2 = new RenderableVertex();
    this.vertexColors = [new Color(), new Color()];
    this.material = null;
    this.z = 0;
    this.renderOrder = 0;
  }
};
var RenderableSprite = class {
  constructor() {
    this.id = 0;
    this.object = null;
    this.x = 0;
    this.y = 0;
    this.z = 0;
    this.rotation = 0;
    this.scale = new Vector2();
    this.material = null;
    this.renderOrder = 0;
  }
};
var Projector = class {
  /**
   * Constructs a new projector.
   */
  constructor() {
    let _object, _objectCount, _objectPoolLength = 0, _vertex, _vertexCount, _vertexPoolLength = 0, _face2, _faceCount, _facePoolLength = 0, _line4, _lineCount, _linePoolLength = 0, _sprite, _spriteCount, _spritePoolLength = 0, _modelMatrix;
    const _renderData = { objects: [], lights: [], elements: [] }, _vector32 = new Vector3(), _vector42 = new Vector4(), _clipBox = new Box3(new Vector3(-1, -1, -1), new Vector3(1, 1, 1)), _boundingBox = new Box3(), _points3 = new Array(3), _viewMatrix2 = new Matrix4(), _viewProjectionMatrix2 = new Matrix4(), _modelViewProjectionMatrix = new Matrix4(), _frustum2 = new Frustum(), _objectPool = [], _vertexPool = [], _facePool = [], _linePool = [], _spritePool = [];
    function RenderList() {
      const normals = [];
      const colors = [];
      const uvs = [];
      let object = null;
      const normalMatrix = new Matrix3();
      function setObject(value2) {
        object = value2;
        normalMatrix.getNormalMatrix(object.matrixWorld);
        normals.length = 0;
        colors.length = 0;
        uvs.length = 0;
      }
      function projectVertex(vertex) {
        const position2 = vertex.position;
        const positionWorld = vertex.positionWorld;
        const positionScreen = vertex.positionScreen;
        positionWorld.copy(position2).applyMatrix4(_modelMatrix);
        positionScreen.copy(positionWorld).applyMatrix4(_viewProjectionMatrix2);
        const invW = 1 / positionScreen.w;
        positionScreen.x *= invW;
        positionScreen.y *= invW;
        positionScreen.z *= invW;
        vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 && positionScreen.y >= -1 && positionScreen.y <= 1 && positionScreen.z >= -1 && positionScreen.z <= 1;
      }
      function pushVertex(x2, y, z) {
        _vertex = getNextVertexInPool();
        _vertex.position.set(x2, y, z);
        projectVertex(_vertex);
      }
      function pushNormal(x2, y, z) {
        normals.push(x2, y, z);
      }
      function pushColor(r, g3, b3) {
        colors.push(r, g3, b3);
      }
      function pushUv(x2, y) {
        uvs.push(x2, y);
      }
      function checkTriangleVisibility(v12, v2, v3) {
        if (v12.visible === true || v2.visible === true || v3.visible === true) return true;
        _points3[0] = v12.positionScreen;
        _points3[1] = v2.positionScreen;
        _points3[2] = v3.positionScreen;
        return _clipBox.intersectsBox(_boundingBox.setFromPoints(_points3));
      }
      function checkBackfaceCulling(v12, v2, v3) {
        return (v3.positionScreen.x - v12.positionScreen.x) * (v2.positionScreen.y - v12.positionScreen.y) - (v3.positionScreen.y - v12.positionScreen.y) * (v2.positionScreen.x - v12.positionScreen.x) < 0;
      }
      function pushLine(a2, b3) {
        const v12 = _vertexPool[a2];
        const v2 = _vertexPool[b3];
        v12.positionScreen.copy(v12.position).applyMatrix4(_modelViewProjectionMatrix);
        v2.positionScreen.copy(v2.position).applyMatrix4(_modelViewProjectionMatrix);
        if (clipLine(v12.positionScreen, v2.positionScreen) === true) {
          v12.positionScreen.multiplyScalar(1 / v12.positionScreen.w);
          v2.positionScreen.multiplyScalar(1 / v2.positionScreen.w);
          _line4 = getNextLineInPool();
          _line4.id = object.id;
          _line4.v1.copy(v12);
          _line4.v2.copy(v2);
          _line4.z = Math.max(v12.positionScreen.z, v2.positionScreen.z);
          _line4.renderOrder = object.renderOrder;
          _line4.material = object.material;
          if (object.material.vertexColors) {
            _line4.vertexColors[0].fromArray(colors, a2 * 3);
            _line4.vertexColors[1].fromArray(colors, b3 * 3);
          }
          _renderData.elements.push(_line4);
        }
      }
      function pushTriangle(a2, b3, c2, material) {
        const v12 = _vertexPool[a2];
        const v2 = _vertexPool[b3];
        const v3 = _vertexPool[c2];
        if (checkTriangleVisibility(v12, v2, v3) === false) return;
        if (material.side === DoubleSide || checkBackfaceCulling(v12, v2, v3) === true) {
          _face2 = getNextFaceInPool();
          _face2.id = object.id;
          _face2.v1.copy(v12);
          _face2.v2.copy(v2);
          _face2.v3.copy(v3);
          _face2.z = (v12.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z) / 3;
          _face2.renderOrder = object.renderOrder;
          _vector32.subVectors(v3.position, v2.position);
          _vector42.subVectors(v12.position, v2.position);
          _vector32.cross(_vector42);
          _face2.normalModel.copy(_vector32);
          _face2.normalModel.applyMatrix3(normalMatrix).normalize();
          for (let i = 0; i < 3; i++) {
            const normal = _face2.vertexNormalsModel[i];
            normal.fromArray(normals, arguments[i] * 3);
            normal.applyMatrix3(normalMatrix).normalize();
            const uv = _face2.uvs[i];
            uv.fromArray(uvs, arguments[i] * 2);
          }
          _face2.vertexNormalsLength = 3;
          _face2.material = material;
          if (material.vertexColors) {
            _face2.color.fromArray(colors, a2 * 3);
          }
          _renderData.elements.push(_face2);
        }
      }
      return {
        setObject,
        projectVertex,
        checkTriangleVisibility,
        checkBackfaceCulling,
        pushVertex,
        pushNormal,
        pushColor,
        pushUv,
        pushLine,
        pushTriangle
      };
    }
    const renderList = new RenderList();
    function projectObject(object) {
      if (object.visible === false) return;
      if (object.isLight) {
        _renderData.lights.push(object);
      } else if (object.isMesh || object.isLine || object.isPoints) {
        if (object.material.visible === false) return;
        if (object.frustumCulled === true && _frustum2.intersectsObject(object) === false) return;
        addObject(object);
      } else if (object.isSprite) {
        if (object.material.visible === false) return;
        if (object.frustumCulled === true && _frustum2.intersectsSprite(object) === false) return;
        addObject(object);
      }
      const children = object.children;
      for (let i = 0, l2 = children.length; i < l2; i++) {
        projectObject(children[i]);
      }
    }
    function addObject(object) {
      _object = getNextObjectInPool();
      _object.id = object.id;
      _object.object = object;
      _vector32.setFromMatrixPosition(object.matrixWorld);
      _vector32.applyMatrix4(_viewProjectionMatrix2);
      _object.z = _vector32.z;
      _object.renderOrder = object.renderOrder;
      _renderData.objects.push(_object);
    }
    this.projectScene = function(scene, camera, sortObjects, sortElements) {
      _faceCount = 0;
      _lineCount = 0;
      _spriteCount = 0;
      _renderData.elements.length = 0;
      if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld();
      if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
      _viewMatrix2.copy(camera.matrixWorldInverse);
      _viewProjectionMatrix2.multiplyMatrices(camera.projectionMatrix, _viewMatrix2);
      _frustum2.setFromProjectionMatrix(_viewProjectionMatrix2);
      _objectCount = 0;
      _renderData.objects.length = 0;
      _renderData.lights.length = 0;
      projectObject(scene);
      if (sortObjects === true) {
        _renderData.objects.sort(painterSort);
      }
      const objects = _renderData.objects;
      for (let o = 0, ol = objects.length; o < ol; o++) {
        const object = objects[o].object;
        const geometry = object.geometry;
        renderList.setObject(object);
        _modelMatrix = object.matrixWorld;
        _vertexCount = 0;
        if (object.isMesh) {
          let material = object.material;
          const isMultiMaterial = Array.isArray(material);
          const attributes = geometry.attributes;
          const groups = geometry.groups;
          if (attributes.position === void 0) continue;
          const positions = attributes.position.array;
          for (let i = 0, l2 = positions.length; i < l2; i += 3) {
            let x2 = positions[i];
            let y = positions[i + 1];
            let z = positions[i + 2];
            const morphTargets = geometry.morphAttributes.position;
            if (morphTargets !== void 0) {
              const morphTargetsRelative = geometry.morphTargetsRelative;
              const morphInfluences = object.morphTargetInfluences;
              for (let t3 = 0, tl = morphTargets.length; t3 < tl; t3++) {
                const influence = morphInfluences[t3];
                if (influence === 0) continue;
                const target = morphTargets[t3];
                if (morphTargetsRelative) {
                  x2 += target.getX(i / 3) * influence;
                  y += target.getY(i / 3) * influence;
                  z += target.getZ(i / 3) * influence;
                } else {
                  x2 += (target.getX(i / 3) - positions[i]) * influence;
                  y += (target.getY(i / 3) - positions[i + 1]) * influence;
                  z += (target.getZ(i / 3) - positions[i + 2]) * influence;
                }
              }
            }
            renderList.pushVertex(x2, y, z);
          }
          if (attributes.normal !== void 0) {
            const normals = attributes.normal.array;
            for (let i = 0, l2 = normals.length; i < l2; i += 3) {
              renderList.pushNormal(normals[i], normals[i + 1], normals[i + 2]);
            }
          }
          if (attributes.color !== void 0) {
            const colors = attributes.color.array;
            for (let i = 0, l2 = colors.length; i < l2; i += 3) {
              renderList.pushColor(colors[i], colors[i + 1], colors[i + 2]);
            }
          }
          if (attributes.uv !== void 0) {
            const uvs = attributes.uv.array;
            for (let i = 0, l2 = uvs.length; i < l2; i += 2) {
              renderList.pushUv(uvs[i], uvs[i + 1]);
            }
          }
          if (geometry.index !== null) {
            const indices = geometry.index.array;
            if (groups.length > 0) {
              for (let g3 = 0; g3 < groups.length; g3++) {
                const group = groups[g3];
                material = isMultiMaterial === true ? object.material[group.materialIndex] : object.material;
                if (material === void 0) continue;
                for (let i = group.start, l2 = group.start + group.count; i < l2; i += 3) {
                  renderList.pushTriangle(indices[i], indices[i + 1], indices[i + 2], material);
                }
              }
            } else {
              for (let i = 0, l2 = indices.length; i < l2; i += 3) {
                renderList.pushTriangle(indices[i], indices[i + 1], indices[i + 2], material);
              }
            }
          } else {
            if (groups.length > 0) {
              for (let g3 = 0; g3 < groups.length; g3++) {
                const group = groups[g3];
                material = isMultiMaterial === true ? object.material[group.materialIndex] : object.material;
                if (material === void 0) continue;
                for (let i = group.start, l2 = group.start + group.count; i < l2; i += 3) {
                  renderList.pushTriangle(i, i + 1, i + 2, material);
                }
              }
            } else {
              for (let i = 0, l2 = positions.length / 3; i < l2; i += 3) {
                renderList.pushTriangle(i, i + 1, i + 2, material);
              }
            }
          }
        } else if (object.isLine) {
          _modelViewProjectionMatrix.multiplyMatrices(_viewProjectionMatrix2, _modelMatrix);
          const attributes = geometry.attributes;
          if (attributes.position !== void 0) {
            const positions = attributes.position.array;
            for (let i = 0, l2 = positions.length; i < l2; i += 3) {
              renderList.pushVertex(positions[i], positions[i + 1], positions[i + 2]);
            }
            if (attributes.color !== void 0) {
              const colors = attributes.color.array;
              for (let i = 0, l2 = colors.length; i < l2; i += 3) {
                renderList.pushColor(colors[i], colors[i + 1], colors[i + 2]);
              }
            }
            if (geometry.index !== null) {
              const indices = geometry.index.array;
              for (let i = 0, l2 = indices.length; i < l2; i += 2) {
                renderList.pushLine(indices[i], indices[i + 1]);
              }
            } else {
              const step = object.isLineSegments ? 2 : 1;
              for (let i = 0, l2 = positions.length / 3 - 1; i < l2; i += step) {
                renderList.pushLine(i, i + 1);
              }
            }
          }
        } else if (object.isPoints) {
          _modelViewProjectionMatrix.multiplyMatrices(_viewProjectionMatrix2, _modelMatrix);
          const attributes = geometry.attributes;
          if (attributes.position !== void 0) {
            const positions = attributes.position.array;
            for (let i = 0, l2 = positions.length; i < l2; i += 3) {
              _vector42.set(positions[i], positions[i + 1], positions[i + 2], 1);
              _vector42.applyMatrix4(_modelViewProjectionMatrix);
              pushPoint(_vector42, object, camera);
            }
          }
        } else if (object.isSprite) {
          object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
          _vector42.set(_modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1);
          _vector42.applyMatrix4(_viewProjectionMatrix2);
          pushPoint(_vector42, object, camera);
        }
      }
      if (sortElements === true) {
        _renderData.elements.sort(painterSort);
      }
      return _renderData;
    };
    function pushPoint(_vector43, object, camera) {
      const invW = 1 / _vector43.w;
      _vector43.z *= invW;
      if (_vector43.z >= -1 && _vector43.z <= 1) {
        _sprite = getNextSpriteInPool();
        _sprite.id = object.id;
        _sprite.x = _vector43.x * invW;
        _sprite.y = _vector43.y * invW;
        _sprite.z = _vector43.z;
        _sprite.renderOrder = object.renderOrder;
        _sprite.object = object;
        _sprite.rotation = object.rotation;
        _sprite.scale.x = object.scale.x * Math.abs(_sprite.x - (_vector43.x + camera.projectionMatrix.elements[0]) / (_vector43.w + camera.projectionMatrix.elements[12]));
        _sprite.scale.y = object.scale.y * Math.abs(_sprite.y - (_vector43.y + camera.projectionMatrix.elements[5]) / (_vector43.w + camera.projectionMatrix.elements[13]));
        _sprite.material = object.material;
        _renderData.elements.push(_sprite);
      }
    }
    function getNextObjectInPool() {
      if (_objectCount === _objectPoolLength) {
        const object = new RenderableObject();
        _objectPool.push(object);
        _objectPoolLength++;
        _objectCount++;
        return object;
      }
      return _objectPool[_objectCount++];
    }
    function getNextVertexInPool() {
      if (_vertexCount === _vertexPoolLength) {
        const vertex = new RenderableVertex();
        _vertexPool.push(vertex);
        _vertexPoolLength++;
        _vertexCount++;
        return vertex;
      }
      return _vertexPool[_vertexCount++];
    }
    function getNextFaceInPool() {
      if (_faceCount === _facePoolLength) {
        const face = new RenderableFace();
        _facePool.push(face);
        _facePoolLength++;
        _faceCount++;
        return face;
      }
      return _facePool[_faceCount++];
    }
    function getNextLineInPool() {
      if (_lineCount === _linePoolLength) {
        const line2 = new RenderableLine();
        _linePool.push(line2);
        _linePoolLength++;
        _lineCount++;
        return line2;
      }
      return _linePool[_lineCount++];
    }
    function getNextSpriteInPool() {
      if (_spriteCount === _spritePoolLength) {
        const sprite = new RenderableSprite();
        _spritePool.push(sprite);
        _spritePoolLength++;
        _spriteCount++;
        return sprite;
      }
      return _spritePool[_spriteCount++];
    }
    function painterSort(a2, b3) {
      if (a2.renderOrder !== b3.renderOrder) {
        return a2.renderOrder - b3.renderOrder;
      } else if (a2.z !== b3.z) {
        return b3.z - a2.z;
      } else if (a2.id !== b3.id) {
        return a2.id - b3.id;
      } else {
        return 0;
      }
    }
    function clipLine(s1, s2) {
      let alpha1 = 0, alpha2 = 1;
      const bc1near = s1.z + s1.w, bc2near = s2.z + s2.w, bc1far = -s1.z + s1.w, bc2far = -s2.z + s2.w;
      if (bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0) {
        return true;
      } else if (bc1near < 0 && bc2near < 0 || bc1far < 0 && bc2far < 0) {
        return false;
      } else {
        if (bc1near < 0) {
          alpha1 = Math.max(alpha1, bc1near / (bc1near - bc2near));
        } else if (bc2near < 0) {
          alpha2 = Math.min(alpha2, bc1near / (bc1near - bc2near));
        }
        if (bc1far < 0) {
          alpha1 = Math.max(alpha1, bc1far / (bc1far - bc2far));
        } else if (bc2far < 0) {
          alpha2 = Math.min(alpha2, bc1far / (bc1far - bc2far));
        }
        if (alpha2 < alpha1) {
          return false;
        } else {
          s1.lerp(s2, alpha1);
          s2.lerp(s1, 1 - alpha2);
          return true;
        }
      }
    }
  }
};

// node_modules/three/examples/jsm/renderers/SVGRenderer.js
var SVGObject = class extends Object3D {
  /**
   * Constructs a new SVG object.
   *
   * @param {SVGElement} node - The SVG element.
   */
  constructor(node) {
    super();
    this.isSVGObject = true;
    this.node = node;
  }
};
var SVGRenderer2 = class {
  /**
   * Constructs a new SVG renderer.
   */
  constructor() {
    let _renderData, _elements, _lights, _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf, _v17, _v26, _v32, _svgNode, _pathCount = 0, _precision = null, _quality = 1, _currentPath, _currentStyle;
    const _this = this, _clipBox = new Box2(), _elemBox = new Box2(), _color5 = new Color(), _diffuseColor = new Color(), _ambientLight = new Color(), _directionalLights = new Color(), _pointLights = new Color(), _clearColor = new Color(), _vector32 = new Vector3(), _centroid = new Vector3(), _normal = new Vector3(), _normalViewMatrix = new Matrix3(), _viewMatrix2 = new Matrix4(), _viewProjectionMatrix2 = new Matrix4(), _svgPathPool = [], _projector = new Projector(), _svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    this.domElement = _svg;
    this.autoClear = true;
    this.sortObjects = true;
    this.sortElements = true;
    this.overdraw = 0.5;
    this.outputColorSpace = SRGBColorSpace;
    this.info = {
      render: {
        vertices: 0,
        faces: 0
      }
    };
    this.setQuality = function(quality) {
      switch (quality) {
        case "high":
          _quality = 1;
          break;
        case "low":
          _quality = 0;
          break;
      }
    };
    this.setClearColor = function(color) {
      _clearColor.set(color);
    };
    this.setPixelRatio = function() {
    };
    this.setSize = function(width2, height2) {
      _svgWidth = width2;
      _svgHeight = height2;
      _svgWidthHalf = _svgWidth / 2;
      _svgHeightHalf = _svgHeight / 2;
      _svg.setAttribute("viewBox", -_svgWidthHalf + " " + -_svgHeightHalf + " " + _svgWidth + " " + _svgHeight);
      _svg.setAttribute("width", _svgWidth);
      _svg.setAttribute("height", _svgHeight);
      _clipBox.min.set(-_svgWidthHalf, -_svgHeightHalf);
      _clipBox.max.set(_svgWidthHalf, _svgHeightHalf);
    };
    this.getSize = function() {
      return {
        width: _svgWidth,
        height: _svgHeight
      };
    };
    this.setPrecision = function(precision) {
      _precision = precision;
    };
    function removeChildNodes() {
      _pathCount = 0;
      while (_svg.childNodes.length > 0) {
        _svg.removeChild(_svg.childNodes[0]);
      }
    }
    function convert(c2) {
      return _precision !== null ? c2.toFixed(_precision) : c2;
    }
    this.clear = function() {
      removeChildNodes();
      _svg.style.backgroundColor = _clearColor.getStyle(_this.outputColorSpace);
    };
    this.render = function(scene, camera) {
      if (camera instanceof Camera === false) {
        console.error("THREE.SVGRenderer.render: camera is not an instance of Camera.");
        return;
      }
      const background = scene.background;
      if (background && background.isColor) {
        removeChildNodes();
        _svg.style.backgroundColor = background.getStyle(_this.outputColorSpace);
      } else if (this.autoClear === true) {
        this.clear();
      }
      _this.info.render.vertices = 0;
      _this.info.render.faces = 0;
      _viewMatrix2.copy(camera.matrixWorldInverse);
      _viewProjectionMatrix2.multiplyMatrices(camera.projectionMatrix, _viewMatrix2);
      _renderData = _projector.projectScene(scene, camera, this.sortObjects, this.sortElements);
      _elements = _renderData.elements;
      _lights = _renderData.lights;
      _normalViewMatrix.getNormalMatrix(camera.matrixWorldInverse);
      calculateLights(_lights);
      _currentPath = "";
      _currentStyle = "";
      for (let e = 0, el = _elements.length; e < el; e++) {
        const element = _elements[e];
        const material = element.material;
        if (material === void 0 || material.opacity === 0) continue;
        _elemBox.makeEmpty();
        if (element instanceof RenderableSprite) {
          _v17 = element;
          _v17.x *= _svgWidthHalf;
          _v17.y *= -_svgHeightHalf;
          renderSprite(_v17, element, material);
        } else if (element instanceof RenderableLine) {
          _v17 = element.v1;
          _v26 = element.v2;
          _v17.positionScreen.x *= _svgWidthHalf;
          _v17.positionScreen.y *= -_svgHeightHalf;
          _v26.positionScreen.x *= _svgWidthHalf;
          _v26.positionScreen.y *= -_svgHeightHalf;
          _elemBox.setFromPoints([_v17.positionScreen, _v26.positionScreen]);
          if (_clipBox.intersectsBox(_elemBox) === true) {
            renderLine(_v17, _v26, material);
          }
        } else if (element instanceof RenderableFace) {
          _v17 = element.v1;
          _v26 = element.v2;
          _v32 = element.v3;
          if (_v17.positionScreen.z < -1 || _v17.positionScreen.z > 1) continue;
          if (_v26.positionScreen.z < -1 || _v26.positionScreen.z > 1) continue;
          if (_v32.positionScreen.z < -1 || _v32.positionScreen.z > 1) continue;
          _v17.positionScreen.x *= _svgWidthHalf;
          _v17.positionScreen.y *= -_svgHeightHalf;
          _v26.positionScreen.x *= _svgWidthHalf;
          _v26.positionScreen.y *= -_svgHeightHalf;
          _v32.positionScreen.x *= _svgWidthHalf;
          _v32.positionScreen.y *= -_svgHeightHalf;
          if (this.overdraw > 0) {
            expand(_v17.positionScreen, _v26.positionScreen, this.overdraw);
            expand(_v26.positionScreen, _v32.positionScreen, this.overdraw);
            expand(_v32.positionScreen, _v17.positionScreen, this.overdraw);
          }
          _elemBox.setFromPoints([
            _v17.positionScreen,
            _v26.positionScreen,
            _v32.positionScreen
          ]);
          if (_clipBox.intersectsBox(_elemBox) === true) {
            renderFace3(_v17, _v26, _v32, element, material);
          }
        }
      }
      flushPath();
      scene.traverseVisible(function(object) {
        if (object.isSVGObject) {
          _vector32.setFromMatrixPosition(object.matrixWorld);
          _vector32.applyMatrix4(_viewProjectionMatrix2);
          if (_vector32.z < -1 || _vector32.z > 1) return;
          const x2 = _vector32.x * _svgWidthHalf;
          const y = -_vector32.y * _svgHeightHalf;
          const node = object.node;
          node.setAttribute("transform", "translate(" + x2 + "," + y + ")");
          _svg.appendChild(node);
        }
      });
    };
    function calculateLights(lights) {
      _ambientLight.setRGB(0, 0, 0);
      _directionalLights.setRGB(0, 0, 0);
      _pointLights.setRGB(0, 0, 0);
      for (let l2 = 0, ll = lights.length; l2 < ll; l2++) {
        const light = lights[l2];
        const lightColor = light.color;
        if (light.isAmbientLight) {
          _ambientLight.r += lightColor.r;
          _ambientLight.g += lightColor.g;
          _ambientLight.b += lightColor.b;
        } else if (light.isDirectionalLight) {
          _directionalLights.r += lightColor.r;
          _directionalLights.g += lightColor.g;
          _directionalLights.b += lightColor.b;
        } else if (light.isPointLight) {
          _pointLights.r += lightColor.r;
          _pointLights.g += lightColor.g;
          _pointLights.b += lightColor.b;
        }
      }
    }
    function calculateLight(lights, position2, normal, color) {
      for (let l2 = 0, ll = lights.length; l2 < ll; l2++) {
        const light = lights[l2];
        const lightColor = light.color;
        if (light.isDirectionalLight) {
          const lightPosition = _vector32.setFromMatrixPosition(light.matrixWorld).normalize();
          let amount = normal.dot(lightPosition);
          if (amount <= 0) continue;
          amount *= light.intensity;
          color.r += lightColor.r * amount;
          color.g += lightColor.g * amount;
          color.b += lightColor.b * amount;
        } else if (light.isPointLight) {
          const lightPosition = _vector32.setFromMatrixPosition(light.matrixWorld);
          let amount = normal.dot(_vector32.subVectors(lightPosition, position2).normalize());
          if (amount <= 0) continue;
          amount *= light.distance == 0 ? 1 : 1 - Math.min(position2.distanceTo(lightPosition) / light.distance, 1);
          if (amount == 0) continue;
          amount *= light.intensity;
          color.r += lightColor.r * amount;
          color.g += lightColor.g * amount;
          color.b += lightColor.b * amount;
        }
      }
    }
    function renderSprite(v12, element, material) {
      let scaleX = element.scale.x * _svgWidthHalf;
      let scaleY = element.scale.y * _svgHeightHalf;
      if (material.isPointsMaterial) {
        scaleX *= material.size;
        scaleY *= material.size;
      }
      const path = "M" + convert(v12.x - scaleX * 0.5) + "," + convert(v12.y - scaleY * 0.5) + "h" + convert(scaleX) + "v" + convert(scaleY) + "h" + convert(-scaleX) + "z";
      let style = "";
      if (material.isSpriteMaterial || material.isPointsMaterial) {
        style = "fill:" + material.color.getStyle(_this.outputColorSpace) + ";fill-opacity:" + material.opacity;
      }
      addPath(style, path);
    }
    function renderLine(v12, v2, material) {
      const path = "M" + convert(v12.positionScreen.x) + "," + convert(v12.positionScreen.y) + "L" + convert(v2.positionScreen.x) + "," + convert(v2.positionScreen.y);
      if (material.isLineBasicMaterial) {
        let style = "fill:none;stroke:" + material.color.getStyle(_this.outputColorSpace) + ";stroke-opacity:" + material.opacity + ";stroke-width:" + material.linewidth + ";stroke-linecap:" + material.linecap;
        if (material.isLineDashedMaterial) {
          style = style + ";stroke-dasharray:" + material.dashSize + "," + material.gapSize;
        }
        addPath(style, path);
      }
    }
    function renderFace3(v12, v2, v3, element, material) {
      _this.info.render.vertices += 3;
      _this.info.render.faces++;
      const path = "M" + convert(v12.positionScreen.x) + "," + convert(v12.positionScreen.y) + "L" + convert(v2.positionScreen.x) + "," + convert(v2.positionScreen.y) + "L" + convert(v3.positionScreen.x) + "," + convert(v3.positionScreen.y) + "z";
      let style = "";
      if (material.isMeshBasicMaterial) {
        _color5.copy(material.color);
        if (material.vertexColors) {
          _color5.multiply(element.color);
        }
      } else if (material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial) {
        _diffuseColor.copy(material.color);
        if (material.vertexColors) {
          _diffuseColor.multiply(element.color);
        }
        _color5.copy(_ambientLight);
        _centroid.copy(v12.positionWorld).add(v2.positionWorld).add(v3.positionWorld).divideScalar(3);
        calculateLight(_lights, _centroid, element.normalModel, _color5);
        _color5.multiply(_diffuseColor).add(material.emissive);
      } else if (material.isMeshNormalMaterial) {
        _normal.copy(element.normalModel).applyMatrix3(_normalViewMatrix).normalize();
        _color5.setRGB(_normal.x, _normal.y, _normal.z).multiplyScalar(0.5).addScalar(0.5);
      }
      if (material.wireframe) {
        style = "fill:none;stroke:" + _color5.getStyle(_this.outputColorSpace) + ";stroke-opacity:" + material.opacity + ";stroke-width:" + material.wireframeLinewidth + ";stroke-linecap:" + material.wireframeLinecap + ";stroke-linejoin:" + material.wireframeLinejoin;
      } else {
        style = "fill:" + _color5.getStyle(_this.outputColorSpace) + ";fill-opacity:" + material.opacity;
      }
      addPath(style, path);
    }
    function expand(v12, v2, pixels) {
      let x2 = v2.x - v12.x, y = v2.y - v12.y;
      const det = x2 * x2 + y * y;
      if (det === 0) return;
      const idet = pixels / Math.sqrt(det);
      x2 *= idet;
      y *= idet;
      v2.x += x2;
      v2.y += y;
      v12.x -= x2;
      v12.y -= y;
    }
    function addPath(style, path) {
      if (_currentStyle === style) {
        _currentPath += path;
      } else {
        flushPath();
        _currentStyle = style;
        _currentPath = path;
      }
    }
    function flushPath() {
      if (_currentPath) {
        _svgNode = getPathNode(_pathCount++);
        _svgNode.setAttribute("d", _currentPath);
        _svgNode.setAttribute("style", _currentStyle);
        _svg.appendChild(_svgNode);
      }
      _currentPath = "";
      _currentStyle = "";
    }
    function getPathNode(id) {
      if (_svgPathPool[id] == null) {
        _svgPathPool[id] = document.createElementNS("http://www.w3.org/2000/svg", "path");
        if (_quality == 0) {
          _svgPathPool[id].setAttribute("shape-rendering", "crispEdges");
        }
        return _svgPathPool[id];
      }
      return _svgPathPool[id];
    }
  }
};

// node_modules/three/examples/jsm/shaders/ACESFilmicToneMappingShader.js
var ACESFilmicToneMappingShader = {
  name: "ACESFilmicToneMappingShader",
  uniforms: {
    "tDiffuse": { value: null },
    "exposure": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		#define saturate(a) clamp( a, 0.0, 1.0 )

		uniform sampler2D tDiffuse;

		uniform float exposure;

		varying vec2 vUv;

		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 ) {

		// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
			const mat3 ACESInputMat = mat3(
				vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source
				vec3( 0.35458, 0.90834, 0.13383 ),
				vec3( 0.04823, 0.01566, 0.83777 )
			);

		// ODT_SAT => XYZ => D60_2_D65 => sRGB
			const mat3 ACESOutputMat = mat3(
				vec3(  1.60475, -0.10208, -0.00327 ), // transposed from source
				vec3( -0.53108,  1.10813, -0.07276 ),
				vec3( -0.07367, -0.00605,  1.07602 )
			);

			color = ACESInputMat * color;

		// Apply RRT and ODT
			color = RRTAndODTFit( color );

			color = ACESOutputMat * color;

		// Clamp to [0, 1]
			return saturate( color );

		}

		void main() {

			vec4 tex = texture2D( tDiffuse, vUv );

			tex.rgb *= exposure / 0.6; // pre-exposed, outside of the tone mapping function

			gl_FragColor = vec4( ACESFilmicToneMapping( tex.rgb ), tex.a );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/BasicShader.js
var BasicShader = {
  name: "BasicShader",
  uniforms: {},
  vertexShader: (
    /* glsl */
    `

		void main() {

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		void main() {

			gl_FragColor = vec4( 1.0, 0.0, 0.0, 0.5 );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/BleachBypassShader.js
var BleachBypassShader = {
  name: "BleachBypassShader",
  uniforms: {
    "tDiffuse": { value: null },
    "opacity": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float opacity;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 base = texture2D( tDiffuse, vUv );

			float lum = luminance( base.rgb );
			vec3 blend = vec3( lum );

			float L = min( 1.0, max( 0.0, 10.0 * ( lum - 0.45 ) ) );

			vec3 result1 = 2.0 * base.rgb * blend;
			vec3 result2 = 1.0 - 2.0 * ( 1.0 - blend ) * ( 1.0 - base.rgb );

			vec3 newColor = mix( result1, result2, L );

			float A2 = opacity * base.a;
			vec3 mixRGB = A2 * newColor.rgb;
			mixRGB += ( ( 1.0 - A2 ) * base.rgb );

			gl_FragColor = vec4( mixRGB, base.a );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/BlendShader.js
var BlendShader = {
  name: "BlendShader",
  uniforms: {
    "tDiffuse1": { value: null },
    "tDiffuse2": { value: null },
    "mixRatio": { value: 0.5 },
    "opacity": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float opacity;
		uniform float mixRatio;

		uniform sampler2D tDiffuse1;
		uniform sampler2D tDiffuse2;

		varying vec2 vUv;

		void main() {

			vec4 texel1 = texture2D( tDiffuse1, vUv );
			vec4 texel2 = texture2D( tDiffuse2, vUv );
			gl_FragColor = opacity * mix( texel1, texel2, mixRatio );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/BokehShader2.js
var BokehShader2 = {
  name: "BokehShader",
  uniforms: {
    "textureWidth": { value: 1 },
    "textureHeight": { value: 1 },
    "focalDepth": { value: 1 },
    "focalLength": { value: 24 },
    "fstop": { value: 0.9 },
    "tColor": { value: null },
    "tDepth": { value: null },
    "maxblur": { value: 1 },
    "showFocus": { value: 0 },
    "manualdof": { value: 0 },
    "vignetting": { value: 0 },
    "depthblur": { value: 0 },
    "threshold": { value: 0.5 },
    "gain": { value: 2 },
    "bias": { value: 0.5 },
    "fringe": { value: 0.7 },
    "znear": { value: 0.1 },
    "zfar": { value: 100 },
    "noise": { value: 1 },
    "dithering": { value: 1e-4 },
    "pentagon": { value: 0 },
    "shaderFocus": { value: 1 },
    "focusCoords": { value: new Vector2() }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		#include <common>

		varying vec2 vUv;

		uniform sampler2D tColor;
		uniform sampler2D tDepth;
		uniform float textureWidth;
		uniform float textureHeight;

		uniform float focalDepth;  //focal distance value in meters, but you may use autofocus option below
		uniform float focalLength; //focal length in mm
		uniform float fstop; //f-stop value
		uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range)

		/*
		make sure that these two values are the same for your camera, otherwise distances will be wrong.
		*/

		uniform float znear; // camera clipping start
		uniform float zfar; // camera clipping end

		//------------------------------------------
		//user variables

		const int samples = SAMPLES; //samples on the first ring
		const int rings = RINGS; //ring count

		const int maxringsamples = rings * samples;

		uniform bool manualdof; // manual dof calculation
		float ndofstart = 1.0; // near dof blur start
		float ndofdist = 2.0; // near dof blur falloff distance
		float fdofstart = 1.0; // far dof blur start
		float fdofdist = 3.0; // far dof blur falloff distance

		float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm)

		uniform bool vignetting; // use optical lens vignetting

		float vignout = 1.3; // vignetting outer border
		float vignin = 0.0; // vignetting inner border
		float vignfade = 22.0; // f-stops till vignette fades

		uniform bool shaderFocus;
		// disable if you use external focalDepth value

		uniform vec2 focusCoords;
		// autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right)
		// if center of screen use vec2(0.5, 0.5);

		uniform float maxblur;
		//clamp value of max blur (0.0 = no blur, 1.0 default)

		uniform float threshold; // highlight threshold;
		uniform float gain; // highlight gain;

		uniform float bias; // bokeh edge bias
		uniform float fringe; // bokeh chromatic aberration / fringing

		uniform bool noise; //use noise instead of pattern for sample dithering

		uniform float dithering;

		uniform bool depthblur; // blur the depth buffer
		float dbsize = 1.25; // depth blur size

		/*
		next part is experimental
		not looking good with small sample and ring count
		looks okay starting from samples = 4, rings = 4
		*/

		uniform bool pentagon; //use pentagon as bokeh shape?
		float feather = 0.4; //pentagon shape feather

		//------------------------------------------

		float penta(vec2 coords) {
			//pentagonal shape
			float scale = float(rings) - 1.3;
			vec4  HS0 = vec4( 1.0,         0.0,         0.0,  1.0);
			vec4  HS1 = vec4( 0.309016994, 0.951056516, 0.0,  1.0);
			vec4  HS2 = vec4(-0.809016994, 0.587785252, 0.0,  1.0);
			vec4  HS3 = vec4(-0.809016994,-0.587785252, 0.0,  1.0);
			vec4  HS4 = vec4( 0.309016994,-0.951056516, 0.0,  1.0);
			vec4  HS5 = vec4( 0.0        ,0.0         , 1.0,  1.0);

			vec4  one = vec4( 1.0 );

			vec4 P = vec4((coords),vec2(scale, scale));

			vec4 dist = vec4(0.0);
			float inorout = -4.0;

			dist.x = dot( P, HS0 );
			dist.y = dot( P, HS1 );
			dist.z = dot( P, HS2 );
			dist.w = dot( P, HS3 );

			dist = smoothstep( -feather, feather, dist );

			inorout += dot( dist, one );

			dist.x = dot( P, HS4 );
			dist.y = HS5.w - abs( P.z );

			dist = smoothstep( -feather, feather, dist );
			inorout += dist.x;

			return clamp( inorout, 0.0, 1.0 );
		}

		float bdepth(vec2 coords) {
			// Depth buffer blur
			float d = 0.0;
			float kernel[9];
			vec2 offset[9];

			vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize;

			offset[0] = vec2(-wh.x,-wh.y);
			offset[1] = vec2( 0.0, -wh.y);
			offset[2] = vec2( wh.x -wh.y);

			offset[3] = vec2(-wh.x,  0.0);
			offset[4] = vec2( 0.0,   0.0);
			offset[5] = vec2( wh.x,  0.0);

			offset[6] = vec2(-wh.x, wh.y);
			offset[7] = vec2( 0.0,  wh.y);
			offset[8] = vec2( wh.x, wh.y);

			kernel[0] = 1.0/16.0;   kernel[1] = 2.0/16.0;   kernel[2] = 1.0/16.0;
			kernel[3] = 2.0/16.0;   kernel[4] = 4.0/16.0;   kernel[5] = 2.0/16.0;
			kernel[6] = 1.0/16.0;   kernel[7] = 2.0/16.0;   kernel[8] = 1.0/16.0;


			for( int i=0; i<9; i++ ) {
				float tmp = texture2D(tDepth, coords + offset[i]).r;
				d += tmp * kernel[i];
			}

			return d;
		}


		vec3 color(vec2 coords,float blur) {
			//processing the sample

			vec3 col = vec3(0.0);
			vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight);

			col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r;
			col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g;
			col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b;

			vec3 lumcoeff = vec3(0.299,0.587,0.114);
			float lum = dot(col.rgb, lumcoeff);
			float thresh = max((lum-threshold)*gain, 0.0);
			return col+mix(vec3(0.0),col,thresh*blur);
		}

		vec3 debugFocus(vec3 col, float blur, float depth) {
			float edge = 0.002*depth; //distance based edge smoothing
			float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0);
			float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0);

			col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6);
			col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2);

			return col;
		}

		float linearize(float depth) {
			return -zfar * znear / (depth * (zfar - znear) - zfar);
		}

		float vignette() {
			float dist = distance(vUv.xy, vec2(0.5,0.5));
			dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist);
			return clamp(dist,0.0,1.0);
		}

		float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) {
			float rings2 = float(rings);
			float step = PI*2.0 / float(ringsamples);
			float pw = cos(j*step)*i;
			float ph = sin(j*step)*i;
			float p = 1.0;
			if (pentagon) {
				p = penta(vec2(pw,ph));
			}
			col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p;
			return 1.0 * mix(1.0, i /rings2, bias) * p;
		}

		void main() {
			//scene depth calculation

			float depth = linearize(texture2D(tDepth,vUv.xy).x);

			// Blur depth?
			if ( depthblur ) {
				depth = linearize(bdepth(vUv.xy));
			}

			//focal plane calculation

			float fDepth = focalDepth;

			if (shaderFocus) {

				fDepth = linearize(texture2D(tDepth,focusCoords).x);

			}

			// dof blur factor calculation

			float blur = 0.0;

			if (manualdof) {
				float a = depth-fDepth; // Focal plane
				float b = (a-fdofstart)/fdofdist; // Far DoF
				float c = (-a-ndofstart)/ndofdist; // Near Dof
				blur = (a>0.0) ? b : c;
			} else {
				float f = focalLength; // focal length in mm
				float d = fDepth*1000.0; // focal plane in mm
				float o = depth*1000.0; // depth in mm

				float a = (o*f)/(o-f);
				float b = (d*f)/(d-f);
				float c = (d-f)/(d*fstop*CoC);

				blur = abs(a-b)*c;
			}

			blur = clamp(blur,0.0,1.0);

			// calculation of pattern for dithering

			vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur;

			// getting blur x and y step factor

			float w = (1.0/textureWidth)*blur*maxblur+noise.x;
			float h = (1.0/textureHeight)*blur*maxblur+noise.y;

			// calculation of final color

			vec3 col = vec3(0.0);

			if(blur < 0.05) {
				//some optimization thingy
				col = texture2D(tColor, vUv.xy).rgb;
			} else {
				col = texture2D(tColor, vUv.xy).rgb;
				float s = 1.0;
				int ringsamples;

				for (int i = 1; i <= rings; i++) {
					/*unboxstart*/
					ringsamples = i * samples;

					for (int j = 0 ; j < maxringsamples ; j++) {
						if (j >= ringsamples) break;
						s += gather(float(i), float(j), ringsamples, col, w, h, blur);
					}
					/*unboxend*/
				}

				col /= s; //divide by sample count
			}

			if (showFocus) {
				col = debugFocus(col, blur, depth);
			}

			if (vignetting) {
				col *= vignette();
			}

			gl_FragColor.rgb = col;
			gl_FragColor.a = 1.0;

			#include <tonemapping_fragment>
			#include <colorspace_fragment>
		}`
  )
};

// node_modules/three/examples/jsm/shaders/BrightnessContrastShader.js
var BrightnessContrastShader = {
  name: "BrightnessContrastShader",
  uniforms: {
    "tDiffuse": { value: null },
    "brightness": { value: 0 },
    "contrast": { value: 0 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform float brightness;
		uniform float contrast;

		varying vec2 vUv;

		void main() {

			gl_FragColor = texture2D( tDiffuse, vUv );

			gl_FragColor.rgb += brightness;

			if (contrast > 0.0) {
				gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - contrast) + 0.5;
			} else {
				gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + contrast) + 0.5;
			}

		}`
  )
};

// node_modules/three/examples/jsm/shaders/ColorCorrectionShader.js
var ColorCorrectionShader = {
  name: "ColorCorrectionShader",
  uniforms: {
    "tDiffuse": { value: null },
    "powRGB": { value: new Vector3(2, 2, 2) },
    "mulRGB": { value: new Vector3(1, 1, 1) },
    "addRGB": { value: new Vector3(0, 0, 0) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform vec3 powRGB;
		uniform vec3 mulRGB;
		uniform vec3 addRGB;

		varying vec2 vUv;

		void main() {

			gl_FragColor = texture2D( tDiffuse, vUv );
			gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/ColorifyShader.js
var ColorifyShader = {
  name: "ColorifyShader",
  uniforms: {
    "tDiffuse": { value: null },
    "color": { value: new Color(16777215) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform vec3 color;
		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );

			float v = luminance( texel.xyz );

			gl_FragColor = vec4( v * color, texel.w );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/DOFMipMapShader.js
var DOFMipMapShader = {
  name: "DOFMipMapShader",
  uniforms: {
    "tColor": { value: null },
    "tDepth": { value: null },
    "focus": { value: 1 },
    "maxblur": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float focus;
		uniform float maxblur;

		uniform sampler2D tColor;
		uniform sampler2D tDepth;

		varying vec2 vUv;

		void main() {

			vec4 depth = texture2D( tDepth, vUv );

			float factor = depth.x - focus;

			vec4 col = texture2D( tColor, vUv, 2.0 * maxblur * abs( focus - depth.x ) );

			gl_FragColor = col;
			gl_FragColor.a = 1.0;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/ExposureShader.js
var ExposureShader = {
  name: "ExposureShader",
  uniforms: {
    "tDiffuse": { value: null },
    "exposure": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float exposure;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			gl_FragColor = texture2D( tDiffuse, vUv );
			gl_FragColor.rgb *= exposure;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/FXAAShader.js
var FXAAShader = {
  name: "FXAAShader",
  uniforms: {
    "tDiffuse": { value: null },
    "resolution": { value: new Vector2(1 / 1024, 1 / 512) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform vec2 resolution;
		varying vec2 vUv;

		#define EDGE_STEP_COUNT 6
		#define EDGE_GUESS 8.0
		#define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0
		const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS );

		float _ContrastThreshold = 0.0312;
		float _RelativeThreshold = 0.063;
		float _SubpixelBlending = 1.0;

		vec4 Sample( sampler2D  tex2D, vec2 uv ) {

			return texture( tex2D, uv );

		}

		float SampleLuminance( sampler2D tex2D, vec2 uv ) {

			return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) );

		}

		float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) {

			uv += texSize * vec2(uOffset, vOffset);
			return SampleLuminance(tex2D, uv);

		}

		struct LuminanceData {

			float m, n, e, s, w;
			float ne, nw, se, sw;
			float highest, lowest, contrast;

		};

		LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) {

			LuminanceData l;
			l.m = SampleLuminance( tex2D, uv );
			l.n = SampleLuminance( tex2D, texSize, uv,  0.0,  1.0 );
			l.e = SampleLuminance( tex2D, texSize, uv,  1.0,  0.0 );
			l.s = SampleLuminance( tex2D, texSize, uv,  0.0, -1.0 );
			l.w = SampleLuminance( tex2D, texSize, uv, -1.0,  0.0 );

			l.ne = SampleLuminance( tex2D, texSize, uv,  1.0,  1.0 );
			l.nw = SampleLuminance( tex2D, texSize, uv, -1.0,  1.0 );
			l.se = SampleLuminance( tex2D, texSize, uv,  1.0, -1.0 );
			l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 );

			l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m );
			l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m );
			l.contrast = l.highest - l.lowest;
			return l;

		}

		bool ShouldSkipPixel( LuminanceData l ) {

			float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest );
			return l.contrast < threshold;

		}

		float DeterminePixelBlendFactor( LuminanceData l ) {

			float f = 2.0 * ( l.n + l.e + l.s + l.w );
			f += l.ne + l.nw + l.se + l.sw;
			f *= 1.0 / 12.0;
			f = abs( f - l.m );
			f = clamp( f / l.contrast, 0.0, 1.0 );

			float blendFactor = smoothstep( 0.0, 1.0, f );
			return blendFactor * blendFactor * _SubpixelBlending;

		}

		struct EdgeData {

			bool isHorizontal;
			float pixelStep;
			float oppositeLuminance, gradient;

		};

		EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) {

			EdgeData e;
			float horizontal =
				abs( l.n + l.s - 2.0 * l.m ) * 2.0 +
				abs( l.ne + l.se - 2.0 * l.e ) +
				abs( l.nw + l.sw - 2.0 * l.w );
			float vertical =
				abs( l.e + l.w - 2.0 * l.m ) * 2.0 +
				abs( l.ne + l.nw - 2.0 * l.n ) +
				abs( l.se + l.sw - 2.0 * l.s );
			e.isHorizontal = horizontal >= vertical;

			float pLuminance = e.isHorizontal ? l.n : l.e;
			float nLuminance = e.isHorizontal ? l.s : l.w;
			float pGradient = abs( pLuminance - l.m );
			float nGradient = abs( nLuminance - l.m );

			e.pixelStep = e.isHorizontal ? texSize.y : texSize.x;

			if (pGradient < nGradient) {

				e.pixelStep = -e.pixelStep;
				e.oppositeLuminance = nLuminance;
				e.gradient = nGradient;

			} else {

				e.oppositeLuminance = pLuminance;
				e.gradient = pGradient;

			}

			return e;

		}

		float DetermineEdgeBlendFactor( sampler2D  tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) {

			vec2 uvEdge = uv;
			vec2 edgeStep;
			if (e.isHorizontal) {

				uvEdge.y += e.pixelStep * 0.5;
				edgeStep = vec2( texSize.x, 0.0 );

			} else {

				uvEdge.x += e.pixelStep * 0.5;
				edgeStep = vec2( 0.0, texSize.y );

			}

			float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5;
			float gradientThreshold = e.gradient * 0.25;

			vec2 puv = uvEdge + edgeStep * edgeSteps[0];
			float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance;
			bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold;

			for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) {

				puv += edgeStep * edgeSteps[i];
				pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance;
				pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold;

			}

			if ( !pAtEnd ) {

				puv += edgeStep * EDGE_GUESS;

			}

			vec2 nuv = uvEdge - edgeStep * edgeSteps[0];
			float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance;
			bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold;

			for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) {

				nuv -= edgeStep * edgeSteps[i];
				nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance;
				nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold;

			}

			if ( !nAtEnd ) {

				nuv -= edgeStep * EDGE_GUESS;

			}

			float pDistance, nDistance;
			if ( e.isHorizontal ) {

				pDistance = puv.x - uv.x;
				nDistance = uv.x - nuv.x;

			} else {

				pDistance = puv.y - uv.y;
				nDistance = uv.y - nuv.y;

			}

			float shortestDistance;
			bool deltaSign;
			if ( pDistance <= nDistance ) {

				shortestDistance = pDistance;
				deltaSign = pLuminanceDelta >= 0.0;

			} else {

				shortestDistance = nDistance;
				deltaSign = nLuminanceDelta >= 0.0;

			}

			if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) {

				return 0.0;

			}

			return 0.5 - shortestDistance / ( pDistance + nDistance );

		}

		vec4 ApplyFXAA( sampler2D  tex2D, vec2 texSize, vec2 uv ) {

			LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv );
			if ( ShouldSkipPixel( luminance ) ) {

				return Sample( tex2D, uv );

			}

			float pixelBlend = DeterminePixelBlendFactor( luminance );
			EdgeData edge = DetermineEdge( texSize, luminance );
			float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv );
			float finalBlend = max( pixelBlend, edgeBlend );

			if (edge.isHorizontal) {

				uv.y += edge.pixelStep * finalBlend;

			} else {

				uv.x += edge.pixelStep * finalBlend;

			}

			return Sample( tex2D, uv );

		}

		void main() {

			gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/FocusShader.js
var FocusShader = {
  name: "FocusShader",
  uniforms: {
    "tDiffuse": { value: null },
    "screenWidth": { value: 1024 },
    "screenHeight": { value: 1024 },
    "sampleDistance": { value: 0.94 },
    "waveFactor": { value: 125e-5 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float screenWidth;
		uniform float screenHeight;
		uniform float sampleDistance;
		uniform float waveFactor;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 color, org, tmp, add;
			float sample_dist, f;
			vec2 vin;
			vec2 uv = vUv;

			add = color = org = texture2D( tDiffuse, uv );

			vin = ( uv - vec2( 0.5 ) ) * vec2( 1.4 );
			sample_dist = dot( vin, vin ) * 2.0;

			f = ( waveFactor * 100.0 + sample_dist ) * sampleDistance * 4.0;

			vec2 sampleSize = vec2(  1.0 / screenWidth, 1.0 / screenHeight ) * vec2( f );

			add += tmp = texture2D( tDiffuse, uv + vec2( 0.111964, 0.993712 ) * sampleSize );
			if( tmp.b < color.b ) color = tmp;

			add += tmp = texture2D( tDiffuse, uv + vec2( 0.846724, 0.532032 ) * sampleSize );
			if( tmp.b < color.b ) color = tmp;

			add += tmp = texture2D( tDiffuse, uv + vec2( 0.943883, -0.330279 ) * sampleSize );
			if( tmp.b < color.b ) color = tmp;

			add += tmp = texture2D( tDiffuse, uv + vec2( 0.330279, -0.943883 ) * sampleSize );
			if( tmp.b < color.b ) color = tmp;

			add += tmp = texture2D( tDiffuse, uv + vec2( -0.532032, -0.846724 ) * sampleSize );
			if( tmp.b < color.b ) color = tmp;

			add += tmp = texture2D( tDiffuse, uv + vec2( -0.993712, -0.111964 ) * sampleSize );
			if( tmp.b < color.b ) color = tmp;

			add += tmp = texture2D( tDiffuse, uv + vec2( -0.707107, 0.707107 ) * sampleSize );
			if( tmp.b < color.b ) color = tmp;

			color = color * vec4( 2.0 ) - ( add / vec4( 8.0 ) );
			color = color + ( add / vec4( 8.0 ) - color ) * ( vec4( 1.0 ) - vec4( sample_dist * 0.5 ) );

			gl_FragColor = vec4( color.rgb * color.rgb * vec3( 0.95 ) + color.rgb, 1.0 );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/FreiChenShader.js
var FreiChenShader = {
  name: "FreiChenShader",
  uniforms: {
    "tDiffuse": { value: null },
    "aspect": { value: new Vector2(512, 512) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		varying vec2 vUv;

		uniform vec2 aspect;

		vec2 texel = vec2( 1.0 / aspect.x, 1.0 / aspect.y );


		mat3 G[9];

		// hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45

		const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 );
		const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 );
		const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 );
		const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 );
		const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 );
		const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 );
		const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 );
		const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 );
		const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 );

		void main(void)
		{

			G[0] = g0,
			G[1] = g1,
			G[2] = g2,
			G[3] = g3,
			G[4] = g4,
			G[5] = g5,
			G[6] = g6,
			G[7] = g7,
			G[8] = g8;

			mat3 I;
			float cnv[9];
			vec3 sample;

		/* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */
			for (float i=0.0; i<3.0; i++) {
				for (float j=0.0; j<3.0; j++) {
					sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb;
					I[int(i)][int(j)] = length(sample);
				}
			}

		/* calculate the convolution values for all the masks */
			for (int i=0; i<9; i++) {
				float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);
				cnv[i] = dp3 * dp3;
			}

			float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]);
			float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M);

			gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0);
		}`
  )
};

// node_modules/three/examples/jsm/shaders/GammaCorrectionShader.js
var GammaCorrectionShader = {
  name: "GammaCorrectionShader",
  uniforms: {
    "tDiffuse": { value: null }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 tex = texture2D( tDiffuse, vUv );

			gl_FragColor = sRGBTransferOETF( tex );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/GodRaysShader.js
var GodRaysDepthMaskShader = {
  name: "GodRaysDepthMaskShader",
  uniforms: {
    tInput: {
      value: null
    }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

		 vUv = uv;
		 gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		varying vec2 vUv;

		uniform sampler2D tInput;

		void main() {

			gl_FragColor = vec4( 1.0 ) - texture2D( tInput, vUv );

		}`
  )
};
var GodRaysGenerateShader = {
  name: "GodRaysGenerateShader",
  uniforms: {
    tInput: {
      value: null
    },
    fStepSize: {
      value: 1
    },
    vSunPositionScreenSpace: {
      value: new Vector3()
    }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

		 vUv = uv;
		 gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		#define TAPS_PER_PASS 6.0

		varying vec2 vUv;

		uniform sampler2D tInput;

		uniform vec3 vSunPositionScreenSpace;
		uniform float fStepSize; // filter step size

		void main() {

		// delta from current pixel to "sun" position

			vec2 delta = vSunPositionScreenSpace.xy - vUv;
			float dist = length( delta );

		// Step vector (uv space)

			vec2 stepv = fStepSize * delta / dist;

		// Number of iterations between pixel and sun

			float iters = dist/fStepSize;

			vec2 uv = vUv.xy;
			float col = 0.0;

		// This breaks ANGLE in Chrome 22
		//	- see http://code.google.com/p/chromium/issues/detail?id=153105

		/*
		// Unrolling didn't do much on my hardware (ATI Mobility Radeon 3450),
		// so i've just left the loop

		"for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {",

		// Accumulate samples, making sure we don't walk past the light source.

		// The check for uv.y < 1 would not be necessary with "border" UV wrap
		// mode, with a black border color. I don't think this is currently
		// exposed by three.js. As a result there might be artifacts when the
		// sun is to the left, right or bottom of screen as these cases are
		// not specifically handled.

		"	col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );",
		"	uv += stepv;",

		"}",
		*/

		// Unrolling loop manually makes it work in ANGLE

			float f = min( 1.0, max( vSunPositionScreenSpace.z / 1000.0, 0.0 ) ); // used to fade out godrays

			if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;
			uv += stepv;

			if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;
			uv += stepv;

			if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;
			uv += stepv;

			if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;
			uv += stepv;

			if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;
			uv += stepv;

			if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f;
			uv += stepv;

		// Should technically be dividing by 'iters but 'TAPS_PER_PASS' smooths out
		// objectionable artifacts, in particular near the sun position. The side
		// effect is that the result is darker than it should be around the sun, as
		// TAPS_PER_PASS is greater than the number of samples actually accumulated.
		// When the result is inverted (in the shader 'godrays_combine this produces
		// a slight bright spot at the position of the sun, even when it is occluded.

			gl_FragColor = vec4( col/TAPS_PER_PASS );
			gl_FragColor.a = 1.0;

		}`
  )
};
var GodRaysCombineShader = {
  name: "GodRaysCombineShader",
  uniforms: {
    tColors: {
      value: null
    },
    tGodRays: {
      value: null
    },
    fGodRayIntensity: {
      value: 0.69
    }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		varying vec2 vUv;

		uniform sampler2D tColors;
		uniform sampler2D tGodRays;

		uniform float fGodRayIntensity;

		void main() {

		// Since THREE.MeshDepthMaterial renders foreground objects white and background
		// objects black, the god-rays will be white streaks. Therefore value is inverted
		// before being combined with tColors

			gl_FragColor = texture2D( tColors, vUv ) + fGodRayIntensity * vec4( 1.0 - texture2D( tGodRays, vUv ).r );
			gl_FragColor.a = 1.0;

		}`
  )
};
var GodRaysFakeSunShader = {
  name: "GodRaysFakeSunShader",
  uniforms: {
    vSunPositionScreenSpace: {
      value: new Vector3()
    },
    fAspect: {
      value: 1
    },
    sunColor: {
      value: new Color(16772608)
    },
    bgColor: {
      value: new Color(0)
    }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		varying vec2 vUv;

		uniform vec3 vSunPositionScreenSpace;
		uniform float fAspect;

		uniform vec3 sunColor;
		uniform vec3 bgColor;

		void main() {

			vec2 diff = vUv - vSunPositionScreenSpace.xy;

		// Correct for aspect ratio

			diff.x *= fAspect;

			float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 );
			prop = 0.35 * pow( 1.0 - prop, 3.0 );

			gl_FragColor.xyz = ( vSunPositionScreenSpace.z > 0.0 ) ? mix( sunColor, bgColor, 1.0 - prop ) : bgColor;
			gl_FragColor.w = 1.0;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/HorizontalBlurShader.js
var HorizontalBlurShader = {
  name: "HorizontalBlurShader",
  uniforms: {
    "tDiffuse": { value: null },
    "h": { value: 1 / 512 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform float h;

		varying vec2 vUv;

		void main() {

			vec4 sum = vec4( 0.0 );

			sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051;
			sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
			sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051;

			gl_FragColor = sum;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/HorizontalTiltShiftShader.js
var HorizontalTiltShiftShader = {
  name: "HorizontalTiltShiftShader",
  uniforms: {
    "tDiffuse": { value: null },
    "h": { value: 1 / 512 },
    "r": { value: 0.35 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform float h;
		uniform float r;

		varying vec2 vUv;

		void main() {

			vec4 sum = vec4( 0.0 );

			float hh = h * abs( r - vUv.y );

			sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * hh, vUv.y ) ) * 0.051;
			sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * hh, vUv.y ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * hh, vUv.y ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * hh, vUv.y ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
			sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * hh, vUv.y ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * hh, vUv.y ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * hh, vUv.y ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * hh, vUv.y ) ) * 0.051;

			gl_FragColor = sum;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/HueSaturationShader.js
var HueSaturationShader = {
  name: "HueSaturationShader",
  uniforms: {
    "tDiffuse": { value: null },
    "hue": { value: 0 },
    "saturation": { value: 0 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform float hue;
		uniform float saturation;

		varying vec2 vUv;

		void main() {

			gl_FragColor = texture2D( tDiffuse, vUv );

			// hue
			float angle = hue * 3.14159265;
			float s = sin(angle), c = cos(angle);
			vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;
			float len = length(gl_FragColor.rgb);
			gl_FragColor.rgb = vec3(
				dot(gl_FragColor.rgb, weights.xyz),
				dot(gl_FragColor.rgb, weights.zxy),
				dot(gl_FragColor.rgb, weights.yzx)
			);

			// saturation
			float average = (gl_FragColor.r + gl_FragColor.g + gl_FragColor.b) / 3.0;
			if (saturation > 0.0) {
				gl_FragColor.rgb += (average - gl_FragColor.rgb) * (1.0 - 1.0 / (1.001 - saturation));
			} else {
				gl_FragColor.rgb += (average - gl_FragColor.rgb) * (-saturation);
			}

		}`
  )
};

// node_modules/three/examples/jsm/shaders/KaleidoShader.js
var KaleidoShader = {
  name: "KaleidoShader",
  uniforms: {
    "tDiffuse": { value: null },
    "sides": { value: 6 },
    "angle": { value: 0 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform float sides;
		uniform float angle;

		varying vec2 vUv;

		void main() {

			vec2 p = vUv - 0.5;
			float r = length(p);
			float a = atan(p.y, p.x) + angle;
			float tau = 2. * 3.1416 ;
			a = mod(a, tau/sides);
			a = abs(a - tau/sides/2.) ;
			p = r * vec2(cos(a), sin(a));
			vec4 color = texture2D(tDiffuse, p + 0.5);
			gl_FragColor = color;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/LuminosityShader.js
var LuminosityShader = {
  name: "LuminosityShader",
  uniforms: {
    "tDiffuse": { value: null }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		#include <common>

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );

			float l = luminance( texel.rgb );

			gl_FragColor = vec4( l, l, l, texel.w );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/MirrorShader.js
var MirrorShader = {
  name: "MirrorShader",
  uniforms: {
    "tDiffuse": { value: null },
    "side": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform int side;

		varying vec2 vUv;

		void main() {

			vec2 p = vUv;
			if (side == 0){
				if (p.x > 0.5) p.x = 1.0 - p.x;
			}else if (side == 1){
				if (p.x < 0.5) p.x = 1.0 - p.x;
			}else if (side == 2){
				if (p.y < 0.5) p.y = 1.0 - p.y;
			}else if (side == 3){
				if (p.y > 0.5) p.y = 1.0 - p.y;
			}
			vec4 color = texture2D(tDiffuse, p);
			gl_FragColor = color;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/NormalMapShader.js
var NormalMapShader = {
  name: "NormalMapShader",
  uniforms: {
    "heightMap": { value: null },
    "resolution": { value: new Vector2(512, 512) },
    "scale": { value: new Vector2(1, 1) },
    "height": { value: 0.05 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float height;
		uniform vec2 resolution;
		uniform sampler2D heightMap;

		varying vec2 vUv;

		void main() {

			float val = texture2D( heightMap, vUv ).x;

			float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x;
			float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x;

			gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height  ) ) + 0.5 ), 1.0 );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/RGBShiftShader.js
var RGBShiftShader = {
  name: "RGBShiftShader",
  uniforms: {
    "tDiffuse": { value: null },
    "amount": { value: 5e-3 },
    "angle": { value: 0 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform float amount;
		uniform float angle;

		varying vec2 vUv;

		void main() {

			vec2 offset = amount * vec2( cos(angle), sin(angle));
			vec4 cr = texture2D(tDiffuse, vUv + offset);
			vec4 cga = texture2D(tDiffuse, vUv);
			vec4 cb = texture2D(tDiffuse, vUv - offset);
			gl_FragColor = vec4(cr.r, cga.g, cb.b, cga.a);

		}`
  )
};

// node_modules/three/examples/jsm/shaders/SepiaShader.js
var SepiaShader = {
  name: "SepiaShader",
  uniforms: {
    "tDiffuse": { value: null },
    "amount": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float amount;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 color = texture2D( tDiffuse, vUv );
			vec3 c = color.rgb;

			color.r = dot( c, vec3( 1.0 - 0.607 * amount, 0.769 * amount, 0.189 * amount ) );
			color.g = dot( c, vec3( 0.349 * amount, 1.0 - 0.314 * amount, 0.168 * amount ) );
			color.b = dot( c, vec3( 0.272 * amount, 0.534 * amount, 1.0 - 0.869 * amount ) );

			gl_FragColor = vec4( min( vec3( 1.0 ), color.rgb ), color.a );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/SobelOperatorShader.js
var SobelOperatorShader = {
  name: "SobelOperatorShader",
  uniforms: {
    "tDiffuse": { value: null },
    "resolution": { value: new Vector2() }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform vec2 resolution;
		varying vec2 vUv;

		void main() {

			vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y );

		// kernel definition (in glsl matrices are filled in column-major order)

			const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 ); // x direction kernel
			const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 ); // y direction kernel

		// fetch the 3x3 neighbourhood of a fragment

		// first column

			float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r;
			float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1,  0 ) ).r;
			float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1,  1 ) ).r;

		// second column

			float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2(  0, -1 ) ).r;
			float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2(  0,  0 ) ).r;
			float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2(  0,  1 ) ).r;

		// third column

			float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2(  1, -1 ) ).r;
			float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2(  1,  0 ) ).r;
			float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2(  1,  1 ) ).r;

		// gradient value in x direction

			float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 +
				Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 +
				Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2;

		// gradient value in y direction

			float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 +
				Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 +
				Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2;

		// magnitude of the total gradient

			float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) );

			gl_FragColor = vec4( vec3( G ), 1 );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/SubsurfaceScatteringShader.js
function replaceAll(string, find2, replace) {
  return string.split(find2).join(replace);
}
var meshphong_frag_head = ShaderChunk["meshphong_frag"].slice(0, ShaderChunk["meshphong_frag"].indexOf("void main() {"));
var meshphong_frag_body = ShaderChunk["meshphong_frag"].slice(ShaderChunk["meshphong_frag"].indexOf("void main() {"));
var SubsurfaceScatteringShader = {
  name: "SubsurfaceScatteringShader",
  uniforms: UniformsUtils.merge([
    ShaderLib["phong"].uniforms,
    {
      "thicknessMap": { value: null },
      "thicknessColor": { value: new Color(16777215) },
      "thicknessDistortion": { value: 0.1 },
      "thicknessAmbient": { value: 0 },
      "thicknessAttenuation": { value: 0.1 },
      "thicknessPower": { value: 2 },
      "thicknessScale": { value: 10 }
    }
  ]),
  vertexShader: [
    "#define USE_UV",
    ShaderChunk["meshphong_vert"]
  ].join("\n"),
  fragmentShader: [
    "#define USE_UV",
    "#define SUBSURFACE",
    meshphong_frag_head,
    "uniform sampler2D thicknessMap;",
    "uniform float thicknessPower;",
    "uniform float thicknessScale;",
    "uniform float thicknessDistortion;",
    "uniform float thicknessAmbient;",
    "uniform float thicknessAttenuation;",
    "uniform vec3 thicknessColor;",
    "void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, inout ReflectedLight reflectedLight) {",
    "	vec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;",
    "	vec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));",
    "	float scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;",
    "	vec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;",
    "	reflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;",
    "}",
    meshphong_frag_body.replace(
      "#include <lights_fragment_begin>",
      replaceAll(
        ShaderChunk["lights_fragment_begin"],
        "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );",
        [
          "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );",
          "#if defined( SUBSURFACE ) && defined( USE_UV )",
          " RE_Direct_Scattering(directLight, vUv, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, reflectedLight);",
          "#endif"
        ].join("\n")
      )
    )
  ].join("\n")
};

// node_modules/three/examples/jsm/shaders/TechnicolorShader.js
var TechnicolorShader = {
  name: "TechnicolorShader",
  uniforms: {
    "tDiffuse": { value: null }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		varying vec2 vUv;

		void main() {

			vec4 tex = texture2D( tDiffuse, vec2( vUv.x, vUv.y ) );
			vec4 newTex = vec4(tex.r, (tex.g + tex.b) * .5, (tex.g + tex.b) * .5, 1.0);

			gl_FragColor = newTex;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/ToonShader.js
var ToonShader1 = {
  name: "ToonShader1",
  uniforms: {
    "uDirLightPos": { value: new Vector3() },
    "uDirLightColor": { value: new Color(15658734) },
    "uAmbientLightColor": { value: new Color(328965) },
    "uBaseColor": { value: new Color(16777215) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec3 vNormal;
		varying vec3 vRefract;

		void main() {

			vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
			vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
			vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );

			vNormal = normalize( normalMatrix * normal );

			vec3 I = worldPosition.xyz - cameraPosition;
			vRefract = refract( normalize( I ), worldNormal, 1.02 );

			gl_Position = projectionMatrix * mvPosition;

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

		uniform vec3 uBaseColor;

		uniform vec3 uDirLightPos;
		uniform vec3 uDirLightColor;

		uniform vec3 uAmbientLightColor;

		varying vec3 vNormal;

		varying vec3 vRefract;

		void main() {

			float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);
			vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;

			float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) );
			intensity += length(lightWeighting) * 0.2;

			float cameraWeighting = dot( normalize( vNormal ), vRefract );
			intensity += pow( 1.0 - length( cameraWeighting ), 6.0 );
			intensity = intensity * 0.2 + 0.3;

			if ( intensity < 0.50 ) {

				gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 );

			} else {

				gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 );

			}

			#include <colorspace_fragment>

		}`
  )
};
var ToonShader2 = {
  uniforms: {
    "uDirLightPos": { value: new Vector3() },
    "uDirLightColor": { value: new Color(15658734) },
    "uAmbientLightColor": { value: new Color(328965) },
    "uBaseColor": { value: new Color(15658734) },
    "uLineColor1": { value: new Color(8421504) },
    "uLineColor2": { value: new Color(0) },
    "uLineColor3": { value: new Color(0) },
    "uLineColor4": { value: new Color(0) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec3 vNormal;

		void main() {

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
			vNormal = normalize( normalMatrix * normal );

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

		uniform vec3 uBaseColor;
		uniform vec3 uLineColor1;
		uniform vec3 uLineColor2;
		uniform vec3 uLineColor3;
		uniform vec3 uLineColor4;

		uniform vec3 uDirLightPos;
		uniform vec3 uDirLightColor;

		uniform vec3 uAmbientLightColor;

		varying vec3 vNormal;

		void main() {

			float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4);
			float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0);

			gl_FragColor = vec4( uBaseColor, 1.0 );

			if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) {

				gl_FragColor *= vec4( uLineColor1, 1.0 );

			}

			if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) {

				gl_FragColor *= vec4( uLineColor2, 1.0 );

			}

			#include <colorspace_fragment>

		}`
  )
};
var ToonShaderHatching = {
  uniforms: {
    "uDirLightPos": { value: new Vector3() },
    "uDirLightColor": { value: new Color(15658734) },
    "uAmbientLightColor": { value: new Color(328965) },
    "uBaseColor": { value: new Color(16777215) },
    "uLineColor1": { value: new Color(0) },
    "uLineColor2": { value: new Color(0) },
    "uLineColor3": { value: new Color(0) },
    "uLineColor4": { value: new Color(0) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec3 vNormal;

		void main() {

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
			vNormal = normalize( normalMatrix * normal );

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

		uniform vec3 uBaseColor;
		uniform vec3 uLineColor1;
		uniform vec3 uLineColor2;
		uniform vec3 uLineColor3;
		uniform vec3 uLineColor4;

		uniform vec3 uDirLightPos;
		uniform vec3 uDirLightColor;

		uniform vec3 uAmbientLightColor;

		varying vec3 vNormal;

		void main() {

			float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);
			vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;

			gl_FragColor = vec4( uBaseColor, 1.0 );

			if ( length(lightWeighting) < 1.00 ) {

				if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {

					gl_FragColor = vec4( uLineColor1, 1.0 );

				}

			}

			if ( length(lightWeighting) < 0.75 ) {

				if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {

					gl_FragColor = vec4( uLineColor2, 1.0 );

				}

			}

			if ( length(lightWeighting) < 0.50 ) {

				if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {

					gl_FragColor = vec4( uLineColor3, 1.0 );

				}

			}

			if ( length(lightWeighting) < 0.3465 ) {

				if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {

					gl_FragColor = vec4( uLineColor4, 1.0 );

			}

			}

			#include <colorspace_fragment>

		}`
  )
};
var ToonShaderDotted = {
  uniforms: {
    "uDirLightPos": { value: new Vector3() },
    "uDirLightColor": { value: new Color(15658734) },
    "uAmbientLightColor": { value: new Color(328965) },
    "uBaseColor": { value: new Color(16777215) },
    "uLineColor1": { value: new Color(0) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec3 vNormal;

		void main() {

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
			vNormal = normalize( normalMatrix * normal );

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

		uniform vec3 uBaseColor;
		uniform vec3 uLineColor1;
		uniform vec3 uLineColor2;
		uniform vec3 uLineColor3;
		uniform vec3 uLineColor4;

		uniform vec3 uDirLightPos;
		uniform vec3 uDirLightColor;

		uniform vec3 uAmbientLightColor;

		varying vec3 vNormal;

		void main() {

			float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0);
			vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting;

			gl_FragColor = vec4( uBaseColor, 1.0 );

			if ( length(lightWeighting) < 1.00 ) {

				if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) {

					gl_FragColor = vec4( uLineColor1, 1.0 );

				}

			}

			if ( length(lightWeighting) < 0.50 ) {

				if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) {

					gl_FragColor = vec4( uLineColor1, 1.0 );

				}

			}

			#include <colorspace_fragment>

		}`
  )
};

// node_modules/three/examples/jsm/shaders/TriangleBlurShader.js
var TriangleBlurShader = {
  name: "TriangleBlurShader",
  uniforms: {
    "texture": { value: null },
    "delta": { value: new Vector2(1, 1) }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		#include <common>

		#define ITERATIONS 10.0

		uniform sampler2D texture;
		uniform vec2 delta;

		varying vec2 vUv;

		void main() {

			vec4 color = vec4( 0.0 );

			float total = 0.0;

		// randomize the lookup values to hide the fixed number of samples

			float offset = rand( vUv );

			for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) {

				float percent = ( t + offset - 0.5 ) / ITERATIONS;
				float weight = 1.0 - abs( percent );

				color += texture2D( texture, vUv + delta * percent ) * weight;
				total += weight;

			}

			gl_FragColor = color / total;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/UnpackDepthRGBAShader.js
var UnpackDepthRGBAShader = {
  name: "UnpackDepthRGBAShader",
  uniforms: {
    "tDiffuse": { value: null },
    "opacity": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float opacity;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		#include <packing>

		void main() {

			float depth = 1.0 - unpackRGBAToDepth( texture2D( tDiffuse, vUv ) );
			gl_FragColor = vec4( vec3( depth ), opacity );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/VelocityShader.js
var VelocityShader = {
  name: "VelocityShader",
  uniforms: UniformsUtils.merge([
    UniformsLib.common,
    UniformsLib.displacementmap,
    {
      modelMatrixPrev: { value: new Matrix4() },
      currentProjectionViewMatrix: { value: new Matrix4() },
      previousProjectionViewMatrix: { value: new Matrix4() }
    }
  ]),
  vertexShader: (
    /* glsl */
    `
#define NORMAL

#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )

	varying vec3 vViewPosition;

#endif

#include <common>
#include <packing>
#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>

uniform mat4 previousProjectionViewMatrix;
uniform mat4 currentProjectionViewMatrix;

uniform mat4 modelMatrixPrev;

varying vec4 clipPositionCurrent;
varying vec4 clipPositionPrevious;

void main() {


	#include <uv_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 <displacementmap_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>

#ifdef USE_SKINNING

	vec4 mvPosition = modelViewMatrix * skinned;
	clipPositionCurrent  = currentProjectionViewMatrix * modelMatrix * skinned;
	clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * skinned;

#else

	vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );
	clipPositionCurrent  = currentProjectionViewMatrix * modelMatrix * vec4( transformed, 1.0 );
	clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * vec4( transformed, 1.0 );

#endif

	gl_Position = projectionMatrix * mvPosition;

	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
}
`
  ),
  fragmentShader: (
    /* glsl */
    `
#define NORMAL

uniform float opacity;

#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>

varying vec4 clipPositionCurrent;
varying vec4 clipPositionPrevious;

void main() {

	vec4 diffuseColor = vec4( 1.0 );
	diffuseColor.a = opacity;

	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>

	vec2 ndcPositionCurrent  = clipPositionCurrent.xy/clipPositionCurrent.w;
	vec2 ndcPositionPrevious = clipPositionPrevious.xy/clipPositionPrevious.w;
	vec2 vel = ( ndcPositionCurrent - ndcPositionPrevious ) * 0.5;
	vel = vel * 0.5 + 0.5;
	vec2 v1 = packDepthToRG(vel.x);
	vec2 v2 = packDepthToRG(vel.y);
	gl_FragColor = vec4(v1.x, v1.y, v2.x, v2.y);

	#include <logdepthbuf_fragment>

}

`
  )
};

// node_modules/three/examples/jsm/shaders/VerticalBlurShader.js
var VerticalBlurShader = {
  name: "VerticalBlurShader",
  uniforms: {
    "tDiffuse": { value: null },
    "v": { value: 1 / 512 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform float v;

		varying vec2 vUv;

		void main() {

			vec4 sum = vec4( 0.0 );

			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051;

			gl_FragColor = sum;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/VerticalTiltShiftShader.js
var VerticalTiltShiftShader = {
  name: "VerticalTiltShiftShader",
  uniforms: {
    "tDiffuse": { value: null },
    "v": { value: 1 / 512 },
    "r": { value: 0.35 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform sampler2D tDiffuse;
		uniform float v;
		uniform float r;

		varying vec2 vUv;

		void main() {

			vec4 sum = vec4( 0.0 );

			float vv = v * abs( r - vUv.y );

			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * vv ) ) * 0.051;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * vv ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * vv ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * vv ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * vv ) ) * 0.1531;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * vv ) ) * 0.12245;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * vv ) ) * 0.0918;
			sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * vv ) ) * 0.051;

			gl_FragColor = sum;

		}`
  )
};

// node_modules/three/examples/jsm/shaders/VignetteShader.js
var VignetteShader = {
  name: "VignetteShader",
  uniforms: {
    "tDiffuse": { value: null },
    "offset": { value: 1 },
    "darkness": { value: 1 }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform float offset;
		uniform float darkness;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			// Eskil's vignette

			vec4 texel = texture2D( tDiffuse, vUv );
			vec2 uv = ( vUv - vec2( 0.5 ) ) * vec2( offset );
			gl_FragColor = vec4( mix( texel.rgb, vec3( 1.0 - darkness ), dot( uv, uv ) ), texel.a );

		}`
  )
};

// node_modules/three/examples/jsm/shaders/VolumeShader.js
var VolumeRenderShader1 = {
  name: "VolumeRenderShader1",
  uniforms: {
    "u_size": { value: new Vector3(1, 1, 1) },
    "u_renderstyle": { value: 0 },
    "u_renderthreshold": { value: 0.5 },
    "u_clim": { value: new Vector2(1, 1) },
    "u_data": { value: null },
    "u_cmdata": { value: null }
  },
  vertexShader: (
    /* glsl */
    `

		varying vec4 v_nearpos;
		varying vec4 v_farpos;
		varying vec3 v_position;

		void main() {
				// Prepare transforms to map to "camera view". See also:
				// https://threejs.org/docs/#api/renderers/webgl/WebGLProgram
				mat4 viewtransformf = modelViewMatrix;
				mat4 viewtransformi = inverse(modelViewMatrix);

				// Project local vertex coordinate to camera position. Then do a step
				// backward (in cam coords) to the near clipping plane, and project back. Do
				// the same for the far clipping plane. This gives us all the information we
				// need to calculate the ray and truncate it to the viewing cone.
				vec4 position4 = vec4(position, 1.0);
				vec4 pos_in_cam = viewtransformf * position4;

				// Intersection of ray and near clipping plane (z = -1 in clip coords)
				pos_in_cam.z = -pos_in_cam.w;
				v_nearpos = viewtransformi * pos_in_cam;

				// Intersection of ray and far clipping plane (z = +1 in clip coords)
				pos_in_cam.z = pos_in_cam.w;
				v_farpos = viewtransformi * pos_in_cam;

				// Set varyings and output pos
				v_position = position;
				gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4;
		}`
  ),
  fragmentShader: (
    /* glsl */
    `

				precision highp float;
				precision mediump sampler3D;

				uniform vec3 u_size;
				uniform int u_renderstyle;
				uniform float u_renderthreshold;
				uniform vec2 u_clim;

				uniform sampler3D u_data;
				uniform sampler2D u_cmdata;

				varying vec3 v_position;
				varying vec4 v_nearpos;
				varying vec4 v_farpos;

				// The maximum distance through our rendering volume is sqrt(3).
				const int MAX_STEPS = 887;	// 887 for 512^3, 1774 for 1024^3
				const int REFINEMENT_STEPS = 4;
				const float relative_step_size = 1.0;
				const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0);
				const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0);
				const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0);
				const float shininess = 40.0;

				void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);
				void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);

				float sample1(vec3 texcoords);
				vec4 apply_colormap(float val);
				vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray);


				void main() {
						// Normalize clipping plane info
						vec3 farpos = v_farpos.xyz / v_farpos.w;
						vec3 nearpos = v_nearpos.xyz / v_nearpos.w;

						// Calculate unit vector pointing in the view direction through this fragment.
						vec3 view_ray = normalize(nearpos.xyz - farpos.xyz);

						// Compute the (negative) distance to the front surface or near clipping plane.
						// v_position is the back face of the cuboid, so the initial distance calculated in the dot
						// product below is the distance from near clip plane to the back of the cuboid
						float distance = dot(nearpos - v_position, view_ray);
						distance = max(distance, min((-0.5 - v_position.x) / view_ray.x,
																				(u_size.x - 0.5 - v_position.x) / view_ray.x));
						distance = max(distance, min((-0.5 - v_position.y) / view_ray.y,
																				(u_size.y - 0.5 - v_position.y) / view_ray.y));
						distance = max(distance, min((-0.5 - v_position.z) / view_ray.z,
																				(u_size.z - 0.5 - v_position.z) / view_ray.z));

						// Now we have the starting position on the front surface
						vec3 front = v_position + view_ray * distance;

						// Decide how many steps to take
						int nsteps = int(-distance / relative_step_size + 0.5);
						if ( nsteps < 1 )
								discard;

						// Get starting location and step vector in texture coordinates
						vec3 step = ((v_position - front) / u_size) / float(nsteps);
						vec3 start_loc = front / u_size;

						// For testing: show the number of steps. This helps to establish
						// whether the rays are correctly oriented
						//'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0);
						//'return;

						if (u_renderstyle == 0)
								cast_mip(start_loc, step, nsteps, view_ray);
						else if (u_renderstyle == 1)
								cast_iso(start_loc, step, nsteps, view_ray);

						if (gl_FragColor.a < 0.05)
								discard;
				}


				float sample1(vec3 texcoords) {
						/* Sample float value from a 3D texture. Assumes intensity data. */
						return texture(u_data, texcoords.xyz).r;
				}


				vec4 apply_colormap(float val) {
						val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]);
						return texture2D(u_cmdata, vec2(val, 0.5));
				}


				void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {

						float max_val = -1e6;
						int max_i = 100;
						vec3 loc = start_loc;

						// Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with
						// non-constant expression. So we use a hard-coded max, and an additional condition
						// inside the loop.
						for (int iter=0; iter<MAX_STEPS; iter++) {
								if (iter >= nsteps)
										break;
								// Sample from the 3D texture
								float val = sample1(loc);
								// Apply MIP operation
								if (val > max_val) {
										max_val = val;
										max_i = iter;
								}
								// Advance location deeper into the volume
								loc += step;
						}

						// Refine location, gives crispier images
						vec3 iloc = start_loc + step * (float(max_i) - 0.5);
						vec3 istep = step / float(REFINEMENT_STEPS);
						for (int i=0; i<REFINEMENT_STEPS; i++) {
								max_val = max(max_val, sample1(iloc));
								iloc += istep;
						}

						// Resolve final color
						gl_FragColor = apply_colormap(max_val);
				}


				void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {

						gl_FragColor = vec4(0.0);	// init transparent
						vec4 color3 = vec4(0.0);	// final color
						vec3 dstep = 1.5 / u_size;	// step to sample derivative
						vec3 loc = start_loc;

						float low_threshold = u_renderthreshold - 0.02 * (u_clim[1] - u_clim[0]);

						// Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with
						// non-constant expression. So we use a hard-coded max, and an additional condition
						// inside the loop.
						for (int iter=0; iter<MAX_STEPS; iter++) {
								if (iter >= nsteps)
										break;

								// Sample from the 3D texture
								float val = sample1(loc);

								if (val > low_threshold) {
										// Take the last interval in smaller steps
										vec3 iloc = loc - 0.5 * step;
										vec3 istep = step / float(REFINEMENT_STEPS);
										for (int i=0; i<REFINEMENT_STEPS; i++) {
												val = sample1(iloc);
												if (val > u_renderthreshold) {
														gl_FragColor = add_lighting(val, iloc, dstep, view_ray);
														return;
												}
												iloc += istep;
										}
								}

								// Advance location deeper into the volume
								loc += step;
						}
				}


				vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray)
				{
					// Calculate color by incorporating lighting

						// View direction
						vec3 V = normalize(view_ray);

						// calculate normal vector from gradient
						vec3 N;
						float val1, val2;
						val1 = sample1(loc + vec3(-step[0], 0.0, 0.0));
						val2 = sample1(loc + vec3(+step[0], 0.0, 0.0));
						N[0] = val1 - val2;
						val = max(max(val1, val2), val);
						val1 = sample1(loc + vec3(0.0, -step[1], 0.0));
						val2 = sample1(loc + vec3(0.0, +step[1], 0.0));
						N[1] = val1 - val2;
						val = max(max(val1, val2), val);
						val1 = sample1(loc + vec3(0.0, 0.0, -step[2]));
						val2 = sample1(loc + vec3(0.0, 0.0, +step[2]));
						N[2] = val1 - val2;
						val = max(max(val1, val2), val);

						float gm = length(N); // gradient magnitude
						N = normalize(N);

						// Flip normal so it points towards viewer
						float Nselect = float(dot(N, V) > 0.0);
						N = (2.0 * Nselect - 1.0) * N;	// ==	Nselect * N - (1.0-Nselect)*N;

						// Init colors
						vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0);
						vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0);
						vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0);

						// note: could allow multiple lights
						for (int i=0; i<1; i++)
						{
								 // Get light direction (make sure to prevent zero division)
								vec3 L = normalize(view_ray);	//lightDirs[i];
								float lightEnabled = float( length(L) > 0.0 );
								L = normalize(L + (1.0 - lightEnabled));

								// Calculate lighting properties
								float lambertTerm = clamp(dot(N, L), 0.0, 1.0);
								vec3 H = normalize(L+V); // Halfway vector
								float specularTerm = pow(max(dot(H, N), 0.0), shininess);

								// Calculate mask
								float mask1 = lightEnabled;

								// Calculate colors
								ambient_color +=	mask1 * ambient_color;	// * gl_LightSource[i].ambient;
								diffuse_color +=	mask1 * lambertTerm;
								specular_color += mask1 * specularTerm * specular_color;
						}

						// Calculate final color by componing different components
						vec4 final_color;
						vec4 color = apply_colormap(val);
						final_color = color * (ambient_color + diffuse_color) + specular_color;
						final_color.a = color.a;
						return final_color;
				}`
  )
};

// node_modules/three/examples/jsm/shaders/WaterRefractionShader.js
var WaterRefractionShader = {
  name: "WaterRefractionShader",
  uniforms: {
    "color": {
      value: null
    },
    "time": {
      value: 0
    },
    "tDiffuse": {
      value: null
    },
    "tDudv": {
      value: null
    },
    "textureMatrix": {
      value: null
    }
  },
  vertexShader: (
    /* glsl */
    `

		uniform mat4 textureMatrix;

		varying vec2 vUv;
		varying vec4 vUvRefraction;

		void main() {

			vUv = uv;

			vUvRefraction = textureMatrix * vec4( position, 1.0 );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

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

		uniform vec3 color;
		uniform float time;
		uniform sampler2D tDiffuse;
		uniform sampler2D tDudv;

		varying vec2 vUv;
		varying vec4 vUvRefraction;

		float blendOverlay( float base, float blend ) {

			return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );

		}

		vec3 blendOverlay( vec3 base, vec3 blend ) {

			return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ),blendOverlay( base.b, blend.b ) );

		}

		void main() {

		 float waveStrength = 0.5;
		 float waveSpeed = 0.03;

			// simple distortion (ripple) via dudv map (see https://www.youtube.com/watch?v=6B7IF6GOu7s)

			vec2 distortedUv = texture2D( tDudv, vec2( vUv.x + time * waveSpeed, vUv.y ) ).rg * waveStrength;
			distortedUv = vUv.xy + vec2( distortedUv.x, distortedUv.y + time * waveSpeed );
			vec2 distortion = ( texture2D( tDudv, distortedUv ).rg * 2.0 - 1.0 ) * waveStrength;

			// new uv coords

			vec4 uv = vec4( vUvRefraction );
			uv.xy += distortion;

			vec4 base = texture2DProj( tDiffuse, uv );

			gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );

			#include <tonemapping_fragment>
			#include <colorspace_fragment>

		}`
  )
};

// node_modules/three/examples/jsm/textures/FlakesTexture.js
var FlakesTexture = class {
  /**
   * Generates a new flakes texture image. The result is a canvas
   * that can be used as an input for {@link CanvasTexture}.
   *
   * @param {number} [width=512] - The width of the image.
   * @param {number} [height=512] - The height of the image.
   * @return {HTMLCanvasElement} The generated image.
   */
  constructor(width2 = 512, height2 = 512) {
    const canvas = document.createElement("canvas");
    canvas.width = width2;
    canvas.height = height2;
    const context = canvas.getContext("2d");
    context.fillStyle = "rgb(127,127,255)";
    context.fillRect(0, 0, width2, height2);
    for (let i = 0; i < 4e3; i++) {
      const x2 = Math.random() * width2;
      const y = Math.random() * height2;
      const r = Math.random() * 3 + 3;
      let nx = Math.random() * 2 - 1;
      let ny = Math.random() * 2 - 1;
      let nz = 1.5;
      const l2 = Math.sqrt(nx * nx + ny * ny + nz * nz);
      nx /= l2;
      ny /= l2;
      nz /= l2;
      context.fillStyle = "rgb(" + (nx * 127 + 127) + "," + (ny * 127 + 127) + "," + nz * 255 + ")";
      context.beginPath();
      context.arc(x2, y, r, 0, Math.PI * 2);
      context.fill();
    }
    return canvas;
  }
};

// node_modules/three/examples/jsm/utils/CameraUtils.js
var CameraUtils_exports = {};
__export(CameraUtils_exports, {
  frameCorners: () => frameCorners
});
var _va = new Vector3();
var _vb = new Vector3();
var _vc = new Vector3();
var _vr = new Vector3();
var _vu = new Vector3();
var _vn = new Vector3();
var _vec = new Vector3();
var _quat = new Quaternion();
function frameCorners(camera, bottomLeftCorner, bottomRightCorner, topLeftCorner, estimateViewFrustum = false) {
  const pa2 = bottomLeftCorner, pb = bottomRightCorner, pc = topLeftCorner;
  const pe = camera.position;
  const n2 = camera.near;
  const f = camera.far;
  _vr.copy(pb).sub(pa2).normalize();
  _vu.copy(pc).sub(pa2).normalize();
  _vn.crossVectors(_vr, _vu).normalize();
  _va.copy(pa2).sub(pe);
  _vb.copy(pb).sub(pe);
  _vc.copy(pc).sub(pe);
  const d = -_va.dot(_vn);
  const l2 = _vr.dot(_va) * n2 / d;
  const r = _vr.dot(_vb) * n2 / d;
  const b3 = _vu.dot(_va) * n2 / d;
  const t3 = _vu.dot(_vc) * n2 / d;
  _quat.setFromUnitVectors(_vec.set(0, 1, 0), _vu);
  camera.quaternion.setFromUnitVectors(_vec.set(0, 0, 1).applyQuaternion(_quat), _vn).multiply(_quat);
  camera.projectionMatrix.set(
    2 * n2 / (r - l2),
    0,
    (r + l2) / (r - l2),
    0,
    0,
    2 * n2 / (t3 - b3),
    (t3 + b3) / (t3 - b3),
    0,
    0,
    0,
    (f + n2) / (n2 - f),
    2 * f * n2 / (n2 - f),
    0,
    0,
    -1,
    0
  );
  camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
  if (estimateViewFrustum) {
    camera.fov = MathUtils.RAD2DEG / Math.min(1, camera.aspect) * Math.atan((_vec.copy(pb).sub(pa2).length() + _vec.copy(pc).sub(pa2).length()) / _va.length());
  }
}

// node_modules/three/examples/jsm/utils/GeometryCompressionUtils.js
var GeometryCompressionUtils_exports = {};
__export(GeometryCompressionUtils_exports, {
  compressNormals: () => compressNormals,
  compressPositions: () => compressPositions,
  compressUvs: () => compressUvs
});
function compressNormals(geometry, encodeMethod) {
  const normal = geometry.attributes.normal;
  if (!normal) {
    console.error("THREE.GeometryCompressionUtils.compressNormals(): Geometry must contain normal attribute.");
  }
  if (normal.isPacked) return;
  if (normal.itemSize != 3) {
    console.error("THREE.GeometryCompressionUtils.compressNormals(): normal.itemSize is not 3, which cannot be encoded.");
  }
  const array = normal.array;
  const count = normal.count;
  let result;
  if (encodeMethod == "DEFAULT") {
    result = new Uint8Array(count * 3);
    for (let idx = 0; idx < array.length; idx += 3) {
      const encoded = defaultEncode(array[idx], array[idx + 1], array[idx + 2], 1);
      result[idx + 0] = encoded[0];
      result[idx + 1] = encoded[1];
      result[idx + 2] = encoded[2];
    }
    geometry.setAttribute("normal", new BufferAttribute(result, 3, true));
    geometry.attributes.normal.bytes = result.length * 1;
  } else if (encodeMethod == "OCT1Byte") {
    result = new Int8Array(count * 2);
    for (let idx = 0; idx < array.length; idx += 3) {
      const encoded = octEncodeBest(array[idx], array[idx + 1], array[idx + 2], 1);
      result[idx / 3 * 2 + 0] = encoded[0];
      result[idx / 3 * 2 + 1] = encoded[1];
    }
    geometry.setAttribute("normal", new BufferAttribute(result, 2, true));
    geometry.attributes.normal.bytes = result.length * 1;
  } else if (encodeMethod == "OCT2Byte") {
    result = new Int16Array(count * 2);
    for (let idx = 0; idx < array.length; idx += 3) {
      const encoded = octEncodeBest(array[idx], array[idx + 1], array[idx + 2], 2);
      result[idx / 3 * 2 + 0] = encoded[0];
      result[idx / 3 * 2 + 1] = encoded[1];
    }
    geometry.setAttribute("normal", new BufferAttribute(result, 2, true));
    geometry.attributes.normal.bytes = result.length * 2;
  } else if (encodeMethod == "ANGLES") {
    result = new Uint16Array(count * 2);
    for (let idx = 0; idx < array.length; idx += 3) {
      const encoded = anglesEncode(array[idx], array[idx + 1], array[idx + 2]);
      result[idx / 3 * 2 + 0] = encoded[0];
      result[idx / 3 * 2 + 1] = encoded[1];
    }
    geometry.setAttribute("normal", new BufferAttribute(result, 2, true));
    geometry.attributes.normal.bytes = result.length * 2;
  } else {
    console.error("Unrecognized encoding method, should be `DEFAULT` or `ANGLES` or `OCT`. ");
  }
  geometry.attributes.normal.needsUpdate = true;
  geometry.attributes.normal.isPacked = true;
  geometry.attributes.normal.packingMethod = encodeMethod;
}
function compressPositions(geometry) {
  const position2 = geometry.attributes.position;
  if (!position2) {
    console.error("THREE.GeometryCompressionUtils.compressPositions(): Geometry must contain position attribute.");
  }
  if (position2.isPacked) return;
  if (position2.itemSize != 3) {
    console.error("THREE.GeometryCompressionUtils.compressPositions(): position.itemSize is not 3, which cannot be packed.");
  }
  const array = position2.array;
  const encodingBytes = 2;
  const result = quantizedEncode(array, encodingBytes);
  const quantized = result.quantized;
  if (geometry.boundingBox == null) geometry.computeBoundingBox();
  if (geometry.boundingSphere == null) geometry.computeBoundingSphere();
  geometry.setAttribute("position", new BufferAttribute(quantized, 3));
  geometry.attributes.position.isPacked = true;
  geometry.attributes.position.needsUpdate = true;
  geometry.attributes.position.bytes = quantized.length * encodingBytes;
}
function compressUvs(geometry) {
  const uvs = geometry.attributes.uv;
  if (!uvs) {
    console.error("THREE.GeometryCompressionUtils.compressUvs(): Geometry must contain uv attribute.");
  }
  if (uvs.isPacked) return;
  const range = { min: Infinity, max: -Infinity };
  const array = uvs.array;
  for (let i = 0; i < array.length; i++) {
    range.min = Math.min(range.min, array[i]);
    range.max = Math.max(range.max, array[i]);
  }
  let result;
  if (range.min >= -1 && range.max <= 1) {
    result = new Uint16Array(array.length);
    for (let i = 0; i < array.length; i += 2) {
      const encoded = defaultEncode(array[i], array[i + 1], 0, 2);
      result[i] = encoded[0];
      result[i + 1] = encoded[1];
    }
    geometry.setAttribute("uv", new BufferAttribute(result, 2, true));
    geometry.attributes.uv.isPacked = true;
    geometry.attributes.uv.needsUpdate = true;
    geometry.attributes.uv.bytes = result.length * 2;
  } else {
    result = quantizedEncodeUV(array, 2);
    geometry.setAttribute("uv", new BufferAttribute(result.quantized, 2));
    geometry.attributes.uv.isPacked = true;
    geometry.attributes.uv.needsUpdate = true;
    geometry.attributes.uv.bytes = result.quantized.length * 2;
  }
}
function defaultEncode(x2, y, z, bytes) {
  if (bytes == 1) {
    const tmpx = Math.round((x2 + 1) * 0.5 * 255);
    const tmpy = Math.round((y + 1) * 0.5 * 255);
    const tmpz = Math.round((z + 1) * 0.5 * 255);
    return new Uint8Array([tmpx, tmpy, tmpz]);
  } else if (bytes == 2) {
    const tmpx = Math.round((x2 + 1) * 0.5 * 65535);
    const tmpy = Math.round((y + 1) * 0.5 * 65535);
    const tmpz = Math.round((z + 1) * 0.5 * 65535);
    return new Uint16Array([tmpx, tmpy, tmpz]);
  } else {
    console.error("number of bytes must be 1 or 2");
  }
}
function anglesEncode(x2, y, z) {
  const normal0 = parseInt(0.5 * (1 + Math.atan2(y, x2) / Math.PI) * 65535);
  const normal1 = parseInt(0.5 * (1 + z) * 65535);
  return new Uint16Array([normal0, normal1]);
}
function octEncodeBest(x2, y, z, bytes) {
  let oct, dec, best, currentCos, bestCos;
  best = oct = octEncodeVec3(x2, y, z, "floor", "floor");
  dec = octDecodeVec2(oct);
  bestCos = dot(x2, y, z, dec);
  oct = octEncodeVec3(x2, y, z, "ceil", "floor");
  dec = octDecodeVec2(oct);
  currentCos = dot(x2, y, z, dec);
  if (currentCos > bestCos) {
    best = oct;
    bestCos = currentCos;
  }
  oct = octEncodeVec3(x2, y, z, "floor", "ceil");
  dec = octDecodeVec2(oct);
  currentCos = dot(x2, y, z, dec);
  if (currentCos > bestCos) {
    best = oct;
    bestCos = currentCos;
  }
  oct = octEncodeVec3(x2, y, z, "ceil", "ceil");
  dec = octDecodeVec2(oct);
  currentCos = dot(x2, y, z, dec);
  if (currentCos > bestCos) {
    best = oct;
  }
  return best;
  function octEncodeVec3(x0, y0, z0, xfunc, yfunc) {
    let x3 = x0 / (Math.abs(x0) + Math.abs(y0) + Math.abs(z0));
    let y2 = y0 / (Math.abs(x0) + Math.abs(y0) + Math.abs(z0));
    if (z < 0) {
      const tempx = (1 - Math.abs(y2)) * (x3 >= 0 ? 1 : -1);
      const tempy = (1 - Math.abs(x3)) * (y2 >= 0 ? 1 : -1);
      x3 = tempx;
      y2 = tempy;
      let diff = 1 - Math.abs(x3) - Math.abs(y2);
      if (diff > 0) {
        diff += 1e-3;
        x3 += x3 > 0 ? diff / 2 : -diff / 2;
        y2 += y2 > 0 ? diff / 2 : -diff / 2;
      }
    }
    if (bytes == 1) {
      return new Int8Array([
        Math[xfunc](x3 * 127.5 + (x3 < 0 ? 1 : 0)),
        Math[yfunc](y2 * 127.5 + (y2 < 0 ? 1 : 0))
      ]);
    }
    if (bytes == 2) {
      return new Int16Array([
        Math[xfunc](x3 * 32767.5 + (x3 < 0 ? 1 : 0)),
        Math[yfunc](y2 * 32767.5 + (y2 < 0 ? 1 : 0))
      ]);
    }
  }
  function octDecodeVec2(oct2) {
    let x3 = oct2[0];
    let y2 = oct2[1];
    if (bytes == 1) {
      x3 /= x3 < 0 ? 127 : 128;
      y2 /= y2 < 0 ? 127 : 128;
    } else if (bytes == 2) {
      x3 /= x3 < 0 ? 32767 : 32768;
      y2 /= y2 < 0 ? 32767 : 32768;
    }
    const z2 = 1 - Math.abs(x3) - Math.abs(y2);
    if (z2 < 0) {
      const tmpx = x3;
      x3 = (1 - Math.abs(y2)) * (x3 >= 0 ? 1 : -1);
      y2 = (1 - Math.abs(tmpx)) * (y2 >= 0 ? 1 : -1);
    }
    const length2 = Math.sqrt(x3 * x3 + y2 * y2 + z2 * z2);
    return [
      x3 / length2,
      y2 / length2,
      z2 / length2
    ];
  }
  function dot(x3, y2, z2, vec3) {
    return x3 * vec3[0] + y2 * vec3[1] + z2 * vec3[2];
  }
}
function quantizedEncode(array, bytes) {
  let quantized, segments;
  if (bytes == 1) {
    quantized = new Uint8Array(array.length);
    segments = 255;
  } else if (bytes == 2) {
    quantized = new Uint16Array(array.length);
    segments = 65535;
  } else {
    console.error("number of bytes error! ");
  }
  const decodeMat = new Matrix4();
  const min = new Float32Array(3);
  const max2 = new Float32Array(3);
  min[0] = min[1] = min[2] = Number.MAX_VALUE;
  max2[0] = max2[1] = max2[2] = -Number.MAX_VALUE;
  for (let i = 0; i < array.length; i += 3) {
    min[0] = Math.min(min[0], array[i + 0]);
    min[1] = Math.min(min[1], array[i + 1]);
    min[2] = Math.min(min[2], array[i + 2]);
    max2[0] = Math.max(max2[0], array[i + 0]);
    max2[1] = Math.max(max2[1], array[i + 1]);
    max2[2] = Math.max(max2[2], array[i + 2]);
  }
  decodeMat.scale(new Vector3(
    (max2[0] - min[0]) / segments,
    (max2[1] - min[1]) / segments,
    (max2[2] - min[2]) / segments
  ));
  decodeMat.elements[12] = min[0];
  decodeMat.elements[13] = min[1];
  decodeMat.elements[14] = min[2];
  decodeMat.transpose();
  const multiplier = new Float32Array([
    max2[0] !== min[0] ? segments / (max2[0] - min[0]) : 0,
    max2[1] !== min[1] ? segments / (max2[1] - min[1]) : 0,
    max2[2] !== min[2] ? segments / (max2[2] - min[2]) : 0
  ]);
  for (let i = 0; i < array.length; i += 3) {
    quantized[i + 0] = Math.floor((array[i + 0] - min[0]) * multiplier[0]);
    quantized[i + 1] = Math.floor((array[i + 1] - min[1]) * multiplier[1]);
    quantized[i + 2] = Math.floor((array[i + 2] - min[2]) * multiplier[2]);
  }
  return {
    quantized,
    decodeMat
  };
}
function quantizedEncodeUV(array, bytes) {
  let quantized, segments;
  if (bytes == 1) {
    quantized = new Uint8Array(array.length);
    segments = 255;
  } else if (bytes == 2) {
    quantized = new Uint16Array(array.length);
    segments = 65535;
  } else {
    console.error("number of bytes error! ");
  }
  const decodeMat = new Matrix3();
  const min = new Float32Array(2);
  const max2 = new Float32Array(2);
  min[0] = min[1] = Number.MAX_VALUE;
  max2[0] = max2[1] = -Number.MAX_VALUE;
  for (let i = 0; i < array.length; i += 2) {
    min[0] = Math.min(min[0], array[i + 0]);
    min[1] = Math.min(min[1], array[i + 1]);
    max2[0] = Math.max(max2[0], array[i + 0]);
    max2[1] = Math.max(max2[1], array[i + 1]);
  }
  decodeMat.scale(
    (max2[0] - min[0]) / segments,
    (max2[1] - min[1]) / segments
  );
  decodeMat.elements[6] = min[0];
  decodeMat.elements[7] = min[1];
  decodeMat.transpose();
  const multiplier = new Float32Array([
    max2[0] !== min[0] ? segments / (max2[0] - min[0]) : 0,
    max2[1] !== min[1] ? segments / (max2[1] - min[1]) : 0
  ]);
  for (let i = 0; i < array.length; i += 2) {
    quantized[i + 0] = Math.floor((array[i + 0] - min[0]) * multiplier[0]);
    quantized[i + 1] = Math.floor((array[i + 1] - min[1]) * multiplier[1]);
  }
  return {
    quantized,
    decodeMat
  };
}

// node_modules/three/examples/jsm/utils/GeometryUtils.js
var GeometryUtils_exports = {};
__export(GeometryUtils_exports, {
  gosper: () => gosper,
  hilbert2D: () => hilbert2D,
  hilbert3D: () => hilbert3D
});
function hilbert2D(center = new Vector3(0, 0, 0), size2 = 10, iterations = 1, v0 = 0, v12 = 1, v2 = 2, v3 = 3) {
  const half = size2 / 2;
  const vec_s = [
    new Vector3(center.x - half, center.y, center.z - half),
    new Vector3(center.x - half, center.y, center.z + half),
    new Vector3(center.x + half, center.y, center.z + half),
    new Vector3(center.x + half, center.y, center.z - half)
  ];
  const vec = [
    vec_s[v0],
    vec_s[v12],
    vec_s[v2],
    vec_s[v3]
  ];
  if (0 <= --iterations) {
    return [
      ...hilbert2D(vec[0], half, iterations, v0, v3, v2, v12),
      ...hilbert2D(vec[1], half, iterations, v0, v12, v2, v3),
      ...hilbert2D(vec[2], half, iterations, v0, v12, v2, v3),
      ...hilbert2D(vec[3], half, iterations, v2, v12, v0, v3)
    ];
  }
  return vec;
}
function hilbert3D(center = new Vector3(0, 0, 0), size2 = 10, iterations = 1, v0 = 0, v12 = 1, v2 = 2, v3 = 3, v4 = 4, v5 = 5, v6 = 6, v7 = 7) {
  const half = size2 / 2;
  const vec_s = [
    new Vector3(center.x - half, center.y + half, center.z - half),
    new Vector3(center.x - half, center.y + half, center.z + half),
    new Vector3(center.x - half, center.y - half, center.z + half),
    new Vector3(center.x - half, center.y - half, center.z - half),
    new Vector3(center.x + half, center.y - half, center.z - half),
    new Vector3(center.x + half, center.y - half, center.z + half),
    new Vector3(center.x + half, center.y + half, center.z + half),
    new Vector3(center.x + half, center.y + half, center.z - half)
  ];
  const vec = [
    vec_s[v0],
    vec_s[v12],
    vec_s[v2],
    vec_s[v3],
    vec_s[v4],
    vec_s[v5],
    vec_s[v6],
    vec_s[v7]
  ];
  if (--iterations >= 0) {
    return [
      ...hilbert3D(vec[0], half, iterations, v0, v3, v4, v7, v6, v5, v2, v12),
      ...hilbert3D(vec[1], half, iterations, v0, v7, v6, v12, v2, v5, v4, v3),
      ...hilbert3D(vec[2], half, iterations, v0, v7, v6, v12, v2, v5, v4, v3),
      ...hilbert3D(vec[3], half, iterations, v2, v3, v0, v12, v6, v7, v4, v5),
      ...hilbert3D(vec[4], half, iterations, v2, v3, v0, v12, v6, v7, v4, v5),
      ...hilbert3D(vec[5], half, iterations, v4, v3, v2, v5, v6, v12, v0, v7),
      ...hilbert3D(vec[6], half, iterations, v4, v3, v2, v5, v6, v12, v0, v7),
      ...hilbert3D(vec[7], half, iterations, v6, v5, v2, v12, v0, v3, v4, v7)
    ];
  }
  return vec;
}
function gosper(size2 = 1) {
  function fractalize(config) {
    let output;
    let input = config.axiom;
    for (let i = 0, il = config.steps; 0 <= il ? i < il : i > il; 0 <= il ? i++ : i--) {
      output = "";
      for (let j2 = 0, jl = input.length; j2 < jl; j2++) {
        const char = input[j2];
        if (char in config.rules) {
          output += config.rules[char];
        } else {
          output += char;
        }
      }
      input = output;
    }
    return output;
  }
  function toPoints(config) {
    let currX = 0, currY = 0;
    let angle = 0;
    const path = [0, 0, 0];
    const fractal = config.fractal;
    for (let i = 0, l2 = fractal.length; i < l2; i++) {
      const char = fractal[i];
      if (char === "+") {
        angle += config.angle;
      } else if (char === "-") {
        angle -= config.angle;
      } else if (char === "F") {
        currX += config.size * Math.cos(angle);
        currY += -config.size * Math.sin(angle);
        path.push(currX, currY, 0);
      }
    }
    return path;
  }
  const gosper2 = fractalize({
    axiom: "A",
    steps: 4,
    rules: {
      A: "A+BF++BF-FA--FAFA-BF+",
      B: "-FA+BFBF++BF+FA--FA-B"
    }
  });
  const points = toPoints({
    fractal: gosper2,
    size: size2,
    angle: Math.PI / 3
    // 60 degrees
  });
  return points;
}

// node_modules/three/examples/jsm/utils/LDrawUtils.js
var LDrawUtils = class {
  /**
   * Merges geometries in the given object by materials and returns a new group object.
   * Use on not indexed geometries. The object buffers reference the old object ones.
   * Special treatment is done to the conditional lines generated by LDrawLoader.
   *
   * @param {Object3D} object - The object to merge.
   * @returns {Group} The merged object.
   */
  static mergeObject(object) {
    function extractGroup(geometry, group, elementSize, isConditionalLine) {
      const newGeometry = new BufferGeometry();
      const originalPositions = geometry.getAttribute("position").array;
      const originalNormals = elementSize === 3 ? geometry.getAttribute("normal").array : null;
      const numVertsGroup = Math.min(group.count, Math.floor(originalPositions.length / 3) - group.start);
      const vertStart = group.start * 3;
      const vertEnd = (group.start + numVertsGroup) * 3;
      const positions = originalPositions.subarray(vertStart, vertEnd);
      const normals = originalNormals !== null ? originalNormals.subarray(vertStart, vertEnd) : null;
      newGeometry.setAttribute("position", new BufferAttribute(positions, 3));
      if (normals !== null) newGeometry.setAttribute("normal", new BufferAttribute(normals, 3));
      if (isConditionalLine) {
        const controlArray0 = geometry.getAttribute("control0").array.subarray(vertStart, vertEnd);
        const controlArray1 = geometry.getAttribute("control1").array.subarray(vertStart, vertEnd);
        const directionArray = geometry.getAttribute("direction").array.subarray(vertStart, vertEnd);
        newGeometry.setAttribute("control0", new BufferAttribute(controlArray0, 3, false));
        newGeometry.setAttribute("control1", new BufferAttribute(controlArray1, 3, false));
        newGeometry.setAttribute("direction", new BufferAttribute(directionArray, 3, false));
      }
      return newGeometry;
    }
    function addGeometry(mat, geometry, geometries) {
      const geoms = geometries[mat.uuid];
      if (!geoms) {
        geometries[mat.uuid] = {
          mat,
          arr: [geometry]
        };
      } else {
        geoms.arr.push(geometry);
      }
    }
    function permuteAttribute(attribute, elemSize) {
      if (!attribute) return;
      const verts = attribute.array;
      const numVerts = Math.floor(verts.length / 3);
      let offset = 0;
      for (let i = 0; i < numVerts; i++) {
        const x2 = verts[offset];
        const y = verts[offset + 1];
        const z = verts[offset + 2];
        verts[offset] = verts[offset + 3];
        verts[offset + 1] = verts[offset + 4];
        verts[offset + 2] = verts[offset + 5];
        verts[offset + 3] = x2;
        verts[offset + 4] = y;
        verts[offset + 5] = z;
        offset += elemSize * 3;
      }
    }
    const meshGeometries = {};
    const linesGeometries = {};
    const condLinesGeometries = {};
    object.updateMatrixWorld(true);
    const normalMatrix = new Matrix3();
    object.traverse((c2) => {
      if (c2.isMesh | c2.isLineSegments) {
        const elemSize = c2.isMesh ? 3 : 2;
        const geometry = c2.geometry.clone();
        const matrixIsInverted = c2.matrixWorld.determinant() < 0;
        if (matrixIsInverted) {
          permuteAttribute(geometry.attributes.position, elemSize);
          permuteAttribute(geometry.attributes.normal, elemSize);
        }
        geometry.applyMatrix4(c2.matrixWorld);
        if (c2.isConditionalLine) {
          geometry.attributes.control0.applyMatrix4(c2.matrixWorld);
          geometry.attributes.control1.applyMatrix4(c2.matrixWorld);
          normalMatrix.getNormalMatrix(c2.matrixWorld);
          geometry.attributes.direction.applyNormalMatrix(normalMatrix);
        }
        const geometries = c2.isMesh ? meshGeometries : c2.isConditionalLine ? condLinesGeometries : linesGeometries;
        if (Array.isArray(c2.material)) {
          for (const groupIndex in geometry.groups) {
            const group = geometry.groups[groupIndex];
            const mat = c2.material[group.materialIndex];
            const newGeometry = extractGroup(geometry, group, elemSize, c2.isConditionalLine);
            addGeometry(mat, newGeometry, geometries);
          }
        } else {
          addGeometry(c2.material, geometry, geometries);
        }
      }
    });
    const mergedObject = new Group();
    const meshMaterialsIds = Object.keys(meshGeometries);
    for (const meshMaterialsId of meshMaterialsIds) {
      const meshGeometry = meshGeometries[meshMaterialsId];
      const mergedGeometry = mergeGeometries(meshGeometry.arr);
      mergedObject.add(new Mesh(mergedGeometry, meshGeometry.mat));
    }
    const linesMaterialsIds = Object.keys(linesGeometries);
    for (const linesMaterialsId of linesMaterialsIds) {
      const lineGeometry = linesGeometries[linesMaterialsId];
      const mergedGeometry = mergeGeometries(lineGeometry.arr);
      mergedObject.add(new LineSegments(mergedGeometry, lineGeometry.mat));
    }
    const condLinesMaterialsIds = Object.keys(condLinesGeometries);
    for (const condLinesMaterialsId of condLinesMaterialsIds) {
      const condLineGeometry = condLinesGeometries[condLinesMaterialsId];
      const mergedGeometry = mergeGeometries(condLineGeometry.arr);
      const condLines = new LineSegments(mergedGeometry, condLineGeometry.mat);
      condLines.isConditionalLine = true;
      mergedObject.add(condLines);
    }
    mergedObject.userData.constructionStep = 0;
    mergedObject.userData.numConstructionSteps = 1;
    return mergedObject;
  }
};

// node_modules/three/examples/jsm/utils/SceneUtils.js
var SceneUtils_exports = {};
__export(SceneUtils_exports, {
  createMeshesFromInstancedMesh: () => createMeshesFromInstancedMesh,
  createMeshesFromMultiMaterialMesh: () => createMeshesFromMultiMaterialMesh,
  createMultiMaterialObject: () => createMultiMaterialObject,
  reduceVertices: () => reduceVertices,
  sortInstancedMesh: () => sortInstancedMesh,
  traverseAncestorsGenerator: () => traverseAncestorsGenerator,
  traverseGenerator: () => traverseGenerator,
  traverseVisibleGenerator: () => traverseVisibleGenerator
});
var _color4 = new Color();
var _matrix5 = new Matrix4();
function createMeshesFromInstancedMesh(instancedMesh) {
  const group = new Group();
  const count = instancedMesh.count;
  const geometry = instancedMesh.geometry;
  const material = instancedMesh.material;
  for (let i = 0; i < count; i++) {
    const mesh = new Mesh(geometry, material);
    instancedMesh.getMatrixAt(i, mesh.matrix);
    mesh.matrix.decompose(mesh.position, mesh.quaternion, mesh.scale);
    group.add(mesh);
  }
  group.copy(instancedMesh);
  group.updateMatrixWorld();
  return group;
}
function createMeshesFromMultiMaterialMesh(mesh) {
  if (Array.isArray(mesh.material) === false) {
    console.warn("THREE.SceneUtils.createMeshesFromMultiMaterialMesh(): The given mesh has no multiple materials.");
    return mesh;
  }
  const object = new Group();
  object.copy(mesh);
  const geometry = mergeGroups(mesh.geometry);
  const index2 = geometry.index;
  const groups = geometry.groups;
  const attributeNames = Object.keys(geometry.attributes);
  for (let i = 0; i < groups.length; i++) {
    const group = groups[i];
    const start = group.start;
    const end = start + group.count;
    const newGeometry = new BufferGeometry();
    const newMaterial = mesh.material[group.materialIndex];
    for (let j2 = 0; j2 < attributeNames.length; j2++) {
      const name2 = attributeNames[j2];
      const attribute = geometry.attributes[name2];
      const itemSize = attribute.itemSize;
      const newLength = group.count * itemSize;
      const type = attribute.array.constructor;
      const newArray = new type(newLength);
      const newAttribute = new BufferAttribute(newArray, itemSize);
      for (let k2 = start, n2 = 0; k2 < end; k2++, n2++) {
        const ind = index2.getX(k2);
        if (itemSize >= 1) newAttribute.setX(n2, attribute.getX(ind));
        if (itemSize >= 2) newAttribute.setY(n2, attribute.getY(ind));
        if (itemSize >= 3) newAttribute.setZ(n2, attribute.getZ(ind));
        if (itemSize >= 4) newAttribute.setW(n2, attribute.getW(ind));
      }
      newGeometry.setAttribute(name2, newAttribute);
    }
    const newMesh = new Mesh(newGeometry, newMaterial);
    object.add(newMesh);
  }
  return object;
}
function createMultiMaterialObject(geometry, materials) {
  const group = new Group();
  for (let i = 0, l2 = materials.length; i < l2; i++) {
    group.add(new Mesh(geometry, materials[i]));
  }
  return group;
}
function reduceVertices(object, func, initialValue) {
  let value2 = initialValue;
  const vertex = new Vector3();
  object.updateWorldMatrix(true, true);
  object.traverseVisible((child) => {
    const { geometry } = child;
    if (geometry !== void 0) {
      const { position: position2 } = geometry.attributes;
      if (position2 !== void 0) {
        for (let i = 0, l2 = position2.count; i < l2; i++) {
          if (child.isMesh) {
            child.getVertexPosition(i, vertex);
          } else {
            vertex.fromBufferAttribute(position2, i);
          }
          if (!child.isSkinnedMesh) {
            vertex.applyMatrix4(child.matrixWorld);
          }
          value2 = func(value2, vertex);
        }
      }
    }
  });
  return value2;
}
function sortInstancedMesh(mesh, compareFn) {
  const instanceMatrixRef = deepCloneAttribute(mesh.instanceMatrix);
  const instanceColorRef = mesh.instanceColor ? deepCloneAttribute(mesh.instanceColor) : null;
  const attributeRefs = /* @__PURE__ */ new Map();
  for (const name2 in mesh.geometry.attributes) {
    const attribute = mesh.geometry.attributes[name2];
    if (attribute.isInstancedBufferAttribute) {
      attributeRefs.set(attribute, deepCloneAttribute(attribute));
    }
  }
  const tokens = [];
  for (let i = 0; i < mesh.count; i++) tokens.push(i);
  tokens.sort(compareFn);
  for (let i = 0; i < tokens.length; i++) {
    const refIndex = tokens[i];
    _matrix5.fromArray(instanceMatrixRef.array, refIndex * mesh.instanceMatrix.itemSize);
    _matrix5.toArray(mesh.instanceMatrix.array, i * mesh.instanceMatrix.itemSize);
    if (mesh.instanceColor) {
      _color4.fromArray(instanceColorRef.array, refIndex * mesh.instanceColor.itemSize);
      _color4.toArray(mesh.instanceColor.array, i * mesh.instanceColor.itemSize);
    }
    for (const name2 in mesh.geometry.attributes) {
      const attribute = mesh.geometry.attributes[name2];
      if (attribute.isInstancedBufferAttribute) {
        const attributeRef = attributeRefs.get(attribute);
        attribute.setX(i, attributeRef.getX(refIndex));
        if (attribute.itemSize > 1) attribute.setY(i, attributeRef.getY(refIndex));
        if (attribute.itemSize > 2) attribute.setZ(i, attributeRef.getZ(refIndex));
        if (attribute.itemSize > 3) attribute.setW(i, attributeRef.getW(refIndex));
      }
    }
  }
}
function* traverseGenerator(object) {
  yield object;
  const children = object.children;
  for (let i = 0, l2 = children.length; i < l2; i++) {
    yield* traverseGenerator(children[i]);
  }
}
function* traverseVisibleGenerator(object) {
  if (object.visible === false) return;
  yield object;
  const children = object.children;
  for (let i = 0, l2 = children.length; i < l2; i++) {
    yield* traverseVisibleGenerator(children[i]);
  }
}
function* traverseAncestorsGenerator(object) {
  const parent2 = object.parent;
  if (parent2 !== null) {
    yield parent2;
    yield* traverseAncestorsGenerator(parent2);
  }
}

// node_modules/three/examples/jsm/utils/ShadowMapViewer.js
var ShadowMapViewer = class {
  /**
   * Constructs a new shadow map viewer.
   *
   * @param {Light} light - The shadow casting light.
   */
  constructor(light) {
    const scope = this;
    const doRenderLabel = light.name !== void 0 && light.name !== "";
    let userAutoClearSetting;
    const frame = {
      x: 10,
      y: 10,
      width: 256,
      height: 256
    };
    const camera = new OrthographicCamera(window.innerWidth / -2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / -2, 1, 10);
    camera.position.set(0, 0, 2);
    const scene = new Scene();
    const shader = UnpackDepthRGBAShader;
    const uniforms = UniformsUtils.clone(shader.uniforms);
    const material = new ShaderMaterial({
      uniforms,
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader
    });
    const plane2 = new PlaneGeometry(frame.width, frame.height);
    const mesh = new Mesh(plane2, material);
    scene.add(mesh);
    let labelCanvas, labelMesh;
    if (doRenderLabel) {
      labelCanvas = document.createElement("canvas");
      const context = labelCanvas.getContext("2d");
      context.font = "Bold 20px Arial";
      const labelWidth = context.measureText(light.name).width;
      labelCanvas.width = labelWidth;
      labelCanvas.height = 25;
      context.font = "Bold 20px Arial";
      context.fillStyle = "rgba( 255, 0, 0, 1 )";
      context.fillText(light.name, 0, 20);
      const labelTexture = new CanvasTexture(labelCanvas);
      const labelMaterial = new MeshBasicMaterial({ map: labelTexture, side: DoubleSide, transparent: true });
      const labelPlane = new PlaneGeometry(labelCanvas.width, labelCanvas.height);
      labelMesh = new Mesh(labelPlane, labelMaterial);
      scene.add(labelMesh);
    }
    function resetPosition() {
      scope.position.set(scope.position.x, scope.position.y);
    }
    this.enabled = true;
    this.size = {
      width: frame.width,
      height: frame.height,
      set: function(width2, height2) {
        this.width = width2;
        this.height = height2;
        mesh.scale.set(this.width / frame.width, this.height / frame.height, 1);
        resetPosition();
      }
    };
    this.position = {
      x: frame.x,
      y: frame.y,
      set: function(x2, y) {
        this.x = x2;
        this.y = y;
        const width2 = scope.size.width;
        const height2 = scope.size.height;
        mesh.position.set(-window.innerWidth / 2 + width2 / 2 + this.x, window.innerHeight / 2 - height2 / 2 - this.y, 0);
        if (doRenderLabel) labelMesh.position.set(mesh.position.x, mesh.position.y - scope.size.height / 2 + labelCanvas.height / 2, 0);
      }
    };
    this.render = function(renderer2) {
      if (this.enabled) {
        uniforms.tDiffuse.value = light.shadow.map.texture;
        userAutoClearSetting = renderer2.autoClear;
        renderer2.autoClear = false;
        renderer2.clearDepth();
        renderer2.render(scene, camera);
        renderer2.autoClear = userAutoClearSetting;
      }
    };
    this.updateForWindowResize = function() {
      if (this.enabled) {
        camera.left = window.innerWidth / -2;
        camera.right = window.innerWidth / 2;
        camera.top = window.innerHeight / 2;
        camera.bottom = window.innerHeight / -2;
        camera.updateProjectionMatrix();
        this.update();
      }
    };
    this.update = function() {
      this.position.set(this.position.x, this.position.y);
      this.size.set(this.size.width, this.size.height);
    };
    this.update();
  }
};

// node_modules/three/examples/jsm/utils/SkeletonUtils.js
var SkeletonUtils_exports = {};
__export(SkeletonUtils_exports, {
  clone: () => clone,
  retarget: () => retarget,
  retargetClip: () => retargetClip
});
function getBoneName(bone, options) {
  if (options.getBoneName !== void 0) {
    return options.getBoneName(bone);
  }
  return options.names[bone.name];
}
function retarget(target, source, options = {}) {
  const quat = new Quaternion(), scale2 = new Vector3(), relativeMatrix = new Matrix4(), globalMatrix = new Matrix4();
  options.preserveBoneMatrix = options.preserveBoneMatrix !== void 0 ? options.preserveBoneMatrix : true;
  options.preserveBonePositions = options.preserveBonePositions !== void 0 ? options.preserveBonePositions : true;
  options.useTargetMatrix = options.useTargetMatrix !== void 0 ? options.useTargetMatrix : false;
  options.hip = options.hip !== void 0 ? options.hip : "hip";
  options.hipInfluence = options.hipInfluence !== void 0 ? options.hipInfluence : new Vector3(1, 1, 1);
  options.scale = options.scale !== void 0 ? options.scale : 1;
  options.names = options.names || {};
  const sourceBones = source.isObject3D ? source.skeleton.bones : getBones(source), bones = target.isObject3D ? target.skeleton.bones : getBones(target);
  let bone, name2, boneTo, bonesPosition;
  if (target.isObject3D) {
    target.skeleton.pose();
  } else {
    options.useTargetMatrix = true;
    options.preserveBoneMatrix = false;
  }
  if (options.preserveBonePositions) {
    bonesPosition = [];
    for (let i = 0; i < bones.length; i++) {
      bonesPosition.push(bones[i].position.clone());
    }
  }
  if (options.preserveBoneMatrix) {
    target.updateMatrixWorld();
    target.matrixWorld.identity();
    for (let i = 0; i < target.children.length; ++i) {
      target.children[i].updateMatrixWorld(true);
    }
  }
  for (let i = 0; i < bones.length; ++i) {
    bone = bones[i];
    name2 = getBoneName(bone, options);
    boneTo = getBoneByName(name2, sourceBones);
    globalMatrix.copy(bone.matrixWorld);
    if (boneTo) {
      boneTo.updateMatrixWorld();
      if (options.useTargetMatrix) {
        relativeMatrix.copy(boneTo.matrixWorld);
      } else {
        relativeMatrix.copy(target.matrixWorld).invert();
        relativeMatrix.multiply(boneTo.matrixWorld);
      }
      scale2.setFromMatrixScale(relativeMatrix);
      relativeMatrix.scale(scale2.set(1 / scale2.x, 1 / scale2.y, 1 / scale2.z));
      globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix));
      if (target.isObject3D) {
        if (options.localOffsets) {
          if (options.localOffsets[bone.name]) {
            globalMatrix.multiply(options.localOffsets[bone.name]);
          }
        }
      }
      globalMatrix.copyPosition(relativeMatrix);
    }
    if (name2 === options.hip) {
      globalMatrix.elements[12] *= options.scale * options.hipInfluence.x;
      globalMatrix.elements[13] *= options.scale * options.hipInfluence.y;
      globalMatrix.elements[14] *= options.scale * options.hipInfluence.z;
      if (options.hipPosition !== void 0) {
        globalMatrix.elements[12] += options.hipPosition.x * options.scale;
        globalMatrix.elements[13] += options.hipPosition.y * options.scale;
        globalMatrix.elements[14] += options.hipPosition.z * options.scale;
      }
    }
    if (bone.parent) {
      bone.matrix.copy(bone.parent.matrixWorld).invert();
      bone.matrix.multiply(globalMatrix);
    } else {
      bone.matrix.copy(globalMatrix);
    }
    bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
    bone.updateMatrixWorld();
  }
  if (options.preserveBonePositions) {
    for (let i = 0; i < bones.length; ++i) {
      bone = bones[i];
      name2 = getBoneName(bone, options) || bone.name;
      if (name2 !== options.hip) {
        bone.position.copy(bonesPosition[i]);
      }
    }
  }
  if (options.preserveBoneMatrix) {
    target.updateMatrixWorld(true);
  }
}
function retargetClip(target, source, clip, options = {}) {
  options.useFirstFramePosition = options.useFirstFramePosition !== void 0 ? options.useFirstFramePosition : false;
  options.fps = options.fps !== void 0 ? options.fps : Math.max(...clip.tracks.map((track) => track.times.length)) / clip.duration;
  options.names = options.names || [];
  if (!source.isObject3D) {
    source = getHelperFromSkeleton(source);
  }
  const numFrames = Math.round(clip.duration * (options.fps / 1e3) * 1e3), delta = clip.duration / (numFrames - 1), convertedTracks = [], mixer = new AnimationMixer(source), bones = getBones(target.skeleton), boneDatas = [];
  let positionOffset, bone, boneTo, boneData, name2;
  mixer.clipAction(clip).play();
  let start = 0, end = numFrames;
  if (options.trim !== void 0) {
    start = Math.round(options.trim[0] * options.fps);
    end = Math.min(Math.round(options.trim[1] * options.fps), numFrames) - start;
    mixer.update(options.trim[0]);
  } else {
    mixer.update(0);
  }
  source.updateMatrixWorld();
  for (let frame = 0; frame < end; ++frame) {
    const time2 = frame * delta;
    retarget(target, source, options);
    for (let j2 = 0; j2 < bones.length; ++j2) {
      bone = bones[j2];
      name2 = getBoneName(bone, options) || bone.name;
      boneTo = getBoneByName(name2, source.skeleton);
      if (boneTo) {
        boneData = boneDatas[j2] = boneDatas[j2] || { bone };
        if (options.hip === name2) {
          if (!boneData.pos) {
            boneData.pos = {
              times: new Float32Array(end),
              values: new Float32Array(end * 3)
            };
          }
          if (options.useFirstFramePosition) {
            if (frame === 0) {
              positionOffset = bone.position.clone();
            }
            bone.position.sub(positionOffset);
          }
          boneData.pos.times[frame] = time2;
          bone.position.toArray(boneData.pos.values, frame * 3);
        }
        if (!boneData.quat) {
          boneData.quat = {
            times: new Float32Array(end),
            values: new Float32Array(end * 4)
          };
        }
        boneData.quat.times[frame] = time2;
        bone.quaternion.toArray(boneData.quat.values, frame * 4);
      }
    }
    if (frame === end - 2) {
      mixer.update(delta - 1e-7);
    } else {
      mixer.update(delta);
    }
    source.updateMatrixWorld();
  }
  for (let i = 0; i < boneDatas.length; ++i) {
    boneData = boneDatas[i];
    if (boneData) {
      if (boneData.pos) {
        convertedTracks.push(new VectorKeyframeTrack(
          ".bones[" + boneData.bone.name + "].position",
          boneData.pos.times,
          boneData.pos.values
        ));
      }
      convertedTracks.push(new QuaternionKeyframeTrack(
        ".bones[" + boneData.bone.name + "].quaternion",
        boneData.quat.times,
        boneData.quat.values
      ));
    }
  }
  mixer.uncacheAction(clip);
  return new AnimationClip(clip.name, -1, convertedTracks);
}
function clone(source) {
  const sourceLookup = /* @__PURE__ */ new Map();
  const cloneLookup = /* @__PURE__ */ new Map();
  const clone2 = source.clone();
  parallelTraverse(source, clone2, function(sourceNode, clonedNode) {
    sourceLookup.set(clonedNode, sourceNode);
    cloneLookup.set(sourceNode, clonedNode);
  });
  clone2.traverse(function(node) {
    if (!node.isSkinnedMesh) return;
    const clonedMesh = node;
    const sourceMesh = sourceLookup.get(node);
    const sourceBones = sourceMesh.skeleton.bones;
    clonedMesh.skeleton = sourceMesh.skeleton.clone();
    clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix);
    clonedMesh.skeleton.bones = sourceBones.map(function(bone) {
      return cloneLookup.get(bone);
    });
    clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix);
  });
  return clone2;
}
function getBoneByName(name2, skeleton) {
  for (let i = 0, bones = getBones(skeleton); i < bones.length; i++) {
    if (name2 === bones[i].name)
      return bones[i];
  }
}
function getBones(skeleton) {
  return Array.isArray(skeleton) ? skeleton : skeleton.bones;
}
function getHelperFromSkeleton(skeleton) {
  const source = new SkeletonHelper(skeleton.bones[0]);
  source.skeleton = skeleton;
  return source;
}
function parallelTraverse(a2, b3, callback) {
  callback(a2, b3);
  for (let i = 0; i < a2.children.length; i++) {
    parallelTraverse(a2.children[i], b3.children[i], callback);
  }
}

// node_modules/three/examples/jsm/utils/SortUtils.js
var SortUtils_exports = {};
__export(SortUtils_exports, {
  radixSort: () => radixSort
});
var POWER = 3;
var BIT_MAX = 32;
var BIN_BITS = 1 << POWER;
var BIN_SIZE = 1 << BIN_BITS;
var BIN_MAX = BIN_SIZE - 1;
var ITERATIONS = BIT_MAX / BIN_BITS;
var bins = new Array(ITERATIONS);
var bins_buffer = new ArrayBuffer((ITERATIONS + 1) * BIN_SIZE * 4);
var c = 0;
for (let i = 0; i < ITERATIONS + 1; i++) {
  bins[i] = new Uint32Array(bins_buffer, c, BIN_SIZE);
  c += BIN_SIZE * 4;
}
var defaultGet = (el) => el;
var radixSort = (arr, opt) => {
  const len = arr.length;
  const options = opt || {};
  const aux = options.aux || new arr.constructor(len);
  const get = options.get || defaultGet;
  const data2 = [arr, aux];
  let compare, accumulate, recurse;
  if (options.reversed) {
    compare = (a2, b3) => a2 < b3;
    accumulate = (bin) => {
      for (let j2 = BIN_SIZE - 2; j2 >= 0; j2--)
        bin[j2] += bin[j2 + 1];
    };
    recurse = (cache, depth, start) => {
      let prev = 0;
      for (let j2 = BIN_MAX; j2 >= 0; j2--) {
        const cur = cache[j2], diff = cur - prev;
        if (diff != 0) {
          if (diff > 32)
            radixSortBlock(depth + 1, start + prev, diff);
          else
            insertionSortBlock(depth + 1, start + prev, diff);
          prev = cur;
        }
      }
    };
  } else {
    compare = (a2, b3) => a2 > b3;
    accumulate = (bin) => {
      for (let j2 = 1; j2 < BIN_SIZE; j2++)
        bin[j2] += bin[j2 - 1];
    };
    recurse = (cache, depth, start) => {
      let prev = 0;
      for (let j2 = 0; j2 < BIN_SIZE; j2++) {
        const cur = cache[j2], diff = cur - prev;
        if (diff != 0) {
          if (diff > 32)
            radixSortBlock(depth + 1, start + prev, diff);
          else
            insertionSortBlock(depth + 1, start + prev, diff);
          prev = cur;
        }
      }
    };
  }
  const insertionSortBlock = (depth, start, len2) => {
    const a2 = data2[depth & 1];
    const b3 = data2[depth + 1 & 1];
    for (let j2 = start + 1; j2 < start + len2; j2++) {
      const p = a2[j2], t3 = get(p) >>> 0;
      let i = j2;
      while (i > start) {
        if (compare(get(a2[i - 1]) >>> 0, t3))
          a2[i] = a2[--i];
        else
          break;
      }
      a2[i] = p;
    }
    if ((depth & 1) == 1) {
      for (let i = start; i < start + len2; i++)
        b3[i] = a2[i];
    }
  };
  const radixSortBlock = (depth, start, len2) => {
    const a2 = data2[depth & 1];
    const b3 = data2[depth + 1 & 1];
    const shift = 3 - depth << POWER;
    const end = start + len2;
    const cache = bins[depth];
    const bin = bins[depth + 1];
    bin.fill(0);
    for (let j2 = start; j2 < end; j2++)
      bin[get(a2[j2]) >>> shift & BIN_MAX]++;
    accumulate(bin);
    cache.set(bin);
    for (let j2 = end - 1; j2 >= start; j2--)
      b3[start + --bin[get(a2[j2]) >>> shift & BIN_MAX]] = a2[j2];
    if (depth == ITERATIONS - 1) return;
    recurse(cache, depth, start);
  };
  radixSortBlock(0, 0, len);
};

// node_modules/three/examples/jsm/utils/WebGLTextureUtils.js
var _renderer;
var fullscreenQuadGeometry;
var fullscreenQuadMaterial;
var fullscreenQuad;
function decompress(texture, maxTextureSize = Infinity, renderer2 = null) {
  if (!fullscreenQuadGeometry) fullscreenQuadGeometry = new PlaneGeometry(2, 2, 1, 1);
  if (!fullscreenQuadMaterial) fullscreenQuadMaterial = new ShaderMaterial({
    uniforms: { blitTexture: new Uniform(texture) },
    vertexShader: `
			varying vec2 vUv;
			void main(){
				vUv = uv;
				gl_Position = vec4(position.xy * 1.0,0.,.999999);
			}`,
    fragmentShader: `
			uniform sampler2D blitTexture; 
			varying vec2 vUv;

			void main(){ 
				gl_FragColor = vec4(vUv.xy, 0, 1);
				
				#ifdef IS_SRGB
				gl_FragColor = sRGBTransferOETF( texture2D( blitTexture, vUv) );
				#else
				gl_FragColor = texture2D( blitTexture, vUv);
				#endif
			}`
  });
  fullscreenQuadMaterial.uniforms.blitTexture.value = texture;
  fullscreenQuadMaterial.defines.IS_SRGB = texture.colorSpace == SRGBColorSpace;
  fullscreenQuadMaterial.needsUpdate = true;
  if (!fullscreenQuad) {
    fullscreenQuad = new Mesh(fullscreenQuadGeometry, fullscreenQuadMaterial);
    fullscreenQuad.frustumCulled = false;
  }
  const _camera2 = new PerspectiveCamera();
  const _scene = new Scene();
  _scene.add(fullscreenQuad);
  if (renderer2 === null) {
    renderer2 = _renderer = new WebGLRenderer({ antialias: false });
  }
  const width2 = Math.min(texture.image.width, maxTextureSize);
  const height2 = Math.min(texture.image.height, maxTextureSize);
  renderer2.setSize(width2, height2);
  renderer2.clear();
  renderer2.render(_scene, _camera2);
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  canvas.width = width2;
  canvas.height = height2;
  context.drawImage(renderer2.domElement, 0, 0, width2, height2);
  const readableTexture = new CanvasTexture(canvas);
  readableTexture.minFilter = texture.minFilter;
  readableTexture.magFilter = texture.magFilter;
  readableTexture.wrapS = texture.wrapS;
  readableTexture.wrapT = texture.wrapT;
  readableTexture.colorSpace = texture.colorSpace;
  readableTexture.name = texture.name;
  if (_renderer) {
    _renderer.forceContextLoss();
    _renderer.dispose();
    _renderer = null;
  }
  return readableTexture;
}

// node_modules/three/examples/jsm/utils/UVsDebug.js
function UVsDebug(geometry, size2 = 1024) {
  const abc = "abc";
  const a2 = new Vector2();
  const b3 = new Vector2();
  const uvs = [
    new Vector2(),
    new Vector2(),
    new Vector2()
  ];
  const face = [];
  const canvas = document.createElement("canvas");
  const width2 = size2;
  const height2 = size2;
  canvas.width = width2;
  canvas.height = height2;
  const ctx = canvas.getContext("2d");
  ctx.lineWidth = 1;
  ctx.strokeStyle = "rgb( 63, 63, 63 )";
  ctx.textAlign = "center";
  ctx.fillStyle = "rgb( 255, 255, 255 )";
  ctx.fillRect(0, 0, width2, height2);
  const index2 = geometry.index;
  const uvAttribute = geometry.attributes.uv;
  if (index2) {
    for (let i = 0, il = index2.count; i < il; i += 3) {
      face[0] = index2.getX(i);
      face[1] = index2.getX(i + 1);
      face[2] = index2.getX(i + 2);
      uvs[0].fromBufferAttribute(uvAttribute, face[0]);
      uvs[1].fromBufferAttribute(uvAttribute, face[1]);
      uvs[2].fromBufferAttribute(uvAttribute, face[2]);
      processFace(face, uvs, i / 3);
    }
  } else {
    for (let i = 0, il = uvAttribute.count; i < il; i += 3) {
      face[0] = i;
      face[1] = i + 1;
      face[2] = i + 2;
      uvs[0].fromBufferAttribute(uvAttribute, face[0]);
      uvs[1].fromBufferAttribute(uvAttribute, face[1]);
      uvs[2].fromBufferAttribute(uvAttribute, face[2]);
      processFace(face, uvs, i / 3);
    }
  }
  return canvas;
  function processFace(face2, uvs2, index3) {
    ctx.beginPath();
    a2.set(0, 0);
    for (let j2 = 0, jl = uvs2.length; j2 < jl; j2++) {
      const uv = uvs2[j2];
      a2.x += uv.x;
      a2.y += uv.y;
      if (j2 === 0) {
        ctx.moveTo(uv.x * (width2 - 2) + 0.5, (1 - uv.y) * (height2 - 2) + 0.5);
      } else {
        ctx.lineTo(uv.x * (width2 - 2) + 0.5, (1 - uv.y) * (height2 - 2) + 0.5);
      }
    }
    ctx.closePath();
    ctx.stroke();
    a2.divideScalar(uvs2.length);
    ctx.font = "18px Arial";
    ctx.fillStyle = "rgb( 63, 63, 63 )";
    ctx.fillText(index3, a2.x * width2, (1 - a2.y) * height2);
    if (a2.x > 0.95) {
      ctx.fillText(index3, a2.x % 1 * width2, (1 - a2.y) * height2);
    }
    ctx.font = "12px Arial";
    ctx.fillStyle = "rgb( 191, 191, 191 )";
    for (let j2 = 0, jl = uvs2.length; j2 < jl; j2++) {
      const uv = uvs2[j2];
      b3.addVectors(a2, uv).divideScalar(2);
      const vnum = face2[j2];
      ctx.fillText(abc[j2] + vnum, b3.x * width2, (1 - b3.y) * height2);
      if (b3.x > 0.95) {
        ctx.fillText(abc[j2] + vnum, b3.x % 1 * width2, (1 - b3.y) * height2);
      }
    }
  }
}

// node_modules/three/examples/jsm/webxr/ARButton.js
var ARButton = class {
  /**
   * Constructs a new AR button.
   *
   * @param {WebGLRenderer|WebGPURenderer} renderer - The renderer.
   * @param {XRSessionInit} [sessionInit] - The a configuration object for the AR session.
   * @return {HTMLElement} The button or an error message if `immersive-ar` isn't supported.
   */
  static createButton(renderer2, sessionInit = {}) {
    const button = document.createElement("button");
    function showStartAR() {
      if (sessionInit.domOverlay === void 0) {
        const overlay = document.createElement("div");
        overlay.style.display = "none";
        document.body.appendChild(overlay);
        const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
        svg.setAttribute("width", 38);
        svg.setAttribute("height", 38);
        svg.style.position = "absolute";
        svg.style.right = "20px";
        svg.style.top = "20px";
        svg.addEventListener("click", function() {
          currentSession.end();
        });
        overlay.appendChild(svg);
        const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
        path.setAttribute("d", "M 12,12 L 28,28 M 28,12 12,28");
        path.setAttribute("stroke", "#fff");
        path.setAttribute("stroke-width", 2);
        svg.appendChild(path);
        if (sessionInit.optionalFeatures === void 0) {
          sessionInit.optionalFeatures = [];
        }
        sessionInit.optionalFeatures.push("dom-overlay");
        sessionInit.domOverlay = { root: overlay };
      }
      let currentSession = null;
      async function onSessionStarted(session) {
        session.addEventListener("end", onSessionEnded);
        renderer2.xr.setReferenceSpaceType("local");
        await renderer2.xr.setSession(session);
        button.textContent = "STOP AR";
        sessionInit.domOverlay.root.style.display = "";
        currentSession = session;
      }
      function onSessionEnded() {
        currentSession.removeEventListener("end", onSessionEnded);
        button.textContent = "START AR";
        sessionInit.domOverlay.root.style.display = "none";
        currentSession = null;
      }
      button.style.display = "";
      button.style.cursor = "pointer";
      button.style.left = "calc(50% - 50px)";
      button.style.width = "100px";
      button.textContent = "START AR";
      button.onmouseenter = function() {
        button.style.opacity = "1.0";
      };
      button.onmouseleave = function() {
        button.style.opacity = "0.5";
      };
      button.onclick = function() {
        if (currentSession === null) {
          navigator.xr.requestSession("immersive-ar", sessionInit).then(onSessionStarted);
        } else {
          currentSession.end();
          if (navigator.xr.offerSession !== void 0) {
            navigator.xr.offerSession("immersive-ar", sessionInit).then(onSessionStarted).catch((err2) => {
              console.warn(err2);
            });
          }
        }
      };
      if (navigator.xr.offerSession !== void 0) {
        navigator.xr.offerSession("immersive-ar", sessionInit).then(onSessionStarted).catch((err2) => {
          console.warn(err2);
        });
      }
    }
    function disableButton() {
      button.style.display = "";
      button.style.cursor = "auto";
      button.style.left = "calc(50% - 75px)";
      button.style.width = "150px";
      button.onmouseenter = null;
      button.onmouseleave = null;
      button.onclick = null;
    }
    function showARNotSupported() {
      disableButton();
      button.textContent = "AR NOT SUPPORTED";
    }
    function showARNotAllowed(exception) {
      disableButton();
      console.warn("Exception when trying to call xr.isSessionSupported", exception);
      button.textContent = "AR NOT ALLOWED";
    }
    function stylizeElement(element) {
      element.style.position = "absolute";
      element.style.bottom = "20px";
      element.style.padding = "12px 6px";
      element.style.border = "1px solid #fff";
      element.style.borderRadius = "4px";
      element.style.background = "rgba(0,0,0,0.1)";
      element.style.color = "#fff";
      element.style.font = "normal 13px sans-serif";
      element.style.textAlign = "center";
      element.style.opacity = "0.5";
      element.style.outline = "none";
      element.style.zIndex = "999";
    }
    if ("xr" in navigator) {
      button.id = "ARButton";
      button.style.display = "none";
      stylizeElement(button);
      navigator.xr.isSessionSupported("immersive-ar").then(function(supported) {
        supported ? showStartAR() : showARNotSupported();
      }).catch(showARNotAllowed);
      return button;
    } else {
      const message = document.createElement("a");
      if (window.isSecureContext === false) {
        message.href = document.location.href.replace(/^http:/, "https:");
        message.innerHTML = "WEBXR NEEDS HTTPS";
      } else {
        message.href = "https://immersiveweb.dev/";
        message.innerHTML = "WEBXR NOT AVAILABLE";
      }
      message.style.left = "calc(50% - 90px)";
      message.style.width = "180px";
      message.style.textDecoration = "none";
      stylizeElement(message);
      return message;
    }
  }
};

// node_modules/three/examples/jsm/webxr/XRHandMeshModel.js
var DEFAULT_HAND_PROFILE_PATH = "https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";
var XRHandMeshModel = class {
  /**
   * Constructs a new XR hand mesh model.
   *
   * @param {XRHandModel} handModel - The hand model.
   * @param {Group} controller - The WebXR controller.
   * @param {?string} path - The model path.
   * @param {XRHandedness} handedness - The handedness of the XR input source.
   * @param {?Loader} [loader=null] - The loader. If not provided, an instance of `GLTFLoader` will be used to load models.
   * @param {?Function} [onLoad=null] - A callback that is executed when a controller model has been loaded.
   */
  constructor(handModel, controller, path, handedness, loader = null, onLoad = null) {
    this.controller = controller;
    this.handModel = handModel;
    this.bones = [];
    if (loader === null) {
      loader = new GLTFLoader();
      loader.setPath(path || DEFAULT_HAND_PROFILE_PATH);
    }
    loader.load(`${handedness}.glb`, (gltf) => {
      const object = gltf.scene.children[0];
      this.handModel.add(object);
      const mesh = object.getObjectByProperty("type", "SkinnedMesh");
      mesh.frustumCulled = false;
      mesh.castShadow = true;
      mesh.receiveShadow = true;
      const joints = [
        "wrist",
        "thumb-metacarpal",
        "thumb-phalanx-proximal",
        "thumb-phalanx-distal",
        "thumb-tip",
        "index-finger-metacarpal",
        "index-finger-phalanx-proximal",
        "index-finger-phalanx-intermediate",
        "index-finger-phalanx-distal",
        "index-finger-tip",
        "middle-finger-metacarpal",
        "middle-finger-phalanx-proximal",
        "middle-finger-phalanx-intermediate",
        "middle-finger-phalanx-distal",
        "middle-finger-tip",
        "ring-finger-metacarpal",
        "ring-finger-phalanx-proximal",
        "ring-finger-phalanx-intermediate",
        "ring-finger-phalanx-distal",
        "ring-finger-tip",
        "pinky-finger-metacarpal",
        "pinky-finger-phalanx-proximal",
        "pinky-finger-phalanx-intermediate",
        "pinky-finger-phalanx-distal",
        "pinky-finger-tip"
      ];
      joints.forEach((jointName) => {
        const bone = object.getObjectByName(jointName);
        if (bone !== void 0) {
          bone.jointName = jointName;
        } else {
          console.warn(`Couldn't find ${jointName} in ${handedness} hand mesh`);
        }
        this.bones.push(bone);
      });
      if (onLoad) onLoad(object);
    });
  }
  /**
   * Updates the mesh based on the tracked XR joints data.
   */
  updateMesh() {
    const XRJoints = this.controller.joints;
    for (let i = 0; i < this.bones.length; i++) {
      const bone = this.bones[i];
      if (bone) {
        const XRJoint = XRJoints[bone.jointName];
        if (XRJoint.visible) {
          const position2 = XRJoint.position;
          bone.position.copy(position2);
          bone.quaternion.copy(XRJoint.quaternion);
        }
      }
    }
  }
};

// node_modules/three/examples/jsm/webxr/OculusHandModel.js
var TOUCH_RADIUS = 0.01;
var POINTING_JOINT = "index-finger-tip";
var OculusHandModel = class extends Object3D {
  /**
   * Constructs a new Oculus hand model.
   *
   * @param {Group} controller - The hand controller.
   * @param {?Loader} [loader=null] - A loader that is used to load hand models.
   * @param {?Function} [onLoad=null] - A callback that is executed when a hand model has been loaded.
   */
  constructor(controller, loader = null, onLoad = null) {
    super();
    this.controller = controller;
    this.motionController = null;
    this.envMap = null;
    this.loader = loader;
    this.onLoad = onLoad;
    this.path = null;
    this.mesh = null;
    controller.addEventListener("connected", (event) => {
      const xrInputSource = event.data;
      if (xrInputSource.hand && !this.motionController) {
        this.xrInputSource = xrInputSource;
        this.motionController = new XRHandMeshModel(this, controller, this.path, xrInputSource.handedness, this.loader, this.onLoad);
      }
    });
    controller.addEventListener("disconnected", () => {
      this.clear();
      this.motionController = null;
    });
  }
  /**
   * Overwritten with a custom implementation. Makes sure the motion controller updates the mesh.
   *
   * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
   * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
   */
  updateMatrixWorld(force) {
    super.updateMatrixWorld(force);
    if (this.motionController) {
      this.motionController.updateMesh();
    }
  }
  /**
   * Returns the pointer position which is the position of the index finger tip.
   *
   * @return {Vector3|null} The pointer position. Returns `null` if not index finger tip joint was found.
   */
  getPointerPosition() {
    const indexFingerTip = this.controller.joints[POINTING_JOINT];
    if (indexFingerTip) {
      return indexFingerTip.position;
    } else {
      return null;
    }
  }
  /**
   * Returns `true` if the current pointer position (the index finger tip) intersections
   * with the given box object.
   *
   *  @param {Mesh} boxObject - The box object.
   * @return {boolean} Whether an intersection was found or not.
   */
  intersectBoxObject(boxObject) {
    const pointerPosition = this.getPointerPosition();
    if (pointerPosition) {
      const indexSphere = new Sphere(pointerPosition, TOUCH_RADIUS);
      const box = new Box3().setFromObject(boxObject);
      return indexSphere.intersectsBox(box);
    } else {
      return false;
    }
  }
  /**
   * Executed actions depending on the interaction state with
   * the given button.
   *
   *  @param {Object} button - The button.
   */
  checkButton(button) {
    if (this.intersectBoxObject(button)) {
      button.onPress();
    } else {
      button.onClear();
    }
    if (button.isPressed()) {
      button.whilePressed();
    }
  }
};

// node_modules/three/examples/jsm/webxr/OculusHandPointerModel.js
var PINCH_MAX = 0.05;
var PINCH_THRESHOLD = 0.02;
var PINCH_MIN = 0.01;
var POINTER_ADVANCE_MAX = 0.02;
var POINTER_OPACITY_MAX = 1;
var POINTER_OPACITY_MIN = 0.4;
var POINTER_FRONT_RADIUS = 2e-3;
var POINTER_REAR_RADIUS = 0.01;
var POINTER_REAR_RADIUS_MIN = 3e-3;
var POINTER_LENGTH = 0.035;
var POINTER_SEGMENTS = 16;
var POINTER_RINGS = 12;
var POINTER_HEMISPHERE_ANGLE = 110;
var YAXIS = new Vector3(0, 1, 0);
var ZAXIS = new Vector3(0, 0, 1);
var CURSOR_RADIUS = 0.02;
var CURSOR_MAX_DISTANCE = 1.5;
var OculusHandPointerModel = class extends Object3D {
  /**
   * Constructs a new Oculus hand model.
   *
   * @param {Group} hand - The hand controller.
   * @param {Group} controller - The WebXR controller in target ray space.
   */
  constructor(hand, controller) {
    super();
    this.hand = hand;
    this.controller = controller;
    this.motionController = null;
    this.envMap = null;
    this.mesh = null;
    this.pointerGeometry = null;
    this.pointerMesh = null;
    this.pointerObject = null;
    this.pinched = false;
    this.attached = false;
    this.cursorObject = null;
    this.raycaster = null;
    this._onConnected = this._onConnected.bind(this);
    this._onDisconnected = this._onDisconnected.bind(this);
    this.hand.addEventListener("connected", this._onConnected);
    this.hand.addEventListener("disconnected", this._onDisconnected);
  }
  _onConnected(event) {
    const xrInputSource = event.data;
    if (xrInputSource.hand) {
      this.visible = true;
      this.xrInputSource = xrInputSource;
      this.createPointer();
    }
  }
  _onDisconnected() {
    this.visible = false;
    this.xrInputSource = null;
    if (this.pointerGeometry) this.pointerGeometry.dispose();
    if (this.pointerMesh && this.pointerMesh.material) this.pointerMesh.material.dispose();
    this.clear();
  }
  _drawVerticesRing(vertices, baseVector, ringIndex) {
    const segmentVector = baseVector.clone();
    for (let i = 0; i < POINTER_SEGMENTS; i++) {
      segmentVector.applyAxisAngle(ZAXIS, Math.PI * 2 / POINTER_SEGMENTS);
      const vid = ringIndex * POINTER_SEGMENTS + i;
      vertices[3 * vid] = segmentVector.x;
      vertices[3 * vid + 1] = segmentVector.y;
      vertices[3 * vid + 2] = segmentVector.z;
    }
  }
  _updatePointerVertices(rearRadius) {
    const vertices = this.pointerGeometry.attributes.position.array;
    const frontFaceBase = new Vector3(
      POINTER_FRONT_RADIUS,
      0,
      -1 * (POINTER_LENGTH - rearRadius)
    );
    this._drawVerticesRing(vertices, frontFaceBase, 0);
    const rearBase = new Vector3(
      Math.sin(Math.PI * POINTER_HEMISPHERE_ANGLE / 180) * rearRadius,
      Math.cos(Math.PI * POINTER_HEMISPHERE_ANGLE / 180) * rearRadius,
      0
    );
    for (let i = 0; i < POINTER_RINGS; i++) {
      this._drawVerticesRing(vertices, rearBase, i + 1);
      rearBase.applyAxisAngle(
        YAXIS,
        Math.PI * POINTER_HEMISPHERE_ANGLE / 180 / (POINTER_RINGS * -2)
      );
    }
    const frontCenterIndex = POINTER_SEGMENTS * (1 + POINTER_RINGS);
    const rearCenterIndex = POINTER_SEGMENTS * (1 + POINTER_RINGS) + 1;
    const frontCenter = new Vector3(
      0,
      0,
      -1 * (POINTER_LENGTH - rearRadius)
    );
    vertices[frontCenterIndex * 3] = frontCenter.x;
    vertices[frontCenterIndex * 3 + 1] = frontCenter.y;
    vertices[frontCenterIndex * 3 + 2] = frontCenter.z;
    const rearCenter = new Vector3(0, 0, rearRadius);
    vertices[rearCenterIndex * 3] = rearCenter.x;
    vertices[rearCenterIndex * 3 + 1] = rearCenter.y;
    vertices[rearCenterIndex * 3 + 2] = rearCenter.z;
    this.pointerGeometry.setAttribute(
      "position",
      new Float32BufferAttribute(vertices, 3)
    );
  }
  /**
   * Creates a pointer mesh and adds it to this model.
   */
  createPointer() {
    let i, j2;
    const vertices = new Array(
      ((POINTER_RINGS + 1) * POINTER_SEGMENTS + 2) * 3
    ).fill(0);
    const indices = [];
    this.pointerGeometry = new BufferGeometry();
    this.pointerGeometry.setAttribute(
      "position",
      new Float32BufferAttribute(vertices, 3)
    );
    this._updatePointerVertices(POINTER_REAR_RADIUS);
    for (i = 0; i < POINTER_RINGS; i++) {
      for (j2 = 0; j2 < POINTER_SEGMENTS - 1; j2++) {
        indices.push(
          i * POINTER_SEGMENTS + j2,
          i * POINTER_SEGMENTS + j2 + 1,
          (i + 1) * POINTER_SEGMENTS + j2
        );
        indices.push(
          i * POINTER_SEGMENTS + j2 + 1,
          (i + 1) * POINTER_SEGMENTS + j2 + 1,
          (i + 1) * POINTER_SEGMENTS + j2
        );
      }
      indices.push(
        (i + 1) * POINTER_SEGMENTS - 1,
        i * POINTER_SEGMENTS,
        (i + 2) * POINTER_SEGMENTS - 1
      );
      indices.push(
        i * POINTER_SEGMENTS,
        (i + 1) * POINTER_SEGMENTS,
        (i + 2) * POINTER_SEGMENTS - 1
      );
    }
    const frontCenterIndex = POINTER_SEGMENTS * (1 + POINTER_RINGS);
    const rearCenterIndex = POINTER_SEGMENTS * (1 + POINTER_RINGS) + 1;
    for (i = 0; i < POINTER_SEGMENTS - 1; i++) {
      indices.push(frontCenterIndex, i + 1, i);
      indices.push(
        rearCenterIndex,
        i + POINTER_SEGMENTS * POINTER_RINGS,
        i + POINTER_SEGMENTS * POINTER_RINGS + 1
      );
    }
    indices.push(frontCenterIndex, 0, POINTER_SEGMENTS - 1);
    indices.push(
      rearCenterIndex,
      POINTER_SEGMENTS * (POINTER_RINGS + 1) - 1,
      POINTER_SEGMENTS * POINTER_RINGS
    );
    const material = new MeshBasicMaterial();
    material.transparent = true;
    material.opacity = POINTER_OPACITY_MIN;
    this.pointerGeometry.setIndex(indices);
    this.pointerMesh = new Mesh(this.pointerGeometry, material);
    this.pointerMesh.position.set(0, 0, -1 * POINTER_REAR_RADIUS);
    this.pointerObject = new Object3D();
    this.pointerObject.add(this.pointerMesh);
    this.raycaster = new Raycaster();
    const cursorGeometry = new SphereGeometry(CURSOR_RADIUS, 10, 10);
    const cursorMaterial = new MeshBasicMaterial();
    cursorMaterial.transparent = true;
    cursorMaterial.opacity = POINTER_OPACITY_MIN;
    this.cursorObject = new Mesh(cursorGeometry, cursorMaterial);
    this.pointerObject.add(this.cursorObject);
    this.add(this.pointerObject);
  }
  _updateRaycaster() {
    if (this.raycaster) {
      const pointerMatrix = this.pointerObject.matrixWorld;
      const tempMatrix = new Matrix4();
      tempMatrix.identity().extractRotation(pointerMatrix);
      this.raycaster.ray.origin.setFromMatrixPosition(pointerMatrix);
      this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(tempMatrix);
    }
  }
  _updatePointer() {
    this.pointerObject.visible = this.controller.visible;
    const indexTip = this.hand.joints["index-finger-tip"];
    const thumbTip = this.hand.joints["thumb-tip"];
    const distance = indexTip.position.distanceTo(thumbTip.position);
    const position2 = indexTip.position.clone().add(thumbTip.position).multiplyScalar(0.5);
    this.pointerObject.position.copy(position2);
    this.pointerObject.quaternion.copy(this.controller.quaternion);
    this.pinched = distance <= PINCH_THRESHOLD;
    const pinchScale = (distance - PINCH_MIN) / (PINCH_MAX - PINCH_MIN);
    const focusScale = (distance - PINCH_MIN) / (PINCH_THRESHOLD - PINCH_MIN);
    if (pinchScale > 1) {
      this._updatePointerVertices(POINTER_REAR_RADIUS);
      this.pointerMesh.position.set(0, 0, -1 * POINTER_REAR_RADIUS);
      this.pointerMesh.material.opacity = POINTER_OPACITY_MIN;
    } else if (pinchScale > 0) {
      const rearRadius = (POINTER_REAR_RADIUS - POINTER_REAR_RADIUS_MIN) * pinchScale + POINTER_REAR_RADIUS_MIN;
      this._updatePointerVertices(rearRadius);
      if (focusScale < 1) {
        this.pointerMesh.position.set(
          0,
          0,
          -1 * rearRadius - (1 - focusScale) * POINTER_ADVANCE_MAX
        );
        this.pointerMesh.material.opacity = POINTER_OPACITY_MIN + (1 - focusScale) * (POINTER_OPACITY_MAX - POINTER_OPACITY_MIN);
      } else {
        this.pointerMesh.position.set(0, 0, -1 * rearRadius);
        this.pointerMesh.material.opacity = POINTER_OPACITY_MIN;
      }
    } else {
      this._updatePointerVertices(POINTER_REAR_RADIUS_MIN);
      this.pointerMesh.position.set(
        0,
        0,
        -1 * POINTER_REAR_RADIUS_MIN - POINTER_ADVANCE_MAX
      );
      this.pointerMesh.material.opacity = POINTER_OPACITY_MAX;
    }
    this.cursorObject.material.opacity = this.pointerMesh.material.opacity;
  }
  /**
   * Overwritten with a custom implementation. Makes sure the internal pointer and raycaster are updated.
   *
   * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
   * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
   */
  updateMatrixWorld(force) {
    super.updateMatrixWorld(force);
    if (this.pointerGeometry) {
      this._updatePointer();
      this._updateRaycaster();
    }
  }
  /**
   * Returns `true` is the model is pinched.
   *
   * @return {boolean} Whether the model is pinched or not.
   */
  isPinched() {
    return this.pinched;
  }
  /**
   * Sets the attached state.
   *
   * @param {boolean} attached - Whether the model is attached or not.
   */
  setAttached(attached) {
    this.attached = attached;
  }
  /**
   * Returns `true` is the model is attached.
   *
   * @return {boolean} Whether the model is attached or not.
   */
  isAttached() {
    return this.attached;
  }
  /**
   * Performs an intersection test with the model's raycaster and the given object.
   *
   * @param {Object3D} object - The 3D object to check for intersection with the ray.
   * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
   * Otherwise it only checks intersection with the object.
   * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
   */
  intersectObject(object, recursive = true) {
    if (this.raycaster) {
      return this.raycaster.intersectObject(object, recursive);
    }
  }
  /**
   * Performs an intersection test with the model's raycaster and the given objects.
   *
   * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
   * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
   * Otherwise it only checks intersection with the object.
   * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
   */
  intersectObjects(objects, recursive = true) {
    if (this.raycaster) {
      return this.raycaster.intersectObjects(objects, recursive);
    }
  }
  /**
   * Checks for intersections between the model's raycaster and the given objects. The method
   * updates the cursor object to the intersection point.
   *
   * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
   * @param {boolean} [recursive=false] - If set to `true`, it also checks all descendants.
   * Otherwise it only checks intersection with the object.
   */
  checkIntersections(objects, recursive = false) {
    if (this.raycaster && !this.attached) {
      const intersections = this.raycaster.intersectObjects(objects, recursive);
      const direction = new Vector3(0, 0, -1);
      if (intersections.length > 0) {
        const intersection = intersections[0];
        const distance = intersection.distance;
        this.cursorObject.position.copy(direction.multiplyScalar(distance));
      } else {
        this.cursorObject.position.copy(direction.multiplyScalar(CURSOR_MAX_DISTANCE));
      }
    }
  }
  /**
   * Sets the cursor to the given distance.
   *
   * @param {number} distance - The distance to set the cursor to.
   */
  setCursor(distance) {
    const direction = new Vector3(0, 0, -1);
    if (this.raycaster && !this.attached) {
      this.cursorObject.position.copy(direction.multiplyScalar(distance));
    }
  }
  /**
   * Frees the GPU-related resources allocated by this instance. Call this
   * method whenever this instance is no longer used in your app.
   */
  dispose() {
    this._onDisconnected();
    this.hand.removeEventListener("connected", this._onConnected);
    this.hand.removeEventListener("disconnected", this._onDisconnected);
  }
};

// node_modules/three/examples/jsm/webxr/Text2D.js
function createText(message, height2) {
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  let metrics = null;
  const textHeight = 100;
  context.font = "normal " + textHeight + "px Arial";
  metrics = context.measureText(message);
  const textWidth = metrics.width;
  canvas.width = textWidth;
  canvas.height = textHeight;
  context.font = "normal " + textHeight + "px Arial";
  context.textAlign = "center";
  context.textBaseline = "middle";
  context.fillStyle = "#ffffff";
  context.fillText(message, textWidth / 2, textHeight / 2);
  const texture = new Texture(canvas);
  texture.needsUpdate = true;
  const material = new MeshBasicMaterial({
    color: 16777215,
    side: DoubleSide,
    map: texture,
    transparent: true
  });
  const geometry = new PlaneGeometry(
    height2 * textWidth / textHeight,
    height2
  );
  const plane2 = new Mesh(geometry, material);
  return plane2;
}

// node_modules/three/examples/jsm/webxr/VRButton.js
var VRButton = class _VRButton {
  /**
   * Constructs a new VR button.
   *
   * @param {WebGLRenderer|WebGPURenderer} renderer - The renderer.
   * @param {XRSessionInit} [sessionInit] - The a configuration object for the AR session.
   * @return {HTMLElement} The button or an error message if `immersive-ar` isn't supported.
   */
  static createButton(renderer2, sessionInit = {}) {
    const button = document.createElement("button");
    function showEnterVR() {
      let currentSession = null;
      async function onSessionStarted(session) {
        session.addEventListener("end", onSessionEnded);
        await renderer2.xr.setSession(session);
        button.textContent = "EXIT VR";
        currentSession = session;
      }
      function onSessionEnded() {
        currentSession.removeEventListener("end", onSessionEnded);
        button.textContent = "ENTER VR";
        currentSession = null;
      }
      button.style.display = "";
      button.style.cursor = "pointer";
      button.style.left = "calc(50% - 50px)";
      button.style.width = "100px";
      button.textContent = "ENTER VR";
      const sessionOptions = {
        ...sessionInit,
        optionalFeatures: [
          "local-floor",
          "bounded-floor",
          "layers",
          ...sessionInit.optionalFeatures || []
        ]
      };
      button.onmouseenter = function() {
        button.style.opacity = "1.0";
      };
      button.onmouseleave = function() {
        button.style.opacity = "0.5";
      };
      button.onclick = function() {
        if (currentSession === null) {
          navigator.xr.requestSession("immersive-vr", sessionOptions).then(onSessionStarted);
        } else {
          currentSession.end();
          if (navigator.xr.offerSession !== void 0) {
            navigator.xr.offerSession("immersive-vr", sessionOptions).then(onSessionStarted).catch((err2) => {
              console.warn(err2);
            });
          }
        }
      };
      if (navigator.xr.offerSession !== void 0) {
        navigator.xr.offerSession("immersive-vr", sessionOptions).then(onSessionStarted).catch((err2) => {
          console.warn(err2);
        });
      }
    }
    function disableButton() {
      button.style.display = "";
      button.style.cursor = "auto";
      button.style.left = "calc(50% - 75px)";
      button.style.width = "150px";
      button.onmouseenter = null;
      button.onmouseleave = null;
      button.onclick = null;
    }
    function showWebXRNotFound() {
      disableButton();
      button.textContent = "VR NOT SUPPORTED";
    }
    function showVRNotAllowed(exception) {
      disableButton();
      console.warn("Exception when trying to call xr.isSessionSupported", exception);
      button.textContent = "VR NOT ALLOWED";
    }
    function stylizeElement(element) {
      element.style.position = "absolute";
      element.style.bottom = "20px";
      element.style.padding = "12px 6px";
      element.style.border = "1px solid #fff";
      element.style.borderRadius = "4px";
      element.style.background = "rgba(0,0,0,0.1)";
      element.style.color = "#fff";
      element.style.font = "normal 13px sans-serif";
      element.style.textAlign = "center";
      element.style.opacity = "0.5";
      element.style.outline = "none";
      element.style.zIndex = "999";
    }
    if ("xr" in navigator) {
      button.id = "VRButton";
      button.style.display = "none";
      stylizeElement(button);
      navigator.xr.isSessionSupported("immersive-vr").then(function(supported) {
        supported ? showEnterVR() : showWebXRNotFound();
        if (supported && _VRButton.xrSessionIsGranted) {
          button.click();
        }
      }).catch(showVRNotAllowed);
      return button;
    } else {
      const message = document.createElement("a");
      if (window.isSecureContext === false) {
        message.href = document.location.href.replace(/^http:/, "https:");
        message.innerHTML = "WEBXR NEEDS HTTPS";
      } else {
        message.href = "https://immersiveweb.dev/";
        message.innerHTML = "WEBXR NOT AVAILABLE";
      }
      message.style.left = "calc(50% - 90px)";
      message.style.width = "180px";
      message.style.textDecoration = "none";
      stylizeElement(message);
      return message;
    }
  }
  /**
   * Registers a `sessiongranted` event listener. When a session is granted, the {@link VRButton#xrSessionIsGranted}
   * flag will evaluate to `true`. This method is automatically called by the module itself so there
   * should be no need to use it on app level.
   */
  static registerSessionGrantedListener() {
    if (typeof navigator !== "undefined" && "xr" in navigator) {
      if (/WebXRViewer\//i.test(navigator.userAgent)) return;
      navigator.xr.addEventListener("sessiongranted", () => {
        _VRButton.xrSessionIsGranted = true;
      });
    }
  }
};
VRButton.xrSessionIsGranted = false;
VRButton.registerSessionGrantedListener();

// node_modules/three/examples/jsm/webxr/XRButton.js
var XRButton = class {
  /**
   * Constructs a new XR button.
   *
   * @param {WebGLRenderer|WebGPURenderer} renderer - The renderer.
   * @param {XRSessionInit} [sessionInit] - The a configuration object for the AR session.
   * @return {HTMLElement} The button or an error message if WebXR isn't supported.
   */
  static createButton(renderer2, sessionInit = {}) {
    const button = document.createElement("button");
    function showStartXR(mode) {
      let currentSession = null;
      async function onSessionStarted(session) {
        session.addEventListener("end", onSessionEnded);
        await renderer2.xr.setSession(session);
        button.textContent = "STOP XR";
        currentSession = session;
      }
      function onSessionEnded() {
        currentSession.removeEventListener("end", onSessionEnded);
        button.textContent = "START XR";
        currentSession = null;
      }
      button.style.display = "";
      button.style.cursor = "pointer";
      button.style.left = "calc(50% - 50px)";
      button.style.width = "100px";
      button.textContent = "START XR";
      const sessionOptions = {
        ...sessionInit,
        optionalFeatures: [
          "local-floor",
          "bounded-floor",
          "layers",
          ...sessionInit.optionalFeatures || []
        ]
      };
      button.onmouseenter = function() {
        button.style.opacity = "1.0";
      };
      button.onmouseleave = function() {
        button.style.opacity = "0.5";
      };
      button.onclick = function() {
        if (currentSession === null) {
          navigator.xr.requestSession(mode, sessionOptions).then(onSessionStarted);
        } else {
          currentSession.end();
          if (navigator.xr.offerSession !== void 0) {
            navigator.xr.offerSession(mode, sessionOptions).then(onSessionStarted).catch((err2) => {
              console.warn(err2);
            });
          }
        }
      };
      if (navigator.xr.offerSession !== void 0) {
        navigator.xr.offerSession(mode, sessionOptions).then(onSessionStarted).catch((err2) => {
          console.warn(err2);
        });
      }
    }
    function disableButton() {
      button.style.display = "";
      button.style.cursor = "auto";
      button.style.left = "calc(50% - 75px)";
      button.style.width = "150px";
      button.onmouseenter = null;
      button.onmouseleave = null;
      button.onclick = null;
    }
    function showXRNotSupported() {
      disableButton();
      button.textContent = "XR NOT SUPPORTED";
    }
    function showXRNotAllowed(exception) {
      disableButton();
      console.warn("Exception when trying to call xr.isSessionSupported", exception);
      button.textContent = "XR NOT ALLOWED";
    }
    function stylizeElement(element) {
      element.style.position = "absolute";
      element.style.bottom = "20px";
      element.style.padding = "12px 6px";
      element.style.border = "1px solid #fff";
      element.style.borderRadius = "4px";
      element.style.background = "rgba(0,0,0,0.1)";
      element.style.color = "#fff";
      element.style.font = "normal 13px sans-serif";
      element.style.textAlign = "center";
      element.style.opacity = "0.5";
      element.style.outline = "none";
      element.style.zIndex = "999";
    }
    if ("xr" in navigator) {
      button.id = "XRButton";
      button.style.display = "none";
      stylizeElement(button);
      navigator.xr.isSessionSupported("immersive-ar").then(function(supported) {
        if (supported) {
          showStartXR("immersive-ar");
        } else {
          navigator.xr.isSessionSupported("immersive-vr").then(function(supported2) {
            if (supported2) {
              showStartXR("immersive-vr");
            } else {
              showXRNotSupported();
            }
          }).catch(showXRNotAllowed);
        }
      }).catch(showXRNotAllowed);
      return button;
    } else {
      const message = document.createElement("a");
      if (window.isSecureContext === false) {
        message.href = document.location.href.replace(/^http:/, "https:");
        message.innerHTML = "WEBXR NEEDS HTTPS";
      } else {
        message.href = "https://immersiveweb.dev/";
        message.innerHTML = "WEBXR NOT AVAILABLE";
      }
      message.style.left = "calc(50% - 90px)";
      message.style.width = "180px";
      message.style.textDecoration = "none";
      stylizeElement(message);
      return message;
    }
  }
};

// node_modules/three/examples/jsm/libs/motion-controllers.module.js
var Constants = {
  Handedness: Object.freeze({
    NONE: "none",
    LEFT: "left",
    RIGHT: "right"
  }),
  ComponentState: Object.freeze({
    DEFAULT: "default",
    TOUCHED: "touched",
    PRESSED: "pressed"
  }),
  ComponentProperty: Object.freeze({
    BUTTON: "button",
    X_AXIS: "xAxis",
    Y_AXIS: "yAxis",
    STATE: "state"
  }),
  ComponentType: Object.freeze({
    TRIGGER: "trigger",
    SQUEEZE: "squeeze",
    TOUCHPAD: "touchpad",
    THUMBSTICK: "thumbstick",
    BUTTON: "button"
  }),
  ButtonTouchThreshold: 0.05,
  AxisTouchThreshold: 0.1,
  VisualResponseProperty: Object.freeze({
    TRANSFORM: "transform",
    VISIBILITY: "visibility"
  })
};
async function fetchJsonFile(path) {
  const response = await fetch(path);
  if (!response.ok) {
    throw new Error(response.statusText);
  } else {
    return response.json();
  }
}
async function fetchProfilesList(basePath) {
  if (!basePath) {
    throw new Error("No basePath supplied");
  }
  const profileListFileName = "profilesList.json";
  const profilesList = await fetchJsonFile(`${basePath}/${profileListFileName}`);
  return profilesList;
}
async function fetchProfile(xrInputSource, basePath, defaultProfile = null, getAssetPath = true) {
  if (!xrInputSource) {
    throw new Error("No xrInputSource supplied");
  }
  if (!basePath) {
    throw new Error("No basePath supplied");
  }
  const supportedProfilesList = await fetchProfilesList(basePath);
  let match;
  xrInputSource.profiles.some((profileId) => {
    const supportedProfile = supportedProfilesList[profileId];
    if (supportedProfile) {
      match = {
        profileId,
        profilePath: `${basePath}/${supportedProfile.path}`,
        deprecated: !!supportedProfile.deprecated
      };
    }
    return !!match;
  });
  if (!match) {
    if (!defaultProfile) {
      throw new Error("No matching profile name found");
    }
    const supportedProfile = supportedProfilesList[defaultProfile];
    if (!supportedProfile) {
      throw new Error(`No matching profile name found and default profile "${defaultProfile}" missing.`);
    }
    match = {
      profileId: defaultProfile,
      profilePath: `${basePath}/${supportedProfile.path}`,
      deprecated: !!supportedProfile.deprecated
    };
  }
  const profile = await fetchJsonFile(match.profilePath);
  let assetPath;
  if (getAssetPath) {
    let layout;
    if (xrInputSource.handedness === "any") {
      layout = profile.layouts[Object.keys(profile.layouts)[0]];
    } else {
      layout = profile.layouts[xrInputSource.handedness];
    }
    if (!layout) {
      throw new Error(
        `No matching handedness, ${xrInputSource.handedness}, in profile ${match.profileId}`
      );
    }
    if (layout.assetPath) {
      assetPath = match.profilePath.replace("profile.json", layout.assetPath);
    }
  }
  return { profile, assetPath };
}
var defaultComponentValues = {
  xAxis: 0,
  yAxis: 0,
  button: 0,
  state: Constants.ComponentState.DEFAULT
};
function normalizeAxes(x2 = 0, y = 0) {
  let xAxis2 = x2;
  let yAxis2 = y;
  const hypotenuse = Math.sqrt(x2 * x2 + y * y);
  if (hypotenuse > 1) {
    const theta = Math.atan2(y, x2);
    xAxis2 = Math.cos(theta);
    yAxis2 = Math.sin(theta);
  }
  const result = {
    normalizedXAxis: xAxis2 * 0.5 + 0.5,
    normalizedYAxis: yAxis2 * 0.5 + 0.5
  };
  return result;
}
var VisualResponse = class {
  constructor(visualResponseDescription) {
    this.componentProperty = visualResponseDescription.componentProperty;
    this.states = visualResponseDescription.states;
    this.valueNodeName = visualResponseDescription.valueNodeName;
    this.valueNodeProperty = visualResponseDescription.valueNodeProperty;
    if (this.valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM) {
      this.minNodeName = visualResponseDescription.minNodeName;
      this.maxNodeName = visualResponseDescription.maxNodeName;
    }
    this.value = 0;
    this.updateFromComponent(defaultComponentValues);
  }
  /**
   * Computes the visual response's interpolation weight based on component state
   * @param {Object} componentValues - The component from which to update
   * @param {number} xAxis - The reported X axis value of the component
   * @param {number} yAxis - The reported Y axis value of the component
   * @param {number} button - The reported value of the component's button
   * @param {string} state - The component's active state
   */
  updateFromComponent({
    xAxis: xAxis2,
    yAxis: yAxis2,
    button,
    state
  }) {
    const { normalizedXAxis, normalizedYAxis } = normalizeAxes(xAxis2, yAxis2);
    switch (this.componentProperty) {
      case Constants.ComponentProperty.X_AXIS:
        this.value = this.states.includes(state) ? normalizedXAxis : 0.5;
        break;
      case Constants.ComponentProperty.Y_AXIS:
        this.value = this.states.includes(state) ? normalizedYAxis : 0.5;
        break;
      case Constants.ComponentProperty.BUTTON:
        this.value = this.states.includes(state) ? button : 0;
        break;
      case Constants.ComponentProperty.STATE:
        if (this.valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY) {
          this.value = this.states.includes(state);
        } else {
          this.value = this.states.includes(state) ? 1 : 0;
        }
        break;
      default:
        throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`);
    }
  }
};
var Component = class {
  /**
   * @param {Object} componentId - Id of the component
   * @param {Object} componentDescription - Description of the component to be created
   */
  constructor(componentId, componentDescription) {
    if (!componentId || !componentDescription || !componentDescription.visualResponses || !componentDescription.gamepadIndices || Object.keys(componentDescription.gamepadIndices).length === 0) {
      throw new Error("Invalid arguments supplied");
    }
    this.id = componentId;
    this.type = componentDescription.type;
    this.rootNodeName = componentDescription.rootNodeName;
    this.touchPointNodeName = componentDescription.touchPointNodeName;
    this.visualResponses = {};
    Object.keys(componentDescription.visualResponses).forEach((responseName) => {
      const visualResponse = new VisualResponse(componentDescription.visualResponses[responseName]);
      this.visualResponses[responseName] = visualResponse;
    });
    this.gamepadIndices = Object.assign({}, componentDescription.gamepadIndices);
    this.values = {
      state: Constants.ComponentState.DEFAULT,
      button: this.gamepadIndices.button !== void 0 ? 0 : void 0,
      xAxis: this.gamepadIndices.xAxis !== void 0 ? 0 : void 0,
      yAxis: this.gamepadIndices.yAxis !== void 0 ? 0 : void 0
    };
  }
  get data() {
    const data2 = { id: this.id, ...this.values };
    return data2;
  }
  /**
   * @description Poll for updated data based on current gamepad state
   * @param {Object} gamepad - The gamepad object from which the component data should be polled
   */
  updateFromGamepad(gamepad) {
    this.values.state = Constants.ComponentState.DEFAULT;
    if (this.gamepadIndices.button !== void 0 && gamepad.buttons.length > this.gamepadIndices.button) {
      const gamepadButton = gamepad.buttons[this.gamepadIndices.button];
      this.values.button = gamepadButton.value;
      this.values.button = this.values.button < 0 ? 0 : this.values.button;
      this.values.button = this.values.button > 1 ? 1 : this.values.button;
      if (gamepadButton.pressed || this.values.button === 1) {
        this.values.state = Constants.ComponentState.PRESSED;
      } else if (gamepadButton.touched || this.values.button > Constants.ButtonTouchThreshold) {
        this.values.state = Constants.ComponentState.TOUCHED;
      }
    }
    if (this.gamepadIndices.xAxis !== void 0 && gamepad.axes.length > this.gamepadIndices.xAxis) {
      this.values.xAxis = gamepad.axes[this.gamepadIndices.xAxis];
      this.values.xAxis = this.values.xAxis < -1 ? -1 : this.values.xAxis;
      this.values.xAxis = this.values.xAxis > 1 ? 1 : this.values.xAxis;
      if (this.values.state === Constants.ComponentState.DEFAULT && Math.abs(this.values.xAxis) > Constants.AxisTouchThreshold) {
        this.values.state = Constants.ComponentState.TOUCHED;
      }
    }
    if (this.gamepadIndices.yAxis !== void 0 && gamepad.axes.length > this.gamepadIndices.yAxis) {
      this.values.yAxis = gamepad.axes[this.gamepadIndices.yAxis];
      this.values.yAxis = this.values.yAxis < -1 ? -1 : this.values.yAxis;
      this.values.yAxis = this.values.yAxis > 1 ? 1 : this.values.yAxis;
      if (this.values.state === Constants.ComponentState.DEFAULT && Math.abs(this.values.yAxis) > Constants.AxisTouchThreshold) {
        this.values.state = Constants.ComponentState.TOUCHED;
      }
    }
    Object.values(this.visualResponses).forEach((visualResponse) => {
      visualResponse.updateFromComponent(this.values);
    });
  }
};
var MotionController = class {
  /**
   * @param {Object} xrInputSource - The XRInputSource to build the MotionController around
   * @param {Object} profile - The best matched profile description for the supplied xrInputSource
   * @param {string} assetUrl
   */
  constructor(xrInputSource, profile, assetUrl) {
    if (!xrInputSource) {
      throw new Error("No xrInputSource supplied");
    }
    if (!profile) {
      throw new Error("No profile supplied");
    }
    this.xrInputSource = xrInputSource;
    this.assetUrl = assetUrl;
    this.id = profile.profileId;
    this.layoutDescription = profile.layouts[xrInputSource.handedness];
    this.components = {};
    Object.keys(this.layoutDescription.components).forEach((componentId) => {
      const componentDescription = this.layoutDescription.components[componentId];
      this.components[componentId] = new Component(componentId, componentDescription);
    });
    this.updateFromGamepad();
  }
  get gripSpace() {
    return this.xrInputSource.gripSpace;
  }
  get targetRaySpace() {
    return this.xrInputSource.targetRaySpace;
  }
  /**
   * @description Returns a subset of component data for simplified debugging
   */
  get data() {
    const data2 = [];
    Object.values(this.components).forEach((component) => {
      data2.push(component.data);
    });
    return data2;
  }
  /**
   * @description Poll for updated data based on current gamepad state
   */
  updateFromGamepad() {
    Object.values(this.components).forEach((component) => {
      component.updateFromGamepad(this.xrInputSource.gamepad);
    });
  }
};

// node_modules/three/examples/jsm/webxr/XRControllerModelFactory.js
var DEFAULT_PROFILES_PATH = "https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles";
var DEFAULT_PROFILE = "generic-trigger";
var XRControllerModel = class extends Object3D {
  /**
   * Constructs a new XR controller model.
   */
  constructor() {
    super();
    this.motionController = null;
    this.envMap = null;
  }
  /**
   * Sets an environment map that is applied to the controller model.
   *
   * @param {?Texture} envMap - The environment map to apply.
   * @return {XRControllerModel} A reference to this instance.
   */
  setEnvironmentMap(envMap) {
    if (this.envMap == envMap) {
      return this;
    }
    this.envMap = envMap;
    this.traverse((child) => {
      if (child.isMesh) {
        child.material.envMap = this.envMap;
        child.material.needsUpdate = true;
      }
    });
    return this;
  }
  /**
   * Overwritten with a custom implementation. Polls data from the XRInputSource and updates the
   * model's components to match the real world data.
   *
   * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
   * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
   */
  updateMatrixWorld(force) {
    super.updateMatrixWorld(force);
    if (!this.motionController) return;
    this.motionController.updateFromGamepad();
    Object.values(this.motionController.components).forEach((component) => {
      Object.values(component.visualResponses).forEach((visualResponse) => {
        const { valueNode, minNode, maxNode, value: value2, valueNodeProperty } = visualResponse;
        if (!valueNode) return;
        if (valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY) {
          valueNode.visible = value2;
        } else if (valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM) {
          valueNode.quaternion.slerpQuaternions(
            minNode.quaternion,
            maxNode.quaternion,
            value2
          );
          valueNode.position.lerpVectors(
            minNode.position,
            maxNode.position,
            value2
          );
        }
      });
    });
  }
};
function findNodes(motionController, scene) {
  Object.values(motionController.components).forEach((component) => {
    const { type, touchPointNodeName, visualResponses } = component;
    if (type === Constants.ComponentType.TOUCHPAD) {
      component.touchPointNode = scene.getObjectByName(touchPointNodeName);
      if (component.touchPointNode) {
        const sphereGeometry = new SphereGeometry(1e-3);
        const material = new MeshBasicMaterial({ color: 255 });
        const sphere = new Mesh(sphereGeometry, material);
        component.touchPointNode.add(sphere);
      } else {
        console.warn(`Could not find touch dot, ${component.touchPointNodeName}, in touchpad component ${component.id}`);
      }
    }
    Object.values(visualResponses).forEach((visualResponse) => {
      const { valueNodeName, minNodeName, maxNodeName, valueNodeProperty } = visualResponse;
      if (valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM) {
        visualResponse.minNode = scene.getObjectByName(minNodeName);
        visualResponse.maxNode = scene.getObjectByName(maxNodeName);
        if (!visualResponse.minNode) {
          console.warn(`Could not find ${minNodeName} in the model`);
          return;
        }
        if (!visualResponse.maxNode) {
          console.warn(`Could not find ${maxNodeName} in the model`);
          return;
        }
      }
      visualResponse.valueNode = scene.getObjectByName(valueNodeName);
      if (!visualResponse.valueNode) {
        console.warn(`Could not find ${valueNodeName} in the model`);
      }
    });
  });
}
function addAssetSceneToControllerModel(controllerModel, scene) {
  findNodes(controllerModel.motionController, scene);
  if (controllerModel.envMap) {
    scene.traverse((child) => {
      if (child.isMesh) {
        child.material.envMap = controllerModel.envMap;
        child.material.needsUpdate = true;
      }
    });
  }
  controllerModel.add(scene);
}
var XRControllerModelFactory = class {
  /**
   * Constructs a new XR controller model factory.
   *
   * @param {?GLTFLoader} [gltfLoader=null] - A glTF loader that is used to load controller models.
   * @param {?Function} [onLoad=null] - A callback that is executed when a controller model has been loaded.
   */
  constructor(gltfLoader = null, onLoad = null) {
    this.gltfLoader = gltfLoader;
    this.path = DEFAULT_PROFILES_PATH;
    this._assetCache = {};
    this.onLoad = onLoad;
    if (!this.gltfLoader) {
      this.gltfLoader = new GLTFLoader();
    }
  }
  /**
   * Sets the path to the model repository.
   *
   * @param {string} path - The path to set.
   * @return {XRControllerModelFactory} A reference to this instance.
   */
  setPath(path) {
    this.path = path;
    return this;
  }
  /**
   * Creates a controller model for the given WebXR controller.
   *
   * @param {Group} controller - The controller.
   * @return {XRControllerModel} The XR controller model.
   */
  createControllerModel(controller) {
    const controllerModel = new XRControllerModel();
    let scene = null;
    controller.addEventListener("connected", (event) => {
      const xrInputSource = event.data;
      if (xrInputSource.targetRayMode !== "tracked-pointer" || !xrInputSource.gamepad || xrInputSource.hand) return;
      fetchProfile(xrInputSource, this.path, DEFAULT_PROFILE).then(({ profile, assetPath }) => {
        controllerModel.motionController = new MotionController(
          xrInputSource,
          profile,
          assetPath
        );
        const cachedAsset = this._assetCache[controllerModel.motionController.assetUrl];
        if (cachedAsset) {
          scene = cachedAsset.scene.clone();
          addAssetSceneToControllerModel(controllerModel, scene);
          if (this.onLoad) this.onLoad(scene);
        } else {
          if (!this.gltfLoader) {
            throw new Error("GLTFLoader not set.");
          }
          this.gltfLoader.setPath("");
          this.gltfLoader.load(
            controllerModel.motionController.assetUrl,
            (asset) => {
              this._assetCache[controllerModel.motionController.assetUrl] = asset;
              scene = asset.scene.clone();
              addAssetSceneToControllerModel(controllerModel, scene);
              if (this.onLoad) this.onLoad(scene);
            },
            null,
            () => {
              throw new Error(`Asset ${controllerModel.motionController.assetUrl} missing or malformed.`);
            }
          );
        }
      }).catch((err2) => {
        console.warn(err2);
      });
    });
    controller.addEventListener("disconnected", () => {
      controllerModel.motionController = null;
      controllerModel.remove(scene);
      scene = null;
    });
    return controllerModel;
  }
};

// node_modules/three/examples/jsm/webxr/XREstimatedLight.js
var SessionLightProbe = class {
  constructor(xrLight, renderer2, lightProbe, environmentEstimation, estimationStartCallback) {
    this.xrLight = xrLight;
    this.renderer = renderer2;
    this.lightProbe = lightProbe;
    this.xrWebGLBinding = null;
    this.estimationStartCallback = estimationStartCallback;
    this.frameCallback = this.onXRFrame.bind(this);
    const session = renderer2.xr.getSession();
    if (environmentEstimation && "XRWebGLBinding" in window) {
      const cubeRenderTarget = new WebGLCubeRenderTarget(16);
      xrLight.environment = cubeRenderTarget.texture;
      const gl = renderer2.getContext();
      switch (session.preferredReflectionFormat) {
        case "srgba8":
          gl.getExtension("EXT_sRGB");
          break;
        case "rgba16f":
          gl.getExtension("OES_texture_half_float");
          break;
      }
      this.xrWebGLBinding = new XRWebGLBinding(session, gl);
      this.lightProbe.addEventListener("reflectionchange", () => {
        this.updateReflection();
      });
    }
    session.requestAnimationFrame(this.frameCallback);
  }
  updateReflection() {
    const textureProperties = this.renderer.properties.get(this.xrLight.environment);
    if (textureProperties) {
      const cubeMap = this.xrWebGLBinding.getReflectionCubeMap(this.lightProbe);
      if (cubeMap) {
        textureProperties.__webglTexture = cubeMap;
        this.xrLight.environment.needsPMREMUpdate = true;
      }
    }
  }
  onXRFrame(time2, xrFrame) {
    if (!this.xrLight) {
      return;
    }
    const session = xrFrame.session;
    session.requestAnimationFrame(this.frameCallback);
    const lightEstimate = xrFrame.getLightEstimate(this.lightProbe);
    if (lightEstimate) {
      this.xrLight.lightProbe.sh.fromArray(lightEstimate.sphericalHarmonicsCoefficients);
      this.xrLight.lightProbe.intensity = 1;
      const intensityScalar = Math.max(
        1,
        Math.max(
          lightEstimate.primaryLightIntensity.x,
          Math.max(
            lightEstimate.primaryLightIntensity.y,
            lightEstimate.primaryLightIntensity.z
          )
        )
      );
      this.xrLight.directionalLight.color.setRGB(
        lightEstimate.primaryLightIntensity.x / intensityScalar,
        lightEstimate.primaryLightIntensity.y / intensityScalar,
        lightEstimate.primaryLightIntensity.z / intensityScalar
      );
      this.xrLight.directionalLight.intensity = intensityScalar;
      this.xrLight.directionalLight.position.copy(lightEstimate.primaryLightDirection);
      if (this.estimationStartCallback) {
        this.estimationStartCallback();
        this.estimationStartCallback = null;
      }
    }
  }
  dispose() {
    this.xrLight = null;
    this.renderer = null;
    this.lightProbe = null;
    this.xrWebGLBinding = null;
  }
};
var XREstimatedLight = class extends Group {
  /**
   * Constructs a new light.
   *
   * @param {WebGLRenderer} renderer - The renderer.
   * @param {boolean} [environmentEstimation=true] - Whether to use environment estimation or not.
   */
  constructor(renderer2, environmentEstimation = true) {
    super();
    this.lightProbe = new LightProbe();
    this.lightProbe.intensity = 0;
    this.add(this.lightProbe);
    this.directionalLight = new DirectionalLight();
    this.directionalLight.intensity = 0;
    this.add(this.directionalLight);
    this.environment = null;
    let sessionLightProbe = null;
    let estimationStarted = false;
    renderer2.xr.addEventListener("sessionstart", () => {
      const session = renderer2.xr.getSession();
      if ("requestLightProbe" in session) {
        session.requestLightProbe({
          reflectionFormat: session.preferredReflectionFormat
        }).then((probe) => {
          sessionLightProbe = new SessionLightProbe(this, renderer2, probe, environmentEstimation, () => {
            estimationStarted = true;
            this.dispatchEvent({ type: "estimationstart" });
          });
        });
      }
    });
    renderer2.xr.addEventListener("sessionend", () => {
      if (sessionLightProbe) {
        sessionLightProbe.dispose();
        sessionLightProbe = null;
      }
      if (estimationStarted) {
        this.dispatchEvent({ type: "estimationend" });
      }
    });
    this.dispose = () => {
      if (sessionLightProbe) {
        sessionLightProbe.dispose();
        sessionLightProbe = null;
      }
      this.remove(this.lightProbe);
      this.lightProbe = null;
      this.remove(this.directionalLight);
      this.directionalLight = null;
      this.environment = null;
    };
  }
};

// node_modules/three/examples/jsm/webxr/XRHandPrimitiveModel.js
var _matrix6 = new Matrix4();
var _vector5 = new Vector3();
var XRHandPrimitiveModel = class {
  /**
   * Constructs a new XR hand primitive model.
   *
   * @param {XRHandModel} handModel - The hand model.
   * @param {Group} controller - The WebXR controller.
   * @param {string} path - The model path.
   * @param {XRHandedness} handedness - The handedness of the XR input source.
   * @param {XRHandPrimitiveModel~Options} options - The model options.
   */
  constructor(handModel, controller, path, handedness, options) {
    this.controller = controller;
    this.handModel = handModel;
    this.envMap = null;
    let geometry;
    if (!options || !options.primitive || options.primitive === "sphere") {
      geometry = new SphereGeometry(1, 10, 10);
    } else if (options.primitive === "box") {
      geometry = new BoxGeometry(1, 1, 1);
    }
    const material = new MeshStandardMaterial();
    this.handMesh = new InstancedMesh(geometry, material, 30);
    this.handMesh.frustumCulled = false;
    this.handMesh.instanceMatrix.setUsage(DynamicDrawUsage);
    this.handMesh.castShadow = true;
    this.handMesh.receiveShadow = true;
    this.handModel.add(this.handMesh);
    this.joints = [
      "wrist",
      "thumb-metacarpal",
      "thumb-phalanx-proximal",
      "thumb-phalanx-distal",
      "thumb-tip",
      "index-finger-metacarpal",
      "index-finger-phalanx-proximal",
      "index-finger-phalanx-intermediate",
      "index-finger-phalanx-distal",
      "index-finger-tip",
      "middle-finger-metacarpal",
      "middle-finger-phalanx-proximal",
      "middle-finger-phalanx-intermediate",
      "middle-finger-phalanx-distal",
      "middle-finger-tip",
      "ring-finger-metacarpal",
      "ring-finger-phalanx-proximal",
      "ring-finger-phalanx-intermediate",
      "ring-finger-phalanx-distal",
      "ring-finger-tip",
      "pinky-finger-metacarpal",
      "pinky-finger-phalanx-proximal",
      "pinky-finger-phalanx-intermediate",
      "pinky-finger-phalanx-distal",
      "pinky-finger-tip"
    ];
  }
  /**
   * Updates the mesh based on the tracked XR joints data.
   */
  updateMesh() {
    const defaultRadius = 8e-3;
    const joints = this.controller.joints;
    let count = 0;
    for (let i = 0; i < this.joints.length; i++) {
      const joint = joints[this.joints[i]];
      if (joint.visible) {
        _vector5.setScalar(joint.jointRadius || defaultRadius);
        _matrix6.compose(joint.position, joint.quaternion, _vector5);
        this.handMesh.setMatrixAt(i, _matrix6);
        count++;
      }
    }
    this.handMesh.count = count;
    this.handMesh.instanceMatrix.needsUpdate = true;
  }
};

// node_modules/three/examples/jsm/webxr/XRHandModelFactory.js
var XRHandModel = class extends Object3D {
  /**
   * Constructs a new XR hand model.
   *
   * @param {Group} controller - The hand controller.
   */
  constructor(controller) {
    super();
    this.controller = controller;
    this.motionController = null;
    this.envMap = null;
    this.mesh = null;
  }
  /**
   * Overwritten with a custom implementation. Makes sure the motion controller updates the mesh.
   *
   * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
   * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
   */
  updateMatrixWorld(force) {
    super.updateMatrixWorld(force);
    if (this.motionController) {
      this.motionController.updateMesh();
    }
  }
};
var XRHandModelFactory = class {
  /**
   * Constructs a new XR hand model factory.
   *
   * @param {?GLTFLoader} [gltfLoader=null] - A glTF loader that is used to load hand models.
   * @param {?Function} [onLoad=null] - A callback that is executed when a hand model has been loaded.
   */
  constructor(gltfLoader = null, onLoad = null) {
    this.gltfLoader = gltfLoader;
    this.path = null;
    this.onLoad = onLoad;
  }
  /**
   * Sets the path to the hand model repository.
   *
   * @param {string} path - The path to set.
   * @return {XRHandModelFactory} A reference to this instance.
   */
  setPath(path) {
    this.path = path;
    return this;
  }
  /**
   * Creates a controller model for the given WebXR hand controller.
   *
   * @param {Group} controller - The hand controller.
   * @param {('spheres'|'boxes'|'mesh')} [profile] - The model profile that defines the model type.
   * @return {XRHandModel} The XR hand model.
   */
  createHandModel(controller, profile) {
    const handModel = new XRHandModel(controller);
    controller.addEventListener("connected", (event) => {
      const xrInputSource = event.data;
      if (xrInputSource.hand && !handModel.motionController) {
        handModel.xrInputSource = xrInputSource;
        if (profile === void 0 || profile === "spheres") {
          handModel.motionController = new XRHandPrimitiveModel(handModel, controller, this.path, xrInputSource.handedness, { primitive: "sphere" });
        } else if (profile === "boxes") {
          handModel.motionController = new XRHandPrimitiveModel(handModel, controller, this.path, xrInputSource.handedness, { primitive: "box" });
        } else if (profile === "mesh") {
          handModel.motionController = new XRHandMeshModel(handModel, controller, this.path, xrInputSource.handedness, this.gltfLoader, this.onLoad);
        }
      }
      controller.visible = true;
    });
    controller.addEventListener("disconnected", () => {
      controller.visible = false;
    });
    return handModel;
  }
};

// node_modules/three/examples/jsm/webxr/XRPlanes.js
var XRPlanes = class extends Object3D {
  /**
   * Constructs a new XR plane container.
   *
   * @param {WebGLRenderer|WebGPURenderer} renderer - The renderer.
   */
  constructor(renderer2) {
    super();
    const matrix2 = new Matrix4();
    const currentPlanes = /* @__PURE__ */ new Map();
    const xr = renderer2.xr;
    xr.addEventListener("planesdetected", (event) => {
      const frame = event.data;
      const planes = frame.detectedPlanes;
      const referenceSpace = xr.getReferenceSpace();
      let planeschanged = false;
      for (const [plane2, mesh] of currentPlanes) {
        if (planes.has(plane2) === false) {
          mesh.geometry.dispose();
          mesh.material.dispose();
          this.remove(mesh);
          currentPlanes.delete(plane2);
          planeschanged = true;
        }
      }
      for (const plane2 of planes) {
        if (currentPlanes.has(plane2) === false) {
          const pose = frame.getPose(plane2.planeSpace, referenceSpace);
          matrix2.fromArray(pose.transform.matrix);
          const polygon = plane2.polygon;
          let minX = Number.MAX_SAFE_INTEGER;
          let maxX = Number.MIN_SAFE_INTEGER;
          let minZ = Number.MAX_SAFE_INTEGER;
          let maxZ = Number.MIN_SAFE_INTEGER;
          for (const point of polygon) {
            minX = Math.min(minX, point.x);
            maxX = Math.max(maxX, point.x);
            minZ = Math.min(minZ, point.z);
            maxZ = Math.max(maxZ, point.z);
          }
          const width2 = maxX - minX;
          const height2 = maxZ - minZ;
          const geometry = new BoxGeometry(width2, 0.01, height2);
          const material = new MeshBasicMaterial({ color: 16777215 * Math.random() });
          const mesh = new Mesh(geometry, material);
          mesh.position.setFromMatrixPosition(matrix2);
          mesh.quaternion.setFromRotationMatrix(matrix2);
          this.add(mesh);
          currentPlanes.set(plane2, mesh);
          planeschanged = true;
        }
      }
      if (planeschanged) {
        this.dispatchEvent({ type: "planeschanged" });
      }
    });
  }
};
export {
  ACESFilmicToneMappingShader,
  AMFLoader,
  ARButton,
  AfterimagePass,
  AfterimageShader,
  AmmoPhysics,
  AnaglyphEffect,
  AnimationClipCreator,
  ArcballControls,
  AsciiEffect,
  BVHLoader,
  BasicShader,
  BleachBypassShader,
  BlendShader,
  BloomPass,
  BlurShaderUtils,
  BokehPass,
  BokehShader,
  BokehShader2,
  BoxLineGeometry,
  BrightnessContrastShader,
  BufferGeometryUtils_exports as BufferGeometryUtils,
  CCDIKHelper,
  CCDIKSolver,
  CSM,
  CSMFrustum,
  CSMHelper,
  CSMShader,
  CSS2DObject,
  CSS2DRenderer,
  CSS3DObject,
  CSS3DRenderer,
  CSS3DSprite,
  CameraUtils_exports as CameraUtils,
  Capsule,
  ClearMaskPass,
  ClearPass,
  ColladaLoader,
  ColorConverter,
  ColorCorrectionShader,
  ColorMapKeywords,
  ColorifyShader,
  ConvexGeometry,
  ConvexHull,
  ConvexObjectBreaker,
  ConvolutionShader,
  CopyShader,
  CubeTexturePass,
  CurveExtras_exports as Curves,
  DDSLoader,
  DOFMipMapShader,
  DRACOExporter,
  DRACOLoader,
  DebugEnvironment,
  DecalGeometry,
  DecalVertex,
  DepthLimitedBlurShader,
  DigitalGlitch,
  DotScreenPass,
  DotScreenShader,
  DragControls,
  EXRExporter,
  EXRLoader,
  EdgeSplitModifier,
  EffectComposer,
  ExposureShader,
  FBXLoader,
  FXAAShader,
  Face,
  FilmPass,
  FilmShader,
  FirstPersonControls,
  FixedTimer,
  FlakesTexture,
  Flow,
  FlyControls,
  FocusShader,
  Font,
  FontLoader,
  FreiChenShader,
  FullScreenQuad,
  GCodeLoader,
  GLTFExporter,
  GLTFLoader,
  GPUComputationRenderer,
  GTAOBlendShader,
  GTAODepthShader,
  GTAOPass,
  GTAOShader,
  GammaCorrectionShader,
  GeometryCompressionUtils_exports as GeometryCompressionUtils,
  GeometryUtils_exports as GeometryUtils,
  GlitchPass,
  GodRaysCombineShader,
  GodRaysDepthMaskShader,
  GodRaysFakeSunShader,
  GodRaysGenerateShader,
  GroundedSkybox,
  Gyroscope,
  HDRCubeTextureLoader,
  HTMLMesh,
  HalfEdge,
  HalftonePass,
  HalftoneShader,
  HorizontalBlurShader,
  HorizontalTiltShiftShader,
  HueSaturationShader,
  IESLoader,
  ImprovedNoise,
  InstancedFlow,
  InteractiveGroup,
  KMZLoader,
  KTX2Exporter,
  KTX2Loader,
  KTXLoader,
  KaleidoShader,
  LDrawConditionalLineMaterial,
  LDrawLoader,
  LDrawUtils,
  LUT3dlLoader,
  LUTCubeLoader,
  LUTPass,
  LWOLoader,
  Lensflare,
  LensflareElement,
  LightProbeGenerator,
  LightProbeHelper,
  Line2,
  LineGeometry,
  LineMaterial,
  LineSegments2,
  LineSegmentsGeometry,
  LottieLoader,
  LuminosityHighPassShader,
  LuminosityShader,
  Lut,
  MD2Character,
  MD2CharacterComplex,
  MD2Loader,
  MDDLoader,
  MTLLoader,
  MapControls,
  MarchingCubes,
  MaskPass,
  MeshGouraudMaterial,
  MeshPostProcessingMaterial,
  MeshSurfaceSampler,
  MirrorShader,
  MorphAnimMesh,
  MorphBlendMesh,
  NO_COMPRESSION,
  NRRDLoader,
  NURBSCurve,
  NURBSSurface,
  NURBSUtils_exports as NURBSUtils,
  NURBSVolume,
  NormalMapShader,
  OBB,
  OBJExporter,
  OBJLoader,
  Octree,
  OctreeHelper,
  OculusHandModel,
  OculusHandPointerModel,
  OrbitControls,
  OutlineEffect,
  OutlinePass,
  OutputPass,
  OutputShader,
  PCDLoader,
  PDBLoader,
  PLYExporter,
  PLYLoader,
  PVRLoader,
  ParallaxBarrierEffect,
  ParametricGeometry,
  Pass,
  PointerLockControls,
  PositionalAudioHelper,
  ProgressiveLightMap,
  Projector,
  RGBELoader,
  RGBMLoader,
  RGBShiftShader,
  RapierPhysics,
  RectAreaLightHelper,
  RectAreaLightTexturesLib,
  RectAreaLightUniformsLib,
  Reflector,
  ReflectorForSSRPass,
  Refractor,
  RenderPass,
  RenderPixelatedPass,
  RenderableFace,
  RenderableLine,
  RenderableObject,
  RenderableSprite,
  RenderableVertex,
  Rhino3dmLoader,
  RollerCoasterGeometry,
  RollerCoasterLiftersGeometry,
  RollerCoasterShadowGeometry,
  RoomEnvironment,
  RoundedBoxGeometry,
  SAOPass,
  SAOShader,
  SMAABlendShader,
  SMAAEdgesShader,
  SMAAPass,
  SMAAWeightsShader,
  SSAARenderPass,
  SSAOBlurShader,
  SSAODepthShader,
  SSAOPass,
  SSAOShader,
  SSRBlurShader,
  SSRDepthShader,
  SSRPass,
  SSRShader,
  STLExporter,
  STLLoader,
  SVGLoader,
  SVGObject,
  SVGRenderer2 as SVGRenderer,
  SavePass,
  SceneUtils_exports as SceneUtils,
  SelectionBox,
  SelectionHelper,
  SepiaShader,
  ShaderPass,
  ShadowMapViewer,
  ShadowMesh,
  SimplexNoise,
  SimplifyModifier,
  SkeletonUtils_exports as SkeletonUtils,
  Sky,
  SkyGeometry,
  SobelOperatorShader,
  SortUtils_exports as SortUtils,
  StereoEffect,
  SubsurfaceScatteringShader,
  TAARenderPass,
  TDSLoader,
  TGALoader,
  TIFFLoader,
  TTFLoader,
  TeapotGeometry,
  TechnicolorShader,
  TessellateModifier,
  TextGeometry,
  TextureHelper,
  TexturePass,
  ThreeMFLoader,
  Timer,
  ToonShader1,
  ToonShader2,
  ToonShaderDotted,
  ToonShaderHatching,
  TrackballControls,
  TransformControls,
  TransformControlsGizmo,
  TransformControlsPlane,
  TreesGeometry,
  TriangleBlurShader,
  TubePainter,
  USDZExporter,
  USDZLoader,
  UVsDebug,
  UltraHDRLoader,
  UnpackDepthRGBAShader,
  UnrealBloomPass,
  VOXData3DTexture,
  VOXLoader,
  VOXMesh,
  VRButton,
  VRMLLoader,
  VTKLoader,
  VelocityShader,
  VertexList,
  VertexNode,
  VertexNormalsHelper,
  VertexTangentsHelper,
  VerticalBlurShader,
  VerticalTiltShiftShader,
  ViewHelper,
  VignetteShader,
  Volume,
  VolumeRenderShader1,
  VolumeSlice,
  Water,
  Water2,
  WaterRefractionShader,
  WebGL_default as WebGL,
  Wireframe,
  WireframeGeometry2,
  WorkerPool,
  XRButton,
  XRControllerModelFactory,
  XREstimatedLight,
  XRHandMeshModel,
  XRHandModelFactory,
  XRHandPrimitiveModel,
  XRPlanes,
  XYZLoader,
  ZIPS_COMPRESSION,
  ZIP_COMPRESSION,
  createText,
  decompress,
  edgeTable,
  generateMagicSquareNoise,
  klein,
  mobius,
  mobius3d,
  plane,
  triTable
};
/*! Bundled license information:

three/examples/jsm/libs/fflate.module.js:
  (*!
  fflate - fast JavaScript compression/decompression
  <https://101arrowz.github.io/fflate>
  Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
  version 0.8.2
  *)

three/examples/jsm/libs/lottie_canvas.module.js:
  (*!
   Transformation Matrix v2.0
   (c) Epistemex 2014-2015
   www.epistemex.com
   By Ken Fyrstenberg
   Contributions by leeoniya.
   License: MIT, header required.
   *)

three/examples/jsm/libs/opentype.module.js:
  (*! https://mths.be/codepointat v0.2.0 by @mathias *)

three/examples/jsm/libs/chevrotain.module.min.js:
  (*! chevrotain - v9.0.1 *)

three/examples/jsm/libs/potpack.module.js:
  (**
   * potpack - by [@mourner](https://github.com/mourner)
   * 
   * A tiny JavaScript function for packing 2D rectangles into a near-square container, 
   * which is useful for generating CSS sprites and WebGL textures. Similar to 
   * [shelf-pack](https://github.com/mapbox/shelf-pack), but static (you can't add items 
   * once a layout is generated), and aims for maximal space utilization.
   *
   * A variation of algorithms used in [rectpack2D](https://github.com/TeamHypersomnia/rectpack2D)
   * and [bin-pack](https://github.com/bryanburgers/bin-pack), which are in turn based 
   * on [this article by Blackpawn](http://blackpawn.com/texts/lightmaps/default.html).
   * 
   * @license
   * ISC License
   * 
   * Copyright (c) 2018, Mapbox
   * 
   * Permission to use, copy, modify, and/or distribute this software for any purpose
   * with or without fee is hereby granted, provided that the above copyright notice
   * and this permission notice appear in all copies.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
   * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
   * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
   * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
   * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
   * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
   * THIS SOFTWARE.
   *)
*/
//# sourceMappingURL=three_examples_jsm_Addons__js.js.map
